hydro2_basic_operators/
add_op.rs

1// ---------------- [ File: src/add_op.rs ]
2crate::ix!();
3
4#[derive(NamedItem,Operator,Debug)]
5#[operator(
6    execute="add", 
7    opcode="BasicOpCode::AddOp", 
8    input0="i32", 
9    output0="i32"
10)]
11pub struct AddOp {
12    name:   String,
13    addend: i32,
14}
15
16impl AddOp {
17    pub fn new(a: i32) -> Self {
18        let name = format!("AddOp(+{})", a);
19        Self { addend: a, name }
20
21
22    }
23    async fn add(&self, input0: &i32) -> NetResult<i32> {
24        info!("OPERATOR running AddOp with addend: {}", self.addend);
25        Ok(*input0 + self.addend)
26    }
27}
28
29#[cfg(test)]
30mod add_op_tests {
31
32    use super::*;
33
34    #[tokio::test]
35    async fn test_add_op_simple() -> Result<(), NetworkError> {
36        let add = AddOp::new(100);
37        let input = [
38            Some(&AddOpIO::Input0(42)),
39            None,
40            None,
41            None,
42        ];
43        let mut out = [None, None, None, None];
44
45        add.execute(input, &mut out).await?;
46        assert_eq!(out[0], Some(AddOpIO::Output0(142)));
47        Ok(())
48    }
49
50    #[tokio::test]
51    async fn test_add_op_negative() -> Result<(), NetworkError> {
52        let add = AddOp::new(-20);
53        let input = [Some(&AddOpIO::Input0(100)), None, None, None];
54        let mut out = [None,None,None,None];
55        add.execute(input, &mut out).await?;
56        assert_eq!(out[0], Some(AddOpIO::Output0(80)));
57        Ok(())
58    }
59
60    #[tokio::test]
61    async fn test_add_op_multiple_calls() -> Result<(), NetworkError> {
62        let add = AddOp::new(5);
63        for x in [0_i32, 10, 100, -10] {
64
65
66            let i0 = AddOpIO::Input0(x);
67            let input = [Some(&i0), None, None, None];
68            let mut out = [None,None,None,None];
69            add.execute(input, &mut out).await?;
70            assert_eq!(out[0], Some(AddOpIO::Output0(x+5)));
71        }
72        Ok(())
73    }
74}