wasmcloud_core/
nats.rs

1//! Core reusable types related to interacting with/using [NATS][nats]
2//!
3//! [nats]: https://nats.io
4
5use async_nats::HeaderMap;
6use std::collections::HashMap;
7
8/// Convert a [`async_nats::HeaderMap`] to a [`HashMap`] used in trace contexts
9#[must_use]
10pub fn convert_header_map_to_hashmap(map: &HeaderMap) -> HashMap<String, String> {
11    map.iter()
12        .flat_map(|(key, value)| {
13            value
14                .iter()
15                .map(|v| (key.to_string(), v.to_string()))
16                .collect::<Vec<_>>()
17        })
18        .collect::<HashMap<String, String>>()
19}
20
21#[cfg(test)]
22mod tests {
23    use std::collections::HashMap;
24
25    use super::convert_header_map_to_hashmap;
26    use anyhow::Result;
27    use async_nats::HeaderMap;
28
29    /// Ensure that hashmaps only take the last valid header value
30    #[test]
31    fn test_duplicates() -> Result<()> {
32        let mut map = HeaderMap::new();
33        map.insert("a", "a");
34        map.insert("a", "b");
35        map.insert("b", "c");
36
37        assert_eq!(
38            convert_header_map_to_hashmap(&map),
39            HashMap::from([("a".into(), "b".into()), ("b".into(), "c".into()),]),
40        );
41        Ok(())
42    }
43}