Struct HeaderMap

Source
pub struct HeaderMap { /* private fields */ }
Expand description

This is a multimap representing HTTP headers. Not that this is not a true hashmap, as the count of headers is generally too small to be worth representing as a map.

Implementations§

Source§

impl HeaderMap

Source

pub fn new() -> Self

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());
Source

pub fn with_capacity(capacity: usize) -> Self

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());
Source

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());
Source

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);
Source

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);
Source

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());
Source

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());
Source

pub fn append(&mut self, name: impl AsRef<str>, value: impl Into<String>)

Appends a key-value pair into the map.

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());
Source

pub fn append_static( &mut self, name: impl AsRef<str>, value: impl Into<&'static str>, )

Appends a key-value pair into the map with a static value.

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());
Source

pub fn append_typed<H: TypedHeader>(&mut self, header: &H)

Appends a typed key-value pair into the map.

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());
Source

pub fn insert( &mut self, name: impl AsRef<str>, value: impl Into<String>, ) -> Option<Cow<'static, str>>

Inserts a key-value pair into the map.

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);
Source

pub fn insert_static( &mut self, name: impl AsRef<str>, value: impl Into<&'static str>, ) -> Option<Cow<'static, str>>

Inserts a key-value pair into the map with a static value.

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);
Source

pub fn insert_typed<H: TypedHeader>( &mut self, header: &H, ) -> Option<Cow<'static, str>>

Inserts a typed key-value pair into the map.

Note that if the header is a TypedHeader with multiple values returned, only the last value is used.

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);
Source

pub fn contains_key(&self, name: &str) -> bool

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"));
Source

pub fn get(&self, name: &str) -> Option<&str>

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");
Source

pub fn get_typed<H: TypedHeader>(&self) -> Option<H>

Returns a reference to the value associated with the key.

The key is defined with an associated type referenced a TypedHeader. If the header is malformed, None is transparently returned

Note that this causes an allocation depending on the implementation of the TypedHeader.

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");

map.append(HOST, "world".parse().unwrap());
assert_eq!(map.get::<Host>().unwrap(), &"hello");
Source

pub fn get_all<'a>(&'a self, name: &'a str) -> impl Iterator<Item = &'a str>

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());
Source

pub fn get_all_typed<'a, H: TypedHeader>( &'a self, ) -> impl Iterator<Item = H> + 'a

Returns a view of all values associated with a key.

The key is defined with an associated type referenced a TypedHeader. If the header is malformed, it is skipped.

Note that this causes an allocation for each header value returned depending on the implementation of the TypedHeader.

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());
Source

pub fn get_mut(&mut self, name: &str) -> Option<&mut Cow<'static, str>>

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");
Source

pub fn remove(&mut self, name: impl AsRef<str>) -> Vec<Cow<'static, str>>

Removes a key from the map, returning the value associated with the key.

Returns an empty vec if the map does not contain the key. If there are multiple values associated with the key, then all are returned.

§Examples
let mut map = HeaderMap::new();
map.insert(HOST, "hello.world".parse().unwrap());

let prev = map.remove(HOST);
assert_eq!("hello.world", &prev[0]);

assert!(map.remove(HOST).is_empty());
Source

pub fn iter(&self) -> impl Iterator<Item = (&str, &str)>

An iterator visiting all key-value pairs.

The iteration order is in insertion order.

§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);
}
Source

pub fn grouped(&self) -> Vec<(&str, SmallVec<[&str; 2]>)>

Trait Implementations§

Source§

impl Clone for HeaderMap

Source§

fn clone(&self) -> HeaderMap

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for HeaderMap

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for HeaderMap

Source§

fn default() -> HeaderMap

Returns the “default value” for a type. Read more
Source§

impl<K: Into<Cow<'static, str>>, V: Into<String>> Extend<(K, V)> for HeaderMap

Source§

fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T)

Extends a collection with the contents of an iterator. Read more
Source§

fn extend_one(&mut self, item: A)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
Source§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
Source§

impl Extractor for &HeaderMap

Source§

fn get(&self, key: &str) -> Option<&str>

Get a value for a key from the HeaderMap. If the value is not valid ASCII, returns None.

Source§

fn keys(&self) -> Vec<&str>

Collect all the keys from the HeaderMap.

Source§

impl<K: Into<Cow<'static, str>>, V: Into<String>> FromIterator<(K, V)> for HeaderMap

Source§

fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> Self

Creates a value from an iterator. Read more
Source§

impl<K: Into<Cow<'static, str>>> Index<K> for HeaderMap

Source§

type Output = str

The returned type after indexing.
Source§

fn index(&self, index: K) -> &Self::Output

Performs the indexing (container[index]) operation. Read more
Source§

impl Injector for &mut HeaderMap

Source§

fn set(&mut self, key: &str, value: String)

Add a key and value to the underlying data.
Source§

impl Into<HeaderMap> for HeaderMap

Source§

fn into(self) -> HeaderMap

Converts this type into the (usually inferred) input type.
Source§

impl<'a> IntoIterator for &'a HeaderMap

Source§

type Item = &'a (Cow<'static, str>, Cow<'static, str>)

The type of the elements being iterated over.
Source§

type IntoIter = Iter<'a, (Cow<'static, str>, Cow<'static, str>)>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl<'a> IntoIterator for &'a mut HeaderMap

Source§

type Item = &'a mut (Cow<'static, str>, Cow<'static, str>)

The type of the elements being iterated over.
Source§

type IntoIter = IterMut<'a, (Cow<'static, str>, Cow<'static, str>)>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl IntoIterator for HeaderMap

Source§

type Item = (Cow<'static, str>, Cow<'static, str>)

The type of the elements being iterated over.
Source§

type IntoIter = IntoIter<<HeaderMap as IntoIterator>::Item>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl PartialEq for HeaderMap

Source§

fn eq(&self, other: &HeaderMap) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl TryFrom<HeaderMap> for HeaderMap

Source§

type Error = HeaderMapConvertError

The type returned in the event of a conversion error.
Source§

fn try_from(value: HeaderMap) -> Result<Self, Self::Error>

Performs the conversion.
Source§

impl Eq for HeaderMap

Source§

impl StructuralPartialEq for HeaderMap

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FutureExt for T

Source§

fn with_context(self, otel_cx: Context) -> WithContext<Self>

Attaches the provided Context to this type, returning a WithContext wrapper. Read more
Source§

fn with_current_context(self) -> WithContext<Self>

Attaches the current Context to this type, returning a WithContext wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.