std_mel/data/string_map/
mod.rs1use melodium_core::{executive::*, *};
2use melodium_macro::{check, mel_data, mel_function, mel_treatment};
3use std::collections::HashMap;
4use std::sync::Arc;
5
6pub mod block;
7
8#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
9#[mel_data(traits(Serialize Deserialize PartialEquality Equality))]
15pub struct StringMap {
16 pub map: HashMap<String, String>,
17}
18
19impl StringMap {
20 pub fn new() -> Self {
21 Self {
22 map: HashMap::new(),
23 }
24 }
25
26 pub fn new_with(map: HashMap<String, String>) -> Self {
27 Self { map }
28 }
29}
30
31impl Display for StringMap {
32 fn display(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> {
33 write!(f, "{:#?}", self)
34 }
35}
36
37#[mel_function]
42pub fn map(entries: Vec<StringMap>) -> StringMap {
43 let mut map = HashMap::new();
44 for submap in entries {
45 map.extend(submap.map);
46 }
47 StringMap { map }
48}
49
50#[mel_function]
54pub fn entry(key: string, value: string) -> StringMap {
55 let mut map = HashMap::new();
56 map.insert(key, value);
57 StringMap { map }
58}
59
60#[mel_treatment(
62 input value Stream<string>
63 output map Stream<StringMap>
64)]
65pub async fn entry(key: string) {
66 while let Ok(value) = value.recv_one_as::<String>().await {
67 let mut new_map = HashMap::new();
68 new_map.insert(key.clone(), value);
69 let new_map = StringMap { map: new_map };
70 check!(map.send_one(Value::Data(Arc::new(new_map))).await)
71 }
72}
73
74#[mel_function]
76pub fn get(map: StringMap, key: string) -> Option<string> {
77 map.map.get(&key).cloned()
78}
79
80#[mel_treatment(
82 input map Stream<StringMap>
83 output value Stream<Option<string>>
84)]
85pub async fn get(key: string) {
86 while let Ok(map) = map.recv_one_as::<Arc<StringMap>>().await {
87 check!(value.send_one_as(map.map.get(&key).cloned()).await)
88 }
89}
90
91#[mel_function]
93pub fn insert(mut map: StringMap, key: string, value: string) -> StringMap {
94 map.map.insert(key, value);
95 map
96}
97
98#[mel_treatment(
100 input base Stream<StringMap>
101 input value Stream<string>
102 output map Stream<StringMap>
103)]
104pub async fn insert(key: string) {
105 while let (Ok(base), Ok(value)) = (
106 base.recv_one_as::<Arc<StringMap>>().await,
107 value.recv_one_as::<String>().await,
108 ) {
109 let mut new_map = Arc::unwrap_or_clone(base);
110 new_map.map.insert(key.clone(), value);
111 check!(map.send_one(Value::Data(Arc::new(new_map))).await)
112 }
113}