jam.utils.codec.composite.choices module

Choice codec implementation for JAM protocol.

Implements encoding and decoding of choice (union) values according to the JAM specification. Choice values are encoded with a 1-byte tag followed by the encoded value based on the tag.

class jam.utils.codec.composite.choices.ChoiceCodec(choices: ~typing.Dict[str, ~typing.Type[~jam.utils.codec.codable.Codable[~jam.utils.codec.composite.choices.T]]], _ChoiceCodec__tag_codec: ~jam.utils.codec.codec.Codec[int] = <jam.utils.codec.primitives.integers.GeneralCodec object>)[source]

Bases: Codec[T], Generic[T]

Codec for choice/union values.

Choice values are encoded with a tag byte indicating the selected type, followed by the encoded value of that type.

The tag is encoded as a general integer, followed by the encoded value of the selected type. The tag value corresponds to the index of the type in the choices list.

Parameters:
  • choices – A list of types that are allowed for this choice. Their index will be used as the tag.

  • tag_codec – A codec for the tag. Defaults to GeneralCodec() [Best for most cases]. Alternatively we can use FixedInt(U8) for a fixed size tag if choices > 128.

Raises:

ValueError – If choices list is empty

__init__(choices: ~typing.Dict[str, ~typing.Type[~jam.utils.codec.codable.Codable[~jam.utils.codec.composite.choices.T]]], _ChoiceCodec__tag_codec: ~jam.utils.codec.codec.Codec[int] = <jam.utils.codec.primitives.integers.GeneralCodec object>)[source]

Initialize ChoiceCodec.

Parameters:

choices – A list of types that are allowed for this choice. Their index will be used as the tag.

Raises:

ValueError – If choices list is empty

encode_size(_value: Dict[str, Codable[T]]) int[source]

Calculate encoded size for value.

Parameters:

value – Value to encode

Returns:

Number of bytes needed for encoding

Raises:

EncodeError – If value type is not in choices list

encode_into(_value: Dict[str, Codable[T]], buffer: bytearray, offset: int = 0) int[source]

Encode value into buffer.

Parameters:
  • value – Value to encode

  • buffer – Target buffer

  • offset – Starting offset

Returns:

Number of bytes written

Raises:

EncodeError – If value type is not in choices list or buffer is too small

static decode_from(choices: Dict[str, Type[Codable[T]]], buffer: bytes | bytearray | memoryview, offset: int = 0) Tuple[Dict[str, Codable[T]], int][source]

Decode choice value from buffer.

Parameters:
  • choices – List of possible types

  • buffer – Source buffer

  • offset – Starting offset

Returns:

Tuple of (decoded value, bytes read)

Raises:
  • DecodeError – If buffer is invalid/too short or tag is invalid

  • ValueError – If choices list is empty