tower_grpc/metadata/
map.rs

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