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
use crate::Color;
use std::fmt;
use std::iter;

const ASCII_1: u8 = b'1';
const ASCII_9: u8 = b'9';
const ASCII_LOWER_A: u8 = b'a';
const ASCII_LOWER_I: u8 = b'i';

/// Represents a position of each cell in the game board.
///
/// # Examples
///
/// ```
/// use shogi::Square;
///
/// let sq = Square::new(4, 4).unwrap();
/// assert_eq!("5e", sq.to_string());
/// ```
///
/// `Square` can be created by parsing a SFEN formatted string as well.
///
/// ```
/// use shogi::Square;
///
/// let sq = Square::from_sfen("5e").unwrap();
/// assert_eq!(4, sq.file());
/// assert_eq!(4, sq.rank());
/// ```
#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
pub struct Square {
    inner: u8,
}

impl Square {
    /// Creates a new instance of `Square`.
    ///
    /// `file` can take a value from 0('1') to 8('9'), while `rank` is from 0('a') to 9('i').
    pub fn new(file: u8, rank: u8) -> Option<Square> {
        if file > 8 || rank > 8 {
            return None;
        }

        Some(Square {
            inner: file * 9 + rank,
        })
    }

    /// Creates a new instance of `Square` from SFEN formatted string.
    pub fn from_sfen(s: &str) -> Option<Square> {
        let bytes: &[u8] = s.as_bytes();

        if bytes.len() != 2
            || bytes[0] < ASCII_1
            || bytes[0] > ASCII_9
            || bytes[1] < ASCII_LOWER_A
            || bytes[1] > ASCII_LOWER_I
        {
            return None;
        }

        let file = bytes[0] - ASCII_1;
        let rank = bytes[1] - ASCII_LOWER_A;

        debug_assert!(
            file < 9 && rank < 9,
            "{} parsed as (file: {}, rank: {})",
            s,
            file,
            rank
        );

        Some(Square {
            inner: file * 9 + rank,
        })
    }

    /// Creates a new instance of `Square` with the given index value.
    pub fn from_index(index: u8) -> Option<Square> {
        if index >= 81 {
            return None;
        }

        Some(Square { inner: index })
    }

    /// Returns an iterator of all variants.
    pub fn iter() -> SquareIter {
        SquareIter { current: 0 }
    }

    /// Returns a file of the square.
    pub fn file(self) -> u8 {
        self.inner / 9
    }

    /// Returns a rank of the square.
    pub fn rank(self) -> u8 {
        self.inner % 9
    }

    /// Returns a new `Square` instance by moving the file and the rank values.
    ///
    /// # Examples
    ///
    /// ```
    /// use shogi::square::consts::*;
    ///
    /// let sq = SQ_2B;
    /// let shifted = sq.shift(2, 3).unwrap();
    ///
    /// assert_eq!(3, shifted.file());
    /// assert_eq!(4, shifted.rank());
    /// ```
    pub fn shift(self, df: i8, dr: i8) -> Option<Square> {
        let f = self.file() as i8 + df;
        let r = self.rank() as i8 + dr;

        if !(0..9).contains(&f) || !(0..9).contains(&r) {
            return None;
        }

        Some(Square {
            inner: (f * 9 + r) as u8,
        })
    }

    /// Returns a relative rank as if the specified color is black.
    ///
    /// # Examples
    ///
    /// ```
    /// use shogi::Color;
    /// use shogi::square::consts::*;
    ///
    /// let sq = SQ_1G;
    ///
    /// assert_eq!(6, sq.relative_rank(Color::Black));
    /// assert_eq!(2, sq.relative_rank(Color::White));
    /// ```
    pub fn relative_rank(self, c: Color) -> u8 {
        if c == Color::Black {
            self.rank()
        } else {
            8 - self.rank()
        }
    }

    /// Tests if the square is in a promotion zone.
    pub fn in_promotion_zone(self, c: Color) -> bool {
        self.relative_rank(c) < 3
    }

    /// Converts the instance into the unique number for array indexing purpose.
    #[inline(always)]
    pub fn index(self) -> usize {
        self.inner as usize
    }
}

impl fmt::Display for Square {
    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        debug_assert!(
            self.file() < 9 && self.rank() < 9,
            "trying to stringify an invalid square: {:?}",
            self
        );
        write!(
            f,
            "{}{}",
            (self.file() + ASCII_1) as char,
            (self.rank() + ASCII_LOWER_A) as char
        )
    }
}

pub mod consts {
    use super::Square;

    macro_rules! make_square {
        {0, $t:ident $($ts:ident)+} => {
            pub const $t: Square = Square { inner: 0 };
            make_square!{1, $($ts)*}
        };
        {$n:expr, $t:ident $($ts:ident)+} => {
            pub const $t: Square = Square { inner: $n };
            make_square!{($n + 1), $($ts)*}
        };
        {$n:expr, $t:ident} => {
            pub const $t: Square = Square { inner: $n };
        };
    }

