[][src]Struct slotmap::secondary::SecondaryMap

pub struct SecondaryMap<K: Key, V> { /* fields omitted */ }

Secondary map, associate data with previously stored elements in a slot map.

A SecondaryMap allows you to efficiently store additional information for each element in a slot map. You can have multiple secondary maps per slot map, but not multiple slot maps per secondary map. It is safe but unspecified behavior if you use keys from multiple different slot maps in the same SecondaryMap.

A SecondaryMap does not leak memory even if you never remove elements. In return, when you remove a key from the primary slot map, after any insert the space associated with the removed element may be reclaimed. Don't expect the values associated with a removed key to stick around after an insertion has happened!

Unlike a SlotMap, a SecondaryMaps elements do not need to be Slottable. This means that if you can't or don't want to use nightly Rust, and your data is not Slottable, you can store that data as secondary data.

Finally a note on memory complexity, the SecondaryMap can use memory for each slot in the primary slot map, and has to iterate over every slot during iteration, regardless of whether you have inserted an associative value at that key or not. If you have some property that you only expect to set for a minority of keys, use a SparseSecondaryMap, which is backed by a HashMap.

Example usage:

// Nightly Rust needed to store String which is not Copy.
let mut players: SlotMap<_, &'static str> = SlotMap::new();
// But not for secondary maps.
let mut nicks: SecondaryMap<_, String> = SecondaryMap::new();
let mut health = SecondaryMap::new();
let mut ammo = SecondaryMap::new();

let alice = players.insert("alice");
nicks.insert(alice, "the_dragon1".to_string());
let bob = players.insert("bob");
nicks.insert(bob, "bobby_".to_string());

for p in players.keys() {
    health.insert(p, 100);
    ammo.insert(p, 30);
}

// Alice attacks Bob with all her ammo!
health[bob] -= ammo[alice] * 3;
ammo[alice] = 0;

Methods

impl<K: Key, V> SecondaryMap<K, V>[src]

pub fn new() -> Self[src]

Constructs a new, empty SecondaryMap.

Examples

let mut sec: SecondaryMap<DefaultKey, i32> = SecondaryMap::new();

pub fn with_capacity(capacity: usize) -> Self[src]

Creates an empty SecondaryMap with the given capacity of slots.

The secondary map will not reallocate until it holds at least capacity slots. Even inserting a single key-value pair might require as many slots as the slot map the key comes from, so it's recommended to match the capacity of a secondary map to its corresponding slot map.

Examples

let mut sm: SlotMap<_, i32> = SlotMap::with_capacity(10);
let mut sec: SecondaryMap<DefaultKey, i32> = SecondaryMap::with_capacity(sm.capacity());

pub fn len(&self) -> usize[src]

Returns the number of elements in the secondary map.

Examples

let mut sm = SlotMap::new();
let k = sm.insert(4);
let mut squared = SecondaryMap::new();
assert_eq!(squared.len(), 0);
squared.insert(k, 16);
assert_eq!(squared.len(), 1);

pub fn is_empty(&self) -> bool[src]

Returns if the secondary map is empty.

Examples

let mut sec: SecondaryMap<DefaultKey, i32> = SecondaryMap::new();
assert!(sec.is_empty());

pub fn capacity(&self) -> usize[src]

Returns the number of elements the SecondaryMap can hold without reallocating.

Examples

let mut sec: SecondaryMap<DefaultKey, i32> = SecondaryMap::with_capacity(10);
assert!(sec.capacity() >= 10);

pub fn set_capacity(&mut self, new_capacity: usize)[src]

Sets the capacity of the SecondaryMap to new_capacity, if it is bigger than the current capacity.

It is recommended to set the capacity of a SecondaryMap to the capacity of its corresponding slot map before inserting many new elements to prevent frequent reallocations. The collection may reserve more space than requested.

Panics

Panics if the new allocation size overflows usize.

Examples

let mut sec: SecondaryMap<DefaultKey, i32> = SecondaryMap::with_capacity(10);
assert!(sec.capacity() >= 10);
sec.set_capacity(1000);
assert!(sec.capacity() >= 1000);

pub fn contains_key(&self, key: K) -> bool[src]

Returns true if the secondary map contains key.

Examples

