getPatternMatchDecoder

function getPatternMatchDecoder<TPatterns>(
    patterns,
): GetUnionDecoderType<GetPatternMatchDecoders<TPatterns>>;

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

This decoder evaluates the byte array against a series of predicate functions in order, and uses the first matching decoder to decode the value.

Type Parameters

Type Parameter
TPatterns extends readonly PatternMatchDecoderEntry<any>[]

Parameters

ParameterTypeDescription
patternsTPatternsAn array of [predicate, decoder] pairs. Predicates are tested in order and the first matching decoder is used to decode the byte array.

Returns

GetUnionDecoderType<GetPatternMatchDecoders<TPatterns>>

A decoder that selects the appropriate variant based on the matched byte pattern.

Throws

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

Example

Decoding values using pattern matching on bytes.

const decoder = getPatternMatchDecoder([
  [(bytes) => bytes.length === 1, getU8Decoder()],
  [(bytes) => bytes.length === 2, getU16Decoder()],
  [(bytes) => bytes.length <= 4, getU32Decoder()]
]);
 
decoder.decode(new Uint8Array([0x2a])); // 42 (decoded as u8)
decoder.decode(new Uint8Array([0xe8, 0x03])) // 1000 (decoded as u16)
decoder.decode(new Uint8Array([0xa0, 0x86, 0x01, 0x00])) // 100_000 (decoded as u32)
decoder.decode(new Uint8Array([0xa0, 0x86, 0x01, 0x00, 0x00]))
// Throws an error because the bytes do not match any pattern

See

On this page