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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
//! White or black.

use core::{array, convert::identity, fmt, mem, num, ops, str::FromStr};

use crate::{
    role::{ByRole, Role},
    square::Rank,
    types::Piece,
    util::out_of_range_error,
};

/// `White` or `Black`.
#[allow(missing_docs)]
#[derive(Copy, Clone, Eq, PartialEq, Debug, Hash)]
pub enum Color {
    Black = 0,
    White = 1,
}

impl Color {
    pub const fn from_char(ch: char) -> Option<Color> {
        Some(match ch {
            'w' => Color::White,
            'b' => Color::Black,
            _ => return None,
        })
    }

    pub fn char(self) -> char {
        self.fold_wb('w', 'b')
    }

    fn from_name(name: &str) -> Option<Color> {
        Some(match name {
            "white" => Color::White,
            "black" => Color::Black,
            _ => return None,
        })
    }

    const fn name(self) -> &'static str {
        match self {
            Color::Black => "black",
            Color::White => "white",
        }
    }

    #[inline]
    pub const fn from_white(white: bool) -> Color {
        if white {
            Color::White
        } else {
            Color::Black
        }
    }

    #[inline]
    pub const fn from_black(black: bool) -> Color {
        if black {
            Color::Black
        } else {
            Color::White
        }
    }

    #[inline]
    pub fn fold_wb<T>(self, white: T, black: T) -> T {
        match self {
            Color::White => white,
            Color::Black => black,
        }
    }

    #[inline]
    pub const fn is_white(self) -> bool {
        matches!(self, Color::White)
    }
    #[inline]
    pub const fn is_black(self) -> bool {
        matches!(self, Color::Black)
    }

    /// Same as `!self`, but usable in `const` contexts.
    #[must_use]
    pub const fn other(self) -> Color {
        match self {
            Color::White => Color::Black,
            Color::Black => Color::White,
        }
    }

    #[inline]
    pub const fn backrank(self) -> Rank {
        match self {
            Color::White => Rank::First,
            Color::Black => Rank::Eighth,
        }
    }

    #[inline]
    pub fn relative_rank(self, rank: Rank) -> Rank {
        match self {
            Color::White => rank,
            Color::Black => rank.flip_vertical(),
        }
    }

    #[inline]
    pub const fn pawn(self) -> Piece {
        Role::Pawn.of(self)
    }

    #[inline]
    pub const fn knight(self) -> Piece {
        Role::Knight.of(self)
    }

    #[inline]
    pub const fn bishop(self) -> Piece {
        Role::Bishop.of(self)
    }

    #[inline]
    pub const fn rook(self) -> Piece {
        Role::Rook.of(self)
    }

    #[inline]
    pub const fn queen(self) -> Piece {
        Role::Queen.of(self)
    }

    #[inline]
    pub const fn king(self) -> Piece {
        Role::King.of(self)
    }

    /// `White` and `Black`, in this order.
    pub const ALL: [Color; 2] = [Color::White, Color::Black];
}

impl ops::Not for Color {
    type Output = Color;

    #[inline]
    fn not(self) -> Color {
        self.fold_wb(Color::Black, Color::White)
    }
}

impl ops::BitXor<bool> for Color {
    type Output = Color;

    #[inline]
    fn bitxor(self, flip: bool) -> Color {
        Color::from_white(self.is_white() ^ flip)
    }
}

impl ops::BitXorAssign<bool> for Color {
    fn bitxor_assign(&mut self, flip: bool) {
        *self = *self ^ flip;
    }
}

impl fmt::Display for Color {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.name())
    }
}

/// Error when parsing an invalid color name.
#[derive(Clone, Debug)]
pub struct ParseColorError;

impl fmt::Display for ParseColorError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("invalid color")
    }
}

#[cfg(feature = "std")]
impl std::error::Error for ParseColorError {}

impl FromStr for Color {
    type Err = ParseColorError;

    fn from_str(s: &str) -> Result<Color, ParseColorError> {
        Color::from_name(s).ok_or(ParseColorError)
    }
}

from_enum_as_int_impl! { Color, u8 i8 u16 i16 u32 i32 u64 i64 u128 i128 usize isize }

macro_rules! try_color_from_int_impl {
    ($($t:ty)+) => {
        $(impl core::convert::TryFrom<$t> for Color {
            type Error = num::TryFromIntError;

            #[inline]
            fn try_from(value: $t) -> Result<Color, Self::Error> {
                Ok(match value {
                    0 => Color::Black,
                    1 => Color::White,
                    _ => return Err(out_of_range_error())
                })
            }
        })+
    }
}

