logic_mesh/blocks/string/
replace.rs1use 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, Str, Value};
12
13use crate::{blocks::InputImpl, blocks::OutputImpl};
14
15#[block]
17#[derive(BlockProps, Debug)]
18#[dis = "Replace"]
19#[category = "string"]
20pub struct Replace {
21 #[input(name = "in", kind = "Str")]
22 pub input: InputImpl,
23 #[input(kind = "Str")]
24 pub find: InputImpl,
25 #[input(kind = "Str")]
26 pub replace: InputImpl,
27 #[output(kind = "Str")]
28 pub out: OutputImpl,
29}
30
31impl Block for Replace {
32 async fn execute(&mut self) {
33 self.read_inputs_until_ready().await;
34
35 if let (Some(Value::Str(input)), Some(Value::Str(find)), Some(Value::Str(replace))) = (
36 self.input.get_value(),
37 self.find.get_value(),
38 self.replace.get_value(),
39 ) {
40 self.out.set(
41 Str {
42 value: input
43 .value
44 .replace(find.value.as_str(), replace.value.as_str()),
45 }
46 .into(),
47 );
48 }
49 }
50}
51
52#[cfg(test)]
53mod test {
54
55 use std::assert_matches::assert_matches;
56
57 use libhaystack::val::{Str, Value};
58
59 use crate::{
60 base::block::Block,
61 base::{
62 block::{test_utils::write_block_inputs, BlockProps},
63 input::input_reader::InputReader,
64 },
65 blocks::string::Replace,
66 };
67
68 #[tokio::test]
69 async fn test_replace() {
70 let mut block = Replace::new();
71
72 println!("block: {:?}", block.desc());
73
74 for _ in write_block_inputs(&mut [
75 (&mut block.input, "ana are mere".into()),
76 (&mut block.find, "ana".into()),
77 (&mut block.replace, "ile".into()),
78 ])
79 .await
80 {
81 block.read_inputs().await;
82 }
83
84 block.execute().await;
85
86 assert_matches!(
87 block.out.value,
88 Value::Str(Str { value, .. }) if value == "ile are mere"
89 );
90 }
91}