    make_square! {0, SQ_1A SQ_1B SQ_1C SQ_1D SQ_1E SQ_1F SQ_1G SQ_1H SQ_1I
    SQ_2A SQ_2B SQ_2C SQ_2D SQ_2E SQ_2F SQ_2G SQ_2H SQ_2I
    SQ_3A SQ_3B SQ_3C SQ_3D SQ_3E SQ_3F SQ_3G SQ_3H SQ_3I
    SQ_4A SQ_4B SQ_4C SQ_4D SQ_4E SQ_4F SQ_4G SQ_4H SQ_4I
    SQ_5A SQ_5B SQ_5C SQ_5D SQ_5E SQ_5F SQ_5G SQ_5H SQ_5I
    SQ_6A SQ_6B SQ_6C SQ_6D SQ_6E SQ_6F SQ_6G SQ_6H SQ_6I
    SQ_7A SQ_7B SQ_7C SQ_7D SQ_7E SQ_7F SQ_7G SQ_7H SQ_7I
    SQ_8A SQ_8B SQ_8C SQ_8D SQ_8E SQ_8F SQ_8G SQ_8H SQ_8I
    SQ_9A SQ_9B SQ_9C SQ_9D SQ_9E SQ_9F SQ_9G SQ_9H SQ_9I}
}

/// This struct is created by the [`iter`] method on [`Square`].
///
/// [`iter`]: ./struct.Square.html#method.iter
/// [`Square`]: struct.Square.html
pub struct SquareIter {
    current: u8,
}

impl iter::Iterator for SquareIter {
    type Item = Square;

    fn next(&mut self) -> Option<Self::Item> {
        let cur = self.current;

        if cur >= 81 {
            return None;
        }

        self.current += 1;

        Some(Square { inner: cur })
    }
}

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

    #[test]
    fn new() {
        for file in 0..9 {
            for rank in 0..9 {
                let sq = Square::new(file, rank).unwrap();
                assert_eq!(file, sq.file());
                assert_eq!(rank, sq.rank());
            }
        }

        assert_eq!(None, Square::new(10, 0));
        assert_eq!(None, Square::new(0, 10));
        assert_eq!(None, Square::new(10, 10));
    }

    #[test]
    fn from_sfen() {
        let ok_cases = [
            ("9a", 8, 0),
            ("1a", 0, 0),
            ("5e", 4, 4),
            ("9i", 8, 8),
            ("1i", 0, 8),
        ];
        let ng_cases = ["", "9j", "_a", "a9", "9 ", " a", "9", "foo"];

        for case in ok_cases.iter() {
            let sq = Square::from_sfen(case.0);
            assert!(sq.is_some());
            assert_eq!(case.1, sq.unwrap().file());
            assert_eq!(case.2, sq.unwrap().rank());
        }

        for case in ng_cases.iter() {
            assert!(
                Square::from_sfen(case).is_none(),
                "{} should cause an error",
                case
            );
        }
    }

    #[test]
    fn from_index() {
        for i in 0..81 {
            assert!(Square::from_index(i).is_some());
        }

        assert!(Square::from_index(82).is_none());
    }

    #[test]
    fn to_sfen() {
        let cases = [
            ("9a", 8, 0),
            ("1a", 0, 0),
            ("5e", 4, 4),
            ("9i", 8, 8),
            ("1i", 0, 8),
        ];

        for case in cases.iter() {
            let sq = Square::new(case.1, case.2).unwrap();
            assert_eq!(case.0, sq.to_string());
        }
    }

    #[test]
    fn shift() {
        let sq = consts::SQ_5E;

        let ok_cases = [
            (-4, -4, 0, 0),
            (-4, 0, 0, 4),
            (0, -4, 4, 0),
            (0, 0, 4, 4),
            (4, 0, 8, 4),
            (0, 4, 4, 8),
            (4, 4, 8, 8),
        ];

        let ng_cases = [(-5, -4), (-4, -5), (5, 0), (0, 5)];

        for case in ok_cases.iter() {
            let shifted = sq.shift(case.0, case.1).unwrap();
            assert_eq!(case.2, shifted.file());
            assert_eq!(case.3, shifted.rank());
        }

        for case in ng_cases.iter() {
            assert!(sq.shift(case.0, case.1).is_none());
        }
    }

    #[test]
    fn relative_rank() {
        let cases = [
            (0, 0, 0, 8),
            (0, 1, 1, 7),
            (0, 2, 2, 6),
            (0, 3, 3, 5),
            (0, 4, 4, 4),
            (0, 5, 5, 3),
            (0, 6, 6, 2),
            (0, 7, 7, 1),
            (0, 8, 8, 0),
        ];

        for case in cases.iter() {
            let sq = Square::new(case.0, case.1).unwrap();
            assert_eq!(case.2, sq.relative_rank(Color::Black));
            assert_eq!(case.3, sq.relative_rank(Color::White));
        }
    }

    #[test]
    fn in_promotion_zone() {
        let cases = [
            (0, 0, true, false),
            (0, 1, true, false),
            (0, 2, true, false),
            (0, 3, false, false),
            (0, 4, false, false),
            (0, 5, false, false),
            (0, 6, false, true),
            (0, 7, false, true),
            (0, 8, false, true),
        ];

        for case in cases.iter() {
            let sq = Square::new(case.0, case.1).unwrap();
            assert_eq!(case.2, sq.in_promotion_zone(Color::Black));
            assert_eq!(case.3, sq.in_promotion_zone(Color::White));
        }
    }

    #[test]
    fn consts() {
        for (i, sq) in Square::iter().enumerate() {
            assert_eq!((i / 9) as u8, sq.file());
            assert_eq!((i % 9) as u8, sq.rank());
        }
    }
}