Skip to main content

SparseSet

Struct SparseSet 

Source
pub struct SparseSet<K> { /* private fields */ }
Expand description

A sparse set of keys convertible to indices.

SparseSet provides an efficient storage mechanism for sets where keys can be converted to usize indices. It uses a bitmap to track which indices are present, 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_set::SparseSet};

#[repr(usize)]
#[derive(Copy, Clone, Debug, PartialEq)]
enum Status {
	Active  = 0,
	Pending = 1,
	Closed  = 2,
}

#[derive(Debug)]
struct StatusError(&'static str);

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")),
		}
	}
}

let mut set = SparseSet::new();
set.insert(Status::Active);
set.insert(Status::Closed);

assert!(set.contains(Status::Active));
assert!(!set.contains(Status::Pending));

Implementations§

Source§

impl<K> SparseSet<K>

Source

pub const fn new() -> Self

Creates a new empty sparse index set.

Source

pub fn with_capacity(capacity: usize) -> Self

Creates a new sparse index set with the specified capacity.

§Arguments
  • capacity - The maximum index that might be stored
Source

pub fn len(&self) -> usize

Returns the number of elements in the set.

Source

pub fn is_empty(&self) -> bool

Returns true if the set 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 set, removing all elements.

Source

pub fn shrink_to_fit(&mut self)

Shrinks the capacity of the set 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 set.

Source

pub fn into_parts(self) -> SmolBitmap

Decomposes the set into its raw bitmap.

§Returns

The underlying SmolBitmap

Source

pub const fn from_parts(bits: SmolBitmap) -> Self

Constructs a sparse set from its raw bitmap.

§Arguments
  • bits - The bitmap tracking which indices are present
Source

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

Returns true if the set is a subset of another.

Source

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

Returns true if the set is a superset of another.

Source

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

Returns true if the set has no elements in common with another.

Source

pub fn union(&self, other: &Self) -> Self

Computes the union with another set.

Source

pub fn intersection(&self, other: &Self) -> Self

Computes the intersection with another set.

Source

pub fn difference(&self, other: &Self) -> Self

Computes the difference with another set.

Source

pub fn symmetric_difference(&self, other: &Self) -> Self

Computes the symmetric difference with another set.

Source§

impl<K: TrySparseIndex> SparseSet<K>

Source

pub fn contains(&self, key: K) -> bool

Returns true if the set contains the specified key.

§Arguments
  • key - The key to check for
Source

pub fn insert(&mut self, key: K) -> bool

Adds a key to the set.

If the set did not have this key present, true is returned. If the set did have this key present, false is returned.

§Arguments
  • key - The key to insert
§Returns

true if the key was newly inserted, false if it was already present

Source

pub fn remove(&mut self, key: K) -> bool

Removes a key from the set.

§Arguments
  • key - The key to remove
§Returns

true if the key was present, false otherwise

Source

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

Retains only the elements specified by the predicate.

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

Source

pub fn iter(&self) -> Iter<'_, K>

Returns an iterator over the keys of the set.

The iterator yields keys in the order of their index values.

Source

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

Returns the minimum (first) element in the set, or None if the set is empty.

Source

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

Returns the maximum (last) element in the set, or None if the set is empty.

Source

pub fn is_sparse(&self) -> bool

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

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

Trait Implementations§

Source§

impl<K> Clone for SparseSet<K>

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> Debug for SparseSet<K>

Source§

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

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

impl<K> Default for SparseSet<K>

Source§

fn default() -> Self

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

impl<'de, K: TrySparseIndex + Deserialize<'de>> Deserialize<'de> for SparseSet<K>

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> Eq for SparseSet<K>

Source§

impl<K: TrySparseIndex> Extend<K> for SparseSet<K>

Source§

fn extend<T: IntoIterator<Item = K>>(&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> FromIterator<K> for SparseSet<K>

Source§

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

Creates a value from an iterator. Read more
Source§

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

Source§

type IntoIter = impl DoubleEndedIterator + ExactSizeIterator + FusedIterator + Clone

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

type Item = K

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> IntoIterator for SparseSet<K>

Source§

type IntoIter = impl DoubleEndedIterator + ExactSizeIterator + FusedIterator + Clone

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

type Item = K

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> PartialEq for SparseSet<K>

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> Serialize for SparseSet<K>

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> Freeze for SparseSet<K>

§

impl<K> RefUnwindSafe for SparseSet<K>
where K: RefUnwindSafe,

§

impl<K> Send for SparseSet<K>
where K: Send,

§

impl<K> Sync for SparseSet<K>
where K: Sync,

§

impl<K> Unpin for SparseSet<K>
where K: Unpin,

§

impl<K> UnsafeUnpin for SparseSet<K>

§

impl<K> UnwindSafe for SparseSet<K>
where K: 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.