le_stream/from_le_stream.rs
1use crate::{Error, Result};
2
3mod core;
4mod heapless;
5mod intx;
6mod macaddr;
7mod std;
8
9/// Parse an object from a stream of bytes with little endianness.
10pub trait FromLeStream: Sized {
11 /// Parse an object from a stream of bytes with little endianness.
12 ///
13 /// # Errors
14 ///
15 /// Returns [`None`] if the stream terminates prematurely.
16 fn from_le_stream<T>(bytes: T) -> Option<Self>
17 where
18 T: Iterator<Item = u8>;
19
20 /// Parse an object from a stream of bytes with little endianness
21 /// that contains exactly the bytes to construct `Self`.
22 ///
23 /// # Errors
24 ///
25 /// Returns an [`Error`] if the stream terminates prematurely
26 /// or is not exhausted after deserializing `Self`.
27 fn from_le_stream_exact<T>(mut bytes: T) -> Result<Self>
28 where
29 T: Iterator<Item = u8>,
30 {
31 let instance = Self::from_le_stream(&mut bytes).ok_or(Error::UnexpectedEndOfStream)?;
32
33 if let Some(next_byte) = bytes.next() {
34 Err(Error::StreamNotExhausted {
35 instance,
36 next_byte,
37 })
38 } else {
39 Ok(instance)
40 }
41 }
42
43 /// Parse an object from a slice of bytes with little endianness
44 /// that contains exactly the bytes to construct `Self`.
45 ///
46 /// # Errors
47 ///
48 /// Returns an [`Error`] if the buffer is too small or contains excess data.
49 fn from_le_slice(bytes: &[u8]) -> Result<Self> {
50 Self::from_le_stream_exact(bytes.iter().copied())
51 }
52}