pub struct SparseMap<K, V> { /* private fields */ }Expand description
A sparse map from keys convertible to indices to values.
SparseMap provides an efficient storage mechanism for mappings
where keys can be converted to usize indices. It uses a bitmap to track
which indices are occupied and a packed vector to store only the present
values, achieving both memory efficiency and fast lookup times.
The key type K must implement Into<usize> and From<usize> to
convert between keys and indices. This makes it ideal for enum keys,
small integers, or other types with a natural index representation.
§Examples
use omp_core::{sparse_index::TrySparseIndex, sparse_map::SparseMap};
#[repr(usize)]
#[derive(Copy, Clone, Debug, PartialEq)]
enum Status {
Active = 0,
Pending = 1,
Closed = 2,
}
#[derive(Debug)]
struct StatusError(String);
impl std::fmt::Display for StatusError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
impl std::error::Error for StatusError {}
impl TrySparseIndex for Status {
type Error = StatusError;
fn index(&self) -> usize {
*self as usize
}
fn try_from_index(index: usize) -> Result<Self, Self::Error> {
match index {
0 => Ok(Status::Active),
1 => Ok(Status::Pending),
2 => Ok(Status::Closed),
_ => Err(StatusError("Invalid status value".to_string())),
}
}
}
let mut map = SparseMap::new();
map.insert(Status::Active, "running");
map.insert(Status::Closed, "finished");
assert_eq!(map.get(Status::Active), Some(&"running"));
assert_eq!(map.get(Status::Pending), None);
assert_eq!(map[Status::Active], "running");Implementations§
Source§impl<K, V> SparseMap<K, V>
impl<K, V> SparseMap<K, V>
Sourcepub fn from_sequence(values: Vec<V>) -> Self
pub fn from_sequence(values: Vec<V>) -> Self
Creates a sparse index map from a sequence of values.
The values are assigned indices starting from 0. This is equivalent to inserting each value with its position as the key.
§Arguments
values- A sequence of values to insert
Sourcepub fn with_capacity(capacity: usize) -> Self
pub fn with_capacity(capacity: usize) -> Self
Creates a new sparse index map with the specified capacity.
§Arguments
capacity- The maximum index that might be stored
Sourcepub fn shrink_to_fit(&mut self)
pub fn shrink_to_fit(&mut self)
Shrinks the capacity of the map as much as possible.
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 map.
Sourcepub fn into_parts(self) -> (SmolBitmap, Vec<V>)
pub fn into_parts(self) -> (SmolBitmap, Vec<V>)
Decomposes the map into its raw parts: bitmap and values vector.
§Returns
A tuple of (SmolBitmap, Vec<V>) representing the bitmap and values
Sourcepub fn from_parts(bits: SmolBitmap, values: Vec<V>) -> Self
pub fn from_parts(bits: SmolBitmap, values: Vec<V>) -> Self
Constructs a sparse map from its raw parts: bitmap and values vector.
§Arguments
bits- The bitmap tracking which indices have valuesvalues- The packed vector of values corresponding to set bits
§Safety
The caller must ensure that the bitmap and values vector are consistent:
- The number of set bits in the bitmap must equal the length of the values vector
- The values must be in the order corresponding to the set bits in the bitmap
Source§impl<K: TrySparseIndex, V> SparseMap<K, V>
impl<K: TrySparseIndex, V> SparseMap<K, V>
Sourcepub fn get_or_insert(&mut self, key: K, value: V) -> &mut V
pub fn get_or_insert(&mut self, key: K, value: V) -> &mut V
Gets the value corresponding to the key, or inserts a default value if not present.
If the key exists in the map, returns a mutable reference to the existing value. If the key does not exist, inserts the provided value and returns a mutable reference to it.
§Arguments
key- The key to look up or insertvalue- The value to insert if the key is not present
§Returns
A mutable reference to the value (either existing or newly inserted)
Sourcepub fn get_or_insert_with<F>(&mut self, key: K, f: F) -> &mut Vwhere
F: FnOnce() -> V,
pub fn get_or_insert_with<F>(&mut self, key: K, f: F) -> &mut Vwhere
F: FnOnce() -> V,
Gets the value corresponding to the key, or inserts a computed default value if not present.
If the key exists in the map, returns a mutable reference to the existing value. If the key does not exist, calls the provided closure to compute a value, inserts it, and returns a mutable reference to it.
§Arguments
key- The key to look up or insertf- A closure that computes the value to insert if the key is not present
§Returns
A mutable reference to the value (either existing or newly inserted)
Sourcepub fn contains_key(&self, key: K) -> bool
pub fn contains_key(&self, key: K) -> bool
Returns true if the map contains a value for the specified key.
§Arguments
key- The key to check for
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.
§Arguments
key- The key to insertvalue- The value to associate with the key
§Returns
The previous value associated with the key, if any
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 pairs (k, v) such that f(&k, &mut v)
returns false.
Sourcepub fn iter(&self) -> Iter<'_, K, V>
pub fn iter(&self) -> Iter<'_, K, V>
Returns an iterator over the key-value pairs of the map.
The iterator yields pairs in the order of their index values.
Sourcepub fn iter_mut(&mut self) -> IterMut<'_, K, V>
pub fn iter_mut(&mut self) -> IterMut<'_, K, V>
Returns a mutable iterator over the key-value pairs of the map.
Sourcepub fn values_mut(&mut self) -> IterMut<'_, V> ⓘ
pub fn values_mut(&mut self) -> IterMut<'_, V> ⓘ
Returns a mutable iterator over the values of the map.
Sourcepub fn rank(&self, key: K) -> usize
pub fn rank(&self, key: K) -> usize
Finds the position in the values vector for the given index.
This counts the number of set bits before the given index to determine where the corresponding value is stored in the packed values vector.
Sourcepub fn first(&self) -> Option<(K, &V)>
pub fn first(&self) -> Option<(K, &V)>
Returns the first (minimum) key-value pair in the map, or None if the
map is empty.
Trait Implementations§
Source§impl<'de, K: TrySparseIndex + Deserialize<'de>, V: Deserialize<'de>> Deserialize<'de> for SparseMap<K, V>
impl<'de, K: TrySparseIndex + Deserialize<'de>, V: Deserialize<'de>> Deserialize<'de> for SparseMap<K, V>
Source§fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>where
D: Deserializer<'de>,
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>where
D: Deserializer<'de>,
impl<K, V: Eq> Eq for SparseMap<K, V>
Source§impl<K: TrySparseIndex, V> Extend<(K, V)> for SparseMap<K, V>
impl<K: TrySparseIndex, V> Extend<(K, V)> for SparseMap<K, V>
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: TrySparseIndex, V> FromIterator<(K, V)> for SparseMap<K, V>
impl<K: TrySparseIndex, V> FromIterator<(K, V)> for SparseMap<K, V>
Source§impl<K: TrySparseIndex, V> Index<K> for SparseMap<K, V>
impl<K: TrySparseIndex, V> Index<K> for SparseMap<K, V>
Source§impl<K: TrySparseIndex, V> IndexMut<K> for SparseMap<K, V>
impl<K: TrySparseIndex, V> IndexMut<K> for SparseMap<K, V>
Source§impl<'a, K: TrySparseIndex, V> IntoIterator for &'a SparseMap<K, V>
impl<'a, K: TrySparseIndex, V> IntoIterator for &'a SparseMap<K, V>
Source§impl<'a, K: TrySparseIndex, V> IntoIterator for &'a mut SparseMap<K, V>
impl<'a, K: TrySparseIndex, V> IntoIterator for &'a mut SparseMap<K, V>
Source§type IntoIter = impl DoubleEndedIterator + ExactSizeIterator + FusedIterator
type IntoIter = impl DoubleEndedIterator + ExactSizeIterator + FusedIterator
Source§impl<K: TrySparseIndex, V> IntoIterator for SparseMap<K, V>
impl<K: TrySparseIndex, V> IntoIterator for SparseMap<K, V>
Source§type IntoIter = impl DoubleEndedIterator + ExactSizeIterator + FusedIterator
type IntoIter = impl DoubleEndedIterator + ExactSizeIterator + FusedIterator
Auto Trait Implementations§
impl<K, V> Freeze for SparseMap<K, V>
impl<K, V> RefUnwindSafe for SparseMap<K, V>where
K: RefUnwindSafe,
V: RefUnwindSafe,
impl<K, V> Send for SparseMap<K, V>
impl<K, V> Sync for SparseMap<K, V>
impl<K, V> Unpin for SparseMap<K, V>
impl<K, V> UnsafeUnpin for SparseMap<K, V>
impl<K, V> UnwindSafe for SparseMap<K, V>where
K: UnwindSafe,
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,
impl<T> DeserializeOwned for Twhere
T: for<'de> Deserialize<'de>,
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read more