Struct tonic::metadata::MetadataMap[][src]

pub struct MetadataMap { /* fields omitted */ }
Expand description

A set of gRPC custom metadata entries.

Examples

Basic usage

let mut map = MetadataMap::new();

map.insert("x-host", "example.com".parse().unwrap());
map.insert("x-number", "123".parse().unwrap());
map.insert_bin("trace-proto-bin", MetadataValue::from_bytes(b"[binary data]"));

assert!(map.contains_key("x-host"));
assert!(!map.contains_key("x-location"));

assert_eq!(map.get("x-host").unwrap(), "example.com");

map.remove("x-host");

assert!(!map.contains_key("x-host"));

Implementations

Create an empty MetadataMap.

The map will be created without any capacity. This function will not allocate.

Examples
let map = MetadataMap::new();

assert!(map.is_empty());
assert_eq!(0, map.capacity());

Convert an HTTP HeaderMap to a MetadataMap

Convert a MetadataMap into a HTTP HeaderMap

Examples
let mut map = MetadataMap::new();
map.insert("x-host", "example.com".parse().unwrap());

let http_map = map.into_headers();

assert_eq!(http_map.get("x-host").unwrap(), "example.com");

Create an empty MetadataMap with the specified capacity.

The returned map will allocate internal storage in order to hold about capacity elements without reallocating. However, this is a “best effort” as there are usage patterns that could cause additional allocations before capacity metadata entries are stored in the map.

More capacity than requested may be allocated.

Examples
let map: MetadataMap = MetadataMap::with_capacity(10);

assert!(map.is_empty());
assert!(map.capacity() >= 10);

Returns the number of metadata entries (ascii and binary) 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 = MetadataMap::new();

assert_eq!(0, map.len());

map.insert("x-host-ip", "127.0.0.1".parse().unwrap());
map.insert_bin("x-host-name-bin", MetadataValue::from_bytes(b"localhost"));

assert_eq!(2, map.len());

map.append("x-host-ip", "text/html".parse().unwrap());

assert_eq!(3, map.len());

Returns the number of keys (ascii and binary) 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 = MetadataMap::new();

assert_eq!(0, map.keys_len());

map.insert("x-host-ip", "127.0.0.1".parse().unwrap());
map.insert_bin("x-host-name-bin", MetadataValue::from_bytes(b"localhost"));

assert_eq!(2, map.keys_len());

map.append("x-host-ip", "text/html".parse().unwrap());

assert_eq!(2, map.keys_len());

Returns true if the map contains no elements.

Examples
let mut map = MetadataMap::new();

assert!(map.is_empty());

map.insert("x-host", "hello.world".parse().unwrap());

assert!(!map.is_empty());

Clears the map, removing all key-value pairs. Keeps the allocated memory for reuse.

Examples
let mut map = MetadataMap::new();
map.insert("x-host", "hello.world".parse().unwrap());

map.clear();
assert!(map.is_empty());
assert!(map.capacity() > 0);

Returns the number of custom metadata entries the map can hold without reallocating.

This number is an approximation as certain usage patterns could cause additional allocations before the returned capacity is filled.

Examples
let mut map = MetadataMap::new();

assert_eq!(0, map.capacity());

map.insert("x-host", "hello.world".parse().unwrap());
assert_eq!(6, map.capacity());

Reserves capacity for at least additional more custom metadata to be inserted into the MetadataMap.

The metadata map may reserve more space to avoid frequent reallocations. Like with with_capacity, this will be a “best effort” to avoid allocations until additional more custom metadata is inserted. Certain usage patterns could cause additional allocations before the number is reached.

Panics

Panics if the new allocation size overflows usize.

Examples
let mut map = MetadataMap::new();
map.reserve(10);

Returns a reference to the value associated with the key. This method is for ascii metadata entries (those whose names don’t end with “-bin”). For binary entries, use get_bin.

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 = MetadataMap::new();
assert!(map.get("x-host").is_none());

map.insert("x-host", "hello".parse().unwrap());
assert_eq!(map.get("x-host").unwrap(), &"hello");
assert_eq!(map.get("x-host").unwrap(), &"hello");

map.append("x-host", "world".parse().unwrap());
assert_eq!(map.get("x-host").unwrap(), &"hello");

