1
0
Fork 0

update bitboards

This commit is contained in:
Paul-Nicolas Madelaine 2025-11-26 23:03:23 +01:00
parent 85c7c8eb52
commit ecb82b3120

View file

@ -2,24 +2,24 @@
use crate::board::*;
use core::iter::ExactSizeIterator;
use core::iter::FusedIterator;
/// A set of squares.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Bitboard(pub u64);
impl Bitboard {
/// Makes a new, empty `Bitboard`.
#[inline]
pub const fn new() -> Self {
Self(0)
}
/// Returns `true` if the bitboard contains the given square.
#[inline]
pub const fn is_empty(&self) -> bool {
self.0 == 0
pub const fn contains(&self, square: Square) -> bool {
self.0 & (1 << square as u8) != 0
}
/// Returns the first square in the bitboard, if any.
#[inline]
pub const fn first(&self) -> Option<Square> {
let mask = self.0;
@ -29,19 +29,19 @@ impl Bitboard {
}
}
/// Returns the last square in the bitboard, if any.
#[inline]
pub const fn last(&self) -> Option<Square> {
let mask = self.0;
match mask {
0 => None,
_ => Some(unsafe {
Square::new_unchecked(63_u8.unchecked_sub(mask.leading_zeros() as u8))
}),
_ => Some(unsafe { Square::new_unchecked(63 ^ mask.leading_zeros() as u8) }),
}
}
/// Removes the first square from the bitboard and returns it, if any.
#[inline]
pub const fn pop(&mut self) -> Option<Square> {
pub const fn pop_first(&mut self) -> Option<Square> {
let mask = &mut self.0;
let square = match mask {
0 => None,
@ -51,21 +51,32 @@ impl Bitboard {
square
}
/// Adds a square to the bitboard.
#[inline]
pub const fn insert(&mut self, square: Square) {
self.0 |= 1 << square as u8;
}
#[inline]
pub const fn contains(&self, square: Square) -> bool {
self.0 & (1 << square as u8) != 0
}
/// Removes a square from the bitboard.
#[inline]
pub const fn remove(&mut self, square: Square) {
self.0 &= !(1 << square as u8);
}
/// Returns the number of squares in the bitboard.
#[inline]
pub const fn len(&self) -> usize {
self.0.count_ones() as usize
}
/// Returns `true` if the bitboard contains no squares.
#[inline]
pub const fn is_empty(&self) -> bool {
self.0 == 0
}
/// Returns the mirror image of the bitboard. This is the set of the mirror images of all the
/// squares in the bitboard.
#[inline]
pub const fn mirror(self) -> Bitboard {
let [a, b, c, d, e, f, g, h] = self.0.to_le_bytes();
@ -138,7 +149,7 @@ impl Iterator for Bitboard {
type Item = Square;
#[inline]
fn next(&mut self) -> Option<Self::Item> {
self.pop()
self.pop_first()
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
@ -174,11 +185,11 @@ impl Iterator for Bitboard {
acc
}
}
impl FusedIterator for Bitboard {}
impl ExactSizeIterator for Bitboard {
impl core::iter::FusedIterator for Bitboard {}
impl core::iter::ExactSizeIterator for Bitboard {
#[inline]
fn len(&self) -> usize {
self.0.count_ones() as usize
self.len()
}
}