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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
//! Functionality dealing with castling in chess.
//!
//! # What is Castling?
//!
//! In chess, [castling] is a special move performed by a king and a rook.
//! Castling can only be done under certain conditions.
//!
//! For example, a piece can't be moved in a castle if it has been moved
//! previously. You can use the [`Rights`] type to keep track of this
//! case:
//!
//! - If a king has moved, both castle rights for its color must be cleared
//! - If a rook has moved, the castle right for its color and board side must be
//! cleared
//!
//! ```txt
//! Before:         | After:
//! r . + . k . + r | . . k r . . . r
//! . . . . . . . . | . . . . . . . .
//! . . . . . . . . | . . . . . . . .
//! . . . . . . . . | . . . . . . . .
//! . . . . . . . . | . . . . . . . .
//! . . . . . . . . | . . . . . . . .
//! . . . . . . . . | . . . . . . . .
//! R . + . K . + R | R . . . . R K .
//! ```
//!
//! In the **before** frame, kings and rooks are in their initial positions.
//! Kings may be moved to the indicated (+) squares. In the **after** frame,
//! White has castled kingside and Black has castled queenside.
//!
//! Notice that the king can only move a maximum of two squares when castling,
//! regardless of which board side.
//!
//! [`Rights`]: struct.Rights.html
//! [castling]: https://en.wikipedia.org/wiki/Castling

use core::{fmt, ops, str};
use prelude::*;

#[cfg(feature = "serde")]
use serde::*;

use iter;

const ALL_BITS: u8 = 0b1111;
const MAX_LEN: usize = 1 + ALL_BITS as usize;

impl_rand!(u8 => Rights, Right);

/// Castle rights for a chess game.
///
/// # Examples
///
/// Similar to with [`Bitboard`], castle rights can be composed with set
/// operations.
///
/// ```
/// # use hexe_core::prelude::*;
/// assert_eq!(
///     Right::WhiteKing   | Right::WhiteQueen,
///     Rights::WHITE_KING | Rights::WHITE_QUEEN
/// );
/// ```
///
/// [`Bitboard`]: ../board/bitboard/struct.Bitboard.html
#[derive(PartialEq, Eq, Clone, Copy, Hash, FromUnchecked)]
pub struct Rights(u8);

impl From<u8> for Rights {
    #[inline]
    fn from(inner: u8) -> Rights {
        Self::FULL & Rights(inner)
    }
}

impl From<Color> for Rights {
    #[inline]
    fn from(color: Color) -> Rights {
        match color {
            Color::White => Self::WHITE_KING | Self::WHITE_QUEEN,
            Color::Black => Self::BLACK_KING | Self::BLACK_QUEEN,
        }
    }
}

impl Default for Rights {
    #[inline]
    fn default() -> Rights { Rights::FULL }
}

impl fmt::Debug for Rights {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if self.is_empty() {
            fmt::Display::fmt("(empty)", f)
        } else {
            self.map_str(|s| fmt::Display::fmt(s, f))
        }
    }
}

impl fmt::Display for Rights {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.map_str(|s| s.fmt(f))
    }
}

define_from_str_error! { Rights;
    /// The error returned when `Rights::from_str` fails.
    "failed to parse a string as castling rights"
}

#[cfg(feature = "serde")]
impl Serialize for Rights {
    fn serialize<S: Serializer>(&self, ser: S) -> Result<S::Ok, S::Error> {
        self.map_str(|s| ser.serialize_str(s))
    }
}

impl str::FromStr for Rights {
    type Err = FromStrError;

    fn from_str(s: &str) -> Result<Rights, FromStrError> {
        let bytes = s.as_bytes();
        let mut result = Rights::EMPTY;

        if bytes.len() == 1 && bytes[0] == b'-' {
            Ok(result)
        } else {
            for &byte in bytes {
                result |= match byte {
                    b'K' => Rights::WHITE_KING,
                    b'k' => Rights::BLACK_KING,
                    b'Q' => Rights::WHITE_QUEEN,
                    b'q' => Rights::BLACK_QUEEN,
                    _ => return Err(FromStrError(())),
                };
            }
            Ok(result)
        }
    }
}

