Skip to main content

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, at most
77//!   `max_alloc` across the whole decode for collection elements that
78//!   occupy no input bytes (`Box<()>`, all-`skip` structs, …), and no
79//!   nesting deeper than [`Config::max_depth`] (so no stack overflow).
80//! - **Wire-format stability** — any 2.x decoder reads any 1.x or 2.x
81//!   encoding of valid data.
82//!
83//! ## Feature flags
84//!
85//! | Feature | Default | Effect |
86//! |---|---|---|
87//! | `std` | yes | `std::error::Error`, `HashMap` / `HashSet`, the [`io`] module |
88//! | `derive` | no | `#[derive(Serialize, Deserialize, DeserializeView)]` |
89//! | `schema` | no | alias for `derive`, kept for compatibility (the schema attributes work with `derive` alone) |
90//! | `serde` | no | the [`serde` adapter](https://docs.rs/pack-io/latest/pack_io/serde/index.html): any `serde` type on the pack-io wire |
91//! | `bytes` | no | `Serialize` / `Deserialize` for `bytes::Bytes` / `BytesMut`, and `Encode` for `BytesMut` |
92//!
93//! ## `no_std`
94//!
95//! `pack-io` is `no_std`-capable. The default build enables `std` for the
96//! [`std::error::Error`] impl, `HashMap` / `HashSet` integration, and the
97//! [`io`] module. Disable the default feature to compile against `core` +
98//! `alloc` only; derives (including versioned ones) work there too:
99//!
100//! ```toml
101//! pack-io = { version = "2", default-features = false, features = ["derive"] }
102//! ```
103
104// The links above to `std`-only items resolve to the items themselves when
105// `std` is on, and to their docs.rs pages when it is off, so the docs build
106// cleanly (`-D warnings`) in every feature configuration.
107#![cfg_attr(
108    feature = "std",
109    doc = "[`IoEncoder`]: crate::IoEncoder\n\
110           [`IoDecoder`]: crate::IoDecoder\n\
111           [`encode_into`]: crate::encode_into\n\
112           [`decode_from`]: crate::decode_from\n\
113           [`io`]: crate::io\n\
114           [`std::error::Error`]: std::error::Error"
115)]
116#![cfg_attr(
117    not(feature = "std"),
118    doc = "[`IoEncoder`]: https://docs.rs/pack-io/2/pack_io/struct.IoEncoder.html\n\
119           [`IoDecoder`]: https://docs.rs/pack-io/2/pack_io/struct.IoDecoder.html\n\
120           [`encode_into`]: https://docs.rs/pack-io/2/pack_io/fn.encode_into.html\n\
121           [`decode_from`]: https://docs.rs/pack-io/2/pack_io/fn.decode_from.html\n\
122           [`io`]: https://docs.rs/pack-io/2/pack_io/io/index.html\n\
123           [`std::error::Error`]: https://doc.rust-lang.org/std/error/trait.Error.html"
124)]
125#![cfg_attr(not(feature = "std"), no_std)]
126#![cfg_attr(docsrs, feature(doc_cfg))]
127#![deny(missing_docs)]
128#![deny(unused_must_use)]
129#![deny(unused_results)]
130#![deny(clippy::unwrap_used)]
131#![deny(clippy::expect_used)]
132#![deny(clippy::todo)]
133#![deny(clippy::unimplemented)]
134#![deny(clippy::print_stdout)]
135#![deny(clippy::print_stderr)]
136#![deny(clippy::dbg_macro)]
137#![deny(clippy::unreachable)]
138#![deny(clippy::undocumented_unsafe_blocks)]
139#![forbid(unsafe_code)]
140#![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used))]
141
142extern crate alloc;
143
144#[cfg(feature = "std")]
145extern crate std;
146
147#[cfg(feature = "bytes")]
148mod bytes_impls;
149mod codec;
150mod error;
151mod impls;
152#[cfg(feature = "std")]
153pub mod io;
154#[cfg(feature = "serde")]
155pub mod serde;
156mod traits;
157mod varint;
158mod view;
159
160pub use crate::codec::{
161    Config, Decode, Decoder, Encode, Encoder, decode, decode_with_config, encode, peek_version,
162    varint_len,
163};
164pub use crate::error::{Result, SerialError};
165pub use crate::traits::{Deserialize, Serialize};
166pub use crate::view::{DeserializeView, decode_view, decode_view_with_config};
167
168#[cfg(feature = "std")]
169pub use crate::io::{IoDecoder, IoEncoder, decode_from, decode_from_with_config, encode_into};
170
171// Re-export the derive macros when the `derive` feature is on. Users write
172// `#[derive(pack_io::Serialize, pack_io::Deserialize, pack_io::DeserializeView)]`
173// and the proc-macro crate is the implementation detail.
174#[cfg(feature = "derive")]
175pub use pack_io_derive::{Deserialize, DeserializeView, Serialize};
176
177/// Semantic version of this crate, as declared in `Cargo.toml`.
178///
179/// # Examples
180///
181/// ```
182/// // VERSION mirrors Cargo.toml exactly, with no parsing.
183/// assert_eq!(pack_io::VERSION, env!("CARGO_PKG_VERSION"));
184/// ```
185pub const VERSION: &str = env!("CARGO_PKG_VERSION");
186
187/// Support code for `pack-io-derive`. Not public API: the items here exist
188/// only so that generated code can reach them through a stable path, and
189/// they may change in any release. The derive crate is pinned to this exact
190/// version of `pack-io`, so the two always move together.
191#[doc(hidden)]
192pub mod __private {
193    use crate::codec::{Config, Decode, Decoder, Encode, Encoder};
194    use crate::error::{Result, SerialError};
195
196    pub use crate::codec::SizeCounter;
197
198    /// Sized adapter so any `E: Encode + ?Sized` can be viewed as
199    /// `&mut dyn Encode` by [`Tally`].
200    pub struct Fwd<'a, E: Encode + ?Sized>(pub &'a mut E);
201
202    impl<E: Encode + ?Sized> core::fmt::Debug for Fwd<'_, E> {
203        fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
204            f.write_str("Fwd")
205        }
206    }
207
208    impl<E: Encode + ?Sized> Encode for Fwd<'_, E> {
209        #[inline]
210        fn write_byte(&mut self, byte: u8) -> Result<()> {
211            self.0.write_byte(byte)
212        }
213
214        #[inline]
215        fn write_bytes(&mut self, bytes: &[u8]) -> Result<()> {
216            self.0.write_bytes(bytes)
217        }
218
219        #[inline]
220        fn reserve(&mut self, additional: usize) {
221            self.0.reserve(additional);
222        }
223
224        #[inline]
225        fn write_varint_u64(&mut self, value: u64) -> Result<()> {
226            self.0.write_varint_u64(value)
227        }
228
229        #[inline]
230        fn write_varint_u128(&mut self, value: u128) -> Result<()> {
231            self.0.write_varint_u128(value)
232        }
233    }
234
235    /// Pass-through encoder that forwards every byte to `inner` and counts
236    /// them. Debug builds of derived versioned encodes write the body
237    /// through it, so the body length is checked in the same single pass
238    /// that writes it (a separate counting pass would re-encode every
239    /// nested versioned body once per level of nesting). The inner encoder
240    /// is type-erased so recursive types instantiate one `Tally` type, not
241    /// one per nesting level.
242    pub struct Tally<'a> {
243        inner: &'a mut dyn Encode,
244        written: usize,
245    }
246
247    impl<'a> Tally<'a> {
248        /// Wrap `inner`, starting the count at zero.
249        #[inline]
250        pub fn new(inner: &'a mut dyn Encode) -> Self {
251            Self { inner, written: 0 }
252        }
253
254        /// Bytes forwarded to the inner encoder so far.
255        #[inline]
256        pub fn written(&self) -> usize {
257            self.written
258        }
259    }
260
261    impl core::fmt::Debug for Tally<'_> {
262        fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
263            f.debug_struct("Tally")
264                .field("written", &self.written)
265                .finish_non_exhaustive()
266        }
267    }
268
269    impl Encode for Tally<'_> {
270        #[inline]
271        fn write_byte(&mut self, byte: u8) -> Result<()> {
272            self.inner.write_byte(byte)?;
273            self.written = self.written.saturating_add(1);
274            Ok(())
275        }
276
277        #[inline]
278        fn write_bytes(&mut self, bytes: &[u8]) -> Result<()> {
279            self.inner.write_bytes(bytes)?;
280            self.written = self.written.saturating_add(bytes.len());
281            Ok(())
282        }
283
284        #[inline]
285        fn reserve(&mut self, additional: usize) {
286            self.inner.reserve(additional);
287        }
288
289        #[inline]
290        fn write_varint_u64(&mut self, value: u64) -> Result<()> {
291            self.inner.write_varint_u64(value)?;
292            self.written = self.written.saturating_add(crate::varint_len(value));
293            Ok(())
294        }
295    }
296
297    /// Read and validate the leading `version` varint of a versioned
298    /// struct whose type declares `known`: it must fit in `u32` and must
299    /// not be the reserved `0`. In canonical mode it must also equal
300    /// `known`, because only a frame at the reader's own version has a
301    /// single encoding the reader can verify (an older frame is a second
302    /// encoding of the defaulted value; a newer one carries fields the
303    /// reader cannot check).
304    #[inline]
305    pub fn read_version<D: Decode + ?Sized>(decoder: &mut D, known: u32) -> Result<u32> {
306        let raw = decoder.read_varint_u64()?;
307        if raw == 0 {
308            return Err(SerialError::InvalidVersion { version: 0 });
309        }
310        let version = u32::try_from(raw).map_err(|_| SerialError::IntegerOutOfRange)?;
311        if version != known && decoder.config().canonical {
312            return Err(SerialError::NonCanonical {
313                reason: "versioned struct version",
314            });
315        }
316        Ok(version)
317    }
318
319    /// Read and validate the `body_len` varint of a versioned struct
320    /// against `max_alloc` and, when known, the remaining input.
321    #[inline]
322    pub fn read_body_len<D: Decode + ?Sized>(decoder: &mut D) -> Result<usize> {
323        let declared = decoder.read_varint_u64()?;
324        let remaining = decoder.remaining_hint();
325        let over_input = remaining.is_some_and(|r| declared > r as u64);
326        if declared > decoder.max_alloc() as u64 || over_input {
327            return Err(SerialError::InvalidLength {
328                declared,
329                remaining: remaining.unwrap_or(0),
330            });
331        }
332        usize::try_from(declared).map_err(|_| SerialError::IntegerOutOfRange)
333    }
334
335    /// A decoder over a versioned struct body that enforces the caller's
336    /// `config`, continues its nesting `depth`, and starts from its running
337    /// `unbacked` total (see [`settle_body`]).
338    #[inline]
339    pub fn body_decoder(
340        bytes: &[u8],
341        config: Config,
342        depth: usize,
343        unbacked: usize,
344    ) -> Decoder<'_> {
345        Decoder::nested(bytes, config, depth, unbacked)
346    }
347
348    /// Finish a versioned body and return its final `unbacked` total.
349    /// Unread bytes are expected when the payload is newer than the type
350    /// (`wire_version > known_version`: fields this reader does not know)
351    /// and tolerated in lenient mode. Canonical mode rejects them in every
352    /// case ([`read_version`] has already required `wire == known` there).
353    #[inline]
354    pub fn finish_body(body: &Decoder<'_>, wire_version: u32, known_version: u32) -> Result<usize> {
355        let _ = (wire_version, known_version);
356        if !body.is_empty() && body.config().canonical {
357            return Err(SerialError::NonCanonical {
358                reason: "versioned body",
359            });
360        }
361        Ok(Decode::unbacked(body))
362    }
363
364    /// Carry the memory a versioned body charged for zero-input collection
365    /// elements (`after - before`) over to the decoder the body was read
366    /// from, so the `max_alloc` budget spans the whole decode.
367    #[inline]
368    pub fn settle_body<D: Decode + ?Sized>(
369        decoder: &mut D,
370        before: usize,
371        after: usize,
372    ) -> Result<()> {
373        if after > before {
374            decoder.charge_unbacked(after - before)?;
375        }
376        Ok(())
377    }
378
379    /// In canonical mode, check that the retired slot that started at
380    /// `start` in `body` holds exactly the bytes `write_default` produces
381    /// (the encoding of the field's default, which is all a conforming
382    /// writer puts there). Does nothing in lenient mode.
383    #[inline]
384    pub fn check_retired<F>(body: &Decoder<'_>, start: usize, write_default: F) -> Result<()>
385    where
386        F: FnOnce(&mut Encoder) -> Result<()>,
387    {
388        if !body.config().canonical {
389            return Ok(());
390        }
391        let slot = body
392            .consumed()
393            .and_then(|consumed| consumed.get(start..))
394            .unwrap_or_default();
395        let mut expected = Encoder::with_capacity(slot.len());
396        write_default(&mut expected)?;
397        if expected.as_bytes() != slot {
398            return Err(SerialError::NonCanonical {
399                reason: "retired field",
400            });
401        }
402        Ok(())
403    }
404
405    /// Debug-build check, emitted by the derive after writing a versioned
406    /// struct's body, that the body length it wrote up front (from
407    /// `encoded_len`) matches the bytes the fields actually produced.
408    #[inline]
409    pub fn check_body_len(declared: usize, written: usize) -> Result<()> {
410        if declared != written {
411            return Err(SerialError::custom(
412                "pack-io: a field's `encoded_len` disagrees with its `serialize`; the versioned body \
413                 length would be wrong",
414            ));
415        }
416        Ok(())
417    }
418
419    /// Count the bytes `write` produces, for `#[pack_io(with = "...")]`
420    /// fields whose helper module has no `encoded_len`.
421    #[inline]
422    pub fn count_with<F>(write: F) -> Result<usize>
423    where
424        F: FnOnce(&mut SizeCounter) -> Result<()>,
425    {
426        let mut counter = SizeCounter::default();
427        write(&mut counter)?;
428        Ok(counter.count())
429    }
430
431    /// `Err(UnknownVariant)` for an enum tag no variant claims.
432    #[inline]
433    pub fn unknown_variant<T>(kind: &'static str, index: u64) -> Result<T> {
434        Err(SerialError::UnknownVariant { kind, index })
435    }
436}
437
438/// Runs the code in `docs/MIGRATION.md` as doctests, so the upgrade guide
439/// cannot drift from the API it describes.
440#[cfg(all(doctest, feature = "derive", feature = "std"))]
441#[doc = include_str!("../docs/MIGRATION.md")]
442pub struct MigrationGuideDoctests;
443
444#[cfg(test)]
445mod tests {
446    use super::*;
447
448    #[test]
449    fn version_matches_cargo_manifest() {
450        assert_eq!(VERSION, env!("CARGO_PKG_VERSION"));
451    }
452
453    // `alloc::string::String` rather than the prelude `String`, so this
454    // test compiles under `cargo test --no-default-features` (no `std`).
455    #[test]
456    fn tier_one_encode_decode_round_trips_a_tuple() {
457        use alloc::string::String;
458        let bytes = encode(&(1_u64, true, String::from("hello"))).expect("encode");
459        let back: (u64, bool, String) = decode(&bytes).expect("decode");
460        assert_eq!(back, (1, true, String::from("hello")));
461    }
462}