Skip to main content

ntex_http/
map.rs

1use std::collections::{self, VecDeque, hash_map, hash_map::Entry};
2use std::fmt;
3
4use foldhash::fast::RandomState;
5
6use crate::{HeaderName, HeaderValue};
7
8type HashMap<K, V> = collections::HashMap<K, V, RandomState>;
9
10/// A value containing one of two possible types.
11#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
12pub enum Either<A, B> {
13    /// First variant.
14    Left(A),
15    /// Second variant.
16    Right(B),
17}
18
19/// A multimap of HTTP header names to values.
20///
21/// Each header name may have one or more values. Methods such as [`get`](Self::get)
22/// return the first value; use [`get_all`](Self::get_all) to iterate over every
23/// value associated with a name.
24#[derive(Clone, PartialEq, Eq)]
25pub struct HeaderMap {
26    pub(crate) inner: HashMap<HeaderName, Value>,
27}
28
29#[derive(Debug, Clone, PartialEq, Eq)]
30pub enum Value {
31    One(HeaderValue),
32    Multi(VecDeque<HeaderValue>),
33}
34
35impl Value {
36    fn get(&self) -> &HeaderValue {
37        match self {
38            Value::One(val) => val,
39            Value::Multi(val) => &val[0],
40        }
41    }
42
43    fn get_mut(&mut self) -> &mut HeaderValue {
44        match self {
45            Value::One(val) => val,
46            Value::Multi(val) => &mut val[0],
47        }
48    }
49
50    pub(crate) fn append(&mut self, val: HeaderValue) {
51        *self = match std::mem::replace(self, Value::Multi(VecDeque::new())) {
52            Value::One(prev_val) => Value::Multi(VecDeque::from([prev_val, val])),
53            Value::Multi(mut vec) => {
54                vec.push_back(val);
55                Value::Multi(vec)
56            }
57        };
58    }
59}
60
61#[derive(Debug)]
62pub struct ValueIntoIter {
63    value: Value,
64}
65
66impl Iterator for ValueIntoIter {
67    type Item = HeaderValue;
68
69    fn next(&mut self) -> Option<Self::Item> {
70        match std::mem::replace(&mut self.value, Value::Multi(VecDeque::new())) {
71            Value::One(val) => Some(val),
72            Value::Multi(mut vec) => {
73                let val = vec.pop_front();
74                self.value = Value::Multi(vec);
75                val
76            }
77        }
78    }
79
80    fn size_hint(&self) -> (usize, Option<usize>) {
81        match self.value {
82            Value::One(_) => (1, Some(1)),
83            Value::Multi(ref v) => v.iter().size_hint(),
84        }
85    }
86}
87
88impl IntoIterator for Value {
89    type Item = HeaderValue;
90    type IntoIter = ValueIntoIter;
91
92    #[inline]
93    fn into_iter(self) -> Self::IntoIter {
94        ValueIntoIter { value: self }
95    }
96}
97
98impl Extend<HeaderValue> for Value {
99    #[inline]
100    fn extend<T>(&mut self, iter: T)
101    where
102        T: IntoIterator<Item = HeaderValue>,
103    {
104        for h in iter {
105            self.append(h);
106        }
107    }
108}
109
110impl From<HeaderValue> for Value {
111    #[inline]
112    fn from(hdr: HeaderValue) -> Value {
113        Value::One(hdr)
114    }
115}
116
117impl<'a> From<&'a HeaderValue> for Value {
118    #[inline]
119    fn from(hdr: &'a HeaderValue) -> Value {
120        Value::One(hdr.clone())
121    }
122}
123
124impl Default for HeaderMap {
125    #[inline]
126    fn default() -> Self {
127        Self::new()
128    }
129}
130
131impl HeaderMap {
132    /// Creates an empty `HeaderMap`.
133    ///
134    /// The map will be created without any capacity. This function will not
135    /// allocate.
136    pub fn new() -> Self {
137        HeaderMap {
138            inner: HashMap::default(),
139        }
140    }
141
142    /// Creates an empty `HeaderMap` with the specified capacity.
143    ///
144    /// The returned map will allocate internal storage in order to hold about
145    /// `capacity` elements without reallocating. However, this is a "best
146    /// effort" as there are usage patterns that could cause additional
147    /// allocations before `capacity` headers are stored in the map.
148    ///
149    /// More capacity than requested may be allocated.
150    pub fn with_capacity(capacity: usize) -> HeaderMap {
151        HeaderMap {
152            inner: HashMap::with_capacity_and_hasher(capacity, RandomState::default()),
153        }
154    }
155
156    /// Returns the number of keys stored in the map.
157    ///
158    /// This counts distinct header names, not the total number of values.
159    pub fn len(&self) -> usize {
160        self.inner.len()
161    }
162
163    /// Returns `true` if the map contains no headers.
164    pub fn is_empty(&self) -> bool {
165        self.inner.len() == 0
166    }
167
168    /// Clears the map, removing all key-value pairs. Keeps the allocated memory
169    /// for reuse.
170    #[inline]
171    pub fn clear(&mut self) {
172        // Pooled maps are often already empty, keep that check inlined so it
173        // does not pay for the erase path's call and register spills.
174        if !self.inner.is_empty() {
175            self.clear_entries();
176        }
177    }
178
179    #[inline(never)]
180    fn clear_entries(&mut self) {
181        // `HashMap::clear` memsets every control byte. Erasing a few entries
182        // one by one is cheaper. Below 8 entries no run of 8 occupied slots
183        // can exist, so each erased slot becomes empty and capacity is kept.
184        if self.inner.len() < 8 {
185            self.inner.retain(|_, _| false);
186        } else {
187            self.inner.clear();
188        }
189    }
190
191    /// Returns the number of headers the map can hold without reallocating.
192    ///
193    /// This number is an approximation as certain usage patterns could cause
194    /// additional allocations before the returned capacity is filled.
195    pub fn capacity(&self) -> usize {
196        self.inner.capacity()
197    }
198
199    /// Reserves capacity for at least `additional` more headers to be inserted
200    /// into the `HeaderMap`.
201    ///
202    /// The header map may reserve more space to avoid frequent reallocations.
203    /// Like with `with_capacity`, this will be a "best effort" to avoid
204    /// allocations until `additional` more headers are inserted. Certain usage
205    /// patterns could cause additional allocations before the number is
206    /// reached.
207    pub fn reserve(&mut self, additional: usize) {
208        self.inner.reserve(additional);
209    }
210
211    /// Returns a reference to the value associated with the key.
212    ///
213    /// If there are multiple values associated with the key, then the first one
214    /// is returned. Use `get_all` to get all values associated with a given
215    /// key. Returns `None` if there are no values associated with the key.
216    pub fn get<N: AsName>(&self, name: N) -> Option<&HeaderValue> {
217        self.get2(name).map(Value::get)
218    }
219
220    fn get2<N: AsName>(&self, name: N) -> Option<&Value> {
221        match name.as_name() {
222            Either::Left(name) => self.inner.get(name),
223            Either::Right(s) => {
224                if let Ok(name) = HeaderName::try_from(s) {
225                    self.inner.get(&name)
226                } else {
227                    None
228                }
229            }
230        }
231    }
232
233    /// Returns a view of all values associated with a key.
234    ///
235    /// The returned view does not incur any allocations and allows iterating
236    /// the values associated with the key. The iterator is empty if there are
237    /// no values associated with the key.
238    pub fn get_all<N: AsName>(&self, name: N) -> GetAll<'_> {
239        GetAll {
240            idx: 0,
241            item: self.get2(name),
242        }
243    }
244
245    /// Returns a mutable reference to the value associated with the key.
246    ///
247    /// If there are multiple values associated with the key, then the first one
248    /// is returned. Use `get_all` to get all values associated with a given
249    /// key. Returns `None` if there are no values associated with the key.
250    pub fn get_mut<N: AsName>(&mut self, name: N) -> Option<&mut HeaderValue> {
251        match name.as_name() {
252            Either::Left(name) => self.inner.get_mut(name).map(Value::get_mut),
253            Either::Right(s) => {
254                if let Ok(name) = HeaderName::try_from(s) {
255                    self.inner.get_mut(&name).map(Value::get_mut)
256                } else {
257                    None
258                }
259            }
260        }
261    }
262
263    /// Returns `true` if the map contains a value for the specified key.
264    pub fn contains_key<N: AsName>(&self, key: N) -> bool {
265        match key.as_name() {
266            Either::Left(name) => self.inner.contains_key(name),
267            Either::Right(s) => {
268                if let Ok(name) = HeaderName::try_from(s) {
269                    self.inner.contains_key(&name)
270                } else {
271                    false
272                }
273            }
274        }
275    }
276
277    /// An iterator visiting all key-value pairs.
278    ///
279    /// The iteration order is arbitrary and may vary between maps. Each key is
280    /// yielded once per associated value.
281    pub fn iter(&self) -> Iter<'_> {
282        Iter::new(self.inner.iter())
283    }
284
285    #[doc(hidden)]
286    pub fn iter_inner(&self) -> hash_map::Iter<'_, HeaderName, Value> {
287        self.inner.iter()
288    }
289
290    /// An iterator visiting all keys.
291    ///
292    /// The iteration order is arbitrary and may vary between maps. Each key is
293    /// yielded only once, even if it has multiple associated values.
294    pub fn keys(&self) -> Keys<'_> {
295        Keys(self.inner.keys())
296    }
297
298    /// Inserts a key-value pair into the map.
299    ///
300    /// The new value replaces all values previously associated with the key.
301    ///
302    /// The key is not updated, though; this matters for types that can be `==`
303    /// without being identical.
304    pub fn insert(&mut self, key: HeaderName, val: HeaderValue) {
305        let _ = self.inner.insert(key, Value::One(val));
306    }
307
308    /// Inserts a key-value pair into the map.
309    ///
310    /// The value is appended after any values already associated with the key.
311    /// The stored key itself is not replaced when an equivalent key exists.
312    pub fn append(&mut self, key: HeaderName, value: HeaderValue) {
313        match self.inner.entry(key) {
314            Entry::Occupied(mut entry) => entry.get_mut().append(value),
315            Entry::Vacant(entry) => {
316                entry.insert(Value::One(value));
317            }
318        }
319    }
320
321    /// Removes all headers for a particular header name from the map.
322    pub fn remove<N: AsName>(&mut self, key: N) {
323        match key.as_name() {
324            Either::Left(name) => {
325                let _ = self.inner.remove(name);
326            }
327            Either::Right(s) => {
328                if let Ok(name) = HeaderName::try_from(s) {
329                    let _ = self.inner.remove(&name);
330                }
331            }
332        }
333    }
334}
335
336#[doc(hidden)]
337pub trait AsName {
338    fn as_name(&self) -> Either<&HeaderName, &str>;
339}
340
341impl AsName for HeaderName {
342    fn as_name(&self) -> Either<&HeaderName, &str> {
343        Either::Left(self)
344    }
345}
346
347impl AsName for &HeaderName {
348    fn as_name(&self) -> Either<&HeaderName, &str> {
349        Either::Left(self)
350    }
351}
352
353impl AsName for &str {
354    fn as_name(&self) -> Either<&HeaderName, &str> {
355        Either::Right(self)
356    }
357}
358
359impl AsName for String {
360    fn as_name(&self) -> Either<&HeaderName, &str> {
361        Either::Right(self.as_str())
362    }
363}
364
365impl AsName for &String {
366    fn as_name(&self) -> Either<&HeaderName, &str> {
367        Either::Right(self.as_str())
368    }
369}
370
371#[derive(Debug)]
372pub struct GetAll<'a> {
373    idx: usize,
374    item: Option<&'a Value>,
375}
376
377impl<'a> Iterator for GetAll<'a> {
378    type Item = &'a HeaderValue;
379
380    #[inline]
381    fn next(&mut self) -> Option<&'a HeaderValue> {
382        if let Some(ref val) = self.item {
383            match val {
384                Value::One(val) => {
385                    self.item.take();
386                    Some(val)
387                }
388                Value::Multi(vec) => {
389                    if self.idx < vec.len() {
390                        let item = Some(&vec[self.idx]);
391                        self.idx += 1;
392                        item
393                    } else {
394                        self.item.take();
395                        None
396                    }
397                }
398            }
399        } else {
400            None
401        }
402    }
403}
404
405#[derive(Debug)]
406pub struct Keys<'a>(hash_map::Keys<'a, HeaderName, Value>);
407
408impl<'a> Iterator for Keys<'a> {
409    type Item = &'a HeaderName;
410
411    #[inline]
412    fn next(&mut self) -> Option<&'a HeaderName> {
413        self.0.next()
414    }
415}
416
417impl<'a> IntoIterator for &'a HeaderMap {
418    type Item = (&'a HeaderName, &'a HeaderValue);
419    type IntoIter = Iter<'a>;
420
421    fn into_iter(self) -> Self::IntoIter {
422        self.iter()
423    }
424}
425
426#[derive(Debug)]
427pub struct Iter<'a> {
428    idx: usize,
429    current: Option<(&'a HeaderName, &'a VecDeque<HeaderValue>)>,
430    inner: hash_map::Iter<'a, HeaderName, Value>,
431}
432
433impl<'a> Iter<'a> {
434    fn new(inner: hash_map::Iter<'a, HeaderName, Value>) -> Self {
435        Self {
436            inner,
437            idx: 0,
438            current: None,
439        }
440    }
441}
442
443impl<'a> Iterator for Iter<'a> {
444    type Item = (&'a HeaderName, &'a HeaderValue);
445
446    #[inline]
447    fn next(&mut self) -> Option<(&'a HeaderName, &'a HeaderValue)> {
448        if let Some(ref mut item) = self.current {
449            if self.idx < item.1.len() {
450                let item = (item.0, &item.1[self.idx]);
451                self.idx += 1;
452                return Some(item);
453            }
454            self.idx = 0;
455            self.current.take();
456        }
457        if let Some(item) = self.inner.next() {
458            match item.1 {
459                Value::One(value) => Some((item.0, value)),
460                Value::Multi(vec) => {
461                    self.current = Some((item.0, vec));
462                    self.next()
463                }
464            }
465        } else {
466            None
467        }
468    }
469}
470
471impl fmt::Debug for HeaderMap {
472    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
473        let mut f = f.debug_map();
474
475        for (key, val) in &self.inner {
476            match val {
477                Value::One(val) => {
478                    let _ = f.entry(&key, &val);
479                }
480                Value::Multi(val) => {
481                    for v in val {
482                        f.entry(&key, &v);
483                    }
484                }
485            }
486        }
487        f.finish()
488    }
489}
490
491#[cfg(test)]
492mod tests {
493    use super::*;
494    use crate::header::{ACCEPT_ENCODING, CONTENT_TYPE};
495
496    /// STATEMENT: `HeaderMap` capacity, insert, lookup by every key type, `get_mut`, `keys` and
497    /// `remove` work together.
498    ///
499    /// HOW:
500    /// - Check `default` and `with_capacity` maps are empty, and `reserve` grows capacity.
501    /// - Insert `content-type`; look it up by `HeaderName`, `&str`, `String` and `&String`.
502    /// - Check `get_mut`, `Debug` and `keys`, then `remove` and expect an empty map.
503    #[test]
504    #[allow(clippy::needless_borrow, clippy::needless_borrows_for_generic_args)]
505    fn test_basics() {
506        let m = HeaderMap::default();
507        assert!(m.is_empty());
508        let mut m = HeaderMap::with_capacity(10);
509        assert!(m.is_empty());
510        assert!(m.capacity() >= 10);
511        m.reserve(20);
512        assert!(m.capacity() >= 20);
513
514        m.insert(CONTENT_TYPE, HeaderValue::from_static("text"));
515        assert!(m.contains_key(CONTENT_TYPE));
516        assert!(m.contains_key("content-type"));
517        assert!(m.contains_key("content-type".to_string()));
518        assert!(m.contains_key(&("content-type".to_string())));
519        assert_eq!(
520            *m.get_mut("content-type").unwrap(),
521            HeaderValue::from_static("text")
522        );
523        assert_eq!(
524            *m.get_mut(CONTENT_TYPE).unwrap(),
525            HeaderValue::from_static("text")
526        );
527        assert!(format!("{m:?}").contains("content-type"));
528
529        assert!(m.keys().any(|x| x == CONTENT_TYPE));
530        m.remove("content-type");
531        assert!(m.is_empty());
532    }
533
534    /// STATEMENT: `append` keeps every value for a name in insertion order, while `get` and
535    /// `get_mut` return the first one.
536    ///
537    /// HOW:
538    /// - Append `gzip`, `br` and `deflate` under `accept-encoding`.
539    /// - Expect `get_all` in that order and `get`/`get_mut` to return `gzip`.
540    /// - Remove the name; expect `get` to return `None`.
541    #[test]
542    fn test_append() {
543        let mut map = HeaderMap::new();
544
545        map.append(ACCEPT_ENCODING, HeaderValue::from_static("gzip"));
546        assert_eq!(
547            map.get_all(ACCEPT_ENCODING).collect::<Vec<_>>(),
548            vec![&HeaderValue::from_static("gzip"),]
549        );
550
551        map.append(ACCEPT_ENCODING, HeaderValue::from_static("br"));
552        map.append(ACCEPT_ENCODING, HeaderValue::from_static("deflate"));
553        assert_eq!(
554            map.get_all(ACCEPT_ENCODING).collect::<Vec<_>>(),
555            vec![
556                &HeaderValue::from_static("gzip"),
557                &HeaderValue::from_static("br"),
558                &HeaderValue::from_static("deflate"),
559            ]
560        );
561        assert_eq!(
562            map.get(ACCEPT_ENCODING),
563            Some(&HeaderValue::from_static("gzip"))
564        );
565        assert_eq!(
566            map.get_mut(ACCEPT_ENCODING),
567            Some(&mut HeaderValue::from_static("gzip"))
568        );
569
570        map.remove(ACCEPT_ENCODING);
571        assert_eq!(map.get(ACCEPT_ENCODING), None);
572    }
573
574    /// STATEMENT: `clear` empties small and large maps and keeps the full capacity, so a
575    /// reused map never loses room to stale erased slots.
576    ///
577    /// HOW:
578    /// - Repeatedly fill a `with_capacity(16)` map with 1 to 7 names, some with several
579    ///   values, and `clear` it; expect it empty and its capacity unchanged every time.
580    /// - Fill it with 12 names and `clear`; expect it empty with the same capacity.
581    /// - Insert again after clearing and expect lookups to find the new values.
582    #[test]
583    fn test_clear() {
584        let names: Vec<HeaderName> = (0..12)
585            .map(|i| HeaderName::try_from(format!("x-h{i}")).unwrap())
586            .collect();
587        let mut m = HeaderMap::with_capacity(16);
588        let cap = m.capacity();
589
590        for round in 0..1000 {
591            for name in &names[..=(round % 7)] {
592                m.append(name.clone(), HeaderValue::from_static("a"));
593                if round % 2 == 0 {
594                    m.append(name.clone(), HeaderValue::from_static("b"));
595                }
596            }
597            m.clear();
598            assert!(m.is_empty());
599            assert_eq!(m.capacity(), cap);
600        }
601
602        for name in &names {
603            m.insert(name.clone(), HeaderValue::from_static("a"));
604        }
605        m.clear();
606        assert!(m.is_empty());
607        assert_eq!(m.capacity(), cap);
608
609        m.insert(CONTENT_TYPE, HeaderValue::from_static("text"));
610        assert_eq!(m.len(), 1);
611        assert_eq!(m.get(CONTENT_TYPE), Some(&HeaderValue::from_static("text")));
612        assert!(!m.contains_key(&names[0]));
613    }
614
615    /// STATEMENT: Converting an `http::HeaderMap` keeps its headers.
616    ///
617    /// HOW:
618    /// - Build an `http::HeaderMap` with `accept-encoding: gzip` and convert it.
619    /// - Expect `get` to return `gzip`.
620    #[test]
621    fn test_from_http() {
622        let mut map = http::HeaderMap::new();
623        map.append(ACCEPT_ENCODING, http::HeaderValue::from_static("gzip"));
624
625        let map2 = HeaderMap::from(map);
626        assert_eq!(
627            map2.get(ACCEPT_ENCODING),
628            Some(&HeaderValue::from_static("gzip"))
629        );
630    }
631
632    /// STATEMENT: The owning iterator of a header `Value` yields every value in order with an
633    /// exact `size_hint`, and stays exhausted.
634    ///
635    /// HOW:
636    /// - Iterate a single value; check `size_hint` before and after `next`.
637    /// - Iterate three appended values; expect `a`, `b`, `c` with matching `size_hint`.
638    /// - Call `next` after the end twice; expect `None`.
639    #[test]
640    fn value_into_iter() {
641        let mut it = Value::One(HeaderValue::from_static("a")).into_iter();
642        assert_eq!(it.size_hint(), (1, Some(1)));
643        assert_eq!(it.next(), Some(HeaderValue::from_static("a")));
644        assert_eq!(it.size_hint(), (0, Some(0)));
645        assert_eq!(it.next(), None);
646
647        let mut val = Value::One(HeaderValue::from_static("a"));
648        val.append(HeaderValue::from_static("b"));
649        val.append(HeaderValue::from_static("c"));
650        let mut it = val.into_iter();
651        assert_eq!(it.size_hint(), (3, Some(3)));
652        assert_eq!(it.next(), Some(HeaderValue::from_static("a")));
653        assert_eq!(it.next(), Some(HeaderValue::from_static("b")));
654        assert_eq!(it.size_hint(), (1, Some(1)));
655        assert_eq!(it.next(), Some(HeaderValue::from_static("c")));
656        assert_eq!(it.next(), None);
657        assert_eq!(it.next(), None);
658    }
659}