diff --git a/src/board/castle_rights.rs b/src/board/castle_rights.rs index b8d8f2b..a48bf4d 100644 --- a/src/board/castle_rights.rs +++ b/src/board/castle_rights.rs @@ -1,4 +1,5 @@ -use super::{Bitboard, Color, File, Square}; +use super::{Bitboard, Color, File, FromFen, Square}; +use crate::error::Error; /// Current castle rights for a player. #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] @@ -108,6 +109,39 @@ impl CastleRights { } } +/// Convert the castling rights segment of a FEN string to an array of [CastleRights]. +impl FromFen for [CastleRights; 2] { + type Err = Error; + + fn from_fen(s: &str) -> Result { + if s.len() > 4 { + return Err(Error::InvalidFen); + } + + let mut res = [CastleRights::NoSide; 2]; + + if s == "-" { + return Ok(res); + } + + for b in s.chars() { + let color = if b.is_uppercase() { + Color::White + } else { + Color::Black + }; + let rights = &mut res[color.index()]; + match b { + 'k' | 'K' => *rights = rights.with_king_side(), + 'q' | 'Q' => *rights = rights.with_queen_side(), + _ => return Err(Error::InvalidFen), + } + } + + Ok(res) + } +} + #[cfg(test)] mod test { use super::*;