diff --git a/board/src/piece.rs b/board/src/piece.rs index 8a85b11..cff9759 100644 --- a/board/src/piece.rs +++ b/board/src/piece.rs @@ -1,8 +1,7 @@ // Eryn Wells -use std::fmt; - use crate::Square; +use std::fmt; #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub enum Color { @@ -58,10 +57,11 @@ impl Shape { } } -pub struct TryFromCharError; +#[derive(Debug, Eq, PartialEq)] +pub struct TryFromError; impl TryFrom for Shape { - type Error = TryFromCharError; + type Error = TryFromError; fn try_from(value: char) -> Result { match value { @@ -71,11 +71,20 @@ impl TryFrom for Shape { 'R' => Ok(Shape::Rook), 'Q' => Ok(Shape::Queen), 'K' => Ok(Shape::King), - _ => Err(TryFromCharError), + _ => Err(TryFromError), } } } +impl TryFrom<&str> for Shape { + type Error = TryFromError; + + fn try_from(value: &str) -> Result { + let first_char = value.chars().nth(0).ok_or(TryFromError)?; + Shape::try_from(first_char) + } +} + impl Into for &Shape { fn into(self) -> char { self._ascii_representation() @@ -147,3 +156,19 @@ impl PlacedPiece { 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!(>::into(Shape::Pawn) as char, 'p'); + } +}