pub struct HeaderMap<T = HeaderValue> { /* private fields */ }
Expand description
A set of HTTP headers
HeaderMap
is an multimap of HeaderName
to values.
Examples
Basic usage
let mut headers = HeaderMap::new();
headers.insert(HOST, "example.com".parse().unwrap());
headers.insert(CONTENT_LENGTH, "123".parse().unwrap());
assert!(headers.contains_key(HOST));
assert!(!headers.contains_key(LOCATION));
assert_eq!(headers[HOST], "example.com");
headers.remove(HOST);
assert!(!headers.contains_key(HOST));
Implementations
sourceimpl HeaderMap<HeaderValue>
impl HeaderMap<HeaderValue>
sourcepub fn new() -> HeaderMap<HeaderValue>
pub fn new() -> HeaderMap<HeaderValue>
Create an empty HeaderMap
.
The map will be created without any capacity. This function will not allocate.
Examples
let map = HeaderMap::new();
assert!(map.is_empty());
assert_eq!(0, map.capacity());
sourceimpl<T> HeaderMap<T>
impl<T> HeaderMap<T>
sourcepub fn with_capacity(capacity: usize) -> HeaderMap<T>
pub fn with_capacity(capacity: usize) -> HeaderMap<T>
Create an empty HeaderMap
with the specified capacity.
The returned map will allocate internal storage in order to hold about
capacity
elements without reallocating. However, this is a “best
effort” as there are usage patterns that could cause additional
allocations before capacity
headers are stored in the map.
More capacity than requested may be allocated.
Examples
let map: HeaderMap<u32> = HeaderMap::with_capacity(10);
assert!(map.is_empty());
assert_eq!(12, map.capacity());
sourcepub fn len(&self) -> usize
pub fn len(&self) -> usize
Returns the number of headers stored in the map.
This number represents the total number of values stored in the map. This number can be greater than or equal to the number of keys stored given that a single key may have more than one associated value.
Examples
let mut map = HeaderMap::new();
assert_eq!(0, map.len());
map.insert(ACCEPT, "text/plain".parse().unwrap());
map.insert(HOST, "localhost".parse().unwrap());
assert_eq!(2, map.len());
map.append(ACCEPT, "text/html".parse().unwrap());
assert_eq!(3, map.len());
sourcepub fn keys_len(&self) -> usize
pub fn keys_len(&self) -> usize
Returns the number of keys stored in the map.
This number will be less than or equal to len()
as each key may have
more than one associated value.
Examples
let mut map = HeaderMap::new();
assert_eq!(0, map.keys_len());
map.insert(ACCEPT, "text/plain".parse().unwrap());
map.insert(HOST, "localhost".parse().unwrap());
assert_eq!(2, map.keys_len());
map.insert(ACCEPT, "text/html".parse().unwrap());
assert_eq!(2, map.keys_len());
sourcepub fn is_empty(&self) -> bool
pub fn is_empty(&self) -> bool
Returns true if the map contains no elements.
Examples
let mut map = HeaderMap::new();
assert!(map.is_empty());
map.insert(HOST, "hello.world".parse().unwrap());
assert!(!map.is_empty());
sourcepub fn clear(&mut self)
pub fn clear(&mut self)
Clears the map, removing all key-value pairs. Keeps the allocated memory for reuse.
Examples
let mut map = HeaderMap::new();
map.insert(HOST, "hello.world".parse().unwrap());
map.clear();
assert!(map.is_empty());
assert!(map.capacity() > 0);
sourcepub fn capacity(&self) -> usize
pub fn capacity(&self) -> usize
Returns the number of headers the map can hold without reallocating.
This number is an approximation as certain usage patterns could cause additional allocations before the returned capacity is filled.
Examples
let mut map = HeaderMap::new();
assert_eq!(0, map.capacity());
map.insert(HOST, "hello.world".parse().unwrap());
assert_eq!(6, map.capacity());
sourcepub fn reserve(&mut self, additional: usize)
pub fn reserve(&mut self, additional: usize)
Reserves capacity for at least additional
more headers to be inserted
into the HeaderMap
.
The header map may reserve more space to avoid frequent reallocations.
Like with with_capacity
, this will be a “best effort” to avoid
allocations until additional
more headers are inserted. Certain usage
patterns could cause additional allocations before the number is
reached.
Panics
Panics if the new allocation size overflows usize
.
Examples
let mut map = HeaderMap::new();
map.reserve(10);
sourcepub fn get<K>(&self, key: K) -> Option<&T> where
K: AsHeaderName,
pub fn get<K>(&self, key: K) -> Option<&T> where
K: AsHeaderName,
Returns a reference to the value associated with the key.
If there are multiple values associated with the key, then the first one
is returned. Use get_all
to get all values associated with a given
key. Returns None
if there are no values associated with the key.
Examples
let mut map = HeaderMap::new();
assert!(map.get("host").is_none());
map.insert(HOST, "hello".parse().unwrap());
assert_eq!(map.get(HOST).unwrap(), &"hello");
assert_eq!(map.get("host").unwrap(), &"hello");
map.append(HOST, "world".parse().unwrap());
assert_eq!(map.get("host").unwrap(), &"hello");
sourcepub fn get_mut<K>(&mut self, key: K) -> Option<&mut T> where
K: AsHeaderName,
pub fn get_mut<K>(&mut self, key: K) -> Option<&mut T> where
K: AsHeaderName,
Returns a mutable reference to the value associated with the key.
If there are multiple values associated with the key, then the first one
is returned. Use entry
to get all values associated with a given
key. Returns None
if there are no values associated with the key.
Examples
let mut map = HeaderMap::default();
map.insert(HOST, "hello".to_string());
map.get_mut("host").unwrap().push_str("-world");
assert_eq!(map.get(HOST).unwrap(), &"hello-world");
sourcepub fn get_all<K>(&self, key: K) -> GetAll<'_, T> where
K: AsHeaderName,
pub fn get_all<K>(&self, key: K) -> GetAll<'_, T> where
K: AsHeaderName,
Returns a view of all values associated with a key.
The returned view does not incur any allocations and allows iterating
the values associated with the key. See GetAll
for more details.
Returns None
if there are no values associated with the key.
Examples
let mut map = HeaderMap::new();
map.insert(HOST, "hello".parse().unwrap());
map.append(HOST, "goodbye".parse().unwrap());
let view = map.get_all("host");
let mut iter = view.iter();
assert_eq!(&"hello", iter.next().unwrap());
assert_eq!(&"goodbye", iter.next().unwrap());
assert!(iter.next().is_none());
sourcepub fn contains_key<K>(&self, key: K) -> bool where
K: AsHeaderName,
pub fn contains_key<K>(&self, key: K) -> bool where
K: AsHeaderName,
Returns true if the map contains a value for the specified key.
Examples
let mut map = HeaderMap::new();
assert!(!map.contains_key(HOST));
map.insert(HOST, "world".parse().unwrap());
assert!(map.contains_key("host"));
sourcepub fn iter(&self) -> Iter<'_, T>ⓘNotable traits for Iter<'a, T>impl<'a, T> Iterator for Iter<'a, T> type Item = (&'a HeaderName, &'a T);
pub fn iter(&self) -> Iter<'_, T>ⓘNotable traits for Iter<'a, T>impl<'a, T> Iterator for Iter<'a, T> type Item = (&'a HeaderName, &'a T);
An iterator visiting all key-value pairs.
The iteration order is arbitrary, but consistent across platforms for the same crate version. Each key will be yielded once per associated value. So, if a key has 3 associated values, it will be yielded 3 times.
Examples
let mut map = HeaderMap::new();
map.insert(HOST, "hello".parse().unwrap());
map.append(HOST, "goodbye".parse().unwrap());
map.insert(CONTENT_LENGTH, "123".parse().unwrap());
for (key, value) in map.iter() {
println!("{:?}: {:?}", key, value);
}
sourcepub fn iter_mut(&mut self) -> IterMut<'_, T>ⓘNotable traits for IterMut<'a, T>impl<'a, T> Iterator for IterMut<'a, T> type Item = (&'a HeaderName, &'a mut T);
pub fn iter_mut(&mut self) -> IterMut<'_, T>ⓘNotable traits for IterMut<'a, T>impl<'a, T> Iterator for IterMut<'a, T> type Item = (&'a HeaderName, &'a mut T);
An iterator visiting all key-value pairs, with mutable value references.
The iterator order is arbitrary, but consistent across platforms for the same crate version. Each key will be yielded once per associated value, so if a key has 3 associated values, it will be yielded 3 times.
Examples
let mut map = HeaderMap::default();
map.insert(HOST, "hello".to_string());
map.append(HOST, "goodbye".to_string());
map.insert(CONTENT_LENGTH, "123".to_string());
for (key, value) in map.iter_mut() {
value.push_str("-boop");
}
sourcepub fn keys(&self) -> Keys<'_, T>ⓘNotable traits for Keys<'a, T>impl<'a, T> Iterator for Keys<'a, T> type Item = &'a HeaderName;
pub fn keys(&self) -> Keys<'_, T>ⓘNotable traits for Keys<'a, T>impl<'a, T> Iterator for Keys<'a, T> type Item = &'a HeaderName;
An iterator visiting all keys.
The iteration order is arbitrary, but consistent across platforms for the same crate version. Each key will be yielded only once even if it has multiple associated values.
Examples
let mut map = HeaderMap::new();
map.insert(HOST, "hello".parse().unwrap());
map.append(HOST, "goodbye".parse().unwrap());
map.insert(CONTENT_LENGTH, "123".parse().unwrap());
for key in map.keys() {
println!("{:?}", key);
}
sourcepub fn values(&self) -> Values<'_, T>ⓘNotable traits for Values<'a, T>impl<'a, T> Iterator for Values<'a, T> type Item = &'a T;
pub fn values(&self) -> Values<'_, T>ⓘNotable traits for Values<'a, T>impl<'a, T> Iterator for Values<'a, T> type Item = &'a T;
An iterator visiting all values.
The iteration order is arbitrary, but consistent across platforms for the same crate version.
Examples
let mut map = HeaderMap::new();
map.insert(HOST, "hello".parse().unwrap());
map.append(HOST, "goodbye".parse().unwrap());
map.insert(CONTENT_LENGTH, "123".parse().unwrap());
for value in map.values() {
println!("{:?}", value);
}
sourcepub fn values_mut(&mut self) -> ValuesMut<'_, T>ⓘNotable traits for ValuesMut<'a, T>impl<'a, T> Iterator for ValuesMut<'a, T> type Item = &'a mut T;
pub fn values_mut(&mut self) -> ValuesMut<'_, T>ⓘNotable traits for ValuesMut<'a, T>impl<'a, T> Iterator for ValuesMut<'a, T> type Item = &'a mut T;
An iterator visiting all values mutably.
The iteration order is arbitrary, but consistent across platforms for the same crate version.
Examples
let mut map = HeaderMap::default();
map.insert(HOST, "hello".to_string());
map.append(HOST, "goodbye".to_string());
map.insert(CONTENT_LENGTH, "123".to_string());
for value in map.values_mut() {
value.push_str("-boop");
}
sourcepub fn drain(&mut self) -> Drain<'_, T>ⓘNotable traits for Drain<'a, T>impl<'a, T> Iterator for Drain<'a, T> type Item = (HeaderName, ValueDrain<'a, T>);
pub fn drain(&mut self) -> Drain<'_, T>ⓘNotable traits for Drain<'a, T>impl<'a, T> Iterator for Drain<'a, T> type Item = (HeaderName, ValueDrain<'a, T>);
Clears the map, returning all entries as an iterator.
The internal memory is kept for reuse.
Examples
let mut map = HeaderMap::new();
map.insert(HOST, "hello".parse().unwrap());
map.append(HOST, "goodbye".parse().unwrap());
map.insert(CONTENT_LENGTH, "123".parse().unwrap());
let mut drain = map.drain();
let (key, mut vals) = drain.next().unwrap();
assert_eq!("host", key);
assert_eq!("hello", vals.next().unwrap());
assert_eq!("goodbye", vals.next().unwrap());
assert!(vals.next().is_none());
let (key, mut vals) = drain.next().unwrap();
assert_eq!("content-length", key);
assert_eq!("123", vals.next().unwrap());
assert!(vals.next().is_none());
sourcepub fn entry<K>(&mut self, key: K) -> Result<Entry<'_, T>, InvalidHeaderName> where
K: AsHeaderName,
pub fn entry<K>(&mut self, key: K) -> Result<Entry<'_, T>, InvalidHeaderName> where
K: AsHeaderName,
Gets the given key’s corresponding entry in the map for in-place manipulation.
Examples
let mut map: HeaderMap<u32> = HeaderMap::default();
let headers = &[
"content-length",
"x-hello",
"Content-Length",
"x-world",
];
for &header in headers {
let counter = map.entry(header).unwrap().or_insert(0);
*counter += 1;
}
assert_eq!(map["content-length"], 2);
assert_eq!(map["x-hello"], 1);
sourcepub fn insert<K>(&mut self, key: K, val: T) -> Option<T> where
K: IntoHeaderName,
pub fn insert<K>(&mut self, key: K, val: T) -> Option<T> where
K: IntoHeaderName,
Inserts a key-value pair into the map.
If the map did not previously have this key present, then None
is
returned.
If the map did have this key present, the new value is associated with
the key and all previous values are removed. Note that only a single
one of the previous values is returned. If there are multiple values
that have been previously associated with the key, then the first one is
returned. See insert_mult
on OccupiedEntry
for an API that returns
all values.
The key is not updated, though; this matters for types that can be ==
without being identical.
Examples
let mut map = HeaderMap::new();
assert!(map.insert(HOST, "world".parse().unwrap()).is_none());
assert!(!map.is_empty());
let mut prev = map.insert(HOST, "earth".parse().unwrap()).unwrap();
assert_eq!("world", prev);
sourcepub fn append<K>(&mut self, key: K, value: T) -> bool where
K: IntoHeaderName,
pub fn append<K>(&mut self, key: K, value: T) -> bool where
K: IntoHeaderName,
Inserts a key-value pair into the map.
If the map did not previously have this key present, then false
is
returned.
If the map did have this key present, the new value is pushed to the end
of the list of values currently associated with the key. The key is not
updated, though; this matters for types that can be ==
without being
identical.
Examples
let mut map = HeaderMap::new();
assert!(map.insert(HOST, "world".parse().unwrap()).is_none());
assert!(!map.is_empty());
map.append(HOST, "earth".parse().unwrap());
let values = map.get_all("host");
let mut i = values.iter();
assert_eq!("world", *i.next().unwrap());
assert_eq!("earth", *i.next().unwrap());
sourcepub fn remove<K>(&mut self, key: K) -> Option<T> where
K: AsHeaderName,
pub fn remove<K>(&mut self, key: K) -> Option<T> where
K: AsHeaderName,
Removes a key from the map, returning the value associated with the key.
Returns None
if the map does not contain the key. If there are
multiple values associated with the key, then the first one is returned.
See remove_entry_mult
on OccupiedEntry
for an API that yields all
values.
Examples
let mut map = HeaderMap::new();
map.insert(HOST, "hello.world".parse().unwrap());
let prev = map.remove(HOST).unwrap();
assert_eq!("hello.world", prev);
assert!(map.remove(HOST).is_none());
Trait Implementations
sourceimpl<T> Extend<(HeaderName, T)> for HeaderMap<T>
impl<T> Extend<(HeaderName, T)> for HeaderMap<T>
sourcepub fn extend<I>(&mut self, iter: I) where
I: IntoIterator<Item = (HeaderName, T)>,
pub fn extend<I>(&mut self, iter: I) where
I: IntoIterator<Item = (HeaderName, T)>,
Extends a collection with the contents of an iterator. Read more
sourcefn extend_one(&mut self, item: A)
fn extend_one(&mut self, item: A)
extend_one
)Extends a collection with exactly one element.
sourcefn extend_reserve(&mut self, additional: usize)
fn extend_reserve(&mut self, additional: usize)
extend_one
)Reserves capacity in a collection for the given number of additional elements. Read more
sourceimpl<T> Extend<(Option<HeaderName>, T)> for HeaderMap<T>
impl<T> Extend<(Option<HeaderName>, T)> for HeaderMap<T>
sourcepub fn extend<I>(&mut self, iter: I) where
I: IntoIterator<Item = (Option<HeaderName>, T)>,
pub fn extend<I>(&mut self, iter: I) where
I: IntoIterator<Item = (Option<HeaderName>, T)>,
Extend a HeaderMap
with the contents of another HeaderMap
.
This function expects the yielded items to follow the same structure as
IntoIter
.
Panics
This panics if the first yielded item does not have a HeaderName
.
Examples
let mut map = HeaderMap::new();
map.insert(ACCEPT, "text/plain".parse().unwrap());
map.insert(HOST, "hello.world".parse().unwrap());
let mut extra = HeaderMap::new();
extra.insert(HOST, "foo.bar".parse().unwrap());
extra.insert(COOKIE, "hello".parse().unwrap());
extra.append(COOKIE, "world".parse().unwrap());
map.extend(extra);
assert_eq!(map["host"], "foo.bar");
assert_eq!(map["accept"], "text/plain");
assert_eq!(map["cookie"], "hello");
let v = map.get_all("host");
assert_eq!(1, v.iter().count());
let v = map.get_all("cookie");
assert_eq!(2, v.iter().count());
sourcefn extend_one(&mut self, item: A)
fn extend_one(&mut self, item: A)
extend_one
)Extends a collection with exactly one element.
sourcefn extend_reserve(&mut self, additional: usize)
fn extend_reserve(&mut self, additional: usize)
extend_one
)Reserves capacity in a collection for the given number of additional elements. Read more
sourceimpl<T> FromIterator<(HeaderName, T)> for HeaderMap<T>
impl<T> FromIterator<(HeaderName, T)> for HeaderMap<T>
sourcepub fn from_iter<I>(iter: I) -> HeaderMap<T> where
I: IntoIterator<Item = (HeaderName, T)>,
pub fn from_iter<I>(iter: I) -> HeaderMap<T> where
I: IntoIterator<Item = (HeaderName, T)>,
Creates a value from an iterator. Read more
sourceimpl<'a, K, V, T> HttpTryFrom<&'a HashMap<K, V, RandomState>> for HeaderMap<T> where
K: Eq + Hash,
T: HttpTryFrom<&'a V>,
HeaderName: HttpTryFrom<&'a K>,
impl<'a, K, V, T> HttpTryFrom<&'a HashMap<K, V, RandomState>> for HeaderMap<T> where
K: Eq + Hash,
T: HttpTryFrom<&'a V>,
HeaderName: HttpTryFrom<&'a K>,
Try to convert a HashMap
into a HeaderMap
.
Examples
use std::collections::HashMap;
use http::{HttpTryFrom, header::HeaderMap};
let mut map = HashMap::new();
map.insert("X-Custom-Header".to_string(), "my value".to_string());
let headers: HeaderMap = HttpTryFrom::try_from(&map).expect("valid headers");
assert_eq!(headers["X-Custom-Header"], "my value");
pub fn try_from(
c: &'a HashMap<K, V, RandomState>
) -> Result<HeaderMap<T>, <HeaderMap<T> as HttpTryFrom<&'a HashMap<K, V, RandomState>>>::Error>
sourceimpl<T> HttpTryFrom<HeaderMap<T>> for HeaderMap<T>
impl<T> HttpTryFrom<HeaderMap<T>> for HeaderMap<T>
sourceimpl<'a, K, T> Index<K> for HeaderMap<T> where
K: AsHeaderName,
impl<'a, K, T> Index<K> for HeaderMap<T> where
K: AsHeaderName,
sourceimpl<'a, T> IntoIterator for &'a HeaderMap<T>
impl<'a, T> IntoIterator for &'a HeaderMap<T>
type Item = (&'a HeaderName, &'a T)
type Item = (&'a HeaderName, &'a T)
The type of the elements being iterated over.
sourceimpl<'a, T> IntoIterator for &'a mut HeaderMap<T>
impl<'a, T> IntoIterator for &'a mut HeaderMap<T>
type Item = (&'a HeaderName, &'a mut T)
type Item = (&'a HeaderName, &'a mut T)
The type of the elements being iterated over.
sourceimpl<T> IntoIterator for HeaderMap<T>
impl<T> IntoIterator for HeaderMap<T>
sourcepub fn into_iter(self) -> IntoIter<T>ⓘNotable traits for IntoIter<T>impl<T> Iterator for IntoIter<T> type Item = (Option<HeaderName>, T);
pub fn into_iter(self) -> IntoIter<T>ⓘNotable traits for IntoIter<T>impl<T> Iterator for IntoIter<T> type Item = (Option<HeaderName>, T);
Creates a consuming iterator, that is, one that moves keys and values out of the map in arbitrary order. The map cannot be used after calling this.
For each yielded item that has None
provided for the HeaderName
,
then the associated header name is the same as that of the previously
yielded item. The first yielded item will have HeaderName
set.
Examples
Basic usage.
let mut map = HeaderMap::new();
map.insert(header::CONTENT_LENGTH, "123".parse().unwrap());
map.insert(header::CONTENT_TYPE, "json".parse().unwrap());
let mut iter = map.into_iter();
assert_eq!(iter.next(), Some((Some(header::CONTENT_LENGTH), "123".parse().unwrap())));
assert_eq!(iter.next(), Some((Some(header::CONTENT_TYPE), "json".parse().unwrap())));
assert!(iter.next().is_none());
Multiple values per key.
let mut map = HeaderMap::new();
map.append(header::CONTENT_LENGTH, "123".parse().unwrap());
map.append(header::CONTENT_LENGTH, "456".parse().unwrap());
map.append(header::CONTENT_TYPE, "json".parse().unwrap());
map.append(header::CONTENT_TYPE, "html".parse().unwrap());
map.append(header::CONTENT_TYPE, "xml".parse().unwrap());
let mut iter = map.into_iter();
assert_eq!(iter.next(), Some((Some(header::CONTENT_LENGTH), "123".parse().unwrap())));
assert_eq!(iter.next(), Some((None, "456".parse().unwrap())));
assert_eq!(iter.next(), Some((Some(header::CONTENT_TYPE), "json".parse().unwrap())));
assert_eq!(iter.next(), Some((None, "html".parse().unwrap())));
assert_eq!(iter.next(), Some((None, "xml".parse().unwrap())));
assert!(iter.next().is_none());
type Item = (Option<HeaderName>, T)
type Item = (Option<HeaderName>, T)
The type of the elements being iterated over.
impl<T> Eq for HeaderMap<T> where
T: Eq,
Auto Trait Implementations
impl<T> RefUnwindSafe for HeaderMap<T> where
T: RefUnwindSafe,
impl<T> Send for HeaderMap<T> where
T: Send,
impl<T> Sync for HeaderMap<T> where
T: Sync,
impl<T> Unpin for HeaderMap<T> where
T: Unpin,
impl<T> UnwindSafe for HeaderMap<T> where
T: UnwindSafe,
Blanket Implementations
sourceimpl<T> BorrowMut<T> for T where
T: ?Sized,
impl<T> BorrowMut<T> for T where
T: ?Sized,
const: unstable · sourcepub fn borrow_mut(&mut self) -> &mut T
pub fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more
sourceimpl<Q, K> Equivalent<K> for Q where
Q: Eq + ?Sized,
K: Borrow<Q> + ?Sized,
impl<Q, K> Equivalent<K> for Q where
Q: Eq + ?Sized,
K: Borrow<Q> + ?Sized,
sourcepub fn equivalent(&self, key: &K) -> bool
pub fn equivalent(&self, key: &K) -> bool
Compare self to key
and return true
if they are equal.
sourceimpl<T> ToOwned for T where
T: Clone,
impl<T> ToOwned for T where
T: Clone,
type Owned = T
type Owned = T
The resulting type after obtaining ownership.
sourcepub fn to_owned(&self) -> T
pub fn to_owned(&self) -> T
Creates owned data from borrowed data, usually by cloning. Read more
sourcepub fn clone_into(&self, target: &mut T)
pub fn clone_into(&self, target: &mut T)
toowned_clone_into
)Uses borrowed data to replace owned data, usually by cloning. Read more