Skip to main content

bin_proto/
util.rs

1//! Helper functions for dealing with iterators
2
3use crate::{BitDecode, BitEncode, Error, Result};
4
5use bitstream_io::{BitRead, BitWrite, Endianness};
6use core::iter;
7#[cfg(feature = "std")]
8use std::io;
9
10#[cfg(not(feature = "std"))]
11use no_std_io2::io;
12
13/// [`BitEncode`]s an iterator of parcels to the stream.
14///
15/// Does not include a length prefix.
16pub fn encode_items<'a, W, E, Ctx, T>(
17    items: impl IntoIterator<Item = &'a T>,
18    write: &mut W,
19    ctx: &mut Ctx,
20) -> Result<()>
21where
22    W: BitWrite,
23    E: Endianness,
24    T: BitEncode<Ctx> + 'a,
25{
26    for item in items {
27        item.encode::<_, E>(write, ctx, ())?;
28    }
29    Ok(())
30}
31
32/// [`BitDecode`]s items until EOF
33pub fn decode_items_to_eof<'a, R, E, Ctx, T>(
34    read: &'a mut R,
35    ctx: &'a mut Ctx,
36) -> impl Iterator<Item = Result<T>> + use<'a, R, E, Ctx, T>
37where
38    R: BitRead,
39    E: Endianness,
40    T: BitDecode<Ctx>,
41{
42    iter::from_fn(|| match T::decode::<_, E>(read, ctx, ()) {
43        Err(Error::Io(e)) if e.kind() == io::ErrorKind::UnexpectedEof => None,
44        other => Some(other),
45    })
46}