createDependentStructDecoder function

DependentStructDecoderBuilder createDependentStructDecoder()

Creates a fluent builder for a struct decoder whose later fields may depend on the decoded values of earlier ones.

Unlike getStructDecoder, which accepts a fixed array of named decoders, this builder lets each field provide a factory that receives the values that have already been decoded. This is useful for binary formats where a count, version, or discriminator decoded near the start of the struct controls how a later field must be parsed.

The builder mirrors the fixed vs variable size behaviour of getStructDecoder. The empty builder finishes to a FixedSizeDecoder of size zero. Adding a FixedSizeDecoder preserves the fixed size property and the sizes accumulate. Adding a VariableSizeDecoder or a DependentStructDecoderFieldFactory drops the builder to variable size, which is then preserved by every subsequent field call.

The returned builder is immutable; each field call returns a new builder whose accumulated field list is extended by the newly added field. Call build to produce the final decoder.

Prefer getStructDecoder when every field's decoder is independent of the values that precede it. Reach for this builder only when at least one field needs to be parameterised by another.

The encoder direction does not need a dependent variant. An encoder already has access to the entire value when serialising, so the existing getStructEncoder can be paired with the decoder returned by this builder and combined with combineCodec to obtain a full codec.

Added in @solana/kit v7.0.0.

import 'dart:typed_data';

import 'package:solana_kit_codecs_data_structures/solana_kit_codecs_data_structures.dart';
import 'package:solana_kit_codecs_numbers/solana_kit_codecs_numbers.dart';

void main() {
  final decoder = createDependentStructDecoder()
      .field('count', getU8Decoder())
      .field(
        'values',
        (fields) => getArrayDecoder(
          getU32Decoder(),
          size: FixedArraySize(fields['count']! as int),
        ),
      )
      .build();

  final (value, _) =
      decoder.read(Uint8List.fromList([2, 1, 0, 0, 0, 2, 0, 0, 0]), 0);
  print(value); // {count: 2, values: [1, 2]}
}

Implementation

DependentStructDecoderBuilder createDependentStructDecoder() {
  return DependentStructDecoderBuilder._(const []);
}