try_color_from_int_impl! { u8 i8 u16 i16 u32 i32 u64 i64 u128 i128 usize isize }

/// Container with values for each [`Color`].
#[derive(Copy, Clone, Default, Eq, PartialEq, Debug, Hash)]
pub struct ByColor<T> {
    pub black: T,
    pub white: T,
}

impl<T> ByColor<T> {
    #[inline]
    pub fn new_with<F>(mut init: F) -> ByColor<T>
    where
        F: FnMut(Color) -> T,
    {
        ByColor {
            white: init(Color::White),
            black: init(Color::Black),
        }
    }

    #[inline]
    pub const fn get(&self, color: Color) -> &T {
        match color {
            Color::Black => &self.black,
            Color::White => &self.white,
        }
    }

    #[inline]
    pub fn get_mut(&mut self, color: Color) -> &mut T {
        match color {
            Color::Black => &mut self.black,
            Color::White => &mut self.white,
        }
    }

    #[deprecated = "Use ByColor::swap()"]
    pub fn flip(&mut self) {
        self.swap();
    }

    pub fn swap(&mut self) {
        mem::swap(&mut self.white, &mut self.black);
    }

    #[must_use]
    pub fn into_flipped(self) -> ByColor<T> {
        ByColor {
            black: self.white,
            white: self.black,
        }
    }

    #[inline]
    pub fn for_each<F>(self, mut f: F)
    where
        F: FnMut(T),
    {
        f(self.white);
        f(self.black);
    }

    #[inline]
    pub fn map<U, F>(self, mut f: F) -> ByColor<U>
    where
        F: FnMut(T) -> U,
    {
        ByColor {
            white: f(self.white),
            black: f(self.black),
        }
    }

    #[inline]
    pub fn find<F>(&self, mut predicate: F) -> Option<Color>
    where
        F: FnMut(&T) -> bool,
    {
        if predicate(&self.white) {
            Some(Color::White)
        } else if predicate(&self.black) {
            Some(Color::Black)
        } else {
            None
        }
    }

    #[inline]
    pub const fn as_ref(&self) -> ByColor<&T> {
        ByColor {
            black: &self.black,
            white: &self.white,
        }
    }

    #[inline]
    pub fn as_mut(&mut self) -> ByColor<&mut T> {
        ByColor {
            black: &mut self.black,
            white: &mut self.white,
        }
    }

    pub fn zip<U>(self, other: ByColor<U>) -> ByColor<(T, U)> {
        ByColor {
            black: (self.black, other.black),
            white: (self.white, other.white),
        }
    }

    pub fn zip_color(self) -> ByColor<(Color, T)> {
        ByColor::new_with(identity).zip(self)
    }

    pub fn iter(&self) -> array::IntoIter<&T, 2> {
        self.as_ref().into_iter()
    }

    pub fn iter_mut(&mut self) -> array::IntoIter<&mut T, 2> {
        self.as_mut().into_iter()
    }
}

impl<T> ByColor<ByRole<T>> {
    pub const fn piece(&self, piece: Piece) -> &T {
        self.get(piece.color).get(piece.role)
    }

    pub fn piece_mut(&mut self, piece: Piece) -> &mut T {
        self.get_mut(piece.color).get_mut(piece.role)
    }
}

#[cfg(feature = "variant")]
impl ByColor<ByRole<u8>> {
    pub(crate) fn count(&self) -> usize {
        self.iter().map(ByRole::count).sum()
    }
}

impl<T: PartialOrd> ByColor<T> {
    pub fn normalize(&mut self) {
        if self.white < self.black {
            self.swap();
        }
    }

    #[must_use]
    pub fn into_normalized(mut self) -> ByColor<T> {
        self.normalize();
        self
    }
}

impl<T: PartialEq> ByColor<T> {
    pub fn is_symmetric(&self) -> bool {
        self.white == self.black
    }
}

impl<T: Copy> ByColor<&T> {
    pub fn copied(self) -> ByColor<T> {
        self.map(|item| *item)
    }
}

impl<T: Clone> ByColor<&T> {
    pub fn cloned(self) -> ByColor<T> {
        self.map(Clone::clone)
    }
}

impl<T> IntoIterator for ByColor<T> {
    type Item = T;
    type IntoIter = array::IntoIter<T, 2>;

    fn into_iter(self) -> Self::IntoIter {
        [self.white, self.black].into_iter()
    }
}