Kit
Functions

addCodecSizePrefix

Call Signature

addCodecSizePrefix<TFrom, TTo>(codec, prefix): FixedSizeCodec<TFrom, TTo>

Stores the byte size of any given codec as an encoded number prefix.

This sets a limit on variable-size codecs and tells us when to stop decoding. When encoding, the size of the encoded data is stored before the encoded data itself. When decoding, the size is read first to know how many bytes to read next.

Type Parameters

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

Parameters

ParameterType
codecFixedSizeCodec<TFrom, TTo>
prefixFixedSizeNumberCodec

Returns

FixedSizeCodec<TFrom, TTo>

Example

For example, say we want to bound a variable-size base-58 string using a u32 size prefix. Here’s how you can use the addCodecSizePrefix function to achieve that.

const getU32Base58Codec = () => addCodecSizePrefix(getBase58Codec(), getU32Codec());
 
getU32Base58Codec().encode('hello world');
// 0x0b00000068656c6c6f20776f726c64
//   |       └-- Our encoded base-58 string.
//   └-- Our encoded u32 size prefix.

Remarks

Separate addEncoderSizePrefix and addDecoderSizePrefix functions are also available.

const bytes = addEncoderSizePrefix(getBase58Encoder(), getU32Encoder()).encode('hello');
const value = addDecoderSizePrefix(getBase58Decoder(), getU32Decoder()).decode(bytes);

See

Call Signature

addCodecSizePrefix<TFrom, TTo>(codec, prefix): VariableSizeCodec<TFrom, TTo>

Stores the byte size of any given codec as an encoded number prefix.

This sets a limit on variable-size codecs and tells us when to stop decoding. When encoding, the size of the encoded data is stored before the encoded data itself. When decoding, the size is read first to know how many bytes to read next.

Type Parameters

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

Parameters

ParameterType
codecCodec<TFrom, TTo>
prefixNumberCodec

Returns

VariableSizeCodec<TFrom, TTo>

Example

For example, say we want to bound a variable-size base-58 string using a u32 size prefix. Here’s how you can use the addCodecSizePrefix function to achieve that.

const getU32Base58Codec = () => addCodecSizePrefix(getBase58Codec(), getU32Codec());
 
getU32Base58Codec().encode('hello world');
// 0x0b00000068656c6c6f20776f726c64
//   |       └-- Our encoded base-58 string.
//   └-- Our encoded u32 size prefix.

Remarks

Separate addEncoderSizePrefix and addDecoderSizePrefix functions are also available.

const bytes = addEncoderSizePrefix(getBase58Encoder(), getU32Encoder()).encode('hello');
const value = addDecoderSizePrefix(getBase58Decoder(), getU32Decoder()).decode(bytes);

See

On this page