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
use core::{array, convert::identity, num};

use crate::{color::Color, types::Piece, util::out_of_range_error};

/// Piece types: `Pawn`, `Knight`, `Bishop`, `Rook`, `Queen`, `King`.
///
/// # Examples
///
/// ```
/// use shakmaty::Role;
///
/// // Piece types are indexed from 1 to 6.
/// assert_eq!(u32::from(Role::Pawn), 1);
/// assert_eq!(u32::from(Role::King), 6);
/// ```
#[allow(missing_docs)]
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Debug, Hash)]
pub enum Role {
    Pawn = 1,
    Knight = 2,
    Bishop = 3,
    Rook = 4,
    Queen = 5,
    King = 6,
}

impl Role {
    /// Gets the piece type from its English letter.
    ///
    /// # Examples
    ///
    /// ```
    /// use shakmaty::Role;
    ///
    /// assert_eq!(Role::from_char('K'), Some(Role::King));
    /// assert_eq!(Role::from_char('n'), Some(Role::Knight));
    ///
    /// assert_eq!(Role::from_char('X'), None);
    /// ```
    pub const fn from_char(ch: char) -> Option<Role> {
        match ch {
            'P' | 'p' => Some(Role::Pawn),
            'N' | 'n' => Some(Role::Knight),
            'B' | 'b' => Some(Role::Bishop),
            'R' | 'r' => Some(Role::Rook),
            'Q' | 'q' => Some(Role::Queen),
            'K' | 'k' => Some(Role::King),
            _ => None,
        }
    }

    /// Gets a [`Piece`] of the given color.
    ///
    /// # Examples
    ///
    /// ```
    /// use shakmaty::{Color, Role};
    ///
    /// assert_eq!(Role::King.of(Color::Black), Color::Black.king());
    /// ```
    #[inline]
    pub const fn of(self, color: Color) -> Piece {
        Piece { color, role: self }
    }

    /// Gets the English letter for the piece type.
    ///
    /// # Examples
    ///
    /// ```
    /// use shakmaty::Role;
    ///
    /// assert_eq!(Role::Rook.char(), 'r');
    /// ```
    pub const fn char(self) -> char {
        match self {
            Role::Pawn => 'p',
            Role::Knight => 'n',
            Role::Bishop => 'b',
            Role::Rook => 'r',
            Role::Queen => 'q',
            Role::King => 'k',
        }
    }

    /// Gets the uppercase English letter for the piece type.
    ///
    /// # Examples
    ///
    /// ```
    /// use shakmaty::Role;
    ///
    /// assert_eq!(Role::Rook.upper_char(), 'R');
    /// ```
    pub const fn upper_char(self) -> char {
        match self {
            Role::Pawn => 'P',
            Role::Knight => 'N',
            Role::Bishop => 'B',
            Role::Rook => 'R',
            Role::Queen => 'Q',
            Role::King => 'K',
        }
    }

    /// `Pawn`, `Knight`, `Bishop`, `Rook`, `Queen`, and `King`, in this order.
    pub const ALL: [Role; 6] = [
        Role::Pawn,
        Role::Knight,
        Role::Bishop,
        Role::Rook,
        Role::Queen,
        Role::King,
    ];
}

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

macro_rules! nonzero_int_from_role_impl {
    ($($t:ty)+) => {
        $(impl From<Role> for $t {
            #[inline]
            fn from(role: Role) -> $t {
                <$t>::new(role.into()).expect("nonzero role discriminant")
            }
        })+
    }
}

nonzero_int_from_role_impl! {
    num::NonZeroU8 num::NonZeroI8
    num::NonZeroU16 num::NonZeroI16
    num::NonZeroU32 num::NonZeroI32
    num::NonZeroU64 num::NonZeroI64
    num::NonZeroU128 num::NonZeroI128
    num::NonZeroUsize num::NonZeroIsize
}

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

            #[inline]
            fn try_from(value: $t) -> Result<Role, Self::Error> {
                Ok(match value {
                    1 => Role::Pawn,
                    2 => Role::Knight,
                    3 => Role::Bishop,
                    4 => Role::Rook,
                    5 => Role::Queen,
                    6 => Role::King,
                    _ => return Err(out_of_range_error()),
                })
            }
        })+
    }
}

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

