diff --git a/rustfmt.toml b/rustfmt.toml deleted file mode 100644 index e69de29..0000000 diff --git a/src/board/bitboard/mod.rs b/src/board/bitboard/mod.rs index 9059235..b0ec90a 100644 --- a/src/board/bitboard/mod.rs +++ b/src/board/bitboard/mod.rs @@ -1,4 +1,4 @@ -use super::{File, Rank, Square}; +use super::Square; use crate::utils::static_assert; mod error; @@ -21,7 +21,7 @@ impl Bitboard { pub const ALL: Bitboard = Bitboard(u64::MAX); /// Array of bitboards representing the eight ranks, in order from rank 1 to rank 8. - pub const RANKS: [Self; Rank::NUM_VARIANTS] = [ + pub const RANKS: [Self; 8] = [ Bitboard(0b00000001_00000001_00000001_00000001_00000001_00000001_00000001_00000001), Bitboard(0b00000010_00000010_00000010_00000010_00000010_00000010_00000010_00000010), Bitboard(0b00000100_00000100_00000100_00000100_00000100_00000100_00000100_00000100), @@ -33,7 +33,7 @@ impl Bitboard { ]; /// Array of bitboards representing the eight files, in order from file A to file H. - pub const FILES: [Self; File::NUM_VARIANTS] = [ + pub const FILES: [Self; 8] = [ Bitboard(0b00000000_00000000_00000000_00000000_00000000_00000000_00000000_11111111), Bitboard(0b00000000_00000000_00000000_00000000_00000000_00000000_11111111_00000000), Bitboard(0b00000000_00000000_00000000_00000000_00000000_11111111_00000000_00000000), diff --git a/src/board/castle_rights.rs b/src/board/castle_rights.rs index 5bd9d91..b34d952 100644 --- a/src/board/castle_rights.rs +++ b/src/board/castle_rights.rs @@ -18,24 +18,11 @@ impl CastleRights { pub const NUM_VARIANTS: usize = 4; /// Convert from a castle rights index into a [CastleRights] type. - /// - /// # Panics - /// - /// Panics if the index is out of bounds. #[inline(always)] pub fn from_index(index: usize) -> Self { - Self::try_from_index(index).expect("index out of bouds") - } - - /// Convert from a castle rights index into a [CastleRights] type. Returns [None] if the index - /// is out of bounds. - pub fn try_from_index(index: usize) -> Option { - if index < Self::NUM_VARIANTS { - // SAFETY: we know the value is in-bounds - Some(unsafe { Self::from_index_unchecked(index) }) - } else { - None - } + assert!(index < Self::NUM_VARIANTS); + // SAFETY: we know the value is in-bounds + unsafe { Self::from_index_unchecked(index) } } /// Convert from a castle rights index into a [CastleRights] type, no bounds checking. diff --git a/src/board/chess_board/builder.rs b/src/board/chess_board/builder.rs index 679b3b7..d16c881 100644 --- a/src/board/chess_board/builder.rs +++ b/src/board/chess_board/builder.rs @@ -1,10 +1,10 @@ -use crate::board::{Bitboard, CastleRights, ChessBoard, Color, Piece, Square, ValidationError}; +use crate::board::{Bitboard, CastleRights, ChessBoard, Color, InvalidError, Piece, Square}; /// Build a [ChessBoard] one piece at a time. #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] pub struct ChessBoardBuilder { /// The list of [Piece] on the board. Indexed by [Square::index]. - pieces: [Option<(Piece, Color)>; Square::NUM_VARIANTS], + pieces: [Option<(Piece, Color)>; 64], // Same fields as [ChessBoard]. castle_rights: [CastleRights; Color::NUM_VARIANTS], en_passant: Option, @@ -17,8 +17,8 @@ pub struct ChessBoardBuilder { impl ChessBoardBuilder { pub fn new() -> Self { Self { - pieces: [None; Square::NUM_VARIANTS], - castle_rights: [CastleRights::NoSide; Color::NUM_VARIANTS], + pieces: [None; 64], + castle_rights: [CastleRights::NoSide; 2], en_passant: Default::default(), half_move_clock: Default::default(), side: Color::White, @@ -80,7 +80,7 @@ impl std::ops::IndexMut for ChessBoardBuilder { } impl TryFrom for ChessBoard { - type Error = ValidationError; + type Error = InvalidError; fn try_from(builder: ChessBoardBuilder) -> Result { let mut piece_occupancy: [Bitboard; Piece::NUM_VARIANTS] = Default::default(); diff --git a/src/board/chess_board/error.rs b/src/board/chess_board/error.rs index bfc3bdc..7b570a4 100644 --- a/src/board/chess_board/error.rs +++ b/src/board/chess_board/error.rs @@ -1,6 +1,6 @@ -/// A singular type for all errors that could happen during [crate::board::ChessBoard::is_valid]. +/// A singular type for all errors that could happen during [ChessBoard::is_valid]. #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub enum ValidationError { +pub enum InvalidError { /// Too many pieces. TooManyPieces, /// Missing king. @@ -27,7 +27,7 @@ pub enum ValidationError { IncoherentPlieCount, } -impl std::fmt::Display for ValidationError { +impl std::fmt::Display for InvalidError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let error_msg = match self { Self::TooManyPieces => "Too many pieces.", @@ -53,4 +53,4 @@ impl std::fmt::Display for ValidationError { } } -impl std::error::Error for ValidationError {} +impl std::error::Error for InvalidError {} diff --git a/src/board/chess_board/mod.rs b/src/board/chess_board/mod.rs index 63dbe51..9ceb673 100644 --- a/src/board/chess_board/mod.rs +++ b/src/board/chess_board/mod.rs @@ -206,16 +206,16 @@ impl ChessBoard { self.validate().is_ok() } - /// Validate the state of the board. Return Err([ValidationError]) if an issue is found. - pub fn validate(&self) -> Result<(), ValidationError> { + /// Validate the state of the board. Return Err([InvalidError]) if an issue is found. + pub fn validate(&self) -> Result<(), InvalidError> { // The current plie count should be odd on white's turn, and vice-versa. if self.total_plies() % 2 != self.current_player().index() as u32 { - return Err(ValidationError::IncoherentPlieCount); + return Err(InvalidError::IncoherentPlieCount); } // Make sure the clocks are in agreement. if self.half_move_clock() > self.total_plies() { - return Err(ValidationError::HalfMoveClockTooHigh); + return Err(InvalidError::HalfMoveClockTooHigh); } // Don't overlap pieces. @@ -224,7 +224,7 @@ impl ChessBoard { for other in Piece::iter() { if piece != other { if !(self.piece_occupancy(piece) & self.piece_occupancy(other)).is_empty() { - return Err(ValidationError::OverlappingPieces); + return Err(InvalidError::OverlappingPieces); } } } @@ -232,7 +232,7 @@ impl ChessBoard { // Don't overlap colors. if !(self.color_occupancy(Color::White) & self.color_occupancy(Color::Black)).is_empty() { - return Err(ValidationError::OverlappingColors); + return Err(InvalidError::OverlappingColors); } // Calculate the union of all pieces. @@ -241,12 +241,12 @@ impl ChessBoard { // Ensure that the pre-computed version is accurate. if combined != self.combined_occupancy() { - return Err(ValidationError::ErroneousCombinedOccupancy); + return Err(InvalidError::ErroneousCombinedOccupancy); } // Ensure that all pieces belong to a color, and no color has pieces that don't exist. if combined != (self.color_occupancy(Color::White) | self.color_occupancy(Color::Black)) { - return Err(ValidationError::ErroneousCombinedOccupancy); + return Err(InvalidError::ErroneousCombinedOccupancy); } for color in Color::iter() { @@ -260,18 +260,18 @@ impl ChessBoard { _ => count <= 10, }; if !possible { - return Err(ValidationError::TooManyPieces); + return Err(InvalidError::TooManyPieces); } } // Check that we have a king if self.occupancy(Piece::King, color).count() != 1 { - return Err(ValidationError::MissingKing); + return Err(InvalidError::MissingKing); } // Check that don't have too many pieces in total if self.color_occupancy(color).count() > 16 { - return Err(ValidationError::TooManyPieces); + return Err(InvalidError::TooManyPieces); } } @@ -280,7 +280,7 @@ impl ChessBoard { & (Rank::First.into_bitboard() | Rank::Eighth.into_bitboard())) .is_empty() { - return Err(ValidationError::InvalidPawnPosition); + return Err(InvalidError::InvalidPawnPosition); } // Verify that rooks and kings that are allowed to castle have not been moved. @@ -296,14 +296,14 @@ impl ChessBoard { let expected_rooks = castle_rights.unmoved_rooks(color); // We must check the intersection, in case there are more than 2 rooks on the board. if (expected_rooks & actual_rooks) != expected_rooks { - return Err(ValidationError::InvalidCastlingRights); + return Err(InvalidError::InvalidCastlingRights); } let actual_king = self.occupancy(Piece::King, color); let expected_king = Square::new(File::E, color.first_rank()); // We have checked that there is exactly one king, no need for intersecting the sets. if actual_king != expected_king.into_bitboard() { - return Err(ValidationError::InvalidCastlingRights); + return Err(InvalidError::InvalidCastlingRights); } } @@ -311,14 +311,14 @@ impl ChessBoard { if let Some(square) = self.en_passant() { // Must be empty if !(self.combined_occupancy() & square).is_empty() { - return Err(ValidationError::InvalidEnPassant); + return Err(InvalidError::InvalidEnPassant); } let opponent = !self.current_player(); // Must be on the opponent's third rank if (square & opponent.third_rank().into_bitboard()).is_empty() { - return Err(ValidationError::InvalidEnPassant); + return Err(InvalidError::InvalidEnPassant); } // Must be behind a pawn @@ -328,7 +328,7 @@ impl ChessBoard { .backward_direction() .move_board(square.into_bitboard()); if (opponent_pawns & double_pushed_pawn).is_empty() { - return Err(ValidationError::InvalidEnPassant); + return Err(InvalidError::InvalidEnPassant); } } @@ -337,12 +337,12 @@ impl ChessBoard { let black_king = self.occupancy(Piece::King, Color::Black); // Unwrap is fine, we already checked that there is exactly one king of each color if !(movegen::king_moves(white_king.try_into().unwrap()) & black_king).is_empty() { - return Err(ValidationError::NeighbouringKings); + return Err(InvalidError::NeighbouringKings); } // Check that the opponent is not currently in check. if !self.compute_checkers(!self.current_player()).is_empty() { - return Err(ValidationError::OpponentInCheck); + return Err(InvalidError::OpponentInCheck); } Ok(()) @@ -411,7 +411,7 @@ impl Default for ChessBoard { | Rank::Second.into_bitboard() | Rank::Seventh.into_bitboard() | Rank::Eighth.into_bitboard(), - castle_rights: [CastleRights::BothSides; Color::NUM_VARIANTS], + castle_rights: [CastleRights::BothSides; 2], en_passant: None, half_move_clock: 0, total_plies: 0, @@ -445,7 +445,7 @@ mod test { }; assert_eq!( position.validate().err().unwrap(), - ValidationError::IncoherentPlieCount, + InvalidError::IncoherentPlieCount, ); } @@ -458,70 +458,130 @@ mod test { builder.with_half_move_clock(10); TryInto::::try_into(builder) }; - assert_eq!(res.err().unwrap(), ValidationError::HalfMoveClockTooHigh); + assert_eq!(res.err().unwrap(), InvalidError::HalfMoveClockTooHigh); } #[test] fn invalid_overlapping_pieces() { - let position = { - let mut builder = ChessBoardBuilder::new(); - builder[Square::E1] = Some((Piece::King, Color::White)); - builder[Square::E8] = Some((Piece::King, Color::Black)); - let mut board: ChessBoard = builder.try_into().unwrap(); - *board.piece_occupancy_mut(Piece::Queen) |= Square::E1.into_bitboard(); - board + let position = ChessBoard { + piece_occupancy: [ + // King + Square::E1 | Square::E8, + // Queen + Square::E1 | Square::E8, + // Rook + Bitboard::EMPTY, + // Bishop + Bitboard::EMPTY, + // Knight + Bitboard::EMPTY, + // Pawn + Bitboard::EMPTY, + ], + color_occupancy: [Square::E1.into_bitboard(), Square::E8.into_bitboard()], + combined_occupancy: Square::E1 | Square::E8, + castle_rights: [CastleRights::NoSide; 2], + en_passant: None, + half_move_clock: 0, + total_plies: 0, + side: Color::White, }; assert_eq!( position.validate().err().unwrap(), - ValidationError::OverlappingPieces, + InvalidError::OverlappingPieces, ); } #[test] fn invalid_overlapping_colors() { - let position = { - let mut builder = ChessBoardBuilder::new(); - builder[Square::E1] = Some((Piece::King, Color::White)); - builder[Square::E8] = Some((Piece::King, Color::Black)); - let mut board: ChessBoard = builder.try_into().unwrap(); - *board.color_occupancy_mut(Color::White) |= Square::E8.into_bitboard(); - board + let position = ChessBoard { + piece_occupancy: [ + // King + Square::E1 | Square::E8, + // Queen + Bitboard::EMPTY, + // Rook + Bitboard::EMPTY, + // Bishop + Bitboard::EMPTY, + // Knight + Bitboard::EMPTY, + // Pawn + Bitboard::EMPTY, + ], + color_occupancy: [Square::E1 | Square::E8, Square::E1 | Square::E8], + combined_occupancy: Square::E1 | Square::E8, + castle_rights: [CastleRights::NoSide; 2], + en_passant: None, + half_move_clock: 0, + total_plies: 0, + side: Color::White, }; assert_eq!( position.validate().err().unwrap(), - ValidationError::OverlappingColors, + InvalidError::OverlappingColors, ); } #[test] fn invalid_combined_does_not_equal_pieces() { - let position = { - let mut builder = ChessBoardBuilder::new(); - builder[Square::E1] = Some((Piece::King, Color::White)); - builder[Square::E8] = Some((Piece::King, Color::Black)); - let mut board: ChessBoard = builder.try_into().unwrap(); - *board.piece_occupancy_mut(Piece::Pawn) |= Square::E2.into_bitboard(); - board + let position = ChessBoard { + piece_occupancy: [ + // King + Square::E1 | Square::E8, + // Queen + Bitboard::EMPTY, + // Rook + Bitboard::EMPTY, + // Bishop + Bitboard::EMPTY, + // Knight + Bitboard::EMPTY, + // Pawn + Bitboard::EMPTY, + ], + color_occupancy: [Square::E1.into_bitboard(), Square::E8.into_bitboard()], + combined_occupancy: Square::E1.into_bitboard(), + castle_rights: [CastleRights::NoSide; 2], + en_passant: None, + half_move_clock: 0, + total_plies: 0, + side: Color::White, }; assert_eq!( position.validate().err().unwrap(), - ValidationError::ErroneousCombinedOccupancy, + InvalidError::ErroneousCombinedOccupancy, ); } #[test] fn invalid_combined_does_not_equal_colors() { - let position = { - let mut builder = ChessBoardBuilder::new(); - builder[Square::E1] = Some((Piece::King, Color::White)); - builder[Square::E8] = Some((Piece::King, Color::Black)); - let mut board: ChessBoard = builder.try_into().unwrap(); - *board.color_occupancy_mut(Color::Black) |= Square::E2.into_bitboard(); - board + let position = ChessBoard { + piece_occupancy: [ + // King + Square::E1 | Square::E8, + // Queen + Bitboard::EMPTY, + // Rook + Bitboard::EMPTY, + // Bishop + Bitboard::EMPTY, + // Knight + Bitboard::EMPTY, + // Pawn + Bitboard::EMPTY, + ], + color_occupancy: [Square::E1 | Square::H1, Square::E8 | Square::H8], + combined_occupancy: Square::E1 | Square::E8, + castle_rights: [CastleRights::NoSide; 2], + en_passant: None, + half_move_clock: 0, + total_plies: 0, + side: Color::White, }; assert_eq!( position.validate().err().unwrap(), - ValidationError::ErroneousCombinedOccupancy, + InvalidError::ErroneousCombinedOccupancy, ); } @@ -535,7 +595,7 @@ mod test { builder[Square::E8] = Some((Piece::King, Color::Black)); TryInto::::try_into(builder) }; - assert_eq!(res.err().unwrap(), ValidationError::TooManyPieces); + assert_eq!(res.err().unwrap(), InvalidError::TooManyPieces); } #[test] @@ -547,7 +607,7 @@ mod test { builder.with_castle_rights(CastleRights::BothSides, Color::White); TryInto::::try_into(builder) }; - assert_eq!(res.err().unwrap(), ValidationError::InvalidCastlingRights); + assert_eq!(res.err().unwrap(), InvalidError::InvalidCastlingRights); } #[test] @@ -563,7 +623,7 @@ mod test { builder.with_castle_rights(CastleRights::BothSides, Color::White); TryInto::::try_into(builder) }; - assert_eq!(res.err().unwrap(), ValidationError::InvalidCastlingRights); + assert_eq!(res.err().unwrap(), InvalidError::InvalidCastlingRights); } #[test] @@ -587,7 +647,7 @@ mod test { builder.with_en_passant(Square::A6); TryInto::::try_into(builder) }; - assert_eq!(res.err().unwrap(), ValidationError::InvalidEnPassant); + assert_eq!(res.err().unwrap(), InvalidError::InvalidEnPassant); } #[test] @@ -600,7 +660,7 @@ mod test { builder.with_en_passant(Square::A6); TryInto::::try_into(builder) }; - assert_eq!(res.err().unwrap(), ValidationError::InvalidEnPassant); + assert_eq!(res.err().unwrap(), InvalidError::InvalidEnPassant); } #[test] @@ -613,7 +673,7 @@ mod test { builder.with_en_passant(Square::A5); TryInto::::try_into(builder) }; - assert_eq!(res.err().unwrap(), ValidationError::InvalidEnPassant); + assert_eq!(res.err().unwrap(), InvalidError::InvalidEnPassant); } #[test] @@ -624,7 +684,7 @@ mod test { builder[Square::E2] = Some((Piece::King, Color::Black)); TryInto::::try_into(builder) }; - assert_eq!(res.err().unwrap(), ValidationError::NeighbouringKings); + assert_eq!(res.err().unwrap(), InvalidError::NeighbouringKings); } #[test] @@ -636,7 +696,7 @@ mod test { builder[Square::E8] = Some((Piece::King, Color::Black)); TryInto::::try_into(builder) }; - assert_eq!(res.err().unwrap(), ValidationError::OpponentInCheck); + assert_eq!(res.err().unwrap(), InvalidError::OpponentInCheck); } #[test] @@ -648,7 +708,7 @@ mod test { builder[Square::H8] = Some((Piece::King, Color::Black)); TryInto::::try_into(builder) }; - assert_eq!(res.err().unwrap(), ValidationError::InvalidPawnPosition); + assert_eq!(res.err().unwrap(), InvalidError::InvalidPawnPosition); } #[test] @@ -665,7 +725,7 @@ mod test { } TryInto::::try_into(builder) }; - assert_eq!(res.err().unwrap(), ValidationError::TooManyPieces); + assert_eq!(res.err().unwrap(), InvalidError::TooManyPieces); } #[test] @@ -699,7 +759,7 @@ mod test { | Square::F3 | Square::G1 | Square::H2, - castle_rights: [CastleRights::NoSide; Color::NUM_VARIANTS], + castle_rights: [CastleRights::NoSide; 2], en_passant: None, half_move_clock: 0, total_plies: 0, diff --git a/src/board/color.rs b/src/board/color.rs index e41d3c5..66b21b3 100644 --- a/src/board/color.rs +++ b/src/board/color.rs @@ -19,24 +19,11 @@ impl Color { } /// Convert from a color index into a [Color] type. - /// - /// # Panics - /// - /// Panics if the index is out of bounds. #[inline(always)] pub fn from_index(index: usize) -> Self { - Self::try_from_index(index).expect("index out of bouds") - } - - /// Convert from a color index into a [Color] type. Returns [None] if the index is out of - /// bounds. - pub fn try_from_index(index: usize) -> Option { - if index < Self::NUM_VARIANTS { - // SAFETY: we know the value is in-bounds - Some(unsafe { Self::from_index_unchecked(index) }) - } else { - None - } + assert!(index < Self::NUM_VARIANTS); + // SAFETY: we know the value is in-bounds + unsafe { Self::from_index_unchecked(index) } } /// Convert from a color index into a [Color] type, no bounds checking. diff --git a/src/board/file.rs b/src/board/file.rs index 1641498..1475e9a 100644 --- a/src/board/file.rs +++ b/src/board/file.rs @@ -35,23 +35,11 @@ impl File { } /// Convert from a file index into a [File] type. - /// - /// # Panics - /// - /// Panics if the index is out of bounds. #[inline(always)] pub fn from_index(index: usize) -> Self { - Self::try_from_index(index).expect("index out of bouds") - } - - /// Convert from a file index into a [File] type. Returns [None] if the index is out of bounds. - pub fn try_from_index(index: usize) -> Option { - if index < Self::NUM_VARIANTS { - // SAFETY: we know the value is in-bounds - Some(unsafe { Self::from_index_unchecked(index) }) - } else { - None - } + assert!(index < Self::NUM_VARIANTS); + // SAFETY: we know the value is in-bounds + unsafe { Self::from_index_unchecked(index) } } /// Convert from a file index into a [File] type, no bounds checking. diff --git a/src/board/piece.rs b/src/board/piece.rs index f6fdce4..58f989a 100644 --- a/src/board/piece.rs +++ b/src/board/piece.rs @@ -28,24 +28,11 @@ impl Piece { } /// Convert from a piece index into a [Piece] type. - /// - /// # Panics - /// - /// Panics if the index is out of bounds. #[inline(always)] pub fn from_index(index: usize) -> Self { - Self::try_from_index(index).expect("index out of bouds") - } - - /// Convert from a piece index into a [Piece] type. Returns [None] if the index is out of - /// bounds. - pub fn try_from_index(index: usize) -> Option { - if index < Self::NUM_VARIANTS { - // SAFETY: we know the value is in-bounds - Some(unsafe { Self::from_index_unchecked(index) }) - } else { - None - } + assert!(index < Self::NUM_VARIANTS); + // SAFETY: we know the value is in-bounds + unsafe { Self::from_index_unchecked(index) } } /// Convert from a piece index into a [Piece] type, no bounds checking. diff --git a/src/board/rank.rs b/src/board/rank.rs index 1632229..f448df5 100644 --- a/src/board/rank.rs +++ b/src/board/rank.rs @@ -35,23 +35,11 @@ impl Rank { } /// Convert from a rank index into a [Rank] type. - /// - /// # Panics - /// - /// Panics if the index is out of bounds. #[inline(always)] pub fn from_index(index: usize) -> Self { - Self::try_from_index(index).expect("index out of bouds") - } - - /// Convert from a rank index into a [Rank] type. Returns [None] if the index is out of bounds. - pub fn try_from_index(index: usize) -> Option { - if index < Self::NUM_VARIANTS { - // SAFETY: we know the value is in-bounds - Some(unsafe { Self::from_index_unchecked(index) }) - } else { - None - } + assert!(index < Self::NUM_VARIANTS); + // SAFETY: we know the value is in-bounds + unsafe { Self::from_index_unchecked(index) } } /// Convert from a rank index into a [Rank] type, no bounds checking. diff --git a/src/board/square.rs b/src/board/square.rs index b5de25b..958c3c9 100644 --- a/src/board/square.rs +++ b/src/board/square.rs @@ -39,10 +39,6 @@ impl Square { ]; /// Construct a [Square] from a [File] and [Rank]. - /// - /// # Panics - /// - /// Panics if the index is out of bounds. #[inline(always)] pub fn new(file: File, rank: Rank) -> Self { // SAFETY: we know the value is in-bounds @@ -57,18 +53,9 @@ impl Square { /// Convert from a square index into a [Square] type. #[inline(always)] pub fn from_index(index: usize) -> Self { - Self::try_from_index(index).expect("index out of bouds") - } - - /// Convert from a square index into a [Square] type. Returns [None] if the index is out of - /// bounds. - pub fn try_from_index(index: usize) -> Option { - if index < Self::NUM_VARIANTS { - // SAFETY: we know the value is in-bounds - Some(unsafe { Self::from_index_unchecked(index) }) - } else { - None - } + assert!(index < Self::NUM_VARIANTS); + // SAFETY: we know the value is in-bounds + unsafe { Self::from_index_unchecked(index) } } /// Convert from a square index into a [Square] type, no bounds checking. diff --git a/src/fen.rs b/src/fen.rs index 03c60c1..90f6dd1 100644 --- a/src/fen.rs +++ b/src/fen.rs @@ -1,5 +1,5 @@ use crate::board::{ - CastleRights, ChessBoard, ChessBoardBuilder, Color, File, Piece, Rank, Square, ValidationError, + CastleRights, ChessBoard, ChessBoardBuilder, Color, File, InvalidError, Piece, Rank, Square, }; /// A trait to mark items that can be converted from a FEN input. @@ -15,7 +15,7 @@ pub enum FenError { /// Invalid FEN input. InvalidFen, /// Invalid chess position. - InvalidPosition(ValidationError), + InvalidPosition(InvalidError), } impl std::fmt::Display for FenError { @@ -29,15 +29,15 @@ impl std::fmt::Display for FenError { impl std::error::Error for FenError {} -/// Allow converting a [ValidationError] into [FenError], for use with the '?' operator. -impl From for FenError { - fn from(err: ValidationError) -> Self { +/// Allow converting a [InvalidError] into [FenError], for use with the '?' operator. +impl From for FenError { + fn from(err: InvalidError) -> Self { Self::InvalidPosition(err) } } /// Convert the castling rights segment of a FEN string to an array of [CastleRights]. -impl FromFen for [CastleRights; Color::NUM_VARIANTS] { +impl FromFen for [CastleRights; 2] { type Err = FenError; fn from_fen(s: &str) -> Result { @@ -45,7 +45,7 @@ impl FromFen for [CastleRights; Color::NUM_VARIANTS] { return Err(FenError::InvalidFen); } - let mut res = [CastleRights::NoSide; Color::NUM_VARIANTS]; + let mut res = [CastleRights::NoSide; 2]; if s == "-" { return Ok(res); @@ -134,7 +134,7 @@ impl FromFen for ChessBoard { let mut builder = ChessBoardBuilder::new(); - let castle_rights = <[CastleRights; Color::NUM_VARIANTS]>::from_fen(castling_rights)?; + let castle_rights = <[CastleRights; 2]>::from_fen(castling_rights)?; for color in Color::iter() { builder.with_castle_rights(castle_rights[color.index()], color); } diff --git a/src/movegen/moves.rs b/src/movegen/moves.rs index d46a733..9840083 100644 --- a/src/movegen/moves.rs +++ b/src/movegen/moves.rs @@ -13,12 +13,12 @@ use crate::{ // A pre-rolled RNG for magic bitboard generation, using pre-determined values. struct PreRolledRng { - numbers: [u64; Square::NUM_VARIANTS], + numbers: [u64; 64], current_index: usize, } impl PreRolledRng { - pub fn new(numbers: [u64; Square::NUM_VARIANTS]) -> Self { + pub fn new(numbers: [u64; 64]) -> Self { Self { numbers, current_index: 0, @@ -39,8 +39,7 @@ impl RandGen for PreRolledRng { /// Compute the set of possible non-attack moves for a pawn on a [Square], given its [Color] and /// set of blockers. pub fn pawn_quiet_moves(color: Color, square: Square, blockers: Bitboard) -> Bitboard { - static PAWN_MOVES: OnceLock<[[Bitboard; Square::NUM_VARIANTS]; Color::NUM_VARIANTS]> = - OnceLock::new(); + static PAWN_MOVES: OnceLock<[[Bitboard; 64]; 2]> = OnceLock::new(); // If there is a piece in front of the pawn, it can't advance if !(color.backward_direction().move_board(blockers) & square).is_empty() { @@ -48,7 +47,7 @@ pub fn pawn_quiet_moves(color: Color, square: Square, blockers: Bitboard) -> Bit } PAWN_MOVES.get_or_init(|| { - let mut res = [[Bitboard::EMPTY; Square::NUM_VARIANTS]; Color::NUM_VARIANTS]; + let mut res = [[Bitboard::EMPTY; 64]; 2]; for color in Color::iter() { for square in Square::iter() { res[color.index()][square.index()] = @@ -61,11 +60,10 @@ pub fn pawn_quiet_moves(color: Color, square: Square, blockers: Bitboard) -> Bit /// Compute the set of possible attacks for a pawn on a [Square], given its [Color]. pub fn pawn_attacks(color: Color, square: Square) -> Bitboard { - static PAWN_ATTACKS: OnceLock<[[Bitboard; Square::NUM_VARIANTS]; Color::NUM_VARIANTS]> = - OnceLock::new(); + static PAWN_ATTACKS: OnceLock<[[Bitboard; 64]; 2]> = OnceLock::new(); PAWN_ATTACKS.get_or_init(|| { - let mut res = [[Bitboard::EMPTY; Square::NUM_VARIANTS]; Color::NUM_VARIANTS]; + let mut res = [[Bitboard::EMPTY; 64]; 2]; for color in Color::iter() { for square in Square::iter() { res[color.index()][square.index()] = naive::pawn_captures(color, square); @@ -83,9 +81,9 @@ pub fn pawn_moves(color: Color, square: Square, blockers: Bitboard) -> Bitboard /// Compute the set of possible moves for a knight on a [Square]. pub fn knight_moves(square: Square) -> Bitboard { - static KNIGHT_MOVES: OnceLock<[Bitboard; Square::NUM_VARIANTS]> = OnceLock::new(); + static KNIGHT_MOVES: OnceLock<[Bitboard; 64]> = OnceLock::new(); KNIGHT_MOVES.get_or_init(|| { - let mut res = [Bitboard::EMPTY; Square::NUM_VARIANTS]; + let mut res = [Bitboard::EMPTY; 64]; for square in Square::iter() { res[square.index()] = naive::knight_moves(square) } @@ -124,9 +122,9 @@ pub fn queen_moves(square: Square, blockers: Bitboard) -> Bitboard { /// Compute the set of possible moves for a king on a [Square]. pub fn king_moves(square: Square) -> Bitboard { - static KING_MOVES: OnceLock<[Bitboard; Square::NUM_VARIANTS]> = OnceLock::new(); + static KING_MOVES: OnceLock<[Bitboard; 64]> = OnceLock::new(); KING_MOVES.get_or_init(|| { - let mut res = [Bitboard::EMPTY; Square::NUM_VARIANTS]; + let mut res = [Bitboard::EMPTY; 64]; for square in Square::iter() { res[square.index()] = naive::king_moves(square) } diff --git a/src/movegen/wizardry/mod.rs b/src/movegen/wizardry/mod.rs index 6918d09..00645d8 100644 --- a/src/movegen/wizardry/mod.rs +++ b/src/movegen/wizardry/mod.rs @@ -59,7 +59,7 @@ impl MagicMoves { // region:sourcegen /// A set of magic numbers for bishop move generation. -pub(crate) const BISHOP_SEED: [u64; Square::NUM_VARIANTS] = [ +pub(crate) const BISHOP_SEED: [u64; 64] = [ 4908958787341189172, 1157496606860279808, 289395876198088778, @@ -127,7 +127,7 @@ pub(crate) const BISHOP_SEED: [u64; Square::NUM_VARIANTS] = [ ]; /// A set of magic numbers for rook move generation. -pub(crate) const ROOK_SEED: [u64; Square::NUM_VARIANTS] = [ +pub(crate) const ROOK_SEED: [u64; 64] = [ 2341871943948451840, 18015635528220736, 72066665545773824, @@ -197,8 +197,6 @@ pub(crate) const ROOK_SEED: [u64; Square::NUM_VARIANTS] = [ #[cfg(test)] mod test { - use std::fmt::Write as _; - use super::*; // A simple XOR-shift RNG implementation. @@ -240,25 +238,20 @@ mod test { Some((prefix, mid, suffix)) } - fn array_string(piece_type: &str, values: &[Magic]) -> Result { - let mut res = String::new(); - - writeln!( - &mut res, - "/// A set of magic numbers for {} move generation.", + fn array_string(piece_type: &str, values: &[Magic]) -> String { + let mut res = format!( + "/// A set of magic numbers for {} move generation.\n", piece_type - )?; - writeln!( - &mut res, - "pub(crate) const {}_SEED: [u64; Square::NUM_VARIANTS] = [", + ); + res.push_str(&format!( + "pub(crate) const {}_SEED: [u64; 64] = [\n", piece_type.to_uppercase() - )?; + )); for magic in values { - writeln!(&mut res, " {},", magic.magic)?; + res.push_str(&format!(" {},\n", magic.magic)); } - writeln!(&mut res, "];")?; - - Ok(res) + res.push_str("];\n"); + res } #[test] @@ -271,8 +264,8 @@ mod test { let original_text = std::fs::read_to_string(file!()).unwrap(); - let bishop_array = array_string("bishop", &bishop_magics[..]).unwrap(); - let rook_array = array_string("rook", &rook_magics[..]).unwrap(); + let bishop_array = array_string("bishop", &bishop_magics[..]); + let rook_array = array_string("rook", &rook_magics[..]); let new_text = { let start_marker = "// region:sourcegen\n";