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    #[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        if self.t == T::ZERO {
26            None
27        } else {
28            let tz = self.t.trailing_zeros();
29            self.t = self.t ^ (T::ONE << tz);
30            Some(tz as usize)
31        }
32    }
33}