bitit 0.1.2

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

/// An iterator over the bits in a value in reverse.
/// Represents each bit from most significant to lease significant as a boolean.
///
/// # Examples
/// ```
/// use bitit::BitIter;
///
/// let x = 0b10101100u8;
/// let mut iter = x.bits_rev();
///
/// assert_eq!(iter.next(), Some(true));
/// assert_eq!(iter.next(), Some(false));
/// assert_eq!(iter.next(), Some(true));
/// assert_eq!(iter.next(), Some(false));
/// assert_eq!(iter.next(), Some(true));
/// assert_eq!(iter.next(), Some(true));
/// assert_eq!(iter.next(), Some(false));
/// assert_eq!(iter.next(), Some(false));
/// assert_eq!(iter.next(), None);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BitsRev<T: Binary> {
    /// The value being iterated.
    n: T,

    /// A mask of the bit that is being checked.
    b: T,
}

impl<T: Binary> BitsRev<T> {
    pub const fn new(n: T) -> Self {
        Self { n, b: T::TOP }
    }
}

impl<T: Binary> Iterator for BitsRev<T> {
    type Item = bool;

    fn next(&mut self) -> Option<Self::Item> {
        // This will stop when shifting right by one pushes out the single 1-bit.
        self.b.has_one().then(|| {
            // Get the current bit and push the mask.
            let x = self.n & self.b;
            self.b >>= 1;

            x != T::ZERO
        })
    }
}