moddef.canonical module¶
Canonical Protobuf binary encoding (spec §33).
Protobuf’s own SerializeToString(deterministic=True) is not portable
across runtimes. The C/upb backend orders map entries by descending key while
the pure-Python backend and the Go reference implementation order them by
ascending key. ModDef’s canonical .moddef form requires ascending map
keys, so we encode the document ourselves.
The encoder reuses Protobuf’s pure-Python scalar field encoders, which are present regardless of the active backend and produce bytes identical to the Go reference for scalars, packed repeated fields, and default omission. We take control only of the two things the backend gets wrong or that need ordering guarantees: map entries are emitted in ascending key order, and nested messages recurse through this same routine.