commonware_codec/
lib.rs

1//! Serialize structured data.
2//!
3//! # Overview
4//!
5//! Provides traits and implementations for efficient and safe binary serialization and
6//! deserialization of structured data. The library focuses on:
7//!
8//! - **Performance:** Uses the [`bytes`] crate and aims to minimize allocations.
9//! - **Safety:** Deserialization of untrusted data is made safer via the `Cfg` associated type in
10//!   the [`Read`] trait, allowing users to impose limits (like maximum lengths) or other strict
11//!   constraints on the data.
12//! - **Ease of Use:** Provides implementations for common Rust types and uses extension traits
13//!   ([`ReadExt`], [`DecodeExt`], etc.) for ergonomic usage.
14//!
15//! # Core Concepts
16//!
17//! The library revolves around a few core traits:
18//!
19//! - [`Write`]: Implement this to define how your type is written to a byte buffer.
20//! - [`Read`]: Implement this to define how your type is read from a byte buffer.
21//!   It has an associated `Cfg` type, primarily used to enforce constraints (e.g., size limits)
22//!   when reading untrusted data. Use `()` if no config is needed.
23//! - [`EncodeSize`]: Implement this to calculate the exact encoded byte size of a value.
24//!   Required for efficient buffer pre-allocation.
25//! - [`FixedSize`]: Marker trait for types whose encoded size is constant. Automatically
26//!   implements [`EncodeSize`].
27//!
28//! Helper traits combine these for convenience:
29//!
30//! - [`Encode`]: Combines [`Write`] + [`EncodeSize`]. Provides [`Encode::encode()`] method.
31//! - [`Decode`]: Requires [`Read`]. Provides [`Decode::decode_cfg()`] method that ensures
32//!   that the entire buffer is consumed.
33//! - [`Codec`]: Combines [`Encode`] + [`Decode`].
34//!
35//! # Supported Types
36//!
37//! Natively supports encoding/decoding for:
38//! - Primitives: [`bool`],
39//!   [`u8`], [`u16`], [`u32`], [`u64`], [`u128`],
40//!   [`i8`], [`i16`], [`i32`], [`i64`], [`i128`],
41//!   [`f32`], [`f64`], `[u8; N]`,
42//!   and [`usize`] (must fit within a [`u32`] for cross-platform compatibility).
43//! - Collections: [`Vec<T>`], [`Option<T>`]
44//! - Tuples: `(T1, T2, ...)` (up to 12 elements)
45//! - Networking:
46//!   [`Ipv4Addr`](`std::net::Ipv4Addr`),
47//!   [`Ipv6Addr`](`std::net::Ipv6Addr`),
48//!   [`SocketAddrV4`](`std::net::SocketAddrV4`),
49//!   [`SocketAddrV6`](`std::net::SocketAddrV6`),
50//!   [`SocketAddr`](`std::net::SocketAddr`)
51//! - Common External Types: [`::bytes::Bytes`]
52//!
53//! # Implementing for Custom Types
54//!
55//! You typically need to implement [`Write`], [`EncodeSize`] (unless [`FixedSize`]), and [`Read`]
56//! for your custom structs and enums.
57//!
58//! ## Example 1. Fixed-Size Type
59//!
60//! ```
61//! use bytes::{Buf, BufMut};
62//! use commonware_codec::{Error, FixedSize, Read, ReadExt, Write, Encode, DecodeExt};
63//!
64//! // Define a custom struct
65//! #[derive(Debug, Clone, PartialEq)]
66//! struct Point {
67//!     x: u32, // FixedSize
68//!     y: u32, // FixedSize
69//! }
70//!
71//! // 1. Implement Write: How to serialize the struct
72//! impl Write for Point {
73//!     fn write(&self, buf: &mut impl BufMut) {
74//!         // u32 implements Write
75//!         self.x.write(buf);
76//!         self.y.write(buf);
77//!     }
78//! }
79//!
80//! // 2. Implement FixedSize (provides EncodeSize automatically)
81//! impl FixedSize for Point {
82//!     // u32 implements FixedSize
83//!     const SIZE: usize = u32::SIZE + u32::SIZE;
84//! }
85//!
86//! // 3. Implement Read: How to deserialize the struct (uses default Cfg = ())
87//! impl Read for Point {
88//!     type Cfg = ();
89//!     fn read_cfg(buf: &mut impl Buf, _: &()) -> Result<Self, Error> {
90//!         // Use ReadExt::read for ergonomic reading when Cfg is ()
91//!         let x = u32::read(buf)?;
92//!         let y = u32::read(buf)?;
93//!         Ok(Self { x, y })
94//!     }
95//! }
96//!
97//! // Point now automatically implements Encode, Decode, Codec
98//! let point = Point { x: 1, y: 2 };
99//!
100//! // Encode is available via FixedSize + Write
101//! let bytes = point.encode();
102//! assert_eq!(bytes.len(), Point::SIZE);
103//!
104//! // Decode is available via Read, use DecodeExt
105//! let decoded_point = Point::decode(bytes).unwrap();
106//! assert_eq!(point, decoded_point);
107//! ```
108//!
109//! ## Example 2. Variable-Size Type
110//!
111//! ```
112//! use bytes::{Buf, BufMut};
113//! use commonware_codec::{
114//!     Decode, Encode, EncodeSize, Error, FixedSize, Read, ReadExt,
115//!     ReadRangeExt, Write, RangeCfg
116//! };
117//! use std::ops::RangeInclusive; // Example RangeCfg
118//!
119//! // Define a simple configuration for reading Item
120//! // Here, it just specifies the maximum allowed metadata length.
121//! #[derive(Clone)]
122//! pub struct ItemConfig {
123//!     max_metadata_len: usize,
124//! }
125//!
126//! // Define a custom struct
127//! #[derive(Debug, Clone, PartialEq)]
128//! struct Item {
129//!     id: u64,           // FixedSize
130//!     name: Option<u32>, // EncodeSize (depends on Option)
131//!     metadata: Vec<u8>, // EncodeSize (variable)
132//! }
133//!
134//! // 1. Implement Write
135//! impl Write for Item {
136//!     fn write(&self, buf: &mut impl BufMut) {
137//!         self.id.write(buf);       // u64 implements Write
138//!         self.name.write(buf);     // Option<u32> implements Write
139//!         self.metadata.write(buf); // Vec<u8> implements Write
140//!     }
141//! }
142//!
143//! // 2. Implement EncodeSize
144//! impl EncodeSize for Item {
145//!     fn encode_size(&self) -> usize {
146//!         // Sum the sizes of the parts
147//!         self.id.encode_size()         // u64 implements EncodeSize (via FixedSize)
148//!         + self.name.encode_size()     // Option<u32> implements EncodeSize
149//!         + self.metadata.encode_size() // Vec<u8> implements EncodeSize
150//!     }
151//! }
152//!
153//! // 3. Implement Read
154//! impl Read for Item {
155//!     type Cfg = ItemConfig;
156//!     fn read_cfg(buf: &mut impl Buf, cfg: &ItemConfig) -> Result<Self, Error> {
157//!         // u64 requires Cfg = (), uses ReadExt::read
158//!         let id = <u64>::read(buf)?;
159//!
160//!         // Option<u32> requires Cfg = (), uses ReadExt::read
161//!         let name = <Option<u32>>::read(buf)?;
162//!
163//!         // For Vec<u8>, the required config is (RangeCfg, InnerConfig)
164//!         // InnerConfig for u8 is (), so we need (RangeCfg, ())
165//!         // We use ReadRangeExt::read_range which handles the () for us.
166//!         // The RangeCfg limits the vector length using our ItemConfig.
167//!         let metadata_range = 0..=cfg.max_metadata_len; // Create the RangeCfg
168//!         let metadata = <Vec<u8>>::read_range(buf, metadata_range)?;
169//!
170//!         Ok(Self { id, name, metadata })
171//!     }
172//! }
173//!
174//! // Now you can use Encode and Decode:
175//! let item = Item { id: 101, name: None, metadata: vec![1, 2, 3] };
176//! let config = ItemConfig { max_metadata_len: 1024 };
177//!
178//! // Encode the item (uses Write + EncodeSize)
179//! let bytes = item.encode(); // Returns BytesMut
180//!
181//! // Decode the item
182//! // decode_cfg ensures all bytes are consumed.
183//! let decoded_item = Item::decode_cfg(bytes, &config).unwrap();
184//! assert_eq!(item, decoded_item);
185//! ```
186
187pub mod codec;
188pub mod config;
189pub mod error;
190pub mod extensions;
191pub mod types;
192pub mod util;
193pub mod varint;
194
195// Re-export main types and traits
196pub use codec::*;
197pub use config::RangeCfg;
198pub use error::Error;
199pub use extensions::*;