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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
// This file is part of the shakmaty library.
// Copyright (C) 2017-2019 Niklas Fiekas <niklas.fiekas@backscattering.de>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.

use std::cmp::max;
use std::convert::TryInto;
use std::fmt;
use std::str;
use std::error::Error;
use std::ops::Sub;

macro_rules! from_repr_u8_impl {
    ($from:ty, $($t:ty)+) => {
        $(impl From<$from> for $t {
            #[inline]
            #[allow(clippy::cast_lossless)]
            fn from(value: $from) -> $t {
                value as u8 as $t
            }
        })+
    }
}

macro_rules! try_from_number_impl {
    ($type:ty, $error:ty, $lower:expr, $upper:expr, $($t:ty)+) => {
        $(impl std::convert::TryFrom<$t> for $type {
            type Error = $error;

            #[inline]
            #[allow(unused_comparisons)]
            #[allow(clippy::cast_lossless)]
            fn try_from(value: $t) -> Result<$type, Self::Error> {
                if $lower <= value && value < $upper {
                    Ok(<$type>::new(value as u32))
                } else {
                    Err(<$error>::from(()))
                }
            }
        })+
    }
}

/// A file of the chessboard.
#[allow(missing_docs)]
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
#[repr(u8)]
pub enum File {
    A = 0, B, C, D, E, F, G, H
}

impl File {
    /// Gets a `File` from an integer index.
    ///
    /// # Panics
    ///
    /// Panics if the index is not in the range `0..=7`.
    #[inline]
    pub fn new(index: u32) -> File {
        assert!(index < 8);
        unsafe { File::new_unchecked(index) }
    }

    /// Gets a `File` from an integer index.
    ///
    /// # Unsafety
    ///
    /// It is the callers responsibility to ensure the index is in the range
    /// `0..=7`.
    #[inline]
    pub unsafe fn new_unchecked(index: u32) -> File {
        debug_assert!(index < 8);
        ::std::mem::transmute(index as u8)
    }


    #[inline]
    pub fn from_char(ch: char) -> Option<File> {
        if 'a' <= ch && ch <= 'h' {
            Some(File::new(u32::from(ch as u8 - b'a')))
        } else {
            None
        }
    }

    #[inline]
    pub fn char(self) -> char {
        char::from(b'a' + u8::from(self))
    }

    #[inline]
    pub fn flip_diagonal(self) -> Rank {
        Rank::new(u32::from(self))
    }

    #[inline]
    pub fn offset(self, delta: i32) -> Option<Rank> {
        i32::from(self).checked_add(delta).and_then(|index| index.try_into().ok())
    }

    #[inline]
    pub fn flip_horizontal(self) -> File {
        File::new(7 - u32::from(self))
    }
}

impl Sub for File {
    type Output = i32;

    #[inline]
    fn sub(self, other: File) -> i32 {
        i32::from(self) - i32::from(other)
    }
}

impl fmt::Display for File {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.char())
    }
}

from_repr_u8_impl! { File, u8 i8 u16 i16 u32 i32 u64 i64 u128 i128 usize isize f32 f64 }

try_from_number_impl! { File, crate::errors::TryFromIntError, 0, 8, u8 i8 u16 i16 u32 i32 u64 i64 u128 i128 usize isize }
try_from_number_impl! { File, crate::errors::TryFromFloatError, 0.0, 8.0, f32 f64 }

/// A rank of the chessboard.
#[allow(missing_docs)]
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
#[repr(u8)]
pub enum Rank {
    First = 0, Second, Third, Fourth, Fifth, Sixth, Seventh, Eighth
}

impl Rank {
    /// Gets a `Rank` from an integer index.
    ///
    /// # Panics
    ///
    /// Panics if the index is not in the range `0..=7`.
    #[inline]
    pub fn new(index: u32) -> Rank {
        assert!(index < 8);
        unsafe { Rank::new_unchecked(index) }
    }

    /// Gets a `Rank` from an integer index.
    ///
    /// # Unsafety
    ///
    /// It is the callers responsibility to ensure the index is in the range
    /// `0..=7`.
    #[inline]
    pub unsafe fn new_unchecked(index: u32) -> Rank {
        debug_assert!(index < 8);
        ::std::mem::transmute(index as u8)
    }

    #[inline]
    pub fn from_char(ch: char) -> Option<Rank> {
        if '1' <= ch && ch <= '8' {
            Some(Rank::new(u32::from(ch as u8 - b'1')))
        } else {
            None
        }
    }

    #[inline]
    pub fn char(self) -> char {
        char::from(b'1' + u8::from(self))
    }

    #[inline]
    pub fn flip_diagonal(self) -> File {
        File::new(u32::from(self))
    }

    #[inline]
    pub fn offset(self, delta: i32) -> Option<Rank> {
        i32::from(self).checked_add(delta).and_then(|index| index.try_into().ok())
    }

    #[inline]
    pub fn flip_vertical(self) -> Rank {
        Rank::new(7 - u32::from(self))
    }
}

impl Sub for Rank {
    type Output = i32;