let mut sm = SlotMap::new();
let k = sm.insert(4);
let mut squared = SecondaryMap::new();
assert!(!squared.contains_key(k));
squared.insert(k, 16);
assert!(squared.contains_key(k));

pub fn insert(&mut self, key: K, value: V) -> Option<V>[src]

Inserts a value into the secondary map at the given key. Can silently fail if key was removed from the originating slot map.

Returns None if this key was not present in the map, the old value otherwise.

Examples

let mut sm = SlotMap::new();
let k = sm.insert(4);
let mut squared = SecondaryMap::new();
assert_eq!(squared.insert(k, 0), None);
assert_eq!(squared.insert(k, 4), Some(0));
// You don't have to use insert if the key is already in the secondary map.
squared[k] *= squared[k];
assert_eq!(squared[k], 16);

pub fn remove(&mut self, key: K) -> Option<V>[src]

Removes a key from the secondary map, returning the value at the key if the key was not previously removed. If key was removed from the originating slot map, its corresponding entry in the secondary map may or may not already be removed.

Examples

let mut sm = SlotMap::new();
let mut squared = SecondaryMap::new();
let k = sm.insert(4);
squared.insert(k, 16);
squared.remove(k);
assert!(!squared.contains_key(k));

// It's not necessary to remove keys deleted from the primary slot map, they
// get deleted automatically when their slots are reused on a subsequent insert.
squared.insert(k, 16);
sm.remove(k); // Remove k from the slot map, making an empty slot.
let new_k = sm.insert(2); // Since sm only has one empty slot, this reuses it.
assert!(!squared.contains_key(new_k)); // Space reuse does not mean equal keys.
assert!(squared.contains_key(k)); // Slot has not been reused in squared yet.
squared.insert(new_k, 4);
assert!(!squared.contains_key(k)); // Old key is no longer available.

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

Retains only the elements specified by the predicate.

In other words, remove all key-value pairs (k, v) such that f(k, &mut v) returns false. This method invalidates any removed keys.

This function must iterate over all slots, empty or not. In the face of many deleted elements it can be inefficient.

Examples

let mut sm = SlotMap::new();
let mut sec = SecondaryMap::new();

let k1 = sm.insert(0); sec.insert(k1, 10);
let k2 = sm.insert(1); sec.insert(k2, 11);
let k3 = sm.insert(2); sec.insert(k3, 12);

sec.retain(|key, val| key == k1 || *val == 11);

assert!(sec.contains_key(k1));
assert!(sec.contains_key(k2));
assert!(!sec.contains_key(k3));

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

pub fn clear(&mut self)[src]

Clears the secondary map. Keeps the allocated memory for reuse.

This function must iterate over all slots, empty or not. In the face of many deleted elements it can be inefficient.

Examples

let mut sm = SlotMap::new();
let mut sec = SecondaryMap::new();
for i in 0..10 {
    sec.insert(sm.insert(i), i);
}
assert_eq!(sec.len(), 10);
sec.clear();
assert_eq!(sec.len(), 0);

Important traits for Drain<'a, K, V>
pub fn drain(&mut self) -> Drain<K, V>[src]

Clears the slot map, returning all key-value pairs in arbitrary order as an iterator. Keeps the allocated memory for reuse.

This function must iterate over all slots, empty or not. In the face of many deleted elements it can be inefficient.

Examples

let mut sm = SlotMap::new();
let k = sm.insert(0);
let mut sec = SecondaryMap::new();
sec.insert(k, 1);
let v: Vec<_> = sec.drain().collect();
assert_eq!(sec.len(), 0);
assert_eq!(v, vec![(k, 1)]);

pub fn get(&self, key: K) -> Option<&V>[src]

Returns a reference to the value corresponding to the key.

Examples

let mut sm = SlotMap::new();
let key = sm.insert("foo");
let mut sec = SecondaryMap::new();
sec.insert(key, "bar");
assert_eq!(sec.get(key), Some(&"bar"));
sec.remove(key);
assert_eq!(sec.get(key), None);

pub unsafe fn get_unchecked(&self, key: K) -> &V[src]

Returns a reference to the value corresponding to the key without version or bounds checking.

Safety

This should only be used if contains_key(key) is true. Otherwise it is potentially unsafe.

