# MessagePack (`serde/msgpack`)

MessagePack exposes comptime-specialized struct codecs and an owning
`MsgPackValue` 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 { msgpackMarshal, msgpackUnmarshalSafe } from "serde/msgpack";

struct Sensor {
    public:
    id: i64,
    temperature: f64,
    active: bool,
}

let source = Sensor { id: 42, temperature: 23.5, active: true };
let packed = msgpackMarshal(&source);
let! decoded = Sensor { id: 0, temperature: 0.0, active: false };
match msgpackUnmarshalSafe(
    packed.raw_ptr() as Ptr<u8>, packed.len() as u64, &decoded,
) {
    Ok(_) => { $println(decoded.temperature); }
    Err(failure) => { $println(failure.message()); }
}
```

Dynamic APIs are `msgpackParseDynamic`, `msgpackParseDynamicSafe`,
`msgpackParseDynamicWithLimits`, `msgpackStringifyDynamic` and `msgpackToJson`.
Binary parsers take an explicit pointer and byte length.

## 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 `msgpackParseDynamicSafe` or `msgpackParseDynamicWithLimits` 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.

`msgpackUnmarshalSafe<T>` and `msgpackUnmarshalWithLimits<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.

```vex
import {
    DecodeLimits,
    msgpackParseDynamicWithLimits,
} from "serde/msgpack";

let! limits = DecodeLimits.standard();
limits.maxTotalBytes = 1024 * 1024 as usize;
limits.maxDepth = 32 as usize;
limits.maxContainerItems = 65_536 as usize;

match msgpackParseDynamicWithLimits(data, length, limits) {
    Ok(value) => { /* consume value */ }
    Err(failure) => { $println(failure.message()); }
}
```

The safe dynamic subset covers integers representable as `i64`, 32/64-bit
floats, strings, binary values, arrays, string-keyed maps, booleans and nil. It
rejects truncation, forged lengths, trailing bytes, invalid UTF-8, non-string
keys, over-budget values, the reserved marker and extension-family markers.
Extensions and timestamps remain rejected until the value model can preserve
them losslessly.

`msgpackParseDynamic` and `msgpackUnmarshal` are single-pass trusted-data paths;
they intentionally skip preflight and are not an untrusted-input API.

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 conformance corpora, duplicate/canonical policy and lossless extension
support remain promotion work.

The 2026-08-25 M2 Max O3 short baseline measured coordinate encode/decode at
13.35/14.28 ns, trusted dynamic parse at 477.94 ns, allocation-free validation
at 49.94 ns and safe dynamic parse at 530.92 ns. The safe boundary added about
11.1% 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 [msgpack-schema.vx]
import { MsgPackValue, msgpackMarshal, msgpackParseDynamicSafe, msgpackStringifyDynamic } from "serde/msgpack";

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

fn readId(packed: &string): Option<i32> {
    match msgpackParseDynamicSafe(packed.raw_ptr() as Ptr<u8>, packed.len() as u64) {
        Err(_) => { return None; }
        Ok(value) => {
            match &value {
                MsgPackValue.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 = msgpackMarshal(&Record { id: 42 });
    match readId(&valid) {
        Some(id) => { if id != 42 { return 1; } }
        None => { return 2; }
    }
    let wrongRoot = msgpackStringifyDynamic(&MsgPackValue.Int(7));
    let wrongField = msgpackMarshal(&WrongType { id: true });
    let outOfRange = msgpackMarshal(&Record { id: -1 });
    for bytes in [&wrongRoot, &wrongField, &outOfRange] {
        match readId(bytes) {
            Some(_) => { return 3; }
            None => {}
        }
    }
    $println("MessagePack schema: PASS");
    return 0;
}
```

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