logic_mesh/blocks/math/
abs.rs

1// Copyright (c) 2022-2023, Radu Racariu.
2
3use uuid::Uuid;
4
5use crate::base::{
6    block::{Block, BlockDesc, BlockProps, BlockState},
7    input::{input_reader::InputReader, Input, InputProps},
8    output::Output,
9};
10
11use libhaystack::val::{kind::HaystackKind, Number, Value};
12
13use crate::{blocks::InputImpl, blocks::OutputImpl};
14
15/// Outputs the absolute value of the input.
16#[block]
17#[derive(BlockProps, Debug)]
18#[category = "math"]
19pub struct Abs {
20    #[input(name = "in", kind = "Number")]
21    pub input: InputImpl,
22    #[output(kind = "Number")]
23    pub out: OutputImpl,
24}
25
26impl Block for Abs {
27    async fn execute(&mut self) {
28        self.read_inputs_until_ready().await;
29
30        if let Some(Value::Number(a)) = self.input.get_value() {
31            self.out.set(
32                Number {
33                    value: a.value.abs(),
34                    unit: a.unit,
35                }
36                .into(),
37            );
38        }
39    }
40}
41
42#[cfg(test)]
43mod test {
44
45    use crate::{
46        base::block::test_utils::write_block_inputs, base::block::Block, blocks::math::Abs,
47    };
48
49    #[tokio::test]
50    async fn test_abs_block() {
51        let mut block = Abs::new();
52
53        write_block_inputs(&mut [(&mut block.input, (-4).into())]).await;
54
55        block.execute().await;
56        assert_eq!(block.out.value, 4.into());
57    }
58}