teo_runtime/headers/
headers.rs

1use std::fmt::{Debug, Display, Formatter};
2use std::str::FromStr;
3use std::sync::{Arc, Mutex};
4use std::vec::IntoIter;
5use hyper::header::HeaderValue;
6use hyper::HeaderMap;
7use hyper::http::HeaderName;
8use teo_result::Result;
9
10#[repr(transparent)]
11#[derive(Clone)]
12pub struct Headers {
13    inner: Arc<Mutex<Inner>>
14}
15
16#[repr(transparent)]
17struct Inner {
18    map: HeaderMap<HeaderValue>,
19}
20
21impl Headers {
22
23    pub fn new() -> Self {
24        Self {
25            inner: Arc::new(Mutex::new(Inner {
26                map: HeaderMap::new()
27            }))
28        }
29    }
30
31    pub fn keys(&self) -> Vec<String> {
32        let guard = self.inner.lock().unwrap();
33        guard.map.keys().map(|k| k.to_string()).collect()
34    }
35
36    pub fn values(&self) -> Vec<String> {
37        let guard = self.inner.lock().unwrap();
38        guard.map.values().map(|v| v.to_str().unwrap().to_string()).collect()
39    }
40
41    pub fn len(&self) -> usize {
42        self.inner.lock().unwrap().map.len()
43    }
44
45    pub fn contains_key(&self, key: impl AsRef<str>) -> bool {
46        let guard = self.inner.lock().unwrap();
47        guard.map.contains_key(key.as_ref())
48    }
49
50    pub fn insert(&self, key: impl Into<String>, value: impl Into<String>) -> Result<()> {
51        let mut guard = self.inner.lock()?;
52        let value_string = value.into();
53        let header_name = HeaderName::from_str(key.into().as_str())?;
54        guard.map.insert(header_name.to_owned(), HeaderValue::from_str(value_string.as_str())?);
55        Ok(())
56    }
57
58    pub fn append(&self, key: impl Into<String>, value: impl Into<String>) -> Result<()> {
59        let mut guard = self.inner.lock()?;
60        let value_string = value.into();
61        let header_name = HeaderName::from_str(key.into().as_str())?;
62        guard.map.append(header_name.to_owned(), HeaderValue::from_str(value_string.as_str())?);
63        Ok(())
64    }
65
66    pub fn get(&self, key: impl AsRef<str>) -> Result<Option<String>> {
67        let guard = self.inner.lock()?;
68        guard.map.get(key.as_ref()).map_or(Ok(None), |s| Ok(Some(s.to_str()?.to_string())))
69    }
70
71    pub fn get_all(&self, key: impl AsRef<str>) -> Result<Vec<String>> {
72        let guard = self.inner.lock()?;
73        Ok(guard.map.get_all(key.as_ref()).iter().map(|s| Ok(s.to_str()?.to_string())).collect::<Result<Vec<String>>>()?)
74    }
75
76    pub fn remove(&self, key: impl AsRef<str>) {
77        let mut guard = self.inner.lock().unwrap();
78        guard.map.remove(key.as_ref());
79    }
80
81    pub fn clear(&self) {
82        let mut guard = self.inner.lock().unwrap();
83        guard.map.clear();
84    }
85
86    pub fn extend_to(&self, map: &mut HeaderMap<HeaderValue>) {
87        let guard = self.inner.lock().unwrap();
88        map.extend(guard.map.clone())
89    }
90
91    pub fn cloned(&self) -> Self {
92        Self {
93            inner: Arc::new(Mutex::new(Inner {
94                map: self.inner.lock().unwrap().map.clone()
95            }))
96        }
97    }
98
99    pub fn to_vec(&self) -> Vec<(String, String)> {
100        let guard = self.inner.lock().unwrap();
101        guard.map.iter().map(|(k, v)| (k.to_string(), v.to_str().unwrap().to_string())).collect()
102    }
103}
104
105impl IntoIterator for Headers {
106    type Item = (String, String);
107    type IntoIter = IntoIter<(String, String)>;
108
109    fn into_iter(self) -> Self::IntoIter {
110        self.to_vec().into_iter()
111    }
112}
113
114impl IntoIterator for &Headers {
115    type Item = (String, String);
116    type IntoIter = IntoIter<(String, String)>;
117
118    fn into_iter(self) -> Self::IntoIter {
119        self.to_vec().into_iter()
120    }
121}
122
123impl From<HeaderMap<HeaderValue>> for Headers {
124    fn from(value: HeaderMap<HeaderValue>) -> Self {
125        Self {
126            inner: Arc::new(Mutex::new(Inner {
127                map: value
128            }))
129        }
130    }
131}
132
133impl Debug for Headers {
134    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
135        let guard = self.inner.lock().unwrap();
136        let header_map = &guard.map;
137        Debug::fmt(header_map, f)
138    }
139}
140
141impl PartialEq for Headers {
142    fn eq(&self, other: &Self) -> bool {
143        let guard_self = self.inner.lock().unwrap();
144        let guard_other = other.inner.lock().unwrap();
145        let self_map = &guard_self.map;
146        let other_map = &guard_other.map;
147        self_map == other_map
148    }
149}