chess_notation_parser/
piece.rs1use std::fmt;
2
3#[derive(Ord, PartialOrd, Debug, PartialEq, Eq, Copy, Clone)]
5pub enum Piece {
6 King,
7 Queen,
8 Rook,
9 Knight,
10 Bishop,
11 Pawn,
12}
13
14impl TryFrom<&str> for Piece {
15 type Error = &'static str;
16
17 fn try_from(piece: &str) -> Result<Self, Self::Error> {
18 Ok(match piece {
19 "K" => Self::King,
20 "Q" => Self::Queen,
21 "R" => Self::Rook,
22 "B" => Self::Bishop,
23 "N" => Self::Knight,
24 "P" => Self::Pawn,
25 _ => return Err("Invalid piece character"),
26 })
27 }
28}
29
30impl fmt::Display for Piece {
31 #[rustfmt::skip]
32 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
33 write!(f, "{}", match self {
34 Self::King => "King",
35 Self::Queen => "Queen",
36 Self::Rook => "Rook",
37 Self::Knight => "Knight",
38 Self::Bishop => "Bishop",
39 Self::Pawn => "Pawn",
40 })
41 }
42}
43
44#[cfg(test)]
45mod tests {
46 use super::*;
47
48 #[test]
49 fn print_player() {
50 assert_eq!("King", format!("{}", Piece::King));
51 assert_eq!("Queen", format!("{}", Piece::Queen));
52 assert_eq!("Rook", format!("{}", Piece::Rook));
53 assert_eq!("Knight", format!("{}", Piece::Knight));
54 assert_eq!("Bishop", format!("{}", Piece::Bishop));
55 assert_eq!("Pawn", format!("{}", Piece::Pawn));
56 }
57
58 #[test]
59 fn try_from_valid() {
60 assert_eq!(Piece::try_from("K").unwrap(), Piece::King);
61 assert_eq!(Piece::try_from("Q").unwrap(), Piece::Queen);
62 assert_eq!(Piece::try_from("R").unwrap(), Piece::Rook);
63 assert_eq!(Piece::try_from("N").unwrap(), Piece::Knight);
64 assert_eq!(Piece::try_from("B").unwrap(), Piece::Bishop);
65 assert_eq!(Piece::try_from("P").unwrap(), Piece::Pawn);
66 }
67
68 #[test]
69 fn try_from_invalid() {
70 assert!(Piece::try_from("").is_err());
71 assert!(Piece::try_from("too big string").is_err());
72 assert!(Piece::try_from("X").is_err());
73 }
74}