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`], [`Option`], `BTreeMap`, `BTreeSet`
44//! - Tuples: `(T1, T2, ...)` (up to 12 elements)
45//! - Common External Types: [::bytes::Bytes]
46//!
47//! With the `std` feature (enabled by default):
48//! - Networking:
49//! [`std::net::Ipv4Addr`],
50//! [`std::net::Ipv6Addr`],
51//! [`std::net::SocketAddrV4`],
52//! [`std::net::SocketAddrV6`],
53//! [`std::net::SocketAddr`]
54//! - Collections:
55//! [`std::collections::HashMap`],
56//! [`std::collections::HashSet`]
57//!
58//! # Implementing for Custom Types
59//!
60//! You typically need to implement [Write], [EncodeSize] (unless [FixedSize]), and [Read]
61//! for your custom structs and enums.
62//!
63//! ## Example 1. Fixed-Size Type
64//!
65//! ```
66//! use bytes::{Buf, BufMut};
67//! use commonware_codec::{Error, FixedSize, Read, ReadExt, Write, Encode, DecodeExt};
68//!
69//! // Define a custom struct
70//! #[derive(Debug, Clone, PartialEq)]
71//! struct Point {
72//! x: u32, // FixedSize
73//! y: u32, // FixedSize
74//! }
75//!
76//! // 1. Implement Write: How to serialize the struct
77//! impl Write for Point {
78//! fn write(&self, buf: &mut impl BufMut) {
79//! // u32 implements Write
80//! self.x.write(buf);
81//! self.y.write(buf);
82//! }
83//! }
84//!
85//! // 2. Implement FixedSize (provides EncodeSize automatically)
86//! impl FixedSize for Point {
87//! // u32 implements FixedSize
88//! const SIZE: usize = u32::SIZE + u32::SIZE;
89//! }
90//!
91//! // 3. Implement Read: How to deserialize the struct (uses default Cfg = ())
92//! impl Read for Point {
93//! type Cfg = ();
94//! fn read_cfg(buf: &mut impl Buf, _: &()) -> Result<Self, Error> {
95//! // Use ReadExt::read for ergonomic reading when Cfg is ()
96//! let x = u32::read(buf)?;
97//! let y = u32::read(buf)?;
98//! Ok(Self { x, y })
99//! }
100//! }
101//!
102//! // Point now automatically implements Encode, Decode, Codec
103//! let point = Point { x: 1, y: 2 };
104//!
105//! // Encode is available via FixedSize + Write
106//! let bytes = point.encode();
107//! assert_eq!(bytes.len(), Point::SIZE);
108//!
109//! // Decode is available via Read, use DecodeExt
110//! let decoded_point = Point::decode(bytes).unwrap();
111//! assert_eq!(point, decoded_point);
112//! ```
113//!
114//! ## Example 2. Variable-Size Type
115//!
116//! ```
117//! use bytes::{Buf, BufMut};
118//! use commonware_codec::{
119//! Decode, Encode, EncodeSize, Error, FixedSize, Read, ReadExt,
120//! ReadRangeExt, Write, RangeCfg
121//! };
122//! use core::ops::RangeInclusive; // Example RangeCfg
123//!
124//! // Define a simple configuration for reading Item
125//! // Here, it just specifies the maximum allowed metadata length.
126//! #[derive(Clone)]
127//! pub struct ItemConfig {
128//! max_metadata_len: usize,
129//! }
130//!
131//! // Define a custom struct
132//! #[derive(Debug, Clone, PartialEq)]
133//! struct Item {
134//! id: u64, // FixedSize
135//! name: Option<u32>, // EncodeSize (depends on Option)
136//! metadata: Vec<u8>, // EncodeSize (variable)
137//! }
138//!
139//! // 1. Implement Write
140//! impl Write for Item {
141//! fn write(&self, buf: &mut impl BufMut) {
142//! self.id.write(buf); // u64 implements Write
143//! self.name.write(buf); // Option<u32> implements Write
144//! self.metadata.write(buf); // Vec<u8> implements Write
145//! }
146//! }
147//!
148//! // 2. Implement EncodeSize
149//! impl EncodeSize for Item {
150//! fn encode_size(&self) -> usize {
151//! // Sum the sizes of the parts
152//! self.id.encode_size() // u64 implements EncodeSize (via FixedSize)
153//! + self.name.encode_size() // Option<u32> implements EncodeSize
154//! + self.metadata.encode_size() // Vec<u8> implements EncodeSize
155//! }
156//! }
157//!
158//! // 3. Implement Read
159//! impl Read for Item {
160//! type Cfg = ItemConfig;
161//! fn read_cfg(buf: &mut impl Buf, cfg: &ItemConfig) -> Result<Self, Error> {
162//! // u64 requires Cfg = (), uses ReadExt::read
163//! let id = <u64>::read(buf)?;
164//!
165//! // Option<u32> requires Cfg = (), uses ReadExt::read
166//! let name = <Option<u32>>::read(buf)?;
167//!
168//! // For Vec<u8>, the required config is (RangeCfg, InnerConfig)
169//! // InnerConfig for u8 is (), so we need (RangeCfg, ())
170//! // We use ReadRangeExt::read_range which handles the () for us.
171//! // The RangeCfg limits the vector length using our ItemConfig.
172//! let metadata_range = 0..=cfg.max_metadata_len; // Create the RangeCfg
173//! let metadata = <Vec<u8>>::read_range(buf, metadata_range)?;
174//!
175//! Ok(Self { id, name, metadata })
176//! }
177//! }
178//!
179//! // Now you can use Encode and Decode:
180//! let item = Item { id: 101, name: None, metadata: vec![1, 2, 3] };
181//! let config = ItemConfig { max_metadata_len: 1024 };
182//!
183//! // Encode the item (uses Write + EncodeSize)
184//! let bytes = item.encode(); // Returns BytesMut
185//!
186//! // Decode the item
187//! // decode_cfg ensures all bytes are consumed.
188//! let decoded_item = Item::decode_cfg(bytes, &config).unwrap();
189//! assert_eq!(item, decoded_item);
190//! ```
191
192#![doc(
193 html_logo_url = "https://commonware.xyz/imgs/rustdoc_logo.svg",
194 html_favicon_url = "https://commonware.xyz/favicon.ico"
195)]
196#![cfg_attr(not(feature = "std"), no_std)]
197
198#[cfg(not(feature = "std"))]
199extern crate alloc;
200
201pub mod codec;
202pub mod config;
203pub mod error;
204pub mod extensions;
205pub mod types;
206pub mod util;
207pub mod varint;
208
209// Re-export main types and traits
210pub use codec::*;
211pub use config::RangeCfg;
212pub use error::Error;
213pub use extensions::*;