Kit
Functions

offsetDecoder

offsetDecoder<TDecoder>(decoder, config): TDecoder

Moves the offset of a given decoder before and/or after decoding.

This function allows a decoder to read its input from a different offset than the one originally provided. It supports both pre-offset adjustments (before decoding) and post-offset adjustments (after decoding).

The pre-offset function determines where decoding should start, while the post-offset function adjusts where the next decoder should continue reading.

For more details, see offsetCodec.

Type Parameters

Type Parameter
TDecoder extends AnyDecoder

Parameters

ParameterTypeDescription
decoderTDecoderThe decoder to adjust.
configOffsetConfigAn object specifying how the offset should be modified.

Returns

TDecoder

A new decoder with adjusted offsets.

Examples

Moving the pre-offset forward by 2 bytes.

const decoder = offsetDecoder(getU32Decoder(), {
    preOffset: ({ preOffset }) => preOffset + 2,
});
const bytes = new Uint8Array([0, 0, 42, 0]); // Value starts at offset 2
decoder.read(bytes, 0); // Actually reads from offset 2

Moving the post-offset forward by 2 bytes.

const decoder = offsetDecoder(getU32Decoder(), {
    postOffset: ({ postOffset }) => postOffset + 2,
});
const bytes = new Uint8Array([42, 0, 0, 0]);
const [value, nextOffset] = decoder.read(bytes, 0); // Next decoder starts at offset 6 instead of 4

Using wrapBytes to read from the last 4 bytes of an array.

const decoder = offsetDecoder(getU32Decoder(), {
    preOffset: ({ wrapBytes }) => wrapBytes(-4), // Moves offset to last 4 bytes of the array
});
const bytes = new Uint8Array([0, 0, 0, 0, 0, 0, 0, 42]); // Value stored at the last 4 bytes
decoder.read(bytes, 0); // Reads from bytes.length - 4

Remarks

If you need both encoding and decoding offsets to be adjusted, use offsetCodec.

See

On this page