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))]
10pub struct StringMap {
11 pub map: HashMap<String, String>,
12}
13
14impl StringMap {
15 pub fn new() -> Self {
16 Self {
17 map: HashMap::new(),
18 }
19 }
20
21 pub fn new_with(map: HashMap<String, String>) -> Self {
22 Self { map }
23 }
24}
25
26impl Display for StringMap {
27 fn display(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> {
28 write!(f, "{:#?}", self)
29 }
30}
31
32#[mel_function]
34pub fn map(entries: Vec<StringMap>) -> StringMap {
35 let mut map = HashMap::new();
36 for submap in entries {
37 map.extend(submap.map);
38 }
39 StringMap { map }
40}
41
42#[mel_function]
44pub fn entry(key: string, value: string) -> StringMap {
45 let mut map = HashMap::new();
46 map.insert(key, value);
47 StringMap { map }
48}
49
50#[mel_treatment(
54 input value Stream<string>
55 output map Stream<StringMap>
56)]
57pub async fn entry(key: string) {
58 while let Ok(value) = value
59 .recv_one()
60 .await
61 .map(|val| GetData::<String>::try_data(val).unwrap())
62 {
63 let mut new_map = HashMap::new();
64 new_map.insert(key.clone(), value);
65 let new_map = StringMap { map: new_map };
66 check!(map.send_one(Value::Data(Arc::new(new_map))).await)
67 }
68}
69
70#[mel_function]
72pub fn get(map: StringMap, key: string) -> Option<string> {
73 map.map.get(&key).cloned()
74}
75
76#[mel_treatment(
80 input map Stream<StringMap>
81 output value Stream<Option<string>>
82)]
83pub async fn get(key: string) {
84 while let Ok(map) = map.recv_one().await.map(|val| {
85 GetData::<Arc<dyn Data>>::try_data(val)
86 .unwrap()
87 .downcast_arc::<StringMap>()
88 .unwrap()
89 }) {
90 check!(value.send_one(map.map.get(&key).cloned().into()).await)
91 }
92}
93
94#[mel_function]
96pub fn insert(mut map: StringMap, key: string, value: string) -> StringMap {
97 map.map.insert(key, value);
98 map
99}
100
101#[mel_treatment(
105 input base Stream<StringMap>
106 input value Stream<string>
107 output map Stream<StringMap>
108)]
109pub async fn insert(key: string) {
110 while let (Ok(base), Ok(value)) = (
111 base.recv_one().await.map(|val| {
112 GetData::<Arc<dyn Data>>::try_data(val)
113 .unwrap()
114 .downcast_arc::<StringMap>()
115 .unwrap()
116 }),
117 value
118 .recv_one()
119 .await
120 .map(|val| GetData::<String>::try_data(val).unwrap()),
121 ) {
122 let mut new_map = Arc::unwrap_or_clone(base);
123 new_map.map.insert(key.clone(), value);
124 check!(map.send_one(Value::Data(Arc::new(new_map))).await)
125 }
126}