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
//!Implements `Bitboard` - chess position representation. Basically it is just a wrapper around
//!`u64`, where each bit corresponds to chess square.

use std::fmt::Display;

use crate::{constants::Direction, File, Rank, Square};

/// Represents particular position on a chess board.
/// It is used in variety of places, but the main purpose of bitboards is to represent position
/// for pieces of each color.
/// This struct implements all bitwise operations, so you can use it in operations with `u64`
/// numbers.
/// Example how to get all pawns in the position:
/// ```no_run
/// let white_pawns = sjakk::bitboard::Bitboard(0xFF_u64 << 8);
/// let black_pawns = white_pawns << 40;
/// let all_pawns = white_pawns | black_pawns;
/// assert_eq!(all_pawns, 0b0000000011111111000000000000000000000000000000001111111100000000);
/// ```
///
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default)]
pub struct Bitboard(pub u64);

impl std::ops::BitOr for Bitboard {
    type Output = Self;
    fn bitor(self, rhs: Self) -> Self::Output {
        Self(self.0 | rhs.0)
    }
}

impl std::ops::BitOr<&Bitboard> for &Bitboard {
    type Output = Bitboard;
    fn bitor(self, rhs: &Bitboard) -> Bitboard {
        Bitboard(self.0 | rhs.0)
    }
}

impl std::ops::BitOr<u64> for Bitboard {
    type Output = Self;
    fn bitor(self, rhs: u64) -> Self::Output {
        Self(self.0 | rhs)
    }
}

impl std::ops::BitAnd for Bitboard {
    type Output = Self;
    fn bitand(self, rhs: Self) -> Self::Output {
        Self(self.0 & rhs.0)
    }
}

impl std::ops::BitAnd for &Bitboard {
    type Output = Bitboard;
    fn bitand(self, rhs: &Bitboard) -> Bitboard {
        Bitboard(self.0 & rhs.0)
    }
}

impl std::ops::BitAnd<u64> for Bitboard {
    type Output = Self;
    fn bitand(self, rhs: u64) -> Self::Output {
        Self(self.0 & rhs)
    }
}

impl std::ops::BitXor for Bitboard {
    type Output = Self;
    fn bitxor(self, rhs: Self) -> Self::Output {
        Self(self.0 ^ rhs.0)
    }
}

impl std::ops::BitXor for &Bitboard {
    type Output = Bitboard;
    fn bitxor(self, rhs: &Bitboard) -> Bitboard {
        Bitboard(self.0 ^ rhs.0)
    }
}

impl std::ops::BitXor<u64> for Bitboard {
    type Output = Self;
    fn bitxor(self, rhs: u64) -> Self::Output {
        Self(self.0 ^ rhs)
    }
}

impl std::ops::BitOrAssign for Bitboard {
    fn bitor_assign(&mut self, rhs: Self) {
        self.0 |= rhs.0
    }
}

impl std::ops::BitOrAssign<u64> for Bitboard {
    fn bitor_assign(&mut self, rhs: u64) {
        self.0 |= rhs
    }
}

impl std::ops::BitOrAssign<&Bitboard> for Bitboard {
    fn bitor_assign(&mut self, rhs: &Bitboard) {
        self.0 |= rhs.0
    }
}

impl std::ops::BitAndAssign for Bitboard {
    fn bitand_assign(&mut self, rhs: Self) {
        self.0 &= rhs.0
    }
}

impl std::ops::BitAndAssign<u64> for Bitboard {
    fn bitand_assign(&mut self, rhs: u64) {
        self.0 &= rhs
    }
}

impl std::ops::BitXorAssign for Bitboard {
    fn bitxor_assign(&mut self, rhs: Self) {
        self.0 ^= rhs.0
    }
}

impl std::ops::BitXorAssign<u64> for Bitboard {
    fn bitxor_assign(&mut self, rhs: u64) {
        self.0 ^= rhs
    }
}

impl std::ops::Not for Bitboard {
    type Output = Self;
    fn not(self) -> Self::Output {
        Self(!self.0)
    }
}

