[board] Fix a counter underflow in the piece set

During perft runs, the PieceSet counter would occasionally underflow, causing
the whole program to crash. This is because, when building a Board from a list
of bitboards, Counts::increment() was only being called once, even when the
bitboard had more than one piece in it. Fix the bug by incrementing during the
loop that sets up the mailbox.

Additionally, refactor the increment() and decrement() methods to be a little
more succinct.
This commit is contained in:
Eryn Wells 2025-08-15 16:15:09 -07:00
parent 3d73760146
commit 182bf81126
2 changed files with 11 additions and 11 deletions

View file

@ -51,11 +51,10 @@ impl PieceSet {
color_occupancy[color_index] |= bitboard;
shape_occupancy[shape_index] |= bitboard;
counts.increment(color, shape);
for square in bitboard.occupied_squares(&IterationDirection::default()) {
let piece = Piece::new(color, shape);
mailbox.set(piece, square);
counts.increment(color, shape);
}
}
}

View file

@ -17,20 +17,21 @@ impl Counts {
const SQUARE_NUM: u8 = Square::NUM as u8;
let updated_value = self.0[color as usize][shape as usize] + 1;
if updated_value <= SQUARE_NUM {
self.0[color as usize][shape as usize] = updated_value;
} else {
unreachable!("piece count for {color} {shape} overflowed");
if updated_value > SQUARE_NUM {
let shape_name = shape.name();
panic!("piece count for {color} {shape_name} overflowed");
}
self.0[color as usize][shape as usize] = updated_value;
}
pub fn decrement(&mut self, color: Color, shape: Shape) {
let count = self.0[color as usize][shape as usize];
if let Some(updated_count) = count.checked_sub(1) {
let updated_count = count.checked_sub(1).unwrap_or_else(|| {
let shape_name = shape.name();
panic!("piece count for {color} {shape_name} should not underflow");
});
self.0[color as usize][shape as usize] = updated_count;
} else {
unreachable!("piece count for {color} {shape} underflowed");
}
}
#[cfg(test)]