logic_mesh/blocks/logic/
xor.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, Bool, Value};
12
13use crate::{blocks::InputImpl, blocks::OutputImpl};
14
15/// Outputs the logical Xor value of the inputs.
16#[block]
17#[derive(BlockProps, Debug)]
18#[category = "logic"]
19pub struct Xor {
20    #[input(name = "in1", kind = "Bool")]
21    pub input1: InputImpl,
22    #[input(name = "in2", kind = "Bool")]
23    pub input2: InputImpl,
24    #[output(kind = "Bool")]
25    pub out: OutputImpl,
26}
27
28impl Block for Xor {
29    async fn execute(&mut self) {
30        self.read_inputs_until_ready().await;
31
32        if let (Some(Value::Bool(a)), Some(Value::Bool(b))) =
33            (self.input1.get_value(), self.input2.get_value())
34        {
35            self.out.set(
36                Bool {
37                    value: a.value ^ b.value,
38                }
39                .into(),
40            );
41        }
42    }
43}
44
45#[cfg(test)]
46mod test {
47
48    use crate::{
49        base::block::test_utils::write_block_inputs,
50        base::{block::Block, input::input_reader::InputReader},
51        blocks::logic::Xor,
52    };
53
54    #[tokio::test]
55    async fn test_xor_block() {
56        let mut block = Xor::new();
57
58        for _ in write_block_inputs(&mut [
59            (&mut block.input1, (true).into()),
60            (&mut block.input2, (1).into()),
61        ])
62        .await
63        {
64            block.read_inputs().await;
65        }
66
67        block.execute().await;
68        assert_eq!(block.out.value, false.into());
69    }
70}