logic_mesh/blocks/math/
odd.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, Value};
12
13use crate::{blocks::InputImpl, blocks::OutputImpl};
14
15/// Outputs true if the input value is odd.
16#[block]
17#[derive(BlockProps, Debug)]
18#[dis = "Odd"]
19#[category = "math"]
20pub struct Odd {
21    #[input(name = "in", kind = "Number")]
22    pub input: InputImpl,
23    #[output(kind = "Bool")]
24    pub out: OutputImpl,
25}
26
27impl Block for Odd {
28    async fn execute(&mut self) {
29        self.read_inputs_until_ready().await;
30
31        if let Some(Value::Number(a)) = self.input.get_value() {
32            let is_odd = a.value % 2.0 != 0.0;
33            self.out.set(is_odd.into());
34        }
35    }
36}
37
38#[cfg(test)]
39mod test {
40
41    use std::assert_matches::assert_matches;
42
43    use libhaystack::val::{Bool, Value};
44
45    use crate::{
46        base::block::test_utils::write_block_inputs, base::block::Block, blocks::math::Odd,
47    };
48
49    #[tokio::test]
50    async fn test_odd_block() {
51        let mut block = Odd::new();
52
53        write_block_inputs(&mut [(&mut block.input, 8.into())]).await;
54        block.execute().await;
55
56        assert_matches!(
57            block.out.value,
58            Value::Bool(Bool { value, .. }) if value == false
59        );
60
61        write_block_inputs(&mut [(&mut block.input, 9.into())]).await;
62        block.execute().await;
63
64        assert_matches!(
65            block.out.value,
66            Value::Bool(Bool { value, .. }) if value
67        );
68    }
69}