jam.types.base.dictionary module

class jam.types.base.dictionary.Dictionary(initial: Mapping[K, V] | None = None)[source]

Bases: Generic[K, V], Codable, Mapping[K, V], JsonSerde

Dictionary implementation that supports codec operations.

A dictionary that maps Codable keys to Codable values, providing both standard dictionary operations and codec functionality for serialization/deserialization.

Examples

>>> from jam.types.base.string import String
>>> from jam.types.base.integers import Int
>>> d = Dictionary({String("key"): Int(42)})
>>> d[String("key")]
Int(42)
>>> encoded = d.encode()
>>> decoded, _ = Dictionary.decode_from(String, Int, encoded)
>>> decoded == d
True
key_type: Type[K]
value_type: Type[V]
__init__(initial: Mapping[K, V] | None = None)[source]

Initialize dictionary.

Parameters:

initial – Optional initial key-value pairs

Raises:

TypeError – If any key or value is not Codable

__getitem__(key: K) V[source]

Get value for key.

__iter__() Iterator[K][source]

Iterate over keys.

__len__() int[source]

Get number of items.

__eq__(other: object) bool[source]

Compare for equality.

__repr__() str[source]

Get string representation.

get(key: K, default: V | None = None) V | None[source]

Get value for key, returning default if key not found.

Parameters:
  • key – Key to look up

  • default – Value to return if key not found

Returns:

Value for key or default

items() ItemsView[K, V][source]

Get view of (key, value) pairs.

keys() KeysView[K][source]

Get view of keys.

values() ValuesView[V][source]

Get view of values.

to_json() Dict[Any, Any][source]

Convert to JSON representation.

classmethod from_json(data: Dict[Any, Any] | Sequence[Any]) Self[source]

Create instance from JSON representation.

jam.types.base.dictionary.decodable_dictionary(key_type: Type[K], value_type: Type[V]) Type[Dictionary[K, V]][source]

jam.types.base.dictionary

Dictionary type implementation for the JAM protocol.

Type Definition

Dictionary[K, V]

  • K: Key type (must be Codable)

  • V: Value type (must be Codable)

  • Ordered key-value pairs

  • Deterministic encoding

Encoding Format

Structure:

[Length_Tag: varint][Length_Data: varies][Pairs...]
where each Pair is:
    [Encoded Key][Encoded Value]

Length encoding:

0x00-0xFC: Direct value (1 byte)
0xFF: u16 value (3 bytes)
0xFE: u24 value (4 bytes)
0xFD: u32 value (5 bytes)

Pairs are sorted by encoded key bytes for deterministic encoding.

Implementation Details

Memory Layout

  • Length prefix: Variable size

  • Key-value pairs: Contiguous

  • Keys and values: Variable size

  • No padding between pairs

Sorting

Keys are sorted by their encoded bytes:

def _sort_pairs(pairs):
    return sorted(
        pairs,
        key=lambda x: x[0].encode()
    )

Size Calculation

Total size is sum of:

  1. Length prefix size

  2. Encoded key sizes

  3. Encoded value sizes

Error Handling

Common error cases:

  1. Invalid key type:

    if not isinstance(key, Codable):
        raise TypeError(f"Key must be Codable, got {type(key)}")
    
  2. Invalid value type:

    if not isinstance(value, Codable):
        raise TypeError(f"Value must be Codable, got {type(value)}")
    
  3. Buffer overflow:

    if len(buffer) - offset < needed_size:
        raise BufferError(f"Buffer too small: need {needed_size} bytes")
    

Examples

Basic Usage

from jam.types.base.dictionary import Dict
from jam.types.base.string import String
from jam.types.base.integers import U32

# Create dictionary
@decodable_dictionary(String, U32)
class StringU32Dict(Dict[String, U32]): ...

d = StringU32Dict({
   String("a"): U32(1),
   String("b"): U32(2)
})

# Encode
encoded = d.encode()
# -> [02 01 61 01 00 00 00 01 62 02 00 00 00]
#    len=2, "a"->1, "b"->2

# Decode
decoded = StringU32Dict.decode(encoded)
assert decoded == {String("a"): U32(1), String("b"): U32(2)}

API Reference

Classes

class jam.types.base.dictionary.Dict(*args, **kwargs)

Bases:

A generic version of dict.

Decorators

jam.types.base.dictionary.decodable_dictionary(key_type: Type[K], value_type: Type[V]) Type[Dictionary[K, V]][source]