impl<T> ::misc::Extract<[T; MAX_LEN]> for Rights {
    type Output = T;

    #[inline]
    fn extract<'a>(self, array: &'a [T; MAX_LEN]) -> &'a T {
        unsafe { array.get_unchecked(self.0 as usize) }
    }

    #[inline]
    fn extract_mut<'a>(self, array: &'a mut [T; MAX_LEN]) -> &'a mut T {
        unsafe { array.get_unchecked_mut(self.0 as usize) }
    }
}

impl Rights {
    /// Rights for white player.
    pub const WHITE: Rights = Rights(0b0011);

    /// Rights for black player.
    pub const BLACK: Rights = Rights(0b1100);

    /// White kingside.
    pub const WHITE_KING: Rights = Rights(0b0001);

    /// White queenside.
    pub const WHITE_QUEEN: Rights = Rights(0b0010);

    /// Black kingside.
    pub const BLACK_KING: Rights = Rights(0b0100);

    /// Black queenside.
    pub const BLACK_QUEEN: Rights = Rights(0b1000);

    /// Returns the result of applying a function to a mutable string
    /// representation of `self`.
    #[inline]
    pub fn map_str<T, F: FnOnce(&mut str) -> T>(&self, f: F) -> T {
        let mut buf = [0u8; 4];
        let slice: &mut [u8] = if self.is_empty() {
            buf[0] = b'-';
            &mut buf[..1]
        } else {
            let mut idx = 0;
            for right in *self {
                unsafe {
                    *buf.get_unchecked_mut(idx) = char::from(right) as u8;
                }
                idx += 1;
            }
            unsafe { buf.get_unchecked_mut(..idx) }
        };
        unsafe { f(str::from_utf8_unchecked_mut(slice)) }
    }
}

impl_bit_set! { Rights ALL_BITS => Right }

impl_composition_ops! { Rights => Right }

impl From<Right> for Rights {
    #[inline]
    fn from(right: Right) -> Self {
        Rights(1 << right as usize)
    }
}

/// An individual castle right for a chess game.
#[derive(PartialEq, Eq, Clone, Copy, Debug, Hash, FromUnchecked)]
#[uncon(impl_from, other(u16, u32, u64, usize))]
#[repr(u8)]
pub enum Right {
    /// White kingside: E1 to G1.
    WhiteKing,
    /// White queenside: E1 to C1.
    WhiteQueen,
    /// Black kingside: E8 to G8.
    BlackKing,
    /// Black queenside: E8 to C8.
    BlackQueen,
}

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

    #[inline]
    fn not(self) -> Side {
        (1 - self as u8).into()
    }
}

impl From<Right> for char {
    #[inline]
    fn from(right: Right) -> char {
        b"KQkq"[right as usize] as char
    }
}

impl From<Right> for Piece {
    #[inline]
    fn from(right: Right) -> Piece {
        match right {
            Right::WhiteKing  => Piece::WhiteKing,
            Right::WhiteQueen => Piece::WhiteQueen,
            Right::BlackKing  => Piece::BlackKing,
            Right::BlackQueen => Piece::BlackQueen,
        }
    }
}

impl Right {
    /// Creates a new castle right for `color` and `side`.
    #[inline]
    pub fn new(color: Color, side: Side) -> Right {
        (((color as u8) << 1) | side as u8).into()
    }

    /// Returns a castle right from the parsed character.
    #[inline]
    pub fn from_char(ch: char) -> Option<Right> {
        match ch {
            'K' => Some(Right::WhiteKing),
            'Q' => Some(Right::WhiteQueen),
            'k' => Some(Right::BlackKing),
            'q' => Some(Right::BlackQueen),
            _ => None,
        }
    }

