From e30bcb3105a319996bbec2f75cb27a541651b60c Mon Sep 17 00:00:00 2001 From: Eryn Wells Date: Sat, 30 Dec 2023 10:26:37 -0800 Subject: [PATCH] [board] Implement BitBoard::file and fmt::Display for BitBoard BitBoard::file returns a BitBoard representing the 0-indexed file. fmt::Display prints a grid of bits in the standard orientation (white on bottom, left to right) Add asserts to the rank and file constructors to catch out of bounds arguments. --- board/src/bitboard/bitboard.rs | 36 ++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/board/src/bitboard/bitboard.rs b/board/src/bitboard/bitboard.rs index 31b5ec4..132f329 100644 --- a/board/src/bitboard/bitboard.rs +++ b/board/src/bitboard/bitboard.rs @@ -18,9 +18,15 @@ impl BitBoard { } pub fn rank(rank: u8) -> BitBoard { + assert!(rank < 8); BitBoard(0xFF).shift_north(rank) } + pub fn file(file: u8) -> BitBoard { + assert!(file < 8); + BitBoard(0x0101010101010101).shift_east(file) + } + pub fn is_empty(&self) -> bool { self.0 == 0 } @@ -68,6 +74,29 @@ impl fmt::UpperHex for BitBoard { } } +impl fmt::Display for BitBoard { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let binary_ranks = format!("{:064b}", self.0) + .chars() + .rev() + .map(|c| String::from(c)) + .collect::>(); + + let mut ranks_written = 0; + for rank in binary_ranks.chunks(8).rev() { + let joined_rank = rank.join(" "); + write!(f, "{}", joined_rank)?; + + ranks_written += 1; + if ranks_written < 8 { + write!(f, "\n")?; + } + } + + Ok(()) + } +} + impl fmt::Debug for BitBoard { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { f.debug_tuple("BitBoard") @@ -136,6 +165,13 @@ mod tests { use super::*; use crate::Square; + #[test] + fn display_and_debug() { + let bb = BitBoard::file(0) | BitBoard::file(3) | BitBoard::rank(7) | BitBoard::rank(4); + println!("{}", &bb); + println!("{:?}", &bb); + } + #[test] fn rank() { assert_eq!(BitBoard::rank(0).0, 0xFF, "Rank 1");