Struct StableMap

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

Source

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

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>

Source

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

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

pub fn contains_key<Q>(&self, key: &Q) -> bool
where K: Eq + Hash, Q: Hash + Equivalent<K> + ?Sized, S: BuildHasher,

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

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

pub fn entry(&mut self, key: K) -> Entry<'_, K, V, S>
where K: Eq + Hash, S: BuildHasher,

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

pub fn entry_ref<'b, Q>(&mut self, key: &'b Q) -> EntryRef<'_, 'b, K, Q, V, S>
where K: Eq + Hash, Q: Hash + Equivalent<K> + ?Sized, S: BuildHasher,

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

pub fn extract_if<F>( &mut self, f: F, ) -> impl FusedIterator<Item = (K, V)> + use<'_, K, V, F, S>
where F: FnMut(&K, &mut V) -> bool,

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

pub fn get<Q>(&self, key: &Q) -> Option<&V>
where K: Eq + Hash, Q: Hash + Equivalent<K> + ?Sized, S: BuildHasher,

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

pub fn get_key_value<Q>(&self, key: &Q) -> Option<(&K, &V)>
where K: Eq + Hash, Q: Hash + Equivalent<K> + ?Sized, S: BuildHasher,

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

pub fn get_key_value_mut<Q>(&mut self, key: &Q) -> Option<(&K, &mut V)>
where K: Eq + Hash, Q: Hash + Equivalent<K> + ?Sized, S: BuildHasher,

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

pub fn get_many_key_value_mut<Q, const N: usize>( &mut self, ks: [&Q; N], ) -> [Option<(&K, &mut V)>; N]
where K: Eq + Hash, Q: Hash + Equivalent<K> + ?Sized, S: BuildHasher,

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

pub unsafe fn get_many_key_value_unchecked_mut<Q, const N: usize>( &mut self, ks: [&Q; N], ) -> [Option<(&K, &mut V)>; N]
where K: Eq + Hash, Q: Hash + Equivalent<K> + ?Sized, S: BuildHasher,

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

pub fn get_many_mut<Q, const N: usize>( &mut self, ks: [&Q; N], ) -> [Option<&mut V>; N]
where K: Eq + Hash, Q: Hash + Equivalent<K> + ?Sized, S: BuildHasher,

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

pub unsafe fn get_many_unchecked_mut<Q, const N: usize>( &mut self, ks: [&Q; N], ) -> [Option<&mut V>; N]
where K: Eq + Hash, Q: Hash + Equivalent<K> + ?Sized, S: BuildHasher,

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

pub fn get_mut<Q>(&mut self, key: &Q) -> Option<&mut V>
where K: Eq + Hash, Q: Hash + Equivalent<K> + ?Sized, S: BuildHasher,

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

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

pub fn insert(&mut self, key: K, value: V) -> Option<V>
where K: Eq + Hash, S: BuildHasher,

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

pub unsafe fn insert_unique_unchecked( &mut self, key: K, value: V, ) -> (&K, &mut V)
where K: Eq + Hash, S: BuildHasher,

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

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

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

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

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

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

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

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

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

pub fn remove<Q>(&mut self, key: &Q) -> Option<V>
where K: Eq + Hash, Q: Hash + Equivalent<K> + ?Sized, S: BuildHasher,

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

pub fn remove_entry<Q>(&mut self, key: &Q) -> Option<(K, V)>
where K: Eq + Hash, Q: Hash + Equivalent<K> + ?Sized, S: BuildHasher,

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

pub fn reserve(&mut self, additional: usize)
where K: Eq + Hash, S: BuildHasher,

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

pub fn retain<F>(&mut self, f: F)
where F: FnMut(&K, &mut V) -> bool,

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

pub fn shrink_to_fit(&mut self)
where K: Eq + Hash, S: BuildHasher,

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

pub fn try_insert( &mut self, key: K, value: V, ) -> Result<&mut V, OccupiedError<'_, K, V, S>>
where K: Eq + Hash, S: BuildHasher,

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!()
}
Source

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

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

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

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

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

