pub trait HashMapExt<K, V, S> {
// Required methods
fn cleared(self) -> Self;
fn inserted(self, k: K, v: V) -> Self
where K: Eq + Hash,
S: BuildHasher;
fn removed<Q>(self, k: &Q) -> Self
where K: Eq + Hash + Borrow<Q>,
S: BuildHasher,
Q: Eq + Hash;
fn retained<F>(self, f: F) -> Self
where K: Eq + Hash,
S: BuildHasher,
F: FnMut(&K, &mut V) -> bool;
fn shrinked_to_fit(self) -> Self
where K: Eq + Hash,
S: BuildHasher;
}
Expand description
Extension trait that contains functions that allow for chaining of
HashMap
functions.
Before:
use std::collections::HashMap;
let mut map = HashMap::new();
map.insert(37, "a");
map.insert(38, "b");
map.remove(&37);
assert_eq!(map.get(&37), None);
assert_eq!(map.get(&38), Some(&"b"));
After:
use fenn::HashMapExt;
use std::collections::HashMap;
let map = HashMap::new()
.inserted(37, "a")
.inserted(38, "b")
.removed(&37);
assert_eq!(map.get(&37), None);
assert_eq!(map.get(&38), Some(&"b"));
Required Methods§
Sourcefn cleared(self) -> Self
fn cleared(self) -> Self
Clears the map, removing all key-value pairs. Keeps the allocated memory for reuse.
§Examples
use fenn::HashMapExt;
use std::collections::HashMap;
let a = HashMap::new()
.inserted(1, "a")
.cleared();
assert!(a.is_empty());
Sourcefn inserted(self, k: K, v: V) -> Self
fn inserted(self, k: K, v: V) -> Self
Inserts a key-value pair into the map.
If the map did have this key present, the value is updated. The key is
not updated, though; this matters for types that can be ==
without
being identical.
§Warning
Unlike the standard HashMap::insert
that this wraps, this function ignores any returned values.
§Examples
use fenn::HashMapExt;
use std::collections::HashMap;
let map = HashMap::new()
.inserted(37, "a");
assert_eq!(map[&37], "a");
assert_eq!(map.is_empty(), false);
Sourcefn retained<F>(self, f: F) -> Self
fn retained<F>(self, f: F) -> Self
Retains only the elements specified by the predicate.
In other words, remove all pairs (k, v)
such that f(&k, &mut v)
returns false
.
§Examples
use fenn::HashMapExt;
use std::collections::HashMap;
let map = (0..8).map(|x|(x, x * 10)).collect::<HashMap<i32, i32>>()
.retained(|&k, _| k % 2 == 0);
assert_eq!(map.len(), 4);
Sourcefn shrinked_to_fit(self) -> Self
fn shrinked_to_fit(self) -> Self
Shrinks the capacity of the map as much as possible. It will drop down as much as possible while maintaining the internal rules and possibly leaving some space in accordance with the resize policy.
§Examples
use fenn::HashMapExt;
use std::collections::HashMap;
let map: HashMap<i32, i32> = HashMap::with_capacity(100)
.inserted(1, 2)
.inserted(3, 4)
.shrinked_to_fit();
assert!(map.capacity() >= 2);
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.