Skip to content

livery.strongroom._canonical

livery.strongroom._canonical

Canonical JSON: the one hashed form of every structured format.

RFC 8785 (JSON Canonicalization Scheme) restricted to the values the store's formats use: objects with string keys, arrays, strings, integers, booleans and null. A float is refused, because a tree's size is an integer and no format carries a fraction; refusing the whole class keeps the number serialisation to plain digits, which every language prints the same way. The same canonicaliser serves every format, so one set of vectors proves it.

Reach for livery.strongroom.canonical to produce bytes and livery.strongroom.FormatError to catch a refusal.

Classes:

Name Description
FormatError

A value does not satisfy one of the store's formats.

Functions:

Name Description
canonical

Encode value as RFC 8785 canonical JSON, UTF-8.

Attributes:

Name Type Description
Value TypeAlias

A JSON value the store's formats may carry: no float, nested the same way.

Value module-attribute

Value: TypeAlias = 'bool | int | str | list[Any] | dict[str, Any] | None'

A JSON value the store's formats may carry: no float, nested the same way.

FormatError

Bases: ValueError

A value does not satisfy one of the store's formats.

The message names the rule that refused it. Every format refusal raises this one class, so a caller validating a whole tree catches one thing.

canonical

canonical(value: Value) -> bytes

Encode value as RFC 8785 canonical JSON, UTF-8.

Object keys sort by their UTF-16 code units, which differs from code-point order above the Basic Multilingual Plane. Strings keep every character above U+001F literal.

Parameters:

Name Type Description Default
value Value

the value to encode. Nested values are encoded the same way.

required

Returns:

Type Description
bytes

The canonical bytes. Two equal values encode to equal bytes.

Raises:

Type Description
FormatError

on a float, an integer past 2^53 in magnitude, a non-string key, or a value of a type no format carries.

Source code in packages/strongroom/src/livery/strongroom/_canonical.py
def canonical(value: Value) -> bytes:
    """Encode *value* as RFC 8785 canonical JSON, UTF-8.

    Object keys sort by their UTF-16 code units, which differs from
    code-point order above the Basic Multilingual Plane. Strings keep
    every character above U+001F literal.

    Args:
        value: the value to encode. Nested values are encoded the same
            way.

    Returns:
        The canonical bytes. Two equal values encode to equal bytes.

    Raises:
        FormatError: on a float, an integer past 2^53 in magnitude, a
            non-string key, or a value of a type no format carries.
    """
    parts: list[str] = []
    _write(value, parts)
    return "".join(parts).encode("utf-8")