bitit 0.1.2

Bitwise iteration over integers.
Documentation
use crate::binary::Binary;

/// An iterator over the indices of the 1-bits in a binary value.
///
/// # Examples
/// ```
/// use bitit::BitIter;
///
/// let x = 0b10101100u8;
/// let mut iter = x.one_indices();
///
/// assert_eq!(iter.next(), Some(2));
/// assert_eq!(iter.next_back(), Some(7));
/// assert_eq!(iter.next(), Some(3));
/// assert_eq!(iter.next(), Some(5));
/// assert_eq!(iter.next(), None);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct OneIndices<T: Binary> {
    n: T,
}

impl<T: Binary> OneIndices<T> {
    pub const fn new(n: T) -> Self {
        Self { n }
    }
}

impl<T: Binary> Iterator for OneIndices<T> {
    type Item = u32;

    fn next(&mut self) -> Option<Self::Item> {
        self.n.has_one().then(|| {
            // Get the index of the least significant 1 and toggle it to 0.
            let i = self.n.trailing_zeros();
            self.n ^= T::ONE << i;

            i
        })
    }
}

impl<T: Binary> DoubleEndedIterator for OneIndices<T> {
    fn next_back(&mut self) -> Option<Self::Item> {
        self.n.has_one().then(|| {
            // Get the index of the most significant 1 and toggle it to 0.
            let i = T::MAX_BIT_IDX - self.n.leading_zeros();
            self.n ^= T::ONE << i;

            i
        })
    }
}