-
Notifications
You must be signed in to change notification settings - Fork 291
/
map.rs
3358 lines (2970 loc) · 96.5 KB
/
map.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::{fmt, mem, ops, ptr, vec};
use std::collections::hash_map::RandomState;
use std::collections::HashMap;
use std::hash::{BuildHasher, Hash, Hasher};
use std::iter::FromIterator;
use std::marker::PhantomData;
use convert::{HttpTryFrom, HttpTryInto};
use Error;
use super::HeaderValue;
use super::name::{HdrName, HeaderName, InvalidHeaderName};
pub use self::as_header_name::AsHeaderName;
pub use self::into_header_name::IntoHeaderName;
/// A set of HTTP headers
///
/// `HeaderMap` is an multimap of [`HeaderName`] to values.
///
/// [`HeaderName`]: struct.HeaderName.html
///
/// # Examples
///
/// Basic usage
///
/// ```
/// # use http::HeaderMap;
/// # use http::header::{CONTENT_LENGTH, HOST, LOCATION};
/// let mut headers = HeaderMap::new();
///
/// headers.insert(HOST, "example.com".parse().unwrap());
/// headers.insert(CONTENT_LENGTH, "123".parse().unwrap());
///
/// assert!(headers.contains_key(HOST));
/// assert!(!headers.contains_key(LOCATION));
///
/// assert_eq!(headers[HOST], "example.com");
///
/// headers.remove(HOST);
///
/// assert!(!headers.contains_key(HOST));
/// ```
#[derive(Clone)]
pub struct HeaderMap<T = HeaderValue> {
// Used to mask values to get an index
mask: Size,
indices: Box<[Pos]>,
entries: Vec<Bucket<T>>,
extra_values: Vec<ExtraValue<T>>,
danger: Danger,
}
// # Implementation notes
//
// Below, you will find a fairly large amount of code. Most of this is to
// provide the necessary functions to efficiently manipulate the header
// multimap. The core hashing table is based on robin hood hashing [1]. While
// this is the same hashing algorithm used as part of Rust's `HashMap` in
// stdlib, many implementation details are different. The two primary reasons
// for this divergence are that `HeaderMap` is a multimap and the structure has
// been optimized to take advantage of the characteristics of HTTP headers.
//
// ## Structure Layout
//
// Most of the data contained by `HeaderMap` is *not* stored in the hash table.
// Instead, pairs of header name and *first* associated header value are stored
// in the `entries` vector. If the header name has more than one associated
// header value, then additional values are stored in `extra_values`. The actual
// hash table (`indices`) only maps hash codes to indices in `entries`. This
// means that, when an eviction happens, the actual header name and value stay
// put and only a tiny amount of memory has to be copied.
//
// Extra values associated with a header name are tracked using a linked list.
// Links are formed with offsets into `extra_values` and not pointers.
//
// [1]: https://en.wikipedia.org/wiki/Hash_table#Robin_Hood_hashing
/// `HeaderMap` entry iterator.
///
/// Yields `(&HeaderName, &value)` tuples. The same header name may be yielded
/// more than once if it has more than one associated value.
#[derive(Debug)]
pub struct Iter<'a, T: 'a> {
inner: IterMut<'a, T>,
}
/// `HeaderMap` mutable entry iterator
///
/// Yields `(&HeaderName, &mut value)` tuples. The same header name may be
/// yielded more than once if it has more than one associated value.
#[derive(Debug)]
pub struct IterMut<'a, T: 'a> {
map: *mut HeaderMap<T>,
entry: usize,
cursor: Option<Cursor>,
lt: PhantomData<&'a mut HeaderMap<T>>,
}
/// An owning iterator over the entries of a `HeaderMap`.
///
/// This struct is created by the `into_iter` method on `HeaderMap`.
#[derive(Debug)]
pub struct IntoIter<T> {
// If None, pull from `entries`
next: Option<usize>,
entries: vec::IntoIter<Bucket<T>>,
extra_values: Vec<ExtraValue<T>>,
}
/// An iterator over `HeaderMap` keys.
///
/// Each header name is yielded only once, even if it has more than one
/// associated value.
#[derive(Debug)]
pub struct Keys<'a, T: 'a> {
inner: ::std::slice::Iter<'a, Bucket<T>>,
}
/// `HeaderMap` value iterator.
///
/// Each value contained in the `HeaderMap` will be yielded.
#[derive(Debug)]
pub struct Values<'a, T: 'a> {
inner: Iter<'a, T>,
}
/// `HeaderMap` mutable value iterator
#[derive(Debug)]
pub struct ValuesMut<'a, T: 'a> {
inner: IterMut<'a, T>,
}
/// A drain iterator for `HeaderMap`.
#[derive(Debug)]
pub struct Drain<'a, T: 'a> {
idx: usize,
map: *mut HeaderMap<T>,
lt: PhantomData<&'a mut HeaderMap<T>>,
}
/// A view to all values stored in a single entry.
///
/// This struct is returned by `HeaderMap::get_all`.
#[derive(Debug)]
pub struct GetAll<'a, T: 'a> {
map: &'a HeaderMap<T>,
index: Option<usize>,
}
/// A view into a single location in a `HeaderMap`, which may be vacant or occupied.
#[derive(Debug)]
pub enum Entry<'a, T: 'a> {
/// An occupied entry
Occupied(OccupiedEntry<'a, T>),
/// A vacant entry
Vacant(VacantEntry<'a, T>),
}
/// A view into a single empty location in a `HeaderMap`.
///
/// This struct is returned as part of the `Entry` enum.
#[derive(Debug)]
pub struct VacantEntry<'a, T: 'a> {
map: &'a mut HeaderMap<T>,
key: HeaderName,
hash: HashValue,
probe: usize,
danger: bool,
}
/// A view into a single occupied location in a `HeaderMap`.
///
/// This struct is returned as part of the `Entry` enum.
#[derive(Debug)]
pub struct OccupiedEntry<'a, T: 'a> {
map: &'a mut HeaderMap<T>,
probe: usize,
index: usize,
}
/// An iterator of all values associated with a single header name.
#[derive(Debug)]
pub struct ValueIter<'a, T: 'a> {
map: &'a HeaderMap<T>,
index: usize,
front: Option<Cursor>,
back: Option<Cursor>,
}
/// A mutable iterator of all values associated with a single header name.
#[derive(Debug)]
pub struct ValueIterMut<'a, T: 'a> {
map: *mut HeaderMap<T>,
index: usize,
front: Option<Cursor>,
back: Option<Cursor>,
lt: PhantomData<&'a mut HeaderMap<T>>,
}
/// An drain iterator of all values associated with a single header name.
#[derive(Debug)]
pub struct ValueDrain<'a, T: 'a> {
map: *mut HeaderMap<T>,
first: Option<T>,
next: Option<usize>,
lt: PhantomData<&'a mut HeaderMap<T>>,
}
/// Tracks the value iterator state
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
enum Cursor {
Head,
Values(usize),
}
/// Type used for representing the size of a HeaderMap value.
///
/// 32,768 is more than enough entries for a single header map. Setting this
/// limit enables using `u16` to represent all offsets, which takes 2 bytes
/// instead of 8 on 64 bit processors.
///
/// Setting this limit is especially benificial for `indices`, making it more
/// cache friendly. More hash codes can fit in a cache line.
///
/// You may notice that `u16` may represent more than 32,768 values. This is
/// true, but 32,768 should be plenty and it allows us to reserve the top bit
/// for future usage.
type Size = usize;
/// This limit falls out from above.
const MAX_SIZE: usize = (1 << 15);
/// An entry in the hash table. This represents the full hash code for an entry
/// as well as the position of the entry in the `entries` vector.
#[derive(Copy, Clone)]
struct Pos {
// Index in the `entries` vec
index: Size,
// Full hash value for the entry.
hash: HashValue,
}
/// Hash values are limited to u16 as well. While `fast_hash` and `Hasher`
/// return `usize` hash codes, limiting the effective hash code to the lower 16
/// bits is fine since we know that the `indices` vector will never grow beyond
/// that size.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
struct HashValue(usize);
/// Stores the data associated with a `HeaderMap` entry. Only the first value is
/// included in this struct. If a header name has more than one associated
/// value, all extra values are stored in the `extra_values` vector. A doubly
/// linked list of entries is maintained. The doubly linked list is used so that
/// removing a value is constant time. This also has the nice property of
/// enabling double ended iteration.
#[derive(Debug, Clone)]
struct Bucket<T> {
hash: HashValue,
key: HeaderName,
value: T,
links: Option<Links>,
}
/// The head and tail of the value linked list.
#[derive(Debug, Copy, Clone)]
struct Links {
next: usize,
tail: usize,
}
/// Node in doubly-linked list of header value entries
#[derive(Debug, Clone)]
struct ExtraValue<T> {
value: T,
prev: Link,
next: Link,
}
/// A header value node is either linked to another node in the `extra_values`
/// list or it points to an entry in `entries`. The entry in `entries` is the
/// start of the list and holds the associated header name.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
enum Link {
Entry(usize),
Extra(usize),
}
/// Tracks the header map danger level! This relates to the adaptive hashing
/// algorithm. A HeaderMap starts in the "green" state, when a large number of
/// collisions are detected, it transitions to the yellow state. At this point,
/// the header map will either grow and switch back to the green state OR it
/// will transition to the red state.
///
/// When in the red state, a safe hashing algorithm is used and all values in
/// the header map have to be rehashed.
#[derive(Clone)]
enum Danger {
Green,
Yellow,
Red(RandomState),
}
// Constants related to detecting DOS attacks.
//
// Displacement is the number of entries that get shifted when inserting a new
// value. Forward shift is how far the entry gets stored from the ideal
// position.
//
// The current constant values were picked from another implementation. It could
// be that there are different values better suited to the header map case.
const DISPLACEMENT_THRESHOLD: usize = 128;
const FORWARD_SHIFT_THRESHOLD: usize = 512;
// The default strategy for handling the yellow danger state is to increase the
// header map capacity in order to (hopefully) reduce the number of collisions.
// If growing the hash map would cause the load factor to drop bellow this
// threshold, then instead of growing, the headermap is switched to the red
// danger state and safe hashing is used instead.
const LOAD_FACTOR_THRESHOLD: f32 = 0.2;
// Macro used to iterate the hash table starting at a given point, looping when
// the end is hit.
macro_rules! probe_loop {
($label:tt: $probe_var: ident < $len: expr, $body: expr) => {
debug_assert!($len > 0);
$label:
loop {
if $probe_var < $len {
$body
$probe_var += 1;
} else {
$probe_var = 0;
}
}
};
($probe_var: ident < $len: expr, $body: expr) => {
debug_assert!($len > 0);
loop {
if $probe_var < $len {
$body
$probe_var += 1;
} else {
$probe_var = 0;
}
}
};
}
// First part of the robinhood algorithm. Given a key, find the slot in which it
// will be inserted. This is done by starting at the "ideal" spot. Then scanning
// until the destination slot is found. A destination slot is either the next
// empty slot or the next slot that is occupied by an entry that has a lower
// displacement (displacement is the distance from the ideal spot).
//
// This is implemented as a macro instead of a function that takes a closure in
// order to guarantee that it is "inlined". There is no way to annotate closures
// to guarantee inlining.
macro_rules! insert_phase_one {
($map:ident,
$key:expr,
$probe:ident,
$pos:ident,
$hash:ident,
$danger:ident,
$vacant:expr,
$occupied:expr,
$robinhood:expr) =>
{{
let $hash = hash_elem_using(&$map.danger, &$key);
let mut $probe = desired_pos($map.mask, $hash);
let mut dist = 0;
let ret;
// Start at the ideal position, checking all slots
probe_loop!('probe: $probe < $map.indices.len(), {
if let Some(($pos, entry_hash)) = $map.indices[$probe].resolve() {
// The slot is already occupied, but check if it has a lower
// displacement.
let their_dist = probe_distance($map.mask, entry_hash, $probe);
if their_dist < dist {
// The new key's distance is larger, so claim this spot and
// displace the current entry.
//
// Check if this insertion is above the danger threshold.
let $danger =
dist >= FORWARD_SHIFT_THRESHOLD && !$map.danger.is_red();
ret = $robinhood;
break 'probe;
} else if entry_hash == $hash && $map.entries[$pos].key == $key {
// There already is an entry with the same key.
ret = $occupied;
break 'probe;
}
} else {
// The entry is vacant, use it for this key.
let $danger =
dist >= FORWARD_SHIFT_THRESHOLD && !$map.danger.is_red();
ret = $vacant;
break 'probe;
}
dist += 1;
});
ret
}}
}
// ===== impl HeaderMap =====
impl HeaderMap {
/// Create an empty `HeaderMap`.
///
/// The map will be created without any capacity. This function will not
/// allocate.
///
/// # Examples
///
/// ```
/// # use http::HeaderMap;
/// let map = HeaderMap::new();
///
/// assert!(map.is_empty());
/// assert_eq!(0, map.capacity());
/// ```
pub fn new() -> Self {
HeaderMap::with_capacity(0)
}
}
impl<T> HeaderMap<T> {
/// Create an empty `HeaderMap` with the specified capacity.
///
/// The returned map will allocate internal storage in order to hold about
/// `capacity` elements without reallocating. However, this is a "best
/// effort" as there are usage patterns that could cause additional
/// allocations before `capacity` headers are stored in the map.
///
/// More capacity than requested may be allocated.
///
/// # Examples
///
/// ```
/// # use http::HeaderMap;
/// let map: HeaderMap<u32> = HeaderMap::with_capacity(10);
///
/// assert!(map.is_empty());
/// assert_eq!(12, map.capacity());
/// ```
pub fn with_capacity(capacity: usize) -> HeaderMap<T> {
assert!(capacity <= MAX_SIZE, "requested capacity too large");
if capacity == 0 {
HeaderMap {
mask: 0,
indices: Box::new([]), // as a ZST, this doesn't actually allocate anything
entries: Vec::new(),
extra_values: Vec::new(),
danger: Danger::Green,
}
} else {
let raw_cap = to_raw_capacity(capacity).next_power_of_two();
debug_assert!(raw_cap > 0);
HeaderMap {
mask: (raw_cap - 1) as Size,
indices: vec![Pos::none(); raw_cap].into_boxed_slice(),
entries: Vec::with_capacity(raw_cap),
extra_values: Vec::new(),
danger: Danger::Green,
}
}
}
/// Returns the number of headers stored in the map.
///
/// This number represents the total number of **values** stored in the map.
/// This number can be greater than or equal to the number of **keys**
/// stored given that a single key may have more than one associated value.
///
/// # Examples
///
/// ```
/// # use http::HeaderMap;
/// # use http::header::{ACCEPT, HOST};
/// let mut map = HeaderMap::new();
///
/// assert_eq!(0, map.len());
///
/// map.insert(ACCEPT, "text/plain".parse().unwrap());
/// map.insert(HOST, "localhost".parse().unwrap());
///
/// assert_eq!(2, map.len());
///
/// map.append(ACCEPT, "text/html".parse().unwrap());
///
/// assert_eq!(3, map.len());
/// ```
pub fn len(&self) -> usize {
self.entries.len() + self.extra_values.len()
}
/// Returns the number of keys stored in the map.
///
/// This number will be less than or equal to `len()` as each key may have
/// more than one associated value.
///
/// # Examples
///
/// ```
/// # use http::HeaderMap;
/// # use http::header::{ACCEPT, HOST};
/// let mut map = HeaderMap::new();
///
/// assert_eq!(0, map.keys_len());
///
/// map.insert(ACCEPT, "text/plain".parse().unwrap());
/// map.insert(HOST, "localhost".parse().unwrap());
///
/// assert_eq!(2, map.keys_len());
///
/// map.insert(ACCEPT, "text/html".parse().unwrap());
///
/// assert_eq!(2, map.keys_len());
/// ```
pub fn keys_len(&self) -> usize {
self.entries.len()
}
/// Returns true if the map contains no elements.
///
/// # Examples
///
/// ```
/// # use http::HeaderMap;
/// # use http::header::HOST;
/// let mut map = HeaderMap::new();
///
/// assert!(map.is_empty());
///
/// map.insert(HOST, "hello.world".parse().unwrap());
///
/// assert!(!map.is_empty());
/// ```
pub fn is_empty(&self) -> bool {
self.entries.len() == 0
}
/// Clears the map, removing all key-value pairs. Keeps the allocated memory
/// for reuse.
///
/// # Examples
///
/// ```
/// # use http::HeaderMap;
/// # use http::header::HOST;
/// let mut map = HeaderMap::new();
/// map.insert(HOST, "hello.world".parse().unwrap());
///
/// map.clear();
/// assert!(map.is_empty());
/// assert!(map.capacity() > 0);
/// ```
pub fn clear(&mut self) {
self.entries.clear();
self.extra_values.clear();
self.danger = Danger::Green;
for e in self.indices.iter_mut() {
*e = Pos::none();
}
}
/// Returns the number of headers the map can hold without reallocating.
///
/// This number is an approximation as certain usage patterns could cause
/// additional allocations before the returned capacity is filled.
///
/// # Examples
///
/// ```
/// # use http::HeaderMap;
/// # use http::header::HOST;
/// let mut map = HeaderMap::new();
///
/// assert_eq!(0, map.capacity());
///
/// map.insert(HOST, "hello.world".parse().unwrap());
/// assert_eq!(6, map.capacity());
/// ```
pub fn capacity(&self) -> usize {
usable_capacity(self.indices.len())
}
/// Reserves capacity for at least `additional` more headers to be inserted
/// into the `HeaderMap`.
///
/// The header map may reserve more space to avoid frequent reallocations.
/// Like with `with_capacity`, this will be a "best effort" to avoid
/// allocations until `additional` more headers are inserted. Certain usage
/// patterns could cause additional allocations before the number is
/// reached.
///
/// # Panics
///
/// Panics if the new allocation size overflows `usize`.
///
/// # Examples
///
/// ```
/// # use http::HeaderMap;
/// # use http::header::HOST;
/// let mut map = HeaderMap::new();
/// map.reserve(10);
/// # map.insert(HOST, "bar".parse().unwrap());
/// ```
pub fn reserve(&mut self, additional: usize) {
// TODO: This can't overflow if done properly... since the max # of
// elements is u16::MAX.
let cap = self.entries.len()
.checked_add(additional)
.expect("reserve overflow");
if cap > self.indices.len() {
let cap = cap.next_power_of_two();
if self.entries.len() == 0 {
self.mask = cap - 1;
self.indices = vec![Pos::none(); cap].into_boxed_slice();
self.entries = Vec::with_capacity(usable_capacity(cap));
} else {
self.grow(cap);
}
}
}
/// Returns a reference to the value associated with the key.
///
/// If there are multiple values associated with the key, then the first one
/// is returned. Use `get_all` to get all values associated with a given
/// key. Returns `None` if there are no values associated with the key.
///
/// # Examples
///
/// ```
/// # use http::HeaderMap;
/// # use http::header::HOST;
/// let mut map = HeaderMap::new();
/// assert!(map.get("host").is_none());
///
/// map.insert(HOST, "hello".parse().unwrap());
/// assert_eq!(map.get(HOST).unwrap(), &"hello");
/// assert_eq!(map.get("host").unwrap(), &"hello");
///
/// map.append(HOST, "world".parse().unwrap());
/// assert_eq!(map.get("host").unwrap(), &"hello");
/// ```
pub fn get<K>(&self, key: K) -> Option<&T>
where K: AsHeaderName
{
self.get2(&key)
}
fn get2<K>(&self, key: &K) -> Option<&T>
where K: AsHeaderName
{
match key.find(self) {
Some((_, found)) => {
let entry = &self.entries[found];
Some(&entry.value)
}
None => None,
}
}
/// Returns a mutable reference to the value associated with the key.
///
/// If there are multiple values associated with the key, then the first one
/// is returned. Use `entry` to get all values associated with a given
/// key. Returns `None` if there are no values associated with the key.
///
/// # Examples
///
/// ```
/// # use http::HeaderMap;
/// # use http::header::HOST;
/// let mut map = HeaderMap::default();
/// map.insert(HOST, "hello".to_string());
/// map.get_mut("host").unwrap().push_str("-world");
///
/// assert_eq!(map.get(HOST).unwrap(), &"hello-world");
/// ```
pub fn get_mut<K>(&mut self, key: K) -> Option<&mut T>
where K: AsHeaderName
{
match key.find(self) {
Some((_, found)) => {
let entry = &mut self.entries[found];
Some(&mut entry.value)
}
None => None,
}
}
/// Returns a view of all values associated with a key.
///
/// The returned view does not incur any allocations and allows iterating
/// the values associated with the key. See [`GetAll`] for more details.
/// Returns `None` if there are no values associated with the key.
///
/// [`GetAll`]: struct.GetAll.html
///
/// # Examples
///
/// ```
/// # use http::HeaderMap;
/// # use http::header::HOST;
/// let mut map = HeaderMap::new();
///
/// map.insert(HOST, "hello".parse().unwrap());
/// map.append(HOST, "goodbye".parse().unwrap());
///
/// let view = map.get_all("host");
///
/// let mut iter = view.iter();
/// assert_eq!(&"hello", iter.next().unwrap());
/// assert_eq!(&"goodbye", iter.next().unwrap());
/// assert!(iter.next().is_none());
/// ```
pub fn get_all<K>(&self, key: K) -> GetAll<T>
where K: AsHeaderName
{
GetAll {
map: self,
index: key.find(self).map(|(_, i)| i),
}
}
/// Returns true if the map contains a value for the specified key.
///
/// # Examples
///
/// ```
/// # use http::HeaderMap;
/// # use http::header::HOST;
/// let mut map = HeaderMap::new();
/// assert!(!map.contains_key(HOST));
///
/// map.insert(HOST, "world".parse().unwrap());
/// assert!(map.contains_key("host"));
/// ```
pub fn contains_key<K>(&self, key: K) -> bool
where K: AsHeaderName
{
key.find(self).is_some()
}
/// An iterator visiting all key-value pairs.
///
/// The iteration order is arbitrary, but consistent across platforms for
/// the same crate version. Each key will be yielded once per associated
/// value. So, if a key has 3 associated values, it will be yielded 3 times.
///
/// # Examples
///
/// ```
/// # use http::HeaderMap;
/// # use http::header::{CONTENT_LENGTH, HOST};
/// let mut map = HeaderMap::new();
///
/// map.insert(HOST, "hello".parse().unwrap());
/// map.append(HOST, "goodbye".parse().unwrap());
/// map.insert(CONTENT_LENGTH, "123".parse().unwrap());
///
/// for (key, value) in map.iter() {
/// println!("{:?}: {:?}", key, value);
/// }
/// ```
pub fn iter(&self) -> Iter<T> {
Iter {
inner: IterMut {
map: self as *const _ as *mut _,
entry: 0,
cursor: self.entries.first().map(|_| Cursor::Head),
lt: PhantomData,
}
}
}
/// An iterator visiting all key-value pairs, with mutable value references.
///
/// The iterator order is arbitrary, but consistent across platforms for the
/// same crate version. Each key will be yielded once per associated value,
/// so if a key has 3 associated values, it will be yielded 3 times.
///
/// # Examples
///
/// ```
/// # use http::HeaderMap;
/// # use http::header::{CONTENT_LENGTH, HOST};
/// let mut map = HeaderMap::default();
///
/// map.insert(HOST, "hello".to_string());
/// map.append(HOST, "goodbye".to_string());
/// map.insert(CONTENT_LENGTH, "123".to_string());
///
/// for (key, value) in map.iter_mut() {
/// value.push_str("-boop");
/// }
/// ```
pub fn iter_mut(&mut self) -> IterMut<T> {
IterMut {
map: self as *mut _,
entry: 0,
cursor: self.entries.first().map(|_| Cursor::Head),
lt: PhantomData,
}
}
/// An iterator visiting all keys.
///
/// The iteration order is arbitrary, but consistent across platforms for
/// the same crate version. Each key will be yielded only once even if it
/// has multiple associated values.
///
/// # Examples
///
/// ```
/// # use http::HeaderMap;
/// # use http::header::{CONTENT_LENGTH, HOST};
/// let mut map = HeaderMap::new();
///
/// map.insert(HOST, "hello".parse().unwrap());
/// map.append(HOST, "goodbye".parse().unwrap());
/// map.insert(CONTENT_LENGTH, "123".parse().unwrap());
///
/// for key in map.keys() {
/// println!("{:?}", key);
/// }
/// ```
pub fn keys(&self) -> Keys<T> {
Keys { inner: self.entries.iter() }
}
/// An iterator visiting all values.
///
/// The iteration order is arbitrary, but consistent across platforms for
/// the same crate version.
///
/// # Examples
///
/// ```
/// # use http::HeaderMap;
/// # use http::header::{CONTENT_LENGTH, HOST};
/// let mut map = HeaderMap::new();
///
/// map.insert(HOST, "hello".parse().unwrap());
/// map.append(HOST, "goodbye".parse().unwrap());
/// map.insert(CONTENT_LENGTH, "123".parse().unwrap());
///
/// for value in map.values() {
/// println!("{:?}", value);
/// }
/// ```
pub fn values(&self) -> Values<T> {
Values { inner: self.iter() }
}
/// An iterator visiting all values mutably.
///
/// The iteration order is arbitrary, but consistent across platforms for
/// the same crate version.
///
/// # Examples
///
/// ```
/// # use http::HeaderMap;
/// # use http::header::{CONTENT_LENGTH, HOST};
/// let mut map = HeaderMap::default();
///
/// map.insert(HOST, "hello".to_string());
/// map.append(HOST, "goodbye".to_string());
/// map.insert(CONTENT_LENGTH, "123".to_string());
///
/// for value in map.values_mut() {
/// value.push_str("-boop");
/// }
/// ```
pub fn values_mut(&mut self) -> ValuesMut<T> {
ValuesMut { inner: self.iter_mut() }
}
/// Clears the map, returning all entries as an iterator.
///
/// The internal memory is kept for reuse.
///
/// # Examples
///
/// ```
/// # use http::HeaderMap;
/// # use http::header::{CONTENT_LENGTH, HOST};
/// let mut map = HeaderMap::new();
///
/// map.insert(HOST, "hello".parse().unwrap());
/// map.append(HOST, "goodbye".parse().unwrap());
/// map.insert(CONTENT_LENGTH, "123".parse().unwrap());
///
/// let mut drain = map.drain();
///
/// let (key, mut vals) = drain.next().unwrap();
///
/// assert_eq!("host", key);
/// assert_eq!("hello", vals.next().unwrap());
/// assert_eq!("goodbye", vals.next().unwrap());
/// assert!(vals.next().is_none());
///
/// let (key, mut vals) = drain.next().unwrap();
///
/// assert_eq!("content-length", key);
/// assert_eq!("123", vals.next().unwrap());
/// assert!(vals.next().is_none());
/// ```
pub fn drain(&mut self) -> Drain<T> {
for i in self.indices.iter_mut() {
*i = Pos::none();
}
Drain {
idx: 0,
map: self as *mut _,
lt: PhantomData,
}
}
fn value_iter(&self, idx: Option<usize>) -> ValueIter<T> {
use self::Cursor::*;
if let Some(idx) = idx {
let back = {
let entry = &self.entries[idx];
entry.links
.map(|l| Values(l.tail))
.unwrap_or(Head)
};
ValueIter {
map: self,
index: idx,
front: Some(Head),
back: Some(back),
}
} else {
ValueIter {
map: self,
index: ::std::usize::MAX,
front: None,
back: None,
}
}
}
fn value_iter_mut(&mut self, idx: usize) -> ValueIterMut<T> {
use self::Cursor::*;
let back = {
let entry = &self.entries[idx];
entry.links
.map(|l| Values(l.tail))
.unwrap_or(Head)
};
ValueIterMut {
map: self as *mut _,
index: idx,
front: Some(Head),
back: Some(back),
lt: PhantomData,
}
}
/// Gets the given key's corresponding entry in the map for in-place
/// manipulation.
///
/// # Examples
///
/// ```
/// # use http::HeaderMap;
/// let mut map: HeaderMap<u32> = HeaderMap::default();
///
/// let headers = &[
/// "content-length",
/// "x-hello",
/// "Content-Length",