Skip to main content

file_storage/util/
headers.rs

1use std::cmp::Ordering;
2use std::hash::{Hash, Hasher};
3
4/// A set of HTTP headers.
5///
6/// # Names
7/// - Names ignore letter case, like in HTTP. Each keeps the case it was added with.
8/// - A set holds one header per name. Adding a name again replaces the header and its case.
9/// - Names and values are not checked. R2 may reject an invalid one when the file is written.
10///
11/// # Cloudflare R2
12/// - `Content-Type`, `Cache-Control`, `Content-Encoding`, `Content-Disposition` and
13///   `Content-Language` become the object's own headers.
14/// - Any other header is stored as custom metadata. R2 receives it as `x-amz-meta-{name}`.
15#[must_use]
16#[derive(Clone, Debug, Default)]
17pub struct Headers {
18    /// The headers sorted by name. Names are compared ignoring case and appear once.
19    entries: Vec<(String, String)>,
20}
21
22impl Headers {
23    //! Names
24
25    /// Compares the header names, ignoring letter case.
26    fn cmp_names(&self, a: &str, b: &str) -> Ordering {
27        let a = a.bytes().map(|byte| byte.to_ascii_lowercase());
28        let b = b.bytes().map(|byte| byte.to_ascii_lowercase());
29        a.cmp(b)
30    }
31}
32
33impl Headers {
34    //! Construction
35
36    /// Creates an empty set of headers.
37    pub fn new() -> Self {
38        Self::default()
39    }
40}
41
42impl Ord for Headers {
43    fn cmp(&self, other: &Self) -> Ordering {
44        for ((a, x), (b, y)) in self.iter().zip(other.iter()) {
45            let order: Ordering = self.cmp_names(a, b).then_with(|| x.cmp(y));
46            if order.is_ne() {
47                return order;
48            }
49        }
50        self.len().cmp(&other.len())
51    }
52}
53
54impl PartialOrd for Headers {
55    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
56        Some(self.cmp(other))
57    }
58}
59
60impl Eq for Headers {}
61
62impl PartialEq for Headers {
63    fn eq(&self, other: &Self) -> bool {
64        self.len() == other.len()
65            && self
66                .iter()
67                .zip(other.iter())
68                .all(|((a, x), (b, y))| a.eq_ignore_ascii_case(b) && x == y)
69    }
70}
71
72impl Hash for Headers {
73    fn hash<H: Hasher>(&self, state: &mut H) {
74        self.len().hash(state);
75        for (name, value) in self.iter() {
76            name.to_ascii_lowercase().hash(state);
77            value.hash(state);
78        }
79    }
80}
81
82impl Headers {
83    //! Properties
84
85    /// Checks if there are no headers.
86    pub fn is_empty(&self) -> bool {
87        self.entries.is_empty()
88    }
89
90    /// Gets the number of headers.
91    pub fn len(&self) -> usize {
92        self.entries.len()
93    }
94
95    /// Gets the value of the header with the `name`. (case-insensitive)
96    pub fn get(&self, name: &str) -> Option<&str> {
97        self.entries
98            .binary_search_by(|(n, _)| self.cmp_names(n, name))
99            .ok()
100            .map(|index| self.entries[index].1.as_str())
101    }
102
103    /// Iterates over the headers in order of their names.
104    pub fn iter(&self) -> impl Iterator<Item = (&str, &str)> {
105        self.entries.iter().map(|(n, v)| (n.as_str(), v.as_str()))
106    }
107}
108
109impl Headers {
110    //! Add
111
112    /// Adds the header.
113    ///
114    /// # Note
115    /// - A header with the same name, in any letter case, is replaced.
116    pub fn add_header<N, V>(&mut self, name: N, value: V)
117    where
118        N: Into<String>,
119        V: Into<String>,
120    {
121        let name: String = name.into();
122        let value: String = value.into();
123        match self
124            .entries
125            .binary_search_by(|(n, _)| self.cmp_names(n, &name))
126        {
127            Ok(index) => self.entries[index] = (name, value),
128            Err(index) => self.entries.insert(index, (name, value)),
129        }
130    }
131
132    /// Adds the header.
133    ///
134    /// # Note
135    /// - A header with the same name, in any letter case, is replaced.
136    pub fn with_header<N, V>(mut self, name: N, value: V) -> Self
137    where
138        N: Into<String>,
139        V: Into<String>,
140    {
141        self.add_header(name, value);
142        self
143    }
144}
145
146#[cfg(test)]
147mod tests {
148    use std::cmp::Ordering;
149    use std::collections::hash_map::DefaultHasher;
150    use std::hash::{Hash, Hasher};
151
152    use crate::Headers;
153
154    fn hash_of(headers: &Headers) -> u64 {
155        let mut hasher: DefaultHasher = DefaultHasher::new();
156        headers.hash(&mut hasher);
157        hasher.finish()
158    }
159
160    #[test]
161    fn empty() {
162        let headers: Headers = Headers::new();
163        assert!(headers.is_empty());
164        assert_eq!(headers.len(), 0);
165        assert_eq!(headers.get("Content-Type"), None);
166    }
167
168    #[test]
169    fn get_ignores_case() {
170        let headers: Headers = Headers::new().with_header("Content-Type", "text/plain");
171        assert_eq!(headers.get("content-type"), Some("text/plain"));
172        assert_eq!(headers.get("CONTENT-TYPE"), Some("text/plain"));
173    }
174
175    #[test]
176    fn adding_a_name_again_replaces_it() {
177        let headers: Headers = Headers::new().with_header("A", "1").with_header("a", "2");
178        let entries: Vec<(&str, &str)> = headers.iter().collect();
179        assert_eq!(entries, vec![("a", "2")]);
180    }
181
182    #[test]
183    fn iter_keeps_case_and_sorts_ignoring_case() {
184        let mut headers: Headers = Headers::new();
185        headers.add_header("B", "2");
186        headers.add_header("a", "1");
187        let entries: Vec<(&str, &str)> = headers.iter().collect();
188        assert_eq!(entries, vec![("a", "1"), ("B", "2")]);
189    }
190
191    #[test]
192    fn eq_ord_and_hash_ignore_case_and_order() {
193        let first: Headers = Headers::new().with_header("A", "1").with_header("b", "2");
194        let second: Headers = Headers::new().with_header("B", "2").with_header("a", "1");
195        assert_eq!(first, second);
196        assert_eq!(first.cmp(&second), Ordering::Equal);
197        assert_eq!(hash_of(&first), hash_of(&second));
198    }
199
200    #[test]
201    fn eq_compares_values_exactly() {
202        let first: Headers = Headers::new().with_header("A", "x");
203        let second: Headers = Headers::new().with_header("A", "X");
204        assert_ne!(first, second);
205    }
206
207    #[test]
208    fn ord_compares_names_ignoring_case_then_values_then_length() {
209        let a1: Headers = Headers::new().with_header("a", "1");
210        let a2: Headers = Headers::new().with_header("A", "2");
211        let b1: Headers = Headers::new().with_header("B", "1");
212        let a1_b1: Headers = a1.clone().with_header("b", "1");
213
214        assert!(a1 < b1);
215        assert!(a1 < a2);
216        assert!(a1 < a1_b1);
217        assert!(a1_b1 < a2);
218        assert!(Headers::new() < a1);
219    }
220}