From c642c1158ab710aa5cf467b64b225aca139149d3 Mon Sep 17 00:00:00 2001 From: Eryn Wells Date: Mon, 22 Jan 2024 08:10:40 -0800 Subject: [PATCH] [board] Implement TryFrom on string types for Color and Shape --- board/src/piece.rs | 51 +++++++++++++++++++++++++++++++++++----------- 1 file changed, 39 insertions(+), 12 deletions(-) diff --git a/board/src/piece.rs b/board/src/piece.rs index 45ed4b0..7dc2e8f 100644 --- a/board/src/piece.rs +++ b/board/src/piece.rs @@ -7,6 +7,12 @@ use crate::{ use std::fmt; use std::slice::Iter; +#[derive(Debug, Eq, PartialEq)] +pub enum TryFromError { + InvalidCharacter, + ZeroLengthString, +} + #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub enum Color { White = 0, @@ -32,6 +38,37 @@ impl Default for Color { } } +impl TryFrom for Color { + type Error = TryFromError; + + fn try_from(value: char) -> Result { + match value { + 'w' | 'W' => Ok(Color::White), + 'b' | 'B' => Ok(Color::Black), + _ => Err(TryFromError::InvalidCharacter), + } + } +} + +macro_rules! try_from_string { + ($type:ty) => { + try_from_string!($type, &str); + try_from_string!($type, &String); + }; + ($type:ty, $from_type:ty) => { + impl TryFrom<$from_type> for $type { + type Error = TryFromError; + + fn try_from(value: $from_type) -> Result { + let first_char = value.chars().nth(0).ok_or(TryFromError::ZeroLengthString)?; + Self::try_from(first_char) + } + } + }; +} + +try_from_string!(Color); + #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub enum Shape { Pawn = 0, @@ -75,9 +112,6 @@ impl Shape { } } -#[derive(Debug, Eq, PartialEq)] -pub struct TryFromError; - impl TryFrom for Shape { type Error = TryFromError; @@ -89,19 +123,12 @@ impl TryFrom for Shape { 'R' | 'r' => Ok(Shape::Rook), 'Q' | 'q' => Ok(Shape::Queen), 'K' | 'k' => Ok(Shape::King), - _ => Err(TryFromError), + _ => Err(TryFromError::InvalidCharacter), } } } -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) - } -} +try_from_string!(Shape); impl Into for &Shape { fn into(self) -> char {