pub struct StableMap<K, V, S = DefaultHashBuilder> { /* private fields */ }
Expand description
A hash map with temporarily-stable indices.
This is a small wrapper around a HashMap<K, V> that splits the map into two parts:
HashMap<K, usize>
Vec<V>
The index of for each key stays the same unless the key is removed from the map or the map is explicitly compacted.
§Example
Consider a service that allows clients to register callbacks:
use {
parking_lot::Mutex,
stable_map::StableMap,
std::sync::{
atomic::{AtomicUsize, Ordering::Relaxed},
Arc,
},
};
pub struct Service {
next_callback_id: AtomicUsize,
callbacks: Mutex<StableMap<CallbackId, Arc<dyn Callback>>>,
}
pub trait Callback {
fn run(&self);
}
#[derive(Copy, Clone, Eq, PartialEq, Debug, Hash)]
pub struct CallbackId(usize);
impl Service {
pub fn register_callback(&self, callback: Arc<dyn Callback>) -> CallbackId {
let id = CallbackId(self.next_callback_id.fetch_add(1, Relaxed));
self.callbacks.lock().insert(id, callback);
id
}
pub fn unregister_callback(&self, id: CallbackId) {
self.callbacks.lock().remove(&id);
}
fn execute_callbacks(&self) {
let mut callbacks = self.callbacks.lock();
for i in 0..callbacks.index_len() {
if let Some(callback) = callbacks.get_by_index(i).cloned() {
// Drop the mutex so that the callback can itself call
// register_callback or unregister_callback.
drop(callbacks);
// Run the callback.
callback.run();
// Re-acquire the mutex.
callbacks = self.callbacks.lock();
}
}
// Compact the map so that index_len does not grow much larger than the actual
// size of the map.
callbacks.compact();
}
}
Implementations§
Source§impl<K, V> StableMap<K, V, DefaultHashBuilder>
impl<K, V> StableMap<K, V, DefaultHashBuilder>
Sourcepub fn new() -> Self
pub fn new() -> Self
Creates an empty StableMap
.
The map is initially created with a capacity of 0, so it will not allocate until it is first inserted into.
§Examples
use stable_map::StableMap;
let mut map: StableMap<&str, i32> = StableMap::new();
assert_eq!(map.len(), 0);
assert_eq!(map.capacity(), 0);
Sourcepub fn with_capacity(capacity: usize) -> Self
pub fn with_capacity(capacity: usize) -> Self
Creates an empty StableMap
with the specified capacity.
The map will be able to hold at least capacity
elements without
reallocating. If capacity
is 0, the map will not allocate.
§Examples
use stable_map::StableMap;
let mut map: StableMap<&str, i32> = StableMap::with_capacity(10);
assert_eq!(map.len(), 0);
assert!(map.capacity() >= 10);
Source§impl<K, V, S> StableMap<K, V, S>
impl<K, V, S> StableMap<K, V, S>
Sourcepub fn capacity(&self) -> usize
pub fn capacity(&self) -> usize
Returns the number of elements the map can hold without reallocating.
This number is a lower bound; the StableMap<K, V>
might be able to hold
more, but is guaranteed to be able to hold at least this many.
§Examples
use stable_map::StableMap;
let map: StableMap<i32, i32> = StableMap::with_capacity(100);
assert_eq!(map.len(), 0);
assert!(map.capacity() >= 100);
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
use stable_map::StableMap;
let mut a = StableMap::new();
a.insert(1, "a");
let capacity_before_clear = a.capacity();
a.clear();
// Map is empty.
assert!(a.is_empty());
// But map capacity is equal to old one.
assert_eq!(a.capacity(), capacity_before_clear);
Sourcepub fn contains_key<Q>(&self, key: &Q) -> bool
pub fn contains_key<Q>(&self, key: &Q) -> bool
Returns true
if the map contains a value for the specified key.
The key may be any borrowed form of the map’s key type, but
Hash
and Eq
on the borrowed form must match those for
the key type.
§Examples
use stable_map::StableMap;
let mut map = StableMap::new();
map.insert(1, "a");
assert_eq!(map.contains_key(&1), true);
assert_eq!(map.contains_key(&2), false);
Sourcepub fn drain(&mut self) -> Drain<'_, K, V> ⓘ
pub fn drain(&mut self) -> Drain<'_, K, V> ⓘ
Clears the map, returning all key-value pairs as an iterator. Keeps the allocated memory for reuse.
If the returned iterator is dropped before being fully consumed, it drops the remaining key-value pairs. The returned iterator keeps a mutable borrow on the vector to optimize its implementation.
§Examples
use stable_map::StableMap;
let mut a = StableMap::new();
a.insert(1, "a");
a.insert(2, "b");
let capacity_before_drain = a.capacity();
for (k, v) in a.drain().take(1) {
assert!(k == 1 || k == 2);
assert!(v == "a" || v == "b");
}
// As we can see, the map is empty and contains no element.
assert!(a.is_empty() && a.len() == 0);
// But map capacity is equal to old one.
assert_eq!(a.capacity(), capacity_before_drain);
let mut a = StableMap::new();
a.insert(1, "a");
a.insert(2, "b");
{ // Iterator is dropped without being consumed.
let d = a.drain();
}
// But the map is empty even if we do not use Drain iterator.
assert!(a.is_empty());
Sourcepub fn entry(&mut self, key: K) -> Entry<'_, K, V, S>
pub fn entry(&mut self, key: K) -> Entry<'_, K, V, S>
Gets the given key’s corresponding entry in the map for in-place manipulation.
§Examples
use stable_map::StableMap;
let mut letters = StableMap::new();
for ch in "a short treatise on fungi".chars() {
let counter = letters.entry(ch).or_insert(0);
*counter += 1;
}
assert_eq!(letters[&'s'], 2);
assert_eq!(letters[&'t'], 3);
assert_eq!(letters[&'u'], 1);
assert_eq!(letters.get(&'y'), None);
Sourcepub fn entry_ref<'b, Q>(&mut self, key: &'b Q) -> EntryRef<'_, 'b, K, Q, V, S>
pub fn entry_ref<'b, Q>(&mut self, key: &'b Q) -> EntryRef<'_, 'b, K, Q, V, S>
Gets the given key’s corresponding entry by reference in the map for in-place manipulation.
§Examples
use stable_map::StableMap;
let mut words: StableMap<String, usize> = StableMap::new();
let source = ["poneyland", "horseyland", "poneyland", "poneyland"];
for (i, &s) in source.iter().enumerate() {
let counter = words.entry_ref(s).or_insert(0);
*counter += 1;
}
assert_eq!(words["poneyland"], 3);
assert_eq!(words["horseyland"], 1);
Sourcepub fn extract_if<F>(
&mut self,
f: F,
) -> impl FusedIterator<Item = (K, V)> + use<'_, K, V, F, S>
pub fn extract_if<F>( &mut self, f: F, ) -> impl FusedIterator<Item = (K, V)> + use<'_, K, V, F, S>
Drains elements which are true under the given predicate, and returns an iterator over the removed items.
In other words, move all pairs (k, v)
such that f(&k, &mut v)
returns true
out
into another iterator.
Note that extract_if
lets you mutate every value in the filter closure, regardless of
whether you choose to keep or remove it.
If the returned ExtractIf
is not exhausted, e.g. because it is dropped without iterating
or the iteration short-circuits, then the remaining elements will be retained.
Use retain()
with a negated predicate if you do not need the returned iterator.
Keeps the allocated memory for reuse.
§Examples
use stable_map::StableMap;
let mut map: StableMap<i32, i32> = (0..8).map(|x| (x, x)).collect();
let drained: StableMap<i32, i32> = map.extract_if(|k, _v| k % 2 == 0).collect();
let mut evens = drained.keys().cloned().collect::<Vec<_>>();
let mut odds = map.keys().cloned().collect::<Vec<_>>();
evens.sort();
odds.sort();
assert_eq!(evens, vec![0, 2, 4, 6]);
assert_eq!(odds, vec![1, 3, 5, 7]);
let mut map: StableMap<i32, i32> = (0..8).map(|x| (x, x)).collect();
{ // Iterator is dropped without being consumed.
let d = map.extract_if(|k, _v| k % 2 != 0);
}
// ExtractIf was not exhausted, therefore no elements were drained.
assert_eq!(map.len(), 8);
Sourcepub fn get<Q>(&self, key: &Q) -> Option<&V>
pub fn get<Q>(&self, key: &Q) -> Option<&V>
Returns a reference to the value corresponding to the key.
The key may be any borrowed form of the map’s key type, but
Hash
and Eq
on the borrowed form must match those for
the key type.
§Examples
use stable_map::StableMap;
let mut map = StableMap::new();
map.insert(1, "a");
assert_eq!(map.get(&1), Some(&"a"));
assert_eq!(map.get(&2), None);
Sourcepub fn get_key_value<Q>(&self, key: &Q) -> Option<(&K, &V)>
pub fn get_key_value<Q>(&self, key: &Q) -> Option<(&K, &V)>
Returns the key-value pair corresponding to the supplied key.
The supplied key may be any borrowed form of the map’s key type, but
Hash
and Eq
on the borrowed form must match those for
the key type.
§Examples
use stable_map::StableMap;
let mut map = StableMap::new();
map.insert(1, "a");
assert_eq!(map.get_key_value(&1), Some((&1, &"a")));
assert_eq!(map.get_key_value(&2), None);
Sourcepub fn get_key_value_mut<Q>(&mut self, key: &Q) -> Option<(&K, &mut V)>
pub fn get_key_value_mut<Q>(&mut self, key: &Q) -> Option<(&K, &mut V)>
Returns the key-value pair corresponding to the supplied key.
The supplied key may be any borrowed form of the map’s key type, but
Hash
and Eq
on the borrowed form must match those for
the key type.
§Examples
use stable_map::StableMap;
let mut map = StableMap::new();
map.insert(1, "a");
assert_eq!(map.get_key_value(&1), Some((&1, &"a")));
assert_eq!(map.get_key_value(&2), None);
Sourcepub fn get_many_key_value_mut<Q, const N: usize>(
&mut self,
ks: [&Q; N],
) -> [Option<(&K, &mut V)>; N]
pub fn get_many_key_value_mut<Q, const N: usize>( &mut self, ks: [&Q; N], ) -> [Option<(&K, &mut V)>; N]
Attempts to get mutable references to N
values in the map at once, with immutable
references to the corresponding keys.
Returns an array of length N
with the results of each query. For soundness, at most one
mutable reference will be returned to any value. None
will be used if the key is missing.
§Panics
Panics if any keys are overlapping.
§Examples
use stable_map::StableMap;
let mut libraries = StableMap::new();
libraries.insert("Bodleian Library".to_string(), 1602);
libraries.insert("Athenæum".to_string(), 1807);
libraries.insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691);
libraries.insert("Library of Congress".to_string(), 1800);
let got = libraries.get_many_key_value_mut([
"Bodleian Library",
"Herzogin-Anna-Amalia-Bibliothek",
]);
assert_eq!(
got,
[
Some((&"Bodleian Library".to_string(), &mut 1602)),
Some((&"Herzogin-Anna-Amalia-Bibliothek".to_string(), &mut 1691)),
],
);
// Missing keys result in None
let got = libraries.get_many_key_value_mut([
"Bodleian Library",
"Gewandhaus",
]);
assert_eq!(got, [Some((&"Bodleian Library".to_string(), &mut 1602)), None]);
use stable_map::StableMap;
let mut libraries = StableMap::new();
libraries.insert("Bodleian Library".to_string(), 1602);
libraries.insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691);
// Duplicate keys result in panic!
let got = libraries.get_many_key_value_mut([
"Bodleian Library",
"Herzogin-Anna-Amalia-Bibliothek",
"Herzogin-Anna-Amalia-Bibliothek",
]);
Sourcepub unsafe fn get_many_key_value_unchecked_mut<Q, const N: usize>(
&mut self,
ks: [&Q; N],
) -> [Option<(&K, &mut V)>; N]
pub unsafe fn get_many_key_value_unchecked_mut<Q, const N: usize>( &mut self, ks: [&Q; N], ) -> [Option<(&K, &mut V)>; N]
Attempts to get mutable references to N
values in the map at once, with immutable
references to the corresponding keys, without validating that the values are unique.
Returns an array of length N
with the results of each query. None
will be returned if
any of the keys are missing.
For a safe alternative see get_many_key_value_mut
.
§Safety
Calling this method with overlapping keys is undefined behavior even if the resulting references are not used.
§Examples
use stable_map::StableMap;
let mut libraries = StableMap::new();
libraries.insert("Bodleian Library".to_string(), 1602);
libraries.insert("Athenæum".to_string(), 1807);
libraries.insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691);
libraries.insert("Library of Congress".to_string(), 1800);
let got = libraries.get_many_key_value_mut([
"Bodleian Library",
"Herzogin-Anna-Amalia-Bibliothek",
]);
assert_eq!(
got,
[
Some((&"Bodleian Library".to_string(), &mut 1602)),
Some((&"Herzogin-Anna-Amalia-Bibliothek".to_string(), &mut 1691)),
],
);
// Missing keys result in None
let got = libraries.get_many_key_value_mut([
"Bodleian Library",
"Gewandhaus",
]);
assert_eq!(
got,
[
Some((&"Bodleian Library".to_string(), &mut 1602)),
None,
],
);
Sourcepub fn get_many_mut<Q, const N: usize>(
&mut self,
ks: [&Q; N],
) -> [Option<&mut V>; N]
pub fn get_many_mut<Q, const N: usize>( &mut self, ks: [&Q; N], ) -> [Option<&mut V>; N]
Attempts to get mutable references to N
values in the map at once.
Returns an array of length N
with the results of each query. For soundness, at most one
mutable reference will be returned to any value. None
will be used if the key is missing.
§Panics
Panics if any keys are overlapping.
§Examples
use stable_map::StableMap;
let mut libraries = StableMap::new();
libraries.insert("Bodleian Library".to_string(), 1602);
libraries.insert("Athenæum".to_string(), 1807);
libraries.insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691);
libraries.insert("Library of Congress".to_string(), 1800);
// Get Athenæum and Bodleian Library
let [Some(a), Some(b)] = libraries.get_many_mut([
"Athenæum",
"Bodleian Library",
]) else { panic!() };
// Assert values of Athenæum and Library of Congress
let got = libraries.get_many_mut([
"Athenæum",
"Library of Congress",
]);
assert_eq!(
got,
[
Some(&mut 1807),
Some(&mut 1800),
],
);
// Missing keys result in None
let got = libraries.get_many_mut([
"Athenæum",
"New York Public Library",
]);
assert_eq!(
got,
[
Some(&mut 1807),
None
]
);
use stable_map::StableMap;
let mut libraries = StableMap::new();
libraries.insert("Athenæum".to_string(), 1807);
// Duplicate keys panic!
let got = libraries.get_many_mut([
"Athenæum",
"Athenæum",
]);
Sourcepub unsafe fn get_many_unchecked_mut<Q, const N: usize>(
&mut self,
ks: [&Q; N],
) -> [Option<&mut V>; N]
pub unsafe fn get_many_unchecked_mut<Q, const N: usize>( &mut self, ks: [&Q; N], ) -> [Option<&mut V>; N]
Attempts to get mutable references to N
values in the map at once, without validating that
the values are unique.
Returns an array of length N
with the results of each query. None
will be used if
the key is missing.
For a safe alternative see get_many_mut
.
§Safety
Calling this method with overlapping keys is undefined behavior even if the resulting references are not used.
§Examples
use stable_map::StableMap;
let mut libraries = StableMap::new();
libraries.insert("Bodleian Library".to_string(), 1602);
libraries.insert("Athenæum".to_string(), 1807);
libraries.insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691);
libraries.insert("Library of Congress".to_string(), 1800);
// SAFETY: The keys do not overlap.
let [Some(a), Some(b)] = (unsafe { libraries.get_many_unchecked_mut([
"Athenæum",
"Bodleian Library",
]) }) else { panic!() };
// SAFETY: The keys do not overlap.
let got = unsafe { libraries.get_many_unchecked_mut([
"Athenæum",
"Library of Congress",
]) };
assert_eq!(
got,
[
Some(&mut 1807),
Some(&mut 1800),
],
);
// SAFETY: The keys do not overlap.
let got = unsafe { libraries.get_many_unchecked_mut([
"Athenæum",
"New York Public Library",
]) };
// Missing keys result in None
assert_eq!(got, [Some(&mut 1807), None]);
Sourcepub fn get_mut<Q>(&mut self, key: &Q) -> Option<&mut V>
pub fn get_mut<Q>(&mut self, key: &Q) -> Option<&mut V>
Returns a mutable reference to the value corresponding to the key.
The key may be any borrowed form of the map’s key type, but
Hash
and Eq
on the borrowed form must match those for
the key type.
§Examples
use stable_map::StableMap;
let mut map = StableMap::new();
map.insert(1, "a");
if let Some(x) = map.get_mut(&1) {
*x = "b";
}
assert_eq!(map[&1], "b");
assert_eq!(map.get_mut(&2), None);
Sourcepub fn hasher(&self) -> &S
pub fn hasher(&self) -> &S
Returns a reference to the map’s BuildHasher
.
§Examples
use hashbrown::DefaultHashBuilder;
use stable_map::StableMap;
let hasher = DefaultHashBuilder::default();
let map: StableMap<i32, i32> = StableMap::with_hasher(hasher);
let hasher: &DefaultHashBuilder = map.hasher();
Sourcepub fn insert(&mut self, key: K, value: V) -> Option<V>
pub fn insert(&mut self, key: K, value: V) -> Option<V>
Inserts a key-value pair into the map.
If the map did not have this key present, None
is returned.
If the map did have this key present, the value is updated, and the old
value is returned. The key is not updated, though; this matters for
types that can be ==
without being identical. See the std::collections
module-level documentation for more.
§Examples
use stable_map::StableMap;
let mut map = StableMap::new();
assert_eq!(map.insert(37, "a"), None);
assert_eq!(map.is_empty(), false);
map.insert(37, "b");
assert_eq!(map.insert(37, "c"), Some("b"));
assert_eq!(map[&37], "c");
Sourcepub unsafe fn insert_unique_unchecked(
&mut self,
key: K,
value: V,
) -> (&K, &mut V)
pub unsafe fn insert_unique_unchecked( &mut self, key: K, value: V, ) -> (&K, &mut V)
Insert a key-value pair into the map without checking if the key already exists in the map.
This operation is faster than regular insert, because it does not perform lookup before insertion.
This operation is useful during initial population of the map. For example, when constructing a map from another map, we know that keys are unique.
Returns a reference to the key and value just inserted.
§Safety
This operation is safe if a key does not exist in the map.
However, if a key exists in the map already, the behavior is unspecified: this operation may panic, loop forever, or any following operation with the map may panic, loop forever or return arbitrary result.
That said, this operation (and following operations) are guaranteed to not violate memory safety.
However this operation is still unsafe because the resulting StableMap
may be passed to unsafe code which does expect the map to behave
correctly, and would cause unsoundness as a result.
§Examples
use stable_map::StableMap;
let mut map1 = StableMap::new();
assert_eq!(map1.insert(1, "a"), None);
assert_eq!(map1.insert(2, "b"), None);
assert_eq!(map1.insert(3, "c"), None);
assert_eq!(map1.len(), 3);
let mut map2 = StableMap::new();
for (key, value) in map1.into_iter() {
unsafe {
map2.insert_unique_unchecked(key, value);
}
}
let (key, value) = unsafe { map2.insert_unique_unchecked(4, "d") };
assert_eq!(key, &4);
assert_eq!(value, &mut "d");
*value = "e";
assert_eq!(map2[&1], "a");
assert_eq!(map2[&2], "b");
assert_eq!(map2[&3], "c");
assert_eq!(map2[&4], "e");
assert_eq!(map2.len(), 4);
Sourcepub fn into_keys(self) -> IntoKeys<K> ⓘ
pub fn into_keys(self) -> IntoKeys<K> ⓘ
Creates a consuming iterator visiting all the keys in arbitrary order.
The map cannot be used after calling this.
The iterator element type is K
.
§Examples
use stable_map::StableMap;
let mut map = StableMap::new();
map.insert("a", 1);
map.insert("b", 2);
map.insert("c", 3);
let mut vec: Vec<&str> = map.into_keys().collect();
// The `IntoKeys` iterator produces keys in arbitrary order, so the
// keys must be sorted to test them against a sorted array.
vec.sort_unstable();
assert_eq!(vec, ["a", "b", "c"]);
Sourcepub fn into_values(self) -> IntoValues<K, V> ⓘ
pub fn into_values(self) -> IntoValues<K, V> ⓘ
Creates a consuming iterator visiting all the values in arbitrary order.
The map cannot be used after calling this.
The iterator element type is V
.
§Examples
use stable_map::StableMap;
let mut map = StableMap::new();
map.insert("a", 1);
map.insert("b", 2);
map.insert("c", 3);
let mut vec: Vec<i32> = map.into_values().collect();
// The `IntoValues` iterator produces values in arbitrary order, so
// the values must be sorted to test them against a sorted array.
vec.sort_unstable();
assert_eq!(vec, [1, 2, 3]);
Sourcepub fn is_empty(&self) -> bool
pub fn is_empty(&self) -> bool
Returns true
if the map contains no elements.
§Examples
use stable_map::StableMap;
let mut a = StableMap::new();
assert!(a.is_empty());
a.insert(1, "a");
assert!(!a.is_empty());
Sourcepub fn is_not_empty(&self) -> bool
pub fn is_not_empty(&self) -> bool
Returns true
if the map contains elements.
§Examples
use stable_map::StableMap;
let mut a = StableMap::new();
assert!(!a.is_not_empty());
a.insert(1, "a");
assert!(a.is_not_empty());
Sourcepub fn iter(&self) -> Iter<'_, K, V> ⓘ
pub fn iter(&self) -> Iter<'_, K, V> ⓘ
An iterator visiting all key-value pairs in arbitrary order.
The iterator element type is (&'a K, &'a V)
.
§Examples
use stable_map::StableMap;
let mut map = StableMap::new();
map.insert("a", 1);
map.insert("b", 2);
map.insert("c", 3);
assert_eq!(map.len(), 3);
let mut vec: Vec<(&str, i32)> = Vec::new();
for (key, val) in map.iter() {
println!("key: {} val: {}", key, val);
vec.push((*key, *val));
}
// The `Iter` iterator produces items in arbitrary order, so the
// items must be sorted to test them against a sorted array.
vec.sort_unstable();
assert_eq!(vec, [("a", 1), ("b", 2), ("c", 3)]);
assert_eq!(map.len(), 3);
Sourcepub fn iter_mut(&mut self) -> IterMut<'_, K, V> ⓘ
pub fn iter_mut(&mut self) -> IterMut<'_, K, V> ⓘ
An iterator visiting all key-value pairs in arbitrary order,
with mutable references to the values.
The iterator element type is (&'a K, &'a mut V)
.
§Examples
use stable_map::StableMap;
let mut map = StableMap::new();
map.insert("a", 1);
map.insert("b", 2);
map.insert("c", 3);
// Update all values
for (_, val) in map.iter_mut() {
*val *= 2;
}
assert_eq!(map.len(), 3);
let mut vec: Vec<(&str, i32)> = Vec::new();
for (key, val) in &map {
println!("key: {} val: {}", key, val);
vec.push((*key, *val));
}
// The `Iter` iterator produces items in arbitrary order, so the
// items must be sorted to test them against a sorted array.
vec.sort_unstable();
assert_eq!(vec, [("a", 2), ("b", 4), ("c", 6)]);
assert_eq!(map.len(), 3);
Sourcepub fn keys(&self) -> Keys<'_, K> ⓘ
pub fn keys(&self) -> Keys<'_, K> ⓘ
An iterator visiting all keys in arbitrary order.
The iterator element type is &'a K
.
§Examples
use stable_map::StableMap;
let mut map = StableMap::new();
map.insert("a", 1);
map.insert("b", 2);
map.insert("c", 3);
assert_eq!(map.len(), 3);
let mut vec: Vec<&str> = Vec::new();
for key in map.keys() {
println!("{}", key);
vec.push(*key);
}
// The `Keys` iterator produces keys in arbitrary order, so the
// keys must be sorted to test them against a sorted array.
vec.sort_unstable();
assert_eq!(vec, ["a", "b", "c"]);
assert_eq!(map.len(), 3);
Sourcepub fn len(&self) -> usize
pub fn len(&self) -> usize
Returns the number of elements in the map.
§Examples
use stable_map::StableMap;
let mut a = StableMap::new();
assert_eq!(a.len(), 0);
a.insert(1, "a");
assert_eq!(a.len(), 1);
Sourcepub fn remove<Q>(&mut self, key: &Q) -> Option<V>
pub fn remove<Q>(&mut self, key: &Q) -> Option<V>
Removes a key from the map, returning the value at the key if the key was previously in the map. Keeps the allocated memory for reuse.
The key may be any borrowed form of the map’s key type, but
Hash
and Eq
on the borrowed form must match those for
the key type.
§Examples
use stable_map::StableMap;
let mut map = StableMap::new();
// The map is empty
assert!(map.is_empty() && map.capacity() == 0);
map.insert(1, "a");
assert_eq!(map.remove(&1), Some("a"));
assert_eq!(map.remove(&1), None);
// Now map holds none elements
assert!(map.is_empty());
Sourcepub fn remove_entry<Q>(&mut self, key: &Q) -> Option<(K, V)>
pub fn remove_entry<Q>(&mut self, key: &Q) -> Option<(K, V)>
Removes a key from the map, returning the stored key and value if the key was previously in the map. Keeps the allocated memory for reuse.
The key may be any borrowed form of the map’s key type, but
Hash
and Eq
on the borrowed form must match those for
the key type.
§Examples
use stable_map::StableMap;
let mut map = StableMap::new();
// The map is empty
assert!(map.is_empty() && map.capacity() == 0);
map.insert(1, "a");
assert_eq!(map.remove_entry(&1), Some((1, "a")));
assert_eq!(map.remove(&1), None);
// Now map hold none elements
assert!(map.is_empty());
Sourcepub fn reserve(&mut self, additional: usize)
pub fn reserve(&mut self, additional: usize)
Reserves capacity for at least additional
more elements to be inserted
in the StableMap
. The collection may reserve more space to avoid
frequent reallocations.
§Panics
Panics if the new capacity exceeds isize::MAX
bytes and abort
the program
in case of allocation error.
§Examples
use stable_map::StableMap;
let mut map: StableMap<&str, i32> = StableMap::new();
// Map is empty and doesn't allocate memory
assert_eq!(map.capacity(), 0);
map.reserve(10);
// And now map can hold at least 10 elements
assert!(map.capacity() >= 10);
Sourcepub fn retain<F>(&mut self, f: F)
pub fn retain<F>(&mut self, f: F)
Retains only the elements specified by the predicate. Keeps the allocated memory for reuse.
In other words, remove all pairs (k, v)
such that f(&k, &mut v)
returns false
.
The elements are visited in unsorted (and unspecified) order.
§Examples
use stable_map::StableMap;
let mut map: StableMap<i32, i32> = (0..8).map(|x|(x, x*10)).collect();
assert_eq!(map.len(), 8);
map.retain(|&k, _| k % 2 == 0);
// We can see, that the number of elements inside map is changed.
assert_eq!(map.len(), 4);
let mut vec: Vec<(i32, i32)> = map.iter().map(|(&k, &v)| (k, v)).collect();
vec.sort_unstable();
assert_eq!(vec, [(0, 0), (2, 20), (4, 40), (6, 60)]);
Sourcepub fn shrink_to_fit(&mut self)
pub fn shrink_to_fit(&mut 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 stable_map::StableMap;
let mut map: StableMap<i32, i32> = StableMap::with_capacity(100);
map.insert(1, 2);
map.insert(3, 4);
assert!(map.capacity() >= 100);
map.shrink_to_fit();
assert!(map.capacity() >= 2);
Sourcepub fn try_insert(
&mut self,
key: K,
value: V,
) -> Result<&mut V, OccupiedError<'_, K, V, S>>
pub fn try_insert( &mut self, key: K, value: V, ) -> Result<&mut V, OccupiedError<'_, K, V, S>>
Tries to insert a key-value pair into the map, and returns a mutable reference to the value in the entry.
§Errors
If the map already had this key present, nothing is updated, and an error containing the occupied entry and the value is returned.
§Examples
Basic usage:
use stable_map::{OccupiedError, StableMap};
let mut map = StableMap::new();
assert_eq!(map.try_insert(37, "a").unwrap(), &"a");
match map.try_insert(37, "b") {
Err(OccupiedError { entry, value }) => {
assert_eq!(entry.key(), &37);
assert_eq!(entry.get(), &"a");
assert_eq!(value, "b");
}
_ => panic!()
}
Sourcepub fn values(&self) -> Values<'_, K, V> ⓘ
pub fn values(&self) -> Values<'_, K, V> ⓘ
An iterator visiting all values in arbitrary order.
The iterator element type is &'a V
.
§Examples
use stable_map::StableMap;
let mut map = StableMap::new();
map.insert("a", 1);
map.insert("b", 2);
map.insert("c", 3);
assert_eq!(map.len(), 3);
let mut vec: Vec<i32> = Vec::new();
for val in map.values() {
println!("{}", val);
vec.push(*val);
}
// The `Values` iterator produces values in arbitrary order, so the
// values must be sorted to test them against a sorted array.
vec.sort_unstable();
assert_eq!(vec, [1, 2, 3]);
assert_eq!(map.len(), 3);
Sourcepub fn values_mut(&mut self) -> ValuesMut<'_, K, V> ⓘ
pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> ⓘ
An iterator visiting all values mutably in arbitrary order.
The iterator element type is &'a mut V
.
§Examples
use stable_map::StableMap;
let mut map = StableMap::new();
map.insert("a", 1);
map.insert("b", 2);
map.insert("c", 3);
for val in map.values_mut() {
*val = *val + 10;
}
assert_eq!(map.len(), 3);
let mut vec: Vec<i32> = Vec::new();
for val in map.values() {
println!("{}", val);
vec.push(*val);
}
// The `Values` iterator produces values in arbitrary order, so the
// values must be sorted to test them against a sorted array.
vec.sort_unstable();
assert_eq!(vec, [11, 12, 13]);
assert_eq!(map.len(), 3);
Sourcepub fn with_capacity_and_hasher(capacity: usize, hash_builder: S) -> Self
pub fn with_capacity_and_hasher(capacity: usize, hash_builder: S) -> Self
Creates an empty StableMap
with the specified capacity, using hash_builder
to hash the keys.
The hash map will be able to hold at least capacity
elements without
reallocating. If capacity
is 0, the hash map will not allocate.
§Examples
use hashbrown::DefaultHashBuilder;
use stable_map::StableMap;
let s = DefaultHashBuilder::default();
let mut map = StableMap::with_capacity_and_hasher(10, s);
assert_eq!(map.len(), 0);
assert!(map.capacity() >= 10);
map.insert(1, 2);
Sourcepub fn with_hasher(hash_builder: S) -> Self
pub fn with_hasher(hash_builder: S) -> Self
Creates an empty StableMap
which will use the given hash builder to hash
keys.
The hash map is initially created with a capacity of 0, so it will not allocate until it is first inserted into.
§Examples
use hashbrown::DefaultHashBuilder;
use stable_map::StableMap;
let s = DefaultHashBuilder::default();
let mut map = StableMap::with_hasher(s);
assert_eq!(map.len(), 0);
assert_eq!(map.capacity(), 0);
map.insert(1, 2);
Sourcepub fn index_len(&self) -> usize
pub fn index_len(&self) -> usize
Returns one more than the highest possible index of this map.
Using get_by_index with higher indices will always return
None
.
§Examples
use stable_map::StableMap;
let mut a = StableMap::new();
assert_eq!(a.index_len(), 0);
a.insert(1, "a");
a.insert(2, "b");
a.remove(&2);
assert_eq!(a.len(), 1);
assert_eq!(a.index_len(), 2);
Sourcepub fn get_index<Q>(&self, q: &Q) -> Option<usize>
pub fn get_index<Q>(&self, q: &Q) -> Option<usize>
Returns the index that the key maps to.
This function returns Some
if and only if the key is contained in the map.
As long as the key is not removed from the map, and unless compact or force_compact is called, this function will always return the same value.
The returned value can be used to retrieve the value by using get_by_index or get_by_index_mut.
§Examples
use stable_map::StableMap;
let mut a = StableMap::new();
assert_eq!(a.index_len(), 0);
a.insert(1, "a");
assert_eq!(a.get_by_index(a.get_index(&1).unwrap()).unwrap(), &"a");
Sourcepub fn get_by_index(&self, index: usize) -> Option<&V>
pub fn get_by_index(&self, index: usize) -> Option<&V>
Returns a reference to the value corresponding to the index.
This function returns Some
if and only if there is a key, key
, for which
get_index returns this index. In this case, it returns the same
value that would be returned by calling get.
§Examples
use stable_map::StableMap;
let mut a = StableMap::new();
assert_eq!(a.index_len(), 0);
a.insert(1, "a");
assert_eq!(a.get_by_index(a.get_index(&1).unwrap()).unwrap(), &"a");
Sourcepub fn get_by_index_mut(&mut self, index: usize) -> Option<&mut V>
pub fn get_by_index_mut(&mut self, index: usize) -> Option<&mut V>
Returns a mutable reference to the value corresponding to the index.
This function returns Some
if and only if there is a key, key
, for which
get_index returns this index. In this case, it returns the same
value that would be returned by calling get_mut.
§Examples
use stable_map::StableMap;
let mut a = StableMap::new();
assert_eq!(a.index_len(), 0);
a.insert(1, "a");
assert_eq!(a.get_by_index_mut(a.get_index(&1).unwrap()).unwrap(), &"a");
Sourcepub unsafe fn get_by_index_unchecked(&self, index: usize) -> &V
pub unsafe fn get_by_index_unchecked(&self, index: usize) -> &V
Returns a reference to the value corresponding to the index, without validating that the index is valid.
This function returns the same value that would be returned by get_by_index.
§Safety
There must be some key
for which self.get_index(k)
would return this index.
§Examples
use stable_map::StableMap;
let mut a = StableMap::new();
assert_eq!(a.index_len(), 0);
a.insert(1, "a");
unsafe {
assert_eq!(a.get_by_index_unchecked(a.get_index(&1).unwrap()), &"a");
}
Sourcepub unsafe fn get_by_index_unchecked_mut(&mut self, index: usize) -> &mut V
pub unsafe fn get_by_index_unchecked_mut(&mut self, index: usize) -> &mut V
Returns a mutable reference to the value corresponding to the index, without validating that the index is valid.
This function returns the same value that would be returned by get_by_index_mut.
§Safety
There must be some key
for which self.get_index(k)
would return this index.
§Examples
use stable_map::StableMap;
let mut a = StableMap::new();
assert_eq!(a.index_len(), 0);
a.insert(1, "a");
unsafe {
assert_eq!(a.get_by_index_unchecked_mut(a.get_index(&1).unwrap()), &"a");
}
Sourcepub fn compact(&mut self)
pub fn compact(&mut self)
Maybe compacts the map, removing indices for which get_by_index
would return
None
.
This function does nothing if there are no more than 8 indices for which
get_by_index returns None
or if at least half of the
indices are in use.
§Examples
use stable_map::StableMap;
let mut map = StableMap::new();
for i in 0..32 {
map.insert(i, i);
}
for i in 0..16 {
map.remove(&i);
}
assert_eq!(map.index_len(), 32);
map.compact();
assert_eq!(map.index_len(), 32);
map.remove(&16);
map.compact();
assert_eq!(map.index_len(), 15);
Sourcepub fn force_compact(&mut self)
pub fn force_compact(&mut self)
Compacts the map, removing indices for which get_by_index
would return None
.
After this function returns, index_len will be the same as len.
§Examples
use stable_map::StableMap;
let mut map = StableMap::new();
map.insert(1, 1);
map.remove(&1);
assert_eq!(map.index_len(), 1);
map.force_compact();
assert_eq!(map.index_len(), 0);
Trait Implementations§
Source§impl<'a, K, V, S> Extend<&'a (K, V)> for StableMap<K, V, S>
impl<'a, K, V, S> Extend<&'a (K, V)> for StableMap<K, V, S>
Source§fn extend<T: IntoIterator<Item = &'a (K, V)>>(&mut self, iter: T)
fn extend<T: IntoIterator<Item = &'a (K, V)>>(&mut self, iter: T)
Source§fn extend_one(&mut self, item: A)
fn extend_one(&mut self, item: A)
extend_one
)Source§fn extend_reserve(&mut self, additional: usize)
fn extend_reserve(&mut self, additional: usize)
extend_one
)Source§impl<'a, K, V, S> Extend<(&'a K, &'a V)> for StableMap<K, V, S>
impl<'a, K, V, S> Extend<(&'a K, &'a V)> for StableMap<K, V, S>
Source§fn extend<T: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: T)
fn extend<T: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: T)
Source§fn extend_one(&mut self, item: A)
fn extend_one(&mut self, item: A)
extend_one
)Source§fn extend_reserve(&mut self, additional: usize)
fn extend_reserve(&mut self, additional: usize)
extend_one
)Source§impl<K, V, S> Extend<(K, V)> for StableMap<K, V, S>
impl<K, V, S> Extend<(K, V)> for StableMap<K, V, S>
Source§fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T)
fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T)
Source§fn extend_one(&mut self, item: A)
fn extend_one(&mut self, item: A)
extend_one
)Source§fn extend_reserve(&mut self, additional: usize)
fn extend_reserve(&mut self, additional: usize)
extend_one
)Source§impl<K, V, S> FromIterator<(K, V)> for StableMap<K, V, S>
impl<K, V, S> FromIterator<(K, V)> for StableMap<K, V, S>
Source§impl<'a, K, V, S> IntoIterator for &'a StableMap<K, V, S>
impl<'a, K, V, S> IntoIterator for &'a StableMap<K, V, S>
Source§impl<'a, K, V, S> IntoIterator for &'a mut StableMap<K, V, S>
impl<'a, K, V, S> IntoIterator for &'a mut StableMap<K, V, S>
Source§impl<K, V, S> IntoIterator for StableMap<K, V, S>
impl<K, V, S> IntoIterator for StableMap<K, V, S>
impl<K, V, S> Eq for StableMap<K, V, S>
impl<K, V, S> Send for StableMap<K, V, S>
impl<K, V, S> Sync for StableMap<K, V, S>
Auto Trait Implementations§
impl<K, V, S> Freeze for StableMap<K, V, S>where
S: Freeze,
impl<K, V, S> RefUnwindSafe for StableMap<K, V, S>
impl<K, V, S> Unpin for StableMap<K, V, S>
impl<K, V, S> UnwindSafe for StableMap<K, V, S>
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<Q, K> Equivalent<K> for Q
impl<Q, K> Equivalent<K> for Q
Source§fn equivalent(&self, key: &K) -> bool
fn equivalent(&self, key: &K) -> bool
key
and return true
if they are equal.