// Attempting to read a key of the wrong type fails by not
// finding anything.
map.append_bin("host-bin", MetadataValue::from_bytes(b"world"));
assert!(map.get("host-bin").is_none());
assert!(map.get("host-bin".to_string()).is_none());
assert!(map.get(&("host-bin".to_string())).is_none());

// Attempting to read an invalid key string fails by not
// finding anything.
assert!(map.get("host{}bin").is_none());
assert!(map.get("host{}bin".to_string()).is_none());
assert!(map.get(&("host{}bin".to_string())).is_none());

Like get, but for Binary keys (for example “trace-proto-bin”).

Examples
let mut map = MetadataMap::new();
assert!(map.get_bin("trace-proto-bin").is_none());

map.insert_bin("trace-proto-bin", MetadataValue::from_bytes(b"hello"));
assert_eq!(map.get_bin("trace-proto-bin").unwrap(), &"hello");
assert_eq!(map.get_bin("trace-proto-bin").unwrap(), &"hello");

map.append_bin("trace-proto-bin", MetadataValue::from_bytes(b"world"));
assert_eq!(map.get_bin("trace-proto-bin").unwrap(), &"hello");

// Attempting to read a key of the wrong type fails by not
// finding anything.
map.append("host", "world".parse().unwrap());
assert!(map.get_bin("host").is_none());
assert!(map.get_bin("host".to_string()).is_none());
assert!(map.get_bin(&("host".to_string())).is_none());

// Attempting to read an invalid key string fails by not
// finding anything.
assert!(map.get_bin("host{}-bin").is_none());
assert!(map.get_bin("host{}-bin".to_string()).is_none());
assert!(map.get_bin(&("host{}-bin".to_string())).is_none());

Returns a mutable reference to the value associated with the key. This method is for ascii metadata entries (those whose names don’t end with “-bin”). For binary entries, use get_mut_bin.

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 = MetadataMap::default();
map.insert("x-host", "hello".parse().unwrap());
map.get_mut("x-host").unwrap().set_sensitive(true);

assert!(map.get("x-host").unwrap().is_sensitive());

// Attempting to read a key of the wrong type fails by not
// finding anything.
map.append_bin("host-bin", MetadataValue::from_bytes(b"world"));
assert!(map.get_mut("host-bin").is_none());
assert!(map.get_mut("host-bin".to_string()).is_none());
assert!(map.get_mut(&("host-bin".to_string())).is_none());

// Attempting to read an invalid key string fails by not
// finding anything.
assert!(map.get_mut("host{}").is_none());
assert!(map.get_mut("host{}".to_string()).is_none());
assert!(map.get_mut(&("host{}".to_string())).is_none());

Like get_mut, but for Binary keys (for example “trace-proto-bin”).

Examples
let mut map = MetadataMap::default();
map.insert_bin("trace-proto-bin", MetadataValue::from_bytes(b"hello"));
map.get_bin_mut("trace-proto-bin").unwrap().set_sensitive(true);

assert!(map.get_bin("trace-proto-bin").unwrap().is_sensitive());

// Attempting to read a key of the wrong type fails by not
// finding anything.
map.append("host", "world".parse().unwrap());
assert!(map.get_bin_mut("host").is_none());
assert!(map.get_bin_mut("host".to_string()).is_none());
assert!(map.get_bin_mut(&("host".to_string())).is_none());

// Attempting to read an invalid key string fails by not
// finding anything.
assert!(map.get_bin_mut("host{}-bin").is_none());
assert!(map.get_bin_mut("host{}-bin".to_string()).is_none());
assert!(map.get_bin_mut(&("host{}-bin".to_string())).is_none());

Returns a view of all values associated with a key. This method is for ascii metadata entries (those whose names don’t end with “-bin”). For binary entries, use get_all_bin.

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 = MetadataMap::new();

map.insert("x-host", "hello".parse().unwrap());
map.append("x-host", "goodbye".parse().unwrap());

{
    let view = map.get_all("x-host");

    let mut iter = view.iter();
    assert_eq!(&"hello", iter.next().unwrap());
    assert_eq!(&"goodbye", iter.next().unwrap());
    assert!(iter.next().is_none());
}

// Attempting to read a key of the wrong type fails by not
// finding anything.
map.append_bin("host-bin", MetadataValue::from_bytes(b"world"));
assert!(map.get_all("host-bin").iter().next().is_none());
assert!(map.get_all("host-bin".to_string()).iter().next().is_none());
assert!(map.get_all(&("host-bin".to_string())).iter().next().is_none());

