Kit
Functions

offsetCodec

offsetCodec<TCodec>(codec, config): TCodec

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

This function allows a codec to encode and decode values at custom offsets within a byte array. It modifies both the pre-offset (where encoding/decoding starts) and the post-offset (where the next operation should continue).

This is particularly useful when working with structured binary formats that require skipping reserved bytes, inserting padding, or aligning fields at specific locations.

Type Parameters

Type Parameter
TCodec extends AnyCodec

Parameters

ParameterTypeDescription
codecTCodecThe codec to adjust.
configOffsetConfigAn object specifying how the offset should be modified.

Returns

TCodec

A new codec with adjusted offsets.

Examples

Moving the pre-offset forward by 2 bytes when encoding and decoding.

const codec = offsetCodec(getU32Codec(), {
    preOffset: ({ preOffset }) => preOffset + 2,
});
const bytes = new Uint8Array(10);
codec.write(42, bytes, 0); // Actually written at offset 2
codec.read(bytes, 0);      // Actually read from offset 2

Moving the post-offset forward by 2 bytes when encoding and decoding.

const codec = offsetCodec(getU32Codec(), {
    postOffset: ({ postOffset }) => postOffset + 2,
});
const bytes = new Uint8Array(10);
codec.write(42, bytes, 0);
// Next encoding starts at offset 6 instead of 4
codec.read(bytes, 0);
// Next decoding starts at offset 6 instead of 4

Using wrapBytes to loop around negative offsets.

const codec = offsetCodec(getU32Codec(), {
    preOffset: ({ wrapBytes }) => wrapBytes(-4), // Moves offset to last 4 bytes
});
const bytes = new Uint8Array(10);
codec.write(42, bytes, 0); // Writes at bytes.length - 4
codec.read(bytes, 0); // Reads from bytes.length - 4

Remarks

If you only need to adjust offsets for encoding, use offsetEncoder. If you only need to adjust offsets for decoding, use offsetDecoder.

const bytes = new Uint8Array(10);
offsetEncoder(getU32Encoder(), { preOffset: ({ preOffset }) => preOffset + 2 }).write(42, bytes, 0);
const [value] = offsetDecoder(getU32Decoder(), { preOffset: ({ preOffset }) => preOffset + 2 }).read(bytes, 0);

See

On this page