impl std::ops::Shl for Bitboard {
    type Output = Self;
    fn shl(self, rhs: Self) -> Self::Output {
        Self(self.0 << rhs.0)
    }
}

impl std::ops::Shl<u64> for Bitboard {
    type Output = Self;
    fn shl(self, rhs: u64) -> Self::Output {
        Self(self.0 << rhs)
    }
}

impl std::ops::Shr for Bitboard {
    type Output = Self;
    fn shr(self, rhs: Self) -> Self::Output {
        Self(self.0 >> rhs.0)
    }
}

impl std::ops::Shr<u64> for Bitboard {
    type Output = Self;
    fn shr(self, rhs: u64) -> Self::Output {
        Self(self.0 >> rhs)
    }
}
impl std::ops::ShlAssign for Bitboard {
    fn shl_assign(&mut self, rhs: Self) {
        self.0 <<= rhs.0
    }
}

impl std::ops::ShlAssign<u64> for Bitboard {
    fn shl_assign(&mut self, rhs: u64) {
        self.0 <<= rhs
    }
}

impl std::ops::ShrAssign for Bitboard {
    fn shr_assign(&mut self, rhs: Self) {
        self.0 >>= rhs.0
    }
}

impl std::ops::ShrAssign<u64> for Bitboard {
    fn shr_assign(&mut self, rhs: u64) {
        self.0 >>= rhs
    }
}

impl PartialEq<u64> for Bitboard {
    fn eq(&self, other: &u64) -> bool {
        self.0.eq(other)
    }
}

impl From<u64> for Bitboard {
    fn from(value: u64) -> Self {
        Self(value)
    }
}

impl std::ops::BitOr<Bitboard> for u64 {
    type Output = u64;
    fn bitor(self, rhs: Bitboard) -> Self::Output {
        self | rhs.0
    }
}

impl std::ops::BitAnd<Bitboard> for u64 {
    type Output = u64;
    fn bitand(self, rhs: Bitboard) -> Self::Output {
        self & rhs.0
    }
}

impl std::ops::BitXor<Bitboard> for u64 {
    type Output = u64;
    fn bitxor(self, rhs: Bitboard) -> Self::Output {
        self ^ rhs.0
    }
}

impl std::ops::BitOrAssign<Bitboard> for u64 {
    fn bitor_assign(&mut self, rhs: Bitboard) {
        *self |= rhs.0;
    }
}

impl std::ops::BitAndAssign<Bitboard> for u64 {
    fn bitand_assign(&mut self, rhs: Bitboard) {
        *self &= rhs.0;
    }
}

impl std::ops::BitXorAssign<Bitboard> for u64 {
    fn bitxor_assign(&mut self, rhs: Bitboard) {
        *self ^= rhs.0;
    }
}

impl std::ops::Mul<Bitboard> for Bitboard {
    type Output = Self;
    fn mul(self, rhs: Bitboard) -> Self::Output {
        Bitboard(self.0 * rhs.0)
    }
}

impl Display for Bitboard {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        writeln!(f)?;
        for row in (0..8).rev() {
            write!(f, "{}", row + 1)?;
            for i in 0..8 {
                write!(f, " {} ", self.0 >> (8 * row + i) & 1)?;
            }

            writeln!(f)?;
        }
        write!(f, "  A  B  C  D  E  F  G  H ")?;
        writeln!(f)?;
        Ok(())
    }
}

impl Bitboard {
    /// Creates bitboard with `1` on the given square, with rest of the board filled with `0`.
    ///
    /// ```
    /// use sjakk::Bitboard;
    /// let bb = Bitboard::from_square_number(10);
    /// assert_eq!(bb.0.trailing_zeros(), 10);
    /// assert_eq!(bb.0.leading_zeros(), 53);
    /// ```
    pub fn from_square_number(square: u8) -> Self {
        Self(1_u64 << square)
    }

    pub const fn from_square(sq: Square) -> Bitboard {
        Bitboard(1u64 << sq.0)
    }

    /// Creates empty board (filled with zeros).
    /// ```
    /// use sjakk::Bitboard;
    /// let bb = Bitboard::empty();
    /// assert_eq!(bb, 0);
    /// ```
    pub fn empty() -> Self {
        Self(0)
    }

