114 lines
2.5 KiB
Rust
114 lines
2.5 KiB
Rust
use num::traits::Num;
|
|
use std::iter::FromIterator;
|
|
|
|
pub struct Multiply<'a, NumType>
|
|
where
|
|
NumType: Num + Copy,
|
|
{
|
|
iterator_a: Box<dyn Iterator<Item = NumType> + 'a>,
|
|
iterator_b: Box<dyn Iterator<Item = NumType> + 'a>,
|
|
}
|
|
|
|
impl<'a, NumType> Multiply<'a, NumType>
|
|
where
|
|
NumType: Num + Copy,
|
|
{
|
|
pub fn from<I>(iterator_a: I, iterator_b: I) -> Multiply<'a, NumType>
|
|
where
|
|
I: Iterator<Item = NumType> + 'a,
|
|
{
|
|
Multiply {
|
|
iterator_a: Box::new(iterator_a),
|
|
iterator_b: Box::new(iterator_b),
|
|
}
|
|
}
|
|
}
|
|
|
|
impl<'a, NumType> Iterator for Multiply<'a, NumType>
|
|
where
|
|
NumType: Num + Copy,
|
|
{
|
|
type Item = NumType;
|
|
|
|
fn next(&mut self) -> Option<Self::Item> {
|
|
let value_a = match self.iterator_a.next() {
|
|
Some(a) => a,
|
|
None => return None,
|
|
};
|
|
|
|
let value_b = match self.iterator_b.next() {
|
|
Some(b) => b,
|
|
None => return None,
|
|
};
|
|
|
|
Some(value_a * value_b)
|
|
}
|
|
}
|
|
|
|
pub struct MultiplyConst<'a, NumType>
|
|
where
|
|
NumType: Num + Copy,
|
|
{
|
|
factor: NumType,
|
|
iterator: Box<dyn Iterator<Item = NumType> + 'a>,
|
|
}
|
|
|
|
impl<'a, NumType> MultiplyConst<'a, NumType>
|
|
where
|
|
NumType: Num + Copy,
|
|
{
|
|
pub fn from<I>(iterator: I, factor: NumType) -> MultiplyConst<'a, NumType>
|
|
where
|
|
I: Iterator<Item = NumType> + 'a,
|
|
{
|
|
MultiplyConst {
|
|
factor: factor,
|
|
iterator: Box::new(iterator),
|
|
}
|
|
}
|
|
}
|
|
|
|
impl<'a, NumType> Iterator for MultiplyConst<'a, NumType>
|
|
where
|
|
NumType: Num + Copy,
|
|
{
|
|
type Item = NumType;
|
|
|
|
fn next(&mut self) -> Option<Self::Item> {
|
|
let value = match self.iterator.next() {
|
|
Some(x) => x,
|
|
None => return None,
|
|
};
|
|
|
|
return Some(value * self.factor);
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn multiply_test() {
|
|
let test_a = vec![1_f32, 2_f32, 3_f32];
|
|
let test_b = vec![4_f32, 5_f32, 6_f32, 7_f32];
|
|
|
|
let result = Multiply::from(test_a.into_iter(), test_b.into_iter());
|
|
|
|
let result_data = Vec::from_iter(result);
|
|
assert_eq!(result_data.len(), 3);
|
|
assert_eq!(result_data, [4_f32, 10_f32, 18_f32]);
|
|
}
|
|
|
|
#[test]
|
|
fn multiplyconst_test() {
|
|
let test_a = vec![1_f32, 2_f32, 3_f32];
|
|
|
|
let result = MultiplyConst::from(test_a.into_iter(), 5_f32);
|
|
|
|
let result_data = Vec::from_iter(result);
|
|
assert_eq!(result_data.len(), 3);
|
|
assert_eq!(result_data, [5_f32, 10_f32, 15_f32]);
|
|
}
|
|
}
|