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