const-cbor
A const-first, allocation-free CBOR codec implementing
RFC 8949. Encode and decode
CBOR directly between Rust values and byte buffers — no value tree, no
heap, no unsafe, no traits, no dependencies.
flash on Cortex-M3 (thumbv7m-none-eabi, `profile.size`: opt-level=z,
fat LTO, panic=abort, symbols stripped), linked `.text` + `.rodata`,
inputs black_boxed so nothing is const-folded away:
core only ................................ 3,148 B
+ float (encode + decode exercised) ...... 4,964 B
+ indefinite ............................. 4,496 B
+ bignum ................................. 3,994 B
+ canonical .............................. 4,000 B
+ deterministic (incl. indefinite) ....... 4,496 B
+ diagnostic ............................. 7,462 B
+ diagnostic + float decimal text ........ 21,578 B
everything enabled and used .............. 24,102 B
Features you do not enable — or call — cost nothing.
Reproduce with the checked-in probe:
`cargo build --profile size --target thumbv7m-none-eabi --example cbor-size`
then `size target/thumbv7m-none-eabi/size/examples/cbor-size`. The same
probe builds and runs on x86_64 (`cargo run --profile size --example cbor-size`),
where the linked `const_cbor` symbols can be inspected directly with
`nm target/size/examples/cbor-size | grep const_cbor`.
Why another CBOR crate?
| const-cbor | serde-based stacks | |
|---|---|---|
| Dependencies | 0 | dozens (transitively) |
| Heap allocation | never | pervasive |
unsafe |
forbidden by lint | present in deps |
| Compile-time work | heads, widths, lengths, whole items via const fn |
runtime |
| Binary size (Cortex-M) | ~1–4 KB | tens of KB |
| API model | concrete-typed methods, chaining | trait impls + derive |
Need serde? The const-cbor-serde companion crate adds
Serialize/Deserialize adapters over this core — the core itself keeps
zero dependencies.
The design pushes work into the compiler: argument widths, head bytes,
and encoded sizes are const fns that LLVM folds for statically known
inputs — entire items can be built during compilation:
use consts;
/// [-10] — one byte of output, built and checked at compile time.
const NEG_TEN: = ;
assert_eq!;
(Overflowing the buffer here is a compile error, not a runtime panic.)
Quick start
[]
= "0.2"
Encode
use Encoder;
let mut buf = ;
let mut enc = new;
// [1000, "hello"]
enc.array_len.unwrap;
enc.u32.unwrap;
enc.str.unwrap;
let n = enc.written;
assert_eq!;
Methods return Result<&mut Self, _> so calls chain; containers declare
their length and you write their items in wire order. Every call either
writes completely or writes nothing (OUT_OF_SPACE keeps the cursor).
Decode
use ;
let mut dec = new;
assert_eq!;
assert_eq!;
assert_eq!; // zero-copy borrow
assert!;
Strings and byte strings borrow from your input buffer. Typed getters are range-checked, never truncating.
Features
Nothing beyond the core is compiled unless you ask:
[]
= { = "0.2", = ["float", "indefinite"] }
| Feature | Capability | RFC section |
|---|---|---|
| (default) | Integers (full u64/i64 space), strings, bytes, arrays, maps, tags, simple values, booleans, null/undefined, structural skip | §3.1, §5 |
float |
f16/f32/f64 with provably-lossless width narrowing and canonical NaN | §3.3, App. D |
indefinite |
Indefinite-length strings (chunk-wise, zero-copy iterators) and open-ended arrays/maps | §3.2 |
raw |
RawValue — validated zero-copy handle to any complete item; lazily re-decodable, verbatim re-emittable |
§5.4 |
stream |
StreamDecoder: incremental decode across arbitrary feed boundaries into one caller-provided scratch buffer |
— |
canonical |
MapBuilder<N>: deterministic map key ordering without allocation |
§4.2 |
diagnostic |
Human-readable rendering of CBOR into RFC 8949 §8 diagnostic notation | §8 |
bignum |
Arbitrary-precision integers via tags 2/3, zero-copy magnitudes | §3.4.3 |
deterministic |
Strict RFC §4.2 validation: minimal widths, shortest floats, sorted map keys | §4.2 |
Serde support
The companion crate serde/ (workspace member) adds Serialize /
Deserialize adapters over the core codec:
[]
= { = "serde" } # or from the registry
use ;
let bytes = to_vec?;
let p: Point = from_slice?;
Representation follows ecosystem conventions (serde_cbor / ciborium):
structs are CBOR maps keyed by field name, enums are externally tagged,
sequences use indefinite lengths. The core crate itself remains
dependency-free.
| std | Host conveniences; the core never requires it | — |
Feature examples
Indefinite strings, chunked both ways:
# use Encoder;
let mut buf = ;
let mut e = new;
e.str_indef.unwrap; // (_ "strea", "ming")
let mut d = new;
let mut chunks = d.str_chunks.unwrap;
while let Some = chunks.next
Canonical map ordering without a heap:
use ;
use MapBuilder;
let mut buf = ;
let mut enc = new;
enc.map_len.unwrap;
let mut m = new;
m.add.unwrap;
m.add.unwrap;
m.finish.unwrap; // reorders into canonical order
let mut dec = new;
dec.map_len.unwrap;
assert_eq!; // "aa" pair now comes first
// Note: canonical order is *bytewise over encoded keys* — the length
// prefix participates. "zeta" (4 bytes) canonically precedes "alpha"
// (5 bytes), unlike plain ASCII ordering.
Streaming decode over packet-sized feeds:
use StreamDecoder;
let mut scratch = ; // bounds max item size
let mut stream = new;
stream.feed;
stream.feed;
if let Ok = stream.take_item
Human-readable diagnostic output:
use ;
let mut buf = ;
let mut enc = new;
enc.array_len.unwrap;
enc.str.unwrap.i16.unwrap.bool.unwrap;
let = enc.finish;
let mut text = ;
let pretty = render.unwrap;
assert_eq!;
Passing unknown fields through untouched:
let raw = decoder.raw_value?; // validates structure only
encoder.raw?; // re-emits verbatim later
Guarantees
| Property | Guarantee |
|---|---|
| Panics | never at runtime — malformed input is always Err(Error) |
| Allocation | never; links only core, no allocator touched |
| Unsafe | #![forbid(unsafe_code)] |
| Recursion | none — skip uses a fixed 32-entry stack |
| Failure atomicity | failed encoder calls leave the buffer unchanged |
| Zero-copy | string/byte payloads borrow from caller memory |
| Errors | single-byte Copy codes implementing core::error::Error |
Strictness follows RFC 8949 §4.2.1: non-minimal integer encodings are accepted on input (preferred form is a SHOULD); genuinely invalid forms — reserved additional information, two-byte simples below 32, non-UTF-8 text, stray breaks — are rejected.
Documentation
docs/guide.md— task-oriented recipesdocs/behavior.md— exact runtime semanticsdocs/conformance.md— clause-by-clause RFC conformance matrixspecs/RFC8949.md— normative source- rustdoc:
cargo doc --open
Development
CI runs tests across every feature combination, clippy with
-D warnings, cross-builds for thumbv7m-none-eabi /
aarch64-unknown-none, and gates release binary size.
Minimum supported Rust: 1.85 (edition 2024, stable only).
License
MIT OR Apache-2.0