65 lines
1.6 KiB
Rust
65 lines
1.6 KiB
Rust
extern crate rusty_dsp;
|
|
|
|
use rusty_dsp::error::DspError;
|
|
|
|
pub struct BitGenerator<'a> {
|
|
bit_pos: usize,
|
|
current_byte: u8,
|
|
iterator: Box<dyn Iterator<Item = Result<u8, DspError>> + 'a>,
|
|
}
|
|
|
|
impl<'a> BitGenerator<'a> {
|
|
pub fn from<I>(iterator: I) -> BitGenerator<'a>
|
|
where
|
|
I: Iterator<Item = Result<u8, DspError>> + 'a,
|
|
{
|
|
BitGenerator {
|
|
bit_pos: 0,
|
|
current_byte: 0,
|
|
iterator: Box::new(iterator),
|
|
}
|
|
}
|
|
}
|
|
|
|
impl<'a> Iterator for BitGenerator<'a> {
|
|
type Item = Result<bool, DspError>;
|
|
|
|
fn next(&mut self) -> Option<Self::Item> {
|
|
if self.bit_pos == 0 {
|
|
let byte = match self.iterator.next() {
|
|
None => return None,
|
|
Some(Err(e)) => return Some(Err(e)),
|
|
Some(Ok(b)) => b,
|
|
};
|
|
|
|
self.current_byte = 0b11000000 | (byte << 1);
|
|
};
|
|
|
|
let bit = (self.current_byte & (1 << self.bit_pos)) != 0;
|
|
self.bit_pos = (self.bit_pos + 1) % 8;
|
|
|
|
Some(Ok(bit))
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn test_bitgenerator() {
|
|
let input = vec![0b11111, 0b01010, 0b00000];
|
|
|
|
let generator = BitGenerator::from(input.into_iter().map(|x| Ok(x)));
|
|
|
|
let result_data: Result<Vec<bool>, DspError> = generator.collect();
|
|
assert_eq!(
|
|
result_data,
|
|
Ok(vec![
|
|
true, true, true, true, true, true, true, true, true, false, true, false, true,
|
|
false, true, true, true, false, false, false, false, false, true, true
|
|
])
|
|
);
|
|
}
|
|
}
|