    /// Creates board, filled with ones.
    ///
    /// ```
    /// use sjakk::Bitboard;
    /// let bb = Bitboard::universe();
    /// assert_eq!(bb, u64::MAX);
    /// ```
    pub fn universe() -> Self {
        Self(u64::MAX)
    }

    /// Move bitboard by 1 bit in [`Direction`].
    /// Use only with single bitsets.
    #[inline]
    pub fn one_step_by_direction(&self, direction: Direction) -> Bitboard {
        assert!(self.0.count_ones() == 1); // is single bitset
        let mask_a_file = 0xfefefefefefefefe_u64;
        let mask_h_file = 0x7f7f7f7f7f7f7f7f_u64;

        match direction {
            Direction::North => Bitboard(self.0 << 8),
            Direction::NorthEast => Bitboard((self.0 << 9) & mask_a_file),
            Direction::East => Bitboard((self.0 << 1) & mask_a_file),
            Direction::SouthEast => Bitboard((self.0 >> 7) & mask_a_file),
            Direction::South => Bitboard(self.0 >> 8),
            Direction::SouthWest => Bitboard((self.0 >> 9) & mask_h_file),
            Direction::West => Bitboard((self.0 >> 1) & mask_h_file),
            Direction::NorthWest => Bitboard((self.0 << 7) & mask_h_file),
        }
    }

    /// Returns true if this [`Bitboard`] is not filled with zeros.
    pub fn is_set(&self) -> bool {
        self.0 != 0
    }

    /// Returns the rank of this [`Bitboard`].
    pub fn rank(&self) -> Rank {
        assert!(self.0.count_ones() == 1); // is single bitset
        todo!()
    }

    /// Returns the file of this [`Bitboard`].
    pub fn file(&self) -> File {
        assert!(self.0.count_ones() == 1); // is single bitset
        todo!()
    }

    /// Returns [`Square`], which is represented by least significant bit.
    /// Can be used to iterate over all pieces, which exists on particular [`Bitboard`]
    pub fn lsb_square(&self) -> Square {
        Square(self.0.trailing_zeros() as u8)
    }

    /// Calculate population count of current bitobard.
    #[inline]
    pub fn popcnt(&self) -> u32 {
        self.0.count_ones()
    }

    #[inline]
    pub fn to_size(&self, rightshift: u8) -> usize {
        (self.0 >> rightshift) as usize
    }
}

impl From<Square> for Bitboard {
    fn from(value: Square) -> Self {
        Self::from_square(value)
    }
}

impl Iterator for Bitboard {
    type Item = Square;

    #[inline]
    fn next(&mut self) -> Option<Square> {
        if self.0 == 0 {
            None
        } else {
            let lsb = self.lsb_square();
            self.0 &= self.0 - 1;
            Some(lsb)
        }
    }
}

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

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

    #[test]
    fn one_ste_by_direction() {
        let bb = Bitboard::from_square(Square(10));
        let bb = bb.one_step_by_direction(Direction::East);
        assert_eq!(bb.lsb_square(), Square(11));
        let bb = bb.one_step_by_direction(Direction::West);
        assert_eq!(bb.lsb_square(), Square(10));
        let bb = bb.one_step_by_direction(Direction::North);
        assert_eq!(bb.lsb_square(), Square(18));
        let bb = bb.one_step_by_direction(Direction::South);
        assert_eq!(bb.lsb_square(), Square(10));
        let bb = bb.one_step_by_direction(Direction::NorthEast);
        assert_eq!(bb.lsb_square(), Square(19));
        let bb = bb.one_step_by_direction(Direction::SouthWest);
        assert_eq!(bb.lsb_square(), Square(10));
        let bb = bb.one_step_by_direction(Direction::NorthWest);
        assert_eq!(bb.lsb_square(), Square(17));
        let bb = bb.one_step_by_direction(Direction::SouthEast);
        assert_eq!(bb.lsb_square(), Square(10));
    }

    #[test]
    fn iterate_over_squares() {
        let bb = Bitboard(0xFF);
        assert_eq!(bb.into_iter().count(), 8);
    }
}