haitaka-types 0.1.3

Internal data types library for haitaka
Documentation
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
//! The [`Square`] enum represent squares on a Shogi board
//!
//! By Japanese convention squares are written as {file}{rank}. For instance, the topmost
//! rightmost square in board diagrams is written either as "1a", "11", or "1一";
//! the center square is written as "5e", "55", or "5五". Internally we represent square
//! "1a" as Square::A1, and square "5e" as Square::E5. So, other than in Internation Chess,
//! ranks (rows) are indicated by letters and files (columns) by numerals.
//!
//! Squares are ordered internally in file-major order: A1, B1, C1, ... I8, I9. This
//! means that the squares on the rightmost file (File::One) correspond to the LSB bits
//! of the bitboards. The main reason for choosing this internal layout is that it
//! makes move generation of Lance moves easier to implement and faster (since Lances
//! slide along files).
//!    
use core::convert::TryInto;
use core::str::FromStr;

use crate::*;

macro_rules! define_square_with_docs {
    ($($square:ident),*) => {
        crate::helpers::simple_enum! {
            /// A square on a Shogi board.
            #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
            pub enum Square {
                $(
                    #[doc = concat!("The ", stringify!($square), " square.")]
                    $square
                ),*
            }
        }
    }
}

// Defining the squares in file-major order.
// Note: Changing this order will break BitBoard::has (and other functions).

define_square_with_docs! {
    A1, B1, C1, D1, E1, F1, G1, H1, I1,
    A2, B2, C2, D2, E2, F2, G2, H2, I2,
    A3, B3, C3, D3, E3, F3, G3, H3, I3,
    A4, B4, C4, D4, E4, F4, G4, H4, I4,
    A5, B5, C5, D5, E5, F5, G5, H5, I5,
    A6, B6, C6, D6, E6, F6, G6, H6, I6,
    A7, B7, C7, D7, E7, F7, G7, H7, I7,
    A8, B8, C8, D8, E8, F8, G8, H8, I8,
    A9, B9, C9, D9, E9, F9, G9, H9, I9
}

crate::helpers::simple_error! {
    /// The value was not a valid [`Square`].
    pub struct SquareParseError = "The value was not a valid Square.";
}

impl FromStr for Square {
    type Err = SquareParseError;

    // "1a" => File::One, Rank::A => Square::A1
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut chars = s.chars();
        let file = chars
            .next()
            .and_then(|c| c.try_into().ok())
            .ok_or(SquareParseError)?;
        let rank = chars
            .next()
            .and_then(|c| c.try_into().ok())
            .ok_or(SquareParseError)?;
        if chars.next().is_some() {
            return Err(SquareParseError);
        }
        Ok(Square::new(file, rank))
    }
}

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

// Directions  Diagrams     Square indices
// NW N NE     A9 ... A1    72 ...  0
//  W . E         ...          ...
// SW S SE     I9 ... I1    80 ...  9

// Diagonal mask for forward ("up") slashing diagonals (/).
const NEG_MASK: u128 = 0x100401004010040100401;

// Diagonal mask for backward ("down") slashing diagonals (\).
const POS_MASK: u128 = 0x1010101010101010100;

// BitBoards for the two main diagonals.
const NEGD: BitBoard = BitBoard::new(NEG_MASK);
const POSD: BitBoard = BitBoard::new(POS_MASK);