Examples

let mut sm = SlotMap::new();
let key = sm.insert("foo");
let mut sec = SecondaryMap::new();
sec.insert(key, "bar");
assert_eq!(unsafe { sec.get_unchecked(key) }, &"bar");
sec.remove(key);
// sec.get_unchecked(key) is now dangerous!

pub fn get_mut(&mut self, key: K) -> Option<&mut V>[src]

Returns a mutable reference to the value corresponding to the key.

Examples

let mut sm = SlotMap::new();
let key = sm.insert("test");
let mut sec = SecondaryMap::new();
sec.insert(key, 3.5);
if let Some(x) = sec.get_mut(key) {
    *x += 3.0;
}
assert_eq!(sec[key], 6.5);

pub unsafe fn get_unchecked_mut(&mut self, key: K) -> &mut V[src]

Returns a mutable reference to the value corresponding to the key without version or bounds checking.

Safety

This should only be used if contains_key(key) is true. Otherwise it is potentially unsafe.

Examples

let mut sm = SlotMap::new();
let key = sm.insert("foo");
let mut sec = SecondaryMap::new();
sec.insert(key, "bar");
unsafe { *sec.get_unchecked_mut(key) = "baz" };
assert_eq!(sec[key], "baz");
sec.remove(key);
// sec.get_unchecked_mut(key) is now dangerous!

Important traits for Iter<'a, K, V>
pub fn iter(&self) -> Iter<K, V>[src]

