Skip to main content

std_mel/text/convert/
char.rs

1use melodium_core::*;
2use melodium_macro::{check, mel_function, mel_treatment};
3
4/// Convert stream of chars into stream of strings.
5#[mel_treatment(
6    input chars Stream<char>
7    output text Stream<string>
8)]
9pub async fn to_string() {
10    while let Ok(chars) = chars.recv_many_as::<char>().await {
11        check!(
12            text.send_one_as(chars.into_iter().collect::<String>())
13                .await
14        );
15    }
16}
17
18/// Convert stream of string into stream of chars.
19#[mel_treatment(
20    input text Stream<string>
21    output chars Stream<char>
22)]
23pub async fn from_string() {
24    while let Ok(text) = text.recv_many_as::<string>().await {
25        let mut output = Vec::new();
26        for text in text {
27            output.extend(text.chars());
28        }
29
30        check!(chars.send_many_as(output).await);
31    }
32}
33
34/// Converts stream of chars into UTF-8 encoded stream of bytes.
35#[mel_treatment(
36    input text Stream<char>
37    output encoded Stream<byte>
38)]
39pub async fn to_utf8() {
40    while let Ok(text) = text.recv_many_as::<char>().await {
41        let mut output = Vec::new();
42        for text in text {
43            output.extend(text.to_string().as_bytes());
44        }
45
46        check!(
47            encoded
48                .send_many(TransmissionValue::Byte(output.into()))
49                .await
50        );
51    }
52}
53
54/// Convert char into UTF-8 encoded vector of bytes.
55#[mel_function]
56pub fn to_utf8(char: char) -> Vec<byte> {
57    char.to_string().as_bytes().into()
58}
59
60/// Converts vector of bytes into vector of char according to UTF-8 encoding.
61///
62/// If any sequence of bytes doesn't follow UTF-8 encoding, it is replaced by the `U+FFFD REPLACEMENT CHARACTER` (�).
63#[mel_function]
64pub fn from_utf8(encoded: Vec<byte>) -> Vec<char> {
65    String::from_utf8_lossy(&encoded).chars().collect()
66}