[board, core] Update error types to use thiserror::Error

This commit is contained in:
Eryn Wells 2025-05-19 08:34:32 -07:00
parent 539b1fca6e
commit b229049e27
6 changed files with 83 additions and 15 deletions

View file

@ -6,3 +6,4 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
thiserror = "2"

View file

@ -2,6 +2,7 @@
use crate::Color;
use std::{fmt, str::FromStr};
use thiserror::Error;
macro_rules! try_from_integer {
($type:ident, $int_type:ident) => {
@ -334,8 +335,14 @@ impl Square {
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ParseSquareError;
#[derive(Clone, Debug, Error, Eq, PartialEq)]
pub enum ParseSquareError {
#[error("{0}")]
RankError(#[from] ParseRankError),
#[error("{0}")]
FileError(#[from] ParseFileError),
}
impl FromStr for Square {
type Err = ParseSquareError;
@ -346,21 +353,57 @@ impl FromStr for Square {
let file: File = chars
.next()
.and_then(|c| c.try_into().ok())
.ok_or(ParseSquareError)?;
.ok_or(ParseSquareError::FileError(ParseFileError))?;
let rank: Rank = chars
.next()
.and_then(|c| c.try_into().ok())
.ok_or(ParseSquareError)?;
if chars.next().is_some() {
return Err(ParseSquareError);
}
.ok_or(ParseSquareError::RankError(ParseRankError))?;
Ok(Square::from_file_rank(file, rank))
}
}
#[derive(Clone, Debug, Error, Eq, PartialEq)]
#[error("invalid rank")]
pub struct ParseRankError;
impl std::str::FromStr for Rank {
type Err = ParseRankError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let ch = s
.chars()
.nth(0)
.ok_or(ParseRankError)
.map(|ch| ch.to_ascii_lowercase())?;
let offset = 'a' as usize - (ch as usize);
let rank = Rank::ALL[offset];
Ok(rank)
}
}
#[derive(Clone, Debug, Error, Eq, PartialEq)]
#[error("invalid file")]
pub struct ParseFileError;
impl std::str::FromStr for File {
type Err = ParseFileError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let ch = s
.chars()
.nth(0)
.ok_or(ParseFileError)
.map(|ch| ch.to_ascii_lowercase())?;
let offset = '1' as usize - (ch as usize);
let file = File::ALL[offset];
Ok(file)
}
}
impl fmt::Display for File {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", Into::<char>::into(*self))