Your browser sucks, JavaScript disabled! Gunnar's console needs JavaScript and WebAssembly. Git over SSH on port 2222 does not.

nordisk/kleene

crates/kleene-sparse/src/bitset.rs

/// A fixed-length set of bits, one per position, 64 to a word.
#[derive(Clone, PartialEq, Eq, Default)]
pub struct Bitset {
    words: Vec<u64>,
    len: usize,
}

impl std::fmt::Debug for Bitset {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Bitset({} of {})", self.count(), self.len)
    }
}

impl Bitset {
    /// `len` bits, all clear.
    pub fn new(len: usize) -> Self {
        Bitset {
            words: vec![0; len.div_ceil(64)],
            len,
        }
    }

    /// `len` bits, all set.
    pub fn full(len: usize) -> Self {
        let mut b = Bitset {
            words: vec![u64::MAX; len.div_ceil(64)],
            len,
        };
        b.clear_tail();
        b
    }

    /// `len` bits with the given positions set; a position at or past `len` is left out.
    pub fn from_indices(len: usize, indices: impl IntoIterator<Item = u32>) -> Self {
        let mut b = Bitset::new(len);
        for i in indices {
            if (i as usize) < len {
                b.set(i as usize);
            }
        }
        b
    }

    fn clear_tail(&mut self) {
        let r = self.len % 64;
        if r != 0
            && let Some(last) = self.words.last_mut()
        {
            *last &= (1u64 << r) - 1;
        }
    }

    /// The number of positions.
    pub fn len(&self) -> usize {
        self.len
    }

    /// True when there are no positions.
    pub fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// Whether bit `i` is set (false past the end).
    #[inline]
    pub fn get(&self, i: usize) -> bool {
        i < self.len && (self.words[i >> 6] >> (i & 63)) & 1 == 1
    }

    /// Set bit `i`; returns whether it was clear before.
    #[inline]
    pub fn set(&mut self, i: usize) -> bool {
        let w = &mut self.words[i >> 6];
        let m = 1u64 << (i & 63);
        let was = *w & m == 0;
        *w |= m;
        was
    }

    /// Clear bit `i`.
    #[inline]
    pub fn unset(&mut self, i: usize) {
        self.words[i >> 6] &= !(1u64 << (i & 63));
    }

    /// Clear every bit.
    pub fn clear(&mut self) {
        self.words.fill(0);
    }

    /// Become a copy of `other` (no allocation when the lengths agree).
    pub fn copy_from(&mut self, other: &Bitset) {
        self.words.clone_from(&other.words);
        self.len = other.len;
    }

    /// The number of set bits.
    pub fn count(&self) -> usize {
        crate::simd::Simd::detect().popcount(&self.words)
    }

    /// Set every bit that is set in `other` (same length).
    pub fn union_with(&mut self, other: &Bitset) {
        crate::simd::Simd::detect().or_assign(&mut self.words, &other.words);
    }

    /// Keep only the bits also set in `other` (same length).
    pub fn intersect_with(&mut self, other: &Bitset) {
        crate::simd::Simd::detect().and_assign(&mut self.words, &other.words);
    }

    /// Clear every bit that is set in `other` (same length).
    pub fn subtract(&mut self, other: &Bitset) {
        crate::simd::Simd::detect().and_not_assign(&mut self.words, &other.words);
    }

    /// Flip every bit.
    pub fn invert(&mut self) {
        for w in &mut self.words {
            *w = !*w;
        }
        self.clear_tail();
    }

    /// The set positions, rising.
    pub fn iter(&self) -> impl Iterator<Item = u32> + '_ {
        self.words.iter().enumerate().flat_map(|(wi, &w)| {
            let mut w = w;
            std::iter::from_fn(move || {
                if w == 0 {
                    return None;
                }
                let t = w.trailing_zeros();
                w &= w - 1;
                Some((wi as u32) * 64 + t)
            })
        })
    }

    /// The positions that are clear, rising.
    pub fn iter_clear(&self) -> impl Iterator<Item = u32> + '_ {
        let len = self.len;
        self.words.iter().enumerate().flat_map(move |(wi, &w)| {
            let mut w = !w;
            if (wi + 1) * 64 > len {
                let r = len - wi * 64;
                if r < 64 {
                    w &= (1u64 << r) - 1;
                }
            }
            std::iter::from_fn(move || {
                if w == 0 {
                    return None;
                }
                let t = w.trailing_zeros();
                w &= w - 1;
                Some((wi as u32) * 64 + t)
            })
        })
    }

    /// The words, 64 positions each, the last one's unused bits clear.
    pub fn words(&self) -> &[u64] {
        &self.words
    }

    /// The words to write in place; the caller keeps bits past the length clear.
    pub(crate) fn words_mut(&mut self) -> &mut [u64] {
        &mut self.words
    }

    /// The words, given back (to be reused, say, as [`Bitset::from_words`] takes them).
    pub fn into_words(self) -> Vec<u64> {
        self.words
    }

    /// A bitset of `len` bits from its words (bits past `len` are cleared).
    pub fn from_words(len: usize, mut words: Vec<u64>) -> Self {
        words.resize(len.div_ceil(64), 0);
        let mut b = Bitset { words, len };
        b.clear_tail();
        b
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn set_get_count_and_iterate() {
        let mut b = Bitset::new(130);
        assert!(b.set(0));
        assert!(b.set(64));
        assert!(b.set(129));
        assert!(!b.set(64));
        assert!(b.get(129) && !b.get(128) && !b.get(500));
        assert_eq!(b.count(), 3);
        assert_eq!(b.iter().collect::<Vec<_>>(), vec![0, 64, 129]);
    }

    #[test]
    fn full_and_invert_keep_the_tail_clear() {
        let mut b = Bitset::full(70);
        assert_eq!(b.count(), 70);
        b.unset(3);
        b.invert();
        assert_eq!(b.iter().collect::<Vec<_>>(), vec![3]);
    }

    #[test]
    fn clear_positions_stop_at_the_length() {
        let b = Bitset::from_indices(67, [0, 2, 64]);
        let clear: Vec<u32> = b.iter_clear().collect();
        assert_eq!(clear.len(), 64);
        assert!(!clear.contains(&64) && clear.contains(&66) && !clear.contains(&67));
    }

    #[test]
    fn union_and_intersection() {
        let mut a = Bitset::from_indices(10, [1, 2, 3]);
        let b = Bitset::from_indices(10, [3, 4]);
        let mut c = a.clone();
        a.union_with(&b);
        c.intersect_with(&b);
        assert_eq!(a.iter().collect::<Vec<_>>(), vec![1, 2, 3, 4]);
        assert_eq!(c.iter().collect::<Vec<_>>(), vec![3]);
    }
}