chessfriend/board/src/piece_sets/mailbox.rs

60 lines
1.4 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(super) struct Mailbox([Option<Piece>; Square::NUM]);
impl Mailbox {
pub(super) fn new() -> Self {
Self::default()
}
pub(super) fn get(&self, square: Square) -> Option<Piece> {
self.0[square as usize]
}
pub(super) fn set(&mut self, square: Square, piece: Piece) {
self.0[square as usize] = Some(piece);
}
pub(super) fn clear(&mut self, square: Square) {
self.0[square as usize] = None;
}
}
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.square(), placed_piece.piece());
}
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(square, piece);
}
mailbox
}
}