flows_text/
split.rs

1// This is free and unencumbered software released into the public domain.
2
3use alloc::string::String;
4use async_flow::{Inputs, Outputs, Result};
5
6/// A block that splits input strings based on a delimiter.
7pub async fn split_string(
8    delimiter: impl AsRef<str>,
9    mut inputs: Inputs<String>,
10    outputs: Outputs<String>,
11) -> Result {
12    let delimiter = delimiter.as_ref();
13    while let Some(input) = inputs.recv().await? {
14        for output in input.split(&delimiter) {
15            outputs.send(output.into()).await?;
16        }
17    }
18    Ok(())
19}
20
21#[cfg(test)]
22mod tests {
23    use super::*;
24    use alloc::boxed::Box;
25    use async_flow::{Channel, InputPort};
26    use core::error::Error;
27
28    #[tokio::test]
29    async fn test_split_string() -> Result<(), Box<dyn Error>> {
30        let mut in_ = Channel::bounded(1);
31        let mut out = Channel::bounded(10);
32
33        let splitter = tokio::spawn(split_string(",", in_.rx, out.tx));
34
35        for input in ["hello,world", "foo,bar,baz", "qux"] {
36            in_.tx.send(input.into()).await.unwrap();
37        }
38        in_.tx.close();
39
40        let _ = tokio::join!(splitter);
41
42        let outputs = out.rx.recv_all().await.unwrap();
43        assert_eq!(
44            outputs,
45            alloc::vec!["hello", "world", "foo", "bar", "baz", "qux"]
46        );
47
48        Ok(())
49    }
50}