Skip to Content
Binal

Semantic Types

UUIDs, network addresses, dates and times, complex and rational numbers

These are codecs over an integer, bytes, or tuple storage, so they follow the same rules as custom codecs: the storage value is validated, and a value the codec rejects raises EncodeError (or ValidationError when the storage value is out of range).

TypePython typeWire format
UUIDuuid.UUID16 bytes, RFC 4122 (big-endian) order
GUIDuuid.UUID16 bytes, first three fields little-endian
IPv4ipaddress.IPv4Address4 bytes, network order
IPv6ipaddress.IPv6Address16 bytes, network order
MACstr ("aa:bb:cc:dd:ee:ff")6 bytes
Complex64complexreal then imaginary, two Float32
Complex128complexreal then imaginary, two Float64
Timestamp(storage, unit)aware datetimewhole units since 1970-01-01 UTC
DateTime(storage, unit)naive datetimewhole units since 1970-01-01 (wall clock)
Date(storage)datedays since 1970-01-01
Time(storage, unit)naive timewhole units since midnight
Duration(storage, unit)timedeltawhole units
Rational(numerator, denominator)Fractionnumerator then positive denominator

The first seven are ready aliases; the rest are codecs used as Annotated metadata, because their storage width and unit are part of each format. unit is "s", "ms", or "us". The defaults are Int64 seconds for Timestamp, DateTime, and Duration, Int32 days for Date, UInt32 milliseconds for Time, and Int32 / UInt32 for Rational.

A time value must be a whole number of units — a Timestamp in seconds rejects a datetime with microseconds rather than truncating it. Timestamp takes only aware datetimes and decodes to UTC; DateTime and Time take only naive values. MAC accepts : or - separators and decodes to lowercase with :. A Rational is stored in lowest terms, and a zero denominator on the wire is a DecodeError.

import ipaddress
import uuid
from datetime import UTC, datetime
from fractions import Fraction
from typing import Annotated

from binal import IPv4, MAC, UUID, BinaryModel, Rational, Timestamp, UInt32


class Lease(BinaryModel, byte_order="big"):
    client: UUID
    address: IPv4
    hardware: MAC
    expires: Annotated[datetime, Timestamp(UInt32)]
    ratio: Annotated[Fraction, Rational()]


Lease(
    client=uuid.UUID(int=1),
    address=ipaddress.IPv4Address("10.0.0.7"),
    hardware="aa:bb:cc:00:11:22",
    expires=datetime(2030, 1, 1, tzinfo=UTC),
    ratio=Fraction(3, 4),
).encode()

The codec classes behind the aliases (UUIDCodec(layout), IPv4Codec, IPv6Codec, MACCodec, ComplexCodec(part)) are exported too, for a different part type such as ComplexCodec(Float16).