pub fn get_index<Q>(&self, q: &Q) -> Option<usize>
where S: BuildHasher, K: Eq + Hash, Q: Hash + Equivalent<K> + ?Sized,

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

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

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

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

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

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

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<K, V, S> Clone for StableMap<K, V, S>
where K: Eq + Hash + Clone, V: Clone, S: BuildHasher + Clone,

Source§

fn clone(&self) -> Self

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<K, V, S> Debug for StableMap<K, V, S>
where K: Debug, V: Debug,

Source§

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

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

impl<K, V, S> Default for StableMap<K, V, S>
where S: Default,

Source§

fn default() -> Self

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

impl<'a, K, V, S> Extend<&'a (K, V)> for StableMap<K, V, S>
where K: Eq + Hash + Clone, V: Clone, S: BuildHasher,

Source§

fn extend<T: IntoIterator<Item = &'a (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<'a, K, V, S> Extend<(&'a K, &'a V)> for StableMap<K, V, S>
where K: Eq + Hash + Clone, V: Clone, S: BuildHasher,

Source§

fn extend<T: IntoIterator<Item = (&'a K, &'a 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<K, V, S> Extend<(K, V)> for StableMap<K, V, S>
where K: Eq + Hash, S: BuildHasher,

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<K, V, S, const N: usize> From<[(K, V); N]> for StableMap<K, V, S>
where K: Eq + Hash, S: BuildHasher + Default,

Source§

fn from(value: [(K, V); N]) -> Self

Converts to this type from the input type.
Source§

impl<K, V, S> From<HashMap<K, V, S>> for StableMap<K, V, S>
where K: Eq + Hash, S: BuildHasher + Clone,

Source§

fn from(value: HashMap<K, V, S>) -> Self

Converts to this type from the input type.
Source§

impl<K, V, S> From<StableMap<K, V, S>> for HashMap<K, V, S>
where K: Eq + Hash, S: BuildHasher + Clone,

Source§

fn from(value: StableMap<K, V, S>) -> Self

Converts to this type from the input type.
Source§

impl<K, V, S> FromIterator<(K, V)> for StableMap<K, V, S>
where K: Eq + Hash, S: BuildHasher + Default,

Source§

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

Creates a value from an iterator. Read more
Source§

impl<K, Q, V, S> Index<&Q> for StableMap<K, V, S>
where K: Eq + Hash, Q: Hash + Equivalent<K> + ?Sized, S: BuildHasher,

Source§

type Output = V

The returned type after indexing.
Source§

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

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

impl<'a, K, V, S> IntoIterator for &'a StableMap<K, V, S>

Source§

type Item = (&'a K, &'a V)

The type of the elements being iterated over.
Source§

type IntoIter = Iter<'a, K, V>

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, K, V, S> IntoIterator for &'a mut StableMap<K, V, S>

Source§

type Item = (&'a K, &'a mut V)

The type of the elements being iterated over.
Source§

type IntoIter = IterMut<'a, K, V>

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<K, V, S> IntoIterator for StableMap<K, V, S>

Source§

type Item = (K, V)

The type of the elements being iterated over.
Source§

type IntoIter = IntoIter<K, V>

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<K, V, S> PartialEq for StableMap<K, V, S>
where K: Eq + Hash, V: PartialEq, S: BuildHasher,

Source§

fn eq(&self, other: &Self) -> 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<K, V, S> Eq for StableMap<K, V, S>
where K: Eq + Hash, V: Eq, S: BuildHasher,

Source§

impl<K, V, S> Send for StableMap<K, V, S>
where K: Send, V: Send, S: Send,

Source§

impl<K, V, S> Sync for StableMap<K, V, S>
where K: Sync, V: Sync, S: Sync,

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>
where S: Unpin, K: Unpin, V: Unpin,

§

impl<K, V, S> UnwindSafe for StableMap<K, V, S>
where S: UnwindSafe, K: UnwindSafe, V: UnwindSafe,

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, 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> 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.