sac-base 0.0.7

Base crate of the sac-signal and sac-control crates
Documentation
use crate::network::node::Node;
use core::ops;
use alloc::boxed::Box;
use core::any::Any;
use crate::helper::iter::iter_n_inputs;

/// Multiplies two or more inputs.
pub struct Multiply {}

impl Multiply {

    /// Generate a new mutliplication operation
    ///
    /// ## Example
    /// ```rust
    /// use sac_base::operations::math::multiply::Multiply;
    /// let mut mul = Multiply::new();
    /// let mut vec = Vec::new();
    /// vec.push(&[2.0][..]);
    /// vec.push(&[4.0][..]);
    /// vec.push(&[0.5][..]);
    /// mul.process((vec, 1));
    /// assert_eq!(mul.poll(), &[4.0][..]);
    /// ```
    pub fn new<T>() -> Node<T>
        where T: Copy + ops::Div<Output=T> + ops::Mul<Output=T> + Default
    {
        let storage = Box::new(0) as Box<dyn Any>;
        Node::new(storage, |data_input, _input, output| {
            iter_n_inputs(data_input, output, |left: T, right: T| {
                return left * right;
            })
        })
    }
}

#[cfg(test)]
mod tests {

    use super::*;
    use alloc::vec::Vec;

    #[test]
    fn test_mul() {

        let mut inputs = Vec::new();
        inputs.push(&[1.0][..]);
        inputs.push(&[2.0][..]);

        let mut mul = Multiply::new();
        mul.process((inputs, 1));

        assert_eq!(mul.poll(), &[2.0][..]);
    }

    #[test]
    fn test_multiple() {

        let mut inputs = Vec::new();
        inputs.push(&[1.0][..]);
        inputs.push(&[2.0][..]);
        inputs.push(&[2.0][..]);

        let mut mul = Multiply::new();
        mul.process((inputs, 1));

        assert_eq!(mul.poll(), &[4.0][..]);
    }

    #[test]
    fn test_long_slice() {

        let mut inputs = Vec::new();
        inputs.push(&[1.0, 5.0, 3.0][..]);
        inputs.push(&[2.0, 2.0][..]);
        inputs.push(&[2.0, 1.0][..]);

        let mut mul = Multiply::new();
        mul.process((inputs, 3));

        assert_eq!(mul.poll(), &[4.0, 10.0, 0.0][..]);
    }

    #[test]
    fn test_multiple_runs() {

        let mut inputs = Vec::new();
        inputs.push(&[1.0][..]);
        inputs.push(&[1.0][..]);

        let mut mul = Multiply::new();
        mul.process((inputs, 1));


        let mut inputs = Vec::new();
        inputs.push(&[2.0][..]);
        inputs.push(&[4.0][..]);
        mul.process((inputs, 1));

        assert_eq!(mul.poll(), &[8.0][..]);
    }
}