1use anyhow::anyhow;
2use std::fmt;
3use std::str::FromStr;
4
5#[derive(Hash, Eq, PartialEq, PartialOrd, Ord, Clone, Copy, Debug)]
6pub enum Piece {
7 Rabbit,
8 Cat,
9 Dog,
10 Horse,
11 Camel,
12 Elephant,
13}
14
15impl fmt::Display for Piece {
16 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
17 let piece = match self {
18 Piece::Elephant => 'e',
19 Piece::Camel => 'm',
20 Piece::Horse => 'h',
21 Piece::Dog => 'd',
22 Piece::Cat => 'c',
23 Piece::Rabbit => 'r',
24 };
25
26 write!(f, "{}", piece)
27 }
28}
29
30impl FromStr for Piece {
31 type Err = anyhow::Error;
32
33 fn from_str(s: &str) -> Result<Self, Self::Err> {
34 let piece = match s.chars().next() {
35 Some(c) if s.len() == 1 => match c {
36 'E' | 'e' => Some(Piece::Elephant),
37 'M' | 'm' => Some(Piece::Camel),
38 'H' | 'h' => Some(Piece::Horse),
39 'D' | 'd' => Some(Piece::Dog),
40 'C' | 'c' => Some(Piece::Cat),
41 'R' | 'r' => Some(Piece::Rabbit),
42 _ => None,
43 },
44 _ => None,
45 };
46
47 piece.ok_or_else(|| anyhow!("Invalid value for piece"))
48 }
49}