/// Container with values for each [`Role`].
#[derive(Copy, Clone, Default, Eq, PartialEq, Debug, Hash)]
#[repr(C)]
pub struct ByRole<T> {
    pub pawn: T,
    pub knight: T,
    pub bishop: T,
    pub rook: T,
    pub queen: T,
    pub king: T,
}

impl<T> ByRole<T> {
    pub fn new_with<F>(mut init: F) -> ByRole<T>
    where
        F: FnMut(Role) -> T,
    {
        ByRole {
            pawn: init(Role::Pawn),
            knight: init(Role::Knight),
            bishop: init(Role::Bishop),
            rook: init(Role::Rook),
            queen: init(Role::Queen),
            king: init(Role::King),
        }
    }

    #[inline]
    pub const fn get(&self, role: Role) -> &T {
        // Safety: Trivial offset into #[repr(C)] struct.
        unsafe {
            &*(self as *const ByRole<T>)
                .cast::<T>()
                .offset(role as isize - 1)
        }
    }

    #[inline]
    pub fn get_mut(&mut self, role: Role) -> &mut T {
        // Safety: Trivial offset into #[repr(C)] struct.
        unsafe {
            &mut *(self as *mut ByRole<T>)
                .cast::<T>()
                .offset(role as isize - 1)
        }
    }

    #[inline]
    pub fn for_each<F>(self, mut f: F)
    where
        F: FnMut(T),
    {
        f(self.pawn);
        f(self.knight);
        f(self.bishop);
        f(self.rook);
        f(self.queen);
        f(self.king);
    }

    #[inline]
    pub fn map<U, F>(self, mut f: F) -> ByRole<U>
    where
        F: FnMut(T) -> U,
    {
        ByRole {
            pawn: f(self.pawn),
            knight: f(self.knight),
            bishop: f(self.bishop),
            rook: f(self.rook),
            queen: f(self.queen),
            king: f(self.king),
        }
    }

    #[inline]
    pub fn find<F>(&self, mut predicate: F) -> Option<Role>
    where
        F: FnMut(&T) -> bool,
    {
        if predicate(&self.pawn) {
            Some(Role::Pawn)
        } else if predicate(&self.knight) {
            Some(Role::Knight)
        } else if predicate(&self.bishop) {
            Some(Role::Bishop)
        } else if predicate(&self.rook) {
            Some(Role::Rook)
        } else if predicate(&self.queen) {
            Some(Role::Queen)
        } else if predicate(&self.king) {
            Some(Role::King)
        } else {
            None
        }
    }

    #[inline]
    pub const fn as_ref(&self) -> ByRole<&T> {
        ByRole {
            pawn: &self.pawn,
            knight: &self.knight,
            bishop: &self.bishop,
            rook: &self.rook,
            queen: &self.queen,
            king: &self.king,
        }
    }

    #[inline]
    pub fn as_mut(&mut self) -> ByRole<&mut T> {
        ByRole {
            pawn: &mut self.pawn,
            knight: &mut self.knight,
            bishop: &mut self.bishop,
            rook: &mut self.rook,
            queen: &mut self.queen,
            king: &mut self.king,
        }
    }

    pub fn zip<U>(self, other: ByRole<U>) -> ByRole<(T, U)> {
        ByRole {
            pawn: (self.pawn, other.pawn),
            knight: (self.knight, other.knight),
            bishop: (self.bishop, other.bishop),
            rook: (self.rook, other.rook),
            queen: (self.queen, other.queen),
            king: (self.king, other.king),
        }
    }

    pub fn zip_role(self) -> ByRole<(Role, T)> {
        ByRole::new_with(identity).zip(self)
    }

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

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

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

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

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

impl<T> IntoIterator for ByRole<T> {
    type Item = T;
    type IntoIter = array::IntoIter<T, 6>;

    fn into_iter(self) -> Self::IntoIter {
        [
            self.pawn,
            self.knight,
            self.bishop,
            self.rook,
            self.queen,
            self.king,
        ]
        .into_iter()
    }
}