Skip to main content

std_mel/data/string_map/
mod.rs

1use 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/// A `string`→`string` map; serialisable and equatable.
10///
11/// Commonly used for environment variables and HTTP headers.
12/// Supports `entry`, `get`, `insert`, and `merge` operations.
13/// Later entries with the same key overwrite earlier ones.
14#[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/// Build a `StringMap` by merging a list of single-entry maps.
38///
39/// Each element in `entries` should be produced by `|entry(key, value)`.
40/// Later entries with the same key overwrite earlier ones.
41#[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/// Build a single-entry `StringMap` mapping `key` to `value`.
51///
52/// Typically used as an argument to `|map([...])` to construct multi-entry maps.
53#[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/// For every `value` received on the stream, produce a single-entry `StringMap` with `key` → `value` and emit it on `map`.
61#[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/// Look up `key` in `map` and return its value, or `none` if the key is absent.
75#[mel_function]
76pub fn get(map: StringMap, key: string) -> Option<string> {
77    map.map.get(&key).cloned()
78}
79
80/// For every `map` received on the stream, look up `key` and emit the result as `Option<string>` on `value`.
81#[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/// Return a copy of `map` with `key` set to `value`, overwriting any existing entry for that key.
92#[mel_function]
93pub fn insert(mut map: StringMap, key: string, value: string) -> StringMap {
94    map.map.insert(key, value);
95    map
96}
97
98/// For every (`base`, `value`) pair received from the two streams, insert `key` → `value` into a copy of `base` and emit it on `map`.
99#[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}