irox_tools/iterators/
chunks.rs1use crate::buf::{Buffer, FixedU8Buf};
6use irox_bits::Bits;
7
8pub struct BitsChunks<'a, const N: usize, T: Bits + 'a> {
9 inner: &'a mut T,
10 buf: FixedU8Buf<N>,
11}
12impl<'a, const N: usize, T: Bits + 'a> Iterator for BitsChunks<'a, N, T>
13where
14 &'a mut Self: 'a,
15{
16 type Item = FixedU8Buf<N>;
17
18 fn next(&mut self) -> Option<FixedU8Buf<N>> {
19 for _ in 0..N {
20 if let Some(v) = self.inner.next_u8().ok()? {
21 let _ = self.buf.push_back(v);
22 } else {
23 break;
24 }
25 }
26 if self.buf.is_empty() {
27 None
28 } else {
29 Some(core::mem::take(&mut self.buf))
30 }
31 }
32}
33
34pub trait BChunks: Bits {
35 fn chunks<const N: usize>(&'_ mut self) -> BitsChunks<'_, N, Self>
36 where
37 Self: Sized;
38}
39
40impl<T> BChunks for T
41where
42 T: Bits,
43{
44 fn chunks<const N: usize>(&'_ mut self) -> BitsChunks<'_, N, Self>
45 where
46 Self: Sized,
47 {
48 BitsChunks {
49 inner: self,
50 buf: Default::default(),
51 }
52 }
53}