1use std::fmt;
2
3type SideInternal = usize;
4
5#[derive(PartialEq, PartialOrd, Copy, Clone)]
7pub struct Side(pub SideInternal);
8
9const CHARS: [char; 2] = ['w', 'b'];
10const NAMES: [&str; 2] = ["white", "black"];
11
12impl Side {
13 pub fn to_char(self) -> char {
14 CHARS[self.to_usize()]
15 }
16
17 pub fn to_usize(self) -> usize {
18 self.0
19 }
20
21 pub fn raw(self) -> SideInternal {
22 self.0
23 }
24
25 pub fn flip(self) -> Side {
27 Side(self.0 ^ 1)
28 }
29
30 pub fn parse(c: char) -> Result<Side, String> {
31 for (i, _c) in CHARS.iter().enumerate() {
32 if *_c == c {
33 return Ok(Side(i));
34 }
35 }
36 Err(format!("Side not recognised: {}", c))
37 }
38
39 pub fn to_str(self) -> &'static str {
40 NAMES[self.0]
41 }
42}
43
44impl fmt::Display for Side {
45 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
46 write!(f, "{}", self.to_char())
47 }
48}
49
50impl fmt::Debug for Side {
51 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
52 write!(f, "{}", self.to_char())
53 }
54}
55
56pub const WHITE: Side = Side(0);
57pub const BLACK: Side = Side(1);
58
59#[cfg(test)]
60mod test {
61 use super::*;
62
63 #[test]
64 fn char() {
65 assert_eq!(BLACK.to_char(), 'b');
66 assert_eq!(WHITE.to_char(), 'w');
67 }
68
69 #[test]
70 fn flip() {
71 assert_eq!(BLACK.flip(), WHITE);
72 assert_eq!(WHITE.flip(), BLACK);
73 }
74}