Skip to main content

rama_http_types/header/
map.rs

1use std::collections::HashMap;
2use std::collections::hash_map::RandomState;
3use std::convert::TryFrom;
4use std::hash::{BuildHasher, Hash, Hasher};
5use std::iter::{FromIterator, FusedIterator};
6use std::marker::PhantomData;
7use std::{fmt, mem, ops, ptr, vec};
8
9use crate::Error;
10
11use super::HeaderValue;
12use super::name::{HdrName, HeaderName, InvalidHeaderName};
13
14pub use self::as_header_name::AsHeaderName;
15pub use self::into_header_name::IntoHeaderName;
16
17/// A specialized [multimap](<https://en.wikipedia.org/wiki/Multimap>) for
18/// header names and values.
19///
20/// # Overview
21///
22/// `HeaderMap` is designed specifically for efficient manipulation of HTTP
23/// headers. It supports multiple values per header name and provides
24/// specialized APIs for insertion, retrieval, and iteration.
25///
26/// The internal implementation is optimized for common usage patterns in HTTP,
27/// and may change across versions. For example, the current implementation uses
28/// [Robin Hood
29/// hashing](<https://en.wikipedia.org/wiki/Hash_table#Robin_Hood_hashing>) to
30/// store entries compactly and enable high load factors with good performance.
31/// However, the collision resolution strategy and storage mechanism are not
32/// part of the public API and may be altered in future releases.
33///
34/// # Iteration order
35///
36/// Unless otherwise specified, the order in which items are returned by
37/// iterators from `HeaderMap` methods is arbitrary; there is no guaranteed
38/// ordering among the elements yielded by such an iterator. Changes to the
39/// iteration order are not considered breaking changes, so users must not rely
40/// on any incidental order produced by such an iterator. However, for a given
41/// crate version, the iteration order will be consistent across all platforms.
42///
43/// # Adaptive hashing
44///
45/// `HeaderMap` uses an adaptive strategy for hashing to maintain fast lookups
46/// while resisting hash collision attacks. The default hash function
47/// prioritizes performance. In scenarios where high collision rates are
48/// detected—typically indicative of denial-of-service attacks—the
49/// implementation switches to a more secure, collision-resistant hash function.
50///
51/// # Limitations
52///
53/// A `HeaderMap` can store at most 32,768 entries \(header name/value pairs\).
54/// Attempting to exceed this limit will result in a panic.
55///
56/// [`HeaderName`]: struct.HeaderName.html
57/// [`HeaderMap`]: struct.HeaderMap.html
58///
59/// # Examples
60///
61/// Basic usage
62///
63/// ```
64/// # use rama_http_types::HeaderMap;
65/// # use rama_http_types::header::{CONTENT_LENGTH, HOST, LOCATION};
66/// let mut headers = HeaderMap::new();
67///
68/// headers.insert(HOST, "example.com".parse().unwrap());
69/// headers.insert(CONTENT_LENGTH, "123".parse().unwrap());
70///
71/// assert!(headers.contains_key(HOST));
72/// assert!(!headers.contains_key(LOCATION));
73///
74/// assert_eq!(headers[HOST], "example.com");
75///
76/// headers.remove(HOST);
77///
78/// assert!(!headers.contains_key(HOST));
79/// ```
80#[derive(Clone)]
81pub struct HeaderMap<T = HeaderValue> {
82    // Used to mask values to get an index
83    mask: Size,
84    indices: Box<[Pos]>,
85    entries: Vec<Bucket<T>>,
86    extra_values: Vec<ExtraValue<T>>,
87    order: Vec<Option<Link>>,
88    order_holes: usize,
89    danger: Danger,
90}
91
92// # Implementation notes
93//
94// Below, you will find a fairly large amount of code. Most of this is to
95// provide the necessary functions to efficiently manipulate the header
96// multimap. The core hashing table is based on robin hood hashing [1]. While
97// this is the same hashing algorithm used as part of Rust's `HashMap` in
98// stdlib, many implementation details are different. The two primary reasons
99// for this divergence are that `HeaderMap` is a multimap and the structure has
100// been optimized to take advantage of the characteristics of HTTP headers.
101//
102// ## Structure Layout
103//
104// Most of the data contained by `HeaderMap` is *not* stored in the hash table.
105// Instead, pairs of header name and *first* associated header value are stored
106// in the `entries` vector. If the header name has more than one associated
107// header value, then additional values are stored in `extra_values`. The actual
108// hash table (`indices`) only maps hash codes to indices in `entries`. This
109// means that, when an eviction happens, the actual header name and value stay
110// put and only a tiny amount of memory has to be copied.
111//
112// Extra values associated with a header name are tracked using a linked list.
113// Links are formed with offsets into `extra_values` and not pointers.
114//
115// [1]: https://en.wikipedia.org/wiki/Hash_table#Robin_Hood_hashing
116
117/// `HeaderMap` entry iterator.
118///
119/// Yields `(&HeaderName, &value)` tuples. The same header name may be yielded
120/// more than once if it has more than one associated value.
121#[derive(Debug)]
122pub struct Iter<'a, T> {
123    map: &'a HeaderMap<T>,
124    entry: usize,
125    cursor: Option<Cursor>,
126}
127
128/// `HeaderMap` mutable entry iterator
129///
130/// Yields `(&HeaderName, &mut value)` tuples. The same header name may be
131/// yielded more than once if it has more than one associated value.
132#[derive(Debug)]
133pub struct IterMut<'a, T> {
134    // Raw access avoids reborrowing the whole `HeaderMap` on every `next()`,
135    // which would invalidate previously yielded `&mut T`s.
136    entries: *mut Bucket<T>,
137    entries_len: usize,
138    // This points at the original `HeaderMap::extra_values` allocation for the
139    // lifetime of the iterator.
140    extra_values: *mut ExtraValue<T>,
141    entry: usize,
142    cursor: Option<Cursor>,
143    lt: PhantomData<&'a mut HeaderMap<T>>,
144}
145
146/// An owning iterator over the entries of a `HeaderMap`.
147///
148/// This struct is created by the `into_iter` method on `HeaderMap`.
149#[derive(Debug)]
150pub struct IntoIter<T> {
151    // If None, pull from `entries`
152    next: Option<usize>,
153    entries: vec::IntoIter<Bucket<T>>,
154    extra_values: Vec<ExtraValue<T>>,
155}
156
157/// An iterator over `HeaderMap` entries in their original insertion order.
158///
159/// Yields `(&HeaderName, &value)` tuples. The same semantic header name may be
160/// yielded more than once and each yielded name preserves the casing that was
161/// used when that field line was inserted.
162#[derive(Debug)]
163pub struct OrderedIter<'a, T> {
164    map: &'a HeaderMap<T>,
165    index: usize,
166}
167
168/// A consuming iterator over `HeaderMap` entries in original insertion order.
169///
170/// Each yielded `HeaderName` preserves the casing that was used when that field
171/// line was inserted.
172#[derive(Debug)]
173pub struct IntoOrderedIter<T> {
174    index: usize,
175    order: Vec<Option<Link>>,
176    entries: Vec<Bucket<T>>,
177    extra_values: Vec<ExtraValue<T>>,
178}
179
180/// An iterator over `HeaderMap` keys.
181///
182/// Each header name is yielded only once, even if it has more than one
183/// associated value.
184#[derive(Debug)]
185pub struct Keys<'a, T> {
186    inner: ::std::slice::Iter<'a, Bucket<T>>,
187}
188
189/// `HeaderMap` value iterator.
190///
191/// Each value contained in the `HeaderMap` will be yielded.
192#[derive(Debug)]
193pub struct Values<'a, T> {
194    inner: Iter<'a, T>,
195}
196
197/// `HeaderMap` mutable value iterator
198#[derive(Debug)]
199pub struct ValuesMut<'a, T> {
200    inner: IterMut<'a, T>,
201}
202
203/// A drain iterator for `HeaderMap`.
204#[derive(Debug)]
205pub struct Drain<'a, T> {
206    idx: usize,
207    len: usize,
208    entries: *mut [Bucket<T>],
209    // If None, pull from `entries`
210    next: Option<usize>,
211    extra_values: *mut Vec<ExtraValue<T>>,
212    lt: PhantomData<&'a mut HeaderMap<T>>,
213}
214
215/// A view to all values stored in a single entry.
216///
217/// This struct is returned by `HeaderMap::get_all`.
218#[derive(Debug)]
219pub struct GetAll<'a, T> {
220    map: &'a HeaderMap<T>,
221    index: Option<usize>,
222}
223
224/// A view into a single location in a `HeaderMap`, which may be vacant or occupied.
225#[derive(Debug)]
226pub enum Entry<'a, T: 'a> {
227    /// An occupied entry
228    Occupied(OccupiedEntry<'a, T>),
229
230    /// A vacant entry
231    Vacant(VacantEntry<'a, T>),
232}
233
234/// A view into a single empty location in a `HeaderMap`.
235///
236/// This struct is returned as part of the `Entry` enum.
237#[derive(Debug)]
238pub struct VacantEntry<'a, T> {
239    map: &'a mut HeaderMap<T>,
240    key: HeaderName,
241    hash: HashValue,
242    probe: usize,
243    danger: bool,
244}
245
246/// A view into a single occupied location in a `HeaderMap`.
247///
248/// This struct is returned as part of the `Entry` enum.
249#[derive(Debug)]
250pub struct OccupiedEntry<'a, T> {
251    map: &'a mut HeaderMap<T>,
252    probe: usize,
253    index: usize,
254}
255
256/// An iterator of all values associated with a single header name.
257#[derive(Debug)]
258pub struct ValueIter<'a, T> {
259    map: &'a HeaderMap<T>,
260    index: usize,
261    front: Option<Cursor>,
262    back: Option<Cursor>,
263}
264
265/// A mutable iterator of all values associated with a single header name.
266#[derive(Debug)]
267pub struct ValueIterMut<'a, T> {
268    // Raw access avoids reborrowing the whole `HeaderMap` on every step.
269    entries: *mut Bucket<T>,
270    // This points at the original `HeaderMap::extra_values` allocation for the
271    // lifetime of the iterator.
272    extra_values: *mut ExtraValue<T>,
273    index: usize,
274    front: Option<Cursor>,
275    back: Option<Cursor>,
276    lt: PhantomData<&'a mut HeaderMap<T>>,
277}
278
279/// An drain iterator of all values associated with a single header name.
280#[derive(Debug)]
281pub struct ValueDrain<'a, T> {
282    first: Option<T>,
283    next: Option<::std::vec::IntoIter<T>>,
284    lt: PhantomData<&'a mut HeaderMap<T>>,
285}
286
287/// Error returned when max capacity of `HeaderMap` is exceeded
288pub struct MaxSizeReached {
289    _priv: (),
290}
291
292/// Tracks the value iterator state
293#[derive(Debug, Copy, Clone, Eq, PartialEq)]
294enum Cursor {
295    Head,
296    Values(usize),
297}
298
299/// Type used for representing the size of a HeaderMap value.
300///
301/// 32,768 is more than enough entries for a single header map. Setting this
302/// limit enables using `u16` to represent all offsets, which takes 2 bytes
303/// instead of 8 on 64 bit processors.
304///
305/// Setting this limit is especially beneficial for `indices`, making it more
306/// cache friendly. More hash codes can fit in a cache line.
307///
308/// You may notice that `u16` may represent more than 32,768 values. This is
309/// true, but 32,768 should be plenty and it allows us to reserve the top bit
310/// for future usage.
311type Size = u16;
312
313/// This limit falls out from above.
314const MAX_SIZE: usize = 1 << 15;
315
316/// An entry in the hash table. This represents the full hash code for an entry
317/// as well as the position of the entry in the `entries` vector.
318#[derive(Copy, Clone)]
319struct Pos {
320    // Index in the `entries` vec
321    index: Size,
322    // Full hash value for the entry.
323    hash: HashValue,
324}
325
326/// Hash values are limited to u16 as well. While `fast_hash` and `Hasher`
327/// return `usize` hash codes, limiting the effective hash code to the lower 16
328/// bits is fine since we know that the `indices` vector will never grow beyond
329/// that size.
330#[derive(Debug, Copy, Clone, Eq, PartialEq)]
331struct HashValue(u16);
332
333/// Stores the data associated with a `HeaderMap` entry. Only the first value is
334/// included in this struct. If a header name has more than one associated
335/// value, all extra values are stored in the `extra_values` vector. A doubly
336/// linked list of entries is maintained. The doubly linked list is used so that
337/// removing a value is constant time. This also has the nice property of
338/// enabling double ended iteration.
339#[derive(Debug, Clone)]
340struct Bucket<T> {
341    hash: HashValue,
342    key: HeaderName,
343    value: T,
344    links: Option<Links>,
345    order: usize,
346}
347
348/// The head and tail of the value linked list.
349#[derive(Debug, Copy, Clone)]
350struct Links {
351    next: usize,
352    tail: usize,
353}
354
355/// Access to the `links` value in a slice of buckets.
356///
357/// It's important that no other field is accessed, since it may have been
358/// freed in a `Drain` iterator.
359#[derive(Debug)]
360struct RawLinks<T>(*mut [Bucket<T>]);
361
362/// Node in doubly-linked list of header value entries
363#[derive(Debug, Clone)]
364struct ExtraValue<T> {
365    key: HeaderName,
366    value: T,
367    prev: Link,
368    next: Link,
369    order: usize,
370}
371
372/// A header value node is either linked to another node in the `extra_values`
373/// list or it points to an entry in `entries`. The entry in `entries` is the
374/// start of the list and holds the associated header name.
375#[derive(Debug, Copy, Clone, Eq, PartialEq)]
376enum Link {
377    Entry(usize),
378    Extra(usize),
379}
380
381/// Tracks the header map danger level! This relates to the adaptive hashing
382/// algorithm. A HeaderMap starts in the "green" state, when a large number of
383/// collisions are detected, it transitions to the yellow state. At this point,
384/// the header map will either grow and switch back to the green state OR it
385/// will transition to the red state.
386///
387/// When in the red state, a safe hashing algorithm is used and all values in
388/// the header map have to be rehashed.
389#[derive(Clone)]
390enum Danger {
391    Green,
392    Yellow,
393    Red(RandomState),
394}
395
396// Constants related to detecting DOS attacks.
397//
398// Displacement is the number of entries that get shifted when inserting a new
399// value. Forward shift is how far the entry gets stored from the ideal
400// position.
401//
402// The current constant values were picked from another implementation. It could
403// be that there are different values better suited to the header map case.
404const DISPLACEMENT_THRESHOLD: usize = 128;
405const FORWARD_SHIFT_THRESHOLD: usize = 512;
406
407// The default strategy for handling the yellow danger state is to increase the
408// header map capacity in order to (hopefully) reduce the number of collisions.
409// If growing the hash map would cause the load factor to drop bellow this
410// threshold, then instead of growing, the headermap is switched to the red
411// danger state and safe hashing is used instead.
412const LOAD_FACTOR_THRESHOLD: usize = 5;
413
414// Macro used to iterate the hash table starting at a given point, looping when
415// the end is hit.
416macro_rules! probe_loop {
417    ($label:tt: $probe_var: ident < $len: expr, $body: expr) => {
418        debug_assert!($len > 0);
419        $label:
420        loop {
421            if $probe_var < $len {
422                $body
423                $probe_var += 1;
424            } else {
425                $probe_var = 0;
426            }
427        }
428    };
429    ($probe_var: ident < $len: expr, $body: expr) => {
430        debug_assert!($len > 0);
431        loop {
432            if $probe_var < $len {
433                $body
434                $probe_var += 1;
435            } else {
436                $probe_var = 0;
437            }
438        }
439    };
440}
441
442// First part of the robinhood algorithm. Given a key, find the slot in which it
443// will be inserted. This is done by starting at the "ideal" spot. Then scanning
444// until the destination slot is found. A destination slot is either the next
445// empty slot or the next slot that is occupied by an entry that has a lower
446// displacement (displacement is the distance from the ideal spot).
447//
448// This is implemented as a macro instead of a function that takes a closure in
449// order to guarantee that it is "inlined". There is no way to annotate closures
450// to guarantee inlining.
451macro_rules! insert_phase_one {
452    ($map:ident,
453     $key:expr,
454     $probe:ident,
455     $pos:ident,
456     $hash:ident,
457     $danger:ident,
458     $vacant:expr,
459     $occupied:expr,
460     $robinhood:expr) =>
461    {{
462        let $hash = hash_elem_using(&$map.danger, &$key);
463        let mut $probe = desired_pos($map.mask, $hash);
464        let mut dist = 0;
465        let ret;
466
467        // Start at the ideal position, checking all slots
468        probe_loop!('probe: $probe < $map.indices.len(), {
469            if let Some(($pos, entry_hash)) = $map.indices[$probe].resolve() {
470                // The slot is already occupied, but check if it has a lower
471                // displacement.
472                let their_dist = probe_distance($map.mask, entry_hash, $probe);
473
474                if their_dist < dist {
475                    // The new key's distance is larger, so claim this spot and
476                    // displace the current entry.
477                    //
478                    // Check if this insertion is above the danger threshold.
479                    let $danger =
480                        dist >= FORWARD_SHIFT_THRESHOLD && !$map.danger.is_red();
481
482                    ret = $robinhood;
483                    break 'probe;
484                } else if entry_hash == $hash && $map.entries[$pos].key == $key {
485                    // There already is an entry with the same key.
486                    ret = $occupied;
487                    break 'probe;
488                }
489            } else {
490                // The entry is vacant, use it for this key.
491                let $danger =
492                    dist >= FORWARD_SHIFT_THRESHOLD && !$map.danger.is_red();
493
494                ret = $vacant;
495                break 'probe;
496            }
497
498            dist += 1;
499        });
500
501        ret
502    }}
503}
504
505// ===== impl HeaderMap =====
506
507impl HeaderMap {
508    /// Create an empty `HeaderMap`.
509    ///
510    /// The map will be created without any capacity. This function will not
511    /// allocate.
512    ///
513    /// # Examples
514    ///
515    /// ```
516    /// # use rama_http_types::HeaderMap;
517    /// let map = HeaderMap::new();
518    ///
519    /// assert!(map.is_empty());
520    /// assert_eq!(0, map.capacity());
521    /// ```
522    #[inline]
523    pub fn new() -> Self {
524        Self::default()
525    }
526}
527
528impl<T> Default for HeaderMap<T> {
529    fn default() -> Self {
530        HeaderMap {
531            mask: 0,
532            indices: Box::new([]), // as a ZST, this doesn't actually allocate anything
533            entries: Vec::new(),
534            extra_values: Vec::new(),
535            order: Vec::new(),
536            order_holes: 0,
537            danger: Danger::Green,
538        }
539    }
540}
541
542impl<T> HeaderMap<T> {
543    /// Create an empty `HeaderMap` with the specified capacity.
544    ///
545    /// The returned map will allocate internal storage in order to hold about
546    /// `capacity` elements without reallocating. However, this is a "best
547    /// effort" as there are usage patterns that could cause additional
548    /// allocations before `capacity` headers are stored in the map.
549    ///
550    /// More capacity than requested may be allocated.
551    ///
552    /// # Panics
553    ///
554    /// This method panics if capacity exceeds max `HeaderMap` capacity.
555    ///
556    /// # Examples
557    ///
558    /// ```
559    /// # use rama_http_types::HeaderMap;
560    /// let map: HeaderMap<u32> = HeaderMap::with_capacity(10);
561    ///
562    /// assert!(map.is_empty());
563    /// assert_eq!(12, map.capacity());
564    /// ```
565    pub fn with_capacity(capacity: usize) -> HeaderMap<T> {
566        Self::try_with_capacity(capacity).expect("size overflows MAX_SIZE")
567    }
568
569    /// Create an empty `HeaderMap` with the specified capacity.
570    ///
571    /// The returned map will allocate internal storage in order to hold about
572    /// `capacity` elements without reallocating. However, this is a "best
573    /// effort" as there are usage patterns that could cause additional
574    /// allocations before `capacity` headers are stored in the map.
575    ///
576    /// More capacity than requested may be allocated.
577    ///
578    /// # Errors
579    ///
580    /// This function may return an error if `HeaderMap` exceeds max capacity
581    ///
582    /// # Examples
583    ///
584    /// ```
585    /// # use rama_http_types::HeaderMap;
586    /// let map: HeaderMap<u32> = HeaderMap::try_with_capacity(10).unwrap();
587    ///
588    /// assert!(map.is_empty());
589    /// assert_eq!(12, map.capacity());
590    /// ```
591    pub fn try_with_capacity(capacity: usize) -> Result<HeaderMap<T>, MaxSizeReached> {
592        if capacity == 0 {
593            Ok(Self::default())
594        } else {
595            let raw_cap = to_raw_capacity(capacity)?;
596            let raw_cap = match raw_cap.checked_next_power_of_two() {
597                Some(c) => c,
598                None => return Err(MaxSizeReached { _priv: () }),
599            };
600            if raw_cap > MAX_SIZE {
601                return Err(MaxSizeReached { _priv: () });
602            }
603            debug_assert!(raw_cap > 0);
604
605            Ok(HeaderMap {
606                mask: (raw_cap - 1) as Size,
607                indices: vec![Pos::none(); raw_cap].into_boxed_slice(),
608                entries: Vec::with_capacity(usable_capacity(raw_cap)),
609                extra_values: Vec::new(),
610                order: Vec::with_capacity(capacity),
611                order_holes: 0,
612                danger: Danger::Green,
613            })
614        }
615    }
616
617    /// Returns the number of headers stored in the map.
618    ///
619    /// This number represents the total number of **values** stored in the map.
620    /// This number can be greater than or equal to the number of **keys**
621    /// stored given that a single key may have more than one associated value.
622    ///
623    /// # Examples
624    ///
625    /// ```
626    /// # use rama_http_types::HeaderMap;
627    /// # use rama_http_types::header::{ACCEPT, HOST};
628    /// let mut map = HeaderMap::new();
629    ///
630    /// assert_eq!(0, map.len());
631    ///
632    /// map.insert(ACCEPT, "text/plain".parse().unwrap());
633    /// map.insert(HOST, "localhost".parse().unwrap());
634    ///
635    /// assert_eq!(2, map.len());
636    ///
637    /// map.append(ACCEPT, "text/html".parse().unwrap());
638    ///
639    /// assert_eq!(3, map.len());
640    /// ```
641    pub fn len(&self) -> usize {
642        self.entries.len() + self.extra_values.len()
643    }
644
645    /// Returns the number of keys stored in the map.
646    ///
647    /// This number will be less than or equal to `len()` as each key may have
648    /// more than one associated value.
649    ///
650    /// # Examples
651    ///
652    /// ```
653    /// # use rama_http_types::HeaderMap;
654    /// # use rama_http_types::header::{ACCEPT, HOST};
655    /// let mut map = HeaderMap::new();
656    ///
657    /// assert_eq!(0, map.keys_len());
658    ///
659    /// map.insert(ACCEPT, "text/plain".parse().unwrap());
660    /// map.insert(HOST, "localhost".parse().unwrap());
661    ///
662    /// assert_eq!(2, map.keys_len());
663    ///
664    /// map.insert(ACCEPT, "text/html".parse().unwrap());
665    ///
666    /// assert_eq!(2, map.keys_len());
667    /// ```
668    pub fn keys_len(&self) -> usize {
669        self.entries.len()
670    }
671
672    /// Returns true if the map contains no elements.
673    ///
674    /// # Examples
675    ///
676    /// ```
677    /// # use rama_http_types::HeaderMap;
678    /// # use rama_http_types::header::HOST;
679    /// let mut map = HeaderMap::new();
680    ///
681    /// assert!(map.is_empty());
682    ///
683    /// map.insert(HOST, "hello.world".parse().unwrap());
684    ///
685    /// assert!(!map.is_empty());
686    /// ```
687    pub fn is_empty(&self) -> bool {
688        self.entries.len() == 0
689    }
690
691    /// Clears the map, removing all key-value pairs. Keeps the allocated memory
692    /// for reuse.
693    ///
694    /// # Examples
695    ///
696    /// ```
697    /// # use rama_http_types::HeaderMap;
698    /// # use rama_http_types::header::HOST;
699    /// let mut map = HeaderMap::new();
700    /// map.insert(HOST, "hello.world".parse().unwrap());
701    ///
702    /// map.clear();
703    /// assert!(map.is_empty());
704    /// assert!(map.capacity() > 0);
705    /// ```
706    pub fn clear(&mut self) {
707        self.entries.clear();
708        self.extra_values.clear();
709        self.order.clear();
710        self.order_holes = 0;
711        self.danger = Danger::Green;
712
713        for e in self.indices.iter_mut() {
714            *e = Pos::none();
715        }
716    }
717
718    /// Returns the number of headers the map can hold without reallocating.
719    ///
720    /// This number is an approximation as certain usage patterns could cause
721    /// additional allocations before the returned capacity is filled.
722    ///
723    /// # Examples
724    ///
725    /// ```
726    /// # use rama_http_types::HeaderMap;
727    /// # use rama_http_types::header::HOST;
728    /// let mut map = HeaderMap::new();
729    ///
730    /// assert_eq!(0, map.capacity());
731    ///
732    /// map.insert(HOST, "hello.world".parse().unwrap());
733    /// assert_eq!(6, map.capacity());
734    /// ```
735    pub fn capacity(&self) -> usize {
736        usable_capacity(self.indices.len())
737    }
738
739    /// Reserves capacity for at least `additional` more headers to be inserted
740    /// into the `HeaderMap`.
741    ///
742    /// The header map may reserve more space to avoid frequent reallocations.
743    /// Like with `with_capacity`, this will be a "best effort" to avoid
744    /// allocations until `additional` more headers are inserted. Certain usage
745    /// patterns could cause additional allocations before the number is
746    /// reached.
747    ///
748    /// # Panics
749    ///
750    /// Panics if the new allocation size overflows `HeaderMap` `MAX_SIZE`.
751    ///
752    /// # Examples
753    ///
754    /// ```
755    /// # use rama_http_types::HeaderMap;
756    /// # use rama_http_types::header::HOST;
757    /// let mut map = HeaderMap::new();
758    /// map.reserve(10);
759    /// # map.insert(HOST, "bar".parse().unwrap());
760    /// ```
761    pub fn reserve(&mut self, additional: usize) {
762        self.try_reserve(additional)
763            .expect("size overflows MAX_SIZE")
764    }
765
766    /// Reserves capacity for at least `additional` more headers to be inserted
767    /// into the `HeaderMap`.
768    ///
769    /// The header map may reserve more space to avoid frequent reallocations.
770    /// Like with `with_capacity`, this will be a "best effort" to avoid
771    /// allocations until `additional` more headers are inserted. Certain usage
772    /// patterns could cause additional allocations before the number is
773    /// reached.
774    ///
775    /// # Errors
776    ///
777    /// This method differs from `reserve` by returning an error instead of
778    /// panicking if the value is too large.
779    ///
780    /// # Examples
781    ///
782    /// ```
783    /// # use rama_http_types::HeaderMap;
784    /// # use rama_http_types::header::HOST;
785    /// let mut map = HeaderMap::new();
786    /// map.try_reserve(10).unwrap();
787    /// # map.try_insert(HOST, "bar".parse().unwrap()).unwrap();
788    /// ```
789    pub fn try_reserve(&mut self, additional: usize) -> Result<(), MaxSizeReached> {
790        // TODO: This can't overflow if done properly... since the max # of
791        // elements is u16::MAX.
792        let cap = self
793            .entries
794            .len()
795            .checked_add(additional)
796            .ok_or_else(MaxSizeReached::new)?;
797
798        let raw_cap = to_raw_capacity(cap)?;
799
800        if raw_cap > self.indices.len() {
801            let raw_cap = raw_cap
802                .checked_next_power_of_two()
803                .ok_or_else(MaxSizeReached::new)?;
804            if raw_cap > MAX_SIZE {
805                return Err(MaxSizeReached::new());
806            }
807
808            if self.entries.is_empty() {
809                self.mask = raw_cap as Size - 1;
810                self.indices = vec![Pos::none(); raw_cap].into_boxed_slice();
811                let cap = usable_capacity(raw_cap);
812                self.entries = Vec::with_capacity(cap);
813                self.order.reserve_exact(cap);
814            } else {
815                self.try_grow(raw_cap)?;
816            }
817        }
818
819        self.order.reserve(additional);
820
821        Ok(())
822    }
823
824    /// Returns a reference to the value associated with the key.
825    ///
826    /// If there are multiple values associated with the key, then the first one
827    /// is returned. Use `get_all` to get all values associated with a given
828    /// key. Returns `None` if there are no values associated with the key.
829    ///
830    /// # Examples
831    ///
832    /// ```
833    /// # use rama_http_types::HeaderMap;
834    /// # use rama_http_types::header::HOST;
835    /// let mut map = HeaderMap::new();
836    /// assert!(map.get("host").is_none());
837    ///
838    /// map.insert(HOST, "hello".parse().unwrap());
839    /// assert_eq!(map.get(HOST).unwrap(), &"hello");
840    /// assert_eq!(map.get("host").unwrap(), &"hello");
841    ///
842    /// map.append(HOST, "world".parse().unwrap());
843    /// assert_eq!(map.get("host").unwrap(), &"hello");
844    /// ```
845    pub fn get<K>(&self, key: K) -> Option<&T>
846    where
847        K: AsHeaderName,
848    {
849        self.get2(&key)
850    }
851
852    fn get2<K>(&self, key: &K) -> Option<&T>
853    where
854        K: AsHeaderName,
855    {
856        match key.find(self) {
857            Some((_, found)) => {
858                let entry = &self.entries[found];
859                Some(&entry.value)
860            }
861            None => None,
862        }
863    }
864
865    /// Returns a mutable reference to the value associated with the key.
866    ///
867    /// If there are multiple values associated with the key, then the first one
868    /// is returned. Use `entry` to get all values associated with a given
869    /// key. Returns `None` if there are no values associated with the key.
870    ///
871    /// # Examples
872    ///
873    /// ```
874    /// # use rama_http_types::HeaderMap;
875    /// # use rama_http_types::header::HOST;
876    /// let mut map = HeaderMap::default();
877    /// map.insert(HOST, "hello".to_string());
878    /// map.get_mut("host").unwrap().push_str("-world");
879    ///
880    /// assert_eq!(map.get(HOST).unwrap(), &"hello-world");
881    /// ```
882    pub fn get_mut<K>(&mut self, key: K) -> Option<&mut T>
883    where
884        K: AsHeaderName,
885    {
886        match key.find(self) {
887            Some((_, found)) => {
888                let entry = &mut self.entries[found];
889                Some(&mut entry.value)
890            }
891            None => None,
892        }
893    }
894
895    /// Returns a view of all values associated with a key.
896    ///
897    /// The returned view does not incur any allocations and allows iterating
898    /// the values associated with the key.  See [`GetAll`] for more details.
899    /// Returns `None` if there are no values associated with the key.
900    ///
901    /// [`GetAll`]: struct.GetAll.html
902    ///
903    /// # Examples
904    ///
905    /// ```
906    /// # use rama_http_types::HeaderMap;
907    /// # use rama_http_types::header::HOST;
908    /// let mut map = HeaderMap::new();
909    ///
910    /// map.insert(HOST, "hello".parse().unwrap());
911    /// map.append(HOST, "goodbye".parse().unwrap());
912    ///
913    /// let view = map.get_all("host");
914    ///
915    /// let mut iter = view.iter();
916    /// assert_eq!(&"hello", iter.next().unwrap());
917    /// assert_eq!(&"goodbye", iter.next().unwrap());
918    /// assert!(iter.next().is_none());
919    /// ```
920    pub fn get_all<K>(&self, key: K) -> GetAll<'_, T>
921    where
922        K: AsHeaderName,
923    {
924        GetAll {
925            map: self,
926            index: key.find(self).map(|(_, i)| i),
927        }
928    }
929
930    /// Returns true if the map contains a value for the specified key.
931    ///
932    /// # Examples
933    ///
934    /// ```
935    /// # use rama_http_types::HeaderMap;
936    /// # use rama_http_types::header::HOST;
937    /// let mut map = HeaderMap::new();
938    /// assert!(!map.contains_key(HOST));
939    ///
940    /// map.insert(HOST, "world".parse().unwrap());
941    /// assert!(map.contains_key("host"));
942    /// ```
943    pub fn contains_key<K>(&self, key: K) -> bool
944    where
945        K: AsHeaderName,
946    {
947        key.find(self).is_some()
948    }
949
950    /// An iterator visiting all key-value pairs.
951    ///
952    /// The iteration order is arbitrary, but consistent across platforms for
953    /// the same crate version. Each key will be yielded once per associated
954    /// value. So, if a key has 3 associated values, it will be yielded 3 times.
955    ///
956    /// # Examples
957    ///
958    /// ```
959    /// # use rama_http_types::HeaderMap;
960    /// # use rama_http_types::header::{CONTENT_LENGTH, HOST};
961    /// let mut map = HeaderMap::new();
962    ///
963    /// map.insert(HOST, "hello".parse().unwrap());
964    /// map.append(HOST, "goodbye".parse().unwrap());
965    /// map.insert(CONTENT_LENGTH, "123".parse().unwrap());
966    ///
967    /// for (key, value) in map.iter() {
968    ///     println!("{:?}: {:?}", key, value);
969    /// }
970    /// ```
971    pub fn iter(&self) -> Iter<'_, T> {
972        Iter {
973            map: self,
974            entry: 0,
975            cursor: self.entries.first().map(|_| Cursor::Head),
976        }
977    }
978
979    /// An iterator visiting all key-value pairs in their original insertion
980    /// order.
981    ///
982    /// Each yielded key preserves the casing that was used for that field line
983    /// when it was inserted into the map.
984    pub fn ordered_iter(&self) -> OrderedIter<'_, T> {
985        OrderedIter {
986            map: self,
987            index: 0,
988        }
989    }
990
991    /// An iterator visiting all key-value pairs, with mutable value references.
992    ///
993    /// The iterator order is arbitrary, but consistent across platforms for the
994    /// same crate version. Each key will be yielded once per associated value,
995    /// so if a key has 3 associated values, it will be yielded 3 times.
996    ///
997    /// # Examples
998    ///
999    /// ```
1000    /// # use rama_http_types::HeaderMap;
1001    /// # use rama_http_types::header::{CONTENT_LENGTH, HOST};
1002    /// let mut map = HeaderMap::default();
1003    ///
1004    /// map.insert(HOST, "hello".to_string());
1005    /// map.append(HOST, "goodbye".to_string());
1006    /// map.insert(CONTENT_LENGTH, "123".to_string());
1007    ///
1008    /// for (key, value) in map.iter_mut() {
1009    ///     value.push_str("-boop");
1010    /// }
1011    /// ```
1012    pub fn iter_mut(&mut self) -> IterMut<'_, T> {
1013        IterMut {
1014            entries: self.entries.as_mut_ptr(),
1015            entries_len: self.entries.len(),
1016            extra_values: self.extra_values.as_mut_ptr(),
1017            entry: 0,
1018            cursor: self.entries.first().map(|_| Cursor::Head),
1019            lt: PhantomData,
1020        }
1021    }
1022
1023    /// An iterator visiting all keys.
1024    ///
1025    /// The iteration order is arbitrary, but consistent across platforms for
1026    /// the same crate version. Each key will be yielded only once even if it
1027    /// has multiple associated values.
1028    ///
1029    /// # Examples
1030    ///
1031    /// ```
1032    /// # use rama_http_types::HeaderMap;
1033    /// # use rama_http_types::header::{CONTENT_LENGTH, HOST};
1034    /// let mut map = HeaderMap::new();
1035    ///
1036    /// map.insert(HOST, "hello".parse().unwrap());
1037    /// map.append(HOST, "goodbye".parse().unwrap());
1038    /// map.insert(CONTENT_LENGTH, "123".parse().unwrap());
1039    ///
1040    /// for key in map.keys() {
1041    ///     println!("{:?}", key);
1042    /// }
1043    /// ```
1044    pub fn keys(&self) -> Keys<'_, T> {
1045        Keys {
1046            inner: self.entries.iter(),
1047        }
1048    }
1049
1050    /// An iterator visiting all values.
1051    ///
1052    /// The iteration order is arbitrary, but consistent across platforms for
1053    /// the same crate version.
1054    ///
1055    /// # Examples
1056    ///
1057    /// ```
1058    /// # use rama_http_types::HeaderMap;
1059    /// # use rama_http_types::header::{CONTENT_LENGTH, HOST};
1060    /// let mut map = HeaderMap::new();
1061    ///
1062    /// map.insert(HOST, "hello".parse().unwrap());
1063    /// map.append(HOST, "goodbye".parse().unwrap());
1064    /// map.insert(CONTENT_LENGTH, "123".parse().unwrap());
1065    ///
1066    /// for value in map.values() {
1067    ///     println!("{:?}", value);
1068    /// }
1069    /// ```
1070    pub fn values(&self) -> Values<'_, T> {
1071        Values { inner: self.iter() }
1072    }
1073
1074    /// An iterator visiting all values mutably.
1075    ///
1076    /// The iteration order is arbitrary, but consistent across platforms for
1077    /// the same crate version.
1078    ///
1079    /// # Examples
1080    ///
1081    /// ```
1082    /// # use rama_http_types::HeaderMap;
1083    /// # use rama_http_types::header::{CONTENT_LENGTH, HOST};
1084    /// let mut map = HeaderMap::default();
1085    ///
1086    /// map.insert(HOST, "hello".to_string());
1087    /// map.append(HOST, "goodbye".to_string());
1088    /// map.insert(CONTENT_LENGTH, "123".to_string());
1089    ///
1090    /// for value in map.values_mut() {
1091    ///     value.push_str("-boop");
1092    /// }
1093    /// ```
1094    pub fn values_mut(&mut self) -> ValuesMut<'_, T> {
1095        ValuesMut {
1096            inner: self.iter_mut(),
1097        }
1098    }
1099
1100    /// Clears the map, returning all entries as an iterator.
1101    ///
1102    /// The internal memory is kept for reuse.
1103    ///
1104    /// For each yielded item that has `None` provided for the `HeaderName`,
1105    /// then the associated header name is the same as that of the previously
1106    /// yielded item. The first yielded item will have `HeaderName` set.
1107    ///
1108    /// # Examples
1109    ///
1110    /// ```
1111    /// # use rama_http_types::HeaderMap;
1112    /// # use rama_http_types::header::{CONTENT_LENGTH, HOST};
1113    /// let mut map = HeaderMap::new();
1114    ///
1115    /// map.insert(HOST, "hello".parse().unwrap());
1116    /// map.append(HOST, "goodbye".parse().unwrap());
1117    /// map.insert(CONTENT_LENGTH, "123".parse().unwrap());
1118    ///
1119    /// let mut drain = map.drain();
1120    ///
1121    ///
1122    /// assert_eq!(drain.next(), Some((Some(HOST), "hello".parse().unwrap())));
1123    /// assert_eq!(drain.next(), Some((None, "goodbye".parse().unwrap())));
1124    ///
1125    /// assert_eq!(drain.next(), Some((Some(CONTENT_LENGTH), "123".parse().unwrap())));
1126    ///
1127    /// assert_eq!(drain.next(), None);
1128    /// ```
1129    pub fn drain(&mut self) -> Drain<'_, T> {
1130        for i in self.indices.iter_mut() {
1131            *i = Pos::none();
1132        }
1133
1134        // Memory safety
1135        //
1136        // When the Drain is first created, it shortens the length of
1137        // the source vector to make sure no uninitialized or moved-from
1138        // elements are accessible at all if the Drain's destructor never
1139        // gets to run.
1140
1141        let entries = &mut self.entries[..] as *mut _;
1142        let extra_values = &mut self.extra_values as *mut _;
1143        let len = self.entries.len();
1144        unsafe {
1145            self.entries.set_len(0);
1146        }
1147        self.order.clear();
1148        self.order_holes = 0;
1149
1150        Drain {
1151            idx: 0,
1152            len,
1153            entries,
1154            extra_values,
1155            next: None,
1156            lt: PhantomData,
1157        }
1158    }
1159
1160    fn value_iter(&self, idx: Option<usize>) -> ValueIter<'_, T> {
1161        use self::Cursor::*;
1162
1163        if let Some(idx) = idx {
1164            let back = {
1165                let entry = &self.entries[idx];
1166
1167                entry.links.map(|l| Values(l.tail)).unwrap_or(Head)
1168            };
1169
1170            ValueIter {
1171                map: self,
1172                index: idx,
1173                front: Some(Head),
1174                back: Some(back),
1175            }
1176        } else {
1177            ValueIter {
1178                map: self,
1179                index: usize::MAX,
1180                front: None,
1181                back: None,
1182            }
1183        }
1184    }
1185
1186    fn value_iter_mut(&mut self, idx: usize) -> ValueIterMut<'_, T> {
1187        use self::Cursor::*;
1188
1189        let back = {
1190            let entry = &self.entries[idx];
1191
1192            entry.links.map(|l| Values(l.tail)).unwrap_or(Head)
1193        };
1194
1195        ValueIterMut {
1196            entries: self.entries.as_mut_ptr(),
1197            extra_values: self.extra_values.as_mut_ptr(),
1198            index: idx,
1199            front: Some(Head),
1200            back: Some(back),
1201            lt: PhantomData,
1202        }
1203    }
1204
1205    /// Gets the given key's corresponding entry in the map for in-place
1206    /// manipulation.
1207    ///
1208    /// # Panics
1209    ///
1210    /// This method panics if capacity exceeds max `HeaderMap` capacity
1211    ///
1212    /// # Examples
1213    ///
1214    /// ```
1215    /// # use rama_http_types::HeaderMap;
1216    /// let mut map: HeaderMap<u32> = HeaderMap::default();
1217    ///
1218    /// let headers = &[
1219    ///     "content-length",
1220    ///     "x-hello",
1221    ///     "Content-Length",
1222    ///     "x-world",
1223    /// ];
1224    ///
1225    /// for &header in headers {
1226    ///     let counter = map.entry(header).or_insert(0);
1227    ///     *counter += 1;
1228    /// }
1229    ///
1230    /// assert_eq!(map["content-length"], 2);
1231    /// assert_eq!(map["x-hello"], 1);
1232    /// ```
1233    pub fn entry<K>(&mut self, key: K) -> Entry<'_, T>
1234    where
1235        K: IntoHeaderName,
1236    {
1237        key.try_entry(self).expect("size overflows MAX_SIZE")
1238    }
1239
1240    /// Gets the given key's corresponding entry in the map for in-place
1241    /// manipulation.
1242    ///
1243    /// # Errors
1244    ///
1245    /// This method differs from `entry` by allowing types that may not be
1246    /// valid `HeaderName`s to passed as the key (such as `String`). If they
1247    /// do not parse as a valid `HeaderName`, this returns an
1248    /// `InvalidHeaderName` error.
1249    ///
1250    /// If reserving space goes over the maximum, this will also return an
1251    /// error. However, to prevent breaking changes to the return type, the
1252    /// error will still say `InvalidHeaderName`, unlike other `try_*` methods
1253    /// which return a `MaxSizeReached` error.
1254    pub fn try_entry<K>(&mut self, key: K) -> Result<Entry<'_, T>, InvalidHeaderName>
1255    where
1256        K: AsHeaderName,
1257    {
1258        key.try_entry(self).map_err(|err| match err {
1259            as_header_name::TryEntryError::InvalidHeaderName(e) => e,
1260            as_header_name::TryEntryError::MaxSizeReached(_e) => {
1261                // Unfortunately, we cannot change the return type of this
1262                // method, so the max size reached error needs to be converted
1263                // into an InvalidHeaderName. Yay.
1264                InvalidHeaderName::new()
1265            }
1266        })
1267    }
1268
1269    fn try_entry2<K>(&mut self, key: K) -> Result<Entry<'_, T>, MaxSizeReached>
1270    where
1271        K: Into<HeaderName>,
1272    {
1273        // Ensure that there is space in the map
1274        self.try_reserve_one()?;
1275        let key = key.into();
1276
1277        Ok(insert_phase_one!(
1278            self,
1279            key,
1280            probe,
1281            pos,
1282            hash,
1283            danger,
1284            Entry::Vacant(VacantEntry {
1285                map: self,
1286                hash,
1287                key: key.into(),
1288                probe,
1289                danger,
1290            }),
1291            Entry::Occupied(OccupiedEntry {
1292                map: self,
1293                index: pos,
1294                probe,
1295            }),
1296            Entry::Vacant(VacantEntry {
1297                map: self,
1298                hash,
1299                key: key.into(),
1300                probe,
1301                danger,
1302            })
1303        ))
1304    }
1305
1306    /// Inserts a key-value pair into the map.
1307    ///
1308    /// If the map did not previously have this key present, then `None` is
1309    /// returned.
1310    ///
1311    /// If the map did have this key present, the new value is associated with
1312    /// the key and all previous values are removed. **Note** that only a single
1313    /// one of the previous values is returned. If there are multiple values
1314    /// that have been previously associated with the key, then the first one is
1315    /// returned. See `insert_mult` on `OccupiedEntry` for an API that returns
1316    /// all values.
1317    ///
1318    /// The key is not updated, though; this matters for types that can be `==`
1319    /// without being identical.
1320    ///
1321    /// # Panics
1322    ///
1323    /// This method panics if capacity exceeds max `HeaderMap` capacity
1324    ///
1325    /// # Examples
1326    ///
1327    /// ```
1328    /// # use rama_http_types::HeaderMap;
1329    /// # use rama_http_types::header::HOST;
1330    /// let mut map = HeaderMap::new();
1331    /// assert!(map.insert(HOST, "world".parse().unwrap()).is_none());
1332    /// assert!(!map.is_empty());
1333    ///
1334    /// let mut prev = map.insert(HOST, "earth".parse().unwrap()).unwrap();
1335    /// assert_eq!("world", prev);
1336    /// ```
1337    pub fn insert<K>(&mut self, key: K, val: T) -> Option<T>
1338    where
1339        K: IntoHeaderName,
1340    {
1341        self.try_insert(key, val).expect("size overflows MAX_SIZE")
1342    }
1343
1344    /// Inserts a key-value pair into the map.
1345    ///
1346    /// If the map did not previously have this key present, then `None` is
1347    /// returned.
1348    ///
1349    /// If the map did have this key present, the new value is associated with
1350    /// the key and all previous values are removed. **Note** that only a single
1351    /// one of the previous values is returned. If there are multiple values
1352    /// that have been previously associated with the key, then the first one is
1353    /// returned. See `insert_mult` on `OccupiedEntry` for an API that returns
1354    /// all values.
1355    ///
1356    /// The key is not updated, though; this matters for types that can be `==`
1357    /// without being identical.
1358    ///
1359    /// # Errors
1360    ///
1361    /// This function may return an error if `HeaderMap` exceeds max capacity
1362    ///
1363    /// # Examples
1364    ///
1365    /// ```
1366    /// # use rama_http_types::HeaderMap;
1367    /// # use rama_http_types::header::HOST;
1368    /// let mut map = HeaderMap::new();
1369    /// assert!(map.try_insert(HOST, "world".parse().unwrap()).unwrap().is_none());
1370    /// assert!(!map.is_empty());
1371    ///
1372    /// let mut prev = map.try_insert(HOST, "earth".parse().unwrap()).unwrap().unwrap();
1373    /// assert_eq!("world", prev);
1374    /// ```
1375    pub fn try_insert<K>(&mut self, key: K, val: T) -> Result<Option<T>, MaxSizeReached>
1376    where
1377        K: IntoHeaderName,
1378    {
1379        key.try_insert(self, val)
1380    }
1381
1382    #[inline]
1383    fn try_insert2<K>(&mut self, key: K, value: T) -> Result<Option<T>, MaxSizeReached>
1384    where
1385        K: Into<HeaderName>,
1386    {
1387        self.try_reserve_one()?;
1388        let key = key.into();
1389
1390        Ok(insert_phase_one!(
1391            self,
1392            key,
1393            probe,
1394            pos,
1395            hash,
1396            danger,
1397            // Vacant
1398            {
1399                let _ = danger; // Make lint happy
1400                let index = self.entries.len();
1401                self.try_insert_entry(hash, key.into(), value)?;
1402                self.indices[probe] = Pos::new(index, hash);
1403                None
1404            },
1405            // Occupied
1406            Some(self.insert_occupied(pos, key, value)),
1407            // Robinhood
1408            {
1409                self.try_insert_phase_two(key.into(), value, hash, probe, danger)?;
1410                None
1411            }
1412        ))
1413    }
1414
1415    /// Set an occupied bucket to the given value
1416    #[inline]
1417    fn insert_occupied(&mut self, index: usize, key: HeaderName, value: T) -> T {
1418        let old = self.insert_occupied_same_key(index, value);
1419        self.entries[index].key = key;
1420        old
1421    }
1422
1423    /// Set an occupied bucket to the given value without changing its key.
1424    #[inline]
1425    fn insert_occupied_same_key(&mut self, index: usize, value: T) -> T {
1426        if let Some(links) = self.entries[index].links {
1427            self.remove_all_extra_values(links.next);
1428        }
1429
1430        let entry = &mut self.entries[index];
1431        mem::replace(&mut entry.value, value)
1432    }
1433
1434    fn insert_occupied_mult(
1435        &mut self,
1436        index: usize,
1437        key: HeaderName,
1438        value: T,
1439    ) -> ValueDrain<'_, T> {
1440        self.insert_occupied_mult_inner(index, Some(key), value)
1441    }
1442
1443    fn insert_occupied_mult_same_key(&mut self, index: usize, value: T) -> ValueDrain<'_, T> {
1444        self.insert_occupied_mult_inner(index, None, value)
1445    }
1446
1447    fn insert_occupied_mult_inner(
1448        &mut self,
1449        index: usize,
1450        key: Option<HeaderName>,
1451        value: T,
1452    ) -> ValueDrain<'_, T> {
1453        let old;
1454        let links;
1455
1456        {
1457            let entry = &mut self.entries[index];
1458
1459            old = mem::replace(&mut entry.value, value);
1460            if let Some(key) = key {
1461                entry.key = key;
1462            }
1463            links = entry.links;
1464        }
1465
1466        let next = links.map(|l| self.drain_all_extra_values(l.next).into_iter());
1467
1468        ValueDrain {
1469            first: Some(old),
1470            next,
1471            lt: PhantomData,
1472        }
1473    }
1474
1475    /// Inserts a key-value pair into the map.
1476    ///
1477    /// If the map did not previously have this key present, then `false` is
1478    /// returned.
1479    ///
1480    /// If the map did have this key present, the new value is pushed to the end
1481    /// of the list of values currently associated with the key. The key is not
1482    /// updated, though; this matters for types that can be `==` without being
1483    /// identical.
1484    ///
1485    /// # Panics
1486    ///
1487    /// This method panics if capacity exceeds max `HeaderMap` capacity
1488    ///
1489    /// # Examples
1490    ///
1491    /// ```
1492    /// # use rama_http_types::HeaderMap;
1493    /// # use rama_http_types::header::HOST;
1494    /// let mut map = HeaderMap::new();
1495    /// assert!(map.insert(HOST, "world".parse().unwrap()).is_none());
1496    /// assert!(!map.is_empty());
1497    ///
1498    /// map.append(HOST, "earth".parse().unwrap());
1499    ///
1500    /// let values = map.get_all("host");
1501    /// let mut i = values.iter();
1502    /// assert_eq!("world", *i.next().unwrap());
1503    /// assert_eq!("earth", *i.next().unwrap());
1504    /// ```
1505    pub fn append<K>(&mut self, key: K, value: T) -> bool
1506    where
1507        K: IntoHeaderName,
1508    {
1509        self.try_append(key, value)
1510            .expect("size overflows MAX_SIZE")
1511    }
1512
1513    /// Inserts a key-value pair into the map.
1514    ///
1515    /// If the map did not previously have this key present, then `false` is
1516    /// returned.
1517    ///
1518    /// If the map did have this key present, the new value is pushed to the end
1519    /// of the list of values currently associated with the key. The key is not
1520    /// updated, though; this matters for types that can be `==` without being
1521    /// identical.
1522    ///
1523    /// # Errors
1524    ///
1525    /// This function may return an error if `HeaderMap` exceeds max capacity
1526    ///
1527    /// # Examples
1528    ///
1529    /// ```
1530    /// # use rama_http_types::HeaderMap;
1531    /// # use rama_http_types::header::HOST;
1532    /// let mut map = HeaderMap::new();
1533    /// assert!(map.try_insert(HOST, "world".parse().unwrap()).unwrap().is_none());
1534    /// assert!(!map.is_empty());
1535    ///
1536    /// map.try_append(HOST, "earth".parse().unwrap()).unwrap();
1537    ///
1538    /// let values = map.get_all("host");
1539    /// let mut i = values.iter();
1540    /// assert_eq!("world", *i.next().unwrap());
1541    /// assert_eq!("earth", *i.next().unwrap());
1542    /// ```
1543    pub fn try_append<K>(&mut self, key: K, value: T) -> Result<bool, MaxSizeReached>
1544    where
1545        K: IntoHeaderName,
1546    {
1547        key.try_append(self, value)
1548    }
1549
1550    #[inline]
1551    fn try_append2<K>(&mut self, key: K, value: T) -> Result<bool, MaxSizeReached>
1552    where
1553        K: Into<HeaderName>,
1554    {
1555        self.try_reserve_one()?;
1556        let key = key.into();
1557
1558        Ok(insert_phase_one!(
1559            self,
1560            key,
1561            probe,
1562            pos,
1563            hash,
1564            danger,
1565            // Vacant
1566            {
1567                let _ = danger;
1568                let index = self.entries.len();
1569                self.try_insert_entry(hash, key.into(), value)?;
1570                self.indices[probe] = Pos::new(index, hash);
1571                false
1572            },
1573            // Occupied
1574            {
1575                self.append_value(pos, key, value);
1576                true
1577            },
1578            // Robinhood
1579            {
1580                self.try_insert_phase_two(key.into(), value, hash, probe, danger)?;
1581
1582                false
1583            }
1584        ))
1585    }
1586
1587    #[inline]
1588    fn find<K>(&self, key: &K) -> Option<(usize, usize)>
1589    where
1590        K: Hash + Into<HeaderName> + ?Sized,
1591        HeaderName: PartialEq<K>,
1592    {
1593        if self.entries.is_empty() {
1594            return None;
1595        }
1596
1597        let hash = hash_elem_using(&self.danger, key);
1598        let mask = self.mask;
1599        let mut probe = desired_pos(mask, hash);
1600        let mut dist = 0;
1601
1602        probe_loop!(probe < self.indices.len(), {
1603            if let Some((i, entry_hash)) = self.indices[probe].resolve() {
1604                if dist > probe_distance(mask, entry_hash, probe) {
1605                    // give up when probe distance is too long
1606                    return None;
1607                } else if entry_hash == hash && self.entries[i].key == *key {
1608                    return Some((probe, i));
1609                }
1610            } else {
1611                return None;
1612            }
1613
1614            dist += 1;
1615        });
1616    }
1617
1618    /// phase 2 is post-insert where we forward-shift `Pos` in the indices.
1619    #[inline]
1620    fn try_insert_phase_two(
1621        &mut self,
1622        key: HeaderName,
1623        value: T,
1624        hash: HashValue,
1625        probe: usize,
1626        danger: bool,
1627    ) -> Result<usize, MaxSizeReached> {
1628        // Push the value and get the index
1629        let index = self.entries.len();
1630        self.try_insert_entry(hash, key, value)?;
1631
1632        let num_displaced = do_insert_phase_two(&mut self.indices, probe, Pos::new(index, hash));
1633
1634        if danger || num_displaced >= DISPLACEMENT_THRESHOLD {
1635            // Increase danger level
1636            self.danger.set_yellow();
1637        }
1638
1639        Ok(index)
1640    }
1641
1642    /// Removes a key from the map, returning the value associated with the key.
1643    ///
1644    /// Returns `None` if the map does not contain the key. If there are
1645    /// multiple values associated with the key, then the first one is returned.
1646    /// See `remove_entry_mult` on `OccupiedEntry` for an API that yields all
1647    /// values.
1648    ///
1649    /// # Examples
1650    ///
1651    /// ```
1652    /// # use rama_http_types::HeaderMap;
1653    /// # use rama_http_types::header::HOST;
1654    /// let mut map = HeaderMap::new();
1655    /// map.insert(HOST, "hello.world".parse().unwrap());
1656    ///
1657    /// let prev = map.remove(HOST).unwrap();
1658    /// assert_eq!("hello.world", prev);
1659    ///
1660    /// assert!(map.remove(HOST).is_none());
1661    /// ```
1662    pub fn remove<K>(&mut self, key: K) -> Option<T>
1663    where
1664        K: AsHeaderName,
1665    {
1666        match key.find(self) {
1667            Some((probe, idx)) => {
1668                if let Some(links) = self.entries[idx].links {
1669                    self.remove_all_extra_values(links.next);
1670                }
1671
1672                let entry = self.remove_found(probe, idx);
1673
1674                Some(entry.value)
1675            }
1676            None => None,
1677        }
1678    }
1679
1680    /// Remove an entry from the map.
1681    ///
1682    /// Warning: To avoid inconsistent state, extra values _must_ be removed
1683    /// for the `found` index (via `remove_all_extra_values` or similar)
1684    /// _before_ this method is called.
1685    #[inline]
1686    fn remove_found(&mut self, probe: usize, found: usize) -> Bucket<T> {
1687        self.remove_order(self.entries[found].order);
1688
1689        // index `probe` and entry `found` is to be removed
1690        // use swap_remove, but then we need to update the index that points
1691        // to the other entry that has to move
1692        self.indices[probe] = Pos::none();
1693        let entry = self.entries.swap_remove(found);
1694
1695        // correct index that points to the entry that had to swap places
1696        if found < self.entries.len() {
1697            let order = self.entries[found].order;
1698            self.set_order_link(order, Link::Entry(found));
1699
1700            let entry = &self.entries[found];
1701            // was not last element
1702            // examine new element in `found` and find it in indices
1703            let mut probe = desired_pos(self.mask, entry.hash);
1704
1705            probe_loop!(probe < self.indices.len(), {
1706                if let Some((i, _)) = self.indices[probe].resolve() {
1707                    if i >= self.entries.len() {
1708                        // found it
1709                        self.indices[probe] = Pos::new(found, entry.hash);
1710                        break;
1711                    }
1712                }
1713            });
1714
1715            // Update links
1716            if let Some(links) = entry.links {
1717                self.extra_values[links.next].prev = Link::Entry(found);
1718                self.extra_values[links.tail].next = Link::Entry(found);
1719            }
1720        }
1721
1722        // backward shift deletion in self.indices
1723        // after probe, shift all non-ideally placed indices backward
1724        if !self.entries.is_empty() {
1725            let mut last_probe = probe;
1726            let mut probe = probe + 1;
1727
1728            probe_loop!(probe < self.indices.len(), {
1729                if let Some((_, entry_hash)) = self.indices[probe].resolve() {
1730                    if probe_distance(self.mask, entry_hash, probe) > 0 {
1731                        self.indices[last_probe] = self.indices[probe];
1732                        self.indices[probe] = Pos::none();
1733                    } else {
1734                        break;
1735                    }
1736                } else {
1737                    break;
1738                }
1739
1740                last_probe = probe;
1741            });
1742        }
1743
1744        entry
1745    }
1746
1747    /// Removes the `ExtraValue` at the given index.
1748    #[inline]
1749    fn remove_extra_value(&mut self, idx: usize) -> ExtraValue<T> {
1750        self.remove_order(self.extra_values[idx].order);
1751
1752        let raw_links = self.raw_links();
1753        let extra = remove_extra_value(raw_links, &mut self.extra_values, idx);
1754
1755        if let Some(moved) = self.extra_values.get(idx) {
1756            let order = moved.order;
1757            self.set_order_link(order, Link::Extra(idx));
1758        }
1759
1760        extra
1761    }
1762
1763    fn remove_all_extra_values(&mut self, mut head: usize) {
1764        loop {
1765            let extra = self.remove_extra_value(head);
1766
1767            if let Link::Extra(idx) = extra.next {
1768                head = idx;
1769            } else {
1770                break;
1771            }
1772        }
1773    }
1774
1775    fn drain_all_extra_values(&mut self, mut head: usize) -> Vec<T> {
1776        let mut vec = Vec::new();
1777        loop {
1778            let extra = self.remove_extra_value(head);
1779            vec.push(extra.value);
1780
1781            if let Link::Extra(idx) = extra.next {
1782                head = idx;
1783            } else {
1784                break;
1785            }
1786        }
1787        vec
1788    }
1789
1790    #[inline]
1791    fn try_insert_entry(
1792        &mut self,
1793        hash: HashValue,
1794        key: HeaderName,
1795        value: T,
1796    ) -> Result<(), MaxSizeReached> {
1797        if self.entries.len() >= MAX_SIZE {
1798            return Err(MaxSizeReached::new());
1799        }
1800
1801        let index = self.entries.len();
1802        let order = self.push_order(Link::Entry(index));
1803
1804        self.entries.push(Bucket {
1805            hash,
1806            key,
1807            value,
1808            links: None,
1809            order,
1810        });
1811
1812        Ok(())
1813    }
1814
1815    fn rebuild(&mut self) {
1816        // Loop over all entries and re-insert them into the map
1817        'outer: for (index, entry) in self.entries.iter_mut().enumerate() {
1818            let hash = hash_elem_using(&self.danger, &entry.key);
1819            let mut probe = desired_pos(self.mask, hash);
1820            let mut dist = 0;
1821
1822            // Update the entry's hash code
1823            entry.hash = hash;
1824
1825            probe_loop!(probe < self.indices.len(), {
1826                if let Some((_, entry_hash)) = self.indices[probe].resolve() {
1827                    // if existing element probed less than us, swap
1828                    let their_dist = probe_distance(self.mask, entry_hash, probe);
1829
1830                    if their_dist < dist {
1831                        // Robinhood
1832                        break;
1833                    }
1834                } else {
1835                    // Vacant slot
1836                    self.indices[probe] = Pos::new(index, hash);
1837                    continue 'outer;
1838                }
1839
1840                dist += 1;
1841            });
1842
1843            do_insert_phase_two(&mut self.indices, probe, Pos::new(index, hash));
1844        }
1845    }
1846
1847    fn reinsert_entry_in_order(&mut self, pos: Pos) {
1848        if let Some((_, entry_hash)) = pos.resolve() {
1849            // Find first empty bucket and insert there
1850            let mut probe = desired_pos(self.mask, entry_hash);
1851
1852            probe_loop!(probe < self.indices.len(), {
1853                if self.indices[probe].resolve().is_none() {
1854                    // empty bucket, insert here
1855                    self.indices[probe] = pos;
1856                    return;
1857                }
1858            });
1859        }
1860    }
1861
1862    fn try_reserve_one(&mut self) -> Result<(), MaxSizeReached> {
1863        let len = self.entries.len();
1864
1865        if self.danger.is_yellow() {
1866            // MAX_SIZE (2^15) and LOAD_FACTOR_THRESHOLD is 5, so the product
1867            // cannot overflow.
1868            if self.entries.len() * LOAD_FACTOR_THRESHOLD >= self.indices.len() {
1869                // Transition back to green danger level
1870                self.danger.set_green();
1871
1872                // Double the capacity
1873                let new_cap = self.indices.len() * 2;
1874
1875                // Grow the capacity
1876                self.try_grow(new_cap)?;
1877            } else {
1878                self.danger.set_red();
1879
1880                // Rebuild hash table
1881                for index in self.indices.iter_mut() {
1882                    *index = Pos::none();
1883                }
1884
1885                self.rebuild();
1886            }
1887        } else if len == self.capacity() {
1888            if len == 0 {
1889                let new_raw_cap = 8;
1890                self.mask = 8 - 1;
1891                self.indices = vec![Pos::none(); new_raw_cap].into_boxed_slice();
1892                let cap = usable_capacity(new_raw_cap);
1893                self.entries = Vec::with_capacity(cap);
1894                self.order.reserve_exact(cap);
1895            } else {
1896                let raw_cap = self.indices.len();
1897                self.try_grow(raw_cap << 1)?;
1898            }
1899        }
1900
1901        Ok(())
1902    }
1903
1904    #[inline]
1905    fn try_grow(&mut self, new_raw_cap: usize) -> Result<(), MaxSizeReached> {
1906        if new_raw_cap > MAX_SIZE {
1907            return Err(MaxSizeReached::new());
1908        }
1909
1910        // find first ideally placed element -- start of cluster
1911        let mut first_ideal = 0;
1912
1913        for (i, pos) in self.indices.iter().enumerate() {
1914            if let Some((_, entry_hash)) = pos.resolve() {
1915                if 0 == probe_distance(self.mask, entry_hash, i) {
1916                    first_ideal = i;
1917                    break;
1918                }
1919            }
1920        }
1921
1922        // visit the entries in an order where we can simply reinsert them
1923        // into self.indices without any bucket stealing.
1924        let old_indices = mem::replace(
1925            &mut self.indices,
1926            vec![Pos::none(); new_raw_cap].into_boxed_slice(),
1927        );
1928        self.mask = new_raw_cap.wrapping_sub(1) as Size;
1929
1930        for &pos in &old_indices[first_ideal..] {
1931            self.reinsert_entry_in_order(pos);
1932        }
1933
1934        for &pos in &old_indices[..first_ideal] {
1935            self.reinsert_entry_in_order(pos);
1936        }
1937
1938        // Reserve additional entry slots
1939        let more = self.capacity() - self.entries.len();
1940        self.entries.reserve_exact(more);
1941        self.order.reserve_exact(more);
1942        Ok(())
1943    }
1944
1945    #[inline]
1946    fn raw_links(&mut self) -> RawLinks<T> {
1947        RawLinks(&mut self.entries[..] as *mut _)
1948    }
1949
1950    #[inline]
1951    fn push_order(&mut self, link: Link) -> usize {
1952        let index = self.order.len();
1953        self.order.push(Some(link));
1954        index
1955    }
1956
1957    #[inline]
1958    fn remove_order(&mut self, index: usize) {
1959        if self.order[index].take().is_some() {
1960            self.order_holes += 1;
1961        }
1962    }
1963
1964    #[inline]
1965    fn set_order_link(&mut self, index: usize, link: Link) {
1966        if let Some(slot) = self.order.get_mut(index)
1967            && slot.is_some()
1968        {
1969            *slot = Some(link);
1970        }
1971    }
1972
1973    #[inline]
1974    fn append_value(&mut self, entry_idx: usize, key: HeaderName, value: T) {
1975        let idx = self.extra_values.len();
1976        let order = self.push_order(Link::Extra(idx));
1977        let entry = &mut self.entries[entry_idx];
1978
1979        match entry.links {
1980            Some(links) => {
1981                self.extra_values.push(ExtraValue {
1982                    key,
1983                    value,
1984                    prev: Link::Extra(links.tail),
1985                    next: Link::Entry(entry_idx),
1986                    order,
1987                });
1988
1989                self.extra_values[links.tail].next = Link::Extra(idx);
1990
1991                entry.links = Some(Links { tail: idx, ..links });
1992            }
1993            None => {
1994                self.extra_values.push(ExtraValue {
1995                    key,
1996                    value,
1997                    prev: Link::Entry(entry_idx),
1998                    next: Link::Entry(entry_idx),
1999                    order,
2000                });
2001
2002                entry.links = Some(Links {
2003                    next: idx,
2004                    tail: idx,
2005                });
2006            }
2007        }
2008    }
2009}
2010
2011/// Removes the `ExtraValue` at the given index.
2012#[inline]
2013fn remove_extra_value<T>(
2014    mut raw_links: RawLinks<T>,
2015    extra_values: &mut Vec<ExtraValue<T>>,
2016    idx: usize,
2017) -> ExtraValue<T> {
2018    let prev;
2019    let next;
2020
2021    {
2022        debug_assert!(extra_values.len() > idx);
2023        let extra = &extra_values[idx];
2024        prev = extra.prev;
2025        next = extra.next;
2026    }
2027
2028    // First unlink the extra value
2029    match (prev, next) {
2030        (Link::Entry(prev), Link::Entry(next)) => {
2031            debug_assert_eq!(prev, next);
2032
2033            raw_links[prev] = None;
2034        }
2035        (Link::Entry(prev), Link::Extra(next)) => {
2036            debug_assert!(raw_links[prev].is_some());
2037
2038            raw_links[prev].as_mut().unwrap().next = next;
2039
2040            debug_assert!(extra_values.len() > next);
2041            extra_values[next].prev = Link::Entry(prev);
2042        }
2043        (Link::Extra(prev), Link::Entry(next)) => {
2044            debug_assert!(raw_links[next].is_some());
2045
2046            raw_links[next].as_mut().unwrap().tail = prev;
2047
2048            debug_assert!(extra_values.len() > prev);
2049            extra_values[prev].next = Link::Entry(next);
2050        }
2051        (Link::Extra(prev), Link::Extra(next)) => {
2052            debug_assert!(extra_values.len() > next);
2053            debug_assert!(extra_values.len() > prev);
2054
2055            extra_values[prev].next = Link::Extra(next);
2056            extra_values[next].prev = Link::Extra(prev);
2057        }
2058    }
2059
2060    // Remove the extra value
2061    let mut extra = extra_values.swap_remove(idx);
2062
2063    // This is the index of the value that was moved (possibly `extra`)
2064    let old_idx = extra_values.len();
2065
2066    // Update the links
2067    if extra.prev == Link::Extra(old_idx) {
2068        extra.prev = Link::Extra(idx);
2069    }
2070
2071    if extra.next == Link::Extra(old_idx) {
2072        extra.next = Link::Extra(idx);
2073    }
2074
2075    // Check if another entry was displaced. If it was, then the links
2076    // need to be fixed.
2077    if idx != old_idx {
2078        let next;
2079        let prev;
2080
2081        {
2082            debug_assert!(extra_values.len() > idx);
2083            let moved = &extra_values[idx];
2084            next = moved.next;
2085            prev = moved.prev;
2086        }
2087
2088        // An entry was moved, we have to the links
2089        match prev {
2090            Link::Entry(entry_idx) => {
2091                // It is critical that we do not attempt to read the
2092                // header name or value as that memory may have been
2093                // "released" already.
2094                debug_assert!(raw_links[entry_idx].is_some());
2095
2096                let links = raw_links[entry_idx].as_mut().unwrap();
2097                links.next = idx;
2098            }
2099            Link::Extra(extra_idx) => {
2100                debug_assert!(extra_values.len() > extra_idx);
2101                extra_values[extra_idx].next = Link::Extra(idx);
2102            }
2103        }
2104
2105        match next {
2106            Link::Entry(entry_idx) => {
2107                debug_assert!(raw_links[entry_idx].is_some());
2108
2109                let links = raw_links[entry_idx].as_mut().unwrap();
2110                links.tail = idx;
2111            }
2112            Link::Extra(extra_idx) => {
2113                debug_assert!(extra_values.len() > extra_idx);
2114                extra_values[extra_idx].prev = Link::Extra(idx);
2115            }
2116        }
2117    }
2118
2119    debug_assert!({
2120        for v in &*extra_values {
2121            assert!(v.next != Link::Extra(old_idx));
2122            assert!(v.prev != Link::Extra(old_idx));
2123        }
2124
2125        true
2126    });
2127
2128    extra
2129}
2130
2131impl<'a, T> IntoIterator for &'a HeaderMap<T> {
2132    type Item = (&'a HeaderName, &'a T);
2133    type IntoIter = Iter<'a, T>;
2134
2135    fn into_iter(self) -> Iter<'a, T> {
2136        self.iter()
2137    }
2138}
2139
2140impl<'a, T> IntoIterator for &'a mut HeaderMap<T> {
2141    type Item = (&'a HeaderName, &'a mut T);
2142    type IntoIter = IterMut<'a, T>;
2143
2144    fn into_iter(self) -> IterMut<'a, T> {
2145        self.iter_mut()
2146    }
2147}
2148
2149impl<T> IntoIterator for HeaderMap<T> {
2150    type Item = (Option<HeaderName>, T);
2151    type IntoIter = IntoIter<T>;
2152
2153    /// Creates a consuming iterator, that is, one that moves keys and values
2154    /// out of the map in arbitrary order. The map cannot be used after calling
2155    /// this.
2156    ///
2157    /// For each yielded item that has `None` provided for the `HeaderName`,
2158    /// then the associated header name is the same as that of the previously
2159    /// yielded item. The first yielded item will have `HeaderName` set.
2160    ///
2161    /// # Examples
2162    ///
2163    /// Basic usage.
2164    ///
2165    /// ```
2166    /// # use rama_http_types::header;
2167    /// # use rama_http_types::header::*;
2168    /// let mut map = HeaderMap::new();
2169    /// map.insert(header::CONTENT_LENGTH, "123".parse().unwrap());
2170    /// map.insert(header::CONTENT_TYPE, "json".parse().unwrap());
2171    ///
2172    /// let mut iter = map.into_iter();
2173    /// assert_eq!(iter.next(), Some((Some(header::CONTENT_LENGTH), "123".parse().unwrap())));
2174    /// assert_eq!(iter.next(), Some((Some(header::CONTENT_TYPE), "json".parse().unwrap())));
2175    /// assert!(iter.next().is_none());
2176    /// ```
2177    ///
2178    /// Multiple values per key.
2179    ///
2180    /// ```
2181    /// # use rama_http_types::header;
2182    /// # use rama_http_types::header::*;
2183    /// let mut map = HeaderMap::new();
2184    ///
2185    /// map.append(header::CONTENT_LENGTH, "123".parse().unwrap());
2186    /// map.append(header::CONTENT_LENGTH, "456".parse().unwrap());
2187    ///
2188    /// map.append(header::CONTENT_TYPE, "json".parse().unwrap());
2189    /// map.append(header::CONTENT_TYPE, "html".parse().unwrap());
2190    /// map.append(header::CONTENT_TYPE, "xml".parse().unwrap());
2191    ///
2192    /// let mut iter = map.into_iter();
2193    ///
2194    /// assert_eq!(iter.next(), Some((Some(header::CONTENT_LENGTH), "123".parse().unwrap())));
2195    /// assert_eq!(iter.next(), Some((None, "456".parse().unwrap())));
2196    ///
2197    /// assert_eq!(iter.next(), Some((Some(header::CONTENT_TYPE), "json".parse().unwrap())));
2198    /// assert_eq!(iter.next(), Some((None, "html".parse().unwrap())));
2199    /// assert_eq!(iter.next(), Some((None, "xml".parse().unwrap())));
2200    /// assert!(iter.next().is_none());
2201    /// ```
2202    fn into_iter(self) -> IntoIter<T> {
2203        IntoIter {
2204            next: None,
2205            entries: self.entries.into_iter(),
2206            extra_values: self.extra_values,
2207        }
2208    }
2209}
2210
2211impl<T> HeaderMap<T> {
2212    /// Creates a consuming iterator over entries in their original insertion
2213    /// order.
2214    ///
2215    /// Each yielded `HeaderName` preserves the casing that was used for that
2216    /// field line when it was inserted into the map.
2217    pub fn into_ordered_iter(self) -> IntoOrderedIter<T> {
2218        IntoOrderedIter {
2219            index: 0,
2220            order: self.order,
2221            entries: self.entries,
2222            extra_values: self.extra_values,
2223        }
2224    }
2225}
2226
2227impl<T> FromIterator<(HeaderName, T)> for HeaderMap<T> {
2228    fn from_iter<I>(iter: I) -> Self
2229    where
2230        I: IntoIterator<Item = (HeaderName, T)>,
2231    {
2232        let mut map = HeaderMap::default();
2233        map.extend(iter);
2234        map
2235    }
2236}
2237
2238/// Try to convert a `HashMap` into a `HeaderMap`.
2239///
2240/// # Examples
2241///
2242/// ```
2243/// use std::collections::HashMap;
2244/// use std::convert::TryInto;
2245/// use rama_http_types::HeaderMap;
2246///
2247/// let mut map = HashMap::new();
2248/// map.insert("X-Custom-Header".to_string(), "my value".to_string());
2249///
2250/// let headers: HeaderMap = (&map).try_into().expect("valid headers");
2251/// assert_eq!(headers["X-Custom-Header"], "my value");
2252/// ```
2253impl<'a, K, V, S, T> TryFrom<&'a HashMap<K, V, S>> for HeaderMap<T>
2254where
2255    K: Eq + Hash,
2256    HeaderName: TryFrom<&'a K>,
2257    <HeaderName as TryFrom<&'a K>>::Error: Into<crate::Error>,
2258    T: TryFrom<&'a V>,
2259    T::Error: Into<crate::Error>,
2260{
2261    type Error = Error;
2262
2263    fn try_from(c: &'a HashMap<K, V, S>) -> Result<Self, Self::Error> {
2264        c.iter()
2265            .map(|(k, v)| -> crate::Result<(HeaderName, T)> {
2266                let name = TryFrom::try_from(k).map_err(Into::into)?;
2267                let value = TryFrom::try_from(v).map_err(Into::into)?;
2268                Ok((name, value))
2269            })
2270            .collect()
2271    }
2272}
2273
2274impl<T> Extend<(Option<HeaderName>, T)> for HeaderMap<T> {
2275    /// Extend a `HeaderMap` with the contents of another `HeaderMap`.
2276    ///
2277    /// This function expects the yielded items to follow the same structure as
2278    /// `IntoIter`.
2279    ///
2280    /// # Panics
2281    ///
2282    /// This panics if the first yielded item does not have a `HeaderName`.
2283    ///
2284    /// # Examples
2285    ///
2286    /// ```
2287    /// # use rama_http_types::header::*;
2288    /// let mut map = HeaderMap::new();
2289    ///
2290    /// map.insert(ACCEPT, "text/plain".parse().unwrap());
2291    /// map.insert(HOST, "hello.world".parse().unwrap());
2292    ///
2293    /// let mut extra = HeaderMap::new();
2294    ///
2295    /// extra.insert(HOST, "foo.bar".parse().unwrap());
2296    /// extra.insert(COOKIE, "hello".parse().unwrap());
2297    /// extra.append(COOKIE, "world".parse().unwrap());
2298    ///
2299    /// map.extend(extra);
2300    ///
2301    /// assert_eq!(map["host"], "foo.bar");
2302    /// assert_eq!(map["accept"], "text/plain");
2303    /// assert_eq!(map["cookie"], "hello");
2304    ///
2305    /// let v = map.get_all("host");
2306    /// assert_eq!(1, v.iter().count());
2307    ///
2308    /// let v = map.get_all("cookie");
2309    /// assert_eq!(2, v.iter().count());
2310    /// ```
2311    fn extend<I: IntoIterator<Item = (Option<HeaderName>, T)>>(&mut self, iter: I) {
2312        let mut iter = iter.into_iter();
2313
2314        // Reserve capacity similar to the (HeaderName, T) impl.
2315        // Keys may be already present or show multiple times in the iterator.
2316        // Reserve the entire hint lower bound if the map is empty.
2317        // Otherwise reserve half the hint (rounded up), so the map
2318        // will only resize twice in the worst case.
2319        let hint = if self.is_empty() {
2320            iter.size_hint().0
2321        } else {
2322            (iter.size_hint().0 + 1) / 2
2323        };
2324
2325        // Clamp the hint so an over-estimate cannot overflow `reserve`.
2326        let max_reserve = usable_capacity(MAX_SIZE).saturating_sub(self.entries.len());
2327        let reserve = hint.min(max_reserve);
2328
2329        self.reserve(reserve);
2330
2331        // The structure of this is a bit weird, but it is mostly to make the
2332        // borrow checker happy.
2333        let (mut key, mut val) = match iter.next() {
2334            Some((Some(key), val)) => (key, val),
2335            Some((None, _)) => panic!("expected a header name, but got None"),
2336            None => return,
2337        };
2338
2339        'outer: loop {
2340            let mut entry = match self.try_entry2(key).expect("size overflows MAX_SIZE") {
2341                Entry::Occupied(mut e) => {
2342                    // Replace all previous values while maintaining a handle to
2343                    // the entry.
2344                    e.insert(val);
2345                    e
2346                }
2347                Entry::Vacant(e) => e.insert_entry(val),
2348            };
2349
2350            // As long as `HeaderName` is none, keep inserting the value into
2351            // the current entry
2352            loop {
2353                match iter.next() {
2354                    Some((Some(k), v)) => {
2355                        key = k;
2356                        val = v;
2357                        continue 'outer;
2358                    }
2359                    Some((None, v)) => {
2360                        entry.append(v);
2361                    }
2362                    None => {
2363                        return;
2364                    }
2365                }
2366            }
2367        }
2368    }
2369}
2370
2371impl<T> Extend<(HeaderName, T)> for HeaderMap<T> {
2372    fn extend<I: IntoIterator<Item = (HeaderName, T)>>(&mut self, iter: I) {
2373        // Keys may be already present or show multiple times in the iterator.
2374        // Reserve the entire hint lower bound if the map is empty.
2375        // Otherwise reserve half the hint (rounded up), so the map
2376        // will only resize twice in the worst case.
2377        let iter = iter.into_iter();
2378
2379        let hint = if self.is_empty() {
2380            iter.size_hint().0
2381        } else {
2382            (iter.size_hint().0 + 1) / 2
2383        };
2384
2385        // Clamp the hint so an over-estimate cannot overflow `reserve`.
2386        let max_reserve = usable_capacity(MAX_SIZE).saturating_sub(self.entries.len());
2387        let reserve = hint.min(max_reserve);
2388
2389        self.reserve(reserve);
2390
2391        for (k, v) in iter {
2392            self.append(k, v);
2393        }
2394    }
2395}
2396
2397impl<T: PartialEq> PartialEq for HeaderMap<T> {
2398    fn eq(&self, other: &HeaderMap<T>) -> bool {
2399        if self.len() != other.len() {
2400            return false;
2401        }
2402
2403        self.keys()
2404            .all(|key| self.get_all(key) == other.get_all(key))
2405    }
2406}
2407
2408impl<T: Eq> Eq for HeaderMap<T> {}
2409
2410impl<T: fmt::Debug> fmt::Debug for HeaderMap<T> {
2411    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2412        f.debug_map().entries(self.iter()).finish()
2413    }
2414}
2415
2416impl serde::Serialize for HeaderMap<HeaderValue> {
2417    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2418    where
2419        S: serde::Serializer,
2420    {
2421        self.ordered_iter()
2422            .collect::<Vec<_>>()
2423            .serialize(serializer)
2424    }
2425}
2426
2427impl<'de> serde::Deserialize<'de> for HeaderMap<HeaderValue> {
2428    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2429    where
2430        D: serde::Deserializer<'de>,
2431    {
2432        Vec::<(HeaderName, HeaderValue)>::deserialize(deserializer)
2433            .map(|headers| headers.into_iter().collect())
2434    }
2435}
2436
2437impl<K, T> ops::Index<K> for HeaderMap<T>
2438where
2439    K: AsHeaderName,
2440{
2441    type Output = T;
2442
2443    /// # Panics
2444    /// Using the index operator will cause a panic if the header you're querying isn't set.
2445    #[inline]
2446    fn index(&self, index: K) -> &T {
2447        match self.get2(&index) {
2448            Some(val) => val,
2449            None => panic!("no entry found for key {:?}", index.as_str()),
2450        }
2451    }
2452}
2453
2454/// phase 2 is post-insert where we forward-shift `Pos` in the indices.
2455///
2456/// returns the number of displaced elements
2457#[inline]
2458fn do_insert_phase_two(indices: &mut [Pos], mut probe: usize, mut old_pos: Pos) -> usize {
2459    let mut num_displaced = 0;
2460
2461    probe_loop!(probe < indices.len(), {
2462        let pos = &mut indices[probe];
2463
2464        if pos.is_none() {
2465            *pos = old_pos;
2466            break;
2467        } else {
2468            num_displaced += 1;
2469            old_pos = mem::replace(pos, old_pos);
2470        }
2471    });
2472
2473    num_displaced
2474}
2475
2476// ===== impl Iter =====
2477
2478impl<'a, T> Iterator for Iter<'a, T> {
2479    type Item = (&'a HeaderName, &'a T);
2480
2481    fn next(&mut self) -> Option<Self::Item> {
2482        use self::Cursor::*;
2483
2484        if self.cursor.is_none() {
2485            if (self.entry + 1) >= self.map.entries.len() {
2486                return None;
2487            }
2488
2489            self.entry += 1;
2490            self.cursor = Some(Cursor::Head);
2491        }
2492
2493        let entry = &self.map.entries[self.entry];
2494
2495        match self.cursor.unwrap() {
2496            Head => {
2497                self.cursor = entry.links.map(|l| Values(l.next));
2498                Some((&entry.key, &entry.value))
2499            }
2500            Values(idx) => {
2501                let extra = &self.map.extra_values[idx];
2502
2503                match extra.next {
2504                    Link::Entry(_) => self.cursor = None,
2505                    Link::Extra(i) => self.cursor = Some(Values(i)),
2506                }
2507
2508                Some((&entry.key, &extra.value))
2509            }
2510        }
2511    }
2512
2513    fn size_hint(&self) -> (usize, Option<usize>) {
2514        let map = self.map;
2515        debug_assert!(map.entries.len() >= self.entry);
2516
2517        let lower = map.entries.len() - self.entry;
2518        // We could pessimistically guess at the upper bound, saying
2519        // that its lower + map.extra_values.len(). That could be
2520        // way over though, such as if we're near the end, and have
2521        // already gone through several extra values...
2522        (lower, None)
2523    }
2524}
2525
2526impl<'a, T> FusedIterator for Iter<'a, T> {}
2527
2528unsafe impl<'a, T: Sync> Sync for Iter<'a, T> {}
2529unsafe impl<'a, T: Sync> Send for Iter<'a, T> {}
2530
2531// ===== impl OrderedIter =====
2532
2533impl<'a, T> Iterator for OrderedIter<'a, T> {
2534    type Item = (&'a HeaderName, &'a T);
2535
2536    fn next(&mut self) -> Option<Self::Item> {
2537        while self.index < self.map.order.len() {
2538            let link = self.map.order[self.index];
2539            self.index += 1;
2540
2541            if let Some(link) = link {
2542                return match link {
2543                    Link::Entry(idx) => {
2544                        let entry = &self.map.entries[idx];
2545                        Some((&entry.key, &entry.value))
2546                    }
2547                    Link::Extra(idx) => {
2548                        let extra = &self.map.extra_values[idx];
2549                        Some((&extra.key, &extra.value))
2550                    }
2551                };
2552            }
2553        }
2554
2555        None
2556    }
2557
2558    fn size_hint(&self) -> (usize, Option<usize>) {
2559        let remaining = self.map.order[self.index..]
2560            .iter()
2561            .filter(|link| link.is_some())
2562            .count();
2563        (remaining, Some(remaining))
2564    }
2565}
2566
2567impl<'a, T> FusedIterator for OrderedIter<'a, T> {}
2568
2569unsafe impl<'a, T: Sync> Sync for OrderedIter<'a, T> {}
2570unsafe impl<'a, T: Sync> Send for OrderedIter<'a, T> {}
2571
2572// ===== impl IterMut =====
2573
2574impl<'a, T> IterMut<'a, T> {
2575    fn next_unsafe(&mut self) -> Option<(*const HeaderName, *mut T)> {
2576        use self::Cursor::*;
2577
2578        if self.cursor.is_none() {
2579            if (self.entry + 1) >= self.entries_len {
2580                return None;
2581            }
2582
2583            self.entry += 1;
2584            self.cursor = Some(Cursor::Head);
2585        }
2586
2587        // SAFETY: `self.entry < self.entries_len`, and the iterator has
2588        // exclusive access to the underlying map for `'a`, so the `entries`
2589        // allocation remains valid for the lifetime of the iterator.
2590        let entry = unsafe { self.entries.add(self.entry) };
2591
2592        match self.cursor.unwrap() {
2593            Head => {
2594                // SAFETY: `entry` points at a live bucket in `entries`.
2595                self.cursor = unsafe { (*entry).links }.map(|l| Values(l.next));
2596                // SAFETY: `entry` points at a live bucket, and the iterator only
2597                // yields each slot at most once, so materializing these field
2598                // pointers does not alias another yielded `&mut T`.
2599                Some(unsafe {
2600                    (
2601                        ptr::addr_of!((*entry).key),
2602                        ptr::addr_of_mut!((*entry).value),
2603                    )
2604                })
2605            }
2606            Values(idx) => {
2607                // SAFETY: `idx` comes from the `links` chain stored in a live
2608                // bucket / extra value, so it points at a live `extra_values`
2609                // slot for the duration of iteration.
2610                let extra = unsafe { self.extra_values.add(idx) };
2611
2612                // SAFETY: `extra` points at a live extra value.
2613                match unsafe { (*extra).next } {
2614                    Link::Entry(_) => self.cursor = None,
2615                    Link::Extra(i) => self.cursor = Some(Values(i)),
2616                }
2617
2618                // SAFETY: `entry` and `extra` both point at live elements in the
2619                // map backing storage, and the iterator only yields each value
2620                // slot at most once.
2621                Some(unsafe {
2622                    (
2623                        ptr::addr_of!((*entry).key),
2624                        ptr::addr_of_mut!((*extra).value),
2625                    )
2626                })
2627            }
2628        }
2629    }
2630}
2631
2632impl<'a, T> Iterator for IterMut<'a, T> {
2633    type Item = (&'a HeaderName, &'a mut T);
2634
2635    fn next(&mut self) -> Option<Self::Item> {
2636        self.next_unsafe()
2637            .map(|(key, ptr)| (unsafe { &*key }, unsafe { &mut *ptr }))
2638    }
2639
2640    fn size_hint(&self) -> (usize, Option<usize>) {
2641        debug_assert!(self.entries_len >= self.entry);
2642
2643        let lower = self.entries_len - self.entry;
2644        // We could pessimistically guess at the upper bound, saying
2645        // that its lower + map.extra_values.len(). That could be
2646        // way over though, such as if we're near the end, and have
2647        // already gone through several extra values...
2648        (lower, None)
2649    }
2650}
2651
2652impl<'a, T> FusedIterator for IterMut<'a, T> {}
2653
2654unsafe impl<'a, T: Sync> Sync for IterMut<'a, T> {}
2655unsafe impl<'a, T: Send> Send for IterMut<'a, T> {}
2656
2657// ===== impl Keys =====
2658
2659impl<'a, T> Iterator for Keys<'a, T> {
2660    type Item = &'a HeaderName;
2661
2662    fn next(&mut self) -> Option<Self::Item> {
2663        self.inner.next().map(|b| &b.key)
2664    }
2665
2666    fn size_hint(&self) -> (usize, Option<usize>) {
2667        self.inner.size_hint()
2668    }
2669
2670    fn nth(&mut self, n: usize) -> Option<Self::Item> {
2671        self.inner.nth(n).map(|b| &b.key)
2672    }
2673
2674    fn count(self) -> usize {
2675        self.inner.count()
2676    }
2677
2678    fn last(self) -> Option<Self::Item> {
2679        self.inner.last().map(|b| &b.key)
2680    }
2681}
2682
2683impl<'a, T> ExactSizeIterator for Keys<'a, T> {}
2684impl<'a, T> FusedIterator for Keys<'a, T> {}
2685
2686// ===== impl Values ====
2687
2688impl<'a, T> Iterator for Values<'a, T> {
2689    type Item = &'a T;
2690
2691    fn next(&mut self) -> Option<Self::Item> {
2692        self.inner.next().map(|(_, v)| v)
2693    }
2694
2695    fn size_hint(&self) -> (usize, Option<usize>) {
2696        self.inner.size_hint()
2697    }
2698}
2699
2700impl<'a, T> FusedIterator for Values<'a, T> {}
2701
2702// ===== impl ValuesMut ====
2703
2704impl<'a, T> Iterator for ValuesMut<'a, T> {
2705    type Item = &'a mut T;
2706
2707    fn next(&mut self) -> Option<Self::Item> {
2708        self.inner.next().map(|(_, v)| v)
2709    }
2710
2711    fn size_hint(&self) -> (usize, Option<usize>) {
2712        self.inner.size_hint()
2713    }
2714}
2715
2716impl<'a, T> FusedIterator for ValuesMut<'a, T> {}
2717
2718// ===== impl Drain =====
2719
2720impl<'a, T> Iterator for Drain<'a, T> {
2721    type Item = (Option<HeaderName>, T);
2722
2723    fn next(&mut self) -> Option<Self::Item> {
2724        if let Some(next) = self.next {
2725            // Remove the extra value
2726
2727            let raw_links = RawLinks(self.entries);
2728            let extra = unsafe { remove_extra_value(raw_links, &mut *self.extra_values, next) };
2729
2730            match extra.next {
2731                Link::Extra(idx) => self.next = Some(idx),
2732                Link::Entry(_) => self.next = None,
2733            }
2734
2735            return Some((None, extra.value));
2736        }
2737
2738        let idx = self.idx;
2739
2740        if idx == self.len {
2741            return None;
2742        }
2743
2744        self.idx += 1;
2745
2746        unsafe {
2747            let entry = &(*self.entries)[idx];
2748
2749            // Read the header name
2750            let key = ptr::read(&entry.key as *const _);
2751            let value = ptr::read(&entry.value as *const _);
2752            self.next = entry.links.map(|l| l.next);
2753
2754            Some((Some(key), value))
2755        }
2756    }
2757
2758    fn size_hint(&self) -> (usize, Option<usize>) {
2759        // At least this many names... It's unknown if the user wants
2760        // to count the extra_values on top.
2761        //
2762        // For instance, extending a new `HeaderMap` wouldn't need to
2763        // reserve the upper-bound in `entries`, only the lower-bound.
2764        let lower = self.len - self.idx;
2765        let upper = unsafe { (*self.extra_values).len() } + lower;
2766        (lower, Some(upper))
2767    }
2768}
2769
2770impl<'a, T> FusedIterator for Drain<'a, T> {}
2771
2772impl<'a, T> Drop for Drain<'a, T> {
2773    fn drop(&mut self) {
2774        struct Guard<'a, 'b, T>(&'a mut Drain<'b, T>);
2775        struct ExtraValuesGuard<T>(*mut Vec<ExtraValue<T>>);
2776
2777        impl<T> Drop for ExtraValuesGuard<T> {
2778            fn drop(&mut self) {
2779                unsafe {
2780                    (*self.0).set_len(0);
2781                }
2782            }
2783        }
2784
2785        impl<'a, 'b, T> Drop for Guard<'a, 'b, T> {
2786            fn drop(&mut self) {
2787                let _extra_values_guard = ExtraValuesGuard(self.0.extra_values);
2788
2789                for _ in self.0.by_ref() {}
2790            }
2791        }
2792
2793        let guard = Guard(self);
2794
2795        for _ in guard.0.by_ref() {}
2796    }
2797}
2798
2799unsafe impl<'a, T: Sync> Sync for Drain<'a, T> {}
2800unsafe impl<'a, T: Send> Send for Drain<'a, T> {}
2801
2802// ===== impl Entry =====
2803
2804impl<'a, T> Entry<'a, T> {
2805    /// Ensures a value is in the entry by inserting the default if empty.
2806    ///
2807    /// Returns a mutable reference to the **first** value in the entry.
2808    ///
2809    /// # Panics
2810    ///
2811    /// This method panics if capacity exceeds max `HeaderMap` capacity
2812    ///
2813    /// # Examples
2814    ///
2815    /// ```
2816    /// # use rama_http_types::HeaderMap;
2817    /// let mut map: HeaderMap<u32> = HeaderMap::default();
2818    ///
2819    /// let headers = &[
2820    ///     "content-length",
2821    ///     "x-hello",
2822    ///     "Content-Length",
2823    ///     "x-world",
2824    /// ];
2825    ///
2826    /// for &header in headers {
2827    ///     let counter = map.entry(header)
2828    ///         .or_insert(0);
2829    ///     *counter += 1;
2830    /// }
2831    ///
2832    /// assert_eq!(map["content-length"], 2);
2833    /// assert_eq!(map["x-hello"], 1);
2834    /// ```
2835    pub fn or_insert(self, default: T) -> &'a mut T {
2836        self.or_try_insert(default)
2837            .expect("size overflows MAX_SIZE")
2838    }
2839
2840    /// Ensures a value is in the entry by inserting the default if empty.
2841    ///
2842    /// Returns a mutable reference to the **first** value in the entry.
2843    ///
2844    /// # Errors
2845    ///
2846    /// This function may return an error if `HeaderMap` exceeds max capacity
2847    ///
2848    /// # Examples
2849    ///
2850    /// ```
2851    /// # use rama_http_types::HeaderMap;
2852    /// let mut map: HeaderMap<u32> = HeaderMap::default();
2853    ///
2854    /// let headers = &[
2855    ///     "content-length",
2856    ///     "x-hello",
2857    ///     "Content-Length",
2858    ///     "x-world",
2859    /// ];
2860    ///
2861    /// for &header in headers {
2862    ///     let counter = map.entry(header)
2863    ///         .or_try_insert(0)
2864    ///         .unwrap();
2865    ///     *counter += 1;
2866    /// }
2867    ///
2868    /// assert_eq!(map["content-length"], 2);
2869    /// assert_eq!(map["x-hello"], 1);
2870    /// ```
2871    pub fn or_try_insert(self, default: T) -> Result<&'a mut T, MaxSizeReached> {
2872        use self::Entry::*;
2873
2874        match self {
2875            Occupied(e) => Ok(e.into_mut()),
2876            Vacant(e) => e.try_insert(default),
2877        }
2878    }
2879
2880    /// Ensures a value is in the entry by inserting the result of the default
2881    /// function if empty.
2882    ///
2883    /// The default function is not called if the entry exists in the map.
2884    /// Returns a mutable reference to the **first** value in the entry.
2885    ///
2886    /// # Examples
2887    ///
2888    /// Basic usage.
2889    ///
2890    /// ```
2891    /// # use rama_http_types::HeaderMap;
2892    /// let mut map = HeaderMap::new();
2893    ///
2894    /// let res = map.entry("x-hello")
2895    ///     .or_insert_with(|| "world".parse().unwrap());
2896    ///
2897    /// assert_eq!(res, "world");
2898    /// ```
2899    ///
2900    /// The default function is not called if the entry exists in the map.
2901    ///
2902    /// ```
2903    /// # use rama_http_types::HeaderMap;
2904    /// # use rama_http_types::header::HOST;
2905    /// let mut map = HeaderMap::new();
2906    /// map.try_insert(HOST, "world".parse().unwrap()).unwrap();
2907    ///
2908    /// let res = map.try_entry("host")
2909    ///     .unwrap()
2910    ///     .or_try_insert_with(|| unreachable!())
2911    ///     .unwrap();
2912    ///
2913    ///
2914    /// assert_eq!(res, "world");
2915    /// ```
2916    pub fn or_insert_with<F: FnOnce() -> T>(self, default: F) -> &'a mut T {
2917        self.or_try_insert_with(default)
2918            .expect("size overflows MAX_SIZE")
2919    }
2920
2921    /// Ensures a value is in the entry by inserting the result of the default
2922    /// function if empty.
2923    ///
2924    /// The default function is not called if the entry exists in the map.
2925    /// Returns a mutable reference to the **first** value in the entry.
2926    ///
2927    /// # Examples
2928    ///
2929    /// Basic usage.
2930    ///
2931    /// ```
2932    /// # use rama_http_types::HeaderMap;
2933    /// let mut map = HeaderMap::new();
2934    ///
2935    /// let res = map.entry("x-hello")
2936    ///     .or_insert_with(|| "world".parse().unwrap());
2937    ///
2938    /// assert_eq!(res, "world");
2939    /// ```
2940    ///
2941    /// The default function is not called if the entry exists in the map.
2942    ///
2943    /// ```
2944    /// # use rama_http_types::HeaderMap;
2945    /// # use rama_http_types::header::HOST;
2946    /// let mut map = HeaderMap::new();
2947    /// map.try_insert(HOST, "world".parse().unwrap()).unwrap();
2948    ///
2949    /// let res = map.try_entry("host")
2950    ///     .unwrap()
2951    ///     .or_try_insert_with(|| unreachable!())
2952    ///     .unwrap();
2953    ///
2954    ///
2955    /// assert_eq!(res, "world");
2956    /// ```
2957    pub fn or_try_insert_with<F: FnOnce() -> T>(
2958        self,
2959        default: F,
2960    ) -> Result<&'a mut T, MaxSizeReached> {
2961        use self::Entry::*;
2962
2963        match self {
2964            Occupied(e) => Ok(e.into_mut()),
2965            Vacant(e) => e.try_insert(default()),
2966        }
2967    }
2968
2969    /// Returns a reference to the entry's key
2970    ///
2971    /// # Examples
2972    ///
2973    /// ```
2974    /// # use rama_http_types::HeaderMap;
2975    /// let mut map = HeaderMap::new();
2976    ///
2977    /// assert_eq!(map.entry("x-hello").key(), "x-hello");
2978    /// ```
2979    pub fn key(&self) -> &HeaderName {
2980        use self::Entry::*;
2981
2982        match *self {
2983            Vacant(ref e) => e.key(),
2984            Occupied(ref e) => e.key(),
2985        }
2986    }
2987}
2988
2989// ===== impl VacantEntry =====
2990
2991impl<'a, T> VacantEntry<'a, T> {
2992    /// Returns a reference to the entry's key
2993    ///
2994    /// # Examples
2995    ///
2996    /// ```
2997    /// # use rama_http_types::HeaderMap;
2998    /// let mut map = HeaderMap::new();
2999    ///
3000    /// assert_eq!(map.entry("x-hello").key().as_str(), "x-hello");
3001    /// ```
3002    pub fn key(&self) -> &HeaderName {
3003        &self.key
3004    }
3005
3006    /// Take ownership of the key
3007    ///
3008    /// # Examples
3009    ///
3010    /// ```
3011    /// # use rama_http_types::header::{HeaderMap, Entry};
3012    /// let mut map = HeaderMap::new();
3013    ///
3014    /// if let Entry::Vacant(v) = map.entry("x-hello") {
3015    ///     assert_eq!(v.into_key().as_str(), "x-hello");
3016    /// }
3017    /// ```
3018    pub fn into_key(self) -> HeaderName {
3019        self.key
3020    }
3021
3022    /// Insert the value into the entry.
3023    ///
3024    /// The value will be associated with this entry's key. A mutable reference
3025    /// to the inserted value will be returned.
3026    ///
3027    /// # Examples
3028    ///
3029    /// ```
3030    /// # use rama_http_types::header::{HeaderMap, Entry};
3031    /// let mut map = HeaderMap::new();
3032    ///
3033    /// if let Entry::Vacant(v) = map.entry("x-hello") {
3034    ///     v.insert("world".parse().unwrap());
3035    /// }
3036    ///
3037    /// assert_eq!(map["x-hello"], "world");
3038    /// ```
3039    pub fn insert(self, value: T) -> &'a mut T {
3040        self.try_insert(value).expect("size overflows MAX_SIZE")
3041    }
3042
3043    /// Insert the value into the entry.
3044    ///
3045    /// The value will be associated with this entry's key. A mutable reference
3046    /// to the inserted value will be returned.
3047    ///
3048    /// # Examples
3049    ///
3050    /// ```
3051    /// # use rama_http_types::header::{HeaderMap, Entry};
3052    /// let mut map = HeaderMap::new();
3053    ///
3054    /// if let Entry::Vacant(v) = map.entry("x-hello") {
3055    ///     v.insert("world".parse().unwrap());
3056    /// }
3057    ///
3058    /// assert_eq!(map["x-hello"], "world");
3059    /// ```
3060    pub fn try_insert(self, value: T) -> Result<&'a mut T, MaxSizeReached> {
3061        // Ensure that there is space in the map
3062        let index =
3063            self.map
3064                .try_insert_phase_two(self.key, value, self.hash, self.probe, self.danger)?;
3065
3066        Ok(&mut self.map.entries[index].value)
3067    }
3068
3069    /// Insert the value into the entry.
3070    ///
3071    /// The value will be associated with this entry's key. The new
3072    /// `OccupiedEntry` is returned, allowing for further manipulation.
3073    ///
3074    /// # Examples
3075    ///
3076    /// ```
3077    /// # use rama_http_types::header::*;
3078    /// let mut map = HeaderMap::new();
3079    ///
3080    /// if let Entry::Vacant(v) = map.try_entry("x-hello").unwrap() {
3081    ///     let mut e = v.try_insert_entry("world".parse().unwrap()).unwrap();
3082    ///     e.insert("world2".parse().unwrap());
3083    /// }
3084    ///
3085    /// assert_eq!(map["x-hello"], "world2");
3086    /// ```
3087    pub fn insert_entry(self, value: T) -> OccupiedEntry<'a, T> {
3088        self.try_insert_entry(value)
3089            .expect("size overflows MAX_SIZE")
3090    }
3091
3092    /// Insert the value into the entry.
3093    ///
3094    /// The value will be associated with this entry's key. The new
3095    /// `OccupiedEntry` is returned, allowing for further manipulation.
3096    ///
3097    /// # Examples
3098    ///
3099    /// ```
3100    /// # use rama_http_types::header::*;
3101    /// let mut map = HeaderMap::new();
3102    ///
3103    /// if let Entry::Vacant(v) = map.try_entry("x-hello").unwrap() {
3104    ///     let mut e = v.try_insert_entry("world".parse().unwrap()).unwrap();
3105    ///     e.insert("world2".parse().unwrap());
3106    /// }
3107    ///
3108    /// assert_eq!(map["x-hello"], "world2");
3109    /// ```
3110    pub fn try_insert_entry(self, value: T) -> Result<OccupiedEntry<'a, T>, MaxSizeReached> {
3111        // Ensure that there is space in the map
3112        let index =
3113            self.map
3114                .try_insert_phase_two(self.key, value, self.hash, self.probe, self.danger)?;
3115
3116        Ok(OccupiedEntry {
3117            map: self.map,
3118            index,
3119            probe: self.probe,
3120        })
3121    }
3122}
3123
3124// ===== impl GetAll =====
3125
3126impl<'a, T: 'a> GetAll<'a, T> {
3127    /// Returns an iterator visiting all values associated with the entry.
3128    ///
3129    /// Values are iterated in insertion order.
3130    ///
3131    /// # Examples
3132    ///
3133    /// ```
3134    /// # use rama_http_types::HeaderMap;
3135    /// # use rama_http_types::header::HOST;
3136    /// let mut map = HeaderMap::new();
3137    /// map.insert(HOST, "hello.world".parse().unwrap());
3138    /// map.append(HOST, "hello.earth".parse().unwrap());
3139    ///
3140    /// let values = map.get_all("host");
3141    /// let mut iter = values.iter();
3142    /// assert_eq!(&"hello.world", iter.next().unwrap());
3143    /// assert_eq!(&"hello.earth", iter.next().unwrap());
3144    /// assert!(iter.next().is_none());
3145    /// ```
3146    pub fn iter(&self) -> ValueIter<'a, T> {
3147        // This creates a new GetAll struct so that the lifetime
3148        // isn't bound to &self.
3149        GetAll {
3150            map: self.map,
3151            index: self.index,
3152        }
3153        .into_iter()
3154    }
3155}
3156
3157impl<'a, T: PartialEq> PartialEq for GetAll<'a, T> {
3158    fn eq(&self, other: &Self) -> bool {
3159        self.iter().eq(other.iter())
3160    }
3161}
3162
3163impl<'a, T> IntoIterator for GetAll<'a, T> {
3164    type Item = &'a T;
3165    type IntoIter = ValueIter<'a, T>;
3166
3167    fn into_iter(self) -> ValueIter<'a, T> {
3168        self.map.value_iter(self.index)
3169    }
3170}
3171
3172impl<'a, 'b: 'a, T> IntoIterator for &'b GetAll<'a, T> {
3173    type Item = &'a T;
3174    type IntoIter = ValueIter<'a, T>;
3175
3176    fn into_iter(self) -> ValueIter<'a, T> {
3177        self.map.value_iter(self.index)
3178    }
3179}
3180
3181// ===== impl ValueIter =====
3182
3183impl<'a, T: 'a> Iterator for ValueIter<'a, T> {
3184    type Item = &'a T;
3185
3186    fn next(&mut self) -> Option<Self::Item> {
3187        use self::Cursor::*;
3188
3189        match self.front {
3190            Some(Head) => {
3191                let entry = &self.map.entries[self.index];
3192
3193                if self.back == Some(Head) {
3194                    self.front = None;
3195                    self.back = None;
3196                } else {
3197                    // Update the iterator state
3198                    match entry.links {
3199                        Some(links) => {
3200                            self.front = Some(Values(links.next));
3201                        }
3202                        None => unreachable!(),
3203                    }
3204                }
3205
3206                Some(&entry.value)
3207            }
3208            Some(Values(idx)) => {
3209                let extra = &self.map.extra_values[idx];
3210
3211                if self.front == self.back {
3212                    self.front = None;
3213                    self.back = None;
3214                } else {
3215                    match extra.next {
3216                        Link::Entry(_) => self.front = None,
3217                        Link::Extra(i) => self.front = Some(Values(i)),
3218                    }
3219                }
3220
3221                Some(&extra.value)
3222            }
3223            None => None,
3224        }
3225    }
3226
3227    fn size_hint(&self) -> (usize, Option<usize>) {
3228        match (self.front, self.back) {
3229            // Exactly 1 value...
3230            (Some(Cursor::Head), Some(Cursor::Head)) => (1, Some(1)),
3231            // At least 1...
3232            (Some(_), _) => (1, None),
3233            // No more values...
3234            (None, _) => (0, Some(0)),
3235        }
3236    }
3237}
3238
3239impl<'a, T: 'a> DoubleEndedIterator for ValueIter<'a, T> {
3240    fn next_back(&mut self) -> Option<Self::Item> {
3241        use self::Cursor::*;
3242
3243        match self.back {
3244            Some(Head) => {
3245                self.front = None;
3246                self.back = None;
3247                Some(&self.map.entries[self.index].value)
3248            }
3249            Some(Values(idx)) => {
3250                let extra = &self.map.extra_values[idx];
3251
3252                if self.front == self.back {
3253                    self.front = None;
3254                    self.back = None;
3255                } else {
3256                    match extra.prev {
3257                        Link::Entry(_) => self.back = Some(Head),
3258                        Link::Extra(idx) => self.back = Some(Values(idx)),
3259                    }
3260                }
3261
3262                Some(&extra.value)
3263            }
3264            None => None,
3265        }
3266    }
3267}
3268
3269impl<'a, T> FusedIterator for ValueIter<'a, T> {}
3270
3271// ===== impl ValueIterMut =====
3272
3273impl<'a, T: 'a> Iterator for ValueIterMut<'a, T> {
3274    type Item = &'a mut T;
3275
3276    fn next(&mut self) -> Option<Self::Item> {
3277        use self::Cursor::*;
3278
3279        // SAFETY: `self.index` was created from a live occupied entry and stays
3280        // fixed for the lifetime of this iterator.
3281        let entry = unsafe { self.entries.add(self.index) };
3282
3283        match self.front {
3284            Some(Head) => {
3285                if self.back == Some(Head) {
3286                    self.front = None;
3287                    self.back = None;
3288                } else {
3289                    // Update the iterator state
3290                    // SAFETY: `entry` points at a live bucket in `entries`.
3291                    match unsafe { (*entry).links } {
3292                        Some(links) => {
3293                            self.front = Some(Values(links.next));
3294                        }
3295                        None => unreachable!(),
3296                    }
3297                }
3298
3299                // SAFETY: `entry` points at a live bucket, and `front`/`back`
3300                // ensure this value slot is yielded at most once.
3301                Some(unsafe { &mut *ptr::addr_of_mut!((*entry).value) })
3302            }
3303            Some(Values(idx)) => {
3304                // SAFETY: `idx` comes from the live linked list rooted at
3305                // `self.index`, so it refers to a live extra value slot.
3306                let extra = unsafe { self.extra_values.add(idx) };
3307
3308                if self.front == self.back {
3309                    self.front = None;
3310                    self.back = None;
3311                } else {
3312                    // SAFETY: `extra` points at a live extra value.
3313                    match unsafe { (*extra).next } {
3314                        Link::Entry(_) => self.front = None,
3315                        Link::Extra(i) => self.front = Some(Values(i)),
3316                    }
3317                }
3318
3319                // SAFETY: `extra` points at a live extra value, and
3320                // `front`/`back` ensure this value slot is yielded at most once.
3321                Some(unsafe { &mut *ptr::addr_of_mut!((*extra).value) })
3322            }
3323            None => None,
3324        }
3325    }
3326}
3327
3328impl<'a, T: 'a> DoubleEndedIterator for ValueIterMut<'a, T> {
3329    fn next_back(&mut self) -> Option<Self::Item> {
3330        use self::Cursor::*;
3331
3332        // SAFETY: `self.index` was created from a live occupied entry and stays
3333        // fixed for the lifetime of this iterator.
3334        let entry = unsafe { self.entries.add(self.index) };
3335
3336        match self.back {
3337            Some(Head) => {
3338                self.front = None;
3339                self.back = None;
3340                // SAFETY: `entry` points at a live bucket, and `front`/`back`
3341                // ensure this value slot is yielded at most once.
3342                Some(unsafe { &mut *ptr::addr_of_mut!((*entry).value) })
3343            }
3344            Some(Values(idx)) => {
3345                // SAFETY: `idx` comes from the live linked list rooted at
3346                // `self.index`, so it refers to a live extra value slot.
3347                let extra = unsafe { self.extra_values.add(idx) };
3348
3349                if self.front == self.back {
3350                    self.front = None;
3351                    self.back = None;
3352                } else {
3353                    // SAFETY: `extra` points at a live extra value.
3354                    match unsafe { (*extra).prev } {
3355                        Link::Entry(_) => self.back = Some(Head),
3356                        Link::Extra(idx) => self.back = Some(Values(idx)),
3357                    }
3358                }
3359
3360                // SAFETY: `extra` points at a live extra value, and
3361                // `front`/`back` ensure this value slot is yielded at most once.
3362                Some(unsafe { &mut *ptr::addr_of_mut!((*extra).value) })
3363            }
3364            None => None,
3365        }
3366    }
3367}
3368
3369impl<'a, T> FusedIterator for ValueIterMut<'a, T> {}
3370
3371unsafe impl<'a, T: Sync> Sync for ValueIterMut<'a, T> {}
3372unsafe impl<'a, T: Send> Send for ValueIterMut<'a, T> {}
3373
3374// ===== impl IntoIter =====
3375
3376impl<T> Iterator for IntoIter<T> {
3377    type Item = (Option<HeaderName>, T);
3378
3379    fn next(&mut self) -> Option<Self::Item> {
3380        if let Some(next) = self.next {
3381            self.next = match self.extra_values[next].next {
3382                Link::Entry(_) => None,
3383                Link::Extra(v) => Some(v),
3384            };
3385
3386            let key = ptr::addr_of_mut!(self.extra_values[next].key);
3387            let value = unsafe {
3388                ptr::drop_in_place(key);
3389                ptr::read(&self.extra_values[next].value)
3390            };
3391
3392            return Some((None, value));
3393        }
3394
3395        if let Some(bucket) = self.entries.next() {
3396            self.next = bucket.links.map(|l| l.next);
3397            let name = Some(bucket.key);
3398            let value = bucket.value;
3399
3400            return Some((name, value));
3401        }
3402
3403        None
3404    }
3405
3406    fn size_hint(&self) -> (usize, Option<usize>) {
3407        let (lower, _) = self.entries.size_hint();
3408        // There could be more than just the entries upper, as there
3409        // could be items in the `extra_values`. We could guess, saying
3410        // `upper + extra_values.len()`, but that could overestimate by a lot.
3411        (lower, None)
3412    }
3413}
3414
3415impl<T> FusedIterator for IntoIter<T> {}
3416
3417impl<T> Drop for IntoIter<T> {
3418    fn drop(&mut self) {
3419        struct Guard<'a, T>(&'a mut IntoIter<T>);
3420
3421        impl<'a, T> Drop for Guard<'a, T> {
3422            fn drop(&mut self) {
3423                unsafe {
3424                    self.0.extra_values.set_len(0);
3425                }
3426            }
3427        }
3428
3429        let guard = Guard(self);
3430
3431        // Ensure the iterator is consumed
3432        for _ in guard.0.by_ref() {}
3433    }
3434}
3435
3436// ===== impl IntoOrderedIter =====
3437
3438impl<T> Iterator for IntoOrderedIter<T> {
3439    type Item = (HeaderName, T);
3440
3441    fn next(&mut self) -> Option<Self::Item> {
3442        while self.index < self.order.len() {
3443            let link = self.order[self.index].take();
3444            self.index += 1;
3445
3446            if let Some(link) = link {
3447                return Some(match link {
3448                    Link::Entry(idx) => {
3449                        let entry = unsafe { self.entries.get_unchecked(idx) };
3450                        let name = unsafe { ptr::read(&entry.key) };
3451                        let value = unsafe { ptr::read(&entry.value) };
3452                        (name, value)
3453                    }
3454                    Link::Extra(idx) => {
3455                        let extra = unsafe { self.extra_values.get_unchecked(idx) };
3456                        let name = unsafe { ptr::read(&extra.key) };
3457                        let value = unsafe { ptr::read(&extra.value) };
3458                        (name, value)
3459                    }
3460                });
3461            }
3462        }
3463
3464        None
3465    }
3466
3467    fn size_hint(&self) -> (usize, Option<usize>) {
3468        (0, Some(self.entries.len() + self.extra_values.len()))
3469    }
3470}
3471
3472impl<T> FusedIterator for IntoOrderedIter<T> {}
3473
3474impl<T> Drop for IntoOrderedIter<T> {
3475    fn drop(&mut self) {
3476        struct Guard<'a, T>(&'a mut IntoOrderedIter<T>);
3477
3478        impl<'a, T> Drop for Guard<'a, T> {
3479            fn drop(&mut self) {
3480                unsafe {
3481                    self.0.entries.set_len(0);
3482                    self.0.extra_values.set_len(0);
3483                }
3484            }
3485        }
3486
3487        let guard = Guard(self);
3488
3489        for _ in guard.0.by_ref() {}
3490    }
3491}
3492
3493// ===== impl OccupiedEntry =====
3494
3495impl<'a, T> OccupiedEntry<'a, T> {
3496    /// Returns a reference to the entry's key.
3497    ///
3498    /// # Examples
3499    ///
3500    /// ```
3501    /// # use rama_http_types::header::{HeaderMap, Entry, HOST};
3502    /// let mut map = HeaderMap::new();
3503    /// map.insert(HOST, "world".parse().unwrap());
3504    ///
3505    /// if let Entry::Occupied(e) = map.entry("host") {
3506    ///     assert_eq!("host", e.key());
3507    /// }
3508    /// ```
3509    pub fn key(&self) -> &HeaderName {
3510        &self.map.entries[self.index].key
3511    }
3512
3513    /// Get a reference to the first value in the entry.
3514    ///
3515    /// Values are stored in insertion order.
3516    ///
3517    /// # Panics
3518    ///
3519    /// `get` panics if there are no values associated with the entry.
3520    ///
3521    /// # Examples
3522    ///
3523    /// ```
3524    /// # use rama_http_types::header::{HeaderMap, Entry, HOST};
3525    /// let mut map = HeaderMap::new();
3526    /// map.insert(HOST, "hello.world".parse().unwrap());
3527    ///
3528    /// if let Entry::Occupied(mut e) = map.entry("host") {
3529    ///     assert_eq!(e.get(), &"hello.world");
3530    ///
3531    ///     e.append("hello.earth".parse().unwrap());
3532    ///
3533    ///     assert_eq!(e.get(), &"hello.world");
3534    /// }
3535    /// ```
3536    pub fn get(&self) -> &T {
3537        &self.map.entries[self.index].value
3538    }
3539
3540    /// Get a mutable reference to the first value in the entry.
3541    ///
3542    /// Values are stored in insertion order.
3543    ///
3544    /// # Panics
3545    ///
3546    /// `get_mut` panics if there are no values associated with the entry.
3547    ///
3548    /// # Examples
3549    ///
3550    /// ```
3551    /// # use rama_http_types::header::{HeaderMap, Entry, HOST};
3552    /// let mut map = HeaderMap::default();
3553    /// map.insert(HOST, "hello.world".to_string());
3554    ///
3555    /// if let Entry::Occupied(mut e) = map.entry("host") {
3556    ///     e.get_mut().push_str("-2");
3557    ///     assert_eq!(e.get(), &"hello.world-2");
3558    /// }
3559    /// ```
3560    pub fn get_mut(&mut self) -> &mut T {
3561        &mut self.map.entries[self.index].value
3562    }
3563
3564    /// Converts the `OccupiedEntry` into a mutable reference to the **first**
3565    /// value.
3566    ///
3567    /// The lifetime of the returned reference is bound to the original map.
3568    ///
3569    /// # Panics
3570    ///
3571    /// `into_mut` panics if there are no values associated with the entry.
3572    ///
3573    /// # Examples
3574    ///
3575    /// ```
3576    /// # use rama_http_types::header::{HeaderMap, Entry, HOST};
3577    /// let mut map = HeaderMap::default();
3578    /// map.insert(HOST, "hello.world".to_string());
3579    /// map.append(HOST, "hello.earth".to_string());
3580    ///
3581    /// if let Entry::Occupied(e) = map.entry("host") {
3582    ///     e.into_mut().push_str("-2");
3583    /// }
3584    ///
3585    /// assert_eq!("hello.world-2", map["host"]);
3586    /// ```
3587    pub fn into_mut(self) -> &'a mut T {
3588        &mut self.map.entries[self.index].value
3589    }
3590
3591    /// Sets the value of the entry.
3592    ///
3593    /// All previous values associated with the entry are removed and the first
3594    /// one is returned. See `insert_mult` for an API that returns all values.
3595    ///
3596    /// # Examples
3597    ///
3598    /// ```
3599    /// # use rama_http_types::header::{HeaderMap, Entry, HOST};
3600    /// let mut map = HeaderMap::new();
3601    /// map.insert(HOST, "hello.world".parse().unwrap());
3602    ///
3603    /// if let Entry::Occupied(mut e) = map.entry("host") {
3604    ///     let mut prev = e.insert("earth".parse().unwrap());
3605    ///     assert_eq!("hello.world", prev);
3606    /// }
3607    ///
3608    /// assert_eq!("earth", map["host"]);
3609    /// ```
3610    pub fn insert(&mut self, value: T) -> T {
3611        self.map.insert_occupied_same_key(self.index, value)
3612    }
3613
3614    /// Sets the value of the entry.
3615    ///
3616    /// This function does the same as `insert` except it returns an iterator
3617    /// that yields all values previously associated with the key.
3618    ///
3619    /// # Examples
3620    ///
3621    /// ```
3622    /// # use rama_http_types::header::{HeaderMap, Entry, HOST};
3623    /// let mut map = HeaderMap::new();
3624    /// map.insert(HOST, "world".parse().unwrap());
3625    /// map.append(HOST, "world2".parse().unwrap());
3626    ///
3627    /// if let Entry::Occupied(mut e) = map.entry("host") {
3628    ///     let mut prev = e.insert_mult("earth".parse().unwrap());
3629    ///     assert_eq!("world", prev.next().unwrap());
3630    ///     assert_eq!("world2", prev.next().unwrap());
3631    ///     assert!(prev.next().is_none());
3632    /// }
3633    ///
3634    /// assert_eq!("earth", map["host"]);
3635    /// ```
3636    pub fn insert_mult(&mut self, value: T) -> ValueDrain<'_, T> {
3637        self.map.insert_occupied_mult_same_key(self.index, value)
3638    }
3639
3640    /// Insert the value into the entry.
3641    ///
3642    /// The new value is appended to the end of the entry's value list. All
3643    /// previous values associated with the entry are retained.
3644    ///
3645    /// # Examples
3646    ///
3647    /// ```
3648    /// # use rama_http_types::header::{HeaderMap, Entry, HOST};
3649    /// let mut map = HeaderMap::new();
3650    /// map.insert(HOST, "world".parse().unwrap());
3651    ///
3652    /// if let Entry::Occupied(mut e) = map.entry("host") {
3653    ///     e.append("earth".parse().unwrap());
3654    /// }
3655    ///
3656    /// let values = map.get_all("host");
3657    /// let mut i = values.iter();
3658    /// assert_eq!("world", *i.next().unwrap());
3659    /// assert_eq!("earth", *i.next().unwrap());
3660    /// ```
3661    pub fn append(&mut self, value: T) {
3662        let idx = self.index;
3663        let key = self.map.entries[idx].key.clone();
3664        self.map.append_value(idx, key, value);
3665    }
3666
3667    /// Remove the entry from the map.
3668    ///
3669    /// All values associated with the entry are removed and the first one is
3670    /// returned. See `remove_entry_mult` for an API that returns all values.
3671    ///
3672    /// # Examples
3673    ///
3674    /// ```
3675    /// # use rama_http_types::header::{HeaderMap, Entry, HOST};
3676    /// let mut map = HeaderMap::new();
3677    /// map.insert(HOST, "world".parse().unwrap());
3678    ///
3679    /// if let Entry::Occupied(e) = map.entry("host") {
3680    ///     let mut prev = e.remove();
3681    ///     assert_eq!("world", prev);
3682    /// }
3683    ///
3684    /// assert!(!map.contains_key("host"));
3685    /// ```
3686    pub fn remove(self) -> T {
3687        self.remove_entry().1
3688    }
3689
3690    /// Remove the entry from the map.
3691    ///
3692    /// The key and all values associated with the entry are removed and the
3693    /// first one is returned. See `remove_entry_mult` for an API that returns
3694    /// all values.
3695    ///
3696    /// # Examples
3697    ///
3698    /// ```
3699    /// # use rama_http_types::header::{HeaderMap, Entry, HOST};
3700    /// let mut map = HeaderMap::new();
3701    /// map.insert(HOST, "world".parse().unwrap());
3702    ///
3703    /// if let Entry::Occupied(e) = map.entry("host") {
3704    ///     let (key, mut prev) = e.remove_entry();
3705    ///     assert_eq!("host", key.as_str());
3706    ///     assert_eq!("world", prev);
3707    /// }
3708    ///
3709    /// assert!(!map.contains_key("host"));
3710    /// ```
3711    pub fn remove_entry(self) -> (HeaderName, T) {
3712        if let Some(links) = self.map.entries[self.index].links {
3713            self.map.remove_all_extra_values(links.next);
3714        }
3715
3716        let entry = self.map.remove_found(self.probe, self.index);
3717
3718        (entry.key, entry.value)
3719    }
3720
3721    /// Remove the entry from the map.
3722    ///
3723    /// The key and all values associated with the entry are removed and
3724    /// returned.
3725    pub fn remove_entry_mult(self) -> (HeaderName, ValueDrain<'a, T>) {
3726        let next = self.map.entries[self.index]
3727            .links
3728            .map(|l| self.map.drain_all_extra_values(l.next).into_iter());
3729
3730        let entry = self.map.remove_found(self.probe, self.index);
3731
3732        let drain = ValueDrain {
3733            first: Some(entry.value),
3734            next,
3735            lt: PhantomData,
3736        };
3737        (entry.key, drain)
3738    }
3739
3740    /// Returns an iterator visiting all values associated with the entry.
3741    ///
3742    /// Values are iterated in insertion order.
3743    ///
3744    /// # Examples
3745    ///
3746    /// ```
3747    /// # use rama_http_types::header::{HeaderMap, Entry, HOST};
3748    /// let mut map = HeaderMap::new();
3749    /// map.insert(HOST, "world".parse().unwrap());
3750    /// map.append(HOST, "earth".parse().unwrap());
3751    ///
3752    /// if let Entry::Occupied(e) = map.entry("host") {
3753    ///     let mut iter = e.iter();
3754    ///     assert_eq!(&"world", iter.next().unwrap());
3755    ///     assert_eq!(&"earth", iter.next().unwrap());
3756    ///     assert!(iter.next().is_none());
3757    /// }
3758    /// ```
3759    pub fn iter(&self) -> ValueIter<'_, T> {
3760        self.map.value_iter(Some(self.index))
3761    }
3762
3763    /// Returns an iterator mutably visiting all values associated with the
3764    /// entry.
3765    ///
3766    /// Values are iterated in insertion order.
3767    ///
3768    /// # Examples
3769    ///
3770    /// ```
3771    /// # use rama_http_types::header::{HeaderMap, Entry, HOST};
3772    /// let mut map = HeaderMap::default();
3773    /// map.insert(HOST, "world".to_string());
3774    /// map.append(HOST, "earth".to_string());
3775    ///
3776    /// if let Entry::Occupied(mut e) = map.entry("host") {
3777    ///     for e in e.iter_mut() {
3778    ///         e.push_str("-boop");
3779    ///     }
3780    /// }
3781    ///
3782    /// let mut values = map.get_all("host");
3783    /// let mut i = values.iter();
3784    /// assert_eq!(&"world-boop", i.next().unwrap());
3785    /// assert_eq!(&"earth-boop", i.next().unwrap());
3786    /// ```
3787    pub fn iter_mut(&mut self) -> ValueIterMut<'_, T> {
3788        self.map.value_iter_mut(self.index)
3789    }
3790}
3791
3792impl<'a, T> IntoIterator for OccupiedEntry<'a, T> {
3793    type Item = &'a mut T;
3794    type IntoIter = ValueIterMut<'a, T>;
3795
3796    fn into_iter(self) -> ValueIterMut<'a, T> {
3797        self.map.value_iter_mut(self.index)
3798    }
3799}
3800
3801impl<'a, 'b: 'a, T> IntoIterator for &'b OccupiedEntry<'a, T> {
3802    type Item = &'a T;
3803    type IntoIter = ValueIter<'a, T>;
3804
3805    fn into_iter(self) -> ValueIter<'a, T> {
3806        self.iter()
3807    }
3808}
3809
3810impl<'a, 'b: 'a, T> IntoIterator for &'b mut OccupiedEntry<'a, T> {
3811    type Item = &'a mut T;
3812    type IntoIter = ValueIterMut<'a, T>;
3813
3814    fn into_iter(self) -> ValueIterMut<'a, T> {
3815        self.iter_mut()
3816    }
3817}
3818
3819// ===== impl ValueDrain =====
3820
3821impl<'a, T> Iterator for ValueDrain<'a, T> {
3822    type Item = T;
3823
3824    fn next(&mut self) -> Option<T> {
3825        if self.first.is_some() {
3826            self.first.take()
3827        } else if let Some(ref mut extras) = self.next {
3828            extras.next()
3829        } else {
3830            None
3831        }
3832    }
3833
3834    fn size_hint(&self) -> (usize, Option<usize>) {
3835        match (&self.first, &self.next) {
3836            // Exactly 1
3837            (&Some(_), &None) => (1, Some(1)),
3838            // 1 + extras
3839            (&Some(_), Some(extras)) => {
3840                let (l, u) = extras.size_hint();
3841                (l + 1, u.map(|u| u + 1))
3842            }
3843            // Extras only
3844            (&None, Some(extras)) => extras.size_hint(),
3845            // No more
3846            (&None, &None) => (0, Some(0)),
3847        }
3848    }
3849}
3850
3851impl<'a, T> FusedIterator for ValueDrain<'a, T> {}
3852
3853impl<'a, T> Drop for ValueDrain<'a, T> {
3854    fn drop(&mut self) {
3855        for _ in self.by_ref() {}
3856    }
3857}
3858
3859unsafe impl<'a, T: Sync> Sync for ValueDrain<'a, T> {}
3860unsafe impl<'a, T: Send> Send for ValueDrain<'a, T> {}
3861
3862// ===== impl RawLinks =====
3863
3864impl<T> Clone for RawLinks<T> {
3865    fn clone(&self) -> RawLinks<T> {
3866        *self
3867    }
3868}
3869
3870impl<T> Copy for RawLinks<T> {}
3871
3872impl<T> ops::Index<usize> for RawLinks<T> {
3873    type Output = Option<Links>;
3874
3875    fn index(&self, idx: usize) -> &Self::Output {
3876        unsafe { &(*self.0)[idx].links }
3877    }
3878}
3879
3880impl<T> ops::IndexMut<usize> for RawLinks<T> {
3881    fn index_mut(&mut self, idx: usize) -> &mut Self::Output {
3882        unsafe { &mut (*self.0)[idx].links }
3883    }
3884}
3885
3886// ===== impl Pos =====
3887
3888impl Pos {
3889    #[inline]
3890    fn new(index: usize, hash: HashValue) -> Self {
3891        debug_assert!(index < MAX_SIZE);
3892        Pos {
3893            index: index as Size,
3894            hash,
3895        }
3896    }
3897
3898    #[inline]
3899    fn none() -> Self {
3900        Pos {
3901            index: !0,
3902            hash: HashValue(0),
3903        }
3904    }
3905
3906    #[inline]
3907    fn is_some(&self) -> bool {
3908        !self.is_none()
3909    }
3910
3911    #[inline]
3912    fn is_none(&self) -> bool {
3913        self.index == !0
3914    }
3915
3916    #[inline]
3917    fn resolve(&self) -> Option<(usize, HashValue)> {
3918        if self.is_some() {
3919            Some((self.index as usize, self.hash))
3920        } else {
3921            None
3922        }
3923    }
3924}
3925
3926impl Danger {
3927    fn is_red(&self) -> bool {
3928        matches!(*self, Danger::Red(_))
3929    }
3930
3931    fn set_red(&mut self) {
3932        debug_assert!(self.is_yellow());
3933        *self = Danger::Red(RandomState::new());
3934    }
3935
3936    fn is_yellow(&self) -> bool {
3937        matches!(*self, Danger::Yellow)
3938    }
3939
3940    fn set_yellow(&mut self) {
3941        if let Danger::Green = *self {
3942            *self = Danger::Yellow;
3943        }
3944    }
3945
3946    fn set_green(&mut self) {
3947        debug_assert!(self.is_yellow());
3948        *self = Danger::Green;
3949    }
3950}
3951
3952// ===== impl MaxSizeReached =====
3953
3954impl MaxSizeReached {
3955    fn new() -> Self {
3956        MaxSizeReached { _priv: () }
3957    }
3958}
3959
3960impl fmt::Debug for MaxSizeReached {
3961    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3962        f.debug_struct("MaxSizeReached")
3963            // skip _priv noise
3964            .finish()
3965    }
3966}
3967
3968impl fmt::Display for MaxSizeReached {
3969    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3970        f.write_str("max size reached")
3971    }
3972}
3973
3974impl std::error::Error for MaxSizeReached {}
3975
3976// ===== impl Utils =====
3977
3978#[inline]
3979fn usable_capacity(cap: usize) -> usize {
3980    cap - cap / 4
3981}
3982
3983#[inline]
3984fn to_raw_capacity(n: usize) -> Result<usize, MaxSizeReached> {
3985    n.checked_add(n / 3).ok_or_else(MaxSizeReached::new)
3986}
3987
3988#[inline]
3989fn desired_pos(mask: Size, hash: HashValue) -> usize {
3990    (hash.0 & mask) as usize
3991}
3992
3993/// The number of steps that `current` is forward of the desired position for hash
3994#[inline]
3995fn probe_distance(mask: Size, hash: HashValue, current: usize) -> usize {
3996    current.wrapping_sub(desired_pos(mask, hash)) & mask as usize
3997}
3998
3999#[inline]
4000fn hash_elem_using<K>(danger: &Danger, k: &K) -> HashValue
4001where
4002    K: Hash + ?Sized,
4003{
4004    const MASK: u64 = (MAX_SIZE as u64) - 1;
4005
4006    let hash = match *danger {
4007        // Safe hash
4008        Danger::Red(ref hasher) => {
4009            let mut h = hasher.build_hasher();
4010            k.hash(&mut h);
4011            h.finish()
4012        }
4013        // Fast hash
4014        _ => {
4015            let mut h = FnvHasher::new();
4016            k.hash(&mut h);
4017            h.finish()
4018        }
4019    };
4020
4021    HashValue((hash & MASK) as u16)
4022}
4023
4024struct FnvHasher(u64);
4025
4026impl FnvHasher {
4027    #[inline]
4028    fn new() -> Self {
4029        FnvHasher(0xcbf29ce484222325)
4030    }
4031}
4032
4033impl std::hash::Hasher for FnvHasher {
4034    #[inline]
4035    fn finish(&self) -> u64 {
4036        self.0
4037    }
4038
4039    #[inline]
4040    fn write(&mut self, bytes: &[u8]) {
4041        let mut hash = self.0;
4042        for &b in bytes {
4043            hash ^= b as u64;
4044            hash = hash.wrapping_mul(0x100000001b3);
4045        }
4046        self.0 = hash;
4047    }
4048}
4049
4050/*
4051 *
4052 * ===== impl IntoHeaderName / AsHeaderName =====
4053 *
4054 */
4055
4056mod into_header_name {
4057    use super::{Entry, HdrName, HeaderMap, HeaderName, MaxSizeReached};
4058
4059    /// A marker trait used to identify values that can be used as insert keys
4060    /// to a `HeaderMap`.
4061    pub trait IntoHeaderName: Sealed {}
4062
4063    // All methods are on this pub(super) trait, instead of `IntoHeaderName`,
4064    // so that they aren't publicly exposed to the world.
4065    //
4066    // Being on the `IntoHeaderName` trait would mean users could call
4067    // `"host".insert(&mut map, "localhost")`.
4068    //
4069    // Ultimately, this allows us to adjust the signatures of these methods
4070    // without breaking any external crate.
4071    pub trait Sealed {
4072        #[doc(hidden)]
4073        fn try_insert<T>(self, map: &mut HeaderMap<T>, val: T)
4074        -> Result<Option<T>, MaxSizeReached>;
4075
4076        #[doc(hidden)]
4077        fn try_append<T>(self, map: &mut HeaderMap<T>, val: T) -> Result<bool, MaxSizeReached>;
4078
4079        #[doc(hidden)]
4080        fn try_entry<T>(self, map: &mut HeaderMap<T>) -> Result<Entry<'_, T>, MaxSizeReached>;
4081    }
4082
4083    // ==== impls ====
4084
4085    impl Sealed for HeaderName {
4086        #[inline]
4087        fn try_insert<T>(
4088            self,
4089            map: &mut HeaderMap<T>,
4090            val: T,
4091        ) -> Result<Option<T>, MaxSizeReached> {
4092            map.try_insert2(self, val)
4093        }
4094
4095        #[inline]
4096        fn try_append<T>(self, map: &mut HeaderMap<T>, val: T) -> Result<bool, MaxSizeReached> {
4097            map.try_append2(self, val)
4098        }
4099
4100        #[inline]
4101        fn try_entry<T>(self, map: &mut HeaderMap<T>) -> Result<Entry<'_, T>, MaxSizeReached> {
4102            map.try_entry2(self)
4103        }
4104    }
4105
4106    impl IntoHeaderName for HeaderName {}
4107
4108    impl Sealed for &HeaderName {
4109        #[inline]
4110        fn try_insert<T>(
4111            self,
4112            map: &mut HeaderMap<T>,
4113            val: T,
4114        ) -> Result<Option<T>, MaxSizeReached> {
4115            map.try_insert2(self, val)
4116        }
4117        #[inline]
4118        fn try_append<T>(self, map: &mut HeaderMap<T>, val: T) -> Result<bool, MaxSizeReached> {
4119            map.try_append2(self, val)
4120        }
4121
4122        #[inline]
4123        fn try_entry<T>(self, map: &mut HeaderMap<T>) -> Result<Entry<'_, T>, MaxSizeReached> {
4124            map.try_entry2(self)
4125        }
4126    }
4127
4128    impl IntoHeaderName for &HeaderName {}
4129
4130    impl Sealed for &'static str {
4131        #[inline]
4132        fn try_insert<T>(
4133            self,
4134            map: &mut HeaderMap<T>,
4135            val: T,
4136        ) -> Result<Option<T>, MaxSizeReached> {
4137            HdrName::from_static(self, move |hdr| map.try_insert2(hdr, val))
4138        }
4139        #[inline]
4140        fn try_append<T>(self, map: &mut HeaderMap<T>, val: T) -> Result<bool, MaxSizeReached> {
4141            HdrName::from_static(self, move |hdr| map.try_append2(hdr, val))
4142        }
4143
4144        #[inline]
4145        fn try_entry<T>(self, map: &mut HeaderMap<T>) -> Result<Entry<'_, T>, MaxSizeReached> {
4146            HdrName::from_static(self, move |hdr| map.try_entry2(hdr))
4147        }
4148    }
4149
4150    impl IntoHeaderName for &'static str {}
4151}
4152
4153mod as_header_name {
4154    use super::{Entry, HdrName, HeaderMap, HeaderName, InvalidHeaderName, MaxSizeReached};
4155
4156    /// A marker trait used to identify values that can be used as search keys
4157    /// to a `HeaderMap`.
4158    pub trait AsHeaderName: Sealed {}
4159
4160    // Debug not currently needed, save on compiling it
4161    #[allow(missing_debug_implementations)]
4162    pub enum TryEntryError {
4163        InvalidHeaderName(InvalidHeaderName),
4164        MaxSizeReached(MaxSizeReached),
4165    }
4166
4167    impl From<InvalidHeaderName> for TryEntryError {
4168        fn from(e: InvalidHeaderName) -> TryEntryError {
4169            TryEntryError::InvalidHeaderName(e)
4170        }
4171    }
4172
4173    impl From<MaxSizeReached> for TryEntryError {
4174        fn from(e: MaxSizeReached) -> TryEntryError {
4175            TryEntryError::MaxSizeReached(e)
4176        }
4177    }
4178
4179    // All methods are on this pub(super) trait, instead of `AsHeaderName`,
4180    // so that they aren't publicly exposed to the world.
4181    //
4182    // Being on the `AsHeaderName` trait would mean users could call
4183    // `"host".find(&map)`.
4184    //
4185    // Ultimately, this allows us to adjust the signatures of these methods
4186    // without breaking any external crate.
4187    pub trait Sealed {
4188        #[doc(hidden)]
4189        fn try_entry<T>(self, map: &mut HeaderMap<T>) -> Result<Entry<'_, T>, TryEntryError>;
4190
4191        #[doc(hidden)]
4192        fn find<T>(&self, map: &HeaderMap<T>) -> Option<(usize, usize)>;
4193
4194        #[doc(hidden)]
4195        fn as_str(&self) -> &str;
4196    }
4197
4198    // ==== impls ====
4199
4200    impl Sealed for HeaderName {
4201        #[inline]
4202        fn try_entry<T>(self, map: &mut HeaderMap<T>) -> Result<Entry<'_, T>, TryEntryError> {
4203            Ok(map.try_entry2(self)?)
4204        }
4205
4206        #[inline]
4207        fn find<T>(&self, map: &HeaderMap<T>) -> Option<(usize, usize)> {
4208            map.find(self)
4209        }
4210
4211        fn as_str(&self) -> &str {
4212            <HeaderName>::as_str(self)
4213        }
4214    }
4215
4216    impl AsHeaderName for HeaderName {}
4217
4218    impl Sealed for &HeaderName {
4219        #[inline]
4220        fn try_entry<T>(self, map: &mut HeaderMap<T>) -> Result<Entry<'_, T>, TryEntryError> {
4221            Ok(map.try_entry2(self)?)
4222        }
4223
4224        #[inline]
4225        fn find<T>(&self, map: &HeaderMap<T>) -> Option<(usize, usize)> {
4226            map.find(*self)
4227        }
4228
4229        fn as_str(&self) -> &str {
4230            <HeaderName>::as_str(self)
4231        }
4232    }
4233
4234    impl AsHeaderName for &HeaderName {}
4235
4236    impl Sealed for &str {
4237        #[inline]
4238        fn try_entry<T>(self, map: &mut HeaderMap<T>) -> Result<Entry<'_, T>, TryEntryError> {
4239            Ok(HdrName::from_bytes(self.as_bytes(), move |hdr| {
4240                map.try_entry2(hdr)
4241            })??)
4242        }
4243
4244        #[inline]
4245        fn find<T>(&self, map: &HeaderMap<T>) -> Option<(usize, usize)> {
4246            HdrName::from_bytes(self.as_bytes(), move |hdr| map.find(&hdr)).unwrap_or(None)
4247        }
4248
4249        fn as_str(&self) -> &str {
4250            self
4251        }
4252    }
4253
4254    impl AsHeaderName for &str {}
4255
4256    impl Sealed for String {
4257        #[inline]
4258        fn try_entry<T>(self, map: &mut HeaderMap<T>) -> Result<Entry<'_, T>, TryEntryError> {
4259            self.as_str().try_entry(map)
4260        }
4261
4262        #[inline]
4263        fn find<T>(&self, map: &HeaderMap<T>) -> Option<(usize, usize)> {
4264            Sealed::find(&self.as_str(), map)
4265        }
4266
4267        fn as_str(&self) -> &str {
4268            self
4269        }
4270    }
4271
4272    impl AsHeaderName for String {}
4273
4274    impl Sealed for &String {
4275        #[inline]
4276        fn try_entry<T>(self, map: &mut HeaderMap<T>) -> Result<Entry<'_, T>, TryEntryError> {
4277            self.as_str().try_entry(map)
4278        }
4279
4280        #[inline]
4281        fn find<T>(&self, map: &HeaderMap<T>) -> Option<(usize, usize)> {
4282            Sealed::find(*self, map)
4283        }
4284
4285        fn as_str(&self) -> &str {
4286            self
4287        }
4288    }
4289
4290    impl AsHeaderName for &String {}
4291}
4292
4293#[test]
4294fn test_bounds() {
4295    fn check_bounds<T: Send + Send>() {}
4296
4297    check_bounds::<HeaderMap<()>>();
4298    check_bounds::<Iter<'static, ()>>();
4299    check_bounds::<IterMut<'static, ()>>();
4300    check_bounds::<Keys<'static, ()>>();
4301    check_bounds::<Values<'static, ()>>();
4302    check_bounds::<ValuesMut<'static, ()>>();
4303    check_bounds::<Drain<'static, ()>>();
4304    check_bounds::<GetAll<'static, ()>>();
4305    check_bounds::<Entry<'static, ()>>();
4306    check_bounds::<VacantEntry<'static, ()>>();
4307    check_bounds::<OccupiedEntry<'static, ()>>();
4308    check_bounds::<ValueIter<'static, ()>>();
4309    check_bounds::<ValueIterMut<'static, ()>>();
4310    check_bounds::<ValueDrain<'static, ()>>();
4311}
4312
4313#[test]
4314fn extend_size_hint_above_capacity() {
4315    // A `HeaderMap` may hold more values than the table can index when many
4316    // values are appended under one name, so an exact size hint can exceed the
4317    // largest `reserve` request. Extending must not panic in that case.
4318    let name = HeaderName::from_static("h");
4319    let value = HeaderValue::from_static("0");
4320    let pairs: Vec<(HeaderName, HeaderValue)> =
4321        std::iter::repeat_with(|| (name.clone(), value.clone()))
4322            .take(24_577)
4323            .collect();
4324
4325    let map = HeaderMap::from_iter(pairs);
4326    assert_eq!(map.len(), 24_577);
4327    assert_eq!(map.keys_len(), 1);
4328}
4329
4330#[cfg(test)]
4331fn assert_header_map_invariants<T>(map: &HeaderMap<T>) {
4332    assert_eq!(map.len(), map.entries.len() + map.extra_values.len());
4333
4334    let live_order_slots = map.order.iter().filter(|link| link.is_some()).count();
4335    let order_holes = map.order.iter().filter(|link| link.is_none()).count();
4336    assert_eq!(live_order_slots, map.len());
4337    assert_eq!(order_holes, map.order_holes);
4338
4339    let mut indexed_entries = vec![false; map.entries.len()];
4340    for pos in &*map.indices {
4341        if let Some((idx, hash)) = pos.resolve() {
4342            assert!(idx < map.entries.len(), "index points past entries: {idx}");
4343            assert_eq!(map.entries[idx].hash, hash);
4344            assert!(!indexed_entries[idx], "entry indexed more than once: {idx}");
4345            indexed_entries[idx] = true;
4346        }
4347    }
4348    assert!(
4349        indexed_entries.iter().all(|seen| *seen),
4350        "not every entry is reachable from indices"
4351    );
4352
4353    let mut linked_extras = vec![false; map.extra_values.len()];
4354    for (entry_idx, entry) in map.entries.iter().enumerate() {
4355        assert_eq!(map.order[entry.order], Some(Link::Entry(entry_idx)));
4356
4357        let Some(links) = entry.links else {
4358            continue;
4359        };
4360
4361        assert!(links.next < map.extra_values.len());
4362        assert!(links.tail < map.extra_values.len());
4363
4364        let mut prev = Link::Entry(entry_idx);
4365        let mut current = links.next;
4366        loop {
4367            assert!(current < map.extra_values.len());
4368            assert!(
4369                !linked_extras[current],
4370                "extra value linked more than once: {current}"
4371            );
4372            linked_extras[current] = true;
4373
4374            let extra = &map.extra_values[current];
4375            assert_eq!(extra.prev, prev);
4376            assert_eq!(extra.key, entry.key);
4377            assert_eq!(map.order[extra.order], Some(Link::Extra(current)));
4378
4379            match extra.next {
4380                Link::Entry(idx) => {
4381                    assert_eq!(idx, entry_idx);
4382                    assert_eq!(current, links.tail);
4383                    break;
4384                }
4385                Link::Extra(next) => {
4386                    prev = Link::Extra(current);
4387                    current = next;
4388                }
4389            }
4390        }
4391    }
4392    assert!(
4393        linked_extras.iter().all(|seen| *seen),
4394        "not every extra value is linked from an entry"
4395    );
4396
4397    for (order_idx, link) in map.order.iter().enumerate() {
4398        match link {
4399            Some(Link::Entry(idx)) => {
4400                assert!(*idx < map.entries.len());
4401                assert_eq!(map.entries[*idx].order, order_idx);
4402            }
4403            Some(Link::Extra(idx)) => {
4404                assert!(*idx < map.extra_values.len());
4405                assert_eq!(map.extra_values[*idx].order, order_idx);
4406            }
4407            None => {}
4408        }
4409    }
4410}
4411
4412#[cfg(test)]
4413#[derive(Clone, Debug)]
4414struct HeaderMapOps(Vec<HeaderMapOp>);
4415
4416#[cfg(test)]
4417#[derive(Clone, Debug)]
4418enum HeaderMapOp {
4419    Append { name: u8, value: u8 },
4420    Insert { name: u8, value: u8 },
4421    Remove { name: u8 },
4422    RemoveEntryMult { name: u8 },
4423    EntryAppend { name: u8, value: u8 },
4424    EntryInsertMult { name: u8, value: u8 },
4425}
4426
4427#[cfg(test)]
4428#[derive(Clone, Debug, Eq, PartialEq)]
4429struct ModelHeader {
4430    semantic_id: usize,
4431    name: String,
4432    value: String,
4433    head: bool,
4434}
4435
4436#[cfg(test)]
4437#[derive(Default)]
4438struct HeaderMapModel {
4439    fields: Vec<Option<ModelHeader>>,
4440}
4441
4442#[cfg(test)]
4443impl HeaderMapModel {
4444    fn len(&self) -> usize {
4445        self.fields.iter().filter(|field| field.is_some()).count()
4446    }
4447
4448    fn ordered(&self) -> Vec<(String, String)> {
4449        self.fields
4450            .iter()
4451            .filter_map(|field| {
4452                field
4453                    .as_ref()
4454                    .map(|field| (field.name.clone(), field.value.clone()))
4455            })
4456            .collect()
4457    }
4458
4459    fn values_for(&self, semantic_id: usize) -> Vec<String> {
4460        self.fields
4461            .iter()
4462            .filter_map(|field| {
4463                let field = field.as_ref()?;
4464                (field.semantic_id == semantic_id).then(|| field.value.clone())
4465            })
4466            .collect()
4467    }
4468
4469    fn head_index(&self, semantic_id: usize) -> Option<usize> {
4470        self.fields.iter().position(|field| {
4471            field
4472                .as_ref()
4473                .is_some_and(|field| field.semantic_id == semantic_id && field.head)
4474        })
4475    }
4476
4477    fn remove(&mut self, semantic_id: usize) {
4478        for field in &mut self.fields {
4479            if field
4480                .as_ref()
4481                .is_some_and(|field| field.semantic_id == semantic_id)
4482            {
4483                *field = None;
4484            }
4485        }
4486    }
4487
4488    fn append(&mut self, semantic_id: usize, name: String, value: String) {
4489        let head = self.head_index(semantic_id).is_none();
4490        self.fields.push(Some(ModelHeader {
4491            semantic_id,
4492            name,
4493            value,
4494            head,
4495        }));
4496    }
4497
4498    fn insert(&mut self, semantic_id: usize, name: String, value: String) {
4499        if let Some(head_idx) = self.head_index(semantic_id) {
4500            for (idx, field) in self.fields.iter_mut().enumerate() {
4501                if idx != head_idx
4502                    && field
4503                        .as_ref()
4504                        .is_some_and(|field| field.semantic_id == semantic_id)
4505                {
4506                    *field = None;
4507                }
4508            }
4509            self.fields[head_idx] = Some(ModelHeader {
4510                semantic_id,
4511                name,
4512                value,
4513                head: true,
4514            });
4515        } else {
4516            self.append(semantic_id, name, value);
4517        }
4518    }
4519
4520    fn entry_append(&mut self, semantic_id: usize, name: String, value: String) {
4521        if let Some(head_idx) = self.head_index(semantic_id) {
4522            let entry_name = self.fields[head_idx].as_ref().unwrap().name.clone();
4523            self.append(semantic_id, entry_name, value);
4524        } else {
4525            self.append(semantic_id, name, value);
4526        }
4527    }
4528
4529    fn entry_insert_mult(&mut self, semantic_id: usize, name: String, value: String) {
4530        if let Some(head_idx) = self.head_index(semantic_id) {
4531            let entry_name = self.fields[head_idx].as_ref().unwrap().name.clone();
4532            self.insert(semantic_id, entry_name, value);
4533        } else {
4534            self.append(semantic_id, name, value);
4535        }
4536    }
4537}
4538
4539#[cfg(test)]
4540impl quickcheck::Arbitrary for HeaderMapOps {
4541    fn arbitrary(g: &mut quickcheck::Gen) -> Self {
4542        let len = usize::from(u8::arbitrary(g) % 80);
4543        let ops = (0..len).map(|_| HeaderMapOp::arbitrary(g)).collect();
4544        Self(ops)
4545    }
4546
4547    fn shrink(&self) -> Box<dyn Iterator<Item = Self>> {
4548        Box::new(self.0.shrink().map(Self))
4549    }
4550}
4551
4552#[cfg(test)]
4553impl quickcheck::Arbitrary for HeaderMapOp {
4554    fn arbitrary(g: &mut quickcheck::Gen) -> Self {
4555        let name = u8::arbitrary(g);
4556        let value = u8::arbitrary(g);
4557        match u8::arbitrary(g) % 6 {
4558            0 => Self::Append { name, value },
4559            1 => Self::Insert { name, value },
4560            2 => Self::Remove { name },
4561            3 => Self::RemoveEntryMult { name },
4562            4 => Self::EntryAppend { name, value },
4563            _ => Self::EntryInsertMult { name, value },
4564        }
4565    }
4566}
4567
4568#[cfg(test)]
4569fn model_header_name(selector: u8) -> (&'static str, usize) {
4570    match selector % 8 {
4571        0 => ("x-a", 0),
4572        1 => ("X-A", 0),
4573        2 => ("x-b", 1),
4574        3 => ("X-B", 1),
4575        4 => ("cookie", 2),
4576        5 => ("Cookie", 2),
4577        6 => ("x-c", 3),
4578        _ => ("X-C", 3),
4579    }
4580}
4581
4582#[cfg(test)]
4583fn model_header_value(value: u8) -> String {
4584    format!("v{value}")
4585}
4586
4587#[cfg(test)]
4588fn make_header_name(name: &str) -> HeaderName {
4589    HeaderName::from_bytes(name.as_bytes()).unwrap()
4590}
4591
4592#[cfg(test)]
4593fn model_original_name(name: &str) -> String {
4594    make_header_name(name).to_string()
4595}
4596
4597#[cfg(test)]
4598fn make_header_value(value: &str) -> HeaderValue {
4599    HeaderValue::from_bytes(value.as_bytes()).unwrap()
4600}
4601
4602#[cfg(test)]
4603fn assert_header_map_matches_model(map: &HeaderMap, model: &HeaderMapModel) {
4604    assert_header_map_invariants(map);
4605    assert_eq!(map.len(), model.len());
4606
4607    let ordered = map
4608        .ordered_iter()
4609        .map(|(name, value)| (name.to_string(), value.to_str().unwrap().to_owned()))
4610        .collect::<Vec<_>>();
4611    assert_eq!(ordered, model.ordered());
4612
4613    let consumed = map
4614        .clone()
4615        .into_ordered_iter()
4616        .map(|(name, value)| (name.to_string(), value.to_str().unwrap().to_owned()))
4617        .collect::<Vec<_>>();
4618    assert_eq!(consumed, ordered);
4619
4620    for (selector, semantic_id) in [
4621        ("x-a", 0),
4622        ("X-A", 0),
4623        ("x-b", 1),
4624        ("X-B", 1),
4625        ("cookie", 2),
4626        ("Cookie", 2),
4627        ("x-c", 3),
4628        ("X-C", 3),
4629    ] {
4630        let actual = map
4631            .get_all(make_header_name(selector))
4632            .iter()
4633            .map(|value| value.to_str().unwrap().to_owned())
4634            .collect::<Vec<_>>();
4635        assert_eq!(actual, model.values_for(semantic_id));
4636    }
4637}
4638
4639#[cfg(test)]
4640impl HeaderMapOps {
4641    fn run(self) {
4642        let mut map = HeaderMap::new();
4643        let mut model = HeaderMapModel::default();
4644
4645        assert_header_map_matches_model(&map, &model);
4646
4647        for op in self.0 {
4648            match op {
4649                HeaderMapOp::Append { name, value } => {
4650                    let (name, semantic_id) = model_header_name(name);
4651                    let value = model_header_value(value);
4652                    map.append(make_header_name(name), make_header_value(&value));
4653                    model.append(semantic_id, model_original_name(name), value);
4654                }
4655                HeaderMapOp::Insert { name, value } => {
4656                    let (name, semantic_id) = model_header_name(name);
4657                    let value = model_header_value(value);
4658                    map.insert(make_header_name(name), make_header_value(&value));
4659                    model.insert(semantic_id, model_original_name(name), value);
4660                }
4661                HeaderMapOp::Remove { name } => {
4662                    let (name, semantic_id) = model_header_name(name);
4663                    map.remove(make_header_name(name));
4664                    model.remove(semantic_id);
4665                }
4666                HeaderMapOp::RemoveEntryMult { name } => {
4667                    let (name, semantic_id) = model_header_name(name);
4668                    if let Entry::Occupied(entry) = map.entry(make_header_name(name)) {
4669                        let _ = entry.remove_entry_mult();
4670                    }
4671                    model.remove(semantic_id);
4672                }
4673                HeaderMapOp::EntryAppend { name, value } => {
4674                    let (name, semantic_id) = model_header_name(name);
4675                    let value = model_header_value(value);
4676                    match map.entry(make_header_name(name)) {
4677                        Entry::Occupied(mut entry) => {
4678                            entry.append(make_header_value(&value));
4679                        }
4680                        Entry::Vacant(entry) => {
4681                            entry.insert_entry(make_header_value(&value));
4682                        }
4683                    }
4684                    model.entry_append(semantic_id, model_original_name(name), value);
4685                }
4686                HeaderMapOp::EntryInsertMult { name, value } => {
4687                    let (name, semantic_id) = model_header_name(name);
4688                    let value = model_header_value(value);
4689                    match map.entry(make_header_name(name)) {
4690                        Entry::Occupied(mut entry) => {
4691                            let _ = entry.insert_mult(make_header_value(&value));
4692                        }
4693                        Entry::Vacant(entry) => {
4694                            entry.insert_entry(make_header_value(&value));
4695                        }
4696                    }
4697                    model.entry_insert_mult(semantic_id, model_original_name(name), value);
4698                }
4699            }
4700
4701            assert_header_map_matches_model(&map, &model);
4702        }
4703    }
4704}
4705
4706#[test]
4707fn quickcheck_header_map_order_and_multivalue_model() {
4708    fn prop(ops: HeaderMapOps) -> bool {
4709        ops.run();
4710        true
4711    }
4712
4713    quickcheck::QuickCheck::new()
4714        .tests(500)
4715        .quickcheck(prop as fn(HeaderMapOps) -> bool);
4716}
4717
4718#[test]
4719fn ensure_miri_itermut_not_violated() {
4720    let mut headers = HeaderMap::<u32>::default();
4721    headers.insert(HeaderName::from_static("hello"), 1u32);
4722    headers.insert(HeaderName::from_static("zomg"), 2u32);
4723
4724    let mut iter = headers.iter_mut();
4725    let (_, first) = iter.next().unwrap();
4726    let (_, second) = iter.next().unwrap();
4727
4728    *first += 10;
4729    *second += 20;
4730}
4731
4732#[test]
4733fn ensure_miri_valueitermut_not_violated() {
4734    let mut headers = HeaderMap::<u32>::default();
4735    headers.insert(HeaderName::from_static("hello"), 1u32);
4736    headers.append(HeaderName::from_static("hello"), 2u32);
4737    headers.append(HeaderName::from_static("hello"), 3u32);
4738
4739    let mut entry = match headers.entry(HeaderName::from_static("hello")) {
4740        Entry::Occupied(entry) => entry,
4741        Entry::Vacant(_) => panic!(),
4742    };
4743
4744    let mut iter = entry.iter_mut();
4745    let first = iter.next().unwrap();
4746    let second = iter.next().unwrap();
4747
4748    *first += 10;
4749    *second += 20;
4750}
4751
4752struct ManuallyAllocated {
4753    ptr: *mut u8,
4754    panic_on_drop: bool,
4755}
4756
4757impl ManuallyAllocated {
4758    fn new(byte: u8, panic_on_drop: bool) -> Self {
4759        Self {
4760            ptr: Box::into_raw(Box::new(byte)),
4761            panic_on_drop,
4762        }
4763    }
4764}
4765
4766impl Drop for ManuallyAllocated {
4767    fn drop(&mut self) {
4768        unsafe {
4769            drop(Box::from_raw(self.ptr));
4770        }
4771
4772        if self.panic_on_drop {
4773            panic!("intentional drop panic");
4774        }
4775    }
4776}
4777
4778#[test]
4779fn into_iter_drop_panic_after_yielding_extra_value_double_drops() {
4780    use std::panic::{AssertUnwindSafe, catch_unwind};
4781
4782    let mut map: HeaderMap<ManuallyAllocated> = HeaderMap::default();
4783    map.append("x-first", ManuallyAllocated::new(1, false));
4784    map.append("x-first", ManuallyAllocated::new(2, false));
4785    map.insert("x-second", ManuallyAllocated::new(3, true));
4786
4787    let mut iter = map.into_iter();
4788
4789    // HeaderMap::IntoIter yields extra values with ptr::read from
4790    // self.extra_values and relies on Drop setting self.extra_values.len() to
4791    // zero after the iterator has been fully consumed. If a later value's Drop
4792    // panics while IntoIter::drop is draining the iterator, that set_len(0) is
4793    // skipped. The Vec then drops already-yielded extra value slots again.
4794    drop(iter.next().unwrap());
4795    drop(iter.next().unwrap());
4796
4797    let _ = catch_unwind(AssertUnwindSafe(|| drop(iter)));
4798}
4799
4800#[test]
4801fn into_ordered_iter_drop_panic_after_yielding_values_does_not_double_drop() {
4802    use std::panic::{AssertUnwindSafe, catch_unwind};
4803
4804    let mut map: HeaderMap<ManuallyAllocated> = HeaderMap::default();
4805    map.append("x-first", ManuallyAllocated::new(1, false));
4806    map.append("x-first", ManuallyAllocated::new(2, false));
4807    map.insert("x-second", ManuallyAllocated::new(3, true));
4808
4809    let mut iter = map.into_ordered_iter();
4810
4811    drop(iter.next().unwrap());
4812    drop(iter.next().unwrap());
4813
4814    let _ = catch_unwind(AssertUnwindSafe(|| drop(iter)));
4815}
4816
4817#[test]
4818fn drain_drop_panic_leaves_map_empty_and_valid() {
4819    use std::panic::{AssertUnwindSafe, catch_unwind};
4820
4821    let mut map: HeaderMap<ManuallyAllocated> = HeaderMap::default();
4822    map.insert("x-panic", ManuallyAllocated::new(1, true));
4823    map.append("x-rest", ManuallyAllocated::new(2, false));
4824    map.append("x-rest", ManuallyAllocated::new(3, false));
4825
4826    let drain = map.drain();
4827    let _ = catch_unwind(AssertUnwindSafe(|| drop(drain)));
4828
4829    assert_header_map_invariants(&map);
4830}
4831
4832#[test]
4833fn skip_duplicates_during_key_iteration() {
4834    let mut map = HeaderMap::new();
4835    map.try_append("a", HeaderValue::from_static("a")).unwrap();
4836    map.try_append("a", HeaderValue::from_static("b")).unwrap();
4837    assert_eq!(map.keys().count(), map.keys_len());
4838}
4839
4840#[test]
4841fn ordered_iter_size_hint_counts_remaining_live_order_slots() {
4842    let mut map = HeaderMap::new();
4843    map.try_insert("a", HeaderValue::from_static("a")).unwrap();
4844    map.try_insert("b", HeaderValue::from_static("b")).unwrap();
4845    map.try_insert("c", HeaderValue::from_static("c")).unwrap();
4846    map.remove("b");
4847
4848    let mut iter = map.ordered_iter();
4849    assert_eq!((2, Some(2)), iter.size_hint());
4850    assert_eq!("a", iter.next().unwrap().0);
4851    assert_eq!((1, Some(1)), iter.size_hint());
4852    assert_eq!("c", iter.next().unwrap().0);
4853    assert_eq!((0, Some(0)), iter.size_hint());
4854    assert!(iter.next().is_none());
4855}
4856
4857#[test]
4858fn drain_size_hint_counts_remaining_entries_and_extras() {
4859    let mut map = HeaderMap::new();
4860    map.append("x-first", HeaderValue::from_static("one"));
4861    map.append("x-first", HeaderValue::from_static("two"));
4862    map.insert("x-second", HeaderValue::from_static("three"));
4863
4864    let mut drain = map.drain();
4865    assert_eq!(drain.size_hint(), (2, Some(3)));
4866
4867    assert_eq!(
4868        drain.next().map(|(name, value)| (
4869            name.map(|name| name.to_string()),
4870            value.to_str().unwrap().to_owned()
4871        )),
4872        Some((Some("x-first".to_owned()), "one".to_owned()))
4873    );
4874    assert_eq!(drain.size_hint(), (1, Some(2)));
4875
4876    assert_eq!(
4877        drain.next().map(|(name, value)| (
4878            name.map(|name| name.to_string()),
4879            value.to_str().unwrap().to_owned()
4880        )),
4881        Some((None, "two".to_owned()))
4882    );
4883    assert_eq!(drain.size_hint(), (1, Some(1)));
4884
4885    assert_eq!(
4886        drain.next().map(|(name, value)| (
4887            name.map(|name| name.to_string()),
4888            value.to_str().unwrap().to_owned()
4889        )),
4890        Some((Some("x-second".to_owned()), "three".to_owned()))
4891    );
4892    assert_eq!(drain.size_hint(), (0, Some(0)));
4893    assert!(drain.next().is_none());
4894}
4895
4896#[test]
4897fn into_iter_size_hint_counts_remaining_entries_only() {
4898    let mut map = HeaderMap::new();
4899    map.append("x-first", HeaderValue::from_static("one"));
4900    map.append("x-first", HeaderValue::from_static("two"));
4901    map.insert("x-second", HeaderValue::from_static("three"));
4902
4903    let mut iter = map.into_iter();
4904    assert_eq!(iter.size_hint(), (2, None));
4905
4906    assert_eq!(
4907        iter.next().map(|(name, value)| (
4908            name.map(|name| name.to_string()),
4909            value.to_str().unwrap().to_owned()
4910        )),
4911        Some((Some("x-first".to_owned()), "one".to_owned()))
4912    );
4913    assert_eq!(iter.size_hint(), (1, None));
4914
4915    assert_eq!(
4916        iter.next().map(|(name, value)| (
4917            name.map(|name| name.to_string()),
4918            value.to_str().unwrap().to_owned()
4919        )),
4920        Some((None, "two".to_owned()))
4921    );
4922    assert_eq!(iter.size_hint(), (1, None));
4923
4924    assert_eq!(
4925        iter.next().map(|(name, value)| (
4926            name.map(|name| name.to_string()),
4927            value.to_str().unwrap().to_owned()
4928        )),
4929        Some((Some("x-second".to_owned()), "three".to_owned()))
4930    );
4931    assert_eq!(iter.size_hint(), (0, None));
4932    assert!(iter.next().is_none());
4933}
4934
4935#[test]
4936fn into_ordered_iter_size_hint_upper_bound_counts_backing_values() {
4937    let mut map = HeaderMap::new();
4938    map.append("x-first", HeaderValue::from_static("one"));
4939    map.append("x-first", HeaderValue::from_static("two"));
4940    map.insert("x-second", HeaderValue::from_static("three"));
4941
4942    let mut iter = map.into_ordered_iter();
4943    assert_eq!(iter.size_hint(), (0, Some(3)));
4944
4945    assert_eq!(
4946        iter.next()
4947            .map(|(name, value)| (name.to_string(), value.to_str().unwrap().to_owned())),
4948        Some(("x-first".to_owned(), "one".to_owned()))
4949    );
4950    assert_eq!(iter.size_hint(), (0, Some(3)));
4951
4952    assert_eq!(
4953        iter.next()
4954            .map(|(name, value)| (name.to_string(), value.to_str().unwrap().to_owned())),
4955        Some(("x-first".to_owned(), "two".to_owned()))
4956    );
4957    assert_eq!(iter.size_hint(), (0, Some(3)));
4958
4959    assert_eq!(
4960        iter.next()
4961            .map(|(name, value)| (name.to_string(), value.to_str().unwrap().to_owned())),
4962        Some(("x-second".to_owned(), "three".to_owned()))
4963    );
4964    assert_eq!(iter.size_hint(), (0, Some(3)));
4965    assert!(iter.next().is_none());
4966}
4967
4968#[test]
4969fn value_drain_size_hint_counts_remaining_values() {
4970    let mut map = HeaderMap::new();
4971    map.append("x-first", HeaderValue::from_static("one"));
4972    map.append("x-first", HeaderValue::from_static("two"));
4973    map.append("x-first", HeaderValue::from_static("three"));
4974
4975    let Entry::Occupied(mut entry) = map.entry("x-first") else {
4976        panic!("expected x-first header");
4977    };
4978    let mut drain = entry.insert_mult(HeaderValue::from_static("replacement"));
4979
4980    assert_eq!(drain.size_hint(), (3, Some(3)));
4981    assert_eq!(
4982        drain.next().map(|value| value.to_str().unwrap().to_owned()),
4983        Some("one".to_owned())
4984    );
4985    assert_eq!(drain.size_hint(), (2, Some(2)));
4986    assert_eq!(
4987        drain.next().map(|value| value.to_str().unwrap().to_owned()),
4988        Some("two".to_owned())
4989    );
4990    assert_eq!(drain.size_hint(), (1, Some(1)));
4991    assert_eq!(
4992        drain.next().map(|value| value.to_str().unwrap().to_owned()),
4993        Some("three".to_owned())
4994    );
4995    assert_eq!(drain.size_hint(), (0, Some(0)));
4996    assert!(drain.next().is_none());
4997}
4998
4999#[test]
5000fn dropping_value_drain_drops_remaining_values() {
5001    use std::cell::Cell;
5002    use std::rc::Rc;
5003
5004    struct DropCounter(Rc<Cell<usize>>);
5005
5006    impl Drop for DropCounter {
5007        fn drop(&mut self) {
5008            self.0.set(self.0.get() + 1);
5009        }
5010    }
5011
5012    let drops = Rc::new(Cell::new(0));
5013    let mut map: HeaderMap<DropCounter> = HeaderMap::default();
5014    map.append("x-first", DropCounter(drops.clone()));
5015    map.append("x-first", DropCounter(drops.clone()));
5016    map.append("x-first", DropCounter(drops.clone()));
5017
5018    let Entry::Occupied(mut entry) = map.entry("x-first") else {
5019        panic!("expected x-first header");
5020    };
5021    let mut drain = entry.insert_mult(DropCounter(drops.clone()));
5022    drop(drain.next());
5023    assert_eq!(drops.get(), 1);
5024
5025    drop(drain);
5026    assert_eq!(drops.get(), 3);
5027}
5028
5029#[test]
5030fn basic_map_api_contracts_cover_capacity_lookup_and_clear() {
5031    let empty = HeaderMap::<HeaderValue>::try_with_capacity(0).unwrap();
5032    assert!(empty.is_empty());
5033    assert_eq!(empty.capacity(), 0);
5034
5035    let mut map = HeaderMap::<HeaderValue>::with_capacity(10);
5036    assert!(map.is_empty());
5037    assert_eq!(map.len(), 0);
5038    assert_eq!(map.keys_len(), 0);
5039    assert_eq!(map.capacity(), 12);
5040    assert_eq!(map.mask as usize, 15);
5041
5042    let mut reserved = HeaderMap::<HeaderValue>::new();
5043    reserved.reserve(10);
5044    assert_eq!(reserved.capacity(), 12);
5045    assert_eq!(reserved.mask as usize, 15);
5046
5047    let mut try_reserved = HeaderMap::<HeaderValue>::new();
5048    try_reserved.try_reserve(10).unwrap();
5049    assert_eq!(try_reserved.capacity(), 12);
5050    assert_eq!(try_reserved.mask as usize, 15);
5051
5052    let max_capacity =
5053        HeaderMap::<HeaderValue>::try_with_capacity(usable_capacity(MAX_SIZE)).unwrap();
5054    assert_eq!(max_capacity.capacity(), usable_capacity(MAX_SIZE));
5055    assert_eq!(max_capacity.mask as usize, MAX_SIZE - 1);
5056    let max_size_err =
5057        HeaderMap::<HeaderValue>::try_with_capacity(usable_capacity(MAX_SIZE) + 1).unwrap_err();
5058    assert_eq!(max_size_err.to_string(), "max size reached");
5059    assert_eq!(format!("{max_size_err:?}"), "MaxSizeReached");
5060    let mut too_large_reserve = HeaderMap::<HeaderValue>::new();
5061    assert!(
5062        too_large_reserve
5063            .try_reserve(usable_capacity(MAX_SIZE) + 1)
5064            .is_err()
5065    );
5066
5067    let key = HeaderName::from_static("x-basic");
5068    let key_string = "x-basic".to_owned();
5069    assert!(!map.contains_key(&key));
5070    assert!(!map.contains_key(&key_string));
5071    assert!(map.get(&key).is_none());
5072    assert!(map.get("x-basic").is_none());
5073    assert!(map.get(key_string.clone()).is_none());
5074    assert!(map.get(&key_string).is_none());
5075
5076    assert!(
5077        map.insert(key.clone(), HeaderValue::from_static("one"))
5078            .is_none()
5079    );
5080    assert!(!map.is_empty());
5081    assert_eq!(map.len(), 1);
5082    assert_eq!(map.keys_len(), 1);
5083    assert!(map.contains_key(&key));
5084    assert!(map.contains_key("x-basic"));
5085    assert!(map.contains_key(key_string.clone()));
5086    assert!(map.contains_key(&key_string));
5087    assert_eq!(map.get(&key).unwrap(), "one");
5088    assert_eq!(map.get(key.clone()).unwrap(), "one");
5089    assert_eq!(map.get("x-basic").unwrap(), "one");
5090    assert_eq!(map.get(key_string.clone()).unwrap(), "one");
5091    assert_eq!(map.get(&key_string).unwrap(), "one");
5092    assert_eq!(map.get("missing"), None);
5093
5094    *map.get_mut("x-basic").unwrap() = HeaderValue::from_static("mutated");
5095    assert_eq!(map.get("x-basic").unwrap(), "mutated");
5096
5097    assert!(map.append("x-basic", HeaderValue::from_static("two")));
5098    assert_eq!(map.len(), 2);
5099    assert_eq!(map.keys_len(), 1);
5100
5101    let borrowed = HeaderName::from_static("x-borrowed");
5102    assert!(
5103        map.insert(&borrowed, HeaderValue::from_static("borrowed"))
5104            .is_none()
5105    );
5106    assert!(map.append(&borrowed, HeaderValue::from_static("borrowed-again")));
5107    assert_eq!(
5108        map.get_all(&borrowed)
5109            .iter()
5110            .map(|value| value.to_str().unwrap().to_owned())
5111            .collect::<Vec<_>>(),
5112        ["borrowed".to_owned(), "borrowed-again".to_owned()]
5113    );
5114
5115    map.clear();
5116    assert!(map.is_empty());
5117    assert_eq!(map.len(), 0);
5118    assert_eq!(map.keys_len(), 0);
5119    assert!(map.capacity() >= 12);
5120    assert!(!map.contains_key("x-basic"));
5121}
5122
5123#[test]
5124fn extend_try_from_equality_debug_and_serde_contracts() {
5125    use std::collections::HashMap;
5126    use std::convert::TryFrom;
5127
5128    let mut raw = HashMap::new();
5129    raw.insert("x-one".to_owned(), "one".to_owned());
5130    raw.insert("x-two".to_owned(), "two".to_owned());
5131
5132    let from_hash = HeaderMap::<HeaderValue>::try_from(&raw).unwrap();
5133    assert_eq!(from_hash.len(), 2);
5134    assert_eq!(from_hash.get("x-one").unwrap(), "one");
5135    assert_eq!(from_hash.get("x-two").unwrap(), "two");
5136
5137    let mut by_name = HeaderMap::new();
5138    by_name.extend([
5139        (
5140            HeaderName::from_static("x-a"),
5141            HeaderValue::from_static("a1"),
5142        ),
5143        (
5144            HeaderName::from_static("x-a"),
5145            HeaderValue::from_static("a2"),
5146        ),
5147        (
5148            HeaderName::from_static("x-b"),
5149            HeaderValue::from_static("b1"),
5150        ),
5151    ]);
5152    assert_eq!(
5153        by_name
5154            .get_all("x-a")
5155            .iter()
5156            .map(|value| value.to_str().unwrap().to_owned())
5157            .collect::<Vec<_>>(),
5158        ["a1".to_owned(), "a2".to_owned()]
5159    );
5160
5161    let mut by_optional_name = HeaderMap::new();
5162    by_optional_name.extend([
5163        (
5164            Some(HeaderName::from_static("x-c")),
5165            HeaderValue::from_static("c1"),
5166        ),
5167        (None, HeaderValue::from_static("c2")),
5168        (
5169            Some(HeaderName::from_static("x-d")),
5170            HeaderValue::from_static("d1"),
5171        ),
5172    ]);
5173    assert_eq!(
5174        by_optional_name
5175            .get_all("x-c")
5176            .iter()
5177            .map(|value| value.to_str().unwrap().to_owned())
5178            .collect::<Vec<_>>(),
5179        ["c1".to_owned(), "c2".to_owned()]
5180    );
5181
5182    let same = by_optional_name.clone();
5183    assert_eq!(by_optional_name, same);
5184    let mut different = same.clone();
5185    different.append("x-c", HeaderValue::from_static("c3"));
5186    assert_ne!(by_optional_name, different);
5187
5188    let debug = format!("{by_optional_name:?}");
5189    assert!(debug.contains("x-c"));
5190    assert!(debug.contains("c1"));
5191
5192    let json = serde_json::to_string(&by_optional_name).unwrap();
5193    let roundtrip: HeaderMap = serde_json::from_str(&json).unwrap();
5194    assert_eq!(
5195        roundtrip
5196            .ordered_iter()
5197            .map(|(name, value)| (name.to_string(), value.to_str().unwrap().to_owned()))
5198            .collect::<Vec<_>>(),
5199        by_optional_name
5200            .ordered_iter()
5201            .map(|(name, value)| (name.to_string(), value.to_str().unwrap().to_owned()))
5202            .collect::<Vec<_>>()
5203    );
5204}
5205
5206#[test]
5207fn unordered_iterators_and_key_value_views_have_stable_contracts() {
5208    let mut map = HeaderMap::new();
5209    map.append("x-first", HeaderValue::from_static("one"));
5210    map.append("x-first", HeaderValue::from_static("two"));
5211    map.insert("x-second", HeaderValue::from_static("three"));
5212
5213    let iter = map.iter();
5214    assert_eq!(iter.size_hint(), (2, None));
5215    let mut iter = iter;
5216    let first = iter
5217        .next()
5218        .map(|(name, value)| (name.to_string(), value.to_str().unwrap().to_owned()))
5219        .unwrap();
5220    assert_eq!(iter.size_hint(), (2, None));
5221    let mut pairs = iter
5222        .map(|(name, value)| (name.to_string(), value.to_str().unwrap().to_owned()))
5223        .collect::<Vec<_>>();
5224    pairs.push(first);
5225    pairs.sort();
5226    assert_eq!(
5227        pairs,
5228        [
5229            ("x-first".to_owned(), "one".to_owned()),
5230            ("x-first".to_owned(), "two".to_owned()),
5231            ("x-second".to_owned(), "three".to_owned()),
5232        ]
5233    );
5234
5235    assert_eq!(map.keys().size_hint(), (2, Some(2)));
5236    let mut keys = map.keys().map(|name| name.to_string()).collect::<Vec<_>>();
5237    keys.sort();
5238    assert_eq!(keys, ["x-first".to_owned(), "x-second".to_owned()]);
5239    assert_eq!(map.keys().count(), 2);
5240    assert!(map.keys().nth(1).is_some());
5241    assert!(map.keys().last().is_some());
5242
5243    assert_eq!(map.values().size_hint(), (2, None));
5244    let mut values = map
5245        .values()
5246        .map(|value| value.to_str().unwrap().to_owned())
5247        .collect::<Vec<_>>();
5248    values.sort();
5249    assert_eq!(
5250        values,
5251        ["one".to_owned(), "three".to_owned(), "two".to_owned()]
5252    );
5253
5254    let mut mutable: HeaderMap<String> = HeaderMap::default();
5255    mutable.append("x-first", "one".to_owned());
5256    mutable.append("x-first", "two".to_owned());
5257    mutable.insert("x-second", "three".to_owned());
5258
5259    let mut iter_mut = mutable.iter_mut();
5260    assert_eq!(iter_mut.size_hint(), (2, None));
5261    iter_mut.next().unwrap().1.push('!');
5262    assert_eq!(iter_mut.size_hint(), (2, None));
5263    for (_, value) in iter_mut {
5264        value.push('!');
5265    }
5266    assert_eq!(mutable.values_mut().size_hint(), (2, None));
5267    for value in mutable.values_mut() {
5268        value.push('?');
5269    }
5270
5271    let mut values = mutable.values().cloned().collect::<Vec<_>>();
5272    values.sort();
5273    assert_eq!(
5274        values,
5275        ["one!?".to_owned(), "three!?".to_owned(), "two!?".to_owned()]
5276    );
5277}
5278
5279#[test]
5280fn per_key_value_iterators_support_forward_and_reverse_traversal() {
5281    let mut map = HeaderMap::new();
5282    map.append("x-multi", HeaderValue::from_static("one"));
5283    map.append("x-multi", HeaderValue::from_static("two"));
5284    map.append("x-multi", HeaderValue::from_static("three"));
5285    map.insert("x-other", HeaderValue::from_static("solo"));
5286
5287    assert_eq!(
5288        map.get_all("x-multi"),
5289        map.get_all(&HeaderName::from_static("x-multi"))
5290    );
5291    assert_ne!(map.get_all("x-multi"), map.get_all("x-other"));
5292
5293    let all = map.get_all("x-multi");
5294    let mut iter = all.iter();
5295    assert_eq!(iter.size_hint(), (1, None));
5296    assert_eq!(iter.next().unwrap(), "one");
5297    assert_eq!(iter.size_hint(), (1, None));
5298    assert_eq!(iter.next_back().unwrap(), "three");
5299    assert_eq!(iter.size_hint(), (1, None));
5300    assert_eq!(iter.next().unwrap(), "two");
5301    assert_eq!(iter.size_hint(), (0, Some(0)));
5302    assert!(iter.next().is_none());
5303    assert!(iter.next_back().is_none());
5304
5305    let mut mutable: HeaderMap<String> = HeaderMap::default();
5306    mutable.append("x-multi", "one".to_owned());
5307    mutable.append("x-multi", "two".to_owned());
5308    mutable.append("x-multi", "three".to_owned());
5309
5310    let Entry::Occupied(mut entry) = mutable.entry("x-multi") else {
5311        panic!("expected x-multi header");
5312    };
5313    let mut iter = entry.iter_mut();
5314    assert_eq!(iter.size_hint(), (0, None));
5315    iter.next().unwrap().push('1');
5316    assert_eq!(iter.size_hint(), (0, None));
5317    iter.next_back().unwrap().push('3');
5318    assert_eq!(iter.size_hint(), (0, None));
5319    iter.next().unwrap().push('2');
5320    assert_eq!(iter.size_hint(), (0, None));
5321    assert!(iter.next().is_none());
5322    assert!(iter.next_back().is_none());
5323
5324    assert_eq!(
5325        mutable
5326            .get_all("x-multi")
5327            .iter()
5328            .cloned()
5329            .collect::<Vec<_>>(),
5330        ["one1".to_owned(), "two2".to_owned(), "three3".to_owned()]
5331    );
5332}
5333
5334#[test]
5335fn growth_remove_and_lookup_stress_preserves_entries_and_order() {
5336    let mut map: HeaderMap<String> = HeaderMap::with_capacity(1);
5337
5338    for i in 0..96 {
5339        let name = HeaderName::from_bytes(format!("x-grow-{i}").as_bytes()).unwrap();
5340        map.insert(name, format!("v{i}"));
5341    }
5342
5343    assert_eq!(map.len(), 96);
5344    assert_eq!(map.keys_len(), 96);
5345    assert!(map.capacity() >= 96);
5346    assert_header_map_invariants(&map);
5347
5348    for i in (0..96).step_by(3) {
5349        let name = HeaderName::from_bytes(format!("x-grow-{i}").as_bytes()).unwrap();
5350        assert_eq!(map.remove(name), Some(format!("v{i}")));
5351    }
5352
5353    assert_eq!(map.len(), 64);
5354    assert_eq!(map.keys_len(), 64);
5355    assert_header_map_invariants(&map);
5356
5357    for i in 0..96 {
5358        let name = format!("x-grow-{i}");
5359        if i % 3 == 0 {
5360            assert!(!map.contains_key(name.as_str()));
5361            assert!(map.get(name.as_str()).is_none());
5362        } else {
5363            assert_eq!(map.get(name.as_str()).unwrap(), &format!("v{i}"));
5364        }
5365    }
5366
5367    for i in (0..96).step_by(3) {
5368        let name = HeaderName::from_bytes(format!("x-grow-{i}").as_bytes()).unwrap();
5369        map.insert(name, format!("reinserted-{i}"));
5370    }
5371
5372    assert_eq!(map.len(), 96);
5373    assert_header_map_invariants(&map);
5374    assert_eq!(map.get("x-grow-0").unwrap(), "reinserted-0");
5375    assert_eq!(map.get("x-grow-95").unwrap(), "v95");
5376}
5377
5378#[test]
5379fn header_map_invariants_survive_ordered_multi_value_mutations() {
5380    let mut map = HeaderMap::new();
5381    assert_header_map_invariants(&map);
5382
5383    map.append("x-first", HeaderValue::from_static("one"));
5384    map.append("x-first", HeaderValue::from_static("two"));
5385    map.append("x-second", HeaderValue::from_static("alpha"));
5386    map.append("x-second", HeaderValue::from_static("beta"));
5387    map.insert("x-third", HeaderValue::from_static("single"));
5388    assert_header_map_invariants(&map);
5389
5390    assert_eq!(map.remove("x-first").unwrap(), "one");
5391    assert_header_map_invariants(&map);
5392
5393    map.append("x-second", HeaderValue::from_static("gamma"));
5394    assert_header_map_invariants(&map);
5395
5396    assert_eq!(
5397        map.insert("x-second", HeaderValue::from_static("replaced"))
5398            .unwrap(),
5399        "alpha"
5400    );
5401    assert_header_map_invariants(&map);
5402
5403    map.append("x-second", HeaderValue::from_static("delta"));
5404    map.append("x-fourth", HeaderValue::from_static("uno"));
5405    map.append("x-fourth", HeaderValue::from_static("dos"));
5406    assert_header_map_invariants(&map);
5407
5408    let Entry::Occupied(fourth) = map.entry("x-fourth") else {
5409        panic!("expected x-fourth header");
5410    };
5411    let (name, values) = fourth.remove_entry_mult();
5412    assert_eq!(name, "x-fourth");
5413    assert_eq!(
5414        values
5415            .map(|value| value.to_str().unwrap().to_owned())
5416            .collect::<Vec<_>>(),
5417        ["uno".to_owned(), "dos".to_owned()]
5418    );
5419    assert_header_map_invariants(&map);
5420
5421    map.append("x-fifth", HeaderValue::from_static("eins"));
5422    map.append("x-fifth", HeaderValue::from_static("zwei"));
5423    let Entry::Occupied(mut fifth) = map.entry("x-fifth") else {
5424        panic!("expected x-fifth header");
5425    };
5426    assert_eq!(
5427        fifth
5428            .insert_mult(HeaderValue::from_static("new"))
5429            .map(|value| value.to_str().unwrap().to_owned())
5430            .collect::<Vec<_>>(),
5431        ["eins".to_owned(), "zwei".to_owned()]
5432    );
5433    assert_header_map_invariants(&map);
5434
5435    let drained = map.drain().collect::<Vec<_>>();
5436    assert!(!drained.is_empty());
5437    assert_header_map_invariants(&map);
5438}
5439
5440#[test]
5441fn remove_entry_mult_then_into_ordered_iter_skips_removed_extras() {
5442    let mut map = HeaderMap::new();
5443    map.append("cookie", HeaderValue::from_static("a=1"));
5444    map.append("cookie", HeaderValue::from_static("b=2"));
5445    map.append("cookie", HeaderValue::from_static("c=3"));
5446
5447    let Entry::Occupied(cookie_headers) = map.entry("cookie") else {
5448        panic!("expected cookie header");
5449    };
5450    let (name, values) = cookie_headers.remove_entry_mult();
5451    let merged = values
5452        .map(|value| value.to_str().unwrap().to_owned())
5453        .collect::<Vec<_>>()
5454        .join("; ");
5455
5456    map.insert(name, HeaderValue::from_str(&merged).unwrap());
5457
5458    let ordered = map
5459        .into_ordered_iter()
5460        .map(|(name, value)| (name.as_str().to_owned(), value.to_str().unwrap().to_owned()))
5461        .collect::<Vec<_>>();
5462
5463    assert_eq!(ordered, [("cookie".to_owned(), "a=1; b=2; c=3".to_owned())]);
5464}
5465
5466#[test]
5467fn insert_mult_then_ordered_iter_updates_moved_extra_order_links() {
5468    let mut map = HeaderMap::new();
5469    map.append("x-first", HeaderValue::from_static("one"));
5470    map.append("x-first", HeaderValue::from_static("two"));
5471    map.append("x-second", HeaderValue::from_static("alpha"));
5472    map.append("x-second", HeaderValue::from_static("beta"));
5473
5474    let Entry::Occupied(mut entry) = map.entry("x-first") else {
5475        panic!("expected x-first header");
5476    };
5477    let old = entry
5478        .insert_mult(HeaderValue::from_static("replaced"))
5479        .map(|value| value.to_str().unwrap().to_owned())
5480        .collect::<Vec<_>>();
5481
5482    assert_eq!(old, ["one".to_owned(), "two".to_owned()]);
5483
5484    let ordered = map
5485        .ordered_iter()
5486        .map(|(name, value)| (name.as_str().to_owned(), value.to_str().unwrap().to_owned()))
5487        .collect::<Vec<_>>();
5488
5489    assert_eq!(
5490        ordered,
5491        [
5492            ("x-first".to_owned(), "replaced".to_owned()),
5493            ("x-second".to_owned(), "alpha".to_owned()),
5494            ("x-second".to_owned(), "beta".to_owned()),
5495        ]
5496    );
5497}
5498
5499#[test]
5500fn order_capacity_grows_with_entry_capacity() {
5501    let mut map = HeaderMap::<HeaderValue>::new();
5502    map.try_insert("a", HeaderValue::from_static("a")).unwrap();
5503
5504    assert!(
5505        map.order.capacity() >= map.entries.capacity(),
5506        "order capacity {} should track entries capacity {}",
5507        map.order.capacity(),
5508        map.entries.capacity()
5509    );
5510
5511    let initial_order_cap = map.order.capacity();
5512    let initial_entry_cap = map.entries.capacity();
5513
5514    for i in 0..initial_entry_cap {
5515        let name = format!("x-rama-{i}");
5516        let name = HeaderName::from_bytes(name.as_bytes()).unwrap();
5517        map.try_insert(name, HeaderValue::from_static("x")).unwrap();
5518    }
5519
5520    assert!(
5521        map.order.capacity() >= map.entries.capacity(),
5522        "order capacity {} should track grown entries capacity {}",
5523        map.order.capacity(),
5524        map.entries.capacity()
5525    );
5526    assert!(map.order.capacity() >= initial_order_cap);
5527}