pack_io/lib.rs
1//! # pack-io
2//!
3//! Compact binary wire format for Rust. Combines speed, schema evolution,
4//! and zero-copy deserialization under a single coherent contract.
5//!
6//! ## At a glance
7//!
8//! - **Tier 1** — [`encode`] and [`decode`]: one line each direction.
9//! [`decode_with_config`] / [`decode_view_with_config`] take a [`Config`]
10//! for untrusted or hashed input.
11//! - **Tier 2** —
12//! - [`Encoder`] / [`Decoder`] for in-memory buffers.
13//! - [`IoEncoder`] / [`IoDecoder`] for `std::io::Write` / `Read` streams
14//! (`std`-gated).
15//! - [`encode_into`] / [`decode_from`] convenience helpers over Read /
16//! Write.
17//! - **Tier 3** — implement [`Serialize`] / [`Deserialize`] on your own
18//! types, or derive them (feature `derive`). Both traits are generic over
19//! the [`Encode`] / [`Decode`] behaviour traits, so one impl works through
20//! every encoder / decoder the crate ships.
21//!
22//! ## Primitive support
23//!
24//! Integers (`u8` … `u128`, `i8` … `i128`, `usize` / `isize`, `NonZero*`),
25//! `bool`, `char`, `f32`, `f64`, `String` / `&str` / `Box<str>`,
26//! fixed-size arrays `[T; N]`, tuples of arity 1…12, `Option<T>`,
27//! `Result<T, E>`, `Duration`, `PhantomData<T>`, and `()`. `Rc<T>`,
28//! `Arc<T>`, `Box<T>` and `Cow<'_, T>` encode transparently as the value they hold.
29//!
30//! ## Collection support
31//!
32//! `Vec<T>` / `&[T]` / `Box<[T]>` / `VecDeque<T>`, `BTreeMap<K, V>`,
33//! `BTreeSet<T>`, and (with the default `std` feature) `HashMap<K, V>` and
34//! `HashSet<T>`. **Maps and sets encode in canonical key-sorted order** so
35//! that hashing, signing, or content-addressing the output is safe
36//! regardless of insertion order or hash randomisation.
37//!
38//! ## Stability
39//!
40//! The wire format has not changed since 1.0: every 2.x decoder reads every
41//! encoding a 1.x or 2.x encoder produced for valid data (checked against
42//! golden vectors written by 1.0.1), and every 2.x encoder produces the
43//! same bytes for the same value. 2.0 is a major release because decoding
44//! now enforces limits and the derive rejects misuse 1.x accepted; see the
45//! [migration guide](https://github.com/jamesgober/pack-io/blob/main/docs/MIGRATION.md).
46//! The normative spec is
47//! [`docs/WIRE_FORMAT.md`](https://github.com/jamesgober/pack-io/blob/main/docs/WIRE_FORMAT.md)
48//! and the public surface is listed in
49//! [`docs/API.md`](https://github.com/jamesgober/pack-io/blob/main/docs/API.md#frozen-public-surface).
50//!
51//! ## Quick start
52//!
53//! ```
54//! use pack_io::{encode, decode};
55//!
56//! let bytes = encode(&(7_u64, true, String::from("hello"))).unwrap();
57//! let back: (u64, bool, String) = decode(&bytes).unwrap();
58//! assert_eq!(back, (7, true, String::from("hello")));
59//! ```
60//!
61//! ## Invariants
62//!
63//! - **Round-trip integrity** — `decode(encode(v)) == v` for every
64//! supported type.
65//! - **Determinism** — the same value always produces the same bytes,
66//! regardless of insertion order, platform, or build flags. With
67//! [`Config::canonical`] on, the reverse also holds: the decoder accepts
68//! only those bytes, so the bytes identify the value. For a versioned
69//! struct that means only frames at the reader's own version (older and
70//! newer frames decode leniently). The guarantee covers types built from
71//! pack-io's impls and derives; a hand-written impl or `with` helper must
72//! itself accept one encoding per value, and serde sets need
73//! `pack_io::serde::sorted_set`.
74//! - **Safe decode**: on any byte sequence, no panic, no read past the
75//! input, no allocation larger than [`Config::max_alloc`] for one value,
76//! no length-prefixed allocation larger than the input can back, the
77//! memory one decoded message builds (collection slots at their
78//! in-memory size, owned buffers, boxed values, elements that occupy no
79//! input) bounded by [`Config::total_alloc_limit`], and no nesting deeper
80//! than [`Config::max_depth`] (so no stack overflow). For peer input,
81//! decode under [`Config::network`].
82//! - **Wire-format stability** — any 2.x decoder reads any 1.x or 2.x
83//! encoding of valid data.
84//!
85//! ## Feature flags
86//!
87//! | Feature | Default | Effect |
88//! |---|---|---|
89//! | `std` | yes | `std::error::Error`, `HashMap` / `HashSet`, the [`io`] module |
90//! | `derive` | no | `#[derive(Serialize, Deserialize, DeserializeView)]` |
91//! | `schema` | no | alias for `derive`, kept for compatibility (the schema attributes work with `derive` alone) |
92//! | `serde` | no | the [`serde` adapter](https://docs.rs/pack-io/latest/pack_io/serde/index.html): any `serde` type on the pack-io wire |
93//! | `bytes` | no | `Serialize` / `Deserialize` for `bytes::Bytes` / `BytesMut`, and `Encode` for `BytesMut` |
94//!
95//! ## `no_std`
96//!
97//! `pack-io` is `no_std`-capable. The default build enables `std` for the
98//! [`std::error::Error`] impl, `HashMap` / `HashSet` integration, and the
99//! [`io`] module. Disable the default feature to compile against `core` +
100//! `alloc` only; derives (including versioned ones) work there too:
101//!
102//! ```toml
103//! pack-io = { version = "2", default-features = false, features = ["derive"] }
104//! ```
105
106// The links above to `std`-only items resolve to the items themselves when
107// `std` is on, and to their docs.rs pages when it is off, so the docs build
108// cleanly (`-D warnings`) in every feature configuration.
109#![cfg_attr(
110 feature = "std",
111 doc = "[`IoEncoder`]: crate::IoEncoder\n\
112 [`IoDecoder`]: crate::IoDecoder\n\
113 [`encode_into`]: crate::encode_into\n\
114 [`decode_from`]: crate::decode_from\n\
115 [`io`]: crate::io\n\
116 [`std::error::Error`]: std::error::Error"
117)]
118#![cfg_attr(
119 not(feature = "std"),
120 doc = "[`IoEncoder`]: https://docs.rs/pack-io/2/pack_io/struct.IoEncoder.html\n\
121 [`IoDecoder`]: https://docs.rs/pack-io/2/pack_io/struct.IoDecoder.html\n\
122 [`encode_into`]: https://docs.rs/pack-io/2/pack_io/fn.encode_into.html\n\
123 [`decode_from`]: https://docs.rs/pack-io/2/pack_io/fn.decode_from.html\n\
124 [`io`]: https://docs.rs/pack-io/2/pack_io/io/index.html\n\
125 [`std::error::Error`]: https://doc.rust-lang.org/std/error/trait.Error.html"
126)]
127#![cfg_attr(not(feature = "std"), no_std)]
128#![cfg_attr(docsrs, feature(doc_cfg))]
129#![deny(missing_docs)]
130#![deny(unused_must_use)]
131#![deny(unused_results)]
132#![deny(clippy::unwrap_used)]
133#![deny(clippy::expect_used)]
134#![deny(clippy::todo)]
135#![deny(clippy::unimplemented)]
136#![deny(clippy::print_stdout)]
137#![deny(clippy::print_stderr)]
138#![deny(clippy::dbg_macro)]
139#![deny(clippy::unreachable)]
140#![deny(clippy::undocumented_unsafe_blocks)]
141#![forbid(unsafe_code)]
142#![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used))]
143
144extern crate alloc;
145
146#[cfg(feature = "std")]
147extern crate std;
148
149#[cfg(feature = "bytes")]
150mod bytes_impls;
151mod codec;
152mod error;
153mod impls;
154#[cfg(feature = "std")]
155pub mod io;
156#[cfg(feature = "serde")]
157pub mod serde;
158mod traits;
159mod varint;
160mod view;
161
162pub use crate::codec::{
163 Config, Decode, Decoder, Encode, Encoder, decode, decode_with_config, encode, peek_version,
164 varint_len,
165};
166pub use crate::error::{Result, SerialError};
167pub use crate::traits::{Deserialize, Serialize};
168pub use crate::view::{DeserializeView, decode_view, decode_view_with_config};
169
170#[cfg(feature = "std")]
171pub use crate::io::{IoDecoder, IoEncoder, decode_from, decode_from_with_config, encode_into};
172
173// Re-export the derive macros when the `derive` feature is on. Users write
174// `#[derive(pack_io::Serialize, pack_io::Deserialize, pack_io::DeserializeView)]`
175// and the proc-macro crate is the implementation detail.
176#[cfg(feature = "derive")]
177pub use pack_io_derive::{Deserialize, DeserializeView, Serialize};
178
179/// Semantic version of this crate, as declared in `Cargo.toml`.
180///
181/// # Examples
182///
183/// ```
184/// // VERSION mirrors Cargo.toml exactly, with no parsing.
185/// assert_eq!(pack_io::VERSION, env!("CARGO_PKG_VERSION"));
186/// ```
187pub const VERSION: &str = env!("CARGO_PKG_VERSION");
188
189/// Support code for `pack-io-derive`. Not public API: the items here exist
190/// only so that generated code can reach them through a stable path, and
191/// they may change in any release. The derive crate is pinned to this exact
192/// version of `pack-io`, so the two always move together.
193#[doc(hidden)]
194pub mod __private {
195 use crate::codec::{Config, Decode, Decoder, Encode, Encoder};
196 use crate::error::{Result, SerialError};
197
198 pub use crate::codec::SizeCounter;
199
200 /// Sized adapter so any `E: Encode + ?Sized` can be viewed as
201 /// `&mut dyn Encode` by [`Tally`].
202 pub struct Fwd<'a, E: Encode + ?Sized>(pub &'a mut E);
203
204 impl<E: Encode + ?Sized> core::fmt::Debug for Fwd<'_, E> {
205 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
206 f.write_str("Fwd")
207 }
208 }
209
210 impl<E: Encode + ?Sized> Encode for Fwd<'_, E> {
211 #[inline]
212 fn write_byte(&mut self, byte: u8) -> Result<()> {
213 self.0.write_byte(byte)
214 }
215
216 #[inline]
217 fn write_bytes(&mut self, bytes: &[u8]) -> Result<()> {
218 self.0.write_bytes(bytes)
219 }
220
221 #[inline]
222 fn reserve(&mut self, additional: usize) {
223 self.0.reserve(additional);
224 }
225
226 #[inline]
227 fn write_varint_u64(&mut self, value: u64) -> Result<()> {
228 self.0.write_varint_u64(value)
229 }
230
231 #[inline]
232 fn write_varint_u128(&mut self, value: u128) -> Result<()> {
233 self.0.write_varint_u128(value)
234 }
235 }
236
237 /// Pass-through encoder that forwards every byte to `inner` and counts
238 /// them. Debug builds of derived versioned encodes write the body
239 /// through it, so the body length is checked in the same single pass
240 /// that writes it (a separate counting pass would re-encode every
241 /// nested versioned body once per level of nesting). The inner encoder
242 /// is type-erased so recursive types instantiate one `Tally` type, not
243 /// one per nesting level.
244 pub struct Tally<'a> {
245 inner: &'a mut dyn Encode,
246 written: usize,
247 }
248
249 impl<'a> Tally<'a> {
250 /// Wrap `inner`, starting the count at zero.
251 #[inline]
252 pub fn new(inner: &'a mut dyn Encode) -> Self {
253 Self { inner, written: 0 }
254 }
255
256 /// Bytes forwarded to the inner encoder so far.
257 #[inline]
258 pub fn written(&self) -> usize {
259 self.written
260 }
261 }
262
263 impl core::fmt::Debug for Tally<'_> {
264 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
265 f.debug_struct("Tally")
266 .field("written", &self.written)
267 .finish_non_exhaustive()
268 }
269 }
270
271 impl Encode for Tally<'_> {
272 #[inline]
273 fn write_byte(&mut self, byte: u8) -> Result<()> {
274 self.inner.write_byte(byte)?;
275 self.written = self.written.saturating_add(1);
276 Ok(())
277 }
278
279 #[inline]
280 fn write_bytes(&mut self, bytes: &[u8]) -> Result<()> {
281 self.inner.write_bytes(bytes)?;
282 self.written = self.written.saturating_add(bytes.len());
283 Ok(())
284 }
285
286 #[inline]
287 fn reserve(&mut self, additional: usize) {
288 self.inner.reserve(additional);
289 }
290
291 #[inline]
292 fn write_varint_u64(&mut self, value: u64) -> Result<()> {
293 self.inner.write_varint_u64(value)?;
294 self.written = self.written.saturating_add(crate::varint_len(value));
295 Ok(())
296 }
297 }
298
299 /// Read and validate the leading `version` varint of a versioned
300 /// struct whose type declares `known`: it must fit in `u32` and must
301 /// not be the reserved `0`. In canonical mode it must also equal
302 /// `known`, because only a frame at the reader's own version has a
303 /// single encoding the reader can verify (an older frame is a second
304 /// encoding of the defaulted value; a newer one carries fields the
305 /// reader cannot check).
306 #[inline]
307 pub fn read_version<D: Decode + ?Sized>(decoder: &mut D, known: u32) -> Result<u32> {
308 let raw = decoder.read_varint_u64()?;
309 if raw == 0 {
310 return Err(SerialError::InvalidVersion { version: 0 });
311 }
312 let version = u32::try_from(raw).map_err(|_| SerialError::IntegerOutOfRange)?;
313 if version != known && decoder.config().canonical {
314 return Err(SerialError::NonCanonical {
315 reason: "versioned struct version",
316 });
317 }
318 Ok(version)
319 }
320
321 /// Read and validate the `body_len` varint of a versioned struct
322 /// against `max_alloc` and, when known, the remaining input.
323 #[inline]
324 pub fn read_body_len<D: Decode + ?Sized>(decoder: &mut D) -> Result<usize> {
325 let declared = decoder.read_varint_u64()?;
326 let remaining = decoder.remaining_hint();
327 let over_input = remaining.is_some_and(|r| declared > r as u64);
328 if declared > decoder.max_alloc() as u64 || over_input {
329 return Err(SerialError::InvalidLength {
330 declared,
331 remaining: remaining.unwrap_or(0),
332 });
333 }
334 usize::try_from(declared).map_err(|_| SerialError::IntegerOutOfRange)
335 }
336
337 /// A decoder over a versioned struct body that enforces the caller's
338 /// `config`, continues its nesting `depth`, and starts from its running
339 /// `unbacked` total (see [`settle_body`]).
340 #[inline]
341 pub fn body_decoder(
342 bytes: &[u8],
343 config: Config,
344 depth: usize,
345 unbacked: usize,
346 ) -> Decoder<'_> {
347 Decoder::nested(bytes, config, depth, unbacked)
348 }
349
350 /// Finish a versioned body and return its final `unbacked` total.
351 /// Unread bytes are expected when the payload is newer than the type
352 /// (`wire_version > known_version`: fields this reader does not know)
353 /// and tolerated in lenient mode. Canonical mode rejects them in every
354 /// case ([`read_version`] has already required `wire == known` there).
355 #[inline]
356 pub fn finish_body(body: &Decoder<'_>, wire_version: u32, known_version: u32) -> Result<usize> {
357 let _ = (wire_version, known_version);
358 if !body.is_empty() && body.config().canonical {
359 return Err(SerialError::NonCanonical {
360 reason: "versioned body",
361 });
362 }
363 Ok(Decode::unbacked(body))
364 }
365
366 /// Carry the memory a versioned body charged (`after - before`) over to
367 /// the decoder the body was read from, so the total budget spans the
368 /// whole decode.
369 #[inline]
370 pub fn settle_body<D: Decode + ?Sized>(
371 decoder: &mut D,
372 before: usize,
373 after: usize,
374 ) -> Result<()> {
375 if after > before {
376 decoder.charge_unbacked(after - before)?;
377 }
378 Ok(())
379 }
380
381 /// In canonical mode, check that the retired slot that started at
382 /// `start` in `body` holds exactly the bytes `write_default` produces
383 /// (the encoding of the field's default, which is all a conforming
384 /// writer puts there). Does nothing in lenient mode.
385 #[inline]
386 pub fn check_retired<F>(body: &Decoder<'_>, start: usize, write_default: F) -> Result<()>
387 where
388 F: FnOnce(&mut Encoder) -> Result<()>,
389 {
390 if !body.config().canonical {
391 return Ok(());
392 }
393 let slot = body
394 .consumed()
395 .and_then(|consumed| consumed.get(start..))
396 .unwrap_or_default();
397 let mut expected = Encoder::with_capacity(slot.len());
398 write_default(&mut expected)?;
399 if expected.as_bytes() != slot {
400 return Err(SerialError::NonCanonical {
401 reason: "retired field",
402 });
403 }
404 Ok(())
405 }
406
407 /// Debug-build check, emitted by the derive after writing a versioned
408 /// struct's body, that the body length it wrote up front (from
409 /// `encoded_len`) matches the bytes the fields actually produced.
410 #[inline]
411 pub fn check_body_len(declared: usize, written: usize) -> Result<()> {
412 if declared != written {
413 return Err(SerialError::custom(
414 "pack-io: a field's `encoded_len` disagrees with its `serialize`; the versioned body \
415 length would be wrong",
416 ));
417 }
418 Ok(())
419 }
420
421 /// Count the bytes `write` produces, for `#[pack_io(with = "...")]`
422 /// fields whose helper module has no `encoded_len`.
423 #[inline]
424 pub fn count_with<F>(write: F) -> Result<usize>
425 where
426 F: FnOnce(&mut SizeCounter) -> Result<()>,
427 {
428 let mut counter = SizeCounter::default();
429 write(&mut counter)?;
430 Ok(counter.count())
431 }
432
433 /// `Err(UnknownVariant)` for an enum tag no variant claims.
434 #[inline]
435 pub fn unknown_variant<T>(kind: &'static str, index: u64) -> Result<T> {
436 Err(SerialError::UnknownVariant { kind, index })
437 }
438}
439
440/// Runs the code in `docs/MIGRATION.md` as doctests, so the upgrade guide
441/// cannot drift from the API it describes.
442#[cfg(all(doctest, feature = "derive", feature = "std"))]
443#[doc = include_str!("../docs/MIGRATION.md")]
444pub struct MigrationGuideDoctests;
445
446#[cfg(test)]
447mod tests {
448 use super::*;
449
450 #[test]
451 fn version_matches_cargo_manifest() {
452 assert_eq!(VERSION, env!("CARGO_PKG_VERSION"));
453 }
454
455 // `alloc::string::String` rather than the prelude `String`, so this
456 // test compiles under `cargo test --no-default-features` (no `std`).
457 #[test]
458 fn tier_one_encode_decode_round_trips_a_tuple() {
459 use alloc::string::String;
460 let bytes = encode(&(1_u64, true, String::from("hello"))).expect("encode");
461 let back: (u64, bool, String) = decode(&bytes).expect("decode");
462 assert_eq!(back, (1, true, String::from("hello")));
463 }
464}