An iterator visiting all key-value pairs in arbitrary order. The iterator element type is (K, &'a V).

This function must iterate over all slots, empty or not. In the face of many deleted elements it can be inefficient.

Examples

let mut sm = SlotMap::new();
let mut sec = SecondaryMap::new();
let k0 = sm.insert(0); sec.insert(k0, 10);
let k1 = sm.insert(1); sec.insert(k1, 11);
let k2 = sm.insert(2); sec.insert(k2, 12);

for (k, v) in sm.iter() {
    println!("key: {:?}, val: {}", k, v);
}

Important traits for IterMut<'a, K, V>
pub fn iter_mut(&mut self) -> IterMut<K, V>[src]

An iterator visiting all key-value pairs in arbitrary order, with mutable references to the values. The iterator element type is (K, &'a mut V).

This function must iterate over all slots, empty or not. In the face of many deleted elements it can be inefficient.

Examples

let mut sm = SlotMap::new();
let mut sec = SecondaryMap::new();
let k0 = sm.insert(1); sec.insert(k0, 10);
let k1 = sm.insert(2); sec.insert(k1, 20);
let k2 = sm.insert(3); sec.insert(k2, 30);

for (k, v) in sec.iter_mut() {
    if k != k1 {
        *v *= -1;
    }
}

assert_eq!(sec[k0], -10);
assert_eq!(sec[k1], 20);
assert_eq!(sec[k2], -30);

Important traits for Keys<'a, K, V>
pub fn keys(&self) -> Keys<K, V>[src]

An iterator visiting all keys in arbitrary order. The iterator element type is K.

This function must iterate over all slots, empty or not. In the face of many deleted elements it can be inefficient.

Examples

let mut sm = SlotMap::new();
let mut sec = SecondaryMap::new();
let k0 = sm.insert(1); sec.insert(k0, 10);
let k1 = sm.insert(2); sec.insert(k1, 20);
let k2 = sm.insert(3); sec.insert(k2, 30);
let keys: HashSet<_> = sec.keys().collect();
let check: HashSet<_> = vec![k0, k1, k2].into_iter().collect();
assert_eq!(keys, check);

Important traits for Values<'a, K, V>
pub fn values(&self) -> Values<K, V>[src]

An iterator visiting all values in arbitrary order. The iterator element type is &'a V.

This function must iterate over all slots, empty or not. In the face of many deleted elements it can be inefficient.

Examples

let mut sm = SlotMap::new();
let mut sec = SecondaryMap::new();
let k0 = sm.insert(1); sec.insert(k0, 10);
let k1 = sm.insert(2); sec.insert(k1, 20);
let k2 = sm.insert(3); sec.insert(k2, 30);
let values: HashSet<_> = sec.values().collect();
let check: HashSet<_> = vec![&10, &20, &30].into_iter().collect();
assert_eq!(values, check);

Important traits for ValuesMut<'a, K, V>
pub fn values_mut(&mut self) -> ValuesMut<K, V>[src]

An iterator visiting all values mutably in arbitrary order. The iterator element type is &'a mut V.

This function must iterate over all slots, empty or not. In the face of many deleted elements it can be inefficient.

Examples

let mut sm = SlotMap::new();
let mut sec = SecondaryMap::new();
sec.insert(sm.insert(1), 10);
sec.insert(sm.insert(2), 20);
sec.insert(sm.insert(3), 30);
sec.values_mut().for_each(|n| { *n *= 3 });
let values: HashSet<_> = sec.into_iter().map(|(_k, v)| v).collect();
let check: HashSet<_> = vec![30, 60, 90].into_iter().collect();
assert_eq!(values, check);

Trait Implementations

impl<K: Key, V: PartialEq> PartialEq<SecondaryMap<K, V>> for SecondaryMap<K, V>[src]

#[must_use] fn ne(&self, other: &Rhs) -> bool1.0.0[src]

This method tests for !=.

impl<K: Key, V> Default for SecondaryMap<K, V>[src]

impl<'a, K: Key, V> IntoIterator for &'a SecondaryMap<K, V>[src]

type Item = (K, &'a V)

The type of the elements being iterated over.

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

Which kind of iterator are we turning this into?

impl<'a, K: Key, V> IntoIterator for &'a mut SecondaryMap<K, V>[src]

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

The type of the elements being iterated over.

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

Which kind of iterator are we turning this into?

impl<K: Key, V> IntoIterator for SecondaryMap<K, V>[src]

type Item = (K, V)

The type of the elements being iterated over.

type IntoIter = IntoIter<K, V>

Which kind of iterator are we turning this into?

impl<K: Key, V> Extend<(K, V)> for SecondaryMap<K, V>[src]

impl<'a, K: Key, V: 'a + Copy> Extend<(K, &'a V)> for SecondaryMap<K, V>[src]

impl<K: Clone + Key, V: Clone> Clone for SecondaryMap<K, V>[src]

fn clone_from(&mut self, source: &Self)1.0.0[src]

Performs copy-assignment from source. Read more

impl<K: Key, V: Eq> Eq for SecondaryMap<K, V>[src]

impl<K: Debug + Key, V: Debug> Debug for SecondaryMap<K, V>[src]

impl<K: Key, V> Index<K> for SecondaryMap<K, V>[src]

type Output = V

The returned type after indexing.

impl<K: Key, V> IndexMut<K> for SecondaryMap<K, V>[src]

impl<K: Key, V> FromIterator<(K, V)> for SecondaryMap<K, V>[src]

Auto Trait Implementations

impl<K, V> Send for SecondaryMap<K, V> where
    V: Send

impl<K, V> Unpin for SecondaryMap<K, V> where
    V: Unpin

impl<K, V> Sync for SecondaryMap<K, V> where
    V: Sync

impl<K, V> UnwindSafe for SecondaryMap<K, V> where
    V: UnwindSafe

impl<K, V> RefUnwindSafe for SecondaryMap<K, V> where
    V: RefUnwindSafe

Blanket Implementations

impl<T> From<T> for T[src]

impl<T, U> Into<U> for T where
    U: From<T>, 
[src]

impl<I> IntoIterator for I where
    I: Iterator
[src]

type Item = <I as Iterator>::Item

The type of the elements being iterated over.

type IntoIter = I

Which kind of iterator are we turning this into?

impl<T> ToOwned for T where
    T: Clone
[src]

type Owned = T

The resulting type after obtaining ownership.

impl<T, U> TryFrom<U> for T where
    U: Into<T>, 
[src]

type Error = Infallible

The type returned in the event of a conversion error.

impl<T, U> TryInto<U> for T where
    U: TryFrom<T>, 
[src]

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

The type returned in the event of a conversion error.

impl<T> Borrow<T> for T where
    T: ?Sized
[src]

impl<T> BorrowMut<T> for T where
    T: ?Sized
[src]

impl<T> Any for T where
    T: 'static + ?Sized
[src]