chessfriend/bitboard/src/shifts.rs
2025-05-16 07:44:59 -07:00

123 lines
2.9 KiB
Rust

// Eryn Wells <eryn@erynwells.me>
use super::BitBoard;
impl BitBoard {
const NOT_A_FILE: u64 = 0xfefe_fefe_fefe_fefe;
const NOT_H_FILE: u64 = 0x7f7f_7f7f_7f7f_7f7f;
#[inline]
pub fn shift_north(&self, n: u8) -> BitBoard {
BitBoard(self.0 << (8 * n))
}
#[inline]
pub fn shift_north_one(&self) -> BitBoard {
BitBoard(self.0 << 8)
}
#[inline]
pub fn shift_north_east_one(&self) -> BitBoard {
BitBoard(self.0 << 9 & BitBoard::NOT_A_FILE)
}
#[inline]
pub fn shift_east(&self, n: u8) -> BitBoard {
// TODO: Implement a bounds check here.
BitBoard(self.0 << n)
}
#[inline]
pub fn shift_east_one(&self) -> BitBoard {
BitBoard(self.0 << 1 & BitBoard::NOT_A_FILE)
}
#[inline]
pub fn shift_south_east_one(&self) -> BitBoard {
BitBoard(self.0 >> 7 & BitBoard::NOT_A_FILE)
}
#[inline]
pub fn shift_south(&self, n: u8) -> BitBoard {
BitBoard(self.0 >> (8 * n))
}
#[inline]
pub fn shift_south_one(&self) -> BitBoard {
BitBoard(self.0 >> 8)
}
#[inline]
pub fn shift_south_west_one(&self) -> BitBoard {
BitBoard(self.0 >> 9 & BitBoard::NOT_H_FILE)
}
#[inline]
pub fn shift_west_one(&self) -> BitBoard {
BitBoard(self.0 >> 1 & BitBoard::NOT_H_FILE)
}
#[inline]
pub fn shift_north_west_one(&self) -> BitBoard {
BitBoard(self.0 << 7 & BitBoard::NOT_H_FILE)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn cardinal_direction_shifts() {
let bb = BitBoard(0x1000_0000); // e4
assert_eq!(bb.shift_north_one(), BitBoard(0x0010_0000_0000), "North");
assert_eq!(bb.shift_east_one(), BitBoard(0x2000_0000), "East");
assert_eq!(bb.shift_south_one(), BitBoard(0x0010_0000), "South");
assert_eq!(bb.shift_west_one(), BitBoard(0x0800_0000), "West");
}
#[test]
fn intercardinal_direction_shifts() {
let bb = BitBoard(0x1000_0000); // e4
assert_eq!(
bb.shift_north_east_one(),
BitBoard(0x0020_0000_0000),
"North East"
);
assert_eq!(
bb.shift_south_east_one(),
BitBoard(0x0020_0000),
"South East"
);
assert_eq!(
bb.shift_south_west_one(),
BitBoard(0x0008_0000),
"South West"
);
assert_eq!(
bb.shift_north_west_one(),
BitBoard(0x0008_0000_0000),
"North West"
);
}
#[test]
fn shift_n() {
assert_eq!(
BitBoard(0x0008_0000_0000).shift_north(2),
BitBoard(0x0008_0000_0000_0000)
);
assert_eq!(
BitBoard(0x0008_0000_0000).shift_east(2),
BitBoard(0x0020_0000_0000)
);
assert_eq!(
BitBoard(0x0008_0000_0000).shift_south(2),
BitBoard(0x0008_0000)
);
}
}