1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
use std::fmt;
use std::iter;
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum Color {
Black,
White,
}
impl Color {
pub fn iter() -> ColorIter {
ColorIter {
current: Some(Color::Black),
}
}
pub fn flip(&self) -> Color {
match *self {
Color::Black => Color::White,
Color::White => Color::Black,
}
}
#[inline(always)]
pub fn index(&self) -> usize {
*self as usize
}
}
impl fmt::Display for Color {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
Color::Black => write!(f, "Black"),
Color::White => write!(f, "White"),
}
}
}
pub struct ColorIter {
current: Option<Color>,
}
impl iter::Iterator for ColorIter {
type Item = Color;
fn next(&mut self) -> Option<Self::Item> {
let current = self.current;
if let Some(current) = self.current {
self.current = match current {
Color::Black => Some(Color::White),
Color::White => None,
}
}
current
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn flip() {
assert_eq!(Color::White, Color::Black.flip());
assert_eq!(Color::Black, Color::White.flip());
}
}