From 76577718d8701b21bd67118532f61c87a2367d89 Mon Sep 17 00:00:00 2001 From: Bruno BELANYI Date: Wed, 27 Jul 2022 23:41:08 +0200 Subject: [PATCH] Add FEN castling rights parsing --- src/board/castle_rights.rs | 36 +++++++++++++++++++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) 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::*;