Skip to main content

encode/
lib.rs

1#![doc = include_str!("../README.md")]
2#![forbid(
3    missing_docs,
4    missing_debug_implementations,
5    unsafe_code,
6    clippy::std_instead_of_core,
7    clippy::std_instead_of_alloc,
8    clippy::dbg_macro,
9    clippy::exit,
10    clippy::infinite_loop,
11    clippy::mem_forget,
12    clippy::panic,
13    clippy::cargo,
14    clippy::missing_const_for_fn,
15    clippy::tabs_in_doc_comments,
16    clippy::perf
17)]
18#![warn(clippy::pedantic)]
19#![cfg_attr(not(feature = "std"), no_std)]
20
21#[cfg(feature = "alloc")]
22extern crate alloc;
23
24pub mod combinators;
25mod encodables;
26pub mod encoders;
27
28/// A trait for types that can be encoded into a specific encoder.
29///
30/// Defines a generic interface for encoding data structures into
31/// an encoder.
32///
33/// ## A note about purity
34///
35/// Implementations of `Encodable` **must be pure**. That means:
36///
37/// - **No side effects**: Implementations must not modify global or external
38///   state.
39/// - **Deterministic**: Given the same input and encoder, the output must
40///   always be the same.
41/// - **No panics**: Panicking inside an `encode` implementation is considered a
42///   bug.
43///
44/// Ignoring these rules may lead to logic errors.
45///
46/// ## Encoder Specialization
47///
48/// On nightly Rust, you can use [trait specialization](https://rust-lang.github.io/rfcs/1210-impl-specialization.html)
49/// to implement optimized encodings for specific encoders, such as
50/// [`SizeEncoder`](encoders::SizeEncoder). For example, you may want to use
51/// this if your encoder runs computationally expensive operations for obtaining
52/// the size of the encoded form.
53///
54/// ## Errors
55///
56/// Implementations must return an appropriate error if encoding fails. Errors
57/// can occur if:
58/// - The encoder encounters an internal error (e.g., out of space).
59/// - The encoded output would be invalid.
60///
61/// Control flow may depend on these errors (unlike [`core::fmt::Write`]).
62pub trait Encodable<E>
63where
64    E: BaseEncoder,
65{
66    /// The error type returned by the `encode` method.
67    ///
68    /// This must include the encoder's error type via `From<E::Error>`.
69    type Error: From<E::Error>;
70
71    /// Encodes `self` into the given encoder.
72    ///
73    /// # Errors
74    ///
75    /// Returns an error if writing fails or if the encoded output would be
76    /// invalid.
77    fn encode(&self, encoder: &mut E) -> Result<(), Self::Error>;
78}
79
80/// A trait that defines common types and operations for encoders.
81///
82/// An encoder is a type that can gather encoded data into a specific output
83/// format. These are typically buffers, but can also be other types that
84/// perform some operation on the encoded result. An example type is the
85/// [`SizeEncoder`] type, which counts how many bytes would be encoded and is
86/// often used for sizing the output buffer before encoding.
87///
88/// The `BaseEncoder` trait is the foundation for all encoders, providing a
89/// common interface for encoding operations. It's also the main building block
90/// for all [`combinators`].
91///
92/// [`SizeEncoder`]: encoders::SizeEncoder
93pub trait BaseEncoder {
94    /// The error type returned by all encoding operations.
95    ///
96    /// For example, an encoder might return an error if the output buffer is
97    /// full.
98    type Error;
99}
100
101/// A trait for encoders that can handle UTF-8 encodables.
102///
103/// This trait extends [`BaseEncoder`] to include a types and methods
104/// specifically used for handling UTF-8 encodables. Encoders may use this trait
105/// as bounds for generic encodables to signal that the output will be UTF-8
106/// encoded. Doing so allows encoders such as [`String`] to be used.
107pub trait StrEncoder: BaseEncoder {
108    /// Writes an [`str`] into the encoder.
109    ///
110    /// # Errors
111    ///
112    /// Returns an error if the encoder is unable to write the string
113    /// due to capacity limits, encoding errors, or internal failures.
114    fn put_str(&mut self, string: &str) -> Result<(), Self::Error>;
115}
116
117/// A trait for encoders that can handle byte encodables.
118///
119/// This trait extends [`BaseEncoder`] to include types and methods specifically
120/// used for handling any kind of byte encodables. Encoders may use this
121/// trait as bounds for generic encodables to signal that the output will be any
122/// kind of byte steam.
123///
124/// Note that all [`ByteEncoder`]s also implement [`StrEncoder`].
125pub trait ByteEncoder: BaseEncoder {
126    /// Writes a slice of bytes into the encoder.
127    ///
128    /// # Errors
129    ///
130    /// Returns an error if the encoder cannot write the entire slice
131    /// due to capacity limits, encoding errors, or internal failures.
132    fn put_slice(&mut self, slice: &[u8]) -> Result<(), Self::Error>;
133    /// Writes a single byte into the encoder.
134    ///
135    /// # Errors
136    ///
137    /// Returns an error if the encoder cannot write the byte
138    /// due to capacity limits, encoding errors, or internal failures.
139    fn put_byte(&mut self, byte: u8) -> Result<(), Self::Error>;
140}
141
142/// An extension trait for types that can compute the size of their encoded form
143/// using a [`SizeEncoder`].
144///
145/// Use this trait to pre-compute buffer sizes or perform validations before
146/// full encoding.
147///
148/// This trait is automatically implemented for all types that implement
149/// [`Encodable`] for [`SizeEncoder`].
150///
151/// ## Errors
152///
153/// Returns an error if the [`Encodable`] fails to encode.
154///
155/// [`SizeEncoder`]: encoders::SizeEncoder
156pub trait EncodableSize: Encodable<encoders::SizeEncoder> {
157    /// Computes the size of the encoded representation of `self`.
158    ///
159    /// # Errors
160    ///
161    /// Returns an error if encoding fails internally during the size
162    /// estimation.
163    fn encoded_size(&self) -> Result<usize, Self::Error>;
164}
165
166impl<T> StrEncoder for T
167where
168    T: ByteEncoder,
169{
170    #[inline]
171    fn put_str(&mut self, string: &str) -> Result<(), Self::Error> {
172        string.as_bytes().encode(self)
173    }
174}
175
176impl<T> EncodableSize for T
177where
178    T: Encodable<encoders::SizeEncoder>,
179{
180    #[inline]
181    fn encoded_size(&self) -> Result<usize, Self::Error> {
182        let mut encoder = encoders::SizeEncoder::new();
183        self.encode(&mut encoder)?;
184        Ok(encoder.size())
185    }
186}
187
188#[cfg(test)]
189mod tests {
190    use super::*;
191
192    #[test]
193    fn assert_that_encoded_size_returns_byte_count() {
194        let size = "hello".encoded_size().unwrap();
195        assert_eq!(size, 5);
196    }
197}