    #[inline]
    fn sub(self, other: Rank) -> i32 {
        i32::from(self) - i32::from(other)
    }
}

impl fmt::Display for Rank {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.char())
    }
}

from_repr_u8_impl! { Rank, u8 i8 u16 i16 u32 i32 u64 i64 u128 i128 usize isize f32 f64 }

try_from_number_impl! { Rank, crate::errors::TryFromIntError, 0, 8, u8 i8 u16 i16 u32 i32 u64 i64 u128 i128 usize isize }
try_from_number_impl! { Rank, crate::errors::TryFromFloatError, 0.0, 8.0, f32 f64 }

/// Error when parsing an invalid square name.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ParseSquareError;

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

impl Error for ParseSquareError {
    fn description(&self) -> &str {
        "invalid square name"
    }
}

impl From<()> for ParseSquareError {
    fn from(_: ()) -> ParseSquareError {
        ParseSquareError
    }
}

/// A square index.
#[allow(missing_docs)]
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
#[repr(u8)]
pub enum Square {
    A1 = 0, B1, C1, D1, E1, F1, G1, H1,
    A2, B2, C2, D2, E2, F2, G2, H2,
    A3, B3, C3, D3, E3, F3, G3, H3,
    A4, B4, C4, D4, E4, F4, G4, H4,
    A5, B5, C5, D5, E5, F5, G5, H5,
    A6, B6, C6, D6, E6, F6, G6, H6,
    A7, B7, C7, D7, E7, F7, G7, H7,
    A8, B8, C8, D8, E8, F8, G8, H8,
}

impl Square {
    /// Gets a `Square` from an integer index.
    ///
    /// # Panics
    ///
    /// Panics if the index is not in the range `0..=63`.
    ///
    /// # Examples
    ///
    /// ```
    /// use shakmaty::Square;
    ///
    /// assert_eq!(Square::new(0), Square::A1);
    /// assert_eq!(Square::new(63), Square::H8);
    /// ```
    #[inline]
    pub fn new(index: u32) -> Square {
        assert!(index < 64);
        unsafe { Square::new_unchecked(index) }
    }

    /// Gets a `Square` from an integer index.
    ///
    /// # Unsafety
    ///
    /// It is the callers responsibility to ensure it is in the range `0..=63`.
    #[inline]
    pub unsafe fn new_unchecked(index: u32) -> Square {
        debug_assert!(index < 64);
        ::std::mem::transmute(index as u8)
    }

    /// Tries to get a square from file and rank.
    ///
    /// # Examples
    ///
    /// ```
    /// use shakmaty::{Square, File, Rank};
    ///
    /// assert_eq!(Square::from_coords(File::A, Rank::First), Square::A1);
    /// ```
    #[inline]
    pub fn from_coords(file: File, rank: Rank) -> Square {
        unsafe { Square::new_unchecked(u32::from(file) | (u32::from(rank) << 3)) }
    }

    /// Parses a square name.
    ///
    /// # Errors
    ///
    /// Returns [`ParseSquareError`] if the input is not a valid square name
    /// in lowercase ASCII characters.
    ///
    /// # Example
    ///
    /// ```
    /// # use std::error::Error;
    /// #
    /// # fn try_main() -> Result<(), Box<Error>> {
    /// use shakmaty::Square;
    ///
    /// let sq = Square::from_ascii(b"a5")?;
    /// assert_eq!(sq, Square::A5);
    /// #
    /// #     Ok(())
    /// # }
    /// #
    /// # fn main() {
    /// #     try_main().unwrap();
    /// # }
    /// ```
    ///
    /// [`ParseSquareError`]: struct.ParseSquareError.html
    #[inline]
    pub fn from_ascii(s: &[u8]) -> Result<Square, ParseSquareError> {
        if s.len() == 2 {
            match (File::from_char(char::from(s[0])), Rank::from_char(char::from(s[1]))) {
                (Some(file), Some(rank)) => Ok(Square::from_coords(file, rank)),
                _ => Err(ParseSquareError),
            }
        } else {
            Err(ParseSquareError)
        }
    }

    /// Gets the file.
    ///
    /// # Examples
    ///
    /// ```
    /// use shakmaty::{Square, File};
    ///
    /// assert_eq!(Square::A1.file(), File::A);
    /// assert_eq!(Square::B2.file(), File::B);
    /// ```
    #[inline]
    pub fn file(self) -> File {
        File::new(u32::from(self) & 7)
    }

    /// Gets the rank.
    ///
    /// # Examples
    ///
    /// ```
    /// use shakmaty::{Square, Rank};
    ///
    /// assert_eq!(Square::A1.rank(), Rank::First);
    /// assert_eq!(Square::B2.rank(), Rank::Second);
    /// ```
    #[inline]
    pub fn rank(self) -> Rank {
        Rank::new(u32::from(self) >> 3)
    }