/// Down-slanting diagonals.
///
/// A square (file, rank) is on down-slanting diagonal `POS_DIA[file + rank]`.
/// The down-slanting diagonals are indexed as
/// ```text
///    8  7  6  5  4  3  2  1  0
///    9  8  7  6  5  4  3  2  1
///   10  9  8  7  6  5  4  3  2
///   11 10  9  8  7  6  5  4  3
///   12 11 10  9  8  7  6  5  4
///   13 12 11 10  9  8  7  6  5
///   13 12 11 10  9  8  7  6  5
///   14 13 12 11 10  9  8  7  6
///   15 14 13 12 11 10  9  8  7
///   16 15 14 13 12 11 10  9  8
/// ```
///
/// # Examples
/// ```
/// use haitaka_types::*;
/// assert_eq!(POS_DIA[8], bitboard! {
///     X . . . . . . . .
///     . X . . . . . . .
///     . . X . . . . . .
///     . . . X . . . . .
///     . . . . X . . . .
///     . . . . . X . . .
///     . . . . . . X . .
///     . . . . . . . X .
///     . . . . . . . . X
/// });
/// assert_eq!(POS_DIA[2], bitboard! {
///     . . . . . . X . .
///     . . . . . . . X .
///     . . . . . . . . X
///     . . . . . . . . .
///     . . . . . . . . .
///     . . . . . . . . .
///     . . . . . . . . .
///     . . . . . . . . .
///     . . . . . . . . .
/// });
/// assert_eq!(POS_DIA[16], bitboard! {
///     . . . . . . . . .
///     . . . . . . . . .
///     . . . . . . . . .
///     . . . . . . . . .
///     . . . . . . . . .
///     . . . . . . . . .
///     . . . . . . . . .
///     . . . . . . . . .
///     X . . . . . . . .
/// });
/// ```
pub const POS_DIA: [BitBoard; 17] = [
    POSD.shr(8),
    POSD.shr(7),
    POSD.shr(6),
    POSD.shr(5),
    POSD.shr(4),
    POSD.shr(3),
    POSD.shr(2),
    POSD.shr(1),
    POSD,
    POSD.shl(1),
    POSD.shl(2),
    POSD.shl(3),
    POSD.shl(4),
    POSD.shl(5),
    POSD.shl(6),
    POSD.shl(7),
    POSD.shl(8),
];

/// Up-slanting diagonals.
///
/// A square (file, rank) is on up-slanting diagonal NEG_DIA[8 + rank - file].
/// The upslanting diagonals are indexed as
/// ```text
///     8  7  6  5  4  3  2  1  0 |  
///     --------------------------+---
///     0  1  2  3  4  5  6  7  8 | 0  
///     1  2  3  4  5  6  7  8  9 | 1
///     2  3  4  5  6  7  8  9 10 | 2
///     3  4  5  6  7  8  9 10 11 | 3
///     4  5  6  7  8  9 10 11 12 | 4
///     5  6  7  8  9 10 11 12 13 | 5
///     6  7  8  9 10 11 12 13 14 | 6
///     7  8  9 10 11 12 13 14 15 | 7
///     8  9 10 11 12 13 14 15 16 | 8
/// ```
///
/// # Examples
/// ```
/// use haitaka_types::*;
/// assert_eq!(NEG_DIA[8], bitboard! {
///     . . . . . . . . X
///     . . . . . . . X .
///     . . . . . . X . .
///     . . . . . X . . .
///     . . . . X . . . .
///     . . . X . . . . .
///     . . X . . . . . .
///     . X . . . . . . .
///     X . . . . . . . .
/// });
/// assert_eq!(NEG_DIA[14], bitboard! {
///     . . . . . . . . .
///     . . . . . . . . .
///     . . . . . . . . .
///     . . . . . . . . .
///     . . . . . . . . .
///     . . . . . . . . .
///     . . . . . . . . X
///     . . . . . . . X .
///     . . . . . . X . .
/// });
/// assert_eq!(NEG_DIA[0], bitboard! {
///     X . . . . . . . .
///     . . . . . . . . .
///     . . . . . . . . .
///     . . . . . . . . .     
///     . . . . . . . . .
///     . . . . . . . . .
///     . . . . . . . . .
///     . . . . . . . . .
///     . . . . . . . . .
/// });
/// ```
pub const NEG_DIA: [BitBoard; 17] = [
    NEGD.shr(8),
    NEGD.shr(7),
    NEGD.shr(6),
    NEGD.shr(5),
    NEGD.shr(4),
    NEGD.shr(3),
    NEGD.shr(2),
    NEGD.shr(1),
    NEGD,
    NEGD.shl(1),
    NEGD.shl(2),
    NEGD.shl(3),
    NEGD.shl(4),
    NEGD.shl(5),
    NEGD.shl(6),
    NEGD.shl(7),
    NEGD.shl(8),
];

impl Square {
    /// Make a square from a file and a rank.
    /// # Examples
    /// ```
    /// # use haitaka_types::*;
    /// assert_eq!(Square::new(File::One, Rank::A), Square::A1);
    /// assert_eq!(Square::new(File::Two, Rank::B), Square::B2);
    /// ```
    #[inline(always)]
    pub const fn new(file: File, rank: Rank) -> Self {
        Self::index_const((file as usize) * 9 + (rank as usize))
    }

