getConstantCodec

function getConstantCodec<TConstant>(
    constant,
): FixedSizeCodec<void, void, TConstant['length']>;

Returns a codec that encodes and decodes a predefined constant byte sequence.

  • Encoding: Always writes the specified byte array.
  • Decoding: Asserts that the next bytes match the constant, throwing an error if they do not.

This is useful for encoding fixed byte patterns required in a binary format or to use in conjunction with other codecs such as getHiddenPrefixCodec or getHiddenSuffixCodec.

Type Parameters

Type ParameterDescription
TConstant extends ReadonlyUint8Array<ArrayBufferLike>The fixed byte sequence to encode and verify during decoding.

Parameters

ParameterTypeDescription
constantTConstantThe predefined byte array to encode and assert during decoding.

Returns

FixedSizeCodec<void, void, TConstant["length"]>

A FixedSizeCodec<void, void, N> where N is the length of the constant.

Example

Encoding and decoding a constant magic number.

const codec = getConstantCodec(new Uint8Array([1, 2, 3]));
 
codec.encode(); // 0x010203
codec.decode(new Uint8Array([1, 2, 3])); // Passes
codec.decode(new Uint8Array([1, 2, 4])); // Throws an error

Remarks

Separate getConstantEncoder and getConstantDecoder functions are available.

const bytes = getConstantEncoder(new Uint8Array([1, 2, 3])).encode();
getConstantDecoder(new Uint8Array([1, 2, 3])).decode(bytes);

See

On this page