[board] Implement TryFrom<&str> for Shape

Convert a string to a Shape using the first character in the string.
Rename TryFromCharError → TryFromError
This commit is contained in:
Eryn Wells 2023-12-28 19:47:40 -07:00
parent 72dabfe73f
commit e1e27fc668

View file

@ -1,8 +1,7 @@
// Eryn Wells <eryn@erynwells.me> // Eryn Wells <eryn@erynwells.me>
use std::fmt;
use crate::Square; use crate::Square;
use std::fmt;
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum Color { pub enum Color {
@ -58,10 +57,11 @@ impl Shape {
} }
} }
pub struct TryFromCharError; #[derive(Debug, Eq, PartialEq)]
pub struct TryFromError;
impl TryFrom<char> for Shape { impl TryFrom<char> for Shape {
type Error = TryFromCharError; type Error = TryFromError;
fn try_from(value: char) -> Result<Self, Self::Error> { fn try_from(value: char) -> Result<Self, Self::Error> {
match value { match value {
@ -71,11 +71,20 @@ impl TryFrom<char> for Shape {
'R' => Ok(Shape::Rook), 'R' => Ok(Shape::Rook),
'Q' => Ok(Shape::Queen), 'Q' => Ok(Shape::Queen),
'K' => Ok(Shape::King), 'K' => Ok(Shape::King),
_ => Err(TryFromCharError), _ => Err(TryFromError),
} }
} }
} }
impl TryFrom<&str> for Shape {
type Error = TryFromError;
fn try_from(value: &str) -> Result<Self, Self::Error> {
let first_char = value.chars().nth(0).ok_or(TryFromError)?;
Shape::try_from(first_char)
}
}
impl Into<char> for &Shape { impl Into<char> for &Shape {
fn into(self) -> char { fn into(self) -> char {
self._ascii_representation() self._ascii_representation()
@ -147,3 +156,19 @@ impl PlacedPiece {
PlacedPiece { piece, square } PlacedPiece { piece, square }
} }
} }
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn shape_try_from() {
assert_eq!(Shape::try_from('p'), Ok(Shape::Pawn));
assert_eq!(Shape::try_from("p"), Ok(Shape::Pawn));
}
#[test]
fn shape_into_char() {
assert_eq!(<Shape as Into<char>>::into(Shape::Pawn) as char, 'p');
}
}