    /// Gets file and rank.
    ///
    /// # Examples
    ///
    /// ```
    /// use shakmaty::{Square, File, Rank};
    ///
    /// assert_eq!(Square::A1.coords(), (File::A, Rank::First));
    /// assert_eq!(Square::H8.coords(), (File::H, Rank::Eighth));
    /// ```
    #[inline]
    pub fn coords(self) -> (File, Rank) {
        (self.file(), self.rank())
    }

    /// Calculates the offset from a square index.
    ///
    /// # Examples
    ///
    /// ```
    /// use shakmaty::Square;
    ///
    /// assert_eq!(Square::F3.offset(8), Some(Square::F4));
    /// assert_eq!(Square::F3.offset(-1), Some(Square::E3));
    ///
    /// assert_eq!(Square::F3.offset(48), None);
    /// ```
    #[inline]
    pub fn offset(self, delta: i32) -> Option<Square> {
        i32::from(self).checked_add(delta).and_then(|index| index.try_into().ok())
    }

    /// Flip the square horizontally.
    ///
    /// ```
    /// use shakmaty::Square;
    ///
    /// assert_eq!(Square::H1.flip_horizontal(), Square::A1);
    /// assert_eq!(Square::D3.flip_horizontal(), Square::E3);
    /// ```
    #[inline]
    pub fn flip_horizontal(self) -> Square {
        // This is safe because all 6 bit values are in the range 0..=63.
        unsafe { Square::new_unchecked(u32::from(self) ^ 0b000_111) }
    }

    /// Flip the square vertically.
    ///
    /// ```
    /// use shakmaty::Square;
    ///
    /// assert_eq!(Square::A8.flip_vertical(), Square::A1);
    /// assert_eq!(Square::D3.flip_vertical(), Square::D6);
    /// ```
    #[inline]
    pub fn flip_vertical(self) -> Square {
        // This is safe because all 6 bit values are in the range 0..=63.
        unsafe { Square::new_unchecked(u32::from(self) ^ 0b111_000) }
    }

    /// Flip at the a1-h8 diagonal by swapping file and rank.
    ///
    /// ```
    /// use shakmaty::Square;
    ///
    /// assert_eq!(Square::A1.flip_diagonal(), Square::A1);
    /// assert_eq!(Square::A3.flip_diagonal(), Square::C1);
    /// ```
    pub fn flip_diagonal(self) -> Square {
        Square::from_coords(self.rank().flip_diagonal(), self.file().flip_diagonal())
    }

    /// Tests is the square is a light square.
    ///
    /// ```
    /// use shakmaty::Square;
    ///
    /// assert!(Square::D1.is_light());
    /// assert!(!Square::D8.is_light());
    /// ```
    #[inline]
    pub fn is_light(self) -> bool {
        (u32::from(self.rank()) + u32::from(self.file())) % 2 == 1
    }

    /// Tests is the square is a dark square.
    ///
    /// ```
    /// use shakmaty::Square;
    ///
    /// assert!(Square::E1.is_dark());
    /// assert!(!Square::E8.is_dark());
    /// ```
    #[inline]
    pub fn is_dark(self) -> bool {
        (u32::from(self.rank()) + u32::from(self.file())) % 2 == 0
    }

    /// The distance between the two squares, i.e. the number of king steps
    /// to get from one square to the other.
    ///
    /// ```
    /// use shakmaty::Square;
    ///
    /// assert_eq!(Square::A2.distance(Square::B5), 3);
    /// ```
    pub fn distance(self, other: Square) -> u32 {
        max((self.file() - other.file()).abs(),
            (self.rank() - other.rank()).abs()) as u32
    }

    /// Combines two squares, taking the file from the first and the rank from
    /// the second.
    ///
    /// ```
    /// use shakmaty::Square;
    ///
    /// assert_eq!(Square::D3.with_rank_of(Square::F5), Square::D5);
    /// ```
    #[inline]
    pub fn with_rank_of(self, other: Square) -> Square {
        Square::from_coords(self.file(), other.rank())
    }
}

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

try_from_number_impl! { Square, crate::errors::TryFromIntError, 0, 64, u8 i8 u16 i16 u32 i32 u64 i64 u128 i128 usize isize }

impl Sub for Square {
    type Output = i32;

    #[inline]
    fn sub(self, other: Square) -> i32 {
        i32::from(self) - i32::from(other)
    }
}

impl From<(File, Rank)> for Square {
    #[inline]
    fn from((file, rank): (File, Rank)) -> Square {
        Square::from_coords(file, rank)
    }
}

impl str::FromStr for Square {
    type Err = ParseSquareError;

    fn from_str(s: &str) -> Result<Square, ParseSquareError> {
        Square::from_ascii(s.as_bytes())
    }
}

impl fmt::Display for Square {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}{}", self.file().char(), self.rank().char())
    }
}

impl fmt::Debug for Square {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.to_string().to_uppercase())
    }
}

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

    #[test]
    fn test_square() {
        for file in (0..8).map(File::new) {
            for rank in (0..8).map(Rank::new) {
                let square = Square::from_coords(file, rank);
                assert_eq!(square.file(), file);
                assert_eq!(square.rank(), rank);
            }
        }
    }
}