tapEncoderBytes

function tapEncoderBytes<TEncoder>(encoder, tap): TEncoder;

Observes the encoded bytes of an encoder after it writes them, without modifying them.

This function takes an existing encoder and returns a new encoder of the exact same type that calls the provided tap function with the byte array after each value is written. The bytes are provided as a ReadonlyUint8Array and are passed through unchanged, making this useful for adding validation guards, logging, or other read-only side effects on the encoded bytes.

The tap function receives the entire byte array alongside the offsets before and after the value was written, so it can inspect the window [preOffset, postOffset) that was just encoded.

If the tap function throws, the encoding is aborted and the error propagates to the caller.

Type Parameters

Type ParameterDescription
TEncoder extends AnyEncoderThe type of the encoder being tapped. The returned encoder has the same type.

Parameters

ParameterTypeDescription
encoderTEncoderThe encoder whose encoded bytes should be observed.
tap(bytes, preOffset, postOffset) => voidA function called with the byte array and offsets after writing. It may throw to abort encoding.

Returns

TEncoder

A new encoder of the same type that observes its encoded bytes.

Throws

Whatever error the tap function throws, aborting the encoding.

Example

Observing the bytes written by a u8 encoder.

const encoder = tapEncoderBytes(getU8Encoder(), (bytes, preOffset, postOffset) => {
    console.log(bytes.slice(preOffset, postOffset));
});

Remarks

The tap fires after the encoder's write step. For variable-size encoders, this means the encoded size is still computed from the value (via getSizeFromValue) before the tap runs, so a custom getSizeFromValue that rejects the value will throw before the tap has a chance to.

To observe the input value instead of the encoded bytes, use tapEncoder.

See

On this page