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
use core::ops::{BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Not};

use crate::{c_compat::OptionSquare, Square};

/// A subset of all squares.
///
/// Because [`Bitboard`] is cheap to copy, it implements [`Copy`].
/// Its [`Default`] value is an empty instance.
#[repr(C)]
#[derive(Eq, PartialEq, Clone, Copy, Debug, Default)]
// Valid representation: self.0[1] >> 17 must be equal to 0.
pub struct Bitboard([u64; 2]);

impl Bitboard {
    /// Creates an empty [`Bitboard`].
    ///
    /// Examples:
    /// ```
    /// use shogi_core::Bitboard;
    /// let empty = Bitboard::empty();
    /// assert_eq!(empty.count(), 0);
    /// ```
    #[export_name = "Bitboard_empty"]
    pub extern "C" fn empty() -> Self {
        Self::default()
    }

    /// Creates a [`Bitboard`] with a single element.
    ///
    /// Examples:
    /// ```
    /// use shogi_core::{Bitboard, Square};
    /// let sq11 = Bitboard::single(Square::new(1, 1).unwrap());
    /// assert_eq!(sq11.count(), 1);
    /// ```
    #[export_name = "Bitboard_single"]
    pub extern "C" fn single(square: Square) -> Self {
        let index = square.index() - 1;
        let value = 1 << (index % 64);
        let inner = if index < 64 { [value, 0] } else { [0, value] };
        Self(inner)
    }

    /// Finds how many elements this [`Bitboard`] has.
    ///
    /// Examples:
    /// ```
    /// use shogi_core::{Bitboard, Square};
    /// let sq11 = Bitboard::single(Square::new(1, 1).unwrap());
    /// let sq55 = Bitboard::single(Square::new(5, 5).unwrap());
    /// assert_eq!((sq11 | sq55).count(), 2);
    /// ```
    #[export_name = "Bitboard_count"]
    pub extern "C" fn count(self) -> u8 {
        (self.0[0].count_ones() + self.0[1].count_ones()) as u8
    }

    /// Checks if `self` is an empty set.
    ///
    /// Equivalent to `self.count() == 0`, but this function is faster.
    ///
    /// Examples:
    /// ```
    /// use shogi_core::{Bitboard, Square};
    /// let sq11 = Bitboard::single(Square::new(1, 1).unwrap());
    /// let sq55 = Bitboard::single(Square::new(5, 5).unwrap());
    /// assert!(!(sq11 | sq55).is_empty());
    /// assert!(Bitboard::empty().is_empty());
    /// ```
    #[export_name = "Bitboard_is_empty"]
    pub extern "C" fn is_empty(self) -> bool {
        self.0 == [0; 2]
    }

    /// Finds if `self` as a subset contains a [`Square`].
    ///
    /// Examples:
    /// ```
    /// use shogi_core::{Bitboard, Square};
    /// let sq11 = Bitboard::single(Square::new(1, 1).unwrap());
    /// assert!(sq11.contains(Square::new(1, 1).unwrap()));
    /// assert!(!sq11.contains(Square::new(9, 9).unwrap()));
    /// ```
    #[export_name = "Bitboard_contains"]
    pub extern "C" fn contains(self, square: Square) -> bool {
        let index = square.index() - 1;
        let value = 1 << (index % 64);
        let overlap = if index < 64 {
            self.0[0] & value
        } else {
            self.0[1] & value
        };
        overlap != 0
    }

    /// Finds the flipped version of `self`.
    ///
    /// Examples:
    /// ```
    /// use shogi_core::{Bitboard, Square};
    /// let sq11 = Bitboard::single(Square::new(1, 1).unwrap());
    /// let sq99 = Bitboard::single(Square::new(9, 9).unwrap());
    /// assert_eq!(sq11.flip(), sq99);
    /// ```
    #[export_name = "Bitboard_flip"]
    pub extern "C" fn flip(self) -> Self {
        let fst_rev = (self.0[0] >> 17) | (self.0[1] << 47);
        let snd_rev = self.0[0] << 47;
        let returned = [fst_rev.reverse_bits(), snd_rev.reverse_bits()];
        Self(returned)
    }

