Skip to main content

aoc/util/
bitset.rs

1//! Add a `biterator` method that treats an integer as a set, iterating over each element where
2//! the respective bit is set. For example `1101` would return 0, 2 and 3.
3use crate::util::integer::*;
4
5pub trait BitOps<T> {
6    #[must_use]
7    fn biterator(self) -> Bitset<T>;
8}
9
10impl<T: Integer<T>> BitOps<T> for T {
11    fn biterator(self) -> Bitset<T> {
12        Bitset { t: self }
13    }
14}
15
16pub struct Bitset<T> {
17    t: T,
18}
19
20impl<T: Integer<T>> Iterator for Bitset<T> {
21    type Item = usize;
22
23    #[inline]
24    fn next(&mut self) -> Option<Self::Item> {
25        let low = self.t.lowest_one()?;
26        self.t = self.t ^ (T::ONE << low);
27        Some(low as usize)
28    }
29}