Skip to main content

le_stream/
consume.rs

1use crate::{FromLeStream, Result};
2
3/// Convenience trait for decoding a value from a byte iterator.
4pub trait Consume<T> {
5    /// Consumes the complete iterator to decode a value of `T`.
6    ///
7    /// # Errors
8    ///
9    /// Returns an [`Error`](crate::Error) if the stream terminates prematurely
10    /// or contains excess bytes after the decoded value.
11    fn consume(self) -> Result<T>;
12
13    /// Decodes one value from the iterator and allows trailing bytes.
14    ///
15    /// Returns [`None`] when the iterator does not contain enough bytes for a
16    /// complete value.
17    fn consume_partial(self) -> Option<T>;
18}
19
20impl<T, I> Consume<T> for I
21where
22    T: FromLeStream,
23    I: Iterator<Item = u8>,
24{
25    fn consume(self) -> Result<T> {
26        T::from_le_stream_exact(self)
27    }
28
29    fn consume_partial(self) -> Option<T> {
30        T::from_le_stream(self)
31    }
32}