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
11        .recv_many()
12        .await
13        .map(|values| TryInto::<Vec<char>>::try_into(values).unwrap())
14    {
15        check!(
16            text.send_one(chars.into_iter().collect::<String>().into())
17                .await
18        );
19    }
20}
21
22/// Convert stream of string into stream of chars.
23#[mel_treatment(
24    input text Stream<string>
25    output chars Stream<char>
26)]
27pub async fn from_string() {
28    while let Ok(text) = text
29        .recv_many()
30        .await
31        .map(|values| TryInto::<Vec<string>>::try_into(values).unwrap())
32    {
33        let mut output = Vec::new();
34        for text in text {
35            output.extend(text.chars());
36        }
37
38        check!(chars.send_many(output.into()).await);
39    }
40}
41
42/// Converts stream of chars into UTF-8 encoded stream of bytes.
43#[mel_treatment(
44    input text Stream<char>
45    output encoded Stream<byte>
46)]
47pub async fn to_utf8() {
48    while let Ok(text) = text
49        .recv_many()
50        .await
51        .map(|values| TryInto::<Vec<char>>::try_into(values).unwrap())
52    {
53        let mut output = Vec::new();
54        for text in text {
55            output.extend(text.to_string().as_bytes());
56        }
57
58        check!(
59            encoded
60                .send_many(TransmissionValue::Byte(output.into()))
61                .await
62        );
63    }
64}
65
66/// Convert char into UTF-8 encoded vector of bytes.
67#[mel_function]
68pub fn to_utf8(char: char) -> Vec<byte> {
69    char.to_string().as_bytes().into()
70}
71
72/// Converts vector of bytes into vector of char according to UTF-8 encoding.
73///
74/// If any sequence of bytes doesn't follow UTF-8 encoding, it is replaced by the `U+FFFD REPLACEMENT CHARACTER` (�).
75#[mel_function]
76pub fn from_utf8(encoded: Vec<byte>) -> Vec<char> {
77    String::from_utf8_lossy(&encoded).chars().collect()
78}