// Attempting to read an invalid key string fails by not
// finding anything.
assert!(map.get_all("host{}").iter().next().is_none());
assert!(map.get_all("host{}".to_string()).iter().next().is_none());
assert!(map.get_all(&("host{}".to_string())).iter().next().is_none());

Like get_all, but for Binary keys (for example “trace-proto-bin”).

Examples
let mut map = MetadataMap::new();

map.insert_bin("trace-proto-bin", MetadataValue::from_bytes(b"hello"));
map.append_bin("trace-proto-bin", MetadataValue::from_bytes(b"goodbye"));

{
    let view = map.get_all_bin("trace-proto-bin");

    let mut iter = view.iter();
    assert_eq!(&"hello", iter.next().unwrap());
    assert_eq!(&"goodbye", iter.next().unwrap());
    assert!(iter.next().is_none());
}

// Attempting to read a key of the wrong type fails by not
// finding anything.
map.append("host", "world".parse().unwrap());
assert!(map.get_all_bin("host").iter().next().is_none());
assert!(map.get_all_bin("host".to_string()).iter().next().is_none());
assert!(map.get_all_bin(&("host".to_string())).iter().next().is_none());

// Attempting to read an invalid key string fails by not
// finding anything.
assert!(map.get_all_bin("host{}-bin").iter().next().is_none());
assert!(map.get_all_bin("host{}-bin".to_string()).iter().next().is_none());
assert!(map.get_all_bin(&("host{}-bin".to_string())).iter().next().is_none());

Returns true if the map contains a value for the specified key. This method works for both ascii and binary entries.

Examples
let mut map = MetadataMap::new();
assert!(!map.contains_key("x-host"));

map.append_bin("host-bin", MetadataValue::from_bytes(b"world"));
map.insert("x-host", "world".parse().unwrap());

// contains_key works for both Binary and Ascii keys:
assert!(map.contains_key("x-host"));
assert!(map.contains_key("host-bin"));

// contains_key returns false for invalid keys:
assert!(!map.contains_key("x{}host"));

An iterator visiting all key-value pairs (both ascii and binary).

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 = MetadataMap::new();

map.insert("x-word", "hello".parse().unwrap());
map.append("x-word", "goodbye".parse().unwrap());
map.insert("x-number", "123".parse().unwrap());

for key_and_value in map.iter() {
    match key_and_value {
        KeyAndValueRef::Ascii(ref key, ref value) =>
            println!("Ascii: {:?}: {:?}", key, value),
        KeyAndValueRef::Binary(ref key, ref value) =>
            println!("Binary: {:?}: {:?}", key, value),
    }
}

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 = MetadataMap::new();

map.insert("x-word", "hello".parse().unwrap());
map.append("x-word", "goodbye".parse().unwrap());
map.insert("x-number", "123".parse().unwrap());

for key_and_value in map.iter_mut() {
    match key_and_value {
        KeyAndMutValueRef::Ascii(key, mut value) =>
            value.set_sensitive(true),
        KeyAndMutValueRef::Binary(key, mut value) =>
            value.set_sensitive(false),
    }
}

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 = MetadataMap::new();

map.insert("x-word", "hello".parse().unwrap());
map.append("x-word", "goodbye".parse().unwrap());
map.insert_bin("x-number-bin", MetadataValue::from_bytes(b"123"));

for key in map.keys() {
    match key {
        KeyRef::Ascii(ref key) =>
            println!("Ascii key: {:?}", key),
        KeyRef::Binary(ref key) =>
            println!("Binary key: {:?}", key),
    }
    println!("{:?}", key);
}

An iterator visiting all values (both ascii and binary).

The iteration order is arbitrary, but consistent across platforms for the same crate version.

Examples
let mut map = MetadataMap::new();

map.insert("x-word", "hello".parse().unwrap());
map.append("x-word", "goodbye".parse().unwrap());
map.insert_bin("x-number-bin", MetadataValue::from_bytes(b"123"));

for value in map.values() {
    match value {
        ValueRef::Ascii(ref value) =>
            println!("Ascii value: {:?}", value),
        ValueRef::Binary(ref value) =>
            println!("Binary value: {:?}", value),
    }
    println!("{:?}", value);
}

