Why pack-io
Existing crates each cover a slice of the problem; none of them own all three properties together.
| Crate | Speed | Schema evolution | Zero-copy decode | Wire-format spec |
|---|---|---|---|---|
bincode |
✓ | — | — | — |
rkyv |
✓ | — | ✓ * | — |
postcard |
✓ | — | — | ✓ |
pack-io |
✓ | ✓ | ✓ | ✓ |
* rkyv requires alignment discipline at every use site; the cost is paid by the caller, not the codec.
The contract is the same wire format on every supported platform, the same bytes for the same value every time, and a decoder that cannot be made to panic, overflow the stack, or allocate memory beyond what the input backs and the configured max_alloc allows.
Speed, with numbers
Measured for v2.0.0 on an AMD Ryzen 9 9950X3D (Ubuntu under WSL2, rustc 1.99, one pinned core), as the fastest of 300 short trials — the machine was shared with other work, which made Criterion's means swing by tens of percent. Method, environment and the full tables: docs/PERFORMANCE_BASELINE.md. Reproduce with cargo bench --bench min_trials --features derive.
| Workload (ns, lower is better) | pack-io | bincode | postcard | rkyv |
|---|---|---|---|---|
| struct encode | 24.4 | 24.0 | 134.0 | 53.6 |
| struct decode (owned) | 57.2 | 153.2 | 134.3 | 55.1 |
| struct decode (zero-copy) | 25.4 | — | — | 12.8 |
u64 round-trip |
5.7 | 7.7 | 6.6 | — |
64-byte String round-trip |
16.6 | 19.8 | 32.4 | — |
64-byte &str view |
5.4 | — | — | — |
4 KiB Vec<u8> decode |
31.3 | 48.8 | 1,137 | — |
pack-io is the fastest of the four on the u64 and String round-trips, the &str view and Vec<u8> decode; it ties bincode on struct encode and rkyv on owned struct decode. rkyv's archived access is about 2× faster than pack-io's zero-copy view — rkyv reads a fixed memory layout, pack-io walks varints as its spec defines, by design. Ratios depend on platform and allocator (on Windows the 1.0 runs had bincode's owned decode much closer to pack-io's), so benchmark your own workload. Regression policy: a change exceeding 5 % on any row blocks the merge; analysis in docs/PERFORMANCE.md.
What it does
- Compact binary encoding of Rust values into a small, predictable wire format
- Schema-versioned messages - append fields without breaking older or newer peers; remove fields with a documented reader-first rollout
- Zero-copy deserialization for
&[u8]/&str/ length-prefixed slices when the input lives long enough - Deterministic output - the same value always produces the same bytes; an opt-in canonical mode makes the decoder accept only those bytes (for versioned structs: only frames at the reader's own version)
- Safe under untrusted input - allocation bounded by the input and a per-value cap, nesting bounded by a depth limit, no panics on malformed bytes
- Runtime-agnostic - synchronous codec, usable from any context
Features
- Compact — varint integers, length-prefixed strings and byte runs, no field names on the wire
- Schema evolution —
#[pack_io(version, since)]to add fields,retiredto drop one safely,peek_versionfor dispatch - Zero-copy decode —
DeserializeViewborrows&str/&[u8]fields straight from the input - Deterministic — canonical map / set ordering;
Config::with_canonical(true)for hash-, signature- and content-address-safe decoding - Safe defaults —
max_alloc(1 GiB) andmax_depth(128) limits, input-bounded allocation, versioned bodies decoded under the caller's limits no_std-capable —core+alloc, derives included- Derive macro —
#[derive(Serialize, Deserialize, DeserializeView)]withskip,default,with,crate, and explicit enumindexattributes (featurederive) - serde adapter — any
serdetype on the pack-io wire, byte-identical to the native derive for the same shape; set fields opt in withpack_io::serde::sorted_set(featureserde) bytesintegration —Bytes/BytesMutvalues, andBytesMutas an encode sink (featurebytes)
Stability contract
Frozen for 2.x |
Reference |
|---|---|
| Public API — types, traits, free functions, attributes, feature flags (additions only) | docs/API.md § Frozen public surface |
| Wire format — byte-level spec (version 1.3) | docs/WIRE_FORMAT.md |
| Performance — comparative baseline | docs/PERFORMANCE_BASELINE.md |
Backwards-compatible additions (new variants on the #[non_exhaustive] SerialError enum, new trait methods with default implementations, new built-in impls for core / alloc types) land in 2.x minor releases. Source-breaking and wire-format-breaking changes wait for a new major version. Upgrading from 1.x: docs/MIGRATION.md.
Per-release history is in CHANGELOG.md; detailed release notes live in docs/release/.
Installation
[]
= "2"
# With derive macros (including the schema-evolution attributes):
= { = "2", = ["derive"] }
# serde adapter / bytes integration:
= { = "2", = ["derive", "serde", "bytes"] }
# no_std build (core + alloc; no streaming I/O, no HashMap / HashSet):
= { = "2", = false, = ["derive"] }
The schema feature from earlier releases still works; it is an alias for derive.
API surface
Three tiers cover every use case. See docs/API.md for the complete reference and docs/WIRE_FORMAT.md for the normative byte-level spec.
Tier 1 — the lazy path
use ;
let bytes: = encode.unwrap;
let back: = decode.unwrap;
assert_eq!;
Tier 2a — the in-memory Encoder / Decoder
Re-use a single Vec<u8> across many encodes; read several values from one buffer. Configuration is validated once, at construction time.
use ;
let mut enc = new;
enc.write.unwrap;
enc.write.unwrap;
let bytes = enc.into_inner;
let cfg = new.with_max_alloc;
let mut dec = with_config.unwrap;
let n: u64 = dec.read.unwrap;
let s: String = dec.read.unwrap;
assert_eq!;
Tier 2b — the streaming IoEncoder<W> / IoDecoder<R>
Write directly into any std::io::Write, read from any std::io::Read. Gated on the default std feature. The streaming decoder grows its buffers only as bytes arrive, so a peer that declares a huge length and stalls costs one small chunk.
use ;
use Cursor;
// Single-shot helpers (encode_into / decode_from) over any Read / Write:
let mut sink: = Vecnew;
encode_into.unwrap;
let back: = decode_from.unwrap;
assert_eq!;
// Or hold an encoder / decoder for multi-value streams:
let mut buf: = Vecnew;
let mut dec = new;
let a: u64 = dec.read.unwrap;
let b: u64 = dec.read.unwrap;
assert_eq!;
Tier 3 — derive on your own types
#[derive(Serialize, Deserialize)] writes the boilerplate. Works on every struct shape (named, tuple, unit), every enum variant shape, and on generic types.
use ;
Enums encode as varint(variant_index) ++ fields. Indices follow declaration order unless pinned with #[pack_io(index = N)], so either append new variants to the end or pin the indices. Attributes: skip, default / default = "path", with = "module", crate = "path" (for crates that re-export pack-io), and index = N; anything unknown is a compile error. See docs/API.md § Derive attributes.
Schema evolution — append-only forward and backward compatibility
Add #[pack_io(version = N)] to your type and #[pack_io(since = N)] to additive fields. Old encoders write what they know; new decoders read what's there and Default::default() the rest. New encoders write everything; old decoders read what they know and skip the trailing bytes inside the length-framed body.
use ;
let bytes = encode.unwrap;
assert_eq!;
// v2 reads v1 cleanly: `timestamp` defaults to None.
let upgraded: MessageV2 = decode.unwrap;
assert_eq!;
// And v1 reads v2 cleanly: the trailing timestamp bytes are skipped.
let bytes = encode.unwrap;
let downgraded: MessageV1 = decode.unwrap;
assert_eq!;
Versioned structs wrap their body in a varint(version) ++ varint(body_len) ++ body frame; non-versioned structs keep the plain field-concatenation encoding. The choice is per-type, opt-in via the attribute. The body is decoded under the caller's limits, and both the owning and the zero-copy decoders read it.
Dropping a field has two forms. #[pack_io(retired = N)] keeps the field's slot on the wire and writes its default from version N: every reader, including ones built before the change, stays aligned and simply sees the default, and new readers ignore whatever is in the slot. That is the safe choice and costs about one byte. #[pack_io(removed = N)] drops the bytes entirely (the 1.x deprecated encoding, so 1.x payloads keep decoding); because readers that predate the removal cannot detect it, roll readers out first. 1.x deprecated = N is a compile error in 2.0 that names both options; write removed = N to keep the exact 1.x bytes. Full normative spec: docs/WIRE_FORMAT.md §3.8.
use ;
Tier 3 — zero-copy views
#[derive(DeserializeView)] plus the [decode_view] free function give you a parallel "borrowed" decode path. &'a str and &'a [u8] fields point directly into the input buffer — no per-field allocation, the borrow checker enforces the lifetime. Types without a lifetime can derive it too, so owned helper types nest inside views.
use ;
let bytes = encode.unwrap;
let view: = decode_view.unwrap;
assert_eq!; // points into `bytes`
On the representative borrow-heavy record (u64 + u8 + String + Vec<String> + Vec<u8>), the view decode takes 25 ns against 57 ns for the owning decode on the measurement machine (about 2.3× faster), and a 64-byte &str view takes 5.4 ns. The gap grows with the number and size of string and byte fields. Reproduce with cargo bench --bench codec_bench --features derive.
Decoding untrusted input
Every decoder enforces, on any byte sequence: no panic, no read past the input, no single value above max_alloc (default 1 GiB), no length-prefixed allocation the input cannot back, at most max_alloc across the whole decode for collection elements that occupy no input bytes (Vec<Box<()>>, structs whose fields are all skip), and no nesting deeper than max_depth (default 128 derived types). Tighten the limits to your protocol, and turn on canonical mode where bytes are hashed or signed (a canonical decoder reads a versioned struct only at its own version):
use ;
use BTreeMap;
let cfg = new
.with_max_alloc
.with_max_depth
.with_canonical;
// An unsorted map with a duplicate key: a lenient decoder accepts it,
// canonical mode rejects it.
let bytes = ;
assert!;
assert_eq!;
serde adapter (feature serde)
let bytes = to_vec.unwrap;
assert_eq!; // same wire as the native derive
let back: Point = from_slice.unwrap;
assert_eq!;
serde-derived types encode to the same bytes as the native derive for the same shape, so the two can be mixed on one wire, with one exception: serde has no set type, so a BTreeSet / HashSet field reaches the adapter as a sequence in iteration order (and a HashSet's order is not deterministic). Mark set fields #[serde(with = "pack_io::serde::sorted_set")] to get the native, sorted set bytes and canonical-mode order checks. deserialize_any-based serde features (untagged enums, flatten) are not supported, because the format is not self-describing. Details: docs/API.md § serde adapter.
If you need to hand-roll: the [Serialize] / [Deserialize] traits
Both are generic over the Encode / Decode behaviour traits — one impl works through every encoder flavour the crate ships (in-memory and streaming).
use ;
Supported types
| Group | Types |
|---|---|
| Unsigned integers | u8, u16, u32, u64, u128, usize, NonZeroU* |
| Signed integers | i8, i16, i32, i64, i128, isize, NonZeroI* |
| Floats | f32, f64 |
| Bool / char / unit | bool, char, (), PhantomData<T> |
| Strings | String, &str (encode + view), Box<str>, Rc<str>, Arc<str>, Cow<str> (borrowed in views) |
| Bytes | Vec<u8>, &[u8] (encode + view), Cow<[u8]>, bytes::Bytes / BytesMut (bytes) |
| Sequences | Vec<T>, &[T] (encode), Box<[T]>, VecDeque<T>, [T; N] |
| Tuples | arity 1 through 12 |
| Sums | Option<T>, Result<T, E> |
| Maps | BTreeMap<K, V>, HashMap<K, V> (std) |
| Sets | BTreeSet<T>, HashSet<T> (std) |
| Time | Duration |
| Pointers | &T (encode), Box<T>, Rc<T>, Arc<T>, Cow<T> — transparent |
| User types | any struct / enum with #[derive(Serialize, Deserialize)] (derive) |
| Zero-copy types | any struct / enum with #[derive(DeserializeView)] (derive) |
| serde types | any serde::Serialize / Deserialize type through pack_io::serde (serde) |
Box<T> encodes exactly like T, so recursive types such as struct List { value: u8, next: Option<Box<List>> } derive directly; their depth is bounded by max_depth.
Canonical map / set encoding (the determinism contract)
Maps and sets (BTreeMap, HashMap, BTreeSet, HashSet) are encoded with entries sorted lexicographically by their encoded key bytes. A HashMap and a BTreeMap holding the same logical data therefore encode to identical bytes, regardless of insertion order or build-flag-dependent hash randomisation. With Config::with_canonical(true) the decoder enforces that order (and shortest-form varints, and for versioned structs the reader's own version, no trailing body bytes and default-valued retired slots), so the bytes identify the value. Canonical decoding stays opt-in in 2.0: lenient decoding already returns the right value for every valid encoding, enforcing canonical form needs the whole frame in memory (the streaming IoDecoder rejects it), and it costs about 25 % on small-key map decoding, which only the users who hash or sign encoded bytes need to pay. Full normative spec: docs/WIRE_FORMAT.md §4.
Invariants
- Round-trip integrity —
decode(encode(v)) == vfor every supported type. - Determinism — the same value always produces the same bytes; no map-iteration-order leaks, no time-dependence, no platform-dependence.
- Safe decode — no panic, no read past the input, allocation bounded by the input and
max_alloc(elements that occupy no input bytes bymax_allocacross the decode), nesting bounded bymax_depth, on any byte sequence. - Wire-format stability — unchanged since 1.0; any 2.x decoder reads any 1.x or 2.x encoding of valid data.
As of 2.0.0 these are enforced by 425 unit and integration tests and 81 doc tests (cargo test --workspace --all-features): property tests for round-trip, determinism, canonical-mode injectivity (versioned structs included) and encoded_len; 46 golden vectors written by pack-io 1.0.1 and 16 for the encodings added in 2.0; a counting-allocator suite that bounds peak memory on hostile input, including collections of elements that occupy no input bytes; recursion-depth tests; and 26 compile-fail / compile-pass cases for the derive. Twenty cargo-fuzz targets run in CI with a 64 MiB allocation limit (fuzz/README.md).
Testing
# Stable + MSRV (1.85) on Linux / macOS / Windows, full feature matrix
RUSTDOCFLAGS="-D warnings"
# Supply chain and API compatibility
# Fuzzing (nightly, Linux / WSL), see fuzz/README.md
&&
# Benchmarks
Examples
Each example is self-contained.
Cross-Platform Support
Tier 1 Support:
- ✅ Linux (x86_64, aarch64)
- ✅ macOS (x86_64, Apple Silicon)
- ✅ Windows (x86_64)
Encoding is byte-deterministic across all three; the CI matrix runs the test suite on each, on stable and MSRV, and also builds for a bare-metal no_std target (thumbv7em-none-eabihf). Platform-specific behaviour is forbidden in the codec — there is no #[cfg(target_os = …)] branch on the encode or decode path.
Where It Fits
pack-io is the serialization substrate under network-protocol, wire-codec, and Hive DB. It is consumed by raft-io for log entries and by event-stream (when it lands) for message framing. It stays foreign-compatible: it works on its own without any other crate in the family.
Contributing
Before opening a PR, the full local checklist must pass:
RUSTDOCFLAGS="-D warnings"
Any change touching the wire format requires a proptest round-trip and a determinism test in the same commit, and must keep tests/golden.rs (vectors written by pack-io 1.0.1) and tests/golden_v2.rs passing. Wire-format-breaking changes are only accepted for a new major version, with a migration note in CHANGELOG.md.