Skip to content

Commit

Permalink
Merge pull request #7 from dewert99/bitset
Browse files Browse the repository at this point in the history
Make bitset public
  • Loading branch information
dewert99 authored May 29, 2024
2 parents b97e663 + 5e85eb7 commit 4c1cd1b
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/raw.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ mod semi_persistent;
/// One variant of semi_persistence
pub mod semi_persistent1;

mod bitset;
/// A simple bitset
pub mod bitset;
pub(crate) mod language;
/// Another variant of semi_persistence
pub mod semi_persistent2;
Expand Down
14 changes: 14 additions & 0 deletions src/raw/bitset.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use serde::{Deserialize, Serialize};
use std::fmt::{Debug, Formatter};
use std::mem;

/// A mapping from indexes to values where all indexes initially map to [`Default::default`]
#[derive(Debug, Default, Clone)]
#[cfg_attr(feature = "serde-1", derive(Serialize, Deserialize))]
pub struct DefaultVec<T>(Box<[T]>);
Expand All @@ -19,6 +20,7 @@ impl<T: Default> DefaultVec<T> {
assert!(i < self.0.len())
}

/// Returns mutable access to the element at `i`
pub fn get_mut(&mut self, i: usize) -> &mut T {
if i < self.0.len() {
&mut self.0[i]
Expand All @@ -28,13 +30,15 @@ impl<T: Default> DefaultVec<T> {
}
}

/// Returns shared access to the element at `i`
pub fn get(&self, i: usize) -> T
where
T: Copy,
{
self.0.get(i).copied().unwrap_or_default()
}

/// Resets all elements to there default value
pub fn clear(&mut self) {
self.0.fill_with(Default::default)
}
Expand All @@ -52,21 +56,27 @@ fn split(x: usize) -> (usize, Elt) {
(x / Elt::BITS as usize, 1 << offset)
}

/// Set of indexes
impl BitSet {
/// Adds an element to the set
pub fn insert(&mut self, x: usize) -> bool {
let (chunk_idx, mask) = split(x);
let chunk = self.0.get_mut(chunk_idx);
let res = (*chunk & mask) != 0;
*chunk |= mask;
res
}

/// Removes an element form the set
pub fn remove(&mut self, x: usize) -> bool {
let (chunk_idx, mask) = split(x);
let chunk = self.0.get_mut(chunk_idx);
let res = (*chunk & mask) != 0;
*chunk &= !mask;
res
}

/// Checks if the set contains an element
pub fn contains(&self, x: usize) -> bool {
let (chunk_idx, mask) = split(x);
let chunk = self.0.get(chunk_idx);
Expand All @@ -80,10 +90,14 @@ impl BitSet {
(chunk & mask) != 0
}

/// Removes all elements from the set
pub fn clear(&mut self) {
self.0.clear()
}

/// Iterate over all elements in the set
/// Run time is proportional to the largest element that has ever been in the set
pub fn iter(&self) -> impl Iterator<Item = usize> + '_ {
let max = self.0 .0.len() * (Elt::BITS as usize);
(0..max).filter(|x| self.contains(*x))
Expand Down

0 comments on commit 4c1cd1b

Please sign in to comment.