Skip to main content

multi_trait/
try_decode_from.rs

1// SPDX-License-Identifier: Apache-2.0
2use crate::Error;
3use unsigned_varint::decode;
4
5/// Trait for fallibly decoding values from byte slices.
6///
7/// This trait provides zero-copy parsing of varint-encoded values from byte slices,
8/// returning both the decoded value and the remaining unconsumed bytes. This design
9/// enables efficient sequential parsing of multiple values from a single buffer.
10///
11/// # Lifetime Parameter
12///
13/// The `'a` lifetime parameter ties the returned slice reference to the input buffer,
14/// preventing dangling references and enabling zero-copy parsing.
15///
16/// # Error Handling
17///
18/// Decoding can fail for several reasons:
19/// - Insufficient bytes in the input
20/// - Invalid varint encoding
21/// - Truncated data
22///
23/// Errors are returned as structured [`Error`] types with proper
24/// source chains for debugging.
25///
26/// # Performance
27///
28/// Decoding is highly optimized:
29/// - Zero allocations (returns slice references)
30/// - No data copying
31/// - Constant-time validation
32///
33/// # Thread Safety
34///
35/// This trait is `Send + Sync` safe. Implementations are stateless and can be
36/// called concurrently from multiple threads.
37///
38/// # Examples
39///
40/// ## Basic Decoding
41///
42/// ```rust
43/// use multi_trait::TryDecodeFrom;
44///
45/// // Decode a single value
46/// let bytes = vec![42];
47/// let (value, remaining) = u8::try_decode_from(&bytes).unwrap();
48/// assert_eq!(value, 42);
49/// assert!(remaining.is_empty());
50/// ```
51///
52/// ## Sequential Decoding
53///
54/// ```rust
55/// use multi_trait::TryDecodeFrom;
56///
57/// // Decode multiple values from one buffer
58/// let bytes = vec![0x01, 0x02, 0x03];
59/// let (first, rest) = u8::try_decode_from(&bytes).unwrap();
60/// let (second, rest) = u8::try_decode_from(rest).unwrap();
61/// let (third, rest) = u8::try_decode_from(rest).unwrap();
62///
63/// assert_eq!(first, 1);
64/// assert_eq!(second, 2);
65/// assert_eq!(third, 3);
66/// assert!(rest.is_empty());
67/// ```
68///
69/// ## Error Handling
70///
71/// ```rust
72/// use multi_trait::{TryDecodeFrom, Error};
73///
74/// // Handle decode errors
75/// let empty: &[u8] = &[];
76/// match u32::try_decode_from(empty) {
77///     Ok((value, _)) => println!("Decoded: {}", value),
78///     Err(Error::UnsignedVarintDecode { .. }) => {
79///         // Expected for empty input
80///     }
81///     Err(e) => panic!("Unexpected error: {}", e),
82/// }
83/// ```
84///
85/// # Implemented For
86///
87/// - `bool`: Decodes 0 as false, non-zero as true
88/// - `u8`, `u16`, `u32`, `u64`, `u128`: Variable-length decoding
89/// - `usize`: Platform-dependent (32-bit or 64-bit)
90pub trait TryDecodeFrom<'a>: Sized {
91    /// The error type returned on decoding failure.
92    ///
93    /// For built-in implementations, this is [`Error`].
94    type Error;
95
96    /// Try to decode a value from a byte slice.
97    ///
98    /// On success, returns a tuple containing:
99    /// 1. The decoded value
100    /// 2. A slice reference to the remaining unconsumed bytes
101    ///
102    /// The remaining bytes slice shares the same lifetime as the input,
103    /// enabling zero-copy sequential parsing.
104    ///
105    /// # Errors
106    ///
107    /// Returns an error if:
108    /// - The input slice is too short
109    /// - The varint encoding is invalid
110    /// - The encoded value is truncated
111    ///
112    /// # Examples
113    ///
114    /// ```rust
115    /// use multi_trait::TryDecodeFrom;
116    ///
117    /// let bytes = vec![0xFF, 0x01]; // Varint encoding of 255
118    /// let (value, remaining) = u8::try_decode_from(&bytes).unwrap();
119    /// assert_eq!(value, 255);
120    /// assert!(remaining.is_empty());
121    /// ```
122    fn try_decode_from(bytes: &'a [u8]) -> Result<(Self, &'a [u8]), Self::Error>;
123}
124
125/// Macro to implement TryDecodeFrom for unsigned integer types using varint decoding.
126///
127/// This macro eliminates code duplication by generating identical implementations
128/// for different numeric types. Each implementation:
129/// 1. Calls the appropriate decode function from unsigned_varint
130/// 2. Maps any decode error to a properly structured Error with source chain
131/// 3. Returns the decoded value and remaining bytes
132///
133/// # Usage
134///
135/// ```text
136/// impl_try_decode_from! {
137///     u8 => u8;
138///     u16 => u16;
139/// }
140/// ```
141///
142/// # Error Handling
143///
144/// The macro properly constructs errors with source chains for debugging,
145/// following Rust error handling best practices.
146///
147/// # Hygiene
148///
149/// This macro uses fully qualified paths to ensure proper hygiene and avoid
150/// namespace collisions with user code.
151macro_rules! impl_try_decode_from {
152    ($($type:ty => $decode_fn:ident);+ $(;)?) => {
153        $(
154            #[doc = concat!("Try to decode a varuint encoded ", stringify!($type))]
155            impl<'a> TryDecodeFrom<'a> for $type {
156                type Error = Error;
157
158                fn try_decode_from(bytes: &'a [u8]) -> Result<(Self, &'a [u8]), Self::Error> {
159                    decode::$decode_fn(bytes)
160                        .map_err(|source| {
161                            #[cfg(feature = "std")]
162                            { Self::Error::UnsignedVarintDecode { source } }
163                            #[cfg(not(feature = "std"))]
164                            { Self::Error::UnsignedVarintDecode { message: alloc::format!("{:?}", source) } }
165                        })
166                }
167            }
168        )+
169    };
170}
171
172/// Try to decode a varuint encoded bool
173impl<'a> TryDecodeFrom<'a> for bool {
174    type Error = Error;
175
176    fn try_decode_from(bytes: &'a [u8]) -> Result<(Self, &'a [u8]), Self::Error> {
177        let (v, ptr) = decode::u8(bytes).map_err(|source| {
178            #[cfg(feature = "std")]
179            {
180                Self::Error::UnsignedVarintDecode { source }
181            }
182            #[cfg(not(feature = "std"))]
183            {
184                Self::Error::UnsignedVarintDecode {
185                    message: alloc::format!("{:?}", source),
186                }
187            }
188        })?;
189        Ok(((v != 0), ptr))
190    }
191}
192
193// Implement TryDecodeFrom for all unsigned integer types using the macro
194impl_try_decode_from! {
195    u8 => u8;
196    u16 => u16;
197    u32 => u32;
198    u64 => u64;
199    u128 => u128;
200    usize => usize;
201}
202
203/// Decode a fixed-length byte array (reads N bytes; used for BLS share identifiers).
204impl<'a, const N: usize> TryDecodeFrom<'a> for [u8; N] {
205    type Error = Error;
206
207    fn try_decode_from(bytes: &'a [u8]) -> Result<([u8; N], &'a [u8]), Self::Error> {
208        if bytes.len() < N {
209            return Err(Error::InsufficientData {
210                expected: N,
211                actual: bytes.len(),
212            });
213        }
214        let (head, rest) = bytes.split_at(N);
215        let arr = <[u8; N]>::try_from(head).map_err(|_| Error::InsufficientData {
216            expected: N,
217            actual: bytes.len(),
218        })?;
219        Ok((arr, rest))
220    }
221}