[board] Implement TryFrom on string types for Color and Shape
This commit is contained in:
parent
3dfebb22eb
commit
c642c1158a
1 changed files with 39 additions and 12 deletions
|
@ -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<char> for Color {
|
||||
type Error = TryFromError;
|
||||
|
||||
fn try_from(value: char) -> Result<Self, Self::Error> {
|
||||
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<Self, Self::Error> {
|
||||
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<char> for Shape {
|
||||
type Error = TryFromError;
|
||||
|
||||
|
@ -89,19 +123,12 @@ impl TryFrom<char> 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<Self, Self::Error> {
|
||||
let first_char = value.chars().nth(0).ok_or(TryFromError)?;
|
||||
Shape::try_from(first_char)
|
||||
}
|
||||
}
|
||||
try_from_string!(Shape);
|
||||
|
||||
impl Into<char> for &Shape {
|
||||
fn into(self) -> char {
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue