getPatternMatchCodec

function getPatternMatchCodec<TPatterns>(
    patterns,
): GetUnionCodecType<GetPatternMatchCodecs<TPatterns>>;

Returns a codec that selects which variant codec to use based on pattern matching.

This codec evaluates values and byte arrays against a series of predicate functions in order, using the first matching codec for encoding or decoding.

Type Parameters

Type Parameter
TPatterns extends readonly ( | readonly [(value) => value is any, (bytes) => boolean, Codec<any, any>] | readonly [(value) => boolean, (bytes) => boolean, Codec<any, any>])[]

Parameters

ParameterTypeDescription
patternsTPatterns & readonly PatternMatchCodecEntry<GetEncoderTypeFromVariants<GetPatternMatchCodecs<TPatterns>>, GetEncoderTypeFromVariants<GetPatternMatchCodecs<TPatterns>>, GetEncoderTypeFromVariants<GetPatternMatchCodecs<TPatterns>>>[]An array of [valuePredicate, bytesPredicate, codec] triples. Predicates are tested in order and the first match determines the codec used. During encoding, valuePredicate receives the value to encode. During decoding, bytesPredicate receives the byte array.

Returns

GetUnionCodecType<GetPatternMatchCodecs<TPatterns>>

A codec that selects the appropriate variant based on the matched pattern.

Throws

Throws a SOLANA_ERROR__CODECS__INVALID_PATTERN_MATCH_VALUE error if a value being encoded does not match any of the specified patterns.

Throws

Throws a SOLANA_ERROR__CODECS__INVALID_PATTERN_MATCH_BYTES error if a byte array being decoded does not match any of the specified patterns.

Example

Encoding and decoding using pattern matching.

const codec = getPatternMatchCodec([
 [
   (n: number) => n < 256,
   (bytes) => bytes.length === 1,
   getU8Codec(),
 ],
 [
   (n: number) => n < 2 ** 16,
   (bytes) => bytes.length === 2,
   getU16Codec(),
 ],
 [
   (n: number) => n < 2 ** 32,
   (bytes) => bytes.length <= 4,
   getU32Codec(),
 ]
]);
 
const bytes1 = codec.encode(42);     // 0x2a, encoded as u8
const value1 = codec.decode(bytes1); // 42, decoded as u8
 
const bytes2 = codec.encode(1000);   // 0xe803, encoded as u16
const value2 = codec.decode(bytes2); // 1000, decoded as u16
 
const bytes3 = codec.encode(100_000); //0xa0860100, encoded as u32
const value3 = codec.decode(bytes3); // 100_000, decoded as u32
 
codec.encode(2 ** 32 + 1);
// throws, no encode pattern matches
codec.decode(new Uint8Array([0xa0, 0x86, 0x01, 0x00, 0x00]))
// throws, no decode pattern matches

See

On this page