getUnionDecoder function

Decoder<Object?> getUnionDecoder(
  1. List<Decoder<Object?>> variants,
  2. int getIndexFromBytes(
    1. Uint8List bytes,
    2. int offset
    )
)

Returns a decoder for union types.

This decoder deserializes values by selecting the correct variant decoder based on the getIndexFromBytes function.

Implementation

Decoder<Object?> getUnionDecoder(
  List<Decoder<Object?>> variants,
  int Function(Uint8List bytes, int offset) getIndexFromBytes,
) {
  final fixedSize = _getUnionFixedSize(variants);

  (Object?, int) readImpl(Uint8List bytes, int offset) {
    final index = getIndexFromBytes(bytes, offset);
    _assertValidVariantIndex(variants, index);
    return variants[index].read(bytes, offset);
  }

  if (fixedSize != null) {
    return FixedSizeDecoder<Object?>(fixedSize: fixedSize, read: readImpl);
  }

  final maxSize = _getUnionMaxSize(variants);
  return VariableSizeDecoder<Object?>(read: readImpl, maxSize: maxSize);
}