aoc/util/
bitset.rs

1//! Add `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    fn biterator(self) -> Bitset<T>;
7}
8
9impl<T: Integer<T>> BitOps<T> for T {
10    fn biterator(self) -> Bitset<T> {
11        Bitset { t: self }
12    }
13}
14
15pub struct Bitset<T> {
16    t: T,
17}
18
19impl<T: Integer<T>> Iterator for Bitset<T> {
20    type Item = usize;
21
22    #[inline]
23    fn next(&mut self) -> Option<Self::Item> {
24        if self.t == T::ZERO {
25            None
26        } else {
27            let tz = self.t.trailing_zeros();
28            self.t = self.t ^ (T::ONE << tz);
29            Some(tz as usize)
30        }
31    }
32}