    /// Returns the path between the rook and king for this right.
    #[inline]
    pub fn path(self) -> Bitboard {
        path::ALL[self as usize]
    }

    /// Returns an efficient iterator over each square in the path between the
    /// rook and king for `self`.
    #[inline]
    pub fn path_iter(self) -> iter::Range<Square> {
        static ITERS: [iter::Range<Square>; 4] = [
            iter::Range { iter: 05..07 },
            iter::Range { iter: 01..04 },
            iter::Range { iter: 61..63 },
            iter::Range { iter: 57..60 },
        ];
        ITERS[self as usize].clone()
    }

    /// Returns the color for `self`.
    #[inline]
    pub fn color(self) -> Color {
        ((self as u8) >> 1).into()
    }

    /// Returns the castle side for `self`.
    #[inline]
    pub fn side(self) -> Side {
        (1 & self as u8).into()
    }
}

pub mod path {
    //! The paths between the rook and king for each castling right.
    use super::*;

    /// White kingside path.
    pub const WHITE_KING: Bitboard = Bitboard(0x60);

    /// Black kingside path.
    pub const BLACK_KING: Bitboard = Bitboard(WHITE_KING.0 << 56);

    /// White queenside path.
    pub const WHITE_QUEEN: Bitboard = Bitboard(0x0E);

    /// Black queenside path.
    pub const BLACK_QUEEN: Bitboard = Bitboard(WHITE_QUEEN.0 << 56);

    /// All paths.
    pub static ALL: [Bitboard; 4] = [
        WHITE_KING,
        WHITE_QUEEN,
        BLACK_KING,
        BLACK_QUEEN,
    ];
}

/// A side used to castle.
#[derive(PartialEq, Eq, Clone, Copy, Debug, Hash, FromUnchecked)]
#[uncon(impl_from, other(u16, u32, u64, usize))]
#[repr(u8)]
pub enum Side {
    /// King castling side (O-O).
    King,
    /// Queen castling side (O-O-O).
    Queen,
}

impl From<Side> for Role {
    #[inline]
    fn from(side: Side) -> Role {
        match side {
            Side::King  => Role::King,
            Side::Queen => Role::Queen,
        }
    }
}

#[cfg(any(test, feature = "rand"))]
impl ::rand::Rand for Side {
    #[inline]
    fn rand<R: ::rand::Rng>(rng: &mut R) -> Self {
        if bool::rand(rng) {
            Side::King
        } else {
            Side::Queen
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn castle_right_new() {
        for &side in &[Side::King, Side::Queen] {
            for &color in &[Color::White, Color::Black] {
                let right = Right::new(color, side);
                assert_eq!(right.side(),  side);
                assert_eq!(right.color(), color);
            }
        }
    }

    #[test]
    fn castle_right_char() {
        for right in Rights::FULL {
            let ch = char::from(right);
            assert_eq!(Some(right), Right::from_char(ch));
        }
    }

    #[test]
    fn castle_right_path() {
        fn path(right: Right) -> Bitboard {
            use self::Right::*;
            match right {
                WhiteKing  => path::WHITE_KING,
                BlackKing  => path::BLACK_KING,
                WhiteQueen => path::WHITE_QUEEN,
                BlackQueen => path::BLACK_QUEEN,
            }
        }
        for right in Rights::FULL {
            assert_eq!(right.path(), path(right));
        }
    }

    #[test]
    fn castle_rights_string() {
        use self::Right::*;

        let pairs = [
            (Rights::FULL, "KQkq"),
            (Rights::EMPTY, "-"),
            (BlackKing.into(), "k"),
            (BlackKing | WhiteQueen, "Qk"),
        ];

        for &(rights, exp) in &pairs {
            rights.map_str(|s| {
                assert_eq!(s, exp);
                assert_eq!(rights, s.parse().unwrap());
            });
        }
    }
}