Rename Square::from_index → from_index_unchecked

This commit is contained in:
Eryn Wells 2024-07-13 08:10:21 -07:00
parent c290f00b9e
commit ee51a13870
2 changed files with 14 additions and 8 deletions

View file

@ -223,14 +223,15 @@ impl BitBoard {
/// board.
#[must_use]
pub fn occupied_squares(&self) -> impl Iterator<Item = Square> {
LeadingBitScanner::new(self.0).map(|idx| unsafe { Square::from_index(idx as u8) })
LeadingBitScanner::new(self.0).map(|idx| unsafe { Square::from_index_unchecked(idx as u8) })
}
/// Return an Iterator over the occupied squares. The Iterator yields
/// squares starting from the trailing (least-significant bit) end of the
/// board.
pub fn occupied_squares_trailing(&self) -> impl Iterator<Item = Square> {
TrailingBitScanner::new(self.0).map(|idx| unsafe { Square::from_index(idx as u8) })
TrailingBitScanner::new(self.0)
.map(|idx| unsafe { Square::from_index_unchecked(idx as u8) })
}
/// If the board is not empty, returns the first occupied square on the
@ -240,7 +241,11 @@ impl BitBoard {
pub fn first_occupied_square(&self) -> Option<Square> {
let leading_zeros = self.0.leading_zeros() as u8;
if leading_zeros < Square::NUM as u8 {
unsafe { Some(Square::from_index(Square::NUM as u8 - leading_zeros - 1)) }
unsafe {
Some(Square::from_index_unchecked(
Square::NUM as u8 - leading_zeros - 1,
))
}
} else {
None
}
@ -253,7 +258,7 @@ impl BitBoard {
pub fn first_occupied_square_trailing(&self) -> Option<Square> {
let trailing_zeros = self.0.trailing_zeros() as u8;
if trailing_zeros < Square::NUM as u8 {
unsafe { Some(Square::from_index(trailing_zeros)) }
unsafe { Some(Square::from_index_unchecked(trailing_zeros)) }
} else {
None
}
@ -318,7 +323,7 @@ impl TryFrom<BitBoard> for Square {
return Err(TryFromBitBoardError::NotSingleSquare);
}
unsafe { Ok(Square::from_index(value.0.trailing_zeros() as u8)) }
unsafe { Ok(Square::from_index_unchecked(value.0.trailing_zeros() as u8)) }
}
}

View file

@ -220,9 +220,10 @@ coordinate_enum!(Square, [
impl Square {
/// # Safety
///
/// This function does not do any bounds checking on the input.
/// This function does not do any bounds checking on the input. In debug
/// builds, this function will assert that the argument is in bounds.
#[must_use]
pub unsafe fn from_index(x: u8) -> Square {
pub unsafe fn from_index_unchecked(x: u8) -> Square {
debug_assert!((x as usize) < Self::NUM);
Self::try_from(x).unwrap_unchecked()
}
@ -232,7 +233,7 @@ impl Square {
pub fn from_file_rank(file: File, rank: Rank) -> Square {
let file_int: u8 = file.into();
let rank_int: u8 = rank.into();
unsafe { Self::from_index(rank_int << 3 | file_int) }
unsafe { Self::from_index_unchecked(rank_int << 3 | file_int) }
}
pub fn from_algebraic_str(s: &str) -> Result<Square, ParseSquareError> {