Skip to main content

SparseMap

Struct SparseMap 

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

Source

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
Source

pub const fn new() -> Self

Creates a new empty sparse index map.

Source

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
Source

pub const fn len(&self) -> usize

Returns the number of key-value pairs in the map.

Source

pub const fn is_empty(&self) -> bool

Returns true if the map contains no elements.

Source

pub const fn capacity(&self) -> usize

Returns the capacity of the underlying bitmap.

Source

pub fn clear(&mut self)

Clears the map, removing all key-value pairs.

Source

pub fn shrink_to_fit(&mut self)

Shrinks the capacity of the map as much as possible.

Source

pub fn reserve(&mut self, additional: usize)

Reserves capacity for at least additional more elements to be inserted in the map.

Source

pub const fn key_set(&self) -> &SparseSet<K>

Returns a set of all keys in the map.

Source

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

Source

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 values
  • values - 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>

Source

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

Gets a reference to the value corresponding to the key.

§Arguments
  • key - The key to look up
§Returns

A reference to the value, or None if the key is not present

Source

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

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

§Arguments
  • key - The key to look up
§Returns

A mutable reference to the value, or None if the key is not present

Source

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 insert
  • value - The value to insert if the key is not present
§Returns

A mutable reference to the value (either existing or newly inserted)

Source

pub fn get_or_insert_with<F>(&mut self, key: K, f: F) -> &mut V
where 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 insert
  • f - 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)

Source

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
Source

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 insert
  • value - The value to associate with the key
§Returns

The previous value associated with the key, if any

Source

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

Removes a key from the map, returning the value at the key if the key was previously in the map.

§Arguments
  • key - The key to remove
§Returns

The removed value, or None if the key was not present

Source

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

Retains only the elements specified by the predicate.

In other words, remove all pairs (k, v) such that f(&k, &mut v) returns false.

Source

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.

Source

pub fn iter_mut(&mut self) -> IterMut<'_, K, V>

Returns a mutable iterator over the key-value pairs of the map.

Source

pub fn keys(&self) -> KeyIter<'_, K>

Returns an iterator over the keys of the map.

Source

pub fn values(&self) -> Iter<'_, V>

Returns an iterator over the values of the map.

Source

pub fn values_mut(&mut self) -> IterMut<'_, V>

Returns a mutable iterator over the values of the map.

Source

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.

Source

pub fn first(&self) -> Option<(K, &V)>

Returns the first (minimum) key-value pair in the map, or None if the map is empty.

Source

pub fn last(&self) -> Option<(K, &V)>

Returns the last (maximum) key-value pair in the map, or None if the map is empty.

Source

pub fn is_sparse(&self) -> bool

Returns true if the map has holes (gaps) in its indices.

A map is considered sparse if there are missing indices between the first and last elements. An empty map or a map with a single element is considered non-sparse.

Trait Implementations§

Source§

impl<K, V: Clone> Clone for SparseMap<K, V>

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<K: TrySparseIndex + Debug, V: Debug> Debug for SparseMap<K, V>

Source§

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

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

impl<K, V> Default for SparseMap<K, V>

Source§

fn default() -> Self

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

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

Deserialize this value from the given Serde deserializer. Read more
Source§

impl<K, V: Eq> Eq for SparseMap<K, V>

Source§

impl<K: TrySparseIndex, V> Extend<(K, V)> for SparseMap<K, V>

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: TrySparseIndex, V> FromIterator<(K, V)> for SparseMap<K, V>

Source§

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

Creates a value from an iterator. Read more
Source§

impl<K: TrySparseIndex, V> Index<K> for SparseMap<K, V>

Source§

type Output = V

The returned type after indexing.
Source§

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

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

impl<K: TrySparseIndex, V> IndexMut<K> for SparseMap<K, V>

Source§

fn index_mut(&mut self, key: K) -> &mut Self::Output

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

impl<'a, K: TrySparseIndex, V> IntoIterator for &'a SparseMap<K, V>

Source§

type IntoIter = impl DoubleEndedIterator + ExactSizeIterator + FusedIterator + Clone

Which kind of iterator are we turning this into?
Source§

type Item = (K, &'a V)

The type of the elements being iterated over.
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl<'a, K: TrySparseIndex, V> IntoIterator for &'a mut SparseMap<K, V>

Source§

type IntoIter = impl DoubleEndedIterator + ExactSizeIterator + FusedIterator

Which kind of iterator are we turning this into?
Source§

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

The type of the elements being iterated over.
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl<K: TrySparseIndex, V> IntoIterator for SparseMap<K, V>

Source§

type IntoIter = impl DoubleEndedIterator + ExactSizeIterator + FusedIterator

Which kind of iterator are we turning this into?
Source§

type Item = (K, V)

The type of the elements being iterated over.
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl<K, V: PartialEq> PartialEq for SparseMap<K, V>

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl<K: TrySparseIndex + Serialize, V: Serialize> Serialize for SparseMap<K, V>

Source§

fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

§

impl<K, V> Freeze for SparseMap<K, V>

§

impl<K, V> RefUnwindSafe for SparseMap<K, V>

§

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

§

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

§

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

§

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> 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<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts 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 more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

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