    /// Get the file of this square.
    /// # Examples
    /// ```
    /// # use haitaka_types::*;
    /// assert_eq!(Square::A1.file(), File::One);
    /// assert_eq!(Square::B2.file(), File::Two);
    /// ```
    #[inline(always)]
    pub const fn file(self) -> File {
        File::index_const(self as usize / 9)
    }

    /// Get the rank of this square.
    /// # Examples
    /// ```
    /// # use haitaka_types::*;
    /// assert_eq!(Square::A1.rank(), Rank::A);
    /// assert_eq!(Square::B2.rank(), Rank::B);
    /// ```
    #[inline(always)]
    pub const fn rank(self) -> Rank {
        Rank::index_const(self as usize % 9)
    }

    /// Get a bitboard with this square set.
    /// ```
    /// # use haitaka_types::*;
    /// assert_eq!(Square::G8.bitboard(), bitboard! {
    ///     . . . . . . . . .
    ///     . . . . . . . . .
    ///     . . . . . . . . .
    ///     . . . . . . . . .
    ///     . . . . . . . . .
    ///     . . . . . . . . .
    ///     . X . . . . . . .
    ///     . . . . . . . . .
    ///     . . . . . . . . .
    /// });
    /// ```
    #[inline(always)]
    pub const fn bitboard(self) -> BitBoard {
        BitBoard(1 << self as usize)
    }

    /// Get the bitboard with the "up" (forward-slanting "/") diagonal for this square.
    ///
    /// # Examples
    /// ```
    /// use haitaka_types::*;
    /// assert_eq!(Square::E5.up_diagonal(), bitboard! {
    ///     . . . . . . . . X
    ///     . . . . . . . X .
    ///     . . . . . . X . .
    ///     . . . . . X . . .
    ///     . . . . X . . . .
    ///     . . . X . . . . .
    ///     . . X . . . . . .
    ///     . X . . . . . . .
    ///     X . . . . . . . .
    /// });
    /// assert_eq!(Square::G3.up_diagonal(), bitboard! {
    ///     . . . . . . . . .
    ///     . . . . . . . . .
    ///     . . . . . . . . .
    ///     . . . . . . . . .
    ///     . . . . . . . . X
    ///     . . . . . . . X .
    ///     . . . . . . X . .
    ///     . . . . . X . . .
    ///     . . . . X . . . .
    /// });
    /// assert_eq!(Square::A1.up_diagonal(), Square::I9.up_diagonal());
    /// assert_eq!(Square::A9.up_diagonal(), Square::A9.bitboard());
    /// assert_eq!(Square::I1.up_diagonal(), Square::I1.bitboard());
    /// ```
    #[inline(always)]
    pub const fn up_diagonal(self) -> BitBoard {
        let rank = self as usize % 9;
        let file = self as usize / 9;
        NEG_DIA[8 + rank - file]
    }

    /// Get the bitboard with the "down" (backwards-slanting "\") diagonal for this square.
    ///
    /// # Examples
    /// ```
    /// use haitaka_types::*;
    /// assert_eq!(Square::E5.down_diagonal(), bitboard! {
    ///     X . . . . . . . .
    ///     . X . . . . . . .
    ///     . . X . . . . . .
    ///     . . . X . . . . .
    ///     . . . . X . . . .
    ///     . . . . . X . . .
    ///     . . . . . . X . .
    ///     . . . . . . . X .
    ///     . . . . . . . . X
    /// });
    /// assert_eq!(Square::A6.down_diagonal(), bitboard! {
    ///     . . . X . . . . .
    ///     . . . . X . . . .
    ///     . . . . . X . . .
    ///     . . . . . . X . .
    ///     . . . . . . . X .
    ///     . . . . . . . . X
    ///     . . . . . . . . .
    ///     . . . . . . . . .
    ///     . . . . . . . . .
    /// });    
    /// assert_eq!(Square::A9.down_diagonal(), Square::I1.down_diagonal());
    /// assert_eq!(Square::A1.down_diagonal(), Square::A1.bitboard());
    /// assert_eq!(Square::I9.down_diagonal(), Square::I9.bitboard());
    /// ```
    #[inline(always)]
    pub const fn down_diagonal(self) -> BitBoard {
        let rank = self as usize % 9;
        let file = self as usize / 9;
        POS_DIA[file + rank]
    }

