Kit
Functions

fixCodecSize

fixCodecSize<TFrom, TTo, TSize>(codec, fixedBytes): FixedSizeCodec<TFrom, TTo, TSize>

Creates a fixed-size codec from a given codec.

The resulting codec ensures that both encoding and decoding operate on a fixed number of bytes. When encoding:

  • If the encoded value is larger than fixedBytes, it is truncated.
  • If it is smaller, it is padded with trailing zeroes.
  • If it is exactly fixedBytes, it remains unchanged.

When decoding:

  • Exactly fixedBytes bytes are read from the input.
  • If the nested decoder has a smaller fixed size, bytes are truncated or padded as necessary.

Type Parameters

Type ParameterDescription
TFromThe type of the value to encode.
TToThe type of the decoded value.
TSize extends numberThe fixed size of the encoded value in bytes.

Parameters

ParameterTypeDescription
codecCodec<TFrom, TTo>The codec to wrap into a fixed-size codec.
fixedBytesTSizeThe fixed number of bytes to read/write.

Returns

FixedSizeCodec<TFrom, TTo, TSize>

A FixedSizeCodec that ensures both encoding and decoding conform to a fixed size.

Example

const codec = fixCodecSize(getUtf8Codec(), 4);
 
const bytes1 = codec.encode("Hello"); // 0x48656c6c (truncated)
const value1 = codec.decode(bytes1);  // "Hell"
 
const bytes2 = codec.encode("Hi");    // 0x48690000 (padded)
const value2 = codec.decode(bytes2);  // "Hi"
 
const bytes3 = codec.encode("Hiya");  // 0x48697961 (same length)
const value3 = codec.decode(bytes3);  // "Hiya"

Remarks

If you only need to enforce a fixed size for encoding, use fixEncoderSize. If you only need to enforce a fixed size for decoding, use fixDecoderSize.

const bytes = fixEncoderSize(getUtf8Encoder(), 4).encode("Hiya");
const value = fixDecoderSize(getUtf8Decoder(), 4).decode(bytes);

See

On this page