Kit
Functions

offsetEncoder

offsetEncoder<TEncoder>(encoder, config): TEncoder

Moves the offset of a given encoder before and/or after encoding.

This function allows an encoder to write its encoded value at a different offset than the one originally provided. It supports both pre-offset adjustments (before encoding) and post-offset adjustments (after encoding).

The pre-offset function determines where encoding should start, while the post-offset function adjusts where the next encoder should continue writing.

For more details, see offsetCodec.

Type Parameters

Type Parameter
TEncoder extends AnyEncoder

Parameters

ParameterTypeDescription
encoderTEncoderThe encoder to adjust.
configOffsetConfigAn object specifying how the offset should be modified.

Returns

TEncoder

A new encoder with adjusted offsets.

Examples

Moving the pre-offset forward by 2 bytes.

const encoder = offsetEncoder(getU32Encoder(), {
    preOffset: ({ preOffset }) => preOffset + 2,
});
const bytes = new Uint8Array(10);
encoder.write(42, bytes, 0); // Actually written at offset 2

Moving the post-offset forward by 2 bytes.

const encoder = offsetEncoder(getU32Encoder(), {
    postOffset: ({ postOffset }) => postOffset + 2,
});
const bytes = new Uint8Array(10);
const nextOffset = encoder.write(42, bytes, 0); // Next encoder starts at offset 6 instead of 4

Using wrapBytes to ensure an offset wraps around the byte array length.

const encoder = offsetEncoder(getU32Encoder(), {
    preOffset: ({ wrapBytes }) => wrapBytes(-4), // Moves offset to last 4 bytes of the array
});
const bytes = new Uint8Array(10);
encoder.write(42, bytes, 0); // Writes at bytes.length - 4

Remarks

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

See

On this page