forked from tower-rs/tower-grpc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
metadata_map.rs
1785 lines (1602 loc) · 52 KB
/
metadata_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 http;
use metadata_key::InvalidMetadataKey;
use metadata_key::MetadataKey;
use metadata_value::MetadataValue;
pub use self::as_metadata_key::AsMetadataKey;
pub use self::into_metadata_key::IntoMetadataKey;
/// A set of gRPC custom metadata entries.
///
/// # Examples
///
/// Basic usage
///
/// ```
/// # use tower_grpc::metadata::*;
/// let mut map = MetadataMap::new();
///
/// map.insert("x-host", "example.com".parse().unwrap());
/// map.insert("x-number", "123".parse().unwrap());
///
/// assert!(map.contains_key("x-host"));
/// assert!(!map.contains_key("x-location"));
///
/// assert_eq!(map.get("x-host").unwrap(), "example.com");
///
/// map.remove("x-host");
///
/// assert!(!map.contains_key("x-host"));
/// ```
#[derive(Clone, Debug, Default)]
pub struct MetadataMap {
headers: http::HeaderMap,
}
/// `MetadataMap` entry iterator.
///
/// Yields `(&MetadataKey, &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> {
inner: http::header::Iter<'a, http::header::HeaderValue>,
}
/// `MetadataMap` entry iterator.
///
/// Yields `(&MetadataKey, &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> {
inner: http::header::IterMut<'a, http::header::HeaderValue>,
}
/// A drain iterator of all values associated with a single metadata key.
#[derive(Debug)]
pub struct ValueDrain<'a> {
inner: http::header::ValueDrain<'a, http::header::HeaderValue>,
}
/// A drain iterator for `MetadataMap`.
#[derive(Debug)]
pub struct Drain<'a> {
inner: http::header::Drain<'a, http::header::HeaderValue>,
}
/// An iterator over `MetadataMap` keys.
///
/// Each header name is yielded only once, even if it has more than one
/// associated value.
#[derive(Debug)]
pub struct Keys<'a> {
inner: http::header::Keys<'a, http::header::HeaderValue>,
}
/// `MetadataMap` value iterator.
///
/// Each value contained in the `MetadataMap` will be yielded.
#[derive(Debug)]
pub struct Values<'a> {
inner: http::header::Values<'a, http::header::HeaderValue>,
}
/// `MetadataMap` value iterator.
///
/// Each value contained in the `MetadataMap` will be yielded.
#[derive(Debug)]
pub struct ValuesMut<'a> {
inner: http::header::ValuesMut<'a, http::header::HeaderValue>,
}
/// An iterator of all values associated with a single metadata key.
#[derive(Debug)]
pub struct ValueIter<'a> {
inner: http::header::ValueIter<'a, http::header::HeaderValue>,
}
/// An iterator of all values associated with a single metadata key.
#[derive(Debug)]
pub struct ValueIterMut<'a> {
inner: http::header::ValueIterMut<'a, http::header::HeaderValue>,
}
/// A view to all values stored in a single entry.
///
/// This struct is returned by `MetadataMap::get_all`.
#[derive(Debug)]
pub struct GetAll<'a> {
inner: http::header::GetAll<'a, http::header::HeaderValue>
}
/// A view into a single location in a `MetadataMap`, which may be vacant or occupied.
#[derive(Debug)]
pub enum Entry<'a> {
/// An occupied entry
Occupied(OccupiedEntry<'a>),
/// A vacant entry
Vacant(VacantEntry<'a>),
}
/// A view into a single empty location in a `MetadataMap`.
///
/// This struct is returned as part of the `Entry` enum.
#[derive(Debug)]
pub struct VacantEntry<'a> {
inner: http::header::VacantEntry<'a, http::header::HeaderValue>,
}
/// A view into a single occupied location in a `MetadataMap`.
///
/// This struct is returned as part of the `Entry` enum.
#[derive(Debug)]
pub struct OccupiedEntry<'a> {
inner: http::header::OccupiedEntry<'a, http::header::HeaderValue>,
}
// ===== impl MetadataMap =====
impl MetadataMap {
/// Create an empty `MetadataMap`.
///
/// The map will be created without any capacity. This function will not
/// allocate.
///
/// # Examples
///
/// ```
/// # use tower_grpc::metadata::*;
/// let map = MetadataMap::new();
///
/// assert!(map.is_empty());
/// assert_eq!(0, map.capacity());
/// ```
pub fn new() -> Self {
MetadataMap::with_capacity(0)
}
/// Convert an HTTP HeaderMap to a MetadataMap
pub fn from_headers(headers: http::HeaderMap) -> Self {
MetadataMap { headers: headers }
}
/// Convert a MetadataMap into a HTTP HeaderMap
///
/// # Examples
///
/// ```
/// # use tower_grpc::metadata::*;
/// let mut map = MetadataMap::new();
/// map.insert("x-host", "example.com".parse().unwrap());
///
/// let http_map = map.into_headers();
///
/// assert_eq!(http_map.get("x-host").unwrap(), "example.com");
/// ```
pub fn into_headers(self) -> http::HeaderMap {
self.headers
}
/// Create an empty `MetadataMap` 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` metadata entries are stored in the map.
///
/// More capacity than requested may be allocated.
///
/// # Examples
///
/// ```
/// # use tower_grpc::metadata::*;
/// let map: MetadataMap = MetadataMap::with_capacity(10);
///
/// assert!(map.is_empty());
/// assert!(map.capacity() >= 10);
/// ```
pub fn with_capacity(capacity: usize) -> MetadataMap {
MetadataMap {
headers: http::HeaderMap::with_capacity(capacity),
}
}
/// Returns the number of metadata entries 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 tower_grpc::metadata::*;
/// let mut map = MetadataMap::new();
///
/// assert_eq!(0, map.len());
///
/// map.insert("x-host-ip", "127.0.0.1".parse().unwrap());
/// map.insert("x-host-name", "localhost".parse().unwrap());
///
/// assert_eq!(2, map.len());
///
/// map.append("x-mime-type", "text/html".parse().unwrap());
///
/// assert_eq!(3, map.len());
/// ```
pub fn len(&self) -> usize {
self.headers.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 tower_grpc::metadata::*;
/// let mut map = MetadataMap::new();
///
/// assert_eq!(0, map.keys_len());
///
/// map.insert("x-mime", "text/plain".parse().unwrap());
/// map.insert("x-host", "localhost".parse().unwrap());
///
/// assert_eq!(2, map.keys_len());
///
/// map.insert("x-mime", "text/html".parse().unwrap());
///
/// assert_eq!(2, map.keys_len());
/// ```
pub fn keys_len(&self) -> usize {
self.headers.keys_len()
}
/// Returns true if the map contains no elements.
///
/// # Examples
///
/// ```
/// # use tower_grpc::metadata::*;
/// let mut map = MetadataMap::new();
///
/// assert!(map.is_empty());
///
/// map.insert("x-host", "hello.world".parse().unwrap());
///
/// assert!(!map.is_empty());
/// ```
pub fn is_empty(&self) -> bool {
self.headers.is_empty()
}
/// Clears the map, removing all key-value pairs. Keeps the allocated memory
/// for reuse.
///
/// # Examples
///
/// ```
/// # use tower_grpc::metadata::*;
/// let mut map = MetadataMap::new();
/// map.insert("x-host", "hello.world".parse().unwrap());
///
/// map.clear();
/// assert!(map.is_empty());
/// assert!(map.capacity() > 0);
/// ```
pub fn clear(&mut self) {
self.headers.clear();
}
/// Returns the number of custom metadata entries 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 tower_grpc::metadata::*;
/// let mut map = MetadataMap::new();
///
/// assert_eq!(0, map.capacity());
///
/// map.insert("x-host", "hello.world".parse().unwrap());
/// assert_eq!(6, map.capacity());
/// ```
pub fn capacity(&self) -> usize {
self.headers.capacity()
}
/// Reserves capacity for at least `additional` more custom metadata to be
/// inserted into the `MetadataMap`.
///
/// The metadata 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 custom metadata is inserted. Certain
/// usage patterns could cause additional allocations before the number is
/// reached.
///
/// # Panics
///
/// Panics if the new allocation size overflows `usize`.
///
/// # Examples
///
/// ```
/// # use tower_grpc::metadata::*;
/// let mut map = MetadataMap::new();
/// map.reserve(10);
/// # map.insert("x-host", "bar".parse().unwrap());
/// ```
pub fn reserve(&mut self, additional: usize) {
self.headers.reserve(additional);
}
/// 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 tower_grpc::metadata::*;
/// let mut map = MetadataMap::new();
/// assert!(map.get("x-host").is_none());
///
/// map.insert("x-host", "hello".parse().unwrap());
/// assert_eq!(map.get("x-host").unwrap(), &"hello");
/// assert_eq!(map.get("x-host").unwrap(), &"hello");
///
/// map.append("x-host", "world".parse().unwrap());
/// assert_eq!(map.get("x-host").unwrap(), &"hello");
/// ```
pub fn get<K>(&self, key: K) -> Option<&MetadataValue>
where K: AsMetadataKey
{
key.get(self)
}
/// 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 tower_grpc::metadata::*;
/// let mut map = MetadataMap::default();
/// map.insert("x-host", "hello".parse().unwrap());
/// map.get_mut("x-host").unwrap().set_sensitive(true);
///
/// assert!(map.get("x-host").unwrap().is_sensitive());
/// ```
pub fn get_mut<K>(&mut self, key: K) -> Option<&mut MetadataValue>
where K: AsMetadataKey
{
key.get_mut(self)
}
/// 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 tower_grpc::metadata::*;
/// let mut map = MetadataMap::new();
///
/// map.insert("x-host", "hello".parse().unwrap());
/// map.append("x-host", "goodbye".parse().unwrap());
///
/// let view = map.get_all("x-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
where K: AsMetadataKey
{
GetAll {
inner: key.get_all(self),
}
}
/// Returns true if the map contains a value for the specified key.
///
/// # Examples
///
/// ```
/// # use tower_grpc::metadata::*;
/// let mut map = MetadataMap::new();
/// assert!(!map.contains_key("x-host"));
///
/// map.insert("x-host", "world".parse().unwrap());
/// assert!(map.contains_key("x-host"));
/// ```
pub fn contains_key<K>(&self, key: K) -> bool
where K: AsMetadataKey
{
key.contains_key(self)
}
/// 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 tower_grpc::metadata::*;
/// let mut map = MetadataMap::new();
///
/// map.insert("x-word", "hello".parse().unwrap());
/// map.append("x-word", "goodbye".parse().unwrap());
/// map.insert("x-number", "123".parse().unwrap());
///
/// for (key, value) in map.iter() {
/// println!("{:?}: {:?}", key, value);
/// }
/// ```
pub fn iter(&self) -> Iter {
Iter { inner: self.headers.iter() }
}
/// 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 tower_grpc::metadata::*;
/// let mut map = MetadataMap::default();
///
/// map.insert("x-word", "hello".parse().unwrap());
/// map.append("x-word", "goodbye".parse().unwrap());
/// map.insert("x-number", "123".parse().unwrap());
///
/// for (key, value) in map.iter_mut() {
/// value.set_sensitive(true);
/// }
/// ```
pub fn iter_mut(&mut self) -> IterMut {
IterMut { inner: self.headers.iter_mut() }
}
/// 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 tower_grpc::metadata::*;
/// let mut map = MetadataMap::new();
///
/// map.insert("x-word", "hello".parse().unwrap());
/// map.append("x-word", "goodbye".parse().unwrap());
/// map.insert("x-number", "123".parse().unwrap());
///
/// for key in map.keys() {
/// println!("{:?}", key);
/// }
/// ```
pub fn keys(&self) -> Keys {
Keys { inner: self.headers.keys() }
}
/// An iterator visiting all values.
///
/// The iteration order is arbitrary, but consistent across platforms for
/// the same crate version.
///
/// # Examples
///
/// ```
/// # use tower_grpc::metadata::*;
/// let mut map = MetadataMap::new();
///
/// map.insert("x-word", "hello".parse().unwrap());
/// map.append("x-word", "goodbye".parse().unwrap());
/// map.insert("x-number", "123".parse().unwrap());
///
/// for value in map.values() {
/// println!("{:?}", value);
/// }
/// ```
pub fn values(&self) -> Values {
Values { inner: self.headers.values() }
}
/// An iterator visiting all values mutably.
///
/// The iteration order is arbitrary, but consistent across platforms for
/// the same crate version.
///
/// # Examples
///
/// ```
/// # use tower_grpc::metadata::*;
/// let mut map = MetadataMap::default();
///
/// map.insert("x-word", "hello".parse().unwrap());
/// map.append("x-word", "goodbye".parse().unwrap());
/// map.insert("x-number", "123".parse().unwrap());
///
/// for value in map.values_mut() {
/// value.set_sensitive(true);
/// }
/// ```
pub fn values_mut(&mut self) -> ValuesMut {
ValuesMut { inner: self.headers.values_mut() }
}
/// Clears the map, returning all entries as an iterator.
///
/// The internal memory is kept for reuse.
///
/// # Examples
///
/// ```
/// # use tower_grpc::metadata::*;
/// let mut map = MetadataMap::new();
///
/// map.insert("x-word", "hello".parse().unwrap());
/// map.append("x-word", "goodbye".parse().unwrap());
/// map.insert("x-number", "123".parse().unwrap());
///
/// let mut drain = map.drain();
///
/// let (key, mut vals) = drain.next().unwrap();
///
/// assert_eq!("x-word", 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!("x-number", key);
/// assert_eq!("123", vals.next().unwrap());
/// assert!(vals.next().is_none());
/// ```
pub fn drain(&mut self) -> Drain {
Drain { inner: self.headers.drain() }
}
/// Gets the given key's corresponding entry in the map for in-place
/// manipulation.
///
/// # Examples
///
/// ```
/// # use tower_grpc::metadata::*;
/// let mut map = MetadataMap::default();
///
/// let headers = &[
/// "content-length",
/// "x-hello",
/// "Content-Length",
/// "x-world",
/// ];
///
/// for &header in headers {
/// let counter = map.entry(header).unwrap().or_insert("".parse().unwrap());
/// *counter = format!("{}{}", counter.to_str().unwrap(), "1").parse().unwrap();
/// }
///
/// assert_eq!(map.get("content-length").unwrap(), "11");
/// assert_eq!(map.get("x-hello").unwrap(), "1");
/// ```
pub fn entry<K>(&mut self, key: K) -> Result<Entry, InvalidMetadataKey>
where K: AsMetadataKey
{
match key.entry(self) {
Ok(entry) => {
Ok(match entry {
http::header::Entry::Occupied(e) =>
Entry::Occupied(OccupiedEntry { inner: e }),
http::header::Entry::Vacant(e) =>
Entry::Vacant(VacantEntry { inner: e }),
})
}
Err(_) => Err(InvalidMetadataKey::new()),
}
}
/// Inserts a key-value pair into the map.
///
/// If the map did not previously have this key present, then `None` is
/// returned.
///
/// If the map did have this key present, the new value is associated with
/// the key and all previous values are removed. **Note** that only a single
/// one of the previous values is returned. If there are multiple values
/// that have been previously associated with the key, then the first one is
/// returned. See `insert_mult` on `OccupiedEntry` for an API that returns
/// all values.
///
/// The key is not updated, though; this matters for types that can be `==`
/// without being identical.
///
/// # Examples
///
/// ```
/// # use tower_grpc::metadata::*;
/// let mut map = MetadataMap::new();
/// assert!(map.insert("x-host", "world".parse().unwrap()).is_none());
/// assert!(!map.is_empty());
///
/// let mut prev = map.insert("x-host", "earth".parse().unwrap()).unwrap();
/// assert_eq!("world", prev);
/// ```
pub fn insert<K>(&mut self, key: K, val: MetadataValue) -> Option<MetadataValue>
where K: IntoMetadataKey
{
key.insert(self, val)
}
/// Inserts a key-value pair into the map.
///
/// If the map did not previously have this key present, then `false` is
/// returned.
///
/// If the map did have this key present, the new value is pushed to the end
/// of the list of values currently associated with the key. The key is not
/// updated, though; this matters for types that can be `==` without being
/// identical.
///
/// # Examples
///
/// ```
/// # use tower_grpc::metadata::*;
/// let mut map = MetadataMap::new();
/// assert!(map.insert("x-host", "world".parse().unwrap()).is_none());
/// assert!(!map.is_empty());
///
/// map.append("x-host", "earth".parse().unwrap());
///
/// let values = map.get_all("x-host");
/// let mut i = values.iter();
/// assert_eq!("world", *i.next().unwrap());
/// assert_eq!("earth", *i.next().unwrap());
/// ```
pub fn append<K>(&mut self, key: K, value: MetadataValue) -> bool
where K: IntoMetadataKey
{
key.append(self, value)
}
/// Removes a key from the map, returning the value associated with the key.
///
/// Returns `None` if the map does not contain the key. If there are
/// multiple values associated with the key, then the first one is returned.
/// See `remove_entry_mult` on `OccupiedEntry` for an API that yields all
/// values.
///
/// # Examples
///
/// ```
/// # use tower_grpc::metadata::*;
/// let mut map = MetadataMap::new();
/// map.insert("x-host", "hello.world".parse().unwrap());
///
/// let prev = map.remove("x-host").unwrap();
/// assert_eq!("hello.world", prev);
///
/// assert!(map.remove("x-host").is_none());
/// ```
pub fn remove<K>(&mut self, key: K) -> Option<MetadataValue>
where K: AsMetadataKey
{
key.remove(self)
}
}
// ===== impl Iter =====
impl<'a> Iterator for Iter<'a> {
type Item = (&'a str, &'a MetadataValue);
fn next(&mut self) -> Option<Self::Item> {
self.inner.next().map(|item| {
let (ref name, value) = item;
let item : Self::Item = (
&name.as_str(),
MetadataValue::from_header_value(value)
);
item
})
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
}
unsafe impl<'a> Sync for Iter<'a> {}
unsafe impl<'a> Send for Iter<'a> {}
// ===== impl IterMut =====
impl<'a> Iterator for IterMut<'a> {
type Item = (&'a str, &'a mut MetadataValue);
fn next(&mut self) -> Option<Self::Item> {
self.inner.next().map(|item| {
let (name, value) = item;
let item : Self::Item = (
&name.as_str(),
MetadataValue::from_mut_header_value(value)
);
item
})
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
}
unsafe impl<'a> Sync for IterMut<'a> {}
unsafe impl<'a> Send for IterMut<'a> {}
// ===== impl ValueDrain =====
impl<'a> Iterator for ValueDrain<'a> {
type Item = MetadataValue;
fn next(&mut self) -> Option<Self::Item> {
self.inner.next().map(|value| {
MetadataValue { inner: value }
})
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
}
unsafe impl<'a> Sync for ValueDrain<'a> {}
unsafe impl<'a> Send for ValueDrain<'a> {}
// ===== impl Drain =====
impl<'a> Iterator for Drain<'a> {
type Item = (MetadataKey, ValueDrain<'a>);
fn next(&mut self) -> Option<Self::Item> {
self.inner.next().map(|item| {
let (name, drain) = item;
(MetadataKey { inner: name }, ValueDrain { inner: drain })
})
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
}
unsafe impl<'a> Sync for Drain<'a> {}
unsafe impl<'a> Send for Drain<'a> {}
// ===== impl Keys =====
impl<'a> Iterator for Keys<'a> {
type Item = &'a str;
fn next(&mut self) -> Option<Self::Item> {
self.inner.next().map(|b| b.as_str())
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
}
impl<'a> ExactSizeIterator for Keys<'a> {}
// ===== impl Values ====
impl<'a> Iterator for Values<'a> {
type Item = &'a MetadataValue;
fn next(&mut self) -> Option<Self::Item> {
self.inner.next().map(&MetadataValue::from_header_value)
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
}
// ===== impl Values ====
impl<'a> Iterator for ValuesMut<'a> {
type Item = &'a mut MetadataValue;
fn next(&mut self) -> Option<Self::Item> {
self.inner.next().map(&MetadataValue::from_mut_header_value)
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
}
// ===== impl ValueIter =====
impl<'a> Iterator for ValueIter<'a> {
type Item = &'a MetadataValue;
fn next(&mut self) -> Option<Self::Item> {
self.inner.next().map(&MetadataValue::from_header_value)
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
}
impl<'a> DoubleEndedIterator for ValueIter<'a> {
fn next_back(&mut self) -> Option<Self::Item> {
self.inner.next_back().map(&MetadataValue::from_header_value)
}
}
// ===== impl ValueIterMut =====
impl<'a> Iterator for ValueIterMut<'a> {
type Item = &'a mut MetadataValue;
fn next(&mut self) -> Option<Self::Item> {
self.inner.next().map(&MetadataValue::from_mut_header_value)
}
}
impl<'a> DoubleEndedIterator for ValueIterMut<'a> {
fn next_back(&mut self) -> Option<Self::Item> {
self.inner.next_back().map(&MetadataValue::from_mut_header_value)
}
}
unsafe impl<'a> Sync for ValueIterMut<'a> {}
unsafe impl<'a> Send for ValueIterMut<'a> {}
// ===== impl Entry =====
impl<'a> Entry<'a> {
/// Ensures a value is in the entry by inserting the default if empty.
///
/// Returns a mutable reference to the **first** value in the entry.
///
/// # Examples
///
/// ```
/// # use tower_grpc::metadata::*;
/// let mut map: MetadataMap = MetadataMap::default();
///
/// let keys = &[
/// "content-length",
/// "x-hello",
/// "Content-Length",
/// "x-world",
/// ];
///
/// for &key in keys {
/// let counter = map.entry(key)
/// .expect("valid key names")
/// .or_insert("".parse().unwrap());
/// *counter = format!("{}{}", counter.to_str().unwrap(), "1").parse().unwrap();
/// }
///
/// assert_eq!(map.get("content-length").unwrap(), "11");
/// assert_eq!(map.get("x-hello").unwrap(), "1");
/// ```
pub fn or_insert(self, default: MetadataValue) -> &'a mut MetadataValue {
use self::Entry::*;
match self {
Occupied(e) => e.into_mut(),
Vacant(e) => e.insert(default),
}
}
/// Ensures a value is in the entry by inserting the result of the default
/// function if empty.
///
/// The default function is not called if the entry exists in the map.
/// Returns a mutable reference to the **first** value in the entry.
///
/// # Examples
///
/// Basic usage.
///
/// ```
/// # use tower_grpc::metadata::*;
/// let mut map = MetadataMap::new();
///
/// let res = map.entry("x-hello").unwrap()
/// .or_insert_with(|| "world".parse().unwrap());
///
/// assert_eq!(res, "world");
/// ```
///
/// The default function is not called if the entry exists in the map.
///
/// ```
/// # use tower_grpc::metadata::*;
/// let mut map = MetadataMap::new();
/// map.insert("host", "world".parse().unwrap());
///
/// let res = map.entry("host")
/// .expect("host is a valid string")
/// .or_insert_with(|| unreachable!());
///
///
/// assert_eq!(res, "world");
/// ```
pub fn or_insert_with<F: FnOnce() -> MetadataValue>(self, default: F)
-> &'a mut MetadataValue {
use self::Entry::*;
match self {
Occupied(e) => e.into_mut(),
Vacant(e) => e.insert(default()),
}
}
/// Returns a reference to the entry's key
///
/// # Examples
///
/// ```
/// # use tower_grpc::metadata::*;
/// let mut map = MetadataMap::new();
///
/// assert_eq!(map.entry("x-hello").unwrap().key(), "x-hello");
/// ```
pub fn key(&self) -> &MetadataKey {
use self::Entry::*;
MetadataKey::from_header_name(match *self {
Vacant(ref e) => e.inner.key(),
Occupied(ref e) => e.inner.key(),
})
}
}
// ===== impl VacantEntry =====
impl<'a> VacantEntry<'a> {
/// Returns a reference to the entry's key
///
/// # Examples
///
/// ```
/// # use tower_grpc::metadata::*;
/// let mut map = MetadataMap::new();
///