1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
//! Core reusable types related to interacting with/using [NATS][nats]
//!
//! [nats]: https://nats.io

use async_nats::HeaderMap;
use std::collections::HashMap;

/// Convert a [`async_nats::HeaderMap`] to a [`HashMap`] used in trace contexts
#[must_use]
pub fn convert_header_map_to_hashmap(map: &HeaderMap) -> HashMap<String, String> {
    map.iter()
        .flat_map(|(key, value)| {
            value
                .iter()
                .map(|v| (key.to_string(), v.to_string()))
                .collect::<Vec<_>>()
        })
        .collect::<HashMap<String, String>>()
}

#[cfg(test)]
mod tests {
    use std::collections::HashMap;

    use super::convert_header_map_to_hashmap;
    use anyhow::Result;
    use async_nats::HeaderMap;

    /// Ensure that hashmaps only take the last valid header value
    #[test]
    fn test_duplicates() -> Result<()> {
        let mut map = HeaderMap::new();
        map.insert("a", "a");
        map.insert("a", "b");
        map.insert("b", "c");

        assert_eq!(
            convert_header_map_to_hashmap(&map),
            HashMap::from([("a".into(), "b".into()), ("b".into(), "c".into()),]),
        );
        Ok(())
    }
}