Skip to content

Instructions

If you have not used CBOR before, start with Why CBOR. That page explains the head byte, major types, preferred encoding, and diagnostic notation that the rest of these steps assume.

Install Mojo 1.1.0

git clone https://github.com/leo-gan/gld-cbor.git
cd gld-cbor
pixi install
pixi run test

If pixi install fails with 401 on conda.modular.com, set PREFIX_API_KEY in a local .env (never commit that file) and run scripts/ci-setup.sh.

After a conda install from prefix.dev:

pixi add --channel https://prefix.dev/leo-gan/leo-gan mojo-cbor

That installs cbor.mojoc (plus wire / runtime / diag / cddl) and gld-cborgen-mojo.

Generate Mojo from CDDL

Write an RFC 8610 CDDL schema, then run the generator. After a conda install the command is gld-cborgen-mojo. In a checkout:

pixi run mojo run -I src src/codegen/cli.mojo -- \
  --cddl testdata/cddl/benchmark_v2.cddl --out tests/generated

pixi run generate rebuilds the in-tree types from testdata/cddl/benchmark_v2.cddl.

Optional members (? field) become Optional[T]. A two-branch choice with null also becomes Optional[T].

Encode and decode

from cbor import encode, decode
from Message import Message

var m = Message()
m.f_int = Int64(150)
var buf = encode(m)
var m2 = decode[Message](buf)

from cbor import … resolves with mojo run -I src in a checkout, or from cbor.mojoc after the package is installed.

CDDL sockets ($name /= type), generic applications (map<int, tstr>), .regexp controls, unwrap (~Group), .bits / .and / .within / .andcbor, and one include "other.cddl" parse in Mojo. The included file cannot include a file already on the include stack (cycles are rejected). export Name and import Name from "file.cddl" load a catalog.

SeqDecoder pulls one sequence item at a time. decode_tstr_span returns a StringSpan into the input for a definite text string. encode_diag_pretty prints arrays and maps with indentation. EncodeOptions.dcbor writes a stricter deterministic subset.

Schema-free items use CborValue:

from cbor import decode_value, encode_value, EncodeOptions

var v = decode_value(buf)
var again = encode_value(v, EncodeOptions.cde)