xref: /tonic/tonic/src/metadata/map.rs (revision 86815d8e)
1 use http::HeaderName;
2 
3 pub(crate) use self::as_encoding_agnostic_metadata_key::AsEncodingAgnosticMetadataKey;
4 pub(crate) use self::as_metadata_key::AsMetadataKey;
5 pub(crate) use self::into_metadata_key::IntoMetadataKey;
6 
7 use super::encoding::{Ascii, Binary, ValueEncoding};
8 use super::key::{InvalidMetadataKey, MetadataKey};
9 use super::value::MetadataValue;
10 
11 use std::marker::PhantomData;
12 
13 /// A set of gRPC custom metadata entries.
14 ///
15 /// # Examples
16 ///
17 /// Basic usage
18 ///
19 /// ```
20 /// # use tonic::metadata::*;
21 /// let mut map = MetadataMap::new();
22 ///
23 /// map.insert("x-host", "example.com".parse().unwrap());
24 /// map.insert("x-number", "123".parse().unwrap());
25 /// map.insert_bin("trace-proto-bin", MetadataValue::from_bytes(b"[binary data]"));
26 ///
27 /// assert!(map.contains_key("x-host"));
28 /// assert!(!map.contains_key("x-location"));
29 ///
30 /// assert_eq!(map.get("x-host").unwrap(), "example.com");
31 ///
32 /// map.remove("x-host");
33 ///
34 /// assert!(!map.contains_key("x-host"));
35 /// ```
36 #[derive(Clone, Debug, Default)]
37 pub struct MetadataMap {
38     headers: http::HeaderMap,
39 }
40 
41 impl AsRef<http::HeaderMap> for MetadataMap {
as_ref(&self) -> &http::HeaderMap42     fn as_ref(&self) -> &http::HeaderMap {
43         &self.headers
44     }
45 }
46 
47 impl AsMut<http::HeaderMap> for MetadataMap {
as_mut(&mut self) -> &mut http::HeaderMap48     fn as_mut(&mut self) -> &mut http::HeaderMap {
49         &mut self.headers
50     }
51 }
52 
53 /// `MetadataMap` entry iterator.
54 ///
55 /// Yields `KeyAndValueRef` values. The same header name may be yielded
56 /// more than once if it has more than one associated value.
57 #[derive(Debug)]
58 pub struct Iter<'a> {
59     inner: http::header::Iter<'a, http::header::HeaderValue>,
60 }
61 
62 /// Reference to a key and an associated value in a `MetadataMap`. It can point
63 /// to either an ascii or a binary ("*-bin") key.
64 #[derive(Debug)]
65 pub enum KeyAndValueRef<'a> {
66     /// An ascii metadata key and value.
67     Ascii(&'a MetadataKey<Ascii>, &'a MetadataValue<Ascii>),
68     /// A binary metadata key and value.
69     Binary(&'a MetadataKey<Binary>, &'a MetadataValue<Binary>),
70 }
71 
72 /// Reference to a key and an associated value in a `MetadataMap`. It can point
73 /// to either an ascii or a binary ("*-bin") key.
74 #[derive(Debug)]
75 pub enum KeyAndMutValueRef<'a> {
76     /// An ascii metadata key and value.
77     Ascii(&'a MetadataKey<Ascii>, &'a mut MetadataValue<Ascii>),
78     /// A binary metadata key and value.
79     Binary(&'a MetadataKey<Binary>, &'a mut MetadataValue<Binary>),
80 }
81 
82 /// `MetadataMap` entry iterator.
83 ///
84 /// Yields `(&MetadataKey, &mut value)` tuples. The same header name may be yielded
85 /// more than once if it has more than one associated value.
86 #[derive(Debug)]
87 pub struct IterMut<'a> {
88     inner: http::header::IterMut<'a, http::header::HeaderValue>,
89 }
90 
91 /// A drain iterator of all values associated with a single metadata key.
92 #[derive(Debug)]
93 pub struct ValueDrain<'a, VE: ValueEncoding> {
94     inner: http::header::ValueDrain<'a, http::header::HeaderValue>,
95     phantom: PhantomData<VE>,
96 }
97 
98 /// An iterator over `MetadataMap` keys.
99 ///
100 /// Yields `KeyRef` values. Each header name is yielded only once, even if it
101 /// has more than one associated value.
102 #[derive(Debug)]
103 pub struct Keys<'a> {
104     inner: http::header::Keys<'a, http::header::HeaderValue>,
105 }
106 
107 /// Reference to a key in a `MetadataMap`. It can point
108 /// to either an ascii or a binary ("*-bin") key.
109 #[derive(Debug)]
110 pub enum KeyRef<'a> {
111     /// An ascii metadata key and value.
112     Ascii(&'a MetadataKey<Ascii>),
113     /// A binary metadata key and value.
114     Binary(&'a MetadataKey<Binary>),
115 }
116 
117 /// `MetadataMap` value iterator.
118 ///
119 /// Yields `ValueRef` values. Each value contained in the `MetadataMap` will be
120 /// yielded.
121 #[derive(Debug)]
122 pub struct Values<'a> {
123     // Need to use http::header::Iter and not http::header::Values to be able
124     // to know if a value is binary or not.
125     inner: http::header::Iter<'a, http::header::HeaderValue>,
126 }
127 
128 /// Reference to a value in a `MetadataMap`. It can point
129 /// to either an ascii or a binary ("*-bin" key) value.
130 #[derive(Debug)]
131 pub enum ValueRef<'a> {
132     /// An ascii metadata key and value.
133     Ascii(&'a MetadataValue<Ascii>),
134     /// A binary metadata key and value.
135     Binary(&'a MetadataValue<Binary>),
136 }
137 
138 /// `MetadataMap` value iterator.
139 ///
140 /// Each value contained in the `MetadataMap` will be yielded.
141 #[derive(Debug)]
142 pub struct ValuesMut<'a> {
143     // Need to use http::header::IterMut and not http::header::ValuesMut to be
144     // able to know if a value is binary or not.
145     inner: http::header::IterMut<'a, http::header::HeaderValue>,
146 }
147 
148 /// Reference to a value in a `MetadataMap`. It can point
149 /// to either an ascii or a binary ("*-bin" key) value.
150 #[derive(Debug)]
151 pub enum ValueRefMut<'a> {
152     /// An ascii metadata key and value.
153     Ascii(&'a mut MetadataValue<Ascii>),
154     /// A binary metadata key and value.
155     Binary(&'a mut MetadataValue<Binary>),
156 }
157 
158 /// An iterator of all values associated with a single metadata key.
159 #[derive(Debug)]
160 pub struct ValueIter<'a, VE: ValueEncoding> {
161     inner: Option<http::header::ValueIter<'a, http::header::HeaderValue>>,
162     phantom: PhantomData<VE>,
163 }
164 
165 /// An iterator of all values associated with a single metadata key.
166 #[derive(Debug)]
167 pub struct ValueIterMut<'a, VE: ValueEncoding> {
168     inner: http::header::ValueIterMut<'a, http::header::HeaderValue>,
169     phantom: PhantomData<VE>,
170 }
171 
172 /// A view to all values stored in a single entry.
173 ///
174 /// This struct is returned by `MetadataMap::get_all` and
175 /// `MetadataMap::get_all_bin`.
176 #[derive(Debug)]
177 pub struct GetAll<'a, VE: ValueEncoding> {
178     inner: Option<http::header::GetAll<'a, http::header::HeaderValue>>,
179     phantom: PhantomData<VE>,
180 }
181 
182 /// A view into a single location in a `MetadataMap`, which may be vacant or
183 /// occupied.
184 #[derive(Debug)]
185 pub enum Entry<'a, VE: ValueEncoding> {
186     /// An occupied entry
187     Occupied(OccupiedEntry<'a, VE>),
188 
189     /// A vacant entry
190     Vacant(VacantEntry<'a, VE>),
191 }
192 
193 /// A view into a single empty location in a `MetadataMap`.
194 ///
195 /// This struct is returned as part of the `Entry` enum.
196 #[derive(Debug)]
197 pub struct VacantEntry<'a, VE: ValueEncoding> {
198     inner: http::header::VacantEntry<'a, http::header::HeaderValue>,
199     phantom: PhantomData<VE>,
200 }
201 
202 /// A view into a single occupied location in a `MetadataMap`.
203 ///
204 /// This struct is returned as part of the `Entry` enum.
205 #[derive(Debug)]
206 pub struct OccupiedEntry<'a, VE: ValueEncoding> {
207     inner: http::header::OccupiedEntry<'a, http::header::HeaderValue>,
208     phantom: PhantomData<VE>,
209 }
210 
211 pub(crate) const GRPC_TIMEOUT_HEADER: &str = "grpc-timeout";
212 
213 // ===== impl MetadataMap =====
214 
215 impl MetadataMap {
216     // Headers reserved by the gRPC protocol.
217     pub(crate) const GRPC_RESERVED_HEADERS: [HeaderName; 6] = [
218         HeaderName::from_static("te"),
219         HeaderName::from_static("user-agent"),
220         HeaderName::from_static("content-type"),
221         HeaderName::from_static("grpc-message"),
222         HeaderName::from_static("grpc-message-type"),
223         HeaderName::from_static("grpc-status"),
224     ];
225 
226     /// Create an empty `MetadataMap`.
227     ///
228     /// The map will be created without any capacity. This function will not
229     /// allocate.
230     ///
231     /// # Examples
232     ///
233     /// ```
234     /// # use tonic::metadata::*;
235     /// let map = MetadataMap::new();
236     ///
237     /// assert!(map.is_empty());
238     /// assert_eq!(0, map.capacity());
239     /// ```
new() -> Self240     pub fn new() -> Self {
241         MetadataMap::with_capacity(0)
242     }
243 
244     /// Convert an HTTP HeaderMap to a MetadataMap
from_headers(headers: http::HeaderMap) -> Self245     pub fn from_headers(headers: http::HeaderMap) -> Self {
246         MetadataMap { headers }
247     }
248 
249     /// Convert a MetadataMap into a HTTP HeaderMap
250     ///
251     /// # Examples
252     ///
253     /// ```
254     /// # use tonic::metadata::*;
255     /// let mut map = MetadataMap::new();
256     /// map.insert("x-host", "example.com".parse().unwrap());
257     ///
258     /// let http_map = map.into_headers();
259     ///
260     /// assert_eq!(http_map.get("x-host").unwrap(), "example.com");
261     /// ```
into_headers(self) -> http::HeaderMap262     pub fn into_headers(self) -> http::HeaderMap {
263         self.headers
264     }
265 
into_sanitized_headers(mut self) -> http::HeaderMap266     pub(crate) fn into_sanitized_headers(mut self) -> http::HeaderMap {
267         for r in &Self::GRPC_RESERVED_HEADERS {
268             self.headers.remove(r);
269         }
270         self.headers
271     }
272 
273     /// Create an empty `MetadataMap` with the specified capacity.
274     ///
275     /// The returned map will allocate internal storage in order to hold about
276     /// `capacity` elements without reallocating. However, this is a "best
277     /// effort" as there are usage patterns that could cause additional
278     /// allocations before `capacity` metadata entries are stored in the map.
279     ///
280     /// More capacity than requested may be allocated.
281     ///
282     /// # Examples
283     ///
284     /// ```
285     /// # use tonic::metadata::*;
286     /// let map: MetadataMap = MetadataMap::with_capacity(10);
287     ///
288     /// assert!(map.is_empty());
289     /// assert!(map.capacity() >= 10);
290     /// ```
with_capacity(capacity: usize) -> MetadataMap291     pub fn with_capacity(capacity: usize) -> MetadataMap {
292         MetadataMap {
293             headers: http::HeaderMap::with_capacity(capacity),
294         }
295     }
296 
297     /// Returns the number of metadata entries (ascii and binary) stored in the
298     /// map.
299     ///
300     /// This number represents the total number of **values** stored in the map.
301     /// This number can be greater than or equal to the number of **keys**
302     /// stored given that a single key may have more than one associated value.
303     ///
304     /// # Examples
305     ///
306     /// ```
307     /// # use tonic::metadata::*;
308     /// let mut map = MetadataMap::new();
309     ///
310     /// assert_eq!(0, map.len());
311     ///
312     /// map.insert("x-host-ip", "127.0.0.1".parse().unwrap());
313     /// map.insert_bin("x-host-name-bin", MetadataValue::from_bytes(b"localhost"));
314     ///
315     /// assert_eq!(2, map.len());
316     ///
317     /// map.append("x-host-ip", "text/html".parse().unwrap());
318     ///
319     /// assert_eq!(3, map.len());
320     /// ```
len(&self) -> usize321     pub fn len(&self) -> usize {
322         self.headers.len()
323     }
324 
325     /// Returns the number of keys (ascii and binary) stored in the map.
326     ///
327     /// This number will be less than or equal to `len()` as each key may have
328     /// more than one associated value.
329     ///
330     /// # Examples
331     ///
332     /// ```
333     /// # use tonic::metadata::*;
334     /// let mut map = MetadataMap::new();
335     ///
336     /// assert_eq!(0, map.keys_len());
337     ///
338     /// map.insert("x-host-ip", "127.0.0.1".parse().unwrap());
339     /// map.insert_bin("x-host-name-bin", MetadataValue::from_bytes(b"localhost"));
340     ///
341     /// assert_eq!(2, map.keys_len());
342     ///
343     /// map.append("x-host-ip", "text/html".parse().unwrap());
344     ///
345     /// assert_eq!(2, map.keys_len());
346     /// ```
keys_len(&self) -> usize347     pub fn keys_len(&self) -> usize {
348         self.headers.keys_len()
349     }
350 
351     /// Returns true if the map contains no elements.
352     ///
353     /// # Examples
354     ///
355     /// ```
356     /// # use tonic::metadata::*;
357     /// let mut map = MetadataMap::new();
358     ///
359     /// assert!(map.is_empty());
360     ///
361     /// map.insert("x-host", "hello.world".parse().unwrap());
362     ///
363     /// assert!(!map.is_empty());
364     /// ```
is_empty(&self) -> bool365     pub fn is_empty(&self) -> bool {
366         self.headers.is_empty()
367     }
368 
369     /// Clears the map, removing all key-value pairs. Keeps the allocated memory
370     /// for reuse.
371     ///
372     /// # Examples
373     ///
374     /// ```
375     /// # use tonic::metadata::*;
376     /// let mut map = MetadataMap::new();
377     /// map.insert("x-host", "hello.world".parse().unwrap());
378     ///
379     /// map.clear();
380     /// assert!(map.is_empty());
381     /// assert!(map.capacity() > 0);
382     /// ```
clear(&mut self)383     pub fn clear(&mut self) {
384         self.headers.clear();
385     }
386 
387     /// Returns the number of custom metadata entries the map can hold without
388     /// reallocating.
389     ///
390     /// This number is an approximation as certain usage patterns could cause
391     /// additional allocations before the returned capacity is filled.
392     ///
393     /// # Examples
394     ///
395     /// ```
396     /// # use tonic::metadata::*;
397     /// let mut map = MetadataMap::new();
398     ///
399     /// assert_eq!(0, map.capacity());
400     ///
401     /// map.insert("x-host", "hello.world".parse().unwrap());
402     /// assert_eq!(6, map.capacity());
403     /// ```
capacity(&self) -> usize404     pub fn capacity(&self) -> usize {
405         self.headers.capacity()
406     }
407 
408     /// Reserves capacity for at least `additional` more custom metadata to be
409     /// inserted into the `MetadataMap`.
410     ///
411     /// The metadata map may reserve more space to avoid frequent reallocations.
412     /// Like with `with_capacity`, this will be a "best effort" to avoid
413     /// allocations until `additional` more custom metadata is inserted. Certain
414     /// usage patterns could cause additional allocations before the number is
415     /// reached.
416     ///
417     /// # Panics
418     ///
419     /// Panics if the new allocation size overflows `usize`.
420     ///
421     /// # Examples
422     ///
423     /// ```
424     /// # use tonic::metadata::*;
425     /// let mut map = MetadataMap::new();
426     /// map.reserve(10);
427     /// # map.insert("x-host", "bar".parse().unwrap());
428     /// ```
reserve(&mut self, additional: usize)429     pub fn reserve(&mut self, additional: usize) {
430         self.headers.reserve(additional);
431     }
432 
433     /// Returns a reference to the value associated with the key. This method
434     /// is for ascii metadata entries (those whose names don't end with
435     /// "-bin"). For binary entries, use get_bin.
436     ///
437     /// If there are multiple values associated with the key, then the first one
438     /// is returned. Use `get_all` to get all values associated with a given
439     /// key. Returns `None` if there are no values associated with the key.
440     ///
441     /// # Examples
442     ///
443     /// ```
444     /// # use tonic::metadata::*;
445     /// let mut map = MetadataMap::new();
446     /// assert!(map.get("x-host").is_none());
447     ///
448     /// map.insert("x-host", "hello".parse().unwrap());
449     /// assert_eq!(map.get("x-host").unwrap(), &"hello");
450     /// assert_eq!(map.get("x-host").unwrap(), &"hello");
451     ///
452     /// map.append("x-host", "world".parse().unwrap());
453     /// assert_eq!(map.get("x-host").unwrap(), &"hello");
454     ///
455     /// // Attempting to read a key of the wrong type fails by not
456     /// // finding anything.
457     /// map.append_bin("host-bin", MetadataValue::from_bytes(b"world"));
458     /// assert!(map.get("host-bin").is_none());
459     /// assert!(map.get("host-bin".to_string()).is_none());
460     /// assert!(map.get(&("host-bin".to_string())).is_none());
461     ///
462     /// // Attempting to read an invalid key string fails by not
463     /// // finding anything.
464     /// assert!(map.get("host{}bin").is_none());
465     /// assert!(map.get("host{}bin".to_string()).is_none());
466     /// assert!(map.get(&("host{}bin".to_string())).is_none());
467     /// ```
get<K>(&self, key: K) -> Option<&MetadataValue<Ascii>> where K: AsMetadataKey<Ascii>,468     pub fn get<K>(&self, key: K) -> Option<&MetadataValue<Ascii>>
469     where
470         K: AsMetadataKey<Ascii>,
471     {
472         key.get(self)
473     }
474 
475     /// Like get, but for Binary keys (for example "trace-proto-bin").
476     ///
477     /// # Examples
478     ///
479     /// ```
480     /// # use tonic::metadata::*;
481     /// let mut map = MetadataMap::new();
482     /// assert!(map.get_bin("trace-proto-bin").is_none());
483     ///
484     /// map.insert_bin("trace-proto-bin", MetadataValue::from_bytes(b"hello"));
485     /// assert_eq!(map.get_bin("trace-proto-bin").unwrap(), &"hello");
486     /// assert_eq!(map.get_bin("trace-proto-bin").unwrap(), &"hello");
487     ///
488     /// map.append_bin("trace-proto-bin", MetadataValue::from_bytes(b"world"));
489     /// assert_eq!(map.get_bin("trace-proto-bin").unwrap(), &"hello");
490     ///
491     /// // Attempting to read a key of the wrong type fails by not
492     /// // finding anything.
493     /// map.append("host", "world".parse().unwrap());
494     /// assert!(map.get_bin("host").is_none());
495     /// assert!(map.get_bin("host".to_string()).is_none());
496     /// assert!(map.get_bin(&("host".to_string())).is_none());
497     ///
498     /// // Attempting to read an invalid key string fails by not
499     /// // finding anything.
500     /// assert!(map.get_bin("host{}-bin").is_none());
501     /// assert!(map.get_bin("host{}-bin".to_string()).is_none());
502     /// assert!(map.get_bin(&("host{}-bin".to_string())).is_none());
503     /// ```
get_bin<K>(&self, key: K) -> Option<&MetadataValue<Binary>> where K: AsMetadataKey<Binary>,504     pub fn get_bin<K>(&self, key: K) -> Option<&MetadataValue<Binary>>
505     where
506         K: AsMetadataKey<Binary>,
507     {
508         key.get(self)
509     }
510 
511     /// Returns a mutable reference to the value associated with the key. This
512     /// method is for ascii metadata entries (those whose names don't end with
513     /// "-bin"). For binary entries, use get_mut_bin.
514     ///
515     /// If there are multiple values associated with the key, then the first one
516     /// is returned. Use `entry` to get all values associated with a given
517     /// key. Returns `None` if there are no values associated with the key.
518     ///
519     /// # Examples
520     ///
521     /// ```
522     /// # use tonic::metadata::*;
523     /// let mut map = MetadataMap::default();
524     /// map.insert("x-host", "hello".parse().unwrap());
525     /// map.get_mut("x-host").unwrap().set_sensitive(true);
526     ///
527     /// assert!(map.get("x-host").unwrap().is_sensitive());
528     ///
529     /// // Attempting to read a key of the wrong type fails by not
530     /// // finding anything.
531     /// map.append_bin("host-bin", MetadataValue::from_bytes(b"world"));
532     /// assert!(map.get_mut("host-bin").is_none());
533     /// assert!(map.get_mut("host-bin".to_string()).is_none());
534     /// assert!(map.get_mut(&("host-bin".to_string())).is_none());
535     ///
536     /// // Attempting to read an invalid key string fails by not
537     /// // finding anything.
538     /// assert!(map.get_mut("host{}").is_none());
539     /// assert!(map.get_mut("host{}".to_string()).is_none());
540     /// assert!(map.get_mut(&("host{}".to_string())).is_none());
541     /// ```
get_mut<K>(&mut self, key: K) -> Option<&mut MetadataValue<Ascii>> where K: AsMetadataKey<Ascii>,542     pub fn get_mut<K>(&mut self, key: K) -> Option<&mut MetadataValue<Ascii>>
543     where
544         K: AsMetadataKey<Ascii>,
545     {
546         key.get_mut(self)
547     }
548 
549     /// Like get_mut, but for Binary keys (for example "trace-proto-bin").
550     ///
551     /// # Examples
552     ///
553     /// ```
554     /// # use tonic::metadata::*;
555     /// let mut map = MetadataMap::default();
556     /// map.insert_bin("trace-proto-bin", MetadataValue::from_bytes(b"hello"));
557     /// map.get_bin_mut("trace-proto-bin").unwrap().set_sensitive(true);
558     ///
559     /// assert!(map.get_bin("trace-proto-bin").unwrap().is_sensitive());
560     ///
561     /// // Attempting to read a key of the wrong type fails by not
562     /// // finding anything.
563     /// map.append("host", "world".parse().unwrap());
564     /// assert!(map.get_bin_mut("host").is_none());
565     /// assert!(map.get_bin_mut("host".to_string()).is_none());
566     /// assert!(map.get_bin_mut(&("host".to_string())).is_none());
567     ///
568     /// // Attempting to read an invalid key string fails by not
569     /// // finding anything.
570     /// assert!(map.get_bin_mut("host{}-bin").is_none());
571     /// assert!(map.get_bin_mut("host{}-bin".to_string()).is_none());
572     /// assert!(map.get_bin_mut(&("host{}-bin".to_string())).is_none());
573     /// ```
get_bin_mut<K>(&mut self, key: K) -> Option<&mut MetadataValue<Binary>> where K: AsMetadataKey<Binary>,574     pub fn get_bin_mut<K>(&mut self, key: K) -> Option<&mut MetadataValue<Binary>>
575     where
576         K: AsMetadataKey<Binary>,
577     {
578         key.get_mut(self)
579     }
580 
581     /// Returns a view of all values associated with a key. This method is for
582     /// ascii metadata entries (those whose names don't end with "-bin"). For
583     /// binary entries, use get_all_bin.
584     ///
585     /// The returned view does not incur any allocations and allows iterating
586     /// the values associated with the key.  See [`GetAll`] for more details.
587     /// Returns `None` if there are no values associated with the key.
588     ///
589     /// [`GetAll`]: struct.GetAll.html
590     ///
591     /// # Examples
592     ///
593     /// ```
594     /// # use tonic::metadata::*;
595     /// let mut map = MetadataMap::new();
596     ///
597     /// map.insert("x-host", "hello".parse().unwrap());
598     /// map.append("x-host", "goodbye".parse().unwrap());
599     ///
600     /// {
601     ///     let view = map.get_all("x-host");
602     ///
603     ///     let mut iter = view.iter();
604     ///     assert_eq!(&"hello", iter.next().unwrap());
605     ///     assert_eq!(&"goodbye", iter.next().unwrap());
606     ///     assert!(iter.next().is_none());
607     /// }
608     ///
609     /// // Attempting to read a key of the wrong type fails by not
610     /// // finding anything.
611     /// map.append_bin("host-bin", MetadataValue::from_bytes(b"world"));
612     /// assert!(map.get_all("host-bin").iter().next().is_none());
613     /// assert!(map.get_all("host-bin".to_string()).iter().next().is_none());
614     /// assert!(map.get_all(&("host-bin".to_string())).iter().next().is_none());
615     ///
616     /// // Attempting to read an invalid key string fails by not
617     /// // finding anything.
618     /// assert!(map.get_all("host{}").iter().next().is_none());
619     /// assert!(map.get_all("host{}".to_string()).iter().next().is_none());
620     /// assert!(map.get_all(&("host{}".to_string())).iter().next().is_none());
621     /// ```
get_all<K>(&self, key: K) -> GetAll<'_, Ascii> where K: AsMetadataKey<Ascii>,622     pub fn get_all<K>(&self, key: K) -> GetAll<'_, Ascii>
623     where
624         K: AsMetadataKey<Ascii>,
625     {
626         GetAll {
627             inner: key.get_all(self),
628             phantom: PhantomData,
629         }
630     }
631 
632     /// Like get_all, but for Binary keys (for example "trace-proto-bin").
633     ///
634     /// # Examples
635     ///
636     /// ```
637     /// # use tonic::metadata::*;
638     /// let mut map = MetadataMap::new();
639     ///
640     /// map.insert_bin("trace-proto-bin", MetadataValue::from_bytes(b"hello"));
641     /// map.append_bin("trace-proto-bin", MetadataValue::from_bytes(b"goodbye"));
642     ///
643     /// {
644     ///     let view = map.get_all_bin("trace-proto-bin");
645     ///
646     ///     let mut iter = view.iter();
647     ///     assert_eq!(&"hello", iter.next().unwrap());
648     ///     assert_eq!(&"goodbye", iter.next().unwrap());
649     ///     assert!(iter.next().is_none());
650     /// }
651     ///
652     /// // Attempting to read a key of the wrong type fails by not
653     /// // finding anything.
654     /// map.append("host", "world".parse().unwrap());
655     /// assert!(map.get_all_bin("host").iter().next().is_none());
656     /// assert!(map.get_all_bin("host".to_string()).iter().next().is_none());
657     /// assert!(map.get_all_bin(&("host".to_string())).iter().next().is_none());
658     ///
659     /// // Attempting to read an invalid key string fails by not
660     /// // finding anything.
661     /// assert!(map.get_all_bin("host{}-bin").iter().next().is_none());
662     /// assert!(map.get_all_bin("host{}-bin".to_string()).iter().next().is_none());
663     /// assert!(map.get_all_bin(&("host{}-bin".to_string())).iter().next().is_none());
664     /// ```
get_all_bin<K>(&self, key: K) -> GetAll<'_, Binary> where K: AsMetadataKey<Binary>,665     pub fn get_all_bin<K>(&self, key: K) -> GetAll<'_, Binary>
666     where
667         K: AsMetadataKey<Binary>,
668     {
669         GetAll {
670             inner: key.get_all(self),
671             phantom: PhantomData,
672         }
673     }
674 
675     /// Returns true if the map contains a value for the specified key. This
676     /// method works for both ascii and binary entries.
677     ///
678     /// # Examples
679     ///
680     /// ```
681     /// # use tonic::metadata::*;
682     /// let mut map = MetadataMap::new();
683     /// assert!(!map.contains_key("x-host"));
684     ///
685     /// map.append_bin("host-bin", MetadataValue::from_bytes(b"world"));
686     /// map.insert("x-host", "world".parse().unwrap());
687     ///
688     /// // contains_key works for both Binary and Ascii keys:
689     /// assert!(map.contains_key("x-host"));
690     /// assert!(map.contains_key("host-bin"));
691     ///
692     /// // contains_key returns false for invalid keys:
693     /// assert!(!map.contains_key("x{}host"));
694     /// ```
contains_key<K>(&self, key: K) -> bool where K: AsEncodingAgnosticMetadataKey,695     pub fn contains_key<K>(&self, key: K) -> bool
696     where
697         K: AsEncodingAgnosticMetadataKey,
698     {
699         key.contains_key(self)
700     }
701 
702     /// An iterator visiting all key-value pairs (both ascii and binary).
703     ///
704     /// The iteration order is arbitrary, but consistent across platforms for
705     /// the same crate version. Each key will be yielded once per associated
706     /// value. So, if a key has 3 associated values, it will be yielded 3 times.
707     ///
708     /// # Examples
709     ///
710     /// ```
711     /// # use tonic::metadata::*;
712     /// let mut map = MetadataMap::new();
713     ///
714     /// map.insert("x-word", "hello".parse().unwrap());
715     /// map.append("x-word", "goodbye".parse().unwrap());
716     /// map.insert("x-number", "123".parse().unwrap());
717     ///
718     /// for key_and_value in map.iter() {
719     ///     match key_and_value {
720     ///         KeyAndValueRef::Ascii(ref key, ref value) =>
721     ///             println!("Ascii: {:?}: {:?}", key, value),
722     ///         KeyAndValueRef::Binary(ref key, ref value) =>
723     ///             println!("Binary: {:?}: {:?}", key, value),
724     ///     }
725     /// }
726     /// ```
iter(&self) -> Iter<'_>727     pub fn iter(&self) -> Iter<'_> {
728         Iter {
729             inner: self.headers.iter(),
730         }
731     }
732 
733     /// An iterator visiting all key-value pairs, with mutable value references.
734     ///
735     /// The iterator order is arbitrary, but consistent across platforms for the
736     /// same crate version. Each key will be yielded once per associated value,
737     /// so if a key has 3 associated values, it will be yielded 3 times.
738     ///
739     /// # Examples
740     ///
741     /// ```
742     /// # use tonic::metadata::*;
743     /// let mut map = MetadataMap::new();
744     ///
745     /// map.insert("x-word", "hello".parse().unwrap());
746     /// map.append("x-word", "goodbye".parse().unwrap());
747     /// map.insert("x-number", "123".parse().unwrap());
748     ///
749     /// for key_and_value in map.iter_mut() {
750     ///     match key_and_value {
751     ///         KeyAndMutValueRef::Ascii(key, mut value) =>
752     ///             value.set_sensitive(true),
753     ///         KeyAndMutValueRef::Binary(key, mut value) =>
754     ///             value.set_sensitive(false),
755     ///     }
756     /// }
757     /// ```
iter_mut(&mut self) -> IterMut<'_>758     pub fn iter_mut(&mut self) -> IterMut<'_> {
759         IterMut {
760             inner: self.headers.iter_mut(),
761         }
762     }
763 
764     /// An iterator visiting all keys.
765     ///
766     /// The iteration order is arbitrary, but consistent across platforms for
767     /// the same crate version. Each key will be yielded only once even if it
768     /// has multiple associated values.
769     ///
770     /// # Examples
771     ///
772     /// ```
773     /// # use tonic::metadata::*;
774     /// let mut map = MetadataMap::new();
775     ///
776     /// map.insert("x-word", "hello".parse().unwrap());
777     /// map.append("x-word", "goodbye".parse().unwrap());
778     /// map.insert_bin("x-number-bin", MetadataValue::from_bytes(b"123"));
779     ///
780     /// for key in map.keys() {
781     ///     match key {
782     ///         KeyRef::Ascii(ref key) =>
783     ///             println!("Ascii key: {:?}", key),
784     ///         KeyRef::Binary(ref key) =>
785     ///             println!("Binary key: {:?}", key),
786     ///     }
787     ///     println!("{:?}", key);
788     /// }
789     /// ```
keys(&self) -> Keys<'_>790     pub fn keys(&self) -> Keys<'_> {
791         Keys {
792             inner: self.headers.keys(),
793         }
794     }
795 
796     /// An iterator visiting all values (both ascii and binary).
797     ///
798     /// The iteration order is arbitrary, but consistent across platforms for
799     /// the same crate version.
800     ///
801     /// # Examples
802     ///
803     /// ```
804     /// # use tonic::metadata::*;
805     /// let mut map = MetadataMap::new();
806     ///
807     /// map.insert("x-word", "hello".parse().unwrap());
808     /// map.append("x-word", "goodbye".parse().unwrap());
809     /// map.insert_bin("x-number-bin", MetadataValue::from_bytes(b"123"));
810     ///
811     /// for value in map.values() {
812     ///     match value {
813     ///         ValueRef::Ascii(ref value) =>
814     ///             println!("Ascii value: {:?}", value),
815     ///         ValueRef::Binary(ref value) =>
816     ///             println!("Binary value: {:?}", value),
817     ///     }
818     ///     println!("{:?}", value);
819     /// }
820     /// ```
values(&self) -> Values<'_>821     pub fn values(&self) -> Values<'_> {
822         Values {
823             inner: self.headers.iter(),
824         }
825     }
826 
827     /// An iterator visiting all values mutably.
828     ///
829     /// The iteration order is arbitrary, but consistent across platforms for
830     /// the same crate version.
831     ///
832     /// # Examples
833     ///
834     /// ```
835     /// # use tonic::metadata::*;
836     /// let mut map = MetadataMap::default();
837     ///
838     /// map.insert("x-word", "hello".parse().unwrap());
839     /// map.append("x-word", "goodbye".parse().unwrap());
840     /// map.insert("x-number", "123".parse().unwrap());
841     ///
842     /// for value in map.values_mut() {
843     ///     match value {
844     ///         ValueRefMut::Ascii(mut value) =>
845     ///             value.set_sensitive(true),
846     ///         ValueRefMut::Binary(mut value) =>
847     ///             value.set_sensitive(false),
848     ///     }
849     /// }
850     /// ```
values_mut(&mut self) -> ValuesMut<'_>851     pub fn values_mut(&mut self) -> ValuesMut<'_> {
852         ValuesMut {
853             inner: self.headers.iter_mut(),
854         }
855     }
856 
857     /// Gets the given ascii key's corresponding entry in the map for in-place
858     /// manipulation. For binary keys, use `entry_bin`.
859     ///
860     /// # Examples
861     ///
862     /// ```
863     /// # use tonic::metadata::*;
864     /// let mut map = MetadataMap::default();
865     ///
866     /// let headers = &[
867     ///     "content-length",
868     ///     "x-hello",
869     ///     "Content-Length",
870     ///     "x-world",
871     /// ];
872     ///
873     /// for &header in headers {
874     ///     let counter = map.entry(header).unwrap().or_insert("".parse().unwrap());
875     ///     *counter = format!("{}{}", counter.to_str().unwrap(), "1").parse().unwrap();
876     /// }
877     ///
878     /// assert_eq!(map.get("content-length").unwrap(), "11");
879     /// assert_eq!(map.get("x-hello").unwrap(), "1");
880     ///
881     /// // Gracefully handles parting invalid key strings
882     /// assert!(!map.entry("a{}b").is_ok());
883     ///
884     /// // Attempting to read a key of the wrong type fails by not
885     /// // finding anything.
886     /// map.append_bin("host-bin", MetadataValue::from_bytes(b"world"));
887     /// assert!(!map.entry("host-bin").is_ok());
888     /// assert!(!map.entry("host-bin".to_string()).is_ok());
889     /// assert!(!map.entry(&("host-bin".to_string())).is_ok());
890     ///
891     /// // Attempting to read an invalid key string fails by not
892     /// // finding anything.
893     /// assert!(!map.entry("host{}").is_ok());
894     /// assert!(!map.entry("host{}".to_string()).is_ok());
895     /// assert!(!map.entry(&("host{}".to_string())).is_ok());
896     /// ```
entry<K>(&mut self, key: K) -> Result<Entry<'_, Ascii>, InvalidMetadataKey> where K: AsMetadataKey<Ascii>,897     pub fn entry<K>(&mut self, key: K) -> Result<Entry<'_, Ascii>, InvalidMetadataKey>
898     where
899         K: AsMetadataKey<Ascii>,
900     {
901         self.generic_entry::<Ascii, K>(key)
902     }
903 
904     /// Gets the given Binary key's corresponding entry in the map for in-place
905     /// manipulation.
906     ///
907     /// # Examples
908     ///
909     /// ```
910     /// # use tonic::metadata::*;
911     /// # use std::str;
912     /// let mut map = MetadataMap::default();
913     ///
914     /// let headers = &[
915     ///     "content-length-bin",
916     ///     "x-hello-bin",
917     ///     "Content-Length-bin",
918     ///     "x-world-bin",
919     /// ];
920     ///
921     /// for &header in headers {
922     ///     let counter = map.entry_bin(header).unwrap().or_insert(MetadataValue::from_bytes(b""));
923     ///     *counter = MetadataValue::from_bytes(format!("{}{}", str::from_utf8(counter.to_bytes().unwrap().as_ref()).unwrap(), "1").as_bytes());
924     /// }
925     ///
926     /// assert_eq!(map.get_bin("content-length-bin").unwrap(), "11");
927     /// assert_eq!(map.get_bin("x-hello-bin").unwrap(), "1");
928     ///
929     /// // Attempting to read a key of the wrong type fails by not
930     /// // finding anything.
931     /// map.append("host", "world".parse().unwrap());
932     /// assert!(!map.entry_bin("host").is_ok());
933     /// assert!(!map.entry_bin("host".to_string()).is_ok());
934     /// assert!(!map.entry_bin(&("host".to_string())).is_ok());
935     ///
936     /// // Attempting to read an invalid key string fails by not
937     /// // finding anything.
938     /// assert!(!map.entry_bin("host{}-bin").is_ok());
939     /// assert!(!map.entry_bin("host{}-bin".to_string()).is_ok());
940     /// assert!(!map.entry_bin(&("host{}-bin".to_string())).is_ok());
941     /// ```
entry_bin<K>(&mut self, key: K) -> Result<Entry<'_, Binary>, InvalidMetadataKey> where K: AsMetadataKey<Binary>,942     pub fn entry_bin<K>(&mut self, key: K) -> Result<Entry<'_, Binary>, InvalidMetadataKey>
943     where
944         K: AsMetadataKey<Binary>,
945     {
946         self.generic_entry::<Binary, K>(key)
947     }
948 
generic_entry<VE: ValueEncoding, K>( &mut self, key: K, ) -> Result<Entry<'_, VE>, InvalidMetadataKey> where K: AsMetadataKey<VE>,949     fn generic_entry<VE: ValueEncoding, K>(
950         &mut self,
951         key: K,
952     ) -> Result<Entry<'_, VE>, InvalidMetadataKey>
953     where
954         K: AsMetadataKey<VE>,
955     {
956         match key.entry(self) {
957             Ok(entry) => Ok(match entry {
958                 http::header::Entry::Occupied(e) => Entry::Occupied(OccupiedEntry {
959                     inner: e,
960                     phantom: PhantomData,
961                 }),
962                 http::header::Entry::Vacant(e) => Entry::Vacant(VacantEntry {
963                     inner: e,
964                     phantom: PhantomData,
965                 }),
966             }),
967             Err(err) => Err(err),
968         }
969     }
970 
971     /// Inserts an ascii key-value pair into the map. To insert a binary entry,
972     /// use `insert_bin`.
973     ///
974     /// This method panics when the given key is a string and it cannot be
975     /// converted to a `MetadataKey<Ascii>`.
976     ///
977     /// If the map did not previously have this key present, then `None` is
978     /// returned.
979     ///
980     /// If the map did have this key present, the new value is associated with
981     /// the key and all previous values are removed. **Note** that only a single
982     /// one of the previous values is returned. If there are multiple values
983     /// that have been previously associated with the key, then the first one is
984     /// returned. See `insert_mult` on `OccupiedEntry` for an API that returns
985     /// all values.
986     ///
987     /// The key is not updated, though; this matters for types that can be `==`
988     /// without being identical.
989     ///
990     /// # Examples
991     ///
992     /// ```
993     /// # use tonic::metadata::*;
994     /// let mut map = MetadataMap::new();
995     /// assert!(map.insert("x-host", "world".parse().unwrap()).is_none());
996     /// assert!(!map.is_empty());
997     ///
998     /// let mut prev = map.insert("x-host", "earth".parse().unwrap()).unwrap();
999     /// assert_eq!("world", prev);
1000     /// ```
1001     ///
1002     /// ```should_panic
1003     /// # use tonic::metadata::*;
1004     /// let mut map = MetadataMap::new();
1005     /// // Trying to insert a key that is not valid panics.
1006     /// map.insert("x{}host", "world".parse().unwrap());
1007     /// ```
1008     ///
1009     /// ```should_panic
1010     /// # use tonic::metadata::*;
1011     /// let mut map = MetadataMap::new();
1012     /// // Trying to insert a key that is binary panics (use insert_bin).
1013     /// map.insert("x-host-bin", "world".parse().unwrap());
1014     /// ```
insert<K>(&mut self, key: K, val: MetadataValue<Ascii>) -> Option<MetadataValue<Ascii>> where K: IntoMetadataKey<Ascii>,1015     pub fn insert<K>(&mut self, key: K, val: MetadataValue<Ascii>) -> Option<MetadataValue<Ascii>>
1016     where
1017         K: IntoMetadataKey<Ascii>,
1018     {
1019         key.insert(self, val)
1020     }
1021 
1022     /// Like insert, but for Binary keys (for example "trace-proto-bin").
1023     ///
1024     /// This method panics when the given key is a string and it cannot be
1025     /// converted to a `MetadataKey<Binary>`.
1026     ///
1027     /// # Examples
1028     ///
1029     /// ```
1030     /// # use tonic::metadata::*;
1031     /// let mut map = MetadataMap::new();
1032     /// assert!(map.insert_bin("trace-proto-bin", MetadataValue::from_bytes(b"world")).is_none());
1033     /// assert!(!map.is_empty());
1034     ///
1035     /// let mut prev = map.insert_bin("trace-proto-bin", MetadataValue::from_bytes(b"earth")).unwrap();
1036     /// assert_eq!("world", prev);
1037     /// ```
1038     ///
1039     /// ```should_panic
1040     /// # use tonic::metadata::*;
1041     /// let mut map = MetadataMap::default();
1042     /// // Attempting to add a binary metadata entry with an invalid name
1043     /// map.insert_bin("trace-proto", MetadataValue::from_bytes(b"hello")); // This line panics!
1044     /// ```
1045     ///
1046     /// ```should_panic
1047     /// # use tonic::metadata::*;
1048     /// let mut map = MetadataMap::new();
1049     /// // Trying to insert a key that is not valid panics.
1050     /// map.insert_bin("x{}host-bin", MetadataValue::from_bytes(b"world")); // This line panics!
1051     /// ```
insert_bin<K>( &mut self, key: K, val: MetadataValue<Binary>, ) -> Option<MetadataValue<Binary>> where K: IntoMetadataKey<Binary>,1052     pub fn insert_bin<K>(
1053         &mut self,
1054         key: K,
1055         val: MetadataValue<Binary>,
1056     ) -> Option<MetadataValue<Binary>>
1057     where
1058         K: IntoMetadataKey<Binary>,
1059     {
1060         key.insert(self, val)
1061     }
1062 
1063     /// Inserts an ascii key-value pair into the map. To insert a binary entry,
1064     /// use `append_bin`.
1065     ///
1066     /// This method panics when the given key is a string and it cannot be
1067     /// converted to a `MetadataKey<Ascii>`.
1068     ///
1069     /// If the map did not previously have this key present, then `false` is
1070     /// returned.
1071     ///
1072     /// If the map did have this key present, the new value is pushed to the end
1073     /// of the list of values currently associated with the key. The key is not
1074     /// updated, though; this matters for types that can be `==` without being
1075     /// identical.
1076     ///
1077     /// # Examples
1078     ///
1079     /// ```
1080     /// # use tonic::metadata::*;
1081     /// let mut map = MetadataMap::new();
1082     /// assert!(map.insert("x-host", "world".parse().unwrap()).is_none());
1083     /// assert!(!map.is_empty());
1084     ///
1085     /// map.append("x-host", "earth".parse().unwrap());
1086     ///
1087     /// let values = map.get_all("x-host");
1088     /// let mut i = values.iter();
1089     /// assert_eq!("world", *i.next().unwrap());
1090     /// assert_eq!("earth", *i.next().unwrap());
1091     /// ```
1092     ///
1093     /// ```should_panic
1094     /// # use tonic::metadata::*;
1095     /// let mut map = MetadataMap::new();
1096     /// // Trying to append a key that is not valid panics.
1097     /// map.append("x{}host", "world".parse().unwrap()); // This line panics!
1098     /// ```
1099     ///
1100     /// ```should_panic
1101     /// # use tonic::metadata::*;
1102     /// let mut map = MetadataMap::new();
1103     /// // Trying to append a key that is binary panics (use append_bin).
1104     /// map.append("x-host-bin", "world".parse().unwrap()); // This line panics!
1105     /// ```
append<K>(&mut self, key: K, value: MetadataValue<Ascii>) -> bool where K: IntoMetadataKey<Ascii>,1106     pub fn append<K>(&mut self, key: K, value: MetadataValue<Ascii>) -> bool
1107     where
1108         K: IntoMetadataKey<Ascii>,
1109     {
1110         key.append(self, value)
1111     }
1112 
1113     /// Like append, but for binary keys (for example "trace-proto-bin").
1114     ///
1115     /// This method panics when the given key is a string and it cannot be
1116     /// converted to a `MetadataKey<Binary>`.
1117     ///
1118     /// # Examples
1119     ///
1120     /// ```
1121     /// # use tonic::metadata::*;
1122     /// let mut map = MetadataMap::new();
1123     /// assert!(map.insert_bin("trace-proto-bin", MetadataValue::from_bytes(b"world")).is_none());
1124     /// assert!(!map.is_empty());
1125     ///
1126     /// map.append_bin("trace-proto-bin", MetadataValue::from_bytes(b"earth"));
1127     ///
1128     /// let values = map.get_all_bin("trace-proto-bin");
1129     /// let mut i = values.iter();
1130     /// assert_eq!("world", *i.next().unwrap());
1131     /// assert_eq!("earth", *i.next().unwrap());
1132     /// ```
1133     ///
1134     /// ```should_panic
1135     /// # use tonic::metadata::*;
1136     /// let mut map = MetadataMap::new();
1137     /// // Trying to append a key that is not valid panics.
1138     /// map.append_bin("x{}host-bin", MetadataValue::from_bytes(b"world")); // This line panics!
1139     /// ```
1140     ///
1141     /// ```should_panic
1142     /// # use tonic::metadata::*;
1143     /// let mut map = MetadataMap::new();
1144     /// // Trying to append a key that is ascii panics (use append).
1145     /// map.append_bin("x-host", MetadataValue::from_bytes(b"world")); // This line panics!
1146     /// ```
append_bin<K>(&mut self, key: K, value: MetadataValue<Binary>) -> bool where K: IntoMetadataKey<Binary>,1147     pub fn append_bin<K>(&mut self, key: K, value: MetadataValue<Binary>) -> bool
1148     where
1149         K: IntoMetadataKey<Binary>,
1150     {
1151         key.append(self, value)
1152     }
1153 
1154     /// Removes an ascii key from the map, returning the value associated with
1155     /// the key. To remove a binary key, use `remove_bin`.
1156     ///
1157     /// Returns `None` if the map does not contain the key. If there are
1158     /// multiple values associated with the key, then the first one is returned.
1159     /// See `remove_entry_mult` on `OccupiedEntry` for an API that yields all
1160     /// values.
1161     ///
1162     /// # Examples
1163     ///
1164     /// ```
1165     /// # use tonic::metadata::*;
1166     /// let mut map = MetadataMap::new();
1167     /// map.insert("x-host", "hello.world".parse().unwrap());
1168     ///
1169     /// let prev = map.remove("x-host").unwrap();
1170     /// assert_eq!("hello.world", prev);
1171     ///
1172     /// assert!(map.remove("x-host").is_none());
1173     ///
1174     /// // Attempting to remove a key of the wrong type fails by not
1175     /// // finding anything.
1176     /// map.append_bin("host-bin", MetadataValue::from_bytes(b"world"));
1177     /// assert!(map.remove("host-bin").is_none());
1178     /// assert!(map.remove("host-bin".to_string()).is_none());
1179     /// assert!(map.remove(&("host-bin".to_string())).is_none());
1180     ///
1181     /// // Attempting to remove an invalid key string fails by not
1182     /// // finding anything.
1183     /// assert!(map.remove("host{}").is_none());
1184     /// assert!(map.remove("host{}".to_string()).is_none());
1185     /// assert!(map.remove(&("host{}".to_string())).is_none());
1186     /// ```
remove<K>(&mut self, key: K) -> Option<MetadataValue<Ascii>> where K: AsMetadataKey<Ascii>,1187     pub fn remove<K>(&mut self, key: K) -> Option<MetadataValue<Ascii>>
1188     where
1189         K: AsMetadataKey<Ascii>,
1190     {
1191         key.remove(self)
1192     }
1193 
1194     /// Like remove, but for Binary keys (for example "trace-proto-bin").
1195     ///
1196     /// # Examples
1197     ///
1198     /// ```
1199     /// # use tonic::metadata::*;
1200     /// let mut map = MetadataMap::new();
1201     /// map.insert_bin("trace-proto-bin", MetadataValue::from_bytes(b"hello.world"));
1202     ///
1203     /// let prev = map.remove_bin("trace-proto-bin").unwrap();
1204     /// assert_eq!("hello.world", prev);
1205     ///
1206     /// assert!(map.remove_bin("trace-proto-bin").is_none());
1207     ///
1208     /// // Attempting to remove a key of the wrong type fails by not
1209     /// // finding anything.
1210     /// map.append("host", "world".parse().unwrap());
1211     /// assert!(map.remove_bin("host").is_none());
1212     /// assert!(map.remove_bin("host".to_string()).is_none());
1213     /// assert!(map.remove_bin(&("host".to_string())).is_none());
1214     ///
1215     /// // Attempting to remove an invalid key string fails by not
1216     /// // finding anything.
1217     /// assert!(map.remove_bin("host{}-bin").is_none());
1218     /// assert!(map.remove_bin("host{}-bin".to_string()).is_none());
1219     /// assert!(map.remove_bin(&("host{}-bin".to_string())).is_none());
1220     /// ```
remove_bin<K>(&mut self, key: K) -> Option<MetadataValue<Binary>> where K: AsMetadataKey<Binary>,1221     pub fn remove_bin<K>(&mut self, key: K) -> Option<MetadataValue<Binary>>
1222     where
1223         K: AsMetadataKey<Binary>,
1224     {
1225         key.remove(self)
1226     }
1227 
merge(&mut self, other: MetadataMap)1228     pub(crate) fn merge(&mut self, other: MetadataMap) {
1229         self.headers.extend(other.headers);
1230     }
1231 }
1232 
1233 // ===== impl Iter =====
1234 
1235 impl<'a> Iterator for Iter<'a> {
1236     type Item = KeyAndValueRef<'a>;
1237 
next(&mut self) -> Option<Self::Item>1238     fn next(&mut self) -> Option<Self::Item> {
1239         self.inner.next().map(|item| {
1240             let (name, value) = item;
1241             if Ascii::is_valid_key(name.as_str()) {
1242                 KeyAndValueRef::Ascii(
1243                     MetadataKey::unchecked_from_header_name_ref(name),
1244                     MetadataValue::unchecked_from_header_value_ref(value),
1245                 )
1246             } else {
1247                 KeyAndValueRef::Binary(
1248                     MetadataKey::unchecked_from_header_name_ref(name),
1249                     MetadataValue::unchecked_from_header_value_ref(value),
1250                 )
1251             }
1252         })
1253     }
1254 
size_hint(&self) -> (usize, Option<usize>)1255     fn size_hint(&self) -> (usize, Option<usize>) {
1256         self.inner.size_hint()
1257     }
1258 }
1259 
1260 // ===== impl IterMut =====
1261 
1262 impl<'a> Iterator for IterMut<'a> {
1263     type Item = KeyAndMutValueRef<'a>;
1264 
next(&mut self) -> Option<Self::Item>1265     fn next(&mut self) -> Option<Self::Item> {
1266         self.inner.next().map(|item| {
1267             let (name, value) = item;
1268             if Ascii::is_valid_key(name.as_str()) {
1269                 KeyAndMutValueRef::Ascii(
1270                     MetadataKey::unchecked_from_header_name_ref(name),
1271                     MetadataValue::unchecked_from_mut_header_value_ref(value),
1272                 )
1273             } else {
1274                 KeyAndMutValueRef::Binary(
1275                     MetadataKey::unchecked_from_header_name_ref(name),
1276                     MetadataValue::unchecked_from_mut_header_value_ref(value),
1277                 )
1278             }
1279         })
1280     }
1281 
size_hint(&self) -> (usize, Option<usize>)1282     fn size_hint(&self) -> (usize, Option<usize>) {
1283         self.inner.size_hint()
1284     }
1285 }
1286 
1287 // ===== impl ValueDrain =====
1288 
1289 impl<VE: ValueEncoding> Iterator for ValueDrain<'_, VE> {
1290     type Item = MetadataValue<VE>;
1291 
next(&mut self) -> Option<Self::Item>1292     fn next(&mut self) -> Option<Self::Item> {
1293         self.inner
1294             .next()
1295             .map(MetadataValue::unchecked_from_header_value)
1296     }
1297 
size_hint(&self) -> (usize, Option<usize>)1298     fn size_hint(&self) -> (usize, Option<usize>) {
1299         self.inner.size_hint()
1300     }
1301 }
1302 
1303 // ===== impl Keys =====
1304 
1305 impl<'a> Iterator for Keys<'a> {
1306     type Item = KeyRef<'a>;
1307 
next(&mut self) -> Option<Self::Item>1308     fn next(&mut self) -> Option<Self::Item> {
1309         self.inner.next().map(|key| {
1310             if Ascii::is_valid_key(key.as_str()) {
1311                 KeyRef::Ascii(MetadataKey::unchecked_from_header_name_ref(key))
1312             } else {
1313                 KeyRef::Binary(MetadataKey::unchecked_from_header_name_ref(key))
1314             }
1315         })
1316     }
1317 
size_hint(&self) -> (usize, Option<usize>)1318     fn size_hint(&self) -> (usize, Option<usize>) {
1319         self.inner.size_hint()
1320     }
1321 }
1322 
1323 impl ExactSizeIterator for Keys<'_> {}
1324 
1325 // ===== impl Values ====
1326 
1327 impl<'a> Iterator for Values<'a> {
1328     type Item = ValueRef<'a>;
1329 
next(&mut self) -> Option<Self::Item>1330     fn next(&mut self) -> Option<Self::Item> {
1331         self.inner.next().map(|item| {
1332             let (name, value) = item;
1333             if Ascii::is_valid_key(name.as_str()) {
1334                 ValueRef::Ascii(MetadataValue::unchecked_from_header_value_ref(value))
1335             } else {
1336                 ValueRef::Binary(MetadataValue::unchecked_from_header_value_ref(value))
1337             }
1338         })
1339     }
1340 
size_hint(&self) -> (usize, Option<usize>)1341     fn size_hint(&self) -> (usize, Option<usize>) {
1342         self.inner.size_hint()
1343     }
1344 }
1345 
1346 // ===== impl Values ====
1347 
1348 impl<'a> Iterator for ValuesMut<'a> {
1349     type Item = ValueRefMut<'a>;
1350 
next(&mut self) -> Option<Self::Item>1351     fn next(&mut self) -> Option<Self::Item> {
1352         self.inner.next().map(|item| {
1353             let (name, value) = item;
1354             if Ascii::is_valid_key(name.as_str()) {
1355                 ValueRefMut::Ascii(MetadataValue::unchecked_from_mut_header_value_ref(value))
1356             } else {
1357                 ValueRefMut::Binary(MetadataValue::unchecked_from_mut_header_value_ref(value))
1358             }
1359         })
1360     }
1361 
size_hint(&self) -> (usize, Option<usize>)1362     fn size_hint(&self) -> (usize, Option<usize>) {
1363         self.inner.size_hint()
1364     }
1365 }
1366 
1367 // ===== impl ValueIter =====
1368 
1369 impl<'a, VE: ValueEncoding> Iterator for ValueIter<'a, VE>
1370 where
1371     VE: 'a,
1372 {
1373     type Item = &'a MetadataValue<VE>;
1374 
next(&mut self) -> Option<Self::Item>1375     fn next(&mut self) -> Option<Self::Item> {
1376         match self.inner {
1377             Some(ref mut inner) => inner
1378                 .next()
1379                 .map(MetadataValue::unchecked_from_header_value_ref),
1380             None => None,
1381         }
1382     }
1383 
size_hint(&self) -> (usize, Option<usize>)1384     fn size_hint(&self) -> (usize, Option<usize>) {
1385         match self.inner {
1386             Some(ref inner) => inner.size_hint(),
1387             None => (0, Some(0)),
1388         }
1389     }
1390 }
1391 
1392 impl<'a, VE: ValueEncoding> DoubleEndedIterator for ValueIter<'a, VE>
1393 where
1394     VE: 'a,
1395 {
next_back(&mut self) -> Option<Self::Item>1396     fn next_back(&mut self) -> Option<Self::Item> {
1397         match self.inner {
1398             Some(ref mut inner) => inner
1399                 .next_back()
1400                 .map(MetadataValue::unchecked_from_header_value_ref),
1401             None => None,
1402         }
1403     }
1404 }
1405 
1406 // ===== impl ValueIterMut =====
1407 
1408 impl<'a, VE: ValueEncoding> Iterator for ValueIterMut<'a, VE>
1409 where
1410     VE: 'a,
1411 {
1412     type Item = &'a mut MetadataValue<VE>;
1413 
next(&mut self) -> Option<Self::Item>1414     fn next(&mut self) -> Option<Self::Item> {
1415         self.inner
1416             .next()
1417             .map(MetadataValue::unchecked_from_mut_header_value_ref)
1418     }
1419 }
1420 
1421 impl<'a, VE: ValueEncoding> DoubleEndedIterator for ValueIterMut<'a, VE>
1422 where
1423     VE: 'a,
1424 {
next_back(&mut self) -> Option<Self::Item>1425     fn next_back(&mut self) -> Option<Self::Item> {
1426         self.inner
1427             .next_back()
1428             .map(MetadataValue::unchecked_from_mut_header_value_ref)
1429     }
1430 }
1431 
1432 // ===== impl Entry =====
1433 
1434 impl<'a, VE: ValueEncoding> Entry<'a, VE> {
1435     /// Ensures a value is in the entry by inserting the default if empty.
1436     ///
1437     /// Returns a mutable reference to the **first** value in the entry.
1438     ///
1439     /// # Examples
1440     ///
1441     /// ```
1442     /// # use tonic::metadata::*;
1443     /// let mut map: MetadataMap = MetadataMap::default();
1444     ///
1445     /// let keys = &[
1446     ///     "content-length",
1447     ///     "x-hello",
1448     ///     "Content-Length",
1449     ///     "x-world",
1450     /// ];
1451     ///
1452     /// for &key in keys {
1453     ///     let counter = map.entry(key)
1454     ///         .expect("valid key names")
1455     ///         .or_insert("".parse().unwrap());
1456     ///     *counter = format!("{}{}", counter.to_str().unwrap(), "1").parse().unwrap();
1457     /// }
1458     ///
1459     /// assert_eq!(map.get("content-length").unwrap(), "11");
1460     /// assert_eq!(map.get("x-hello").unwrap(), "1");
1461     /// ```
or_insert(self, default: MetadataValue<VE>) -> &'a mut MetadataValue<VE>1462     pub fn or_insert(self, default: MetadataValue<VE>) -> &'a mut MetadataValue<VE> {
1463         use self::Entry::*;
1464 
1465         match self {
1466             Occupied(e) => e.into_mut(),
1467             Vacant(e) => e.insert(default),
1468         }
1469     }
1470 
1471     /// Ensures a value is in the entry by inserting the result of the default
1472     /// function if empty.
1473     ///
1474     /// The default function is not called if the entry exists in the map.
1475     /// Returns a mutable reference to the **first** value in the entry.
1476     ///
1477     /// # Examples
1478     ///
1479     /// Basic usage.
1480     ///
1481     /// ```
1482     /// # use tonic::metadata::*;
1483     /// let mut map = MetadataMap::new();
1484     ///
1485     /// let res = map.entry("x-hello").unwrap()
1486     ///     .or_insert_with(|| "world".parse().unwrap());
1487     ///
1488     /// assert_eq!(res, "world");
1489     /// ```
1490     ///
1491     /// The default function is not called if the entry exists in the map.
1492     ///
1493     /// ```
1494     /// # use tonic::metadata::*;
1495     /// let mut map = MetadataMap::new();
1496     /// map.insert("host", "world".parse().unwrap());
1497     ///
1498     /// let res = map.entry("host")
1499     ///     .expect("host is a valid string")
1500     ///     .or_insert_with(|| unreachable!());
1501     ///
1502     ///
1503     /// assert_eq!(res, "world");
1504     /// ```
or_insert_with<F: FnOnce() -> MetadataValue<VE>>( self, default: F, ) -> &'a mut MetadataValue<VE>1505     pub fn or_insert_with<F: FnOnce() -> MetadataValue<VE>>(
1506         self,
1507         default: F,
1508     ) -> &'a mut MetadataValue<VE> {
1509         use self::Entry::*;
1510 
1511         match self {
1512             Occupied(e) => e.into_mut(),
1513             Vacant(e) => e.insert(default()),
1514         }
1515     }
1516 
1517     /// Returns a reference to the entry's key
1518     ///
1519     /// # Examples
1520     ///
1521     /// ```
1522     /// # use tonic::metadata::*;
1523     /// let mut map = MetadataMap::new();
1524     ///
1525     /// assert_eq!(map.entry("x-hello").unwrap().key(), "x-hello");
1526     /// ```
key(&self) -> &MetadataKey<VE>1527     pub fn key(&self) -> &MetadataKey<VE> {
1528         use self::Entry::*;
1529 
1530         MetadataKey::unchecked_from_header_name_ref(match *self {
1531             Vacant(ref e) => e.inner.key(),
1532             Occupied(ref e) => e.inner.key(),
1533         })
1534     }
1535 }
1536 
1537 // ===== impl VacantEntry =====
1538 
1539 impl<'a, VE: ValueEncoding> VacantEntry<'a, VE> {
1540     /// Returns a reference to the entry's key
1541     ///
1542     /// # Examples
1543     ///
1544     /// ```
1545     /// # use tonic::metadata::*;
1546     /// let mut map = MetadataMap::new();
1547     ///
1548     /// assert_eq!(map.entry("x-hello").unwrap().key(), "x-hello");
1549     /// ```
key(&self) -> &MetadataKey<VE>1550     pub fn key(&self) -> &MetadataKey<VE> {
1551         MetadataKey::unchecked_from_header_name_ref(self.inner.key())
1552     }
1553 
1554     /// Take ownership of the key
1555     ///
1556     /// # Examples
1557     ///
1558     /// ```
1559     /// # use tonic::metadata::*;
1560     /// let mut map = MetadataMap::new();
1561     ///
1562     /// if let Entry::Vacant(v) = map.entry("x-hello").unwrap() {
1563     ///     assert_eq!(v.into_key().as_str(), "x-hello");
1564     /// }
1565     /// ```
into_key(self) -> MetadataKey<VE>1566     pub fn into_key(self) -> MetadataKey<VE> {
1567         MetadataKey::unchecked_from_header_name(self.inner.into_key())
1568     }
1569 
1570     /// Insert the value into the entry.
1571     ///
1572     /// The value will be associated with this entry's key. A mutable reference
1573     /// to the inserted value will be returned.
1574     ///
1575     /// # Examples
1576     ///
1577     /// ```
1578     /// # use tonic::metadata::*;
1579     /// let mut map = MetadataMap::new();
1580     ///
1581     /// if let Entry::Vacant(v) = map.entry("x-hello").unwrap() {
1582     ///     v.insert("world".parse().unwrap());
1583     /// }
1584     ///
1585     /// assert_eq!(map.get("x-hello").unwrap(), "world");
1586     /// ```
insert(self, value: MetadataValue<VE>) -> &'a mut MetadataValue<VE>1587     pub fn insert(self, value: MetadataValue<VE>) -> &'a mut MetadataValue<VE> {
1588         MetadataValue::unchecked_from_mut_header_value_ref(self.inner.insert(value.inner))
1589     }
1590 
1591     /// Insert the value into the entry.
1592     ///
1593     /// The value will be associated with this entry's key. The new
1594     /// `OccupiedEntry` is returned, allowing for further manipulation.
1595     ///
1596     /// # Examples
1597     ///
1598     /// ```
1599     /// # use tonic::metadata::*;
1600     /// let mut map = MetadataMap::new();
1601     ///
1602     /// if let Entry::Vacant(v) = map.entry("x-hello").unwrap() {
1603     ///     let mut e = v.insert_entry("world".parse().unwrap());
1604     ///     e.insert("world2".parse().unwrap());
1605     /// }
1606     ///
1607     /// assert_eq!(map.get("x-hello").unwrap(), "world2");
1608     /// ```
insert_entry(self, value: MetadataValue<VE>) -> OccupiedEntry<'a, Ascii>1609     pub fn insert_entry(self, value: MetadataValue<VE>) -> OccupiedEntry<'a, Ascii> {
1610         OccupiedEntry {
1611             inner: self.inner.insert_entry(value.inner),
1612             phantom: PhantomData,
1613         }
1614     }
1615 }
1616 
1617 // ===== impl OccupiedEntry =====
1618 
1619 impl<'a, VE: ValueEncoding> OccupiedEntry<'a, VE> {
1620     /// Returns a reference to the entry's key.
1621     ///
1622     /// # Examples
1623     ///
1624     /// ```
1625     /// # use tonic::metadata::*;
1626     /// let mut map = MetadataMap::new();
1627     /// map.insert("host", "world".parse().unwrap());
1628     ///
1629     /// if let Entry::Occupied(e) = map.entry("host").unwrap() {
1630     ///     assert_eq!("host", e.key());
1631     /// }
1632     /// ```
key(&self) -> &MetadataKey<VE>1633     pub fn key(&self) -> &MetadataKey<VE> {
1634         MetadataKey::unchecked_from_header_name_ref(self.inner.key())
1635     }
1636 
1637     /// Get a reference to the first value in the entry.
1638     ///
1639     /// Values are stored in insertion order.
1640     ///
1641     /// # Panics
1642     ///
1643     /// `get` panics if there are no values associated with the entry.
1644     ///
1645     /// # Examples
1646     ///
1647     /// ```
1648     /// # use tonic::metadata::*;
1649     /// let mut map = MetadataMap::new();
1650     /// map.insert("host", "hello.world".parse().unwrap());
1651     ///
1652     /// if let Entry::Occupied(mut e) = map.entry("host").unwrap() {
1653     ///     assert_eq!(e.get(), &"hello.world");
1654     ///
1655     ///     e.append("hello.earth".parse().unwrap());
1656     ///
1657     ///     assert_eq!(e.get(), &"hello.world");
1658     /// }
1659     /// ```
get(&self) -> &MetadataValue<VE>1660     pub fn get(&self) -> &MetadataValue<VE> {
1661         MetadataValue::unchecked_from_header_value_ref(self.inner.get())
1662     }
1663 
1664     /// Get a mutable reference to the first value in the entry.
1665     ///
1666     /// Values are stored in insertion order.
1667     ///
1668     /// # Panics
1669     ///
1670     /// `get_mut` panics if there are no values associated with the entry.
1671     ///
1672     /// # Examples
1673     ///
1674     /// ```
1675     /// # use tonic::metadata::*;
1676     /// let mut map = MetadataMap::default();
1677     /// map.insert("host", "hello.world".parse().unwrap());
1678     ///
1679     /// if let Entry::Occupied(mut e) = map.entry("host").unwrap() {
1680     ///     e.get_mut().set_sensitive(true);
1681     ///     assert_eq!(e.get(), &"hello.world");
1682     ///     assert!(e.get().is_sensitive());
1683     /// }
1684     /// ```
get_mut(&mut self) -> &mut MetadataValue<VE>1685     pub fn get_mut(&mut self) -> &mut MetadataValue<VE> {
1686         MetadataValue::unchecked_from_mut_header_value_ref(self.inner.get_mut())
1687     }
1688 
1689     /// Converts the `OccupiedEntry` into a mutable reference to the **first**
1690     /// value.
1691     ///
1692     /// The lifetime of the returned reference is bound to the original map.
1693     ///
1694     /// # Panics
1695     ///
1696     /// `into_mut` panics if there are no values associated with the entry.
1697     ///
1698     /// # Examples
1699     ///
1700     /// ```
1701     /// # use tonic::metadata::*;
1702     /// let mut map = MetadataMap::default();
1703     /// map.insert("host", "hello.world".parse().unwrap());
1704     /// map.append("host", "hello.earth".parse().unwrap());
1705     ///
1706     /// if let Entry::Occupied(e) = map.entry("host").unwrap() {
1707     ///     e.into_mut().set_sensitive(true);
1708     /// }
1709     ///
1710     /// assert!(map.get("host").unwrap().is_sensitive());
1711     /// ```
into_mut(self) -> &'a mut MetadataValue<VE>1712     pub fn into_mut(self) -> &'a mut MetadataValue<VE> {
1713         MetadataValue::unchecked_from_mut_header_value_ref(self.inner.into_mut())
1714     }
1715 
1716     /// Sets the value of the entry.
1717     ///
1718     /// All previous values associated with the entry are removed and the first
1719     /// one is returned. See `insert_mult` for an API that returns all values.
1720     ///
1721     /// # Examples
1722     ///
1723     /// ```
1724     /// # use tonic::metadata::*;
1725     /// let mut map = MetadataMap::new();
1726     /// map.insert("host", "hello.world".parse().unwrap());
1727     ///
1728     /// if let Entry::Occupied(mut e) = map.entry("host").unwrap() {
1729     ///     let mut prev = e.insert("earth".parse().unwrap());
1730     ///     assert_eq!("hello.world", prev);
1731     /// }
1732     ///
1733     /// assert_eq!("earth", map.get("host").unwrap());
1734     /// ```
insert(&mut self, value: MetadataValue<VE>) -> MetadataValue<VE>1735     pub fn insert(&mut self, value: MetadataValue<VE>) -> MetadataValue<VE> {
1736         let header_value = self.inner.insert(value.inner);
1737         MetadataValue::unchecked_from_header_value(header_value)
1738     }
1739 
1740     /// Sets the value of the entry.
1741     ///
1742     /// This function does the same as `insert` except it returns an iterator
1743     /// that yields all values previously associated with the key.
1744     ///
1745     /// # Examples
1746     ///
1747     /// ```
1748     /// # use tonic::metadata::*;
1749     /// let mut map = MetadataMap::new();
1750     /// map.insert("host", "world".parse().unwrap());
1751     /// map.append("host", "world2".parse().unwrap());
1752     ///
1753     /// if let Entry::Occupied(mut e) = map.entry("host").unwrap() {
1754     ///     let mut prev = e.insert_mult("earth".parse().unwrap());
1755     ///     assert_eq!("world", prev.next().unwrap());
1756     ///     assert_eq!("world2", prev.next().unwrap());
1757     ///     assert!(prev.next().is_none());
1758     /// }
1759     ///
1760     /// assert_eq!("earth", map.get("host").unwrap());
1761     /// ```
insert_mult(&mut self, value: MetadataValue<VE>) -> ValueDrain<'_, VE>1762     pub fn insert_mult(&mut self, value: MetadataValue<VE>) -> ValueDrain<'_, VE> {
1763         ValueDrain {
1764             inner: self.inner.insert_mult(value.inner),
1765             phantom: PhantomData,
1766         }
1767     }
1768 
1769     /// Insert the value into the entry.
1770     ///
1771     /// The new value is appended to the end of the entry's value list. All
1772     /// previous values associated with the entry are retained.
1773     ///
1774     /// # Examples
1775     ///
1776     /// ```
1777     /// # use tonic::metadata::*;
1778     /// let mut map = MetadataMap::new();
1779     /// map.insert("host", "world".parse().unwrap());
1780     ///
1781     /// if let Entry::Occupied(mut e) = map.entry("host").unwrap() {
1782     ///     e.append("earth".parse().unwrap());
1783     /// }
1784     ///
1785     /// let values = map.get_all("host");
1786     /// let mut i = values.iter();
1787     /// assert_eq!("world", *i.next().unwrap());
1788     /// assert_eq!("earth", *i.next().unwrap());
1789     /// ```
append(&mut self, value: MetadataValue<VE>)1790     pub fn append(&mut self, value: MetadataValue<VE>) {
1791         self.inner.append(value.inner)
1792     }
1793 
1794     /// Remove the entry from the map.
1795     ///
1796     /// All values associated with the entry are removed and the first one is
1797     /// returned. See `remove_entry_mult` for an API that returns all values.
1798     ///
1799     /// # Examples
1800     ///
1801     /// ```
1802     /// # use tonic::metadata::*;
1803     /// let mut map = MetadataMap::new();
1804     /// map.insert("host", "world".parse().unwrap());
1805     ///
1806     /// if let Entry::Occupied(e) = map.entry("host").unwrap() {
1807     ///     let mut prev = e.remove();
1808     ///     assert_eq!("world", prev);
1809     /// }
1810     ///
1811     /// assert!(!map.contains_key("host"));
1812     /// ```
remove(self) -> MetadataValue<VE>1813     pub fn remove(self) -> MetadataValue<VE> {
1814         let value = self.inner.remove();
1815         MetadataValue::unchecked_from_header_value(value)
1816     }
1817 
1818     /// Remove the entry from the map.
1819     ///
1820     /// The key and all values associated with the entry are removed and the
1821     /// first one is returned. See `remove_entry_mult` for an API that returns
1822     /// all values.
1823     ///
1824     /// # Examples
1825     ///
1826     /// ```
1827     /// # use tonic::metadata::*;
1828     /// let mut map = MetadataMap::new();
1829     /// map.insert("host", "world".parse().unwrap());
1830     ///
1831     /// if let Entry::Occupied(e) = map.entry("host").unwrap() {
1832     ///     let (key, mut prev) = e.remove_entry();
1833     ///     assert_eq!("host", key.as_str());
1834     ///     assert_eq!("world", prev);
1835     /// }
1836     ///
1837     /// assert!(!map.contains_key("host"));
1838     /// ```
remove_entry(self) -> (MetadataKey<VE>, MetadataValue<VE>)1839     pub fn remove_entry(self) -> (MetadataKey<VE>, MetadataValue<VE>) {
1840         let (name, value) = self.inner.remove_entry();
1841         (
1842             MetadataKey::unchecked_from_header_name(name),
1843             MetadataValue::unchecked_from_header_value(value),
1844         )
1845     }
1846 
1847     /// Remove the entry from the map.
1848     ///
1849     /// The key and all values associated with the entry are removed and
1850     /// returned.
remove_entry_mult(self) -> (MetadataKey<VE>, ValueDrain<'a, VE>)1851     pub fn remove_entry_mult(self) -> (MetadataKey<VE>, ValueDrain<'a, VE>) {
1852         let (name, value_drain) = self.inner.remove_entry_mult();
1853         (
1854             MetadataKey::unchecked_from_header_name(name),
1855             ValueDrain {
1856                 inner: value_drain,
1857                 phantom: PhantomData,
1858             },
1859         )
1860     }
1861 
1862     /// Returns an iterator visiting all values associated with the entry.
1863     ///
1864     /// Values are iterated in insertion order.
1865     ///
1866     /// # Examples
1867     ///
1868     /// ```
1869     /// # use tonic::metadata::*;
1870     /// let mut map = MetadataMap::new();
1871     /// map.insert("host", "world".parse().unwrap());
1872     /// map.append("host", "earth".parse().unwrap());
1873     ///
1874     /// if let Entry::Occupied(e) = map.entry("host").unwrap() {
1875     ///     let mut iter = e.iter();
1876     ///     assert_eq!(&"world", iter.next().unwrap());
1877     ///     assert_eq!(&"earth", iter.next().unwrap());
1878     ///     assert!(iter.next().is_none());
1879     /// }
1880     /// ```
iter(&self) -> ValueIter<'_, VE>1881     pub fn iter(&self) -> ValueIter<'_, VE> {
1882         ValueIter {
1883             inner: Some(self.inner.iter()),
1884             phantom: PhantomData,
1885         }
1886     }
1887 
1888     /// Returns an iterator mutably visiting all values associated with the
1889     /// entry.
1890     ///
1891     /// Values are iterated in insertion order.
1892     ///
1893     /// # Examples
1894     ///
1895     /// ```
1896     /// # use tonic::metadata::*;
1897     /// let mut map = MetadataMap::default();
1898     /// map.insert("host", "world".parse().unwrap());
1899     /// map.append("host", "earth".parse().unwrap());
1900     ///
1901     /// if let Entry::Occupied(mut e) = map.entry("host").unwrap() {
1902     ///     for e in e.iter_mut() {
1903     ///         e.set_sensitive(true);
1904     ///     }
1905     /// }
1906     ///
1907     /// let mut values = map.get_all("host");
1908     /// let mut i = values.iter();
1909     /// assert!(i.next().unwrap().is_sensitive());
1910     /// assert!(i.next().unwrap().is_sensitive());
1911     /// ```
iter_mut(&mut self) -> ValueIterMut<'_, VE>1912     pub fn iter_mut(&mut self) -> ValueIterMut<'_, VE> {
1913         ValueIterMut {
1914             inner: self.inner.iter_mut(),
1915             phantom: PhantomData,
1916         }
1917     }
1918 }
1919 
1920 impl<'a, VE: ValueEncoding> IntoIterator for OccupiedEntry<'a, VE>
1921 where
1922     VE: 'a,
1923 {
1924     type Item = &'a mut MetadataValue<VE>;
1925     type IntoIter = ValueIterMut<'a, VE>;
1926 
into_iter(self) -> ValueIterMut<'a, VE>1927     fn into_iter(self) -> ValueIterMut<'a, VE> {
1928         ValueIterMut {
1929             inner: self.inner.into_iter(),
1930             phantom: PhantomData,
1931         }
1932     }
1933 }
1934 
1935 impl<'a, 'b: 'a, VE: ValueEncoding> IntoIterator for &'b OccupiedEntry<'a, VE> {
1936     type Item = &'a MetadataValue<VE>;
1937     type IntoIter = ValueIter<'a, VE>;
1938 
into_iter(self) -> ValueIter<'a, VE>1939     fn into_iter(self) -> ValueIter<'a, VE> {
1940         self.iter()
1941     }
1942 }
1943 
1944 impl<'a, 'b: 'a, VE: ValueEncoding> IntoIterator for &'b mut OccupiedEntry<'a, VE> {
1945     type Item = &'a mut MetadataValue<VE>;
1946     type IntoIter = ValueIterMut<'a, VE>;
1947 
into_iter(self) -> ValueIterMut<'a, VE>1948     fn into_iter(self) -> ValueIterMut<'a, VE> {
1949         self.iter_mut()
1950     }
1951 }
1952 
1953 // ===== impl GetAll =====
1954 
1955 impl<'a, VE: ValueEncoding> GetAll<'a, VE> {
1956     /// Returns an iterator visiting all values associated with the entry.
1957     ///
1958     /// Values are iterated in insertion order.
1959     ///
1960     /// # Examples
1961     ///
1962     /// ```
1963     /// # use tonic::metadata::*;
1964     /// let mut map = MetadataMap::new();
1965     /// map.insert("x-host", "hello.world".parse().unwrap());
1966     /// map.append("x-host", "hello.earth".parse().unwrap());
1967     ///
1968     /// let values = map.get_all("x-host");
1969     /// let mut iter = values.iter();
1970     /// assert_eq!(&"hello.world", iter.next().unwrap());
1971     /// assert_eq!(&"hello.earth", iter.next().unwrap());
1972     /// assert!(iter.next().is_none());
1973     /// ```
iter(&self) -> ValueIter<'a, VE>1974     pub fn iter(&self) -> ValueIter<'a, VE> {
1975         ValueIter {
1976             inner: self.inner.as_ref().map(|inner| inner.iter()),
1977             phantom: PhantomData,
1978         }
1979     }
1980 }
1981 
1982 impl<VE: ValueEncoding> PartialEq for GetAll<'_, VE> {
eq(&self, other: &Self) -> bool1983     fn eq(&self, other: &Self) -> bool {
1984         self.inner.iter().eq(other.inner.iter())
1985     }
1986 }
1987 
1988 impl<'a, VE: ValueEncoding> IntoIterator for GetAll<'a, VE>
1989 where
1990     VE: 'a,
1991 {
1992     type Item = &'a MetadataValue<VE>;
1993     type IntoIter = ValueIter<'a, VE>;
1994 
into_iter(self) -> ValueIter<'a, VE>1995     fn into_iter(self) -> ValueIter<'a, VE> {
1996         ValueIter {
1997             inner: self.inner.map(|inner| inner.into_iter()),
1998             phantom: PhantomData,
1999         }
2000     }
2001 }
2002 
2003 impl<'a, 'b: 'a, VE: ValueEncoding> IntoIterator for &'b GetAll<'a, VE> {
2004     type Item = &'a MetadataValue<VE>;
2005     type IntoIter = ValueIter<'a, VE>;
2006 
into_iter(self) -> ValueIter<'a, VE>2007     fn into_iter(self) -> ValueIter<'a, VE> {
2008         ValueIter {
2009             inner: self.inner.as_ref().map(|inner| inner.into_iter()),
2010             phantom: PhantomData,
2011         }
2012     }
2013 }
2014 
2015 // ===== impl IntoMetadataKey / AsMetadataKey =====
2016 
2017 mod into_metadata_key {
2018     use super::{MetadataMap, MetadataValue, ValueEncoding};
2019     use crate::metadata::key::MetadataKey;
2020 
2021     /// A marker trait used to identify values that can be used as insert keys
2022     /// to a `MetadataMap`.
2023     pub trait IntoMetadataKey<VE: ValueEncoding>: Sealed<VE> {}
2024 
2025     // All methods are on this pub(super) trait, instead of `IntoMetadataKey`,
2026     // so that they aren't publicly exposed to the world.
2027     //
2028     // Being on the `IntoMetadataKey` trait would mean users could call
2029     // `"host".insert(&mut map, "localhost")`.
2030     //
2031     // Ultimately, this allows us to adjust the signatures of these methods
2032     // without breaking any external crate.
2033     pub trait Sealed<VE: ValueEncoding> {
2034         #[doc(hidden)]
insert(self, map: &mut MetadataMap, val: MetadataValue<VE>) -> Option<MetadataValue<VE>>2035         fn insert(self, map: &mut MetadataMap, val: MetadataValue<VE>)
2036             -> Option<MetadataValue<VE>>;
2037 
2038         #[doc(hidden)]
append(self, map: &mut MetadataMap, val: MetadataValue<VE>) -> bool2039         fn append(self, map: &mut MetadataMap, val: MetadataValue<VE>) -> bool;
2040     }
2041 
2042     // ==== impls ====
2043 
2044     impl<VE: ValueEncoding> Sealed<VE> for MetadataKey<VE> {
2045         #[doc(hidden)]
2046         #[inline]
insert( self, map: &mut MetadataMap, val: MetadataValue<VE>, ) -> Option<MetadataValue<VE>>2047         fn insert(
2048             self,
2049             map: &mut MetadataMap,
2050             val: MetadataValue<VE>,
2051         ) -> Option<MetadataValue<VE>> {
2052             map.headers
2053                 .insert(self.inner, val.inner)
2054                 .map(MetadataValue::unchecked_from_header_value)
2055         }
2056 
2057         #[doc(hidden)]
2058         #[inline]
append(self, map: &mut MetadataMap, val: MetadataValue<VE>) -> bool2059         fn append(self, map: &mut MetadataMap, val: MetadataValue<VE>) -> bool {
2060             map.headers.append(self.inner, val.inner)
2061         }
2062     }
2063 
2064     impl<VE: ValueEncoding> IntoMetadataKey<VE> for MetadataKey<VE> {}
2065 
2066     impl<VE: ValueEncoding> Sealed<VE> for &MetadataKey<VE> {
2067         #[doc(hidden)]
2068         #[inline]
insert( self, map: &mut MetadataMap, val: MetadataValue<VE>, ) -> Option<MetadataValue<VE>>2069         fn insert(
2070             self,
2071             map: &mut MetadataMap,
2072             val: MetadataValue<VE>,
2073         ) -> Option<MetadataValue<VE>> {
2074             map.headers
2075                 .insert(&self.inner, val.inner)
2076                 .map(MetadataValue::unchecked_from_header_value)
2077         }
2078         #[doc(hidden)]
2079         #[inline]
append(self, map: &mut MetadataMap, val: MetadataValue<VE>) -> bool2080         fn append(self, map: &mut MetadataMap, val: MetadataValue<VE>) -> bool {
2081             map.headers.append(&self.inner, val.inner)
2082         }
2083     }
2084 
2085     impl<VE: ValueEncoding> IntoMetadataKey<VE> for &MetadataKey<VE> {}
2086 
2087     impl<VE: ValueEncoding> Sealed<VE> for &'static str {
2088         #[doc(hidden)]
2089         #[inline]
insert( self, map: &mut MetadataMap, val: MetadataValue<VE>, ) -> Option<MetadataValue<VE>>2090         fn insert(
2091             self,
2092             map: &mut MetadataMap,
2093             val: MetadataValue<VE>,
2094         ) -> Option<MetadataValue<VE>> {
2095             // Perform name validation
2096             let key = MetadataKey::<VE>::from_static(self);
2097 
2098             map.headers
2099                 .insert(key.inner, val.inner)
2100                 .map(MetadataValue::unchecked_from_header_value)
2101         }
2102         #[doc(hidden)]
2103         #[inline]
append(self, map: &mut MetadataMap, val: MetadataValue<VE>) -> bool2104         fn append(self, map: &mut MetadataMap, val: MetadataValue<VE>) -> bool {
2105             // Perform name validation
2106             let key = MetadataKey::<VE>::from_static(self);
2107 
2108             map.headers.append(key.inner, val.inner)
2109         }
2110     }
2111 
2112     impl<VE: ValueEncoding> IntoMetadataKey<VE> for &'static str {}
2113 }
2114 
2115 mod as_metadata_key {
2116     use super::{MetadataMap, MetadataValue, ValueEncoding};
2117     use crate::metadata::key::{InvalidMetadataKey, MetadataKey};
2118     use http::header::{Entry, GetAll, HeaderValue};
2119 
2120     /// A marker trait used to identify values that can be used as search keys
2121     /// to a `MetadataMap`.
2122     pub trait AsMetadataKey<VE: ValueEncoding>: Sealed<VE> {}
2123 
2124     // All methods are on this pub(super) trait, instead of `AsMetadataKey`,
2125     // so that they aren't publicly exposed to the world.
2126     //
2127     // Being on the `AsMetadataKey` trait would mean users could call
2128     // `"host".find(&map)`.
2129     //
2130     // Ultimately, this allows us to adjust the signatures of these methods
2131     // without breaking any external crate.
2132     pub trait Sealed<VE: ValueEncoding> {
2133         #[doc(hidden)]
get(self, map: &MetadataMap) -> Option<&MetadataValue<VE>>2134         fn get(self, map: &MetadataMap) -> Option<&MetadataValue<VE>>;
2135 
2136         #[doc(hidden)]
get_mut(self, map: &mut MetadataMap) -> Option<&mut MetadataValue<VE>>2137         fn get_mut(self, map: &mut MetadataMap) -> Option<&mut MetadataValue<VE>>;
2138 
2139         #[doc(hidden)]
get_all(self, map: &MetadataMap) -> Option<GetAll<'_, HeaderValue>>2140         fn get_all(self, map: &MetadataMap) -> Option<GetAll<'_, HeaderValue>>;
2141 
2142         #[doc(hidden)]
entry(self, map: &mut MetadataMap) -> Result<Entry<'_, HeaderValue>, InvalidMetadataKey>2143         fn entry(self, map: &mut MetadataMap)
2144             -> Result<Entry<'_, HeaderValue>, InvalidMetadataKey>;
2145 
2146         #[doc(hidden)]
remove(self, map: &mut MetadataMap) -> Option<MetadataValue<VE>>2147         fn remove(self, map: &mut MetadataMap) -> Option<MetadataValue<VE>>;
2148     }
2149 
2150     // ==== impls ====
2151 
2152     impl<VE: ValueEncoding> Sealed<VE> for MetadataKey<VE> {
2153         #[doc(hidden)]
2154         #[inline]
get(self, map: &MetadataMap) -> Option<&MetadataValue<VE>>2155         fn get(self, map: &MetadataMap) -> Option<&MetadataValue<VE>> {
2156             map.headers
2157                 .get(self.inner)
2158                 .map(MetadataValue::unchecked_from_header_value_ref)
2159         }
2160 
2161         #[doc(hidden)]
2162         #[inline]
get_mut(self, map: &mut MetadataMap) -> Option<&mut MetadataValue<VE>>2163         fn get_mut(self, map: &mut MetadataMap) -> Option<&mut MetadataValue<VE>> {
2164             map.headers
2165                 .get_mut(self.inner)
2166                 .map(MetadataValue::unchecked_from_mut_header_value_ref)
2167         }
2168 
2169         #[doc(hidden)]
2170         #[inline]
get_all(self, map: &MetadataMap) -> Option<GetAll<'_, HeaderValue>>2171         fn get_all(self, map: &MetadataMap) -> Option<GetAll<'_, HeaderValue>> {
2172             Some(map.headers.get_all(self.inner))
2173         }
2174 
2175         #[doc(hidden)]
2176         #[inline]
entry( self, map: &mut MetadataMap, ) -> Result<Entry<'_, HeaderValue>, InvalidMetadataKey>2177         fn entry(
2178             self,
2179             map: &mut MetadataMap,
2180         ) -> Result<Entry<'_, HeaderValue>, InvalidMetadataKey> {
2181             Ok(map.headers.entry(self.inner))
2182         }
2183 
2184         #[doc(hidden)]
2185         #[inline]
remove(self, map: &mut MetadataMap) -> Option<MetadataValue<VE>>2186         fn remove(self, map: &mut MetadataMap) -> Option<MetadataValue<VE>> {
2187             map.headers
2188                 .remove(self.inner)
2189                 .map(MetadataValue::unchecked_from_header_value)
2190         }
2191     }
2192 
2193     impl<VE: ValueEncoding> AsMetadataKey<VE> for MetadataKey<VE> {}
2194 
2195     impl<VE: ValueEncoding> Sealed<VE> for &MetadataKey<VE> {
2196         #[doc(hidden)]
2197         #[inline]
get(self, map: &MetadataMap) -> Option<&MetadataValue<VE>>2198         fn get(self, map: &MetadataMap) -> Option<&MetadataValue<VE>> {
2199             map.headers
2200                 .get(&self.inner)
2201                 .map(MetadataValue::unchecked_from_header_value_ref)
2202         }
2203 
2204         #[doc(hidden)]
2205         #[inline]
get_mut(self, map: &mut MetadataMap) -> Option<&mut MetadataValue<VE>>2206         fn get_mut(self, map: &mut MetadataMap) -> Option<&mut MetadataValue<VE>> {
2207             map.headers
2208                 .get_mut(&self.inner)
2209                 .map(MetadataValue::unchecked_from_mut_header_value_ref)
2210         }
2211 
2212         #[doc(hidden)]
2213         #[inline]
get_all(self, map: &MetadataMap) -> Option<GetAll<'_, HeaderValue>>2214         fn get_all(self, map: &MetadataMap) -> Option<GetAll<'_, HeaderValue>> {
2215             Some(map.headers.get_all(&self.inner))
2216         }
2217 
2218         #[doc(hidden)]
2219         #[inline]
entry( self, map: &mut MetadataMap, ) -> Result<Entry<'_, HeaderValue>, InvalidMetadataKey>2220         fn entry(
2221             self,
2222             map: &mut MetadataMap,
2223         ) -> Result<Entry<'_, HeaderValue>, InvalidMetadataKey> {
2224             Ok(map.headers.entry(&self.inner))
2225         }
2226 
2227         #[doc(hidden)]
2228         #[inline]
remove(self, map: &mut MetadataMap) -> Option<MetadataValue<VE>>2229         fn remove(self, map: &mut MetadataMap) -> Option<MetadataValue<VE>> {
2230             map.headers
2231                 .remove(&self.inner)
2232                 .map(MetadataValue::unchecked_from_header_value)
2233         }
2234     }
2235 
2236     impl<VE: ValueEncoding> AsMetadataKey<VE> for &MetadataKey<VE> {}
2237 
2238     impl<VE: ValueEncoding> Sealed<VE> for &str {
2239         #[doc(hidden)]
2240         #[inline]
get(self, map: &MetadataMap) -> Option<&MetadataValue<VE>>2241         fn get(self, map: &MetadataMap) -> Option<&MetadataValue<VE>> {
2242             if !VE::is_valid_key(self) {
2243                 return None;
2244             }
2245             map.headers
2246                 .get(self)
2247                 .map(MetadataValue::unchecked_from_header_value_ref)
2248         }
2249 
2250         #[doc(hidden)]
2251         #[inline]
get_mut(self, map: &mut MetadataMap) -> Option<&mut MetadataValue<VE>>2252         fn get_mut(self, map: &mut MetadataMap) -> Option<&mut MetadataValue<VE>> {
2253             if !VE::is_valid_key(self) {
2254                 return None;
2255             }
2256             map.headers
2257                 .get_mut(self)
2258                 .map(MetadataValue::unchecked_from_mut_header_value_ref)
2259         }
2260 
2261         #[doc(hidden)]
2262         #[inline]
get_all(self, map: &MetadataMap) -> Option<GetAll<'_, HeaderValue>>2263         fn get_all(self, map: &MetadataMap) -> Option<GetAll<'_, HeaderValue>> {
2264             if !VE::is_valid_key(self) {
2265                 return None;
2266             }
2267             Some(map.headers.get_all(self))
2268         }
2269 
2270         #[doc(hidden)]
2271         #[inline]
entry( self, map: &mut MetadataMap, ) -> Result<Entry<'_, HeaderValue>, InvalidMetadataKey>2272         fn entry(
2273             self,
2274             map: &mut MetadataMap,
2275         ) -> Result<Entry<'_, HeaderValue>, InvalidMetadataKey> {
2276             if !VE::is_valid_key(self) {
2277                 return Err(InvalidMetadataKey::new());
2278             }
2279 
2280             let key = http::header::HeaderName::from_bytes(self.as_bytes())
2281                 .map_err(|_| InvalidMetadataKey::new())?;
2282             let entry = map.headers.entry(key);
2283             Ok(entry)
2284         }
2285 
2286         #[doc(hidden)]
2287         #[inline]
remove(self, map: &mut MetadataMap) -> Option<MetadataValue<VE>>2288         fn remove(self, map: &mut MetadataMap) -> Option<MetadataValue<VE>> {
2289             if !VE::is_valid_key(self) {
2290                 return None;
2291             }
2292             map.headers
2293                 .remove(self)
2294                 .map(MetadataValue::unchecked_from_header_value)
2295         }
2296     }
2297 
2298     impl<VE: ValueEncoding> AsMetadataKey<VE> for &str {}
2299 
2300     impl<VE: ValueEncoding> Sealed<VE> for String {
2301         #[doc(hidden)]
2302         #[inline]
get(self, map: &MetadataMap) -> Option<&MetadataValue<VE>>2303         fn get(self, map: &MetadataMap) -> Option<&MetadataValue<VE>> {
2304             if !VE::is_valid_key(self.as_str()) {
2305                 return None;
2306             }
2307             map.headers
2308                 .get(self.as_str())
2309                 .map(MetadataValue::unchecked_from_header_value_ref)
2310         }
2311 
2312         #[doc(hidden)]
2313         #[inline]
get_mut(self, map: &mut MetadataMap) -> Option<&mut MetadataValue<VE>>2314         fn get_mut(self, map: &mut MetadataMap) -> Option<&mut MetadataValue<VE>> {
2315             if !VE::is_valid_key(self.as_str()) {
2316                 return None;
2317             }
2318             map.headers
2319                 .get_mut(self.as_str())
2320                 .map(MetadataValue::unchecked_from_mut_header_value_ref)
2321         }
2322 
2323         #[doc(hidden)]
2324         #[inline]
get_all(self, map: &MetadataMap) -> Option<GetAll<'_, HeaderValue>>2325         fn get_all(self, map: &MetadataMap) -> Option<GetAll<'_, HeaderValue>> {
2326             if !VE::is_valid_key(self.as_str()) {
2327                 return None;
2328             }
2329             Some(map.headers.get_all(self.as_str()))
2330         }
2331 
2332         #[doc(hidden)]
2333         #[inline]
entry( self, map: &mut MetadataMap, ) -> Result<Entry<'_, HeaderValue>, InvalidMetadataKey>2334         fn entry(
2335             self,
2336             map: &mut MetadataMap,
2337         ) -> Result<Entry<'_, HeaderValue>, InvalidMetadataKey> {
2338             if !VE::is_valid_key(self.as_str()) {
2339                 return Err(InvalidMetadataKey::new());
2340             }
2341 
2342             let key = http::header::HeaderName::from_bytes(self.as_bytes())
2343                 .map_err(|_| InvalidMetadataKey::new())?;
2344             Ok(map.headers.entry(key))
2345         }
2346 
2347         #[doc(hidden)]
2348         #[inline]
remove(self, map: &mut MetadataMap) -> Option<MetadataValue<VE>>2349         fn remove(self, map: &mut MetadataMap) -> Option<MetadataValue<VE>> {
2350             if !VE::is_valid_key(self.as_str()) {
2351                 return None;
2352             }
2353             map.headers
2354                 .remove(self.as_str())
2355                 .map(MetadataValue::unchecked_from_header_value)
2356         }
2357     }
2358 
2359     impl<VE: ValueEncoding> AsMetadataKey<VE> for String {}
2360 
2361     impl<VE: ValueEncoding> Sealed<VE> for &String {
2362         #[doc(hidden)]
2363         #[inline]
get(self, map: &MetadataMap) -> Option<&MetadataValue<VE>>2364         fn get(self, map: &MetadataMap) -> Option<&MetadataValue<VE>> {
2365             if !VE::is_valid_key(self) {
2366                 return None;
2367             }
2368             map.headers
2369                 .get(self.as_str())
2370                 .map(MetadataValue::unchecked_from_header_value_ref)
2371         }
2372 
2373         #[doc(hidden)]
2374         #[inline]
get_mut(self, map: &mut MetadataMap) -> Option<&mut MetadataValue<VE>>2375         fn get_mut(self, map: &mut MetadataMap) -> Option<&mut MetadataValue<VE>> {
2376             if !VE::is_valid_key(self) {
2377                 return None;
2378             }
2379             map.headers
2380                 .get_mut(self.as_str())
2381                 .map(MetadataValue::unchecked_from_mut_header_value_ref)
2382         }
2383 
2384         #[doc(hidden)]
2385         #[inline]
get_all(self, map: &MetadataMap) -> Option<GetAll<'_, HeaderValue>>2386         fn get_all(self, map: &MetadataMap) -> Option<GetAll<'_, HeaderValue>> {
2387             if !VE::is_valid_key(self) {
2388                 return None;
2389             }
2390             Some(map.headers.get_all(self.as_str()))
2391         }
2392 
2393         #[doc(hidden)]
2394         #[inline]
entry( self, map: &mut MetadataMap, ) -> Result<Entry<'_, HeaderValue>, InvalidMetadataKey>2395         fn entry(
2396             self,
2397             map: &mut MetadataMap,
2398         ) -> Result<Entry<'_, HeaderValue>, InvalidMetadataKey> {
2399             if !VE::is_valid_key(self) {
2400                 return Err(InvalidMetadataKey::new());
2401             }
2402 
2403             let key = http::header::HeaderName::from_bytes(self.as_bytes())
2404                 .map_err(|_| InvalidMetadataKey::new())?;
2405             Ok(map.headers.entry(key))
2406         }
2407 
2408         #[doc(hidden)]
2409         #[inline]
remove(self, map: &mut MetadataMap) -> Option<MetadataValue<VE>>2410         fn remove(self, map: &mut MetadataMap) -> Option<MetadataValue<VE>> {
2411             if !VE::is_valid_key(self) {
2412                 return None;
2413             }
2414             map.headers
2415                 .remove(self.as_str())
2416                 .map(MetadataValue::unchecked_from_header_value)
2417         }
2418     }
2419 
2420     impl<VE: ValueEncoding> AsMetadataKey<VE> for &String {}
2421 }
2422 
2423 mod as_encoding_agnostic_metadata_key {
2424     use super::{MetadataMap, ValueEncoding};
2425     use crate::metadata::key::MetadataKey;
2426 
2427     /// A marker trait used to identify values that can be used as search keys
2428     /// to a `MetadataMap`, for operations that don't expose the actual value.
2429     pub trait AsEncodingAgnosticMetadataKey: Sealed {}
2430 
2431     // All methods are on this pub(super) trait, instead of
2432     // `AsEncodingAgnosticMetadataKey`, so that they aren't publicly exposed to
2433     // the world.
2434     //
2435     // Being on the `AsEncodingAgnosticMetadataKey` trait would mean users could
2436     // call `"host".contains_key(&map)`.
2437     //
2438     // Ultimately, this allows us to adjust the signatures of these methods
2439     // without breaking any external crate.
2440     pub trait Sealed {
2441         #[doc(hidden)]
contains_key(&self, map: &MetadataMap) -> bool2442         fn contains_key(&self, map: &MetadataMap) -> bool;
2443     }
2444 
2445     // ==== impls ====
2446 
2447     impl<VE: ValueEncoding> Sealed for MetadataKey<VE> {
2448         #[doc(hidden)]
2449         #[inline]
contains_key(&self, map: &MetadataMap) -> bool2450         fn contains_key(&self, map: &MetadataMap) -> bool {
2451             map.headers.contains_key(&self.inner)
2452         }
2453     }
2454 
2455     impl<VE: ValueEncoding> AsEncodingAgnosticMetadataKey for MetadataKey<VE> {}
2456 
2457     impl<VE: ValueEncoding> Sealed for &MetadataKey<VE> {
2458         #[doc(hidden)]
2459         #[inline]
contains_key(&self, map: &MetadataMap) -> bool2460         fn contains_key(&self, map: &MetadataMap) -> bool {
2461             map.headers.contains_key(&self.inner)
2462         }
2463     }
2464 
2465     impl<VE: ValueEncoding> AsEncodingAgnosticMetadataKey for &MetadataKey<VE> {}
2466 
2467     impl Sealed for &str {
2468         #[doc(hidden)]
2469         #[inline]
contains_key(&self, map: &MetadataMap) -> bool2470         fn contains_key(&self, map: &MetadataMap) -> bool {
2471             map.headers.contains_key(*self)
2472         }
2473     }
2474 
2475     impl AsEncodingAgnosticMetadataKey for &str {}
2476 
2477     impl Sealed for String {
2478         #[doc(hidden)]
2479         #[inline]
contains_key(&self, map: &MetadataMap) -> bool2480         fn contains_key(&self, map: &MetadataMap) -> bool {
2481             map.headers.contains_key(self.as_str())
2482         }
2483     }
2484 
2485     impl AsEncodingAgnosticMetadataKey for String {}
2486 
2487     impl Sealed for &String {
2488         #[doc(hidden)]
2489         #[inline]
contains_key(&self, map: &MetadataMap) -> bool2490         fn contains_key(&self, map: &MetadataMap) -> bool {
2491             map.headers.contains_key(self.as_str())
2492         }
2493     }
2494 
2495     impl AsEncodingAgnosticMetadataKey for &String {}
2496 }
2497 
2498 #[cfg(test)]
2499 mod tests {
2500     use super::*;
2501 
2502     #[test]
test_from_headers_takes_http_headers()2503     fn test_from_headers_takes_http_headers() {
2504         let mut http_map = http::HeaderMap::new();
2505         http_map.insert("x-host", "example.com".parse().unwrap());
2506 
2507         let map = MetadataMap::from_headers(http_map);
2508 
2509         assert_eq!(map.get("x-host").unwrap(), "example.com");
2510     }
2511 
2512     #[test]
test_to_headers_encoding()2513     fn test_to_headers_encoding() {
2514         use crate::Status;
2515         let special_char_message = "Beyond 100% ascii \t\n\r��️��������";
2516         let s1 = Status::unknown(special_char_message);
2517 
2518         assert_eq!(s1.message(), special_char_message);
2519 
2520         let s1_map = s1.to_header_map().unwrap();
2521         let s2 = Status::from_header_map(&s1_map).unwrap();
2522 
2523         assert_eq!(s1.message(), s2.message());
2524 
2525         assert!(
2526             s1_map
2527                 .get("grpc-message")
2528                 .unwrap()
2529                 .to_str()
2530                 .unwrap()
2531                 .starts_with("Beyond%20100%25%20ascii"),
2532             "Percent sign or other character isn't encoded as desired: {:?}",
2533             s1_map.get("grpc-message")
2534         );
2535     }
2536 
2537     #[test]
test_iter_categorizes_ascii_entries()2538     fn test_iter_categorizes_ascii_entries() {
2539         let mut map = MetadataMap::new();
2540 
2541         map.insert("x-word", "hello".parse().unwrap());
2542         map.append_bin("x-word-bin", MetadataValue::from_bytes(b"goodbye"));
2543         map.insert_bin("x-number-bin", MetadataValue::from_bytes(b"123"));
2544 
2545         let mut found_x_word = false;
2546         for key_and_value in map.iter() {
2547             if let KeyAndValueRef::Ascii(key, _value) = key_and_value {
2548                 if key.as_str() == "x-word" {
2549                     found_x_word = true;
2550                 } else {
2551                     panic!("Unexpected key");
2552                 }
2553             }
2554         }
2555         assert!(found_x_word);
2556     }
2557 
2558     #[test]
test_iter_categorizes_binary_entries()2559     fn test_iter_categorizes_binary_entries() {
2560         let mut map = MetadataMap::new();
2561 
2562         map.insert("x-word", "hello".parse().unwrap());
2563         map.append_bin("x-word-bin", MetadataValue::from_bytes(b"goodbye"));
2564 
2565         let mut found_x_word_bin = false;
2566         for key_and_value in map.iter() {
2567             if let KeyAndValueRef::Binary(key, _value) = key_and_value {
2568                 if key.as_str() == "x-word-bin" {
2569                     found_x_word_bin = true;
2570                 } else {
2571                     panic!("Unexpected key");
2572                 }
2573             }
2574         }
2575         assert!(found_x_word_bin);
2576     }
2577 
2578     #[test]
test_iter_mut_categorizes_ascii_entries()2579     fn test_iter_mut_categorizes_ascii_entries() {
2580         let mut map = MetadataMap::new();
2581 
2582         map.insert("x-word", "hello".parse().unwrap());
2583         map.append_bin("x-word-bin", MetadataValue::from_bytes(b"goodbye"));
2584         map.insert_bin("x-number-bin", MetadataValue::from_bytes(b"123"));
2585 
2586         let mut found_x_word = false;
2587         for key_and_value in map.iter_mut() {
2588             if let KeyAndMutValueRef::Ascii(key, _value) = key_and_value {
2589                 if key.as_str() == "x-word" {
2590                     found_x_word = true;
2591                 } else {
2592                     panic!("Unexpected key");
2593                 }
2594             }
2595         }
2596         assert!(found_x_word);
2597     }
2598 
2599     #[test]
test_iter_mut_categorizes_binary_entries()2600     fn test_iter_mut_categorizes_binary_entries() {
2601         let mut map = MetadataMap::new();
2602 
2603         map.insert("x-word", "hello".parse().unwrap());
2604         map.append_bin("x-word-bin", MetadataValue::from_bytes(b"goodbye"));
2605 
2606         let mut found_x_word_bin = false;
2607         for key_and_value in map.iter_mut() {
2608             if let KeyAndMutValueRef::Binary(key, _value) = key_and_value {
2609                 if key.as_str() == "x-word-bin" {
2610                     found_x_word_bin = true;
2611                 } else {
2612                     panic!("Unexpected key");
2613                 }
2614             }
2615         }
2616         assert!(found_x_word_bin);
2617     }
2618 
2619     #[test]
test_keys_categorizes_ascii_entries()2620     fn test_keys_categorizes_ascii_entries() {
2621         let mut map = MetadataMap::new();
2622 
2623         map.insert("x-word", "hello".parse().unwrap());
2624         map.append_bin("x-word-bin", MetadataValue::from_bytes(b"goodbye"));
2625         map.insert_bin("x-number-bin", MetadataValue::from_bytes(b"123"));
2626 
2627         let mut found_x_word = false;
2628         for key in map.keys() {
2629             if let KeyRef::Ascii(key) = key {
2630                 if key.as_str() == "x-word" {
2631                     found_x_word = true;
2632                 } else {
2633                     panic!("Unexpected key");
2634                 }
2635             }
2636         }
2637         assert!(found_x_word);
2638     }
2639 
2640     #[test]
test_keys_categorizes_binary_entries()2641     fn test_keys_categorizes_binary_entries() {
2642         let mut map = MetadataMap::new();
2643 
2644         map.insert("x-word", "hello".parse().unwrap());
2645         map.insert_bin("x-number-bin", MetadataValue::from_bytes(b"123"));
2646 
2647         let mut found_x_number_bin = false;
2648         for key in map.keys() {
2649             if let KeyRef::Binary(key) = key {
2650                 if key.as_str() == "x-number-bin" {
2651                     found_x_number_bin = true;
2652                 } else {
2653                     panic!("Unexpected key");
2654                 }
2655             }
2656         }
2657         assert!(found_x_number_bin);
2658     }
2659 
2660     #[test]
test_values_categorizes_ascii_entries()2661     fn test_values_categorizes_ascii_entries() {
2662         let mut map = MetadataMap::new();
2663 
2664         map.insert("x-word", "hello".parse().unwrap());
2665         map.append_bin("x-word-bin", MetadataValue::from_bytes(b"goodbye"));
2666         map.insert_bin("x-number-bin", MetadataValue::from_bytes(b"123"));
2667 
2668         let mut found_x_word = false;
2669         for value in map.values() {
2670             if let ValueRef::Ascii(value) = value {
2671                 if *value == "hello" {
2672                     found_x_word = true;
2673                 } else {
2674                     panic!("Unexpected key");
2675                 }
2676             }
2677         }
2678         assert!(found_x_word);
2679     }
2680 
2681     #[test]
test_values_categorizes_binary_entries()2682     fn test_values_categorizes_binary_entries() {
2683         let mut map = MetadataMap::new();
2684 
2685         map.insert("x-word", "hello".parse().unwrap());
2686         map.append_bin("x-word-bin", MetadataValue::from_bytes(b"goodbye"));
2687 
2688         let mut found_x_word_bin = false;
2689         for value_ref in map.values() {
2690             if let ValueRef::Binary(value) = value_ref {
2691                 assert_eq!(*value, "goodbye");
2692                 found_x_word_bin = true;
2693             }
2694         }
2695         assert!(found_x_word_bin);
2696     }
2697 
2698     #[test]
test_values_mut_categorizes_ascii_entries()2699     fn test_values_mut_categorizes_ascii_entries() {
2700         let mut map = MetadataMap::new();
2701 
2702         map.insert("x-word", "hello".parse().unwrap());
2703         map.append_bin("x-word-bin", MetadataValue::from_bytes(b"goodbye"));
2704         map.insert_bin("x-number-bin", MetadataValue::from_bytes(b"123"));
2705 
2706         let mut found_x_word = false;
2707         for value_ref in map.values_mut() {
2708             if let ValueRefMut::Ascii(value) = value_ref {
2709                 assert_eq!(*value, "hello");
2710                 found_x_word = true;
2711             }
2712         }
2713         assert!(found_x_word);
2714     }
2715 
2716     #[test]
test_values_mut_categorizes_binary_entries()2717     fn test_values_mut_categorizes_binary_entries() {
2718         let mut map = MetadataMap::new();
2719 
2720         map.insert("x-word", "hello".parse().unwrap());
2721         map.append_bin("x-word-bin", MetadataValue::from_bytes(b"goodbye"));
2722 
2723         let mut found_x_word_bin = false;
2724         for value in map.values_mut() {
2725             if let ValueRefMut::Binary(value) = value {
2726                 assert_eq!(*value, "goodbye");
2727                 found_x_word_bin = true;
2728             }
2729         }
2730         assert!(found_x_word_bin);
2731     }
2732 
2733     #[allow(dead_code)]
value_drain_is_send_sync()2734     fn value_drain_is_send_sync() {
2735         fn is_send_sync<T: Send + Sync>() {}
2736 
2737         is_send_sync::<Iter<'_>>();
2738         is_send_sync::<IterMut<'_>>();
2739 
2740         is_send_sync::<ValueDrain<'_, Ascii>>();
2741         is_send_sync::<ValueDrain<'_, Binary>>();
2742 
2743         is_send_sync::<ValueIterMut<'_, Ascii>>();
2744         is_send_sync::<ValueIterMut<'_, Binary>>();
2745     }
2746 }
2747