1
0
Fork 0

update interface for text records

This commit is contained in:
Paul-Nicolas Madelaine 2025-10-23 23:34:31 +02:00
parent 0d8b9cc9cf
commit 149aa841c9
5 changed files with 198 additions and 179 deletions

View file

@ -27,7 +27,7 @@
//! use eschac::prelude::*;
//!
//! // read a position from a text record
//! let setup = "7k/4P1rp/5Q2/5p2/1Pp1bP2/8/r4K1P/6R1 w - -".parse::<Setup>()?;
//! let setup = Setup::from_text_record("7k/4P1rp/5Q2/5p2/1Pp1bP2/8/r4K1P/6R1 w - -")?;
//! let position = setup.into_position()?;
//!
//! // read a move in algebraic notation

View file

@ -82,16 +82,28 @@ impl Position {
/// ```
/// # use eschac::setup::Setup;
/// # |s: &str| -> Option<eschac::position::Position> {
/// s.parse::<Setup>().ok().and_then(|pos| pos.into_position().ok())
/// Setup::from_text_record(s).ok().and_then(|pos| pos.into_position().ok())
/// # };
/// ```
#[inline]
pub fn from_text_record(s: &str) -> Option<Self> {
s.parse::<Setup>()
Setup::from_text_record(s)
.ok()
.and_then(|pos| pos.into_position().ok())
}
/// Returns the text record of the position.
///
/// This is a shortcut for:
/// ```
/// # |position: eschac::position::Position| {
/// position.as_setup().to_text_record()
/// # };
#[inline]
pub fn to_text_record(&self) -> String {
self.as_setup().to_text_record()
}
/// Returns all the legal moves on the position.
#[inline]
pub fn legal_moves<'l>(&'l self) -> Moves<'l> {
@ -469,7 +481,7 @@ impl Position {
impl std::fmt::Debug for Position {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
f.debug_tuple("Position")
.field(&self.as_setup().to_string())
.field(&TextRecord(self.as_setup()))
.finish()
}
}

View file