    /// If `self` is not empty, find a [`Square`] in `self` and returns it, removing it from `self`.
    ///
    /// The returned value is unspecified. It is guaranteed that the returned [`Square`] is a member of `self`.
    ///
    /// Examples:
    /// ```
    /// use shogi_core::{Bitboard, Square};
    /// let sq11 = Bitboard::single(Square::new(1, 1).unwrap());
    /// let sq99 = Bitboard::single(Square::new(9, 9).unwrap());
    /// let mut bitboard = sq11 | sq99;
    /// assert!(bitboard.pop().is_some());
    /// assert!(bitboard.pop().is_some());
    /// assert!(bitboard.pop().is_none()); // after `pop`ping twice `bitboard` becomes empty
    /// assert!(bitboard.is_empty());
    /// ```
    pub fn pop(&mut self) -> Option<Square> {
        if self.0[0] != 0 {
            let index = self.0[0].trailing_zeros() + 1;
            // Safety: 1 <= index <= 64
            let square = unsafe { Square::from_u8_unchecked(index as u8) };
            debug_assert!(self.contains(square));
            *self ^= square;
            return Some(square);
        }
        if self.0[1] == 0 {
            return None;
        }
        let index = self.0[1].trailing_zeros() + 64 + 1;
        // Safety: `65 <= index <= 81` holds because `self.0[1] & 0x1ffff` is not zero
        let square = unsafe { Square::from_u8_unchecked(index as u8) };
        debug_assert!(self.contains(square));
        *self ^= square;
        Some(square)
    }

    /// C interface of [`Bitboard::pop`].
    #[no_mangle]
    pub extern "C" fn Bitboard_pop(&mut self) -> OptionSquare {
        self.pop().into()
    }
}

impl Iterator for Bitboard {
    type Item = Square;

    fn next(&mut self) -> Option<Self::Item> {
        self.pop()
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        (0, Some(81))
    }
}

macro_rules! define_bit_trait {
    (trait => $trait:ident, assign_trait => $assign_trait:ident, funname => $funname:ident, assign_funname => $assign_funname:ident, op => $op:tt,) => {
        impl $trait for Bitboard {
            type Output = Self;

            fn $funname(self, rhs: Self) -> Self::Output {
                Self([self.0[0] $op rhs.0[0], self.0[1] $op rhs.0[1]])
            }
        }
        // Supports reference types in favor of https://doc.rust-lang.org/std/ops/index.html
        impl $trait<&'_ Bitboard> for Bitboard {
            type Output = Bitboard;

            fn $funname(self, rhs: &Self) -> Self::Output {
                self $op *rhs
            }
        }
        impl $trait<Bitboard> for &'_ Bitboard {
            type Output = Bitboard;

            fn $funname(self, rhs: Bitboard) -> Self::Output {
                *self $op rhs
            }
        }
        impl $trait<&'_ Bitboard> for &'_ Bitboard {
            type Output = Bitboard;

            fn $funname(self, rhs: &Bitboard) -> Self::Output {
                *self $op *rhs
            }
        }
        impl $assign_trait for Bitboard {
            fn $assign_funname(&mut self, rhs: Self) {
                *self = *self $op rhs;
            }
        }
        impl $assign_trait<&'_ Bitboard> for Bitboard {
            fn $assign_funname(&mut self, rhs: &Self) {
                *self = *self $op *rhs;
            }
        }
        impl $assign_trait<Square> for Bitboard {
            fn $assign_funname(&mut self, rhs: Square) {
                *self = *self $op Bitboard::single(rhs);
            }
        }
        impl $assign_trait<&'_ Square> for Bitboard {
            fn $assign_funname(&mut self, rhs: &Square) {
                *self = *self $op Bitboard::single(*rhs);
            }
        }
    };
}

