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)]
|
2024-07-13 08:08:12 -07:00
|
|
|
pub(crate) struct Mailbox([Option<Piece>; Square::NUM]);
|
2024-07-12 15:52:41 -07:00
|
|
|
|
|
|
|
impl Mailbox {
|
2024-07-13 08:08:12 -07:00
|
|
|
pub(crate) fn new() -> Self {
|
2024-07-12 15:52:41 -07:00
|
|
|
Self::default()
|
|
|
|
}
|
|
|
|
|
2024-07-13 08:08:12 -07:00
|
|
|
pub(crate) fn get(&self, square: Square) -> Option<Piece> {
|
2024-07-12 15:52:41 -07:00
|
|
|
self.0[square as usize]
|
|
|
|
}
|
|
|
|
|
2024-07-13 08:08:12 -07:00
|
|
|
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);
|
|
|
|
}
|
|
|
|
|
2024-07-13 08:08:12 -07:00
|
|
|
pub(crate) fn remove(&mut self, square: Square) {
|
2024-07-12 15:52:41 -07:00
|
|
|
self.0[square as usize] = None;
|
|
|
|
}
|
2024-07-13 08:08:12 -07:00
|
|
|
|
|
|
|
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 {
|
2024-07-13 08:08:12 -07:00
|
|
|
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 {
|
2024-07-13 08:08:12 -07:00
|
|
|
mailbox.set(piece, square);
|
2024-07-12 15:52:41 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
mailbox
|
|
|
|
}
|
|
|
|
}
|