@ -13,13 +13,14 @@ use crate::position::*;
/// It must be validated and converted to a [`Position`] using the [`Setup::into_position`] method
/// before generating moves.
///
/// This type implements [`FromStr`](std::str::FromStr) and [`Display`](std::fmt::Display) to parse
/// and print positions from text records.
/// ## Text description
///
/// Forsyth-Edwards Notation (FEN) is typically used to describe chess positions as text. eschac
/// uses a slightly different notation, which simply removes the last two fields of the FEN string
/// uses a slightly different notation, which simply removes the last two fields of the FEN record
/// (i.e. the halfmove clock and the fullmove number) as the [`Position`] type does not keep
/// track of those.
/// track of those. For example, the starting position is recorded as
/// `rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq -`. [`Setup::from_text_record`] and
/// [`Setup::to_text_record`] can be used to read and write these records.
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct Setup {
pub(crate) w: Bitboard,
@ -48,9 +49,23 @@ impl Setup {
}
}
/// Reads a position from a text record.
///
/// This is a shortcut for:
/// ```
/// # use eschac::setup::Setup;
/// # |record: &str| {
/// Setup::from_ascii_record(record.as_bytes())
/// # };
/// ```
#[inline]
pub fn from_text_record(record: &str) -> Result<Self, ParseRecordError> {
Self::from_ascii_record(record.as_bytes())
}
/// Reads a position from an ascii record.
pub fn from_ascii(s: &[u8]) -> Result<Self, ParseSetupError> {
let mut s = s.iter().copied().peekable();
pub fn from_ascii_record(record: &[u8]) -> Result<Self, ParseRecordError> {
let mut s = record.iter().copied().peekable();
let mut setup = Setup::new();
(|| {
let mut accept_empty_square = true;
@ -85,19 +100,14 @@ impl Setup {
}
(rank == 0).then_some(())?;
(file == 8).then_some(())?;
Some(())
})()
.ok_or(ParseSetupError::InvalidBoard)?;
(|| {
match s.next()? {
b'w' => setup.set_turn(Color::White),
b'b' => setup.set_turn(Color::Black),
_ => return None,
}
(s.next()? == b' ').then_some(())
})()
.ok_or(ParseSetupError::InvalidTurn)?;
(|| {
(s.next()? == b' ').then_some(())?;
if s.next_if_eq(&b'-').is_none() {
if s.next_if_eq(&b'K').is_some() {
setup.set_castling_rights(Color::White, CastlingSide::Short, true);
@ -112,10 +122,8 @@ impl Setup {
setup.set_castling_rights(Color::Black, CastlingSide::Long, true);
}
}
(s.next()? == b' ').then_some(())
})()
.ok_or(ParseSetupError::InvalidCastlingRights)?;
(|| {
(s.next()? == b' ').then_some(())?;
match s.next()? {
b'-' => (),
file => setup.set_en_passant_target_square(Some(Square::new(
@ -123,10 +131,95 @@ impl Setup {
Rank::from_ascii(s.next()?)?,
))),
}
s.next().is_none().then_some(())
s.next().is_none().then_some(())?;
Some(setup)
})()
.ok_or(ParseSetupError::InvalidEnPassantTargetSquare)?;
Ok(setup)
.ok_or_else(|| ParseRecordError {
byte: record.len() - s.len(),
})
}
/// Returns the text record of the position.
pub fn to_text_record(&self) -> String {
let mut record = String::with_capacity(81);
self.write_text_record(&mut record).unwrap();
record
}
/// Writes the text record of the position.
pub fn write_text_record<W>(&self, w: &mut W) -> std::fmt::Result
where
W: std::fmt::Write,
{
for rank in Rank::all().into_iter().rev() {
let mut count = 0;
for file in File::all() {
match self.get(Square::new(file, rank)) {
Some(piece) => {
if count > 0 {
w.write_char(char::from_u32('0' as u32 + count).unwrap())?;
}
count = 0;
w.write_char(match piece.color {
Color::White => piece.role.to_char_uppercase(),
Color::Black => piece.role.to_char_lowercase(),
})?;
}
None => {
count += 1;
}
}
}
if count > 0 {
w.write_char(char::from_u32('0' as u32 + count).unwrap())?;
}
if rank != Rank::First {
w.write_char('/')?;
}
}
w.write_char(' ')?;
w.write_char(match self.turn {
Color::White => 'w',
Color::Black => 'b',
})?;
w.write_char(' ')?;
let mut no_castle_available = true;
if self.castling_rights(Color::White, CastlingSide::Short) {
w.write_char('K')?;
no_castle_available = false;
}
if self.castling_rights(Color::White, CastlingSide::Long) {
w.write_char('Q')?;
no_castle_available = false;
}
if self.castling_rights(Color::Black, CastlingSide::Short) {
w.write_char('k')?;
no_castle_available = false;
}
if self.castling_rights(Color::Black, CastlingSide::Long) {
w.write_char('q')?;
no_castle_available = false;
}
if no_castle_available {
w.write_char('-')?;
}
w.write_char(' ')?;
match self.en_passant.try_into_square() {
Some(sq) => {
w.write_str(sq.to_str())?;
}
None => {
w.write_char('-')?;
}
}
Ok(())
}
/// Returns the occupancy of a square.
@ -424,119 +517,28 @@ impl TryFrom<Setup> for Position {
}
}
impl std::fmt::Debug for Setup {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
f.debug_tuple("Setup").field(&self.to_string()).finish()
pub(crate) struct TextRecord<'a>(pub(crate) &'a Setup);
impl<'a> std::fmt::Display for TextRecord<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.write_text_record(f)
}
}
impl std::fmt::Display for Setup {
impl<'a> std::fmt::Debug for TextRecord<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
use std::fmt::Write;
for rank in Rank::all().into_iter().rev() {
let mut count = 0;
for file in File::all() {
match self.get(Square::new(file, rank)) {
Some(piece) => {
if count > 0 {
f.write_char(char::from_u32('0' as u32 + count).unwrap())?;
}
count = 0;
f.write_char(match piece.color {
Color::White => piece.role.to_char_uppercase(),
Color::Black => piece.role.to_char_lowercase(),
})?;
}
None => {
count += 1;
}
}
}
if count > 0 {
f.write_char(char::from_u32('0' as u32 + count).unwrap())?;
}
if rank != Rank::First {
f.write_char('/')?;
}
}
f.write_char(' ')?;
f.write_char(match self.turn {
Color::White => 'w',
Color::Black => 'b',
})?;
f.write_char(' ')?;
let mut no_castle_available = true;
if self.castling_rights(Color::White, CastlingSide::Short) {
f.write_char('K')?;
no_castle_available = false;
}
if self.castling_rights(Color::White, CastlingSide::Long) {
f.write_char('Q')?;
no_castle_available = false;
}
if self.castling_rights(Color::Black, CastlingSide::Short) {
f.write_char('k')?;
no_castle_available = false;
}
if self.castling_rights(Color::Black, CastlingSide::Long) {
f.write_char('q')?;
no_castle_available = false;
}
if no_castle_available {
f.write_char('-')?;
}
f.write_char(' ')?;
match self.en_passant.try_into_square() {
Some(sq) => {
f.write_str(sq.to_str())?;
}
None => {
write!(f, "-")?;
}
}
f.write_char('"')?;
self.0.write_text_record(f)?;
f.write_char('"')?;
Ok(())
}
}
impl std::str::FromStr for Setup {
type Err = ParseSetupError;
#[inline]
fn from_str(s: &str) -> Result<Self, Self::Err> {
Self::from_ascii(s.as_bytes())
impl std::fmt::Debug for Setup {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
f.debug_tuple("Setup").field(&TextRecord(&self)).finish()
}
}
/// An error when trying to parse a position record.
///
/// The variant indicates the field that caused the error.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ParseSetupError {
InvalidBoard,
InvalidTurn,
InvalidCastlingRights,
InvalidEnPassantTargetSquare,
}
impl std::fmt::Display for ParseSetupError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let details = match self {
Self::InvalidBoard => "board",
Self::InvalidTurn => "turn",
Self::InvalidCastlingRights => "castling rights",
Self::InvalidEnPassantTargetSquare => "en passant target square",
};
write!(f, "invalid text record ({details})")
}
}
impl std::error::Error for ParseSetupError {}
/// An invalid position.
///
/// This is an illegal position that can't be represented with the [`Position`] type.
@ -549,7 +551,7 @@ impl std::fmt::Display for IllegalPosition {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
use std::fmt::Write;
let setup = &self.setup;
write!(f, "`{setup}` is illegal:")?;
write!(f, "`{}` is illegal:", &TextRecord(setup))?;
let mut first = true;
for reason in self.reasons {
if !first {
@ -654,3 +656,17 @@ impl std::fmt::Display for IllegalPositionReason {
f.write_str(self.to_str())
}
}
/// An error when trying to parse a position record.
///
/// The variant indicates the field that caused the error.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ParseRecordError {
pub byte: usize,
}
impl std::fmt::Display for ParseRecordError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "invalid text record (at byte {})", self.byte)
}
}
impl std::error::Error for ParseRecordError {}