define_bit_trait!(
    trait => BitAnd, assign_trait => BitAndAssign,
    funname => bitand, assign_funname => bitand_assign,
    op => &,
);
define_bit_trait!(
    trait => BitOr, assign_trait => BitOrAssign,
    funname => bitor, assign_funname => bitor_assign,
    op => |,
);
define_bit_trait!(
    trait => BitXor, assign_trait => BitXorAssign,
    funname => bitxor, assign_funname => bitxor_assign,
    op => ^,
);

// `cbindgen` cannot find exported functions that are generated by macros.
// We need to define them manually for cbindgen to find and make bindings of them.
#[doc(hidden)]
impl Bitboard {
    #[no_mangle]
    pub extern "C" fn Bitboard_bitand(a: Bitboard, b: Bitboard) -> Bitboard {
        a & b
    }
    #[no_mangle]
    pub extern "C" fn Bitboard_bitand_assign(a: &mut Bitboard, b: Bitboard) {
        *a &= b;
    }

    #[no_mangle]
    pub extern "C" fn Bitboard_bitor(a: Bitboard, b: Bitboard) -> Bitboard {
        a | b
    }
    #[no_mangle]
    pub extern "C" fn Bitboard_bitor_assign(a: &mut Bitboard, b: Bitboard) {
        *a |= b;
    }

    #[no_mangle]
    pub extern "C" fn Bitboard_bitxor(a: Bitboard, b: Bitboard) -> Bitboard {
        a ^ b
    }
    #[no_mangle]
    pub extern "C" fn Bitboard_bitxor_assign(a: &mut Bitboard, b: Bitboard) {
        *a ^= b;
    }
}

impl Not for Bitboard {
    type Output = Self;

    /// Returns the complementary subset of `self`.
    ///
    /// You can create a subset consisting of the entire board with `!Bitboard::empty()`.
    ///
    /// Examples:
    /// ```
    /// use shogi_core::Bitboard;
    /// assert_eq!((!Bitboard::empty()).count(), 81);
    /// ```
    fn not(self) -> Self::Output {
        Self([!self.0[0], !self.0[1] & ((1 << 17) - 1)])
    }
}

impl Not for &'_ Bitboard {
    type Output = Bitboard;

    /// Returns the complementary subset of `self`.
    ///
    /// You can create a subset consisting of the entire board with `!Bitboard::empty()`.
    ///
    /// Examples:
    /// ```
    /// use shogi_core::Bitboard;
    /// assert_eq!((!&Bitboard::empty()).count(), 81);
    /// ```
    fn not(self) -> Self::Output {
        !*self
    }
}

/// C interface of `Bitboard::not`.
#[no_mangle]
pub extern "C" fn Bitboard_not(a: Bitboard) -> Bitboard {
    !a
}

impl_ord_for_single_field!(Bitboard);
impl_hash_for_single_field!(Bitboard);

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

    #[test]
    fn contains_works() {
        for file in 1..=9 {
            for rank in 1..=9 {
                let sq = Square::new(file, rank).unwrap();
                assert!(Bitboard::single(sq).contains(sq));
                for ofile in 1..=9 {
                    for orank in 1..=9 {
                        let osq = Square::new(ofile, orank).unwrap();
                        assert_eq!(Bitboard::single(sq).contains(osq), sq == osq);
                    }
                }
            }
        }
    }

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

    #[test]
    fn pop_works() {
        for square in Square::all() {
            let mut bitboard = Bitboard::single(square);
            assert_eq!(bitboard.pop(), Some(square));
            assert!(bitboard.is_empty());
        }
        for sq1 in Square::all() {
            for sq2 in Square::all() {
                if sq1 == sq2 {
                    continue;
                }
                let mut bitboard = Bitboard::single(sq1) | Bitboard::single(sq2);
                let result1 = bitboard.pop().unwrap();
                let result2 = bitboard.pop().unwrap();
                assert!((result1, result2) == (sq1, sq2) || (result1, result2) == (sq2, sq1));
                assert!(bitboard.is_empty());
            }
        }
    }
}