Kit
Functions

addCodecSentinel

Call Signature

addCodecSentinel<TFrom, TTo>(codec, sentinel): FixedSizeCodec<TFrom, TTo>

Creates a Codec that writes a given Uint8Array sentinel after the encoded value and, when decoding, continues reading until the sentinel is found.

This sets a limit on variable-size codecs and tells us when to stop decoding.

Type Parameters

Type ParameterDescription
TFromThe type of the value to encode.
TToThe type of the decoded value.

Parameters

ParameterType
codecFixedSizeCodec<TFrom, TTo>
sentinelReadonlyUint8Array

Returns

FixedSizeCodec<TFrom, TTo>

Example

const codec = addCodecSentinel(getUtf8Codec(), new Uint8Array([255, 255]));
codec.encode('hello');
// 0x68656c6c6fffff
//   |        └-- Our sentinel.
//   └-- Our encoded string.

Remarks

Note that the sentinel must not be present in the encoded data and must be present in the decoded data for this to work. If this is not the case, dedicated errors will be thrown.

const sentinel = new Uint8Array([108, 108]); // 'll'
const codec = addCodecSentinel(getUtf8Codec(), sentinel);
 
codec.encode('hello'); // Throws: sentinel is in encoded data.
codec.decode(new Uint8Array([1, 2, 3])); // Throws: sentinel missing in decoded data.

Separate addEncoderSentinel and addDecoderSentinel functions are also available.

const bytes = addEncoderSentinel(getUtf8Encoder(), sentinel).encode('hello');
const value = addDecoderSentinel(getUtf8Decoder(), sentinel).decode(bytes);

See

Call Signature

addCodecSentinel<TFrom, TTo>(codec, sentinel): VariableSizeCodec<TFrom, TTo>

Creates a Codec that writes a given Uint8Array sentinel after the encoded value and, when decoding, continues reading until the sentinel is found.

This sets a limit on variable-size codecs and tells us when to stop decoding.

Type Parameters

Type ParameterDescription
TFromThe type of the value to encode.
TToThe type of the decoded value.

Parameters

ParameterType
codecCodec<TFrom, TTo>
sentinelReadonlyUint8Array

Returns

VariableSizeCodec<TFrom, TTo>

Example

const codec = addCodecSentinel(getUtf8Codec(), new Uint8Array([255, 255]));
codec.encode('hello');
// 0x68656c6c6fffff
//   |        └-- Our sentinel.
//   └-- Our encoded string.

Remarks

Note that the sentinel must not be present in the encoded data and must be present in the decoded data for this to work. If this is not the case, dedicated errors will be thrown.

const sentinel = new Uint8Array([108, 108]); // 'll'
const codec = addCodecSentinel(getUtf8Codec(), sentinel);
 
codec.encode('hello'); // Throws: sentinel is in encoded data.
codec.decode(new Uint8Array([1, 2, 3])); // Throws: sentinel missing in decoded data.

Separate addEncoderSentinel and addDecoderSentinel functions are also available.

const bytes = addEncoderSentinel(getUtf8Encoder(), sentinel).encode('hello');
const value = addDecoderSentinel(getUtf8Decoder(), sentinel).decode(bytes);

See

On this page