vercel_lambda/
strmap.rs

1use std::{
2	collections::{hash_map::Keys, HashMap},
3	fmt,
4	sync::Arc,
5};
6
7use serde::de::{Deserialize, Deserializer, MapAccess, Visitor};
8
9/// A read-only view into a map of string data
10#[derive(Default, Debug, PartialEq)]
11pub struct StrMap(pub(crate) Arc<HashMap<String, String>>);
12
13impl StrMap {
14	/// Return a named value where available
15	pub fn get(&self, key: &str) -> Option<&str> {
16		self.0.get(key).map(|value| value.as_ref())
17	}
18
19	/// Return true if the underlying map is empty
20	pub fn is_empty(&self) -> bool {
21		self.0.is_empty()
22	}
23
24	/// Return an iterator over keys and values
25	pub fn iter(&self) -> StrMapIter<'_> {
26		StrMapIter {
27			data: self,
28			keys: self.0.keys(),
29		}
30	}
31}
32
33impl Clone for StrMap {
34	fn clone(&self) -> Self {
35		// only clone the inner data
36		StrMap(self.0.clone())
37	}
38}
39impl From<HashMap<String, String>> for StrMap {
40	fn from(inner: HashMap<String, String>) -> Self {
41		StrMap(Arc::new(inner))
42	}
43}
44
45/// A read only reference to `StrMap` key and value slice pairings
46pub struct StrMapIter<'a> {
47	data: &'a StrMap,
48	keys: Keys<'a, String, String>,
49}
50
51impl<'a> Iterator for StrMapIter<'a> {
52	type Item = (&'a str, &'a str);
53
54	#[inline]
55	fn next(&mut self) -> Option<(&'a str, &'a str)> {
56		self.keys
57			.next()
58			.and_then(|k| self.data.get(k).map(|v| (k.as_str(), v)))
59	}
60}
61
62impl<'de> Deserialize<'de> for StrMap {
63	fn deserialize<D>(deserializer: D) -> Result<StrMap, D::Error>
64	where
65		D: Deserializer<'de>,
66	{
67		struct StrMapVisitor;
68
69		impl<'de> Visitor<'de> for StrMapVisitor {
70			type Value = StrMap;
71
72			fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
73				write!(formatter, "a StrMap")
74			}
75
76			fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
77			where
78				A: MapAccess<'de>,
79			{
80				let mut inner = HashMap::new();
81				while let Some((key, value)) = map.next_entry()? {
82					inner.insert(key, value);
83				}
84				Ok(StrMap(Arc::new(inner)))
85			}
86		}
87
88		deserializer.deserialize_map(StrMapVisitor)
89	}
90}