lim_bit_vec/
lib.rs

1#![no_std]
2use list_fn::{Empty, FlatScanFn, Id, ListFn, ListSome, ListState};
3use uints::UInt;
4
5// LSB first bit vector.
6#[derive(Clone, Copy, Debug, PartialEq, Default)]
7pub struct BitVec<T: UInt> {
8    pub array: T,
9    pub size: u8,
10}
11
12impl<T: UInt> BitVec<T> {
13    pub fn new_full(array: T) -> Self {
14        Self::new(array, T::BITS)
15    }
16    pub fn new(array: T, size: u8) -> Self {
17        BitVec { array, size }
18    }
19    pub fn concat(self, v: Self) -> Self {
20        BitVec {
21            array: self.array | (v.array << self.size),
22            size: self.size + v.size,
23        }
24    }
25}
26
27impl<T: UInt> ListFn for BitVec<T> {
28    type Item = bool;
29    type End = ();
30    fn next(self) -> ListState<Self> {
31        match self.size {
32            0 => ListState::End(()),
33            size => ListState::Some(ListSome {
34                first: self.array & T::ONE != T::ZERO,
35                next: BitVec::new(self.array >> 1, size - 1),
36            }),
37        }
38    }
39}
40
41pub const fn bit_vec16_new(array: u16, size: u8) -> BitVec16 {
42    BitVec16 { array, size }
43}
44
45pub type BitVec64 = BitVec<u64>;
46
47pub type BitVec32 = BitVec<u32>;
48
49pub type BitVec16 = BitVec<u16>;
50
51#[derive(Default)]
52pub struct ByteList(BitVec32);
53
54impl ListFn for ByteList {
55    type Item = u8;
56    type End = ByteList;
57    fn next(self) -> ListState<Self> {
58        if self.0.size < 8 {
59            ListState::End(self)
60        } else {
61            ListState::Some(ListSome {
62                first: self.0.array as u8,
63                next: ByteList(BitVec::new(self.0.array >> 8, self.0.size - 8)),
64            })
65        }
66    }
67}
68
69impl FlatScanFn for ByteList {
70    type InputItem = BitVec16;
71    type InputResult = ();
72    type OutputList = Self;
73    type EndList = Empty<u8, Id<BitVec32>>;
74    fn map_item(self, item: BitVec16) -> Self::OutputList {
75        ByteList(self.0.concat(BitVec32::new(item.array as u32, item.size)))
76    }
77    fn map_result(self, _: ()) -> Self::EndList {
78        Empty::new(Id::new(self.0))
79    }
80}