# CBOR (`serde/cbor`)

The CBOR module provides comptime-specialized structured codecs and an owning
`CborValue` dynamic tree.

## Round trip with a known schema

The producer and consumer below use the same struct schema. For external data,
use the dynamic parsing and field checks described in the next section.

```vex
import { cborMarshal, cborUnmarshalSafe } from "serde/cbor";

struct Stats {
    public:
    hp: i64,
    mp: i64,
}

let source = Stats { hp: 100, mp: 50 };
let packed = cborMarshal(&source);
let! decoded = Stats { hp: 0, mp: 0 };
match cborUnmarshalSafe(
    packed.raw_ptr() as Ptr<u8>, packed.len() as u64, &decoded,
) {
    Ok(_) => { $println(decoded.hp); }
    Err(failure) => { $println(failure.message()); }
}
```

Dynamic APIs are `cborParseDynamic`, `cborParseDynamicSafe`,
`cborParseDynamicWithLimits`, `cborStringifyDynamic` and `cborToJson`. They
operate on a pointer and explicit byte length when parsing binary input.

## Safe and trusted paths

Binary pointer/length pairs must refer to a live readable allocation of that
initialized length. Keep the input owner alive throughout the call; a format
validator cannot prove that an arbitrary foreign pointer is valid.

Use `cborParseDynamicSafe` or `cborParseDynamicWithLimits` for
external bytes, then check the root shape, required fields, exact value types
and application ranges before constructing a domain value. The preflight
checks wire format and resource budgets; it does not define an application
schema. Parse failures return `DecodeError` with a typed kind and byte offset.

`cborUnmarshalSafe<T>` and `cborUnmarshalWithLimits<T>` run the same
wire-format preflight and then use the typed decoder. They do **not** validate
compatibility with `T`, reject every type mismatch or enforce required fields.
Use them only when the input schema is already trusted. Post-decode field
checks cannot make that unchecked typed traversal suitable for external data.

Use a per-protocol budget when the standard defaults are wider than your wire
contract:

```vex
import {
    DecodeErrorKind,
    DecodeLimits,
    cborParseDynamicWithLimits,
} from "serde/cbor";

let! limits = DecodeLimits.standard();
limits.maxTotalBytes = 1024 * 1024 as usize;
limits.maxDepth = 32 as usize;
limits.maxNodes = 100_000 as usize;

match cborParseDynamicWithLimits(data, length, limits) {
    Ok(value) => { /* consume value */ }
    Err(failure) => {
        if failure.isKind(DecodeErrorKind.DepthLimit) {
            $println("CBOR nesting rejected");
        }
    }
}
```

The safe subset accepts definite integers representable as `i64`, byte/text
strings, arrays, string-keyed maps, booleans, null and 32/64-bit
floats. It rejects truncation, trailing bytes, invalid UTF-8, non-string map
keys, over-budget values, tags, indefinite values and unsupported simple
values. Tags, `undefined` and indefinite containers need a future lossless
representation; silently erasing them would be incorrect.

`cborParseDynamic` and `cborUnmarshal` are single-pass trusted-data paths. They
do not validate bounds first and must not be used directly on untrusted input.

The historical regression matrix covers structured/dynamic round trips and
rejection of malformed wire data before struct mutation, plus truncation,
forged lengths, trailing bytes, invalid UTF-8, integer overflow, non-string keys
and resource budgets at O0 and O3. It does not establish typed-schema validation.
Official RFC 8949 corpora, canonical encoding and lossless tag/indefinite-value
support remain promotion work.

The 2026-08-25 M2 Max O3 short baseline measured coordinate encode/decode at
14.96/17.49 ns, trusted dynamic parse at 488.66 ns, allocation-free validation
at 51.87 ns and safe dynamic parse at 545.63 ns. The safe boundary added about
11.7% on this small fixture. These are regression baselines, not portable
promises.

## Check a domain field before construction

This complete program accepts an object with an integer `id` in `0..=100_000`.
It rejects a scalar root, a boolean field and a negative identifier. Extra keys
are ignored by this example; define stricter unknown-key and duplicate-key
policies separately if your protocol requires them. `asInt()` alone is not a
type check, because it returns a default for other variants.

```vex [cbor-schema.vx]
import { CborValue, cborMarshal, cborParseDynamicSafe, cborStringifyDynamic } from "serde/cbor";

struct Record { public: id: i64 }
struct WrongType { public: id: bool }

fn readId(packed: &string): Option<i32> {
    match cborParseDynamicSafe(packed.raw_ptr() as Ptr<u8>, packed.len() as u64) {
        Err(_) => { return None; }
        Ok(value) => {
            match &value {
                CborValue.Object(fields) => {
                    let key = "id";
                    match fields.get(&key) {
                        Some(field) => {
                            if !field.isInt() { return None; }
                            let id = field.asInt();
                            if id < 0 || id > 100_000 { return None; }
                            return Some(id as i32);
                        }
                        None => { return None; }
                    }
                }
                _ => { return None; }
            }
        }
    }
}

fn main(): i32 {
    let valid = cborMarshal(&Record { id: 42 });
    match readId(&valid) {
        Some(id) => { if id != 42 { return 1; } }
        None => { return 2; }
    }
    let wrongRoot = cborStringifyDynamic(&CborValue.Int(7));
    let wrongField = cborMarshal(&WrongType { id: true });
    let outOfRange = cborMarshal(&Record { id: -1 });
    for bytes in [&wrongRoot, &wrongField, &outOfRange] {
        match readId(bytes) {
            Some(_) => { return 3; }
            None => {}
        }
    }
    $println("CBOR schema: PASS");
    return 0;
}
```

Run `vex run cbor-schema.vx`. Expected stdout is `CBOR schema: PASS`,
exit 0. The input strings remain alive for the entire parse; only the checked
integer is returned to the application.