An iterator visiting all values mutably.

The iteration order is arbitrary, but consistent across platforms for the same crate version.

Examples
let mut map = MetadataMap::default();

map.insert("x-word", "hello".parse().unwrap());
map.append("x-word", "goodbye".parse().unwrap());
map.insert("x-number", "123".parse().unwrap());

for value in map.values_mut() {
    match value {
        ValueRefMut::Ascii(mut value) =>
            value.set_sensitive(true),
        ValueRefMut::Binary(mut value) =>
            value.set_sensitive(false),
    }
}

Gets the given ascii key’s corresponding entry in the map for in-place manipulation. For binary keys, use entry_bin.

Examples
let mut map = MetadataMap::default();

let headers = &[
    "content-length",
    "x-hello",
    "Content-Length",
    "x-world",
];

for &header in headers {
    let counter = map.entry(header).unwrap().or_insert("".parse().unwrap());
    *counter = format!("{}{}", counter.to_str().unwrap(), "1").parse().unwrap();
}

assert_eq!(map.get("content-length").unwrap(), "11");
assert_eq!(map.get("x-hello").unwrap(), "1");

// Gracefully handles parting invalid key strings
assert!(!map.entry("a{}b").is_ok());

// Attempting to read a key of the wrong type fails by not
// finding anything.
map.append_bin("host-bin", MetadataValue::from_bytes(b"world"));
assert!(!map.entry("host-bin").is_ok());
assert!(!map.entry("host-bin".to_string()).is_ok());
assert!(!map.entry(&("host-bin".to_string())).is_ok());

// Attempting to read an invalid key string fails by not
// finding anything.
assert!(!map.entry("host{}").is_ok());
assert!(!map.entry("host{}".to_string()).is_ok());
assert!(!map.entry(&("host{}".to_string())).is_ok());

Gets the given Binary key’s corresponding entry in the map for in-place manipulation.

Examples
let mut map = MetadataMap::default();

let headers = &[
    "content-length-bin",
    "x-hello-bin",
    "Content-Length-bin",
    "x-world-bin",
];

for &header in headers {
    let counter = map.entry_bin(header).unwrap().or_insert(MetadataValue::from_bytes(b""));
    *counter = MetadataValue::from_bytes(format!("{}{}", str::from_utf8(counter.to_bytes().unwrap().as_ref()).unwrap(), "1").as_bytes());
}

assert_eq!(map.get_bin("content-length-bin").unwrap(), "11");
assert_eq!(map.get_bin("x-hello-bin").unwrap(), "1");

// Attempting to read a key of the wrong type fails by not
// finding anything.
map.append("host", "world".parse().unwrap());
assert!(!map.entry_bin("host").is_ok());
assert!(!map.entry_bin("host".to_string()).is_ok());
assert!(!map.entry_bin(&("host".to_string())).is_ok());

// Attempting to read an invalid key string fails by not
// finding anything.
assert!(!map.entry_bin("host{}-bin").is_ok());
assert!(!map.entry_bin("host{}-bin".to_string()).is_ok());
assert!(!map.entry_bin(&("host{}-bin".to_string())).is_ok());

Inserts an ascii key-value pair into the map. To insert a binary entry, use insert_bin.

This method panics when the given key is a string and it cannot be converted to a MetadataKey.

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 = MetadataMap::new();
assert!(map.insert("x-host", "world".parse().unwrap()).is_none());
assert!(!map.is_empty());

let mut prev = map.insert("x-host", "earth".parse().unwrap()).unwrap();
assert_eq!("world", prev);
let mut map = MetadataMap::new();
// Trying to insert a key that is not valid panics.
map.insert("x{}host", "world".parse().unwrap());
let mut map = MetadataMap::new();
// Trying to insert a key that is binary panics (use insert_bin).
map.insert("x-host-bin", "world".parse().unwrap());

Like insert, but for Binary keys (for example “trace-proto-bin”).

This method panics when the given key is a string and it cannot be converted to a MetadataKey.

Examples
let mut map = MetadataMap::new();
assert!(map.insert_bin("trace-proto-bin", MetadataValue::from_bytes(b"world")).is_none());
assert!(!map.is_empty());

