http/header/
map.rs

1use std::collections::hash_map::RandomState;
2use std::collections::HashMap;
3use std::convert::TryFrom;
4use std::hash::{BuildHasher, Hash, Hasher};
5use std::iter::{FromIterator, FusedIterator};
6use std::marker::PhantomData;
7use std::{fmt, mem, ops, ptr, vec};
8
9use crate::Error;
10
11use super::name::{HdrName, HeaderName, InvalidHeaderName};
12use super::HeaderValue;
13
14pub use self::as_header_name::AsHeaderName;
15pub use self::into_header_name::IntoHeaderName;
16
17/// A set of HTTP headers
18///
19/// `HeaderMap` is a multimap of [`HeaderName`] to values.
20///
21/// [`HeaderName`]: struct.HeaderName.html
22///
23/// # Examples
24///
25/// Basic usage
26///
27/// ```
28/// # use http::HeaderMap;
29/// # use http::header::{CONTENT_LENGTH, HOST, LOCATION};
30/// let mut headers = HeaderMap::new();
31///
32/// headers.insert(HOST, "example.com".parse().unwrap());
33/// headers.insert(CONTENT_LENGTH, "123".parse().unwrap());
34///
35/// assert!(headers.contains_key(HOST));
36/// assert!(!headers.contains_key(LOCATION));
37///
38/// assert_eq!(headers[HOST], "example.com");
39///
40/// headers.remove(HOST);
41///
42/// assert!(!headers.contains_key(HOST));
43/// ```
44#[derive(Clone)]
45pub struct HeaderMap<T = HeaderValue> {
46    // Used to mask values to get an index
47    mask: Size,
48    indices: Box<[Pos]>,
49    entries: Vec<Bucket<T>>,
50    extra_values: Vec<ExtraValue<T>>,
51    danger: Danger,
52}
53
54// # Implementation notes
55//
56// Below, you will find a fairly large amount of code. Most of this is to
57// provide the necessary functions to efficiently manipulate the header
58// multimap. The core hashing table is based on robin hood hashing [1]. While
59// this is the same hashing algorithm used as part of Rust's `HashMap` in
60// stdlib, many implementation details are different. The two primary reasons
61// for this divergence are that `HeaderMap` is a multimap and the structure has
62// been optimized to take advantage of the characteristics of HTTP headers.
63//
64// ## Structure Layout
65//
66// Most of the data contained by `HeaderMap` is *not* stored in the hash table.
67// Instead, pairs of header name and *first* associated header value are stored
68// in the `entries` vector. If the header name has more than one associated
69// header value, then additional values are stored in `extra_values`. The actual
70// hash table (`indices`) only maps hash codes to indices in `entries`. This
71// means that, when an eviction happens, the actual header name and value stay
72// put and only a tiny amount of memory has to be copied.
73//
74// Extra values associated with a header name are tracked using a linked list.
75// Links are formed with offsets into `extra_values` and not pointers.
76//
77// [1]: https://en.wikipedia.org/wiki/Hash_table#Robin_Hood_hashing
78
79/// `HeaderMap` entry iterator.
80///
81/// Yields `(&HeaderName, &value)` tuples. The same header name may be yielded
82/// more than once if it has more than one associated value.
83#[derive(Debug)]
84pub struct Iter<'a, T> {
85    map: &'a HeaderMap<T>,
86    entry: usize,
87    cursor: Option<Cursor>,
88}
89
90/// `HeaderMap` mutable entry iterator
91///
92/// Yields `(&HeaderName, &mut value)` tuples. The same header name may be
93/// yielded more than once if it has more than one associated value.
94#[derive(Debug)]
95pub struct IterMut<'a, T> {
96    map: *mut HeaderMap<T>,
97    entry: usize,
98    cursor: Option<Cursor>,
99    lt: PhantomData<&'a mut HeaderMap<T>>,
100}
101
102/// An owning iterator over the entries of a `HeaderMap`.
103///
104/// This struct is created by the `into_iter` method on `HeaderMap`.
105#[derive(Debug)]
106pub struct IntoIter<T> {
107    // If None, pull from `entries`
108    next: Option<usize>,
109    entries: vec::IntoIter<Bucket<T>>,
110    extra_values: Vec<ExtraValue<T>>,
111}
112
113/// An iterator over `HeaderMap` keys.
114///
115/// Each header name is yielded only once, even if it has more than one
116/// associated value.
117#[derive(Debug)]
118pub struct Keys<'a, T> {
119    inner: ::std::slice::Iter<'a, Bucket<T>>,
120}
121
122/// `HeaderMap` value iterator.
123///
124/// Each value contained in the `HeaderMap` will be yielded.
125#[derive(Debug)]
126pub struct Values<'a, T> {
127    inner: Iter<'a, T>,
128}
129
130/// `HeaderMap` mutable value iterator
131#[derive(Debug)]
132pub struct ValuesMut<'a, T> {
133    inner: IterMut<'a, T>,
134}
135
136/// A drain iterator for `HeaderMap`.
137#[derive(Debug)]
138pub struct Drain<'a, T> {
139    idx: usize,
140    len: usize,
141    entries: *mut [Bucket<T>],
142    // If None, pull from `entries`
143    next: Option<usize>,
144    extra_values: *mut Vec<ExtraValue<T>>,
145    lt: PhantomData<&'a mut HeaderMap<T>>,
146}
147
148/// A view to all values stored in a single entry.
149///
150/// This struct is returned by `HeaderMap::get_all`.
151#[derive(Debug)]
152pub struct GetAll<'a, T> {
153    map: &'a HeaderMap<T>,
154    index: Option<usize>,
155}
156
157/// A view into a single location in a `HeaderMap`, which may be vacant or occupied.
158#[derive(Debug)]
159pub enum Entry<'a, T: 'a> {
160    /// An occupied entry
161    Occupied(OccupiedEntry<'a, T>),
162
163    /// A vacant entry
164    Vacant(VacantEntry<'a, T>),
165}
166
167/// A view into a single empty location in a `HeaderMap`.
168///
169/// This struct is returned as part of the `Entry` enum.
170#[derive(Debug)]
171pub struct VacantEntry<'a, T> {
172    map: &'a mut HeaderMap<T>,
173    key: HeaderName,
174    hash: HashValue,
175    probe: usize,
176    danger: bool,
177}
178
179/// A view into a single occupied location in a `HeaderMap`.
180///
181/// This struct is returned as part of the `Entry` enum.
182#[derive(Debug)]
183pub struct OccupiedEntry<'a, T> {
184    map: &'a mut HeaderMap<T>,
185    probe: usize,
186    index: usize,
187}
188
189/// An iterator of all values associated with a single header name.
190#[derive(Debug)]
191pub struct ValueIter<'a, T> {
192    map: &'a HeaderMap<T>,
193    index: usize,
194    front: Option<Cursor>,
195    back: Option<Cursor>,
196}
197
198/// A mutable iterator of all values associated with a single header name.
199#[derive(Debug)]
200pub struct ValueIterMut<'a, T> {
201    map: *mut HeaderMap<T>,
202    index: usize,
203    front: Option<Cursor>,
204    back: Option<Cursor>,
205    lt: PhantomData<&'a mut HeaderMap<T>>,
206}
207
208/// An drain iterator of all values associated with a single header name.
209#[derive(Debug)]
210pub struct ValueDrain<'a, T> {
211    first: Option<T>,
212    next: Option<::std::vec::IntoIter<T>>,
213    lt: PhantomData<&'a mut HeaderMap<T>>,
214}
215
216/// Error returned when max capacity of `HeaderMap` is exceeded
217pub struct MaxSizeReached {
218    _priv: (),
219}
220
221/// Tracks the value iterator state
222#[derive(Debug, Copy, Clone, Eq, PartialEq)]
223enum Cursor {
224    Head,
225    Values(usize),
226}
227
228/// Type used for representing the size of a HeaderMap value.
229///
230/// 32,768 is more than enough entries for a single header map. Setting this
231/// limit enables using `u16` to represent all offsets, which takes 2 bytes
232/// instead of 8 on 64 bit processors.
233///
234/// Setting this limit is especially beneficial for `indices`, making it more
235/// cache friendly. More hash codes can fit in a cache line.
236///
237/// You may notice that `u16` may represent more than 32,768 values. This is
238/// true, but 32,768 should be plenty and it allows us to reserve the top bit
239/// for future usage.
240type Size = u16;
241
242/// This limit falls out from above.
243const MAX_SIZE: usize = 1 << 15;
244
245/// An entry in the hash table. This represents the full hash code for an entry
246/// as well as the position of the entry in the `entries` vector.
247#[derive(Copy, Clone)]
248struct Pos {
249    // Index in the `entries` vec
250    index: Size,
251    // Full hash value for the entry.
252    hash: HashValue,
253}
254
255/// Hash values are limited to u16 as well. While `fast_hash` and `Hasher`
256/// return `usize` hash codes, limiting the effective hash code to the lower 16
257/// bits is fine since we know that the `indices` vector will never grow beyond
258/// that size.
259#[derive(Debug, Copy, Clone, Eq, PartialEq)]
260struct HashValue(u16);
261
262/// Stores the data associated with a `HeaderMap` entry. Only the first value is
263/// included in this struct. If a header name has more than one associated
264/// value, all extra values are stored in the `extra_values` vector. A doubly
265/// linked list of entries is maintained. The doubly linked list is used so that
266/// removing a value is constant time. This also has the nice property of
267/// enabling double ended iteration.
268#[derive(Debug, Clone)]
269struct Bucket<T> {
270    hash: HashValue,
271    key: HeaderName,
272    value: T,
273    links: Option<Links>,
274}
275
276/// The head and tail of the value linked list.
277#[derive(Debug, Copy, Clone)]
278struct Links {
279    next: usize,
280    tail: usize,
281}
282
283/// Access to the `links` value in a slice of buckets.
284///
285/// It's important that no other field is accessed, since it may have been
286/// freed in a `Drain` iterator.
287#[derive(Debug)]
288struct RawLinks<T>(*mut [Bucket<T>]);
289
290/// Node in doubly-linked list of header value entries
291#[derive(Debug, Clone)]
292struct ExtraValue<T> {
293    value: T,
294    prev: Link,
295    next: Link,
296}
297
298/// A header value node is either linked to another node in the `extra_values`
299/// list or it points to an entry in `entries`. The entry in `entries` is the
300/// start of the list and holds the associated header name.
301#[derive(Debug, Copy, Clone, Eq, PartialEq)]
302enum Link {
303    Entry(usize),
304    Extra(usize),
305}
306
307/// Tracks the header map danger level! This relates to the adaptive hashing
308/// algorithm. A HeaderMap starts in the "green" state, when a large number of
309/// collisions are detected, it transitions to the yellow state. At this point,
310/// the header map will either grow and switch back to the green state OR it
311/// will transition to the red state.
312///
313/// When in the red state, a safe hashing algorithm is used and all values in
314/// the header map have to be rehashed.
315#[derive(Clone)]
316enum Danger {
317    Green,
318    Yellow,
319    Red(RandomState),
320}
321
322// Constants related to detecting DOS attacks.
323//
324// Displacement is the number of entries that get shifted when inserting a new
325// value. Forward shift is how far the entry gets stored from the ideal
326// position.
327//
328// The current constant values were picked from another implementation. It could
329// be that there are different values better suited to the header map case.
330const DISPLACEMENT_THRESHOLD: usize = 128;
331const FORWARD_SHIFT_THRESHOLD: usize = 512;
332
333// The default strategy for handling the yellow danger state is to increase the
334// header map capacity in order to (hopefully) reduce the number of collisions.
335// If growing the hash map would cause the load factor to drop bellow this
336// threshold, then instead of growing, the headermap is switched to the red
337// danger state and safe hashing is used instead.
338const LOAD_FACTOR_THRESHOLD: f32 = 0.2;
339
340// Macro used to iterate the hash table starting at a given point, looping when
341// the end is hit.
342macro_rules! probe_loop {
343    ($label:tt: $probe_var: ident < $len: expr, $body: expr) => {
344        debug_assert!($len > 0);
345        $label:
346        loop {
347            if $probe_var < $len {
348                $body
349                $probe_var += 1;
350            } else {
351                $probe_var = 0;
352            }
353        }
354    };
355    ($probe_var: ident < $len: expr, $body: expr) => {
356        debug_assert!($len > 0);
357        loop {
358            if $probe_var < $len {
359                $body
360                $probe_var += 1;
361            } else {
362                $probe_var = 0;
363            }
364        }
365    };
366}
367
368// First part of the robinhood algorithm. Given a key, find the slot in which it
369// will be inserted. This is done by starting at the "ideal" spot. Then scanning
370// until the destination slot is found. A destination slot is either the next
371// empty slot or the next slot that is occupied by an entry that has a lower
372// displacement (displacement is the distance from the ideal spot).
373//
374// This is implemented as a macro instead of a function that takes a closure in
375// order to guarantee that it is "inlined". There is no way to annotate closures
376// to guarantee inlining.
377macro_rules! insert_phase_one {
378    ($map:ident,
379     $key:expr,
380     $probe:ident,
381     $pos:ident,
382     $hash:ident,
383     $danger:ident,
384     $vacant:expr,
385     $occupied:expr,
386     $robinhood:expr) =>
387    {{
388        let $hash = hash_elem_using(&$map.danger, &$key);
389        let mut $probe = desired_pos($map.mask, $hash);
390        let mut dist = 0;
391        let ret;
392
393        // Start at the ideal position, checking all slots
394        probe_loop!('probe: $probe < $map.indices.len(), {
395            if let Some(($pos, entry_hash)) = $map.indices[$probe].resolve() {
396                // The slot is already occupied, but check if it has a lower
397                // displacement.
398                let their_dist = probe_distance($map.mask, entry_hash, $probe);
399
400                if their_dist < dist {
401                    // The new key's distance is larger, so claim this spot and
402                    // displace the current entry.
403                    //
404                    // Check if this insertion is above the danger threshold.
405                    let $danger =
406                        dist >= FORWARD_SHIFT_THRESHOLD && !$map.danger.is_red();
407
408                    ret = $robinhood;
409                    break 'probe;
410                } else if entry_hash == $hash && $map.entries[$pos].key == $key {
411                    // There already is an entry with the same key.
412                    ret = $occupied;
413                    break 'probe;
414                }
415            } else {
416                // The entry is vacant, use it for this key.
417                let $danger =
418                    dist >= FORWARD_SHIFT_THRESHOLD && !$map.danger.is_red();
419
420                ret = $vacant;
421                break 'probe;
422            }
423
424            dist += 1;
425        });
426
427        ret
428    }}
429}
430
431// ===== impl HeaderMap =====
432
433impl HeaderMap {
434    /// Create an empty `HeaderMap`.
435    ///
436    /// The map will be created without any capacity. This function will not
437    /// allocate.
438    ///
439    /// # Examples
440    ///
441    /// ```
442    /// # use http::HeaderMap;
443    /// let map = HeaderMap::new();
444    ///
445    /// assert!(map.is_empty());
446    /// assert_eq!(0, map.capacity());
447    /// ```
448    pub fn new() -> Self {
449        HeaderMap::try_with_capacity(0).unwrap()
450    }
451}
452
453impl<T> HeaderMap<T> {
454    /// Create an empty `HeaderMap` with the specified capacity.
455    ///
456    /// The returned map will allocate internal storage in order to hold about
457    /// `capacity` elements without reallocating. However, this is a "best
458    /// effort" as there are usage patterns that could cause additional
459    /// allocations before `capacity` headers are stored in the map.
460    ///
461    /// More capacity than requested may be allocated.
462    ///
463    /// # Panics
464    ///
465    /// This method panics if capacity exceeds max `HeaderMap` capacity.
466    ///
467    /// # Examples
468    ///
469    /// ```
470    /// # use http::HeaderMap;
471    /// let map: HeaderMap<u32> = HeaderMap::with_capacity(10);
472    ///
473    /// assert!(map.is_empty());
474    /// assert_eq!(12, map.capacity());
475    /// ```
476    pub fn with_capacity(capacity: usize) -> HeaderMap<T> {
477        Self::try_with_capacity(capacity).expect("size overflows MAX_SIZE")
478    }
479
480    /// Create an empty `HeaderMap` with the specified capacity.
481    ///
482    /// The returned map will allocate internal storage in order to hold about
483    /// `capacity` elements without reallocating. However, this is a "best
484    /// effort" as there are usage patterns that could cause additional
485    /// allocations before `capacity` headers are stored in the map.
486    ///
487    /// More capacity than requested may be allocated.
488    ///
489    /// # Errors
490    ///
491    /// This function may return an error if `HeaderMap` exceeds max capacity
492    ///
493    /// # Examples
494    ///
495    /// ```
496    /// # use http::HeaderMap;
497    /// let map: HeaderMap<u32> = HeaderMap::try_with_capacity(10).unwrap();
498    ///
499    /// assert!(map.is_empty());
500    /// assert_eq!(12, map.capacity());
501    /// ```
502    pub fn try_with_capacity(capacity: usize) -> Result<HeaderMap<T>, MaxSizeReached> {
503        if capacity == 0 {
504            Ok(HeaderMap {
505                mask: 0,
506                indices: Box::new([]), // as a ZST, this doesn't actually allocate anything
507                entries: Vec::new(),
508                extra_values: Vec::new(),
509                danger: Danger::Green,
510            })
511        } else {
512            let raw_cap = match to_raw_capacity(capacity).checked_next_power_of_two() {
513                Some(c) => c,
514                None => return Err(MaxSizeReached { _priv: () }),
515            };
516            if raw_cap > MAX_SIZE {
517                return Err(MaxSizeReached { _priv: () });
518            }
519            debug_assert!(raw_cap > 0);
520
521            Ok(HeaderMap {
522                mask: (raw_cap - 1) as Size,
523                indices: vec![Pos::none(); raw_cap].into_boxed_slice(),
524                entries: Vec::with_capacity(usable_capacity(raw_cap)),
525                extra_values: Vec::new(),
526                danger: Danger::Green,
527            })
528        }
529    }
530
531    /// Returns the number of headers stored in the map.
532    ///
533    /// This number represents the total number of **values** stored in the map.
534    /// This number can be greater than or equal to the number of **keys**
535    /// stored given that a single key may have more than one associated value.
536    ///
537    /// # Examples
538    ///
539    /// ```
540    /// # use http::HeaderMap;
541    /// # use http::header::{ACCEPT, HOST};
542    /// let mut map = HeaderMap::new();
543    ///
544    /// assert_eq!(0, map.len());
545    ///
546    /// map.insert(ACCEPT, "text/plain".parse().unwrap());
547    /// map.insert(HOST, "localhost".parse().unwrap());
548    ///
549    /// assert_eq!(2, map.len());
550    ///
551    /// map.append(ACCEPT, "text/html".parse().unwrap());
552    ///
553    /// assert_eq!(3, map.len());
554    /// ```
555    pub fn len(&self) -> usize {
556        self.entries.len() + self.extra_values.len()
557    }
558
559    /// Returns the number of keys stored in the map.
560    ///
561    /// This number will be less than or equal to `len()` as each key may have
562    /// more than one associated value.
563    ///
564    /// # Examples
565    ///
566    /// ```
567    /// # use http::HeaderMap;
568    /// # use http::header::{ACCEPT, HOST};
569    /// let mut map = HeaderMap::new();
570    ///
571    /// assert_eq!(0, map.keys_len());
572    ///
573    /// map.insert(ACCEPT, "text/plain".parse().unwrap());
574    /// map.insert(HOST, "localhost".parse().unwrap());
575    ///
576    /// assert_eq!(2, map.keys_len());
577    ///
578    /// map.insert(ACCEPT, "text/html".parse().unwrap());
579    ///
580    /// assert_eq!(2, map.keys_len());
581    /// ```
582    pub fn keys_len(&self) -> usize {
583        self.entries.len()
584    }
585
586    /// Returns true if the map contains no elements.
587    ///
588    /// # Examples
589    ///
590    /// ```
591    /// # use http::HeaderMap;
592    /// # use http::header::HOST;
593    /// let mut map = HeaderMap::new();
594    ///
595    /// assert!(map.is_empty());
596    ///
597    /// map.insert(HOST, "hello.world".parse().unwrap());
598    ///
599    /// assert!(!map.is_empty());
600    /// ```
601    pub fn is_empty(&self) -> bool {
602        self.entries.len() == 0
603    }
604
605    /// Clears the map, removing all key-value pairs. Keeps the allocated memory
606    /// for reuse.
607    ///
608    /// # Examples
609    ///
610    /// ```
611    /// # use http::HeaderMap;
612    /// # use http::header::HOST;
613    /// let mut map = HeaderMap::new();
614    /// map.insert(HOST, "hello.world".parse().unwrap());
615    ///
616    /// map.clear();
617    /// assert!(map.is_empty());
618    /// assert!(map.capacity() > 0);
619    /// ```
620    pub fn clear(&mut self) {
621        self.entries.clear();
622        self.extra_values.clear();
623        self.danger = Danger::Green;
624
625        for e in self.indices.iter_mut() {
626            *e = Pos::none();
627        }
628    }
629
630    /// Returns the number of headers the map can hold without reallocating.
631    ///
632    /// This number is an approximation as certain usage patterns could cause
633    /// additional allocations before the returned capacity is filled.
634    ///
635    /// # Examples
636    ///
637    /// ```
638    /// # use http::HeaderMap;
639    /// # use http::header::HOST;
640    /// let mut map = HeaderMap::new();
641    ///
642    /// assert_eq!(0, map.capacity());
643    ///
644    /// map.insert(HOST, "hello.world".parse().unwrap());
645    /// assert_eq!(6, map.capacity());
646    /// ```
647    pub fn capacity(&self) -> usize {
648        usable_capacity(self.indices.len())
649    }
650
651    /// Reserves capacity for at least `additional` more headers to be inserted
652    /// into the `HeaderMap`.
653    ///
654    /// The header map may reserve more space to avoid frequent reallocations.
655    /// Like with `with_capacity`, this will be a "best effort" to avoid
656    /// allocations until `additional` more headers are inserted. Certain usage
657    /// patterns could cause additional allocations before the number is
658    /// reached.
659    ///
660    /// # Panics
661    ///
662    /// Panics if the new allocation size overflows `HeaderMap` `MAX_SIZE`.
663    ///
664    /// # Examples
665    ///
666    /// ```
667    /// # use http::HeaderMap;
668    /// # use http::header::HOST;
669    /// let mut map = HeaderMap::new();
670    /// map.reserve(10);
671    /// # map.insert(HOST, "bar".parse().unwrap());
672    /// ```
673    pub fn reserve(&mut self, additional: usize) {
674        self.try_reserve(additional)
675            .expect("size overflows MAX_SIZE")
676    }
677
678    /// Reserves capacity for at least `additional` more headers to be inserted
679    /// into the `HeaderMap`.
680    ///
681    /// The header map may reserve more space to avoid frequent reallocations.
682    /// Like with `with_capacity`, this will be a "best effort" to avoid
683    /// allocations until `additional` more headers are inserted. Certain usage
684    /// patterns could cause additional allocations before the number is
685    /// reached.
686    ///
687    /// # Errors
688    ///
689    /// This method differs from `reserve` by returning an error instead of
690    /// panicking if the value is too large.
691    ///
692    /// # Examples
693    ///
694    /// ```
695    /// # use http::HeaderMap;
696    /// # use http::header::HOST;
697    /// let mut map = HeaderMap::new();
698    /// map.try_reserve(10).unwrap();
699    /// # map.try_insert(HOST, "bar".parse().unwrap()).unwrap();
700    /// ```
701    pub fn try_reserve(&mut self, additional: usize) -> Result<(), MaxSizeReached> {
702        // TODO: This can't overflow if done properly... since the max # of
703        // elements is u16::MAX.
704        let cap = self
705            .entries
706            .len()
707            .checked_add(additional)
708            .ok_or_else(MaxSizeReached::new)?;
709
710        if cap > self.indices.len() {
711            let cap = cap
712                .checked_next_power_of_two()
713                .ok_or_else(MaxSizeReached::new)?;
714            if cap > MAX_SIZE {
715                return Err(MaxSizeReached::new());
716            }
717
718            if self.entries.is_empty() {
719                self.mask = cap as Size - 1;
720                self.indices = vec![Pos::none(); cap].into_boxed_slice();
721                self.entries = Vec::with_capacity(usable_capacity(cap));
722            } else {
723                self.try_grow(cap)?;
724            }
725        }
726
727        Ok(())
728    }
729
730    /// Returns a reference to the value associated with the key.
731    ///
732    /// If there are multiple values associated with the key, then the first one
733    /// is returned. Use `get_all` to get all values associated with a given
734    /// key. Returns `None` if there are no values associated with the key.
735    ///
736    /// # Examples
737    ///
738    /// ```
739    /// # use http::HeaderMap;
740    /// # use http::header::HOST;
741    /// let mut map = HeaderMap::new();
742    /// assert!(map.get("host").is_none());
743    ///
744    /// map.insert(HOST, "hello".parse().unwrap());
745    /// assert_eq!(map.get(HOST).unwrap(), &"hello");
746    /// assert_eq!(map.get("host").unwrap(), &"hello");
747    ///
748    /// map.append(HOST, "world".parse().unwrap());
749    /// assert_eq!(map.get("host").unwrap(), &"hello");
750    /// ```
751    pub fn get<K>(&self, key: K) -> Option<&T>
752    where
753        K: AsHeaderName,
754    {
755        self.get2(&key)
756    }
757
758    fn get2<K>(&self, key: &K) -> Option<&T>
759    where
760        K: AsHeaderName,
761    {
762        match key.find(self) {
763            Some((_, found)) => {
764                let entry = &self.entries[found];
765                Some(&entry.value)
766            }
767            None => None,
768        }
769    }
770
771    /// Returns a mutable reference to the value associated with the key.
772    ///
773    /// If there are multiple values associated with the key, then the first one
774    /// is returned. Use `entry` to get all values associated with a given
775    /// key. Returns `None` if there are no values associated with the key.
776    ///
777    /// # Examples
778    ///
779    /// ```
780    /// # use http::HeaderMap;
781    /// # use http::header::HOST;
782    /// let mut map = HeaderMap::default();
783    /// map.insert(HOST, "hello".to_string());
784    /// map.get_mut("host").unwrap().push_str("-world");
785    ///
786    /// assert_eq!(map.get(HOST).unwrap(), &"hello-world");
787    /// ```
788    pub fn get_mut<K>(&mut self, key: K) -> Option<&mut T>
789    where
790        K: AsHeaderName,
791    {
792        match key.find(self) {
793            Some((_, found)) => {
794                let entry = &mut self.entries[found];
795                Some(&mut entry.value)
796            }
797            None => None,
798        }
799    }
800
801    /// Returns a view of all values associated with a key.
802    ///
803    /// The returned view does not incur any allocations and allows iterating
804    /// the values associated with the key.  See [`GetAll`] for more details.
805    /// Returns `None` if there are no values associated with the key.
806    ///
807    /// [`GetAll`]: struct.GetAll.html
808    ///
809    /// # Examples
810    ///
811    /// ```
812    /// # use http::HeaderMap;
813    /// # use http::header::HOST;
814    /// let mut map = HeaderMap::new();
815    ///
816    /// map.insert(HOST, "hello".parse().unwrap());
817    /// map.append(HOST, "goodbye".parse().unwrap());
818    ///
819    /// let view = map.get_all("host");
820    ///
821    /// let mut iter = view.iter();
822    /// assert_eq!(&"hello", iter.next().unwrap());
823    /// assert_eq!(&"goodbye", iter.next().unwrap());
824    /// assert!(iter.next().is_none());
825    /// ```
826    pub fn get_all<K>(&self, key: K) -> GetAll<'_, T>
827    where
828        K: AsHeaderName,
829    {
830        GetAll {
831            map: self,
832            index: key.find(self).map(|(_, i)| i),
833        }
834    }
835
836    /// Returns true if the map contains a value for the specified key.
837    ///
838    /// # Examples
839    ///
840    /// ```
841    /// # use http::HeaderMap;
842    /// # use http::header::HOST;
843    /// let mut map = HeaderMap::new();
844    /// assert!(!map.contains_key(HOST));
845    ///
846    /// map.insert(HOST, "world".parse().unwrap());
847    /// assert!(map.contains_key("host"));
848    /// ```
849    pub fn contains_key<K>(&self, key: K) -> bool
850    where
851        K: AsHeaderName,
852    {
853        key.find(self).is_some()
854    }
855
856    /// An iterator visiting all key-value pairs.
857    ///
858    /// The iteration order is arbitrary, but consistent across platforms for
859    /// the same crate version. Each key will be yielded once per associated
860    /// value. So, if a key has 3 associated values, it will be yielded 3 times.
861    ///
862    /// # Examples
863    ///
864    /// ```
865    /// # use http::HeaderMap;
866    /// # use http::header::{CONTENT_LENGTH, HOST};
867    /// let mut map = HeaderMap::new();
868    ///
869    /// map.insert(HOST, "hello".parse().unwrap());
870    /// map.append(HOST, "goodbye".parse().unwrap());
871    /// map.insert(CONTENT_LENGTH, "123".parse().unwrap());
872    ///
873    /// for (key, value) in map.iter() {
874    ///     println!("{:?}: {:?}", key, value);
875    /// }
876    /// ```
877    pub fn iter(&self) -> Iter<'_, T> {
878        Iter {
879            map: self,
880            entry: 0,
881            cursor: self.entries.first().map(|_| Cursor::Head),
882        }
883    }
884
885    /// An iterator visiting all key-value pairs, with mutable value references.
886    ///
887    /// The iterator order is arbitrary, but consistent across platforms for the
888    /// same crate version. Each key will be yielded once per associated value,
889    /// so if a key has 3 associated values, it will be yielded 3 times.
890    ///
891    /// # Examples
892    ///
893    /// ```
894    /// # use http::HeaderMap;
895    /// # use http::header::{CONTENT_LENGTH, HOST};
896    /// let mut map = HeaderMap::default();
897    ///
898    /// map.insert(HOST, "hello".to_string());
899    /// map.append(HOST, "goodbye".to_string());
900    /// map.insert(CONTENT_LENGTH, "123".to_string());
901    ///
902    /// for (key, value) in map.iter_mut() {
903    ///     value.push_str("-boop");
904    /// }
905    /// ```
906    pub fn iter_mut(&mut self) -> IterMut<'_, T> {
907        IterMut {
908            map: self as *mut _,
909            entry: 0,
910            cursor: self.entries.first().map(|_| Cursor::Head),
911            lt: PhantomData,
912        }
913    }
914
915    /// An iterator visiting all keys.
916    ///
917    /// The iteration order is arbitrary, but consistent across platforms for
918    /// the same crate version. Each key will be yielded only once even if it
919    /// has multiple associated values.
920    ///
921    /// # Examples
922    ///
923    /// ```
924    /// # use http::HeaderMap;
925    /// # use http::header::{CONTENT_LENGTH, HOST};
926    /// let mut map = HeaderMap::new();
927    ///
928    /// map.insert(HOST, "hello".parse().unwrap());
929    /// map.append(HOST, "goodbye".parse().unwrap());
930    /// map.insert(CONTENT_LENGTH, "123".parse().unwrap());
931    ///
932    /// for key in map.keys() {
933    ///     println!("{:?}", key);
934    /// }
935    /// ```
936    pub fn keys(&self) -> Keys<'_, T> {
937        Keys {
938            inner: self.entries.iter(),
939        }
940    }
941
942    /// An iterator visiting all values.
943    ///
944    /// The iteration order is arbitrary, but consistent across platforms for
945    /// the same crate version.
946    ///
947    /// # Examples
948    ///
949    /// ```
950    /// # use http::HeaderMap;
951    /// # use http::header::{CONTENT_LENGTH, HOST};
952    /// let mut map = HeaderMap::new();
953    ///
954    /// map.insert(HOST, "hello".parse().unwrap());
955    /// map.append(HOST, "goodbye".parse().unwrap());
956    /// map.insert(CONTENT_LENGTH, "123".parse().unwrap());
957    ///
958    /// for value in map.values() {
959    ///     println!("{:?}", value);
960    /// }
961    /// ```
962    pub fn values(&self) -> Values<'_, T> {
963        Values { inner: self.iter() }
964    }
965
966    /// An iterator visiting all values mutably.
967    ///
968    /// The iteration order is arbitrary, but consistent across platforms for
969    /// the same crate version.
970    ///
971    /// # Examples
972    ///
973    /// ```
974    /// # use http::HeaderMap;
975    /// # use http::header::{CONTENT_LENGTH, HOST};
976    /// let mut map = HeaderMap::default();
977    ///
978    /// map.insert(HOST, "hello".to_string());
979    /// map.append(HOST, "goodbye".to_string());
980    /// map.insert(CONTENT_LENGTH, "123".to_string());
981    ///
982    /// for value in map.values_mut() {
983    ///     value.push_str("-boop");
984    /// }
985    /// ```
986    pub fn values_mut(&mut self) -> ValuesMut<'_, T> {
987        ValuesMut {
988            inner: self.iter_mut(),
989        }
990    }
991
992    /// Clears the map, returning all entries as an iterator.
993    ///
994    /// The internal memory is kept for reuse.
995    ///
996    /// For each yielded item that has `None` provided for the `HeaderName`,
997    /// then the associated header name is the same as that of the previously
998    /// yielded item. The first yielded item will have `HeaderName` set.
999    ///
1000    /// # Examples
1001    ///
1002    /// ```
1003    /// # use http::HeaderMap;
1004    /// # use http::header::{CONTENT_LENGTH, HOST};
1005    /// let mut map = HeaderMap::new();
1006    ///
1007    /// map.insert(HOST, "hello".parse().unwrap());
1008    /// map.append(HOST, "goodbye".parse().unwrap());
1009    /// map.insert(CONTENT_LENGTH, "123".parse().unwrap());
1010    ///
1011    /// let mut drain = map.drain();
1012    ///
1013    ///
1014    /// assert_eq!(drain.next(), Some((Some(HOST), "hello".parse().unwrap())));
1015    /// assert_eq!(drain.next(), Some((None, "goodbye".parse().unwrap())));
1016    ///
1017    /// assert_eq!(drain.next(), Some((Some(CONTENT_LENGTH), "123".parse().unwrap())));
1018    ///
1019    /// assert_eq!(drain.next(), None);
1020    /// ```
1021    pub fn drain(&mut self) -> Drain<'_, T> {
1022        for i in self.indices.iter_mut() {
1023            *i = Pos::none();
1024        }
1025
1026        // Memory safety
1027        //
1028        // When the Drain is first created, it shortens the length of
1029        // the source vector to make sure no uninitialized or moved-from
1030        // elements are accessible at all if the Drain's destructor never
1031        // gets to run.
1032
1033        let entries = &mut self.entries[..] as *mut _;
1034        let extra_values = &mut self.extra_values as *mut _;
1035        let len = self.entries.len();
1036        unsafe {
1037            self.entries.set_len(0);
1038        }
1039
1040        Drain {
1041            idx: 0,
1042            len,
1043            entries,
1044            extra_values,
1045            next: None,
1046            lt: PhantomData,
1047        }
1048    }
1049
1050    fn value_iter(&self, idx: Option<usize>) -> ValueIter<'_, T> {
1051        use self::Cursor::*;
1052
1053        if let Some(idx) = idx {
1054            let back = {
1055                let entry = &self.entries[idx];
1056
1057                entry.links.map(|l| Values(l.tail)).unwrap_or(Head)
1058            };
1059
1060            ValueIter {
1061                map: self,
1062                index: idx,
1063                front: Some(Head),
1064                back: Some(back),
1065            }
1066        } else {
1067            ValueIter {
1068                map: self,
1069                index: usize::MAX,
1070                front: None,
1071                back: None,
1072            }
1073        }
1074    }
1075
1076    fn value_iter_mut(&mut self, idx: usize) -> ValueIterMut<'_, T> {
1077        use self::Cursor::*;
1078
1079        let back = {
1080            let entry = &self.entries[idx];
1081
1082            entry.links.map(|l| Values(l.tail)).unwrap_or(Head)
1083        };
1084
1085        ValueIterMut {
1086            map: self as *mut _,
1087            index: idx,
1088            front: Some(Head),
1089            back: Some(back),
1090            lt: PhantomData,
1091        }
1092    }
1093
1094    /// Gets the given key's corresponding entry in the map for in-place
1095    /// manipulation.
1096    ///
1097    /// # Panics
1098    ///
1099    /// This method panics if capacity exceeds max `HeaderMap` capacity
1100    ///
1101    /// # Examples
1102    ///
1103    /// ```
1104    /// # use http::HeaderMap;
1105    /// let mut map: HeaderMap<u32> = HeaderMap::default();
1106    ///
1107    /// let headers = &[
1108    ///     "content-length",
1109    ///     "x-hello",
1110    ///     "Content-Length",
1111    ///     "x-world",
1112    /// ];
1113    ///
1114    /// for &header in headers {
1115    ///     let counter = map.entry(header).or_insert(0);
1116    ///     *counter += 1;
1117    /// }
1118    ///
1119    /// assert_eq!(map["content-length"], 2);
1120    /// assert_eq!(map["x-hello"], 1);
1121    /// ```
1122    pub fn entry<K>(&mut self, key: K) -> Entry<'_, T>
1123    where
1124        K: IntoHeaderName,
1125    {
1126        key.try_entry(self).expect("size overflows MAX_SIZE")
1127    }
1128
1129    /// Gets the given key's corresponding entry in the map for in-place
1130    /// manipulation.
1131    ///
1132    /// # Errors
1133    ///
1134    /// This method differs from `entry` by allowing types that may not be
1135    /// valid `HeaderName`s to passed as the key (such as `String`). If they
1136    /// do not parse as a valid `HeaderName`, this returns an
1137    /// `InvalidHeaderName` error.
1138    ///
1139    /// If reserving space goes over the maximum, this will also return an
1140    /// error. However, to prevent breaking changes to the return type, the
1141    /// error will still say `InvalidHeaderName`, unlike other `try_*` methods
1142    /// which return a `MaxSizeReached` error.
1143    pub fn try_entry<K>(&mut self, key: K) -> Result<Entry<'_, T>, InvalidHeaderName>
1144    where
1145        K: AsHeaderName,
1146    {
1147        key.try_entry(self).map_err(|err| match err {
1148            as_header_name::TryEntryError::InvalidHeaderName(e) => e,
1149            as_header_name::TryEntryError::MaxSizeReached(_e) => {
1150                // Unfortunately, we cannot change the return type of this
1151                // method, so the max size reached error needs to be converted
1152                // into an InvalidHeaderName. Yay.
1153                InvalidHeaderName::new()
1154            }
1155        })
1156    }
1157
1158    fn try_entry2<K>(&mut self, key: K) -> Result<Entry<'_, T>, MaxSizeReached>
1159    where
1160        K: Hash + Into<HeaderName>,
1161        HeaderName: PartialEq<K>,
1162    {
1163        // Ensure that there is space in the map
1164        self.try_reserve_one()?;
1165
1166        Ok(insert_phase_one!(
1167            self,
1168            key,
1169            probe,
1170            pos,
1171            hash,
1172            danger,
1173            Entry::Vacant(VacantEntry {
1174                map: self,
1175                hash,
1176                key: key.into(),
1177                probe,
1178                danger,
1179            }),
1180            Entry::Occupied(OccupiedEntry {
1181                map: self,
1182                index: pos,
1183                probe,
1184            }),
1185            Entry::Vacant(VacantEntry {
1186                map: self,
1187                hash,
1188                key: key.into(),
1189                probe,
1190                danger,
1191            })
1192        ))
1193    }
1194
1195    /// Inserts a key-value pair into the map.
1196    ///
1197    /// If the map did not previously have this key present, then `None` is
1198    /// returned.
1199    ///
1200    /// If the map did have this key present, the new value is associated with
1201    /// the key and all previous values are removed. **Note** that only a single
1202    /// one of the previous values is returned. If there are multiple values
1203    /// that have been previously associated with the key, then the first one is
1204    /// returned. See `insert_mult` on `OccupiedEntry` for an API that returns
1205    /// all values.
1206    ///
1207    /// The key is not updated, though; this matters for types that can be `==`
1208    /// without being identical.
1209    ///
1210    /// # Panics
1211    ///
1212    /// This method panics if capacity exceeds max `HeaderMap` capacity
1213    ///
1214    /// # Examples
1215    ///
1216    /// ```
1217    /// # use http::HeaderMap;
1218    /// # use http::header::HOST;
1219    /// let mut map = HeaderMap::new();
1220    /// assert!(map.insert(HOST, "world".parse().unwrap()).is_none());
1221    /// assert!(!map.is_empty());
1222    ///
1223    /// let mut prev = map.insert(HOST, "earth".parse().unwrap()).unwrap();
1224    /// assert_eq!("world", prev);
1225    /// ```
1226    pub fn insert<K>(&mut self, key: K, val: T) -> Option<T>
1227    where
1228        K: IntoHeaderName,
1229    {
1230        self.try_insert(key, val).expect("size overflows MAX_SIZE")
1231    }
1232
1233    /// Inserts a key-value pair into the map.
1234    ///
1235    /// If the map did not previously have this key present, then `None` is
1236    /// returned.
1237    ///
1238    /// If the map did have this key present, the new value is associated with
1239    /// the key and all previous values are removed. **Note** that only a single
1240    /// one of the previous values is returned. If there are multiple values
1241    /// that have been previously associated with the key, then the first one is
1242    /// returned. See `insert_mult` on `OccupiedEntry` for an API that returns
1243    /// all values.
1244    ///
1245    /// The key is not updated, though; this matters for types that can be `==`
1246    /// without being identical.
1247    ///
1248    /// # Errors
1249    ///
1250    /// This function may return an error if `HeaderMap` exceeds max capacity
1251    ///
1252    /// # Examples
1253    ///
1254    /// ```
1255    /// # use http::HeaderMap;
1256    /// # use http::header::HOST;
1257    /// let mut map = HeaderMap::new();
1258    /// assert!(map.try_insert(HOST, "world".parse().unwrap()).unwrap().is_none());
1259    /// assert!(!map.is_empty());
1260    ///
1261    /// let mut prev = map.try_insert(HOST, "earth".parse().unwrap()).unwrap().unwrap();
1262    /// assert_eq!("world", prev);
1263    /// ```
1264    pub fn try_insert<K>(&mut self, key: K, val: T) -> Result<Option<T>, MaxSizeReached>
1265    where
1266        K: IntoHeaderName,
1267    {
1268        key.try_insert(self, val)
1269    }
1270
1271    #[inline]
1272    fn try_insert2<K>(&mut self, key: K, value: T) -> Result<Option<T>, MaxSizeReached>
1273    where
1274        K: Hash + Into<HeaderName>,
1275        HeaderName: PartialEq<K>,
1276    {
1277        self.try_reserve_one()?;
1278
1279        Ok(insert_phase_one!(
1280            self,
1281            key,
1282            probe,
1283            pos,
1284            hash,
1285            danger,
1286            // Vacant
1287            {
1288                let _ = danger; // Make lint happy
1289                let index = self.entries.len();
1290                self.try_insert_entry(hash, key.into(), value)?;
1291                self.indices[probe] = Pos::new(index, hash);
1292                None
1293            },
1294            // Occupied
1295            Some(self.insert_occupied(pos, value)),
1296            // Robinhood
1297            {
1298                self.try_insert_phase_two(key.into(), value, hash, probe, danger)?;
1299                None
1300            }
1301        ))
1302    }
1303
1304    /// Set an occupied bucket to the given value
1305    #[inline]
1306    fn insert_occupied(&mut self, index: usize, value: T) -> T {
1307        if let Some(links) = self.entries[index].links {
1308            self.remove_all_extra_values(links.next);
1309        }
1310
1311        let entry = &mut self.entries[index];
1312        mem::replace(&mut entry.value, value)
1313    }
1314
1315    fn insert_occupied_mult(&mut self, index: usize, value: T) -> ValueDrain<'_, T> {
1316        let old;
1317        let links;
1318
1319        {
1320            let entry = &mut self.entries[index];
1321
1322            old = mem::replace(&mut entry.value, value);
1323            links = entry.links.take();
1324        }
1325
1326        let raw_links = self.raw_links();
1327        let extra_values = &mut self.extra_values;
1328
1329        let next =
1330            links.map(|l| drain_all_extra_values(raw_links, extra_values, l.next).into_iter());
1331
1332        ValueDrain {
1333            first: Some(old),
1334            next,
1335            lt: PhantomData,
1336        }
1337    }
1338
1339    /// Inserts a key-value pair into the map.
1340    ///
1341    /// If the map did not previously have this key present, then `false` is
1342    /// returned.
1343    ///
1344    /// If the map did have this key present, the new value is pushed to the end
1345    /// of the list of values currently associated with the key. The key is not
1346    /// updated, though; this matters for types that can be `==` without being
1347    /// identical.
1348    ///
1349    /// # Panics
1350    ///
1351    /// This method panics if capacity exceeds max `HeaderMap` capacity
1352    ///
1353    /// # Examples
1354    ///
1355    /// ```
1356    /// # use http::HeaderMap;
1357    /// # use http::header::HOST;
1358    /// let mut map = HeaderMap::new();
1359    /// assert!(map.insert(HOST, "world".parse().unwrap()).is_none());
1360    /// assert!(!map.is_empty());
1361    ///
1362    /// map.append(HOST, "earth".parse().unwrap());
1363    ///
1364    /// let values = map.get_all("host");
1365    /// let mut i = values.iter();
1366    /// assert_eq!("world", *i.next().unwrap());
1367    /// assert_eq!("earth", *i.next().unwrap());
1368    /// ```
1369    pub fn append<K>(&mut self, key: K, value: T) -> bool
1370    where
1371        K: IntoHeaderName,
1372    {
1373        self.try_append(key, value)
1374            .expect("size overflows MAX_SIZE")
1375    }
1376
1377    /// Inserts a key-value pair into the map.
1378    ///
1379    /// If the map did not previously have this key present, then `false` is
1380    /// returned.
1381    ///
1382    /// If the map did have this key present, the new value is pushed to the end
1383    /// of the list of values currently associated with the key. The key is not
1384    /// updated, though; this matters for types that can be `==` without being
1385    /// identical.
1386    ///
1387    /// # Errors
1388    ///
1389    /// This function may return an error if `HeaderMap` exceeds max capacity
1390    ///
1391    /// # Examples
1392    ///
1393    /// ```
1394    /// # use http::HeaderMap;
1395    /// # use http::header::HOST;
1396    /// let mut map = HeaderMap::new();
1397    /// assert!(map.try_insert(HOST, "world".parse().unwrap()).unwrap().is_none());
1398    /// assert!(!map.is_empty());
1399    ///
1400    /// map.try_append(HOST, "earth".parse().unwrap()).unwrap();
1401    ///
1402    /// let values = map.get_all("host");
1403    /// let mut i = values.iter();
1404    /// assert_eq!("world", *i.next().unwrap());
1405    /// assert_eq!("earth", *i.next().unwrap());
1406    /// ```
1407    pub fn try_append<K>(&mut self, key: K, value: T) -> Result<bool, MaxSizeReached>
1408    where
1409        K: IntoHeaderName,
1410    {
1411        key.try_append(self, value)
1412    }
1413
1414    #[inline]
1415    fn try_append2<K>(&mut self, key: K, value: T) -> Result<bool, MaxSizeReached>
1416    where
1417        K: Hash + Into<HeaderName>,
1418        HeaderName: PartialEq<K>,
1419    {
1420        self.try_reserve_one()?;
1421
1422        Ok(insert_phase_one!(
1423            self,
1424            key,
1425            probe,
1426            pos,
1427            hash,
1428            danger,
1429            // Vacant
1430            {
1431                let _ = danger;
1432                let index = self.entries.len();
1433                self.try_insert_entry(hash, key.into(), value)?;
1434                self.indices[probe] = Pos::new(index, hash);
1435                false
1436            },
1437            // Occupied
1438            {
1439                append_value(pos, &mut self.entries[pos], &mut self.extra_values, value);
1440                true
1441            },
1442            // Robinhood
1443            {
1444                self.try_insert_phase_two(key.into(), value, hash, probe, danger)?;
1445
1446                false
1447            }
1448        ))
1449    }
1450
1451    #[inline]
1452    fn find<K>(&self, key: &K) -> Option<(usize, usize)>
1453    where
1454        K: Hash + Into<HeaderName> + ?Sized,
1455        HeaderName: PartialEq<K>,
1456    {
1457        if self.entries.is_empty() {
1458            return None;
1459        }
1460
1461        let hash = hash_elem_using(&self.danger, key);
1462        let mask = self.mask;
1463        let mut probe = desired_pos(mask, hash);
1464        let mut dist = 0;
1465
1466        probe_loop!(probe < self.indices.len(), {
1467            if let Some((i, entry_hash)) = self.indices[probe].resolve() {
1468                if dist > probe_distance(mask, entry_hash, probe) {
1469                    // give up when probe distance is too long
1470                    return None;
1471                } else if entry_hash == hash && self.entries[i].key == *key {
1472                    return Some((probe, i));
1473                }
1474            } else {
1475                return None;
1476            }
1477
1478            dist += 1;
1479        });
1480    }
1481
1482    /// phase 2 is post-insert where we forward-shift `Pos` in the indices.
1483    #[inline]
1484    fn try_insert_phase_two(
1485        &mut self,
1486        key: HeaderName,
1487        value: T,
1488        hash: HashValue,
1489        probe: usize,
1490        danger: bool,
1491    ) -> Result<usize, MaxSizeReached> {
1492        // Push the value and get the index
1493        let index = self.entries.len();
1494        self.try_insert_entry(hash, key, value)?;
1495
1496        let num_displaced = do_insert_phase_two(&mut self.indices, probe, Pos::new(index, hash));
1497
1498        if danger || num_displaced >= DISPLACEMENT_THRESHOLD {
1499            // Increase danger level
1500            self.danger.set_yellow();
1501        }
1502
1503        Ok(index)
1504    }
1505
1506    /// Removes a key from the map, returning the value associated with the key.
1507    ///
1508    /// Returns `None` if the map does not contain the key. If there are
1509    /// multiple values associated with the key, then the first one is returned.
1510    /// See `remove_entry_mult` on `OccupiedEntry` for an API that yields all
1511    /// values.
1512    ///
1513    /// # Examples
1514    ///
1515    /// ```
1516    /// # use http::HeaderMap;
1517    /// # use http::header::HOST;
1518    /// let mut map = HeaderMap::new();
1519    /// map.insert(HOST, "hello.world".parse().unwrap());
1520    ///
1521    /// let prev = map.remove(HOST).unwrap();
1522    /// assert_eq!("hello.world", prev);
1523    ///
1524    /// assert!(map.remove(HOST).is_none());
1525    /// ```
1526    pub fn remove<K>(&mut self, key: K) -> Option<T>
1527    where
1528        K: AsHeaderName,
1529    {
1530        match key.find(self) {
1531            Some((probe, idx)) => {
1532                if let Some(links) = self.entries[idx].links {
1533                    self.remove_all_extra_values(links.next);
1534                }
1535
1536                let entry = self.remove_found(probe, idx);
1537
1538                Some(entry.value)
1539            }
1540            None => None,
1541        }
1542    }
1543
1544    /// Remove an entry from the map.
1545    ///
1546    /// Warning: To avoid inconsistent state, extra values _must_ be removed
1547    /// for the `found` index (via `remove_all_extra_values` or similar)
1548    /// _before_ this method is called.
1549    #[inline]
1550    fn remove_found(&mut self, probe: usize, found: usize) -> Bucket<T> {
1551        // index `probe` and entry `found` is to be removed
1552        // use swap_remove, but then we need to update the index that points
1553        // to the other entry that has to move
1554        self.indices[probe] = Pos::none();
1555        let entry = self.entries.swap_remove(found);
1556
1557        // correct index that points to the entry that had to swap places
1558        if let Some(entry) = self.entries.get(found) {
1559            // was not last element
1560            // examine new element in `found` and find it in indices
1561            let mut probe = desired_pos(self.mask, entry.hash);
1562
1563            probe_loop!(probe < self.indices.len(), {
1564                if let Some((i, _)) = self.indices[probe].resolve() {
1565                    if i >= self.entries.len() {
1566                        // found it
1567                        self.indices[probe] = Pos::new(found, entry.hash);
1568                        break;
1569                    }
1570                }
1571            });
1572
1573            // Update links
1574            if let Some(links) = entry.links {
1575                self.extra_values[links.next].prev = Link::Entry(found);
1576                self.extra_values[links.tail].next = Link::Entry(found);
1577            }
1578        }
1579
1580        // backward shift deletion in self.indices
1581        // after probe, shift all non-ideally placed indices backward
1582        if !self.entries.is_empty() {
1583            let mut last_probe = probe;
1584            let mut probe = probe + 1;
1585
1586            probe_loop!(probe < self.indices.len(), {
1587                if let Some((_, entry_hash)) = self.indices[probe].resolve() {
1588                    if probe_distance(self.mask, entry_hash, probe) > 0 {
1589                        self.indices[last_probe] = self.indices[probe];
1590                        self.indices[probe] = Pos::none();
1591                    } else {
1592                        break;
1593                    }
1594                } else {
1595                    break;
1596                }
1597
1598                last_probe = probe;
1599            });
1600        }
1601
1602        entry
1603    }
1604
1605    /// Removes the `ExtraValue` at the given index.
1606    #[inline]
1607    fn remove_extra_value(&mut self, idx: usize) -> ExtraValue<T> {
1608        let raw_links = self.raw_links();
1609        remove_extra_value(raw_links, &mut self.extra_values, idx)
1610    }
1611
1612    fn remove_all_extra_values(&mut self, mut head: usize) {
1613        loop {
1614            let extra = self.remove_extra_value(head);
1615
1616            if let Link::Extra(idx) = extra.next {
1617                head = idx;
1618            } else {
1619                break;
1620            }
1621        }
1622    }
1623
1624    #[inline]
1625    fn try_insert_entry(
1626        &mut self,
1627        hash: HashValue,
1628        key: HeaderName,
1629        value: T,
1630    ) -> Result<(), MaxSizeReached> {
1631        if self.entries.len() >= MAX_SIZE {
1632            return Err(MaxSizeReached::new());
1633        }
1634
1635        self.entries.push(Bucket {
1636            hash,
1637            key,
1638            value,
1639            links: None,
1640        });
1641
1642        Ok(())
1643    }
1644
1645    fn rebuild(&mut self) {
1646        // Loop over all entries and re-insert them into the map
1647        'outer: for (index, entry) in self.entries.iter_mut().enumerate() {
1648            let hash = hash_elem_using(&self.danger, &entry.key);
1649            let mut probe = desired_pos(self.mask, hash);
1650            let mut dist = 0;
1651
1652            // Update the entry's hash code
1653            entry.hash = hash;
1654
1655            probe_loop!(probe < self.indices.len(), {
1656                if let Some((_, entry_hash)) = self.indices[probe].resolve() {
1657                    // if existing element probed less than us, swap
1658                    let their_dist = probe_distance(self.mask, entry_hash, probe);
1659
1660                    if their_dist < dist {
1661                        // Robinhood
1662                        break;
1663                    }
1664                } else {
1665                    // Vacant slot
1666                    self.indices[probe] = Pos::new(index, hash);
1667                    continue 'outer;
1668                }
1669
1670                dist += 1;
1671            });
1672
1673            do_insert_phase_two(&mut self.indices, probe, Pos::new(index, hash));
1674        }
1675    }
1676
1677    fn reinsert_entry_in_order(&mut self, pos: Pos) {
1678        if let Some((_, entry_hash)) = pos.resolve() {
1679            // Find first empty bucket and insert there
1680            let mut probe = desired_pos(self.mask, entry_hash);
1681
1682            probe_loop!(probe < self.indices.len(), {
1683                if self.indices[probe].resolve().is_none() {
1684                    // empty bucket, insert here
1685                    self.indices[probe] = pos;
1686                    return;
1687                }
1688            });
1689        }
1690    }
1691
1692    fn try_reserve_one(&mut self) -> Result<(), MaxSizeReached> {
1693        let len = self.entries.len();
1694
1695        if self.danger.is_yellow() {
1696            let load_factor = self.entries.len() as f32 / self.indices.len() as f32;
1697
1698            if load_factor >= LOAD_FACTOR_THRESHOLD {
1699                // Transition back to green danger level
1700                self.danger.set_green();
1701
1702                // Double the capacity
1703                let new_cap = self.indices.len() * 2;
1704
1705                // Grow the capacity
1706                self.try_grow(new_cap)?;
1707            } else {
1708                self.danger.set_red();
1709
1710                // Rebuild hash table
1711                for index in self.indices.iter_mut() {
1712                    *index = Pos::none();
1713                }
1714
1715                self.rebuild();
1716            }
1717        } else if len == self.capacity() {
1718            if len == 0 {
1719                let new_raw_cap = 8;
1720                self.mask = 8 - 1;
1721                self.indices = vec![Pos::none(); new_raw_cap].into_boxed_slice();
1722                self.entries = Vec::with_capacity(usable_capacity(new_raw_cap));
1723            } else {
1724                let raw_cap = self.indices.len();
1725                self.try_grow(raw_cap << 1)?;
1726            }
1727        }
1728
1729        Ok(())
1730    }
1731
1732    #[inline]
1733    fn try_grow(&mut self, new_raw_cap: usize) -> Result<(), MaxSizeReached> {
1734        if new_raw_cap > MAX_SIZE {
1735            return Err(MaxSizeReached::new());
1736        }
1737
1738        // find first ideally placed element -- start of cluster
1739        let mut first_ideal = 0;
1740
1741        for (i, pos) in self.indices.iter().enumerate() {
1742            if let Some((_, entry_hash)) = pos.resolve() {
1743                if 0 == probe_distance(self.mask, entry_hash, i) {
1744                    first_ideal = i;
1745                    break;
1746                }
1747            }
1748        }
1749
1750        // visit the entries in an order where we can simply reinsert them
1751        // into self.indices without any bucket stealing.
1752        let old_indices = mem::replace(
1753            &mut self.indices,
1754            vec![Pos::none(); new_raw_cap].into_boxed_slice(),
1755        );
1756        self.mask = new_raw_cap.wrapping_sub(1) as Size;
1757
1758        for &pos in &old_indices[first_ideal..] {
1759            self.reinsert_entry_in_order(pos);
1760        }
1761
1762        for &pos in &old_indices[..first_ideal] {
1763            self.reinsert_entry_in_order(pos);
1764        }
1765
1766        // Reserve additional entry slots
1767        let more = self.capacity() - self.entries.len();
1768        self.entries.reserve_exact(more);
1769        Ok(())
1770    }
1771
1772    #[inline]
1773    fn raw_links(&mut self) -> RawLinks<T> {
1774        RawLinks(&mut self.entries[..] as *mut _)
1775    }
1776}
1777
1778/// Removes the `ExtraValue` at the given index.
1779#[inline]
1780fn remove_extra_value<T>(
1781    mut raw_links: RawLinks<T>,
1782    extra_values: &mut Vec<ExtraValue<T>>,
1783    idx: usize,
1784) -> ExtraValue<T> {
1785    let prev;
1786    let next;
1787
1788    {
1789        debug_assert!(extra_values.len() > idx);
1790        let extra = &extra_values[idx];
1791        prev = extra.prev;
1792        next = extra.next;
1793    }
1794
1795    // First unlink the extra value
1796    match (prev, next) {
1797        (Link::Entry(prev), Link::Entry(next)) => {
1798            debug_assert_eq!(prev, next);
1799
1800            raw_links[prev] = None;
1801        }
1802        (Link::Entry(prev), Link::Extra(next)) => {
1803            debug_assert!(raw_links[prev].is_some());
1804
1805            raw_links[prev].as_mut().unwrap().next = next;
1806
1807            debug_assert!(extra_values.len() > next);
1808            extra_values[next].prev = Link::Entry(prev);
1809        }
1810        (Link::Extra(prev), Link::Entry(next)) => {
1811            debug_assert!(raw_links[next].is_some());
1812
1813            raw_links[next].as_mut().unwrap().tail = prev;
1814
1815            debug_assert!(extra_values.len() > prev);
1816            extra_values[prev].next = Link::Entry(next);
1817        }
1818        (Link::Extra(prev), Link::Extra(next)) => {
1819            debug_assert!(extra_values.len() > next);
1820            debug_assert!(extra_values.len() > prev);
1821
1822            extra_values[prev].next = Link::Extra(next);
1823            extra_values[next].prev = Link::Extra(prev);
1824        }
1825    }
1826
1827    // Remove the extra value
1828    let mut extra = extra_values.swap_remove(idx);
1829
1830    // This is the index of the value that was moved (possibly `extra`)
1831    let old_idx = extra_values.len();
1832
1833    // Update the links
1834    if extra.prev == Link::Extra(old_idx) {
1835        extra.prev = Link::Extra(idx);
1836    }
1837
1838    if extra.next == Link::Extra(old_idx) {
1839        extra.next = Link::Extra(idx);
1840    }
1841
1842    // Check if another entry was displaced. If it was, then the links
1843    // need to be fixed.
1844    if idx != old_idx {
1845        let next;
1846        let prev;
1847
1848        {
1849            debug_assert!(extra_values.len() > idx);
1850            let moved = &extra_values[idx];
1851            next = moved.next;
1852            prev = moved.prev;
1853        }
1854
1855        // An entry was moved, we have to the links
1856        match prev {
1857            Link::Entry(entry_idx) => {
1858                // It is critical that we do not attempt to read the
1859                // header name or value as that memory may have been
1860                // "released" already.
1861                debug_assert!(raw_links[entry_idx].is_some());
1862
1863                let links = raw_links[entry_idx].as_mut().unwrap();
1864                links.next = idx;
1865            }
1866            Link::Extra(extra_idx) => {
1867                debug_assert!(extra_values.len() > extra_idx);
1868                extra_values[extra_idx].next = Link::Extra(idx);
1869            }
1870        }
1871
1872        match next {
1873            Link::Entry(entry_idx) => {
1874                debug_assert!(raw_links[entry_idx].is_some());
1875
1876                let links = raw_links[entry_idx].as_mut().unwrap();
1877                links.tail = idx;
1878            }
1879            Link::Extra(extra_idx) => {
1880                debug_assert!(extra_values.len() > extra_idx);
1881                extra_values[extra_idx].prev = Link::Extra(idx);
1882            }
1883        }
1884    }
1885
1886    debug_assert!({
1887        for v in &*extra_values {
1888            assert!(v.next != Link::Extra(old_idx));
1889            assert!(v.prev != Link::Extra(old_idx));
1890        }
1891
1892        true
1893    });
1894
1895    extra
1896}
1897
1898fn drain_all_extra_values<T>(
1899    raw_links: RawLinks<T>,
1900    extra_values: &mut Vec<ExtraValue<T>>,
1901    mut head: usize,
1902) -> Vec<T> {
1903    let mut vec = Vec::new();
1904    loop {
1905        let extra = remove_extra_value(raw_links, extra_values, head);
1906        vec.push(extra.value);
1907
1908        if let Link::Extra(idx) = extra.next {
1909            head = idx;
1910        } else {
1911            break;
1912        }
1913    }
1914    vec
1915}
1916
1917impl<'a, T> IntoIterator for &'a HeaderMap<T> {
1918    type Item = (&'a HeaderName, &'a T);
1919    type IntoIter = Iter<'a, T>;
1920
1921    fn into_iter(self) -> Iter<'a, T> {
1922        self.iter()
1923    }
1924}
1925
1926impl<'a, T> IntoIterator for &'a mut HeaderMap<T> {
1927    type Item = (&'a HeaderName, &'a mut T);
1928    type IntoIter = IterMut<'a, T>;
1929
1930    fn into_iter(self) -> IterMut<'a, T> {
1931        self.iter_mut()
1932    }
1933}
1934
1935impl<T> IntoIterator for HeaderMap<T> {
1936    type Item = (Option<HeaderName>, T);
1937    type IntoIter = IntoIter<T>;
1938
1939    /// Creates a consuming iterator, that is, one that moves keys and values
1940    /// out of the map in arbitrary order. The map cannot be used after calling
1941    /// this.
1942    ///
1943    /// For each yielded item that has `None` provided for the `HeaderName`,
1944    /// then the associated header name is the same as that of the previously
1945    /// yielded item. The first yielded item will have `HeaderName` set.
1946    ///
1947    /// # Examples
1948    ///
1949    /// Basic usage.
1950    ///
1951    /// ```
1952    /// # use http::header;
1953    /// # use http::header::*;
1954    /// let mut map = HeaderMap::new();
1955    /// map.insert(header::CONTENT_LENGTH, "123".parse().unwrap());
1956    /// map.insert(header::CONTENT_TYPE, "json".parse().unwrap());
1957    ///
1958    /// let mut iter = map.into_iter();
1959    /// assert_eq!(iter.next(), Some((Some(header::CONTENT_LENGTH), "123".parse().unwrap())));
1960    /// assert_eq!(iter.next(), Some((Some(header::CONTENT_TYPE), "json".parse().unwrap())));
1961    /// assert!(iter.next().is_none());
1962    /// ```
1963    ///
1964    /// Multiple values per key.
1965    ///
1966    /// ```
1967    /// # use http::header;
1968    /// # use http::header::*;
1969    /// let mut map = HeaderMap::new();
1970    ///
1971    /// map.append(header::CONTENT_LENGTH, "123".parse().unwrap());
1972    /// map.append(header::CONTENT_LENGTH, "456".parse().unwrap());
1973    ///
1974    /// map.append(header::CONTENT_TYPE, "json".parse().unwrap());
1975    /// map.append(header::CONTENT_TYPE, "html".parse().unwrap());
1976    /// map.append(header::CONTENT_TYPE, "xml".parse().unwrap());
1977    ///
1978    /// let mut iter = map.into_iter();
1979    ///
1980    /// assert_eq!(iter.next(), Some((Some(header::CONTENT_LENGTH), "123".parse().unwrap())));
1981    /// assert_eq!(iter.next(), Some((None, "456".parse().unwrap())));
1982    ///
1983    /// assert_eq!(iter.next(), Some((Some(header::CONTENT_TYPE), "json".parse().unwrap())));
1984    /// assert_eq!(iter.next(), Some((None, "html".parse().unwrap())));
1985    /// assert_eq!(iter.next(), Some((None, "xml".parse().unwrap())));
1986    /// assert!(iter.next().is_none());
1987    /// ```
1988    fn into_iter(self) -> IntoIter<T> {
1989        IntoIter {
1990            next: None,
1991            entries: self.entries.into_iter(),
1992            extra_values: self.extra_values,
1993        }
1994    }
1995}
1996
1997impl<T> FromIterator<(HeaderName, T)> for HeaderMap<T> {
1998    fn from_iter<I>(iter: I) -> Self
1999    where
2000        I: IntoIterator<Item = (HeaderName, T)>,
2001    {
2002        let mut map = HeaderMap::default();
2003        map.extend(iter);
2004        map
2005    }
2006}
2007
2008/// Try to convert a `HashMap` into a `HeaderMap`.
2009///
2010/// # Examples
2011///
2012/// ```
2013/// use std::collections::HashMap;
2014/// use std::convert::TryInto;
2015/// use http::HeaderMap;
2016///
2017/// let mut map = HashMap::new();
2018/// map.insert("X-Custom-Header".to_string(), "my value".to_string());
2019///
2020/// let headers: HeaderMap = (&map).try_into().expect("valid headers");
2021/// assert_eq!(headers["X-Custom-Header"], "my value");
2022/// ```
2023impl<'a, K, V, S, T> TryFrom<&'a HashMap<K, V, S>> for HeaderMap<T>
2024where
2025    K: Eq + Hash,
2026    HeaderName: TryFrom<&'a K>,
2027    <HeaderName as TryFrom<&'a K>>::Error: Into<crate::Error>,
2028    T: TryFrom<&'a V>,
2029    T::Error: Into<crate::Error>,
2030{
2031    type Error = Error;
2032
2033    fn try_from(c: &'a HashMap<K, V, S>) -> Result<Self, Self::Error> {
2034        c.iter()
2035            .map(|(k, v)| -> crate::Result<(HeaderName, T)> {
2036                let name = TryFrom::try_from(k).map_err(Into::into)?;
2037                let value = TryFrom::try_from(v).map_err(Into::into)?;
2038                Ok((name, value))
2039            })
2040            .collect()
2041    }
2042}
2043
2044impl<T> Extend<(Option<HeaderName>, T)> for HeaderMap<T> {
2045    /// Extend a `HeaderMap` with the contents of another `HeaderMap`.
2046    ///
2047    /// This function expects the yielded items to follow the same structure as
2048    /// `IntoIter`.
2049    ///
2050    /// # Panics
2051    ///
2052    /// This panics if the first yielded item does not have a `HeaderName`.
2053    ///
2054    /// # Examples
2055    ///
2056    /// ```
2057    /// # use http::header::*;
2058    /// let mut map = HeaderMap::new();
2059    ///
2060    /// map.insert(ACCEPT, "text/plain".parse().unwrap());
2061    /// map.insert(HOST, "hello.world".parse().unwrap());
2062    ///
2063    /// let mut extra = HeaderMap::new();
2064    ///
2065    /// extra.insert(HOST, "foo.bar".parse().unwrap());
2066    /// extra.insert(COOKIE, "hello".parse().unwrap());
2067    /// extra.append(COOKIE, "world".parse().unwrap());
2068    ///
2069    /// map.extend(extra);
2070    ///
2071    /// assert_eq!(map["host"], "foo.bar");
2072    /// assert_eq!(map["accept"], "text/plain");
2073    /// assert_eq!(map["cookie"], "hello");
2074    ///
2075    /// let v = map.get_all("host");
2076    /// assert_eq!(1, v.iter().count());
2077    ///
2078    /// let v = map.get_all("cookie");
2079    /// assert_eq!(2, v.iter().count());
2080    /// ```
2081    fn extend<I: IntoIterator<Item = (Option<HeaderName>, T)>>(&mut self, iter: I) {
2082        let mut iter = iter.into_iter();
2083
2084        // The structure of this is a bit weird, but it is mostly to make the
2085        // borrow checker happy.
2086        let (mut key, mut val) = match iter.next() {
2087            Some((Some(key), val)) => (key, val),
2088            Some((None, _)) => panic!("expected a header name, but got None"),
2089            None => return,
2090        };
2091
2092        'outer: loop {
2093            let mut entry = match self.try_entry2(key).expect("size overflows MAX_SIZE") {
2094                Entry::Occupied(mut e) => {
2095                    // Replace all previous values while maintaining a handle to
2096                    // the entry.
2097                    e.insert(val);
2098                    e
2099                }
2100                Entry::Vacant(e) => e.insert_entry(val),
2101            };
2102
2103            // As long as `HeaderName` is none, keep inserting the value into
2104            // the current entry
2105            loop {
2106                match iter.next() {
2107                    Some((Some(k), v)) => {
2108                        key = k;
2109                        val = v;
2110                        continue 'outer;
2111                    }
2112                    Some((None, v)) => {
2113                        entry.append(v);
2114                    }
2115                    None => {
2116                        return;
2117                    }
2118                }
2119            }
2120        }
2121    }
2122}
2123
2124impl<T> Extend<(HeaderName, T)> for HeaderMap<T> {
2125    fn extend<I: IntoIterator<Item = (HeaderName, T)>>(&mut self, iter: I) {
2126        // Keys may be already present or show multiple times in the iterator.
2127        // Reserve the entire hint lower bound if the map is empty.
2128        // Otherwise reserve half the hint (rounded up), so the map
2129        // will only resize twice in the worst case.
2130        let iter = iter.into_iter();
2131
2132        let reserve = if self.is_empty() {
2133            iter.size_hint().0
2134        } else {
2135            (iter.size_hint().0 + 1) / 2
2136        };
2137
2138        self.reserve(reserve);
2139
2140        for (k, v) in iter {
2141            self.append(k, v);
2142        }
2143    }
2144}
2145
2146impl<T: PartialEq> PartialEq for HeaderMap<T> {
2147    fn eq(&self, other: &HeaderMap<T>) -> bool {
2148        if self.len() != other.len() {
2149            return false;
2150        }
2151
2152        self.keys()
2153            .all(|key| self.get_all(key) == other.get_all(key))
2154    }
2155}
2156
2157impl<T: Eq> Eq for HeaderMap<T> {}
2158
2159impl<T: fmt::Debug> fmt::Debug for HeaderMap<T> {
2160    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2161        f.debug_map().entries(self.iter()).finish()
2162    }
2163}
2164
2165impl<T> Default for HeaderMap<T> {
2166    fn default() -> Self {
2167        HeaderMap::try_with_capacity(0).expect("zero capacity should never fail")
2168    }
2169}
2170
2171impl<K, T> ops::Index<K> for HeaderMap<T>
2172where
2173    K: AsHeaderName,
2174{
2175    type Output = T;
2176
2177    /// # Panics
2178    /// Using the index operator will cause a panic if the header you're querying isn't set.
2179    #[inline]
2180    fn index(&self, index: K) -> &T {
2181        match self.get2(&index) {
2182            Some(val) => val,
2183            None => panic!("no entry found for key {:?}", index.as_str()),
2184        }
2185    }
2186}
2187
2188/// phase 2 is post-insert where we forward-shift `Pos` in the indices.
2189///
2190/// returns the number of displaced elements
2191#[inline]
2192fn do_insert_phase_two(indices: &mut [Pos], mut probe: usize, mut old_pos: Pos) -> usize {
2193    let mut num_displaced = 0;
2194
2195    probe_loop!(probe < indices.len(), {
2196        let pos = &mut indices[probe];
2197
2198        if pos.is_none() {
2199            *pos = old_pos;
2200            break;
2201        } else {
2202            num_displaced += 1;
2203            old_pos = mem::replace(pos, old_pos);
2204        }
2205    });
2206
2207    num_displaced
2208}
2209
2210#[inline]
2211fn append_value<T>(
2212    entry_idx: usize,
2213    entry: &mut Bucket<T>,
2214    extra: &mut Vec<ExtraValue<T>>,
2215    value: T,
2216) {
2217    match entry.links {
2218        Some(links) => {
2219            let idx = extra.len();
2220            extra.push(ExtraValue {
2221                value,
2222                prev: Link::Extra(links.tail),
2223                next: Link::Entry(entry_idx),
2224            });
2225
2226            extra[links.tail].next = Link::Extra(idx);
2227
2228            entry.links = Some(Links { tail: idx, ..links });
2229        }
2230        None => {
2231            let idx = extra.len();
2232            extra.push(ExtraValue {
2233                value,
2234                prev: Link::Entry(entry_idx),
2235                next: Link::Entry(entry_idx),
2236            });
2237
2238            entry.links = Some(Links {
2239                next: idx,
2240                tail: idx,
2241            });
2242        }
2243    }
2244}
2245
2246// ===== impl Iter =====
2247
2248impl<'a, T> Iterator for Iter<'a, T> {
2249    type Item = (&'a HeaderName, &'a T);
2250
2251    fn next(&mut self) -> Option<Self::Item> {
2252        use self::Cursor::*;
2253
2254        if self.cursor.is_none() {
2255            if (self.entry + 1) >= self.map.entries.len() {
2256                return None;
2257            }
2258
2259            self.entry += 1;
2260            self.cursor = Some(Cursor::Head);
2261        }
2262
2263        let entry = &self.map.entries[self.entry];
2264
2265        match self.cursor.unwrap() {
2266            Head => {
2267                self.cursor = entry.links.map(|l| Values(l.next));
2268                Some((&entry.key, &entry.value))
2269            }
2270            Values(idx) => {
2271                let extra = &self.map.extra_values[idx];
2272
2273                match extra.next {
2274                    Link::Entry(_) => self.cursor = None,
2275                    Link::Extra(i) => self.cursor = Some(Values(i)),
2276                }
2277
2278                Some((&entry.key, &extra.value))
2279            }
2280        }
2281    }
2282
2283    fn size_hint(&self) -> (usize, Option<usize>) {
2284        let map = self.map;
2285        debug_assert!(map.entries.len() >= self.entry);
2286
2287        let lower = map.entries.len() - self.entry;
2288        // We could pessimistically guess at the upper bound, saying
2289        // that its lower + map.extra_values.len(). That could be
2290        // way over though, such as if we're near the end, and have
2291        // already gone through several extra values...
2292        (lower, None)
2293    }
2294}
2295
2296impl<'a, T> FusedIterator for Iter<'a, T> {}
2297
2298unsafe impl<'a, T: Sync> Sync for Iter<'a, T> {}
2299unsafe impl<'a, T: Sync> Send for Iter<'a, T> {}
2300
2301// ===== impl IterMut =====
2302
2303impl<'a, T> IterMut<'a, T> {
2304    fn next_unsafe(&mut self) -> Option<(&'a HeaderName, *mut T)> {
2305        use self::Cursor::*;
2306
2307        if self.cursor.is_none() {
2308            if (self.entry + 1) >= unsafe { &*self.map }.entries.len() {
2309                return None;
2310            }
2311
2312            self.entry += 1;
2313            self.cursor = Some(Cursor::Head);
2314        }
2315
2316        let entry = unsafe { &mut (*self.map).entries[self.entry] };
2317
2318        match self.cursor.unwrap() {
2319            Head => {
2320                self.cursor = entry.links.map(|l| Values(l.next));
2321                Some((&entry.key, &mut entry.value as *mut _))
2322            }
2323            Values(idx) => {
2324                let extra = unsafe { &mut (*self.map).extra_values[idx] };
2325
2326                match extra.next {
2327                    Link::Entry(_) => self.cursor = None,
2328                    Link::Extra(i) => self.cursor = Some(Values(i)),
2329                }
2330
2331                Some((&entry.key, &mut extra.value as *mut _))
2332            }
2333        }
2334    }
2335}
2336
2337impl<'a, T> Iterator for IterMut<'a, T> {
2338    type Item = (&'a HeaderName, &'a mut T);
2339
2340    fn next(&mut self) -> Option<Self::Item> {
2341        self.next_unsafe()
2342            .map(|(key, ptr)| (key, unsafe { &mut *ptr }))
2343    }
2344
2345    fn size_hint(&self) -> (usize, Option<usize>) {
2346        let map = unsafe { &*self.map };
2347        debug_assert!(map.entries.len() >= self.entry);
2348
2349        let lower = map.entries.len() - self.entry;
2350        // We could pessimistically guess at the upper bound, saying
2351        // that its lower + map.extra_values.len(). That could be
2352        // way over though, such as if we're near the end, and have
2353        // already gone through several extra values...
2354        (lower, None)
2355    }
2356}
2357
2358impl<'a, T> FusedIterator for IterMut<'a, T> {}
2359
2360unsafe impl<'a, T: Sync> Sync for IterMut<'a, T> {}
2361unsafe impl<'a, T: Send> Send for IterMut<'a, T> {}
2362
2363// ===== impl Keys =====
2364
2365impl<'a, T> Iterator for Keys<'a, T> {
2366    type Item = &'a HeaderName;
2367
2368    fn next(&mut self) -> Option<Self::Item> {
2369        self.inner.next().map(|b| &b.key)
2370    }
2371
2372    fn size_hint(&self) -> (usize, Option<usize>) {
2373        self.inner.size_hint()
2374    }
2375
2376    fn nth(&mut self, n: usize) -> Option<Self::Item> {
2377        self.inner.nth(n).map(|b| &b.key)
2378    }
2379
2380    fn count(self) -> usize {
2381        self.inner.count()
2382    }
2383
2384    fn last(self) -> Option<Self::Item> {
2385        self.inner.last().map(|b| &b.key)
2386    }
2387}
2388
2389impl<'a, T> ExactSizeIterator for Keys<'a, T> {}
2390impl<'a, T> FusedIterator for Keys<'a, T> {}
2391
2392// ===== impl Values ====
2393
2394impl<'a, T> Iterator for Values<'a, T> {
2395    type Item = &'a T;
2396
2397    fn next(&mut self) -> Option<Self::Item> {
2398        self.inner.next().map(|(_, v)| v)
2399    }
2400
2401    fn size_hint(&self) -> (usize, Option<usize>) {
2402        self.inner.size_hint()
2403    }
2404}
2405
2406impl<'a, T> FusedIterator for Values<'a, T> {}
2407
2408// ===== impl ValuesMut ====
2409
2410impl<'a, T> Iterator for ValuesMut<'a, T> {
2411    type Item = &'a mut T;
2412
2413    fn next(&mut self) -> Option<Self::Item> {
2414        self.inner.next().map(|(_, v)| v)
2415    }
2416
2417    fn size_hint(&self) -> (usize, Option<usize>) {
2418        self.inner.size_hint()
2419    }
2420}
2421
2422impl<'a, T> FusedIterator for ValuesMut<'a, T> {}
2423
2424// ===== impl Drain =====
2425
2426impl<'a, T> Iterator for Drain<'a, T> {
2427    type Item = (Option<HeaderName>, T);
2428
2429    fn next(&mut self) -> Option<Self::Item> {
2430        if let Some(next) = self.next {
2431            // Remove the extra value
2432
2433            let raw_links = RawLinks(self.entries);
2434            let extra = unsafe { remove_extra_value(raw_links, &mut *self.extra_values, next) };
2435
2436            match extra.next {
2437                Link::Extra(idx) => self.next = Some(idx),
2438                Link::Entry(_) => self.next = None,
2439            }
2440
2441            return Some((None, extra.value));
2442        }
2443
2444        let idx = self.idx;
2445
2446        if idx == self.len {
2447            return None;
2448        }
2449
2450        self.idx += 1;
2451
2452        unsafe {
2453            let entry = &(*self.entries)[idx];
2454
2455            // Read the header name
2456            let key = ptr::read(&entry.key as *const _);
2457            let value = ptr::read(&entry.value as *const _);
2458            self.next = entry.links.map(|l| l.next);
2459
2460            Some((Some(key), value))
2461        }
2462    }
2463
2464    fn size_hint(&self) -> (usize, Option<usize>) {
2465        // At least this many names... It's unknown if the user wants
2466        // to count the extra_values on top.
2467        //
2468        // For instance, extending a new `HeaderMap` wouldn't need to
2469        // reserve the upper-bound in `entries`, only the lower-bound.
2470        let lower = self.len - self.idx;
2471        let upper = unsafe { (*self.extra_values).len() } + lower;
2472        (lower, Some(upper))
2473    }
2474}
2475
2476impl<'a, T> FusedIterator for Drain<'a, T> {}
2477
2478impl<'a, T> Drop for Drain<'a, T> {
2479    fn drop(&mut self) {
2480        for _ in self {}
2481    }
2482}
2483
2484unsafe impl<'a, T: Sync> Sync for Drain<'a, T> {}
2485unsafe impl<'a, T: Send> Send for Drain<'a, T> {}
2486
2487// ===== impl Entry =====
2488
2489impl<'a, T> Entry<'a, T> {
2490    /// Ensures a value is in the entry by inserting the default if empty.
2491    ///
2492    /// Returns a mutable reference to the **first** value in the entry.
2493    ///
2494    /// # Panics
2495    ///
2496    /// This method panics if capacity exceeds max `HeaderMap` capacity
2497    ///
2498    /// # Examples
2499    ///
2500    /// ```
2501    /// # use http::HeaderMap;
2502    /// let mut map: HeaderMap<u32> = HeaderMap::default();
2503    ///
2504    /// let headers = &[
2505    ///     "content-length",
2506    ///     "x-hello",
2507    ///     "Content-Length",
2508    ///     "x-world",
2509    /// ];
2510    ///
2511    /// for &header in headers {
2512    ///     let counter = map.entry(header)
2513    ///         .or_insert(0);
2514    ///     *counter += 1;
2515    /// }
2516    ///
2517    /// assert_eq!(map["content-length"], 2);
2518    /// assert_eq!(map["x-hello"], 1);
2519    /// ```
2520    pub fn or_insert(self, default: T) -> &'a mut T {
2521        self.or_try_insert(default)
2522            .expect("size overflows MAX_SIZE")
2523    }
2524
2525    /// Ensures a value is in the entry by inserting the default if empty.
2526    ///
2527    /// Returns a mutable reference to the **first** value in the entry.
2528    ///
2529    /// # Errors
2530    ///
2531    /// This function may return an error if `HeaderMap` exceeds max capacity
2532    ///
2533    /// # Examples
2534    ///
2535    /// ```
2536    /// # use http::HeaderMap;
2537    /// let mut map: HeaderMap<u32> = HeaderMap::default();
2538    ///
2539    /// let headers = &[
2540    ///     "content-length",
2541    ///     "x-hello",
2542    ///     "Content-Length",
2543    ///     "x-world",
2544    /// ];
2545    ///
2546    /// for &header in headers {
2547    ///     let counter = map.entry(header)
2548    ///         .or_try_insert(0)
2549    ///         .unwrap();
2550    ///     *counter += 1;
2551    /// }
2552    ///
2553    /// assert_eq!(map["content-length"], 2);
2554    /// assert_eq!(map["x-hello"], 1);
2555    /// ```
2556    pub fn or_try_insert(self, default: T) -> Result<&'a mut T, MaxSizeReached> {
2557        use self::Entry::*;
2558
2559        match self {
2560            Occupied(e) => Ok(e.into_mut()),
2561            Vacant(e) => e.try_insert(default),
2562        }
2563    }
2564
2565    /// Ensures a value is in the entry by inserting the result of the default
2566    /// function if empty.
2567    ///
2568    /// The default function is not called if the entry exists in the map.
2569    /// Returns a mutable reference to the **first** value in the entry.
2570    ///
2571    /// # Examples
2572    ///
2573    /// Basic usage.
2574    ///
2575    /// ```
2576    /// # use http::HeaderMap;
2577    /// let mut map = HeaderMap::new();
2578    ///
2579    /// let res = map.entry("x-hello")
2580    ///     .or_insert_with(|| "world".parse().unwrap());
2581    ///
2582    /// assert_eq!(res, "world");
2583    /// ```
2584    ///
2585    /// The default function is not called if the entry exists in the map.
2586    ///
2587    /// ```
2588    /// # use http::HeaderMap;
2589    /// # use http::header::HOST;
2590    /// let mut map = HeaderMap::new();
2591    /// map.try_insert(HOST, "world".parse().unwrap()).unwrap();
2592    ///
2593    /// let res = map.try_entry("host")
2594    ///     .unwrap()
2595    ///     .or_try_insert_with(|| unreachable!())
2596    ///     .unwrap();
2597    ///
2598    ///
2599    /// assert_eq!(res, "world");
2600    /// ```
2601    pub fn or_insert_with<F: FnOnce() -> T>(self, default: F) -> &'a mut T {
2602        self.or_try_insert_with(default)
2603            .expect("size overflows MAX_SIZE")
2604    }
2605
2606    /// Ensures a value is in the entry by inserting the result of the default
2607    /// function if empty.
2608    ///
2609    /// The default function is not called if the entry exists in the map.
2610    /// Returns a mutable reference to the **first** value in the entry.
2611    ///
2612    /// # Examples
2613    ///
2614    /// Basic usage.
2615    ///
2616    /// ```
2617    /// # use http::HeaderMap;
2618    /// let mut map = HeaderMap::new();
2619    ///
2620    /// let res = map.entry("x-hello")
2621    ///     .or_insert_with(|| "world".parse().unwrap());
2622    ///
2623    /// assert_eq!(res, "world");
2624    /// ```
2625    ///
2626    /// The default function is not called if the entry exists in the map.
2627    ///
2628    /// ```
2629    /// # use http::HeaderMap;
2630    /// # use http::header::HOST;
2631    /// let mut map = HeaderMap::new();
2632    /// map.try_insert(HOST, "world".parse().unwrap()).unwrap();
2633    ///
2634    /// let res = map.try_entry("host")
2635    ///     .unwrap()
2636    ///     .or_try_insert_with(|| unreachable!())
2637    ///     .unwrap();
2638    ///
2639    ///
2640    /// assert_eq!(res, "world");
2641    /// ```
2642    pub fn or_try_insert_with<F: FnOnce() -> T>(
2643        self,
2644        default: F,
2645    ) -> Result<&'a mut T, MaxSizeReached> {
2646        use self::Entry::*;
2647
2648        match self {
2649            Occupied(e) => Ok(e.into_mut()),
2650            Vacant(e) => e.try_insert(default()),
2651        }
2652    }
2653
2654    /// Returns a reference to the entry's key
2655    ///
2656    /// # Examples
2657    ///
2658    /// ```
2659    /// # use http::HeaderMap;
2660    /// let mut map = HeaderMap::new();
2661    ///
2662    /// assert_eq!(map.entry("x-hello").key(), "x-hello");
2663    /// ```
2664    pub fn key(&self) -> &HeaderName {
2665        use self::Entry::*;
2666
2667        match *self {
2668            Vacant(ref e) => e.key(),
2669            Occupied(ref e) => e.key(),
2670        }
2671    }
2672}
2673
2674// ===== impl VacantEntry =====
2675
2676impl<'a, T> VacantEntry<'a, T> {
2677    /// Returns a reference to the entry's key
2678    ///
2679    /// # Examples
2680    ///
2681    /// ```
2682    /// # use http::HeaderMap;
2683    /// let mut map = HeaderMap::new();
2684    ///
2685    /// assert_eq!(map.entry("x-hello").key().as_str(), "x-hello");
2686    /// ```
2687    pub fn key(&self) -> &HeaderName {
2688        &self.key
2689    }
2690
2691    /// Take ownership of the key
2692    ///
2693    /// # Examples
2694    ///
2695    /// ```
2696    /// # use http::header::{HeaderMap, Entry};
2697    /// let mut map = HeaderMap::new();
2698    ///
2699    /// if let Entry::Vacant(v) = map.entry("x-hello") {
2700    ///     assert_eq!(v.into_key().as_str(), "x-hello");
2701    /// }
2702    /// ```
2703    pub fn into_key(self) -> HeaderName {
2704        self.key
2705    }
2706
2707    /// Insert the value into the entry.
2708    ///
2709    /// The value will be associated with this entry's key. A mutable reference
2710    /// to the inserted value will be returned.
2711    ///
2712    /// # Examples
2713    ///
2714    /// ```
2715    /// # use http::header::{HeaderMap, Entry};
2716    /// let mut map = HeaderMap::new();
2717    ///
2718    /// if let Entry::Vacant(v) = map.entry("x-hello") {
2719    ///     v.insert("world".parse().unwrap());
2720    /// }
2721    ///
2722    /// assert_eq!(map["x-hello"], "world");
2723    /// ```
2724    pub fn insert(self, value: T) -> &'a mut T {
2725        self.try_insert(value).expect("size overflows MAX_SIZE")
2726    }
2727
2728    /// Insert the value into the entry.
2729    ///
2730    /// The value will be associated with this entry's key. A mutable reference
2731    /// to the inserted value will be returned.
2732    ///
2733    /// # Examples
2734    ///
2735    /// ```
2736    /// # use http::header::{HeaderMap, Entry};
2737    /// let mut map = HeaderMap::new();
2738    ///
2739    /// if let Entry::Vacant(v) = map.entry("x-hello") {
2740    ///     v.insert("world".parse().unwrap());
2741    /// }
2742    ///
2743    /// assert_eq!(map["x-hello"], "world");
2744    /// ```
2745    pub fn try_insert(self, value: T) -> Result<&'a mut T, MaxSizeReached> {
2746        // Ensure that there is space in the map
2747        let index =
2748            self.map
2749                .try_insert_phase_two(self.key, value, self.hash, self.probe, self.danger)?;
2750
2751        Ok(&mut self.map.entries[index].value)
2752    }
2753
2754    /// Insert the value into the entry.
2755    ///
2756    /// The value will be associated with this entry's key. The new
2757    /// `OccupiedEntry` is returned, allowing for further manipulation.
2758    ///
2759    /// # Examples
2760    ///
2761    /// ```
2762    /// # use http::header::*;
2763    /// let mut map = HeaderMap::new();
2764    ///
2765    /// if let Entry::Vacant(v) = map.try_entry("x-hello").unwrap() {
2766    ///     let mut e = v.try_insert_entry("world".parse().unwrap()).unwrap();
2767    ///     e.insert("world2".parse().unwrap());
2768    /// }
2769    ///
2770    /// assert_eq!(map["x-hello"], "world2");
2771    /// ```
2772    pub fn insert_entry(self, value: T) -> OccupiedEntry<'a, T> {
2773        self.try_insert_entry(value)
2774            .expect("size overflows MAX_SIZE")
2775    }
2776
2777    /// Insert the value into the entry.
2778    ///
2779    /// The value will be associated with this entry's key. The new
2780    /// `OccupiedEntry` is returned, allowing for further manipulation.
2781    ///
2782    /// # Examples
2783    ///
2784    /// ```
2785    /// # use http::header::*;
2786    /// let mut map = HeaderMap::new();
2787    ///
2788    /// if let Entry::Vacant(v) = map.try_entry("x-hello").unwrap() {
2789    ///     let mut e = v.try_insert_entry("world".parse().unwrap()).unwrap();
2790    ///     e.insert("world2".parse().unwrap());
2791    /// }
2792    ///
2793    /// assert_eq!(map["x-hello"], "world2");
2794    /// ```
2795    pub fn try_insert_entry(self, value: T) -> Result<OccupiedEntry<'a, T>, MaxSizeReached> {
2796        // Ensure that there is space in the map
2797        let index =
2798            self.map
2799                .try_insert_phase_two(self.key, value, self.hash, self.probe, self.danger)?;
2800
2801        Ok(OccupiedEntry {
2802            map: self.map,
2803            index,
2804            probe: self.probe,
2805        })
2806    }
2807}
2808
2809// ===== impl GetAll =====
2810
2811impl<'a, T: 'a> GetAll<'a, T> {
2812    /// Returns an iterator visiting all values associated with the entry.
2813    ///
2814    /// Values are iterated in insertion order.
2815    ///
2816    /// # Examples
2817    ///
2818    /// ```
2819    /// # use http::HeaderMap;
2820    /// # use http::header::HOST;
2821    /// let mut map = HeaderMap::new();
2822    /// map.insert(HOST, "hello.world".parse().unwrap());
2823    /// map.append(HOST, "hello.earth".parse().unwrap());
2824    ///
2825    /// let values = map.get_all("host");
2826    /// let mut iter = values.iter();
2827    /// assert_eq!(&"hello.world", iter.next().unwrap());
2828    /// assert_eq!(&"hello.earth", iter.next().unwrap());
2829    /// assert!(iter.next().is_none());
2830    /// ```
2831    pub fn iter(&self) -> ValueIter<'a, T> {
2832        // This creates a new GetAll struct so that the lifetime
2833        // isn't bound to &self.
2834        GetAll {
2835            map: self.map,
2836            index: self.index,
2837        }
2838        .into_iter()
2839    }
2840}
2841
2842impl<'a, T: PartialEq> PartialEq for GetAll<'a, T> {
2843    fn eq(&self, other: &Self) -> bool {
2844        self.iter().eq(other.iter())
2845    }
2846}
2847
2848impl<'a, T> IntoIterator for GetAll<'a, T> {
2849    type Item = &'a T;
2850    type IntoIter = ValueIter<'a, T>;
2851
2852    fn into_iter(self) -> ValueIter<'a, T> {
2853        self.map.value_iter(self.index)
2854    }
2855}
2856
2857impl<'a, 'b: 'a, T> IntoIterator for &'b GetAll<'a, T> {
2858    type Item = &'a T;
2859    type IntoIter = ValueIter<'a, T>;
2860
2861    fn into_iter(self) -> ValueIter<'a, T> {
2862        self.map.value_iter(self.index)
2863    }
2864}
2865
2866// ===== impl ValueIter =====
2867
2868impl<'a, T: 'a> Iterator for ValueIter<'a, T> {
2869    type Item = &'a T;
2870
2871    fn next(&mut self) -> Option<Self::Item> {
2872        use self::Cursor::*;
2873
2874        match self.front {
2875            Some(Head) => {
2876                let entry = &self.map.entries[self.index];
2877
2878                if self.back == Some(Head) {
2879                    self.front = None;
2880                    self.back = None;
2881                } else {
2882                    // Update the iterator state
2883                    match entry.links {
2884                        Some(links) => {
2885                            self.front = Some(Values(links.next));
2886                        }
2887                        None => unreachable!(),
2888                    }
2889                }
2890
2891                Some(&entry.value)
2892            }
2893            Some(Values(idx)) => {
2894                let extra = &self.map.extra_values[idx];
2895
2896                if self.front == self.back {
2897                    self.front = None;
2898                    self.back = None;
2899                } else {
2900                    match extra.next {
2901                        Link::Entry(_) => self.front = None,
2902                        Link::Extra(i) => self.front = Some(Values(i)),
2903                    }
2904                }
2905
2906                Some(&extra.value)
2907            }
2908            None => None,
2909        }
2910    }
2911
2912    fn size_hint(&self) -> (usize, Option<usize>) {
2913        match (self.front, self.back) {
2914            // Exactly 1 value...
2915            (Some(Cursor::Head), Some(Cursor::Head)) => (1, Some(1)),
2916            // At least 1...
2917            (Some(_), _) => (1, None),
2918            // No more values...
2919            (None, _) => (0, Some(0)),
2920        }
2921    }
2922}
2923
2924impl<'a, T: 'a> DoubleEndedIterator for ValueIter<'a, T> {
2925    fn next_back(&mut self) -> Option<Self::Item> {
2926        use self::Cursor::*;
2927
2928        match self.back {
2929            Some(Head) => {
2930                self.front = None;
2931                self.back = None;
2932                Some(&self.map.entries[self.index].value)
2933            }
2934            Some(Values(idx)) => {
2935                let extra = &self.map.extra_values[idx];
2936
2937                if self.front == self.back {
2938                    self.front = None;
2939                    self.back = None;
2940                } else {
2941                    match extra.prev {
2942                        Link::Entry(_) => self.back = Some(Head),
2943                        Link::Extra(idx) => self.back = Some(Values(idx)),
2944                    }
2945                }
2946
2947                Some(&extra.value)
2948            }
2949            None => None,
2950        }
2951    }
2952}
2953
2954impl<'a, T> FusedIterator for ValueIter<'a, T> {}
2955
2956// ===== impl ValueIterMut =====
2957
2958impl<'a, T: 'a> Iterator for ValueIterMut<'a, T> {
2959    type Item = &'a mut T;
2960
2961    fn next(&mut self) -> Option<Self::Item> {
2962        use self::Cursor::*;
2963
2964        let entry = unsafe { &mut (*self.map).entries[self.index] };
2965
2966        match self.front {
2967            Some(Head) => {
2968                if self.back == Some(Head) {
2969                    self.front = None;
2970                    self.back = None;
2971                } else {
2972                    // Update the iterator state
2973                    match entry.links {
2974                        Some(links) => {
2975                            self.front = Some(Values(links.next));
2976                        }
2977                        None => unreachable!(),
2978                    }
2979                }
2980
2981                Some(&mut entry.value)
2982            }
2983            Some(Values(idx)) => {
2984                let extra = unsafe { &mut (*self.map).extra_values[idx] };
2985
2986                if self.front == self.back {
2987                    self.front = None;
2988                    self.back = None;
2989                } else {
2990                    match extra.next {
2991                        Link::Entry(_) => self.front = None,
2992                        Link::Extra(i) => self.front = Some(Values(i)),
2993                    }
2994                }
2995
2996                Some(&mut extra.value)
2997            }
2998            None => None,
2999        }
3000    }
3001}
3002
3003impl<'a, T: 'a> DoubleEndedIterator for ValueIterMut<'a, T> {
3004    fn next_back(&mut self) -> Option<Self::Item> {
3005        use self::Cursor::*;
3006
3007        let entry = unsafe { &mut (*self.map).entries[self.index] };
3008
3009        match self.back {
3010            Some(Head) => {
3011                self.front = None;
3012                self.back = None;
3013                Some(&mut entry.value)
3014            }
3015            Some(Values(idx)) => {
3016                let extra = unsafe { &mut (*self.map).extra_values[idx] };
3017
3018                if self.front == self.back {
3019                    self.front = None;
3020                    self.back = None;
3021                } else {
3022                    match extra.prev {
3023                        Link::Entry(_) => self.back = Some(Head),
3024                        Link::Extra(idx) => self.back = Some(Values(idx)),
3025                    }
3026                }
3027
3028                Some(&mut extra.value)
3029            }
3030            None => None,
3031        }
3032    }
3033}
3034
3035impl<'a, T> FusedIterator for ValueIterMut<'a, T> {}
3036
3037unsafe impl<'a, T: Sync> Sync for ValueIterMut<'a, T> {}
3038unsafe impl<'a, T: Send> Send for ValueIterMut<'a, T> {}
3039
3040// ===== impl IntoIter =====
3041
3042impl<T> Iterator for IntoIter<T> {
3043    type Item = (Option<HeaderName>, T);
3044
3045    fn next(&mut self) -> Option<Self::Item> {
3046        if let Some(next) = self.next {
3047            self.next = match self.extra_values[next].next {
3048                Link::Entry(_) => None,
3049                Link::Extra(v) => Some(v),
3050            };
3051
3052            let value = unsafe { ptr::read(&self.extra_values[next].value) };
3053
3054            return Some((None, value));
3055        }
3056
3057        if let Some(bucket) = self.entries.next() {
3058            self.next = bucket.links.map(|l| l.next);
3059            let name = Some(bucket.key);
3060            let value = bucket.value;
3061
3062            return Some((name, value));
3063        }
3064
3065        None
3066    }
3067
3068    fn size_hint(&self) -> (usize, Option<usize>) {
3069        let (lower, _) = self.entries.size_hint();
3070        // There could be more than just the entries upper, as there
3071        // could be items in the `extra_values`. We could guess, saying
3072        // `upper + extra_values.len()`, but that could overestimate by a lot.
3073        (lower, None)
3074    }
3075}
3076
3077impl<T> FusedIterator for IntoIter<T> {}
3078
3079impl<T> Drop for IntoIter<T> {
3080    fn drop(&mut self) {
3081        // Ensure the iterator is consumed
3082        for _ in self.by_ref() {}
3083
3084        // All the values have already been yielded out.
3085        unsafe {
3086            self.extra_values.set_len(0);
3087        }
3088    }
3089}
3090
3091// ===== impl OccupiedEntry =====
3092
3093impl<'a, T> OccupiedEntry<'a, T> {
3094    /// Returns a reference to the entry's key.
3095    ///
3096    /// # Examples
3097    ///
3098    /// ```
3099    /// # use http::header::{HeaderMap, Entry, HOST};
3100    /// let mut map = HeaderMap::new();
3101    /// map.insert(HOST, "world".parse().unwrap());
3102    ///
3103    /// if let Entry::Occupied(e) = map.entry("host") {
3104    ///     assert_eq!("host", e.key());
3105    /// }
3106    /// ```
3107    pub fn key(&self) -> &HeaderName {
3108        &self.map.entries[self.index].key
3109    }
3110
3111    /// Get a reference to the first value in the entry.
3112    ///
3113    /// Values are stored in insertion order.
3114    ///
3115    /// # Panics
3116    ///
3117    /// `get` panics if there are no values associated with the entry.
3118    ///
3119    /// # Examples
3120    ///
3121    /// ```
3122    /// # use http::header::{HeaderMap, Entry, HOST};
3123    /// let mut map = HeaderMap::new();
3124    /// map.insert(HOST, "hello.world".parse().unwrap());
3125    ///
3126    /// if let Entry::Occupied(mut e) = map.entry("host") {
3127    ///     assert_eq!(e.get(), &"hello.world");
3128    ///
3129    ///     e.append("hello.earth".parse().unwrap());
3130    ///
3131    ///     assert_eq!(e.get(), &"hello.world");
3132    /// }
3133    /// ```
3134    pub fn get(&self) -> &T {
3135        &self.map.entries[self.index].value
3136    }
3137
3138    /// Get a mutable reference to the first value in the entry.
3139    ///
3140    /// Values are stored in insertion order.
3141    ///
3142    /// # Panics
3143    ///
3144    /// `get_mut` panics if there are no values associated with the entry.
3145    ///
3146    /// # Examples
3147    ///
3148    /// ```
3149    /// # use http::header::{HeaderMap, Entry, HOST};
3150    /// let mut map = HeaderMap::default();
3151    /// map.insert(HOST, "hello.world".to_string());
3152    ///
3153    /// if let Entry::Occupied(mut e) = map.entry("host") {
3154    ///     e.get_mut().push_str("-2");
3155    ///     assert_eq!(e.get(), &"hello.world-2");
3156    /// }
3157    /// ```
3158    pub fn get_mut(&mut self) -> &mut T {
3159        &mut self.map.entries[self.index].value
3160    }
3161
3162    /// Converts the `OccupiedEntry` into a mutable reference to the **first**
3163    /// value.
3164    ///
3165    /// The lifetime of the returned reference is bound to the original map.
3166    ///
3167    /// # Panics
3168    ///
3169    /// `into_mut` panics if there are no values associated with the entry.
3170    ///
3171    /// # Examples
3172    ///
3173    /// ```
3174    /// # use http::header::{HeaderMap, Entry, HOST};
3175    /// let mut map = HeaderMap::default();
3176    /// map.insert(HOST, "hello.world".to_string());
3177    /// map.append(HOST, "hello.earth".to_string());
3178    ///
3179    /// if let Entry::Occupied(e) = map.entry("host") {
3180    ///     e.into_mut().push_str("-2");
3181    /// }
3182    ///
3183    /// assert_eq!("hello.world-2", map["host"]);
3184    /// ```
3185    pub fn into_mut(self) -> &'a mut T {
3186        &mut self.map.entries[self.index].value
3187    }
3188
3189    /// Sets the value of the entry.
3190    ///
3191    /// All previous values associated with the entry are removed and the first
3192    /// one is returned. See `insert_mult` for an API that returns all values.
3193    ///
3194    /// # Examples
3195    ///
3196    /// ```
3197    /// # use http::header::{HeaderMap, Entry, HOST};
3198    /// let mut map = HeaderMap::new();
3199    /// map.insert(HOST, "hello.world".parse().unwrap());
3200    ///
3201    /// if let Entry::Occupied(mut e) = map.entry("host") {
3202    ///     let mut prev = e.insert("earth".parse().unwrap());
3203    ///     assert_eq!("hello.world", prev);
3204    /// }
3205    ///
3206    /// assert_eq!("earth", map["host"]);
3207    /// ```
3208    pub fn insert(&mut self, value: T) -> T {
3209        self.map.insert_occupied(self.index, value)
3210    }
3211
3212    /// Sets the value of the entry.
3213    ///
3214    /// This function does the same as `insert` except it returns an iterator
3215    /// that yields all values previously associated with the key.
3216    ///
3217    /// # Examples
3218    ///
3219    /// ```
3220    /// # use http::header::{HeaderMap, Entry, HOST};
3221    /// let mut map = HeaderMap::new();
3222    /// map.insert(HOST, "world".parse().unwrap());
3223    /// map.append(HOST, "world2".parse().unwrap());
3224    ///
3225    /// if let Entry::Occupied(mut e) = map.entry("host") {
3226    ///     let mut prev = e.insert_mult("earth".parse().unwrap());
3227    ///     assert_eq!("world", prev.next().unwrap());
3228    ///     assert_eq!("world2", prev.next().unwrap());
3229    ///     assert!(prev.next().is_none());
3230    /// }
3231    ///
3232    /// assert_eq!("earth", map["host"]);
3233    /// ```
3234    pub fn insert_mult(&mut self, value: T) -> ValueDrain<'_, T> {
3235        self.map.insert_occupied_mult(self.index, value)
3236    }
3237
3238    /// Insert the value into the entry.
3239    ///
3240    /// The new value is appended to the end of the entry's value list. All
3241    /// previous values associated with the entry are retained.
3242    ///
3243    /// # Examples
3244    ///
3245    /// ```
3246    /// # use http::header::{HeaderMap, Entry, HOST};
3247    /// let mut map = HeaderMap::new();
3248    /// map.insert(HOST, "world".parse().unwrap());
3249    ///
3250    /// if let Entry::Occupied(mut e) = map.entry("host") {
3251    ///     e.append("earth".parse().unwrap());
3252    /// }
3253    ///
3254    /// let values = map.get_all("host");
3255    /// let mut i = values.iter();
3256    /// assert_eq!("world", *i.next().unwrap());
3257    /// assert_eq!("earth", *i.next().unwrap());
3258    /// ```
3259    pub fn append(&mut self, value: T) {
3260        let idx = self.index;
3261        let entry = &mut self.map.entries[idx];
3262        append_value(idx, entry, &mut self.map.extra_values, value);
3263    }
3264
3265    /// Remove the entry from the map.
3266    ///
3267    /// All values associated with the entry are removed and the first one is
3268    /// returned. See `remove_entry_mult` for an API that returns all values.
3269    ///
3270    /// # Examples
3271    ///
3272    /// ```
3273    /// # use http::header::{HeaderMap, Entry, HOST};
3274    /// let mut map = HeaderMap::new();
3275    /// map.insert(HOST, "world".parse().unwrap());
3276    ///
3277    /// if let Entry::Occupied(e) = map.entry("host") {
3278    ///     let mut prev = e.remove();
3279    ///     assert_eq!("world", prev);
3280    /// }
3281    ///
3282    /// assert!(!map.contains_key("host"));
3283    /// ```
3284    pub fn remove(self) -> T {
3285        self.remove_entry().1
3286    }
3287
3288    /// Remove the entry from the map.
3289    ///
3290    /// The key and all values associated with the entry are removed and the
3291    /// first one is returned. See `remove_entry_mult` for an API that returns
3292    /// all values.
3293    ///
3294    /// # Examples
3295    ///
3296    /// ```
3297    /// # use http::header::{HeaderMap, Entry, HOST};
3298    /// let mut map = HeaderMap::new();
3299    /// map.insert(HOST, "world".parse().unwrap());
3300    ///
3301    /// if let Entry::Occupied(e) = map.entry("host") {
3302    ///     let (key, mut prev) = e.remove_entry();
3303    ///     assert_eq!("host", key.as_str());
3304    ///     assert_eq!("world", prev);
3305    /// }
3306    ///
3307    /// assert!(!map.contains_key("host"));
3308    /// ```
3309    pub fn remove_entry(self) -> (HeaderName, T) {
3310        if let Some(links) = self.map.entries[self.index].links {
3311            self.map.remove_all_extra_values(links.next);
3312        }
3313
3314        let entry = self.map.remove_found(self.probe, self.index);
3315
3316        (entry.key, entry.value)
3317    }
3318
3319    /// Remove the entry from the map.
3320    ///
3321    /// The key and all values associated with the entry are removed and
3322    /// returned.
3323    pub fn remove_entry_mult(self) -> (HeaderName, ValueDrain<'a, T>) {
3324        let raw_links = self.map.raw_links();
3325        let extra_values = &mut self.map.extra_values;
3326
3327        let next = self.map.entries[self.index]
3328            .links
3329            .map(|l| drain_all_extra_values(raw_links, extra_values, l.next).into_iter());
3330
3331        let entry = self.map.remove_found(self.probe, self.index);
3332
3333        let drain = ValueDrain {
3334            first: Some(entry.value),
3335            next,
3336            lt: PhantomData,
3337        };
3338        (entry.key, drain)
3339    }
3340
3341    /// Returns an iterator visiting all values associated with the entry.
3342    ///
3343    /// Values are iterated in insertion order.
3344    ///
3345    /// # Examples
3346    ///
3347    /// ```
3348    /// # use http::header::{HeaderMap, Entry, HOST};
3349    /// let mut map = HeaderMap::new();
3350    /// map.insert(HOST, "world".parse().unwrap());
3351    /// map.append(HOST, "earth".parse().unwrap());
3352    ///
3353    /// if let Entry::Occupied(e) = map.entry("host") {
3354    ///     let mut iter = e.iter();
3355    ///     assert_eq!(&"world", iter.next().unwrap());
3356    ///     assert_eq!(&"earth", iter.next().unwrap());
3357    ///     assert!(iter.next().is_none());
3358    /// }
3359    /// ```
3360    pub fn iter(&self) -> ValueIter<'_, T> {
3361        self.map.value_iter(Some(self.index))
3362    }
3363
3364    /// Returns an iterator mutably visiting all values associated with the
3365    /// entry.
3366    ///
3367    /// Values are iterated in insertion order.
3368    ///
3369    /// # Examples
3370    ///
3371    /// ```
3372    /// # use http::header::{HeaderMap, Entry, HOST};
3373    /// let mut map = HeaderMap::default();
3374    /// map.insert(HOST, "world".to_string());
3375    /// map.append(HOST, "earth".to_string());
3376    ///
3377    /// if let Entry::Occupied(mut e) = map.entry("host") {
3378    ///     for e in e.iter_mut() {
3379    ///         e.push_str("-boop");
3380    ///     }
3381    /// }
3382    ///
3383    /// let mut values = map.get_all("host");
3384    /// let mut i = values.iter();
3385    /// assert_eq!(&"world-boop", i.next().unwrap());
3386    /// assert_eq!(&"earth-boop", i.next().unwrap());
3387    /// ```
3388    pub fn iter_mut(&mut self) -> ValueIterMut<'_, T> {
3389        self.map.value_iter_mut(self.index)
3390    }
3391}
3392
3393impl<'a, T> IntoIterator for OccupiedEntry<'a, T> {
3394    type Item = &'a mut T;
3395    type IntoIter = ValueIterMut<'a, T>;
3396
3397    fn into_iter(self) -> ValueIterMut<'a, T> {
3398        self.map.value_iter_mut(self.index)
3399    }
3400}
3401
3402impl<'a, 'b: 'a, T> IntoIterator for &'b OccupiedEntry<'a, T> {
3403    type Item = &'a T;
3404    type IntoIter = ValueIter<'a, T>;
3405
3406    fn into_iter(self) -> ValueIter<'a, T> {
3407        self.iter()
3408    }
3409}
3410
3411impl<'a, 'b: 'a, T> IntoIterator for &'b mut OccupiedEntry<'a, T> {
3412    type Item = &'a mut T;
3413    type IntoIter = ValueIterMut<'a, T>;
3414
3415    fn into_iter(self) -> ValueIterMut<'a, T> {
3416        self.iter_mut()
3417    }
3418}
3419
3420// ===== impl ValueDrain =====
3421
3422impl<'a, T> Iterator for ValueDrain<'a, T> {
3423    type Item = T;
3424
3425    fn next(&mut self) -> Option<T> {
3426        if self.first.is_some() {
3427            self.first.take()
3428        } else if let Some(ref mut extras) = self.next {
3429            extras.next()
3430        } else {
3431            None
3432        }
3433    }
3434
3435    fn size_hint(&self) -> (usize, Option<usize>) {
3436        match (&self.first, &self.next) {
3437            // Exactly 1
3438            (&Some(_), &None) => (1, Some(1)),
3439            // 1 + extras
3440            (&Some(_), Some(extras)) => {
3441                let (l, u) = extras.size_hint();
3442                (l + 1, u.map(|u| u + 1))
3443            }
3444            // Extras only
3445            (&None, Some(extras)) => extras.size_hint(),
3446            // No more
3447            (&None, &None) => (0, Some(0)),
3448        }
3449    }
3450}
3451
3452impl<'a, T> FusedIterator for ValueDrain<'a, T> {}
3453
3454impl<'a, T> Drop for ValueDrain<'a, T> {
3455    fn drop(&mut self) {
3456        for _ in self.by_ref() {}
3457    }
3458}
3459
3460unsafe impl<'a, T: Sync> Sync for ValueDrain<'a, T> {}
3461unsafe impl<'a, T: Send> Send for ValueDrain<'a, T> {}
3462
3463// ===== impl RawLinks =====
3464
3465impl<T> Clone for RawLinks<T> {
3466    fn clone(&self) -> RawLinks<T> {
3467        *self
3468    }
3469}
3470
3471impl<T> Copy for RawLinks<T> {}
3472
3473impl<T> ops::Index<usize> for RawLinks<T> {
3474    type Output = Option<Links>;
3475
3476    fn index(&self, idx: usize) -> &Self::Output {
3477        unsafe { &(*self.0)[idx].links }
3478    }
3479}
3480
3481impl<T> ops::IndexMut<usize> for RawLinks<T> {
3482    fn index_mut(&mut self, idx: usize) -> &mut Self::Output {
3483        unsafe { &mut (*self.0)[idx].links }
3484    }
3485}
3486
3487// ===== impl Pos =====
3488
3489impl Pos {
3490    #[inline]
3491    fn new(index: usize, hash: HashValue) -> Self {
3492        debug_assert!(index < MAX_SIZE);
3493        Pos {
3494            index: index as Size,
3495            hash,
3496        }
3497    }
3498
3499    #[inline]
3500    fn none() -> Self {
3501        Pos {
3502            index: !0,
3503            hash: HashValue(0),
3504        }
3505    }
3506
3507    #[inline]
3508    fn is_some(&self) -> bool {
3509        !self.is_none()
3510    }
3511
3512    #[inline]
3513    fn is_none(&self) -> bool {
3514        self.index == !0
3515    }
3516
3517    #[inline]
3518    fn resolve(&self) -> Option<(usize, HashValue)> {
3519        if self.is_some() {
3520            Some((self.index as usize, self.hash))
3521        } else {
3522            None
3523        }
3524    }
3525}
3526
3527impl Danger {
3528    fn is_red(&self) -> bool {
3529        matches!(*self, Danger::Red(_))
3530    }
3531
3532    fn set_red(&mut self) {
3533        debug_assert!(self.is_yellow());
3534        *self = Danger::Red(RandomState::new());
3535    }
3536
3537    fn is_yellow(&self) -> bool {
3538        matches!(*self, Danger::Yellow)
3539    }
3540
3541    fn set_yellow(&mut self) {
3542        if let Danger::Green = *self {
3543            *self = Danger::Yellow;
3544        }
3545    }
3546
3547    fn set_green(&mut self) {
3548        debug_assert!(self.is_yellow());
3549        *self = Danger::Green;
3550    }
3551}
3552
3553// ===== impl MaxSizeReached =====
3554
3555impl MaxSizeReached {
3556    fn new() -> Self {
3557        MaxSizeReached { _priv: () }
3558    }
3559}
3560
3561impl fmt::Debug for MaxSizeReached {
3562    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3563        f.debug_struct("MaxSizeReached")
3564            // skip _priv noise
3565            .finish()
3566    }
3567}
3568
3569impl fmt::Display for MaxSizeReached {
3570    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3571        f.write_str("max size reached")
3572    }
3573}
3574
3575impl std::error::Error for MaxSizeReached {}
3576
3577// ===== impl Utils =====
3578
3579#[inline]
3580fn usable_capacity(cap: usize) -> usize {
3581    cap - cap / 4
3582}
3583
3584#[inline]
3585fn to_raw_capacity(n: usize) -> usize {
3586    match n.checked_add(n / 3) {
3587        Some(n) => n,
3588        None => panic!(
3589            "requested capacity {} too large: overflow while converting to raw capacity",
3590            n
3591        ),
3592    }
3593}
3594
3595#[inline]
3596fn desired_pos(mask: Size, hash: HashValue) -> usize {
3597    (hash.0 & mask) as usize
3598}
3599
3600/// The number of steps that `current` is forward of the desired position for hash
3601#[inline]
3602fn probe_distance(mask: Size, hash: HashValue, current: usize) -> usize {
3603    current.wrapping_sub(desired_pos(mask, hash)) & mask as usize
3604}
3605
3606fn hash_elem_using<K>(danger: &Danger, k: &K) -> HashValue
3607where
3608    K: Hash + ?Sized,
3609{
3610    use fnv::FnvHasher;
3611
3612    const MASK: u64 = (MAX_SIZE as u64) - 1;
3613
3614    let hash = match *danger {
3615        // Safe hash
3616        Danger::Red(ref hasher) => {
3617            let mut h = hasher.build_hasher();
3618            k.hash(&mut h);
3619            h.finish()
3620        }
3621        // Fast hash
3622        _ => {
3623            let mut h = FnvHasher::default();
3624            k.hash(&mut h);
3625            h.finish()
3626        }
3627    };
3628
3629    HashValue((hash & MASK) as u16)
3630}
3631
3632/*
3633 *
3634 * ===== impl IntoHeaderName / AsHeaderName =====
3635 *
3636 */
3637
3638mod into_header_name {
3639    use super::{Entry, HdrName, HeaderMap, HeaderName, MaxSizeReached};
3640
3641    /// A marker trait used to identify values that can be used as insert keys
3642    /// to a `HeaderMap`.
3643    pub trait IntoHeaderName: Sealed {}
3644
3645    // All methods are on this pub(super) trait, instead of `IntoHeaderName`,
3646    // so that they aren't publicly exposed to the world.
3647    //
3648    // Being on the `IntoHeaderName` trait would mean users could call
3649    // `"host".insert(&mut map, "localhost")`.
3650    //
3651    // Ultimately, this allows us to adjust the signatures of these methods
3652    // without breaking any external crate.
3653    pub trait Sealed {
3654        #[doc(hidden)]
3655        fn try_insert<T>(self, map: &mut HeaderMap<T>, val: T)
3656            -> Result<Option<T>, MaxSizeReached>;
3657
3658        #[doc(hidden)]
3659        fn try_append<T>(self, map: &mut HeaderMap<T>, val: T) -> Result<bool, MaxSizeReached>;
3660
3661        #[doc(hidden)]
3662        fn try_entry<T>(self, map: &mut HeaderMap<T>) -> Result<Entry<'_, T>, MaxSizeReached>;
3663    }
3664
3665    // ==== impls ====
3666
3667    impl Sealed for HeaderName {
3668        #[inline]
3669        fn try_insert<T>(
3670            self,
3671            map: &mut HeaderMap<T>,
3672            val: T,
3673        ) -> Result<Option<T>, MaxSizeReached> {
3674            map.try_insert2(self, val)
3675        }
3676
3677        #[inline]
3678        fn try_append<T>(self, map: &mut HeaderMap<T>, val: T) -> Result<bool, MaxSizeReached> {
3679            map.try_append2(self, val)
3680        }
3681
3682        #[inline]
3683        fn try_entry<T>(self, map: &mut HeaderMap<T>) -> Result<Entry<'_, T>, MaxSizeReached> {
3684            map.try_entry2(self)
3685        }
3686    }
3687
3688    impl IntoHeaderName for HeaderName {}
3689
3690    impl<'a> Sealed for &'a HeaderName {
3691        #[inline]
3692        fn try_insert<T>(
3693            self,
3694            map: &mut HeaderMap<T>,
3695            val: T,
3696        ) -> Result<Option<T>, MaxSizeReached> {
3697            map.try_insert2(self, val)
3698        }
3699        #[inline]
3700        fn try_append<T>(self, map: &mut HeaderMap<T>, val: T) -> Result<bool, MaxSizeReached> {
3701            map.try_append2(self, val)
3702        }
3703
3704        #[inline]
3705        fn try_entry<T>(self, map: &mut HeaderMap<T>) -> Result<Entry<'_, T>, MaxSizeReached> {
3706            map.try_entry2(self)
3707        }
3708    }
3709
3710    impl<'a> IntoHeaderName for &'a HeaderName {}
3711
3712    impl Sealed for &'static str {
3713        #[inline]
3714        fn try_insert<T>(
3715            self,
3716            map: &mut HeaderMap<T>,
3717            val: T,
3718        ) -> Result<Option<T>, MaxSizeReached> {
3719            HdrName::from_static(self, move |hdr| map.try_insert2(hdr, val))
3720        }
3721        #[inline]
3722        fn try_append<T>(self, map: &mut HeaderMap<T>, val: T) -> Result<bool, MaxSizeReached> {
3723            HdrName::from_static(self, move |hdr| map.try_append2(hdr, val))
3724        }
3725
3726        #[inline]
3727        fn try_entry<T>(self, map: &mut HeaderMap<T>) -> Result<Entry<'_, T>, MaxSizeReached> {
3728            HdrName::from_static(self, move |hdr| map.try_entry2(hdr))
3729        }
3730    }
3731
3732    impl IntoHeaderName for &'static str {}
3733}
3734
3735mod as_header_name {
3736    use super::{Entry, HdrName, HeaderMap, HeaderName, InvalidHeaderName, MaxSizeReached};
3737
3738    /// A marker trait used to identify values that can be used as search keys
3739    /// to a `HeaderMap`.
3740    pub trait AsHeaderName: Sealed {}
3741
3742    // Debug not currently needed, save on compiling it
3743    #[allow(missing_debug_implementations)]
3744    pub enum TryEntryError {
3745        InvalidHeaderName(InvalidHeaderName),
3746        MaxSizeReached(MaxSizeReached),
3747    }
3748
3749    impl From<InvalidHeaderName> for TryEntryError {
3750        fn from(e: InvalidHeaderName) -> TryEntryError {
3751            TryEntryError::InvalidHeaderName(e)
3752        }
3753    }
3754
3755    impl From<MaxSizeReached> for TryEntryError {
3756        fn from(e: MaxSizeReached) -> TryEntryError {
3757            TryEntryError::MaxSizeReached(e)
3758        }
3759    }
3760
3761    // All methods are on this pub(super) trait, instead of `AsHeaderName`,
3762    // so that they aren't publicly exposed to the world.
3763    //
3764    // Being on the `AsHeaderName` trait would mean users could call
3765    // `"host".find(&map)`.
3766    //
3767    // Ultimately, this allows us to adjust the signatures of these methods
3768    // without breaking any external crate.
3769    pub trait Sealed {
3770        #[doc(hidden)]
3771        fn try_entry<T>(self, map: &mut HeaderMap<T>) -> Result<Entry<'_, T>, TryEntryError>;
3772
3773        #[doc(hidden)]
3774        fn find<T>(&self, map: &HeaderMap<T>) -> Option<(usize, usize)>;
3775
3776        #[doc(hidden)]
3777        fn as_str(&self) -> &str;
3778    }
3779
3780    // ==== impls ====
3781
3782    impl Sealed for HeaderName {
3783        #[inline]
3784        fn try_entry<T>(self, map: &mut HeaderMap<T>) -> Result<Entry<'_, T>, TryEntryError> {
3785            Ok(map.try_entry2(self)?)
3786        }
3787
3788        #[inline]
3789        fn find<T>(&self, map: &HeaderMap<T>) -> Option<(usize, usize)> {
3790            map.find(self)
3791        }
3792
3793        fn as_str(&self) -> &str {
3794            <HeaderName>::as_str(self)
3795        }
3796    }
3797
3798    impl AsHeaderName for HeaderName {}
3799
3800    impl<'a> Sealed for &'a HeaderName {
3801        #[inline]
3802        fn try_entry<T>(self, map: &mut HeaderMap<T>) -> Result<Entry<'_, T>, TryEntryError> {
3803            Ok(map.try_entry2(self)?)
3804        }
3805
3806        #[inline]
3807        fn find<T>(&self, map: &HeaderMap<T>) -> Option<(usize, usize)> {
3808            map.find(*self)
3809        }
3810
3811        fn as_str(&self) -> &str {
3812            <HeaderName>::as_str(self)
3813        }
3814    }
3815
3816    impl<'a> AsHeaderName for &'a HeaderName {}
3817
3818    impl<'a> Sealed for &'a str {
3819        #[inline]
3820        fn try_entry<T>(self, map: &mut HeaderMap<T>) -> Result<Entry<'_, T>, TryEntryError> {
3821            Ok(HdrName::from_bytes(self.as_bytes(), move |hdr| {
3822                map.try_entry2(hdr)
3823            })??)
3824        }
3825
3826        #[inline]
3827        fn find<T>(&self, map: &HeaderMap<T>) -> Option<(usize, usize)> {
3828            HdrName::from_bytes(self.as_bytes(), move |hdr| map.find(&hdr)).unwrap_or(None)
3829        }
3830
3831        fn as_str(&self) -> &str {
3832            self
3833        }
3834    }
3835
3836    impl<'a> AsHeaderName for &'a str {}
3837
3838    impl Sealed for String {
3839        #[inline]
3840        fn try_entry<T>(self, map: &mut HeaderMap<T>) -> Result<Entry<'_, T>, TryEntryError> {
3841            self.as_str().try_entry(map)
3842        }
3843
3844        #[inline]
3845        fn find<T>(&self, map: &HeaderMap<T>) -> Option<(usize, usize)> {
3846            Sealed::find(&self.as_str(), map)
3847        }
3848
3849        fn as_str(&self) -> &str {
3850            self
3851        }
3852    }
3853
3854    impl AsHeaderName for String {}
3855
3856    impl<'a> Sealed for &'a String {
3857        #[inline]
3858        fn try_entry<T>(self, map: &mut HeaderMap<T>) -> Result<Entry<'_, T>, TryEntryError> {
3859            self.as_str().try_entry(map)
3860        }
3861
3862        #[inline]
3863        fn find<T>(&self, map: &HeaderMap<T>) -> Option<(usize, usize)> {
3864            Sealed::find(*self, map)
3865        }
3866
3867        fn as_str(&self) -> &str {
3868            self
3869        }
3870    }
3871
3872    impl<'a> AsHeaderName for &'a String {}
3873}
3874
3875#[test]
3876fn test_bounds() {
3877    fn check_bounds<T: Send + Send>() {}
3878
3879    check_bounds::<HeaderMap<()>>();
3880    check_bounds::<Iter<'static, ()>>();
3881    check_bounds::<IterMut<'static, ()>>();
3882    check_bounds::<Keys<'static, ()>>();
3883    check_bounds::<Values<'static, ()>>();
3884    check_bounds::<ValuesMut<'static, ()>>();
3885    check_bounds::<Drain<'static, ()>>();
3886    check_bounds::<GetAll<'static, ()>>();
3887    check_bounds::<Entry<'static, ()>>();
3888    check_bounds::<VacantEntry<'static, ()>>();
3889    check_bounds::<OccupiedEntry<'static, ()>>();
3890    check_bounds::<ValueIter<'static, ()>>();
3891    check_bounds::<ValueIterMut<'static, ()>>();
3892    check_bounds::<ValueDrain<'static, ()>>();
3893}
3894
3895#[test]
3896fn skip_duplicates_during_key_iteration() {
3897    let mut map = HeaderMap::new();
3898    map.try_append("a", HeaderValue::from_static("a")).unwrap();
3899    map.try_append("a", HeaderValue::from_static("b")).unwrap();
3900    assert_eq!(map.keys().count(), map.keys_len());
3901}