pub struct SlotMap<K: Key, V> { /* private fields */ }
Expand description
Slot map, storage with stable unique keys.
See crate documentation for more details.
Implementations§
source§impl<V> SlotMap<DefaultKey, V>
impl<V> SlotMap<DefaultKey, V>
sourcepub fn with_capacity(capacity: usize) -> Self
pub fn with_capacity(capacity: usize) -> Self
source§impl<K: Key, V> SlotMap<K, V>
impl<K: Key, V> SlotMap<K, V>
sourcepub fn with_capacity_and_key(capacity: usize) -> Self
pub fn with_capacity_and_key(capacity: usize) -> Self
Creates an empty SlotMap
with the given capacity and a custom key
type.
The slot map will not reallocate until it holds at least capacity
elements.
§Examples
new_key_type! {
struct MessageKey;
}
let mut messages = SlotMap::with_capacity_and_key(3);
let welcome: MessageKey = messages.insert("Welcome");
let good_day = messages.insert("Good day");
let hello = messages.insert("Hello");
sourcepub fn len(&self) -> usize
pub fn len(&self) -> usize
Returns the number of elements in the slot map.
§Examples
let mut sm = SlotMap::with_capacity(10);
sm.insert("len() counts actual elements, not capacity");
let key = sm.insert("removed elements don't count either");
sm.remove(key);
assert_eq!(sm.len(), 1);
sourcepub fn is_empty(&self) -> bool
pub fn is_empty(&self) -> bool
Returns if the slot map is empty.
§Examples
let mut sm = SlotMap::new();
let key = sm.insert("dummy");
assert_eq!(sm.is_empty(), false);
sm.remove(key);
assert_eq!(sm.is_empty(), true);
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 SlotMap
. The collection may reserve more space to avoid
frequent reallocations.
§Panics
Panics if the new allocation size overflows usize
.
§Examples
let mut sm = SlotMap::new();
sm.insert("foo");
sm.reserve(32);
assert!(sm.capacity() >= 33);
sourcepub fn contains_key(&self, key: K) -> bool
pub fn contains_key(&self, key: K) -> bool
sourcepub fn insert_with_key<F>(&mut self, f: F) -> Kwhere
F: FnOnce(K) -> V,
pub fn insert_with_key<F>(&mut self, f: F) -> Kwhere
F: FnOnce(K) -> V,
Inserts a value given by f
into the slot map. The key where the
value will be stored is passed into f
. This is useful to store values
that contain their own key.
§Panics
Panics if the number of elements in the slot map equals 232 - 2.
§Examples
let mut sm = SlotMap::new();
let key = sm.insert_with_key(|k| (k, 20));
assert_eq!(sm[key], (key, 20));
sourcepub fn try_insert_with_key<F, E>(&mut self, f: F) -> Result<K, E>
pub fn try_insert_with_key<F, E>(&mut self, f: F) -> Result<K, E>
Inserts a value given by f
into the slot map. The key where the
value will be stored is passed into f
. This is useful to store values
that contain their own key.
If f
returns Err
, this method returns the error. The slotmap is untouched.
§Panics
Panics if the number of elements in the slot map equals 232 - 2.
§Examples
let mut sm = SlotMap::new();
let key = sm.try_insert_with_key::<_, ()>(|k| Ok((k, 20))).unwrap();
assert_eq!(sm[key], (key, 20));
sm.try_insert_with_key::<_, ()>(|k| Err(())).unwrap_err();
sourcepub fn remove(&mut self, key: K) -> Option<V>
pub fn remove(&mut self, key: K) -> Option<V>
Removes a key from the slot map, returning the value at the key if the key was not previously removed.
§Examples
let mut sm = SlotMap::new();
let key = sm.insert(42);
assert_eq!(sm.remove(key), Some(42));
assert_eq!(sm.remove(key), None);
sourcepub fn retain<F>(&mut self, f: F)
pub fn retain<F>(&mut self, f: F)
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 k1 = sm.insert(0);
let k2 = sm.insert(1);
let k3 = sm.insert(2);
sm.retain(|key, val| key == k1 || *val == 1);
assert!(sm.contains_key(k1));
assert!(sm.contains_key(k2));
assert!(!sm.contains_key(k3));
assert_eq!(2, sm.len());
sourcepub fn clear(&mut self)
pub fn clear(&mut self)
Clears the slot 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();
for i in 0..10 {
sm.insert(i);
}
assert_eq!(sm.len(), 10);
sm.clear();
assert_eq!(sm.len(), 0);
sourcepub fn drain(&mut self) -> Drain<'_, K, V> ⓘ
pub fn drain(&mut self) -> Drain<'_, K, V> ⓘ
Clears the slot map, returning all key-value pairs in arbitrary order as an iterator. Keeps the allocated memory for reuse.
When the iterator is dropped all elements in the slot map are removed,
even if the iterator was not fully consumed. If the iterator is not
dropped (using e.g. std::mem::forget
), only the elements that were
iterated over are removed.
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 v: Vec<_> = sm.drain().collect();
assert_eq!(sm.len(), 0);
assert_eq!(v, vec![(k, 0)]);
sourcepub fn get(&self, key: K) -> Option<&V>
pub fn get(&self, key: K) -> Option<&V>
Returns a reference to the value corresponding to the key.
§Examples
let mut sm = SlotMap::new();
let key = sm.insert("bar");
assert_eq!(sm.get(key), Some(&"bar"));
sm.remove(key);
assert_eq!(sm.get(key), None);
sourcepub unsafe fn get_unchecked(&self, key: K) -> &V
pub unsafe fn get_unchecked(&self, key: K) -> &V
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("bar");
assert_eq!(unsafe { sm.get_unchecked(key) }, &"bar");
sm.remove(key);
// sm.get_unchecked(key) is now dangerous!
sourcepub fn get_mut(&mut self, key: K) -> Option<&mut V>
pub fn get_mut(&mut self, key: K) -> Option<&mut V>
Returns a mutable reference to the value corresponding to the key.
§Examples
let mut sm = SlotMap::new();
let key = sm.insert(3.5);
if let Some(x) = sm.get_mut(key) {
*x += 3.0;
}
assert_eq!(sm[key], 6.5);
sourcepub unsafe fn get_unchecked_mut(&mut self, key: K) -> &mut V
pub unsafe fn get_unchecked_mut(&mut self, key: K) -> &mut V
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");
unsafe { *sm.get_unchecked_mut(key) = "bar" };
assert_eq!(sm[key], "bar");
sm.remove(key);
// sm.get_unchecked_mut(key) is now dangerous!
sourcepub fn get_disjoint_mut<const N: usize>(
&mut self,
keys: [K; N],
) -> Option<[&mut V; N]>
pub fn get_disjoint_mut<const N: usize>( &mut self, keys: [K; N], ) -> Option<[&mut V; N]>
Returns mutable references to the values corresponding to the given keys. All keys must be valid and disjoint, otherwise None is returned.
Requires at least stable Rust version 1.51.
§Examples
let mut sm = SlotMap::new();
let ka = sm.insert("butter");
let kb = sm.insert("apples");
let kc = sm.insert("charlie");
sm.remove(kc); // Make key c invalid.
assert_eq!(sm.get_disjoint_mut([ka, kb, kc]), None); // Has invalid key.
assert_eq!(sm.get_disjoint_mut([ka, ka]), None); // Not disjoint.
let [a, b] = sm.get_disjoint_mut([ka, kb]).unwrap();
std::mem::swap(a, b);
assert_eq!(sm[ka], "apples");
assert_eq!(sm[kb], "butter");
sourcepub unsafe fn get_disjoint_unchecked_mut<const N: usize>(
&mut self,
keys: [K; N],
) -> [&mut V; N]
pub unsafe fn get_disjoint_unchecked_mut<const N: usize>( &mut self, keys: [K; N], ) -> [&mut V; N]
Returns mutable references to the values corresponding to the given keys. All keys must be valid and disjoint.
Requires at least stable Rust version 1.51.
§Safety
This should only be used if contains_key(key)
is true for every given
key and no two keys are equal. Otherwise it is potentially unsafe.
§Examples
let mut sm = SlotMap::new();
let ka = sm.insert("butter");
let kb = sm.insert("apples");
let [a, b] = unsafe { sm.get_disjoint_unchecked_mut([ka, kb]) };
std::mem::swap(a, b);
assert_eq!(sm[ka], "apples");
assert_eq!(sm[kb], "butter");
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 (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 k0 = sm.insert(0);
let k1 = sm.insert(1);
let k2 = sm.insert(2);
for (k, v) in sm.iter() {
println!("key: {:?}, val: {}", k, v);
}
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
(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 k0 = sm.insert(10);
let k1 = sm.insert(20);
let k2 = sm.insert(30);
for (k, v) in sm.iter_mut() {
if k != k1 {
*v *= -1;
}
}
assert_eq!(sm[k0], -10);
assert_eq!(sm[k1], 20);
assert_eq!(sm[k2], -30);
sourcepub fn keys(&self) -> Keys<'_, K, V> ⓘ
pub fn keys(&self) -> Keys<'_, K, V> ⓘ
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 k0 = sm.insert(10);
let k1 = sm.insert(20);
let k2 = sm.insert(30);
let keys: HashSet<_> = sm.keys().collect();
let check: HashSet<_> = vec![k0, k1, k2].into_iter().collect();
assert_eq!(keys, check);
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
.
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 k0 = sm.insert(10);
let k1 = sm.insert(20);
let k2 = sm.insert(30);
let values: HashSet<_> = sm.values().collect();
let check: HashSet<_> = vec![&10, &20, &30].into_iter().collect();
assert_eq!(values, check);
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
.
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();
sm.insert(1);
sm.insert(2);
sm.insert(3);
sm.values_mut().for_each(|n| { *n *= 3 });
let values: HashSet<_> = sm.into_iter().map(|(_k, v)| v).collect();
let check: HashSet<_> = vec![3, 6, 9].into_iter().collect();
assert_eq!(values, check);
Trait Implementations§
source§impl<'a, K: Key, V> IntoIterator for &'a SlotMap<K, V>
impl<'a, K: Key, V> IntoIterator for &'a SlotMap<K, V>
source§impl<'a, K: Key, V> IntoIterator for &'a mut SlotMap<K, V>
impl<'a, K: Key, V> IntoIterator for &'a mut SlotMap<K, V>
Auto Trait Implementations§
impl<K, V> Freeze for SlotMap<K, V>
impl<K, V> RefUnwindSafe for SlotMap<K, V>where
V: RefUnwindSafe,
impl<K, V> Send for SlotMap<K, V>where
V: Send,
impl<K, V> Sync for SlotMap<K, V>where
V: Sync,
impl<K, V> Unpin for SlotMap<K, V>where
V: Unpin,
impl<K, V> UnwindSafe for SlotMap<K, V>where
V: UnwindSafe,
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§unsafe fn clone_to_uninit(&self, dst: *mut T)
unsafe fn clone_to_uninit(&self, dst: *mut T)
clone_to_uninit
)