let mut prev = map.insert_bin("trace-proto-bin", MetadataValue::from_bytes(b"earth")).unwrap();
assert_eq!("world", prev);
let mut map = MetadataMap::default();
// Attempting to add a binary metadata entry with an invalid name
map.insert_bin("trace-proto", MetadataValue::from_bytes(b"hello")); // This line panics!
let mut map = MetadataMap::new();
// Trying to insert a key that is not valid panics.
map.insert_bin("x{}host-bin", MetadataValue::from_bytes(b"world")); // This line panics!

Inserts an ascii key-value pair into the map. To insert a binary entry, use append_bin.

This method panics when the given key is a string and it cannot be converted to a MetadataKey.

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 = MetadataMap::new();
assert!(map.insert("x-host", "world".parse().unwrap()).is_none());
assert!(!map.is_empty());

map.append("x-host", "earth".parse().unwrap());

let values = map.get_all("x-host");
let mut i = values.iter();
assert_eq!("world", *i.next().unwrap());
assert_eq!("earth", *i.next().unwrap());
let mut map = MetadataMap::new();
// Trying to append a key that is not valid panics.
map.append("x{}host", "world".parse().unwrap()); // This line panics!
let mut map = MetadataMap::new();
// Trying to append a key that is binary panics (use append_bin).
map.append("x-host-bin", "world".parse().unwrap()); // This line panics!

Like append, but for binary keys (for example “trace-proto-bin”).

This method panics when the given key is a string and it cannot be converted to a MetadataKey.

Examples
let mut map = MetadataMap::new();
assert!(map.insert_bin("trace-proto-bin", MetadataValue::from_bytes(b"world")).is_none());
assert!(!map.is_empty());

map.append_bin("trace-proto-bin", MetadataValue::from_bytes(b"earth"));

let values = map.get_all_bin("trace-proto-bin");
let mut i = values.iter();
assert_eq!("world", *i.next().unwrap());
assert_eq!("earth", *i.next().unwrap());
let mut map = MetadataMap::new();
// Trying to append a key that is not valid panics.
map.append_bin("x{}host-bin", MetadataValue::from_bytes(b"world")); // This line panics!
let mut map = MetadataMap::new();
// Trying to append a key that is ascii panics (use append).
map.append_bin("x-host", MetadataValue::from_bytes(b"world")); // This line panics!

Removes an ascii key from the map, returning the value associated with the key. To remove a binary key, use remove_bin.

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 = MetadataMap::new();
map.insert("x-host", "hello.world".parse().unwrap());

let prev = map.remove("x-host").unwrap();
assert_eq!("hello.world", prev);

assert!(map.remove("x-host").is_none());

// Attempting to remove a key of the wrong type fails by not
// finding anything.
map.append_bin("host-bin", MetadataValue::from_bytes(b"world"));
assert!(map.remove("host-bin").is_none());
assert!(map.remove("host-bin".to_string()).is_none());
assert!(map.remove(&("host-bin".to_string())).is_none());

// Attempting to remove an invalid key string fails by not
// finding anything.
assert!(map.remove("host{}").is_none());
assert!(map.remove("host{}".to_string()).is_none());
assert!(map.remove(&("host{}".to_string())).is_none());

Like remove, but for Binary keys (for example “trace-proto-bin”).

Examples
let mut map = MetadataMap::new();
map.insert_bin("trace-proto-bin", MetadataValue::from_bytes(b"hello.world"));

let prev = map.remove_bin("trace-proto-bin").unwrap();
assert_eq!("hello.world", prev);

assert!(map.remove_bin("trace-proto-bin").is_none());

// Attempting to remove a key of the wrong type fails by not
// finding anything.
map.append("host", "world".parse().unwrap());
assert!(map.remove_bin("host").is_none());
assert!(map.remove_bin("host".to_string()).is_none());
assert!(map.remove_bin(&("host".to_string())).is_none());

// Attempting to remove an invalid key string fails by not
// finding anything.
assert!(map.remove_bin("host{}-bin").is_none());
assert!(map.remove_bin("host{}-bin".to_string()).is_none());
assert!(map.remove_bin(&("host{}-bin".to_string())).is_none());

Trait Implementations

Returns a copy of the value. Read more

Performs copy-assignment from source. Read more

Formats the value using the given formatter. Read more

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

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Performs the conversion.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

Performs the conversion.

The resulting type after obtaining ownership.

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

🔬 This is a nightly-only experimental API. (toowned_clone_into #41263)

recently added

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

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more