[board] Implement a TrailingBitScanner

This bit scanner iterates populated bits in a BitBoard from the trailing (least-significant) end.

Rename BitScanner → LeadingBitScanner.
Factor implementation of these two into a macro.
Clean up iterator returned by BitBoard::occupied_squares
Implement BitBoard::occupied_squares_trailing
This commit is contained in:
Eryn Wells 2024-01-06 19:41:26 -08:00
parent 35756e28cf
commit 2394afc210
3 changed files with 83 additions and 22 deletions

View file

@ -1,8 +1,8 @@
// Eryn Wells <eryn@erynwells.me>
use super::library::{library, FILES, RANKS};
use super::BitScanner;
use crate::Square;
use super::{LeadingBitScanner, TrailingBitScanner};
use crate::{square::Direction, Square};
use std::fmt;
use std::ops::{BitAnd, BitAndAssign, BitOr, BitOrAssign, Not};
@ -62,11 +62,16 @@ impl BitBoard {
}
impl BitBoard {
/// Return an Iterator over the occupied squares, starting from the leading
/// (most-significant bit) end of the field.
pub(crate) fn occupied_squares(&self) -> impl Iterator<Item = Square> {
BitScanner::new(self.0)
.map(|x| u8::try_from(x))
.take_while(|x| x.is_ok())
.map(|x| Square::from_index(x.unwrap() as usize))
LeadingBitScanner::new(self.0).map(Square::from_index)
}
/// Return an Iterator over the occupied squares, starting from the trailing
/// (least-significant bit) end of the field.
pub(crate) fn occupied_squares_trailing(&self) -> impl Iterator<Item = Square> {
LeadingBitScanner::new(self.0).map(Square::from_index)
}
}