tapCodecBytes

function tapCodecBytes<TCodec>(codec, encodeTap, decodeTap?): TCodec;

Observes the raw bytes of a codec on both sides, without modifying them.

This function takes an existing codec and returns a new codec of the exact same type that:

  • Calls encodeTap with the byte array after each value is written.
  • Calls decodeTap (if provided) with the byte array before each value is read.

The bytes are provided as ReadonlyUint8Arrays and are passed through unchanged, making this useful for adding validation guards, logging, or other read-only side effects. If either tap function throws, the corresponding operation is aborted and the error propagates to the caller.

Type Parameters

Type ParameterDescription
TCodec extends AnyCodecThe type of the codec being tapped. The returned codec has the same type.

Parameters

ParameterTypeDescription
codecTCodecThe codec whose raw bytes should be observed.
encodeTap(bytes, preOffset, postOffset) => voidA function called with the byte array and offsets after writing. It may throw to abort encoding.
decodeTap?(bytes, offset) => voidAn optional function called with the byte array and offset before reading. It may throw to abort decoding.

Returns

TCodec

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

Throws

Whatever error the tap functions throw, aborting the corresponding operation.

Example

Guarding the raw bytes of a boolean codec before decoding.

const codec = tapCodecBytes(
    getBooleanCodec(),
    () => {},
    (bytes, offset) => {
        if (bytes[offset] > 1) throw new Error('Expected a 0 or a 1 for booleans');
    },
);

Remarks

If only the encoded bytes need observing, use tapEncoderBytes. If only the raw bytes before decoding need observing, use tapDecoderBytes. To observe the values instead of the raw bytes, use tapCodec.

See

On this page