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