commonware_codec/
lib.rs

1//! Serialize structured data.
2//!
3//! # Overview
4//!
5//! A binary serialization library designed to efficiently and safely:
6//! - Serialize structured data into a binary format
7//! - Deserialize untrusted binary input into structured data
8//!
9//! # Supported Types
10//!
11//! Natively supports:
12//! - Primitives: `u8`, `u16`, `u32`, `u64`, `i8`, `i16`, `i32`, `i64`, `f32`, `f64`, `bool`
13//! - Collections: `Vec<T>`, `Option<T>`, tuples, and fixed-size arrays like `[u8; N]`
14//! - Recursive serialization of nested structs and enums via trait implementations
15//!
16//! User-defined types can be serialized and deserialized by implementing the `Codec` trait.
17//! For types with a constant encoded size, optionally implement the `SizedCodec` trait.
18//!
19//! # Example
20//!
21//! ```
22//! use commonware_codec::{Codec, Reader, Writer, Error};
23//!
24//! // Define a custom struct
25//! #[derive(Debug, Clone, PartialEq)]
26//! struct Point {
27//!     xy: (u64, u64),
28//!     z: Option<u32>,
29//!     metadata: [u8; 11],
30//! }
31//!
32//! // Implement the Codec trait
33//! impl Codec for Point {
34//!     fn write(&self, writer: &mut impl Writer) {
35//!         // Basic types can be written by inferring the type
36//!         self.xy.write(writer);
37//!         self.z.write(writer);
38//!         self.metadata.write(writer);
39//!     }
40//!
41//!     fn read(reader: &mut impl Reader) -> Result<Self, Error> {
42//!         // Basic types can be inferred by the return type
43//!         let xy = <(u64, u64)>::read(reader)?;
44//!         let z = <Option<u32>>::read(reader)?;
45//!         let metadata = <[u8; 11]>::read(reader)?;
46//!         Ok(Self { xy, z, metadata })
47//!     }
48//!
49//!     fn len_encoded(&self) -> usize {
50//!       self.xy.len_encoded() + self.z.len_encoded() + self.metadata.len_encoded()
51//!     }
52//! }
53//! ```
54
55pub mod buffer;
56pub mod codec;
57pub mod error;
58pub mod types;
59pub mod varint;
60
61// Re-export main types and traits
62pub use buffer::{ReadBuffer, WriteBuffer};
63pub use codec::{Codec, Reader, SizedCodec, Writer};
64pub use error::Error;