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
25    #[tokio::test]
26    async fn test_split_string() {
27        use async_flow::{Port, bounded};
28
29        let (mut in_tx, in_rx) = bounded(1);
30        let (out_tx, mut out_rx) = bounded(10);
31
32        let splitter = tokio::spawn(split_string(",", in_rx, out_tx));
33
34        for input in ["hello,world", "foo,bar,baz", "qux"] {
35            in_tx.send(input.into()).await.unwrap();
36        }
37        in_tx.close();
38
39        let _ = tokio::join!(splitter);
40
41        let outputs = out_rx.recv_all().await.unwrap();
42        assert_eq!(
43            outputs,
44            alloc::vec!["hello", "world", "foo", "bar", "baz", "qux"]
45        );
46    }
47}