logic_mesh/blocks/string/
concat.rs

1// Copyright (c) 2022-2024, 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 the concatenated value of all the input strings.
16#[block]
17#[derive(BlockProps, Debug)]
18#[dis = "Concat"]
19#[category = "string"]
20#[input(kind = "Str", count = 16)]
21pub struct Concat {
22    #[output(kind = "Str")]
23    pub out: OutputImpl,
24}
25
26impl Block for Concat {
27    async fn execute(&mut self) {
28        self.read_inputs_until_ready().await;
29
30        let result = self
31            .inputs()
32            .iter()
33            .filter_map(|input| match input.get_value() {
34                Some(Value::Str(val)) => Some(val.value.clone()),
35                _ => None,
36            })
37            .reduce(|mut acc, val| {
38                acc.push_str(&val);
39                acc
40            });
41
42        if let Some(result) = result {
43            self.out.set(result.as_str().into())
44        }
45    }
46}
47
48#[cfg(test)]
49mod test {
50
51    use std::assert_matches::assert_matches;
52
53    use libhaystack::val::{Str, Value};
54
55    use crate::{
56        base::block::test_utils::write_block_inputs,
57        base::{
58            block::{Block, BlockProps},
59            input::input_reader::InputReader,
60        },
61        blocks::string::Concat,
62    };
63
64    #[tokio::test]
65    async fn test_concat() {
66        let mut block = Concat::new();
67
68        write_block_inputs(&mut [(block.inputs_mut()[0], "first ".into())]).await;
69        write_block_inputs(&mut [(block.inputs_mut()[1], "last".into())]).await;
70        block.read_inputs().await;
71
72        block.execute().await;
73
74        assert_matches!(
75            block.out.value,
76            Value::Str(Str { value}) if value == "first last"
77        );
78    }
79}