rusty-dsp/src/fillers.rs

70 lines
1.7 KiB
Rust

use num::traits::Num;
use super::error::DspError;
pub struct ConstFiller<'a, NumType>
where
NumType: Num + Copy,
{
value: NumType,
iterator: Box<dyn Iterator<Item = Result<NumType, DspError>> + 'a>,
}
impl<'a, NumType> ConstFiller<'a, NumType>
where
NumType: Num + Copy,
{
pub fn from<I>(iterator: I, value: NumType) -> ConstFiller<'a, NumType>
where
I: Iterator<Item = Result<NumType, DspError>> + 'a,
{
ConstFiller {
value: value,
iterator: Box::new(iterator),
}
}
}
impl<'a, NumType> Iterator for ConstFiller<'a, NumType>
where
NumType: Num + Copy,
{
type Item = Result<NumType, DspError>;
fn next(&mut self) -> Option<Self::Item> {
match self.iterator.next() {
Some(Ok(x)) => Some(Ok(x)),
Some(Err(DspError::WouldBlock)) => Some(Ok(self.value)),
Some(Err(e)) => Some(Err(e)),
None => None,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn const_filler_test() {
let test = vec![
Ok(4_f32),
Err(DspError::WouldBlock),
Ok(5_f32),
Err(DspError::WouldBlock),
Ok(6_f32),
Ok(7_f32),
];
let mut filler = ConstFiller::from(test.into_iter(), 23_f32);
assert_eq!(filler.next(), Some(Ok(4_f32)));
assert_eq!(filler.next(), Some(Ok(23_f32)));
assert_eq!(filler.next(), Some(Ok(5_f32)));
assert_eq!(filler.next(), Some(Ok(23_f32)));
assert_eq!(filler.next(), Some(Ok(6_f32)));
assert_eq!(filler.next(), Some(Ok(7_f32)));
assert_eq!(filler.next(), None);
}
}