tapDecoderBytes

function tapDecoderBytes<TDecoder>(decoder, tap): TDecoder;

Observes the raw bytes of a decoder before it decodes them, without modifying them.

This function takes an existing decoder and returns a new decoder of the exact same type that calls the provided tap function with the byte array before each value is read. 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 raw bytes.

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

Type Parameters

Type ParameterDescription
TDecoder extends AnyDecoderThe type of the decoder being tapped. The returned decoder has the same type.

Parameters

ParameterTypeDescription
decoderTDecoderThe decoder whose raw bytes should be observed.
tap(bytes, offset) => voidA function called with the byte array and offset before reading. It may throw to abort decoding.

Returns

TDecoder

A new decoder of the same type that observes its raw bytes.

Throws

Whatever error the tap function throws, aborting the decoding.

Example

Guarding the raw bytes of a boolean decoder.

const decoder = tapDecoderBytes(getBooleanDecoder(), (bytes, offset) => {
    if (bytes[offset] > 1) throw new Error('Expected a 0 or a 1 for booleans');
});
decoder.decode(new Uint8Array([1])); // true
decoder.decode(new Uint8Array([2])); // Throws 'Expected a 0 or a 1 for booleans'

Remarks

To observe the decoded value instead of the raw bytes, use tapDecoder.

See

On this page