chessfriend/board/src/piece_sets/mailbox.rs

70 lines
1.8 KiB
Rust
Raw Normal View History

2024-07-12 15:52:41 -07:00
// Eryn Wells <eryn@erynwells.me>
use chessfriend_core::{Piece, PlacedPiece, Square};
use std::iter::FromIterator;
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub(crate) struct Mailbox([Option<Piece>; Square::NUM]);
2024-07-12 15:52:41 -07:00
impl Mailbox {
pub(crate) fn new() -> Self {
2024-07-12 15:52:41 -07:00
Self::default()
}
pub(crate) fn get(&self, square: Square) -> Option<Piece> {
2024-07-12 15:52:41 -07:00
self.0[square as usize]
}
pub(crate) fn set(&mut self, piece: Piece, square: Square) {
2024-07-12 15:52:41 -07:00
self.0[square as usize] = Some(piece);
}
pub(crate) fn remove(&mut self, square: Square) {
2024-07-12 15:52:41 -07:00
self.0[square as usize] = None;
}
pub(crate) fn iter(&self) -> impl Iterator<Item = PlacedPiece> {
self.0
.into_iter()
.flatten() // Remove the Nones
.zip(0u8..) // Enumerate with u8 instead of usize
.map(|(piece, index)| {
PlacedPiece::new(piece, unsafe { Square::from_index_unchecked(index) })
})
}
2024-07-12 15:52:41 -07:00
}
impl Default for Mailbox {
fn default() -> Self {
Self([None; Square::NUM])
}
}
impl From<[Option<Piece>; Square::NUM]> for Mailbox {
fn from(value: [Option<Piece>; Square::NUM]) -> Self {
Mailbox(value)
}
}
impl FromIterator<PlacedPiece> for Mailbox {
fn from_iter<T: IntoIterator<Item = PlacedPiece>>(iter: T) -> Self {
let mut mailbox = Self::new();
for placed_piece in iter {
mailbox.set(placed_piece.piece(), placed_piece.square());
2024-07-12 15:52:41 -07:00
}
mailbox
}
}
impl FromIterator<(Square, Piece)> for Mailbox {
fn from_iter<T: IntoIterator<Item = (Square, Piece)>>(iter: T) -> Self {
let mut mailbox = Self::new();
for (square, piece) in iter {
mailbox.set(piece, square);
2024-07-12 15:52:41 -07:00
}
mailbox
}
}