http_with_url/header/
map.rs

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