    /// Add a file and rank offset to the given square.
    ///
    /// Since square A1 is the topmost-rightmost square,
    /// positive offsets correspond to a down- and leftwards
    /// direction. Note that A1 means file 1 and rank A.
    ///
    /// # Panics
    /// Panic if the offset would put the square out of bounds.
    /// See [`Square::try_offset`] for a non-panicking variant.
    ///
    /// # Examples
    /// ```
    /// # use haitaka_types::*;
    /// assert_eq!(Square::A1.offset(2, 1), Square::B3);
    /// assert_eq!(Square::B3.offset(-2, -1), Square::A1);  
    /// assert_eq!(Square::H1.offset(0, 1), Square::I1);
    /// assert_eq!(Square::H9.offset(0, 1), Square::I9);
    /// ```
    pub const fn offset(self, file_offset: i8, rank_offset: i8) -> Square {
        if let Some(sq) = self.try_offset(file_offset, rank_offset) {
            sq
        } else {
            panic!("Offset puts square out of bounds");
        }
    }

    /// Non-panicking version of [`Square::offset`].
    ///
    /// # Errors
    /// See [`Square::offset`]'s panics.
    ///
    /// # Examples
    /// ```
    /// use haitaka_types::*;
    /// assert_eq!(Square::A1.try_offset(1, 1), Some(Square::B2));
    /// assert_eq!(Square::E5.try_offset(-1, -1), Some(Square::D4));
    /// assert_eq!(Square::H9.try_offset(0, -1), Some(Square::G9));
    /// assert_eq!(Square::C3.try_offset(2, 0), Some(Square::C5));
    /// assert_eq!(Square::A1.try_offset(-1, 0), None); // File out of bounds
    /// assert_eq!(Square::A1.try_offset(0, -1), None); // Rank out of bounds
    /// assert_eq!(Square::I9.try_offset(1, 0), None); // File out of bounds
    /// assert_eq!(Square::I9.try_offset(0, 1), None); // Rank out of bounds
    /// ```
    #[inline(always)]
    pub const fn try_offset(self, file_offset: i8, rank_offset: i8) -> Option<Square> {
        let file_index = self.file() as i8 + file_offset;
        let rank_index = self.rank() as i8 + rank_offset;

        if file_index < 0 || file_index >= 9 || rank_index < 0 || rank_index >= 9 {
            return None;
        }
        Some(Square::new(
            File::index_const(file_index as usize),
            Rank::index_const(rank_index as usize),
        ))
    }

    /// Flip the file of this square.
    ///
    /// Mirrors square in the central File::Five.
    ///
    /// # Examples
    /// ```
    /// # use haitaka_types::*;
    /// assert_eq!(Square::A1.flip_file(), Square::A9);
    /// ```
    #[inline(always)]
    pub const fn flip_file(self) -> Self {
        Self::new(self.file().flip(), self.rank())
    }

    /// Flip the rank of this square.
    ///
    /// Mirrors square in the central Rank::E.
    ///
    /// # Examples
    /// ```
    /// # use haitaka_types::*;
    /// assert_eq!(Square::A1.flip_rank(), Square::I1);
    /// ```
    #[inline(always)]
    pub const fn flip_rank(self) -> Self {
        Self::new(self.file(), self.rank().flip())
    }

    /// Flip both rank and file of this square.
    ///
    /// This rotates the square around the center square E5.
    ///
    /// # Examples
    /// ```
    /// # use haitaka_types::*;
    /// assert_eq!(Square::A1.flip(), Square::I9);
    /// assert_eq!(Square::E5.flip(), Square::E5);
    /// ```
    #[inline(always)]
    pub const fn flip(self) -> Self {
        Self::new(self.file().flip(), self.rank().flip())
    }

    /// Get a square relative to some color.
    ///
    /// This effectively _rotates_ the board if viewed from Gote's/White's
    /// perspective. It flips both the rank and the file of the square.
    ///
    /// Note that the initial Shogi position has rotational symmetry.
    /// This differs from the initial position in International Chess which has
    /// mirror symmetry (flipping the ranks).
    ///   
    /// # Examples
    /// ```
    /// # use haitaka_types::*;
    /// assert_eq!(Square::A1.relative_to(Color::White), Square::I9);
    /// assert_eq!(Square::E5.relative_to(Color::White), Square::E5);
    /// assert_eq!(Square::A1.relative_to(Color::Black), Square::A1);
    /// ```
    #[inline(always)]
    pub const fn relative_to(self, color: Color) -> Self {
        if let Color::Black = color {
            self
        } else {
            Self::new(self.file().flip(), self.rank().flip())
        }
    }
}