le_stream/from_le_stream.rs
1use crate::{Error, Result};
2
3mod alloc;
4mod bytes;
5mod core;
6mod heapless;
7mod intx;
8mod macaddr;
9
10/// Parses a value from a stream of little-endian bytes.
11///
12/// Implementations read exactly the bytes required to construct `Self` and
13/// leave any remaining bytes in the input iterator. Use
14/// [`from_le_stream_exact`](Self::from_le_stream_exact) when trailing bytes
15/// should be treated as an error.
16pub trait FromLeStream: Sized {
17 /// Parses a value from the front of a little-endian byte stream.
18 ///
19 /// The method returns [`None`] when the stream ends before a complete value
20 /// can be decoded. Implementations may leave unread bytes in `bytes` after
21 /// successfully decoding one value.
22 ///
23 /// # Examples
24 ///
25 /// ```
26 /// use le_stream::FromLeStream;
27 ///
28 /// let mut bytes = [0x34, 0x12, 0xFF].into_iter();
29 ///
30 /// assert_eq!(u16::from_le_stream(&mut bytes), Some(0x1234));
31 /// assert_eq!(bytes.next(), Some(0xFF));
32 /// ```
33 fn from_le_stream<T>(bytes: T) -> Option<Self>
34 where
35 T: Iterator<Item = u8>;
36
37 /// Parses a value from a little-endian byte stream and requires exhaustion.
38 ///
39 /// # Errors
40 ///
41 /// Returns [`Error::UnexpectedEndOfStream`] if the stream ends before a
42 /// complete value can be decoded, or [`Error::StreamNotExhausted`] if a
43 /// value was decoded but more bytes remain.
44 fn from_le_stream_exact<T>(mut bytes: T) -> Result<Self>
45 where
46 T: Iterator<Item = u8>,
47 {
48 let instance = Self::from_le_stream(&mut bytes).ok_or(Error::UnexpectedEndOfStream)?;
49
50 if let Some(next_byte) = bytes.next() {
51 Err(Error::StreamNotExhausted {
52 instance,
53 next_byte,
54 })
55 } else {
56 Ok(instance)
57 }
58 }
59
60 /// Parses a value from a little-endian byte slice and requires exhaustion.
61 ///
62 /// # Errors
63 ///
64 /// Returns an [`Error`] if the slice is too short or contains bytes after
65 /// the decoded value.
66 fn from_le_slice(bytes: &[u8]) -> Result<Self> {
67 Self::from_le_stream_exact(bytes.iter().copied())
68 }
69}