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
//! A structure for zobrist hashing.

use std::{fmt, hash, mem, ptr};

use core::castle::Rights;
use core::misc::Extract;
use core::piece::Role;
use core::square::{File, Square};

mod tables;

const NUM_PIECES:  usize = 6;
const NUM_SQUARES: usize = 64;
const PIECE_TOTAL: usize = NUM_SQUARES * NUM_PIECES;
const NUM_CASTLE:  usize = 0b1111 + 1;
const NUM_COLORS:  usize = 1;
const NUM_EP:      usize = 8;

const NUM_KEYS:  usize = PIECE_TOTAL + NUM_CASTLE + NUM_EP + NUM_COLORS;
const NUM_BYTES: usize = NUM_KEYS * 8;

type Keys = [u64; NUM_KEYS];

type Bytes = [u8; NUM_BYTES];

/// Static pseudorandomly-generated [`Zobrist`](struct.Zobrist.html) keys.
///
/// # Backward Compatibility
///
/// Hashes within this instance are **not** guaranteed to remain the same across
/// different crate versions. Changing hashes is a backward compatible change.
pub static KEYS: Zobrist = tables::STATIC;

/// Keys for [Zobrist hashing][wiki].
///
/// [wiki]: https://en.wikipedia.org/wiki/Zobrist_hashing
#[repr(C)]
pub struct Zobrist {
    /// Keys for each piece at each square.
    pub pieces: [[u64; NUM_SQUARES]; NUM_PIECES],
    /// Keys for each possible set of castle rights.
    pub castle: [u64; NUM_CASTLE],
    /// Keys for each en passant file.
    pub en_passant: [u64; NUM_EP],
    /// Key for the playing color.
    pub color: u64,
}

// Copy is not implemented due to large structure size
impl Clone for Zobrist {
    #[inline]
    fn clone(&self) -> Zobrist {
        // Should be efficient memcpy
        unsafe { ptr::read(self) }
    }
}

impl fmt::Debug for Zobrist {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        // `[u64; 64]` does not implement `fmt::Debug`
        let pieces: [&[u64]; 6] = [
            &self.pieces[0], &self.pieces[1], &self.pieces[2],
            &self.pieces[3], &self.pieces[4], &self.pieces[5],
        ];
        f.debug_struct("Zobrist")
            .field("pieces",     &pieces)
            .field("castle",     &self.castle)
            .field("en_passant", &self.en_passant)
            .field("color",      &self.color)
            .finish()
    }
}

impl hash::Hash for Zobrist {
    #[inline]
    fn hash<H: hash::Hasher>(&self, state: &mut H) {
        state.write(self.as_bytes());
    }
}

impl Default for Zobrist {
    /// Returns an instance with all keys zeroed out.
    #[inline]
    fn default() -> Zobrist {
        unsafe { mem::zeroed() }
    }
}

impl PartialEq for Zobrist {
    #[inline]
    fn eq(&self, other: &Zobrist) -> bool {
        self.as_slice() == other.as_slice()
    }
}

impl Eq for Zobrist {}

impl AsRef<[u64]> for Zobrist {
    #[inline]
    fn as_ref(&self) -> &[u64] { self.as_slice() }
}

impl AsMut<[u64]> for Zobrist {
    #[inline]
    fn as_mut(&mut self) -> &mut [u64] { self.as_mut_slice() }
}

impl AsRef<[u8]> for Zobrist {
    #[inline]
    fn as_ref(&self) -> &[u8] { self.as_bytes() }
}

impl AsMut<[u8]> for Zobrist {
    #[inline]
    fn as_mut(&mut self) -> &mut [u8] { self.as_bytes_mut() }
}

#[cfg(any(test, feature = "rand"))]
impl ::rand::Rand for Zobrist {
    fn rand<R: ::rand::Rng>(rng: &mut R) -> Zobrist {
        let mut zobrist = Zobrist::default();
        rng.fill_bytes(zobrist.as_bytes_mut());
        zobrist
    }
}

impl Zobrist {
    /// Returns the key for the piece role at a square.
    #[inline]
    pub fn piece(&self, role: Role, square: Square) -> u64 {
        self.pieces[role as usize][square as usize]
    }

    /// Returns the key for the castle rights.
    #[inline]
    pub fn castle(&self, rights: Rights) -> u64 {
        *rights.extract(&self.castle)
    }

    /// Returns the en passant key for the file.
    #[inline]
    pub fn en_passant(&self, file: File) -> u64 {
        self.en_passant[file as usize]
    }

    /// Clear all hashes by setting them to zero.
    #[inline]
    pub fn clear(&mut self) {
        unsafe { ::util::zero(self) }
    }

    /// Returns the zobrist keys as a contiguous slice.
    #[inline]
    pub fn as_slice(&self) -> &[u64] {
        let ptr = self as *const Zobrist as *const Keys;
        unsafe { &*ptr }
    }

    /// Returns the zobrist keys as a contiguous mutable slice.
    #[inline]
    pub fn as_mut_slice(&mut self) -> &mut [u64] {
        let ptr = self as *mut Zobrist as *mut Keys;
        unsafe { &mut *ptr }
    }

    /// Returns the zobrist keys as a contiguous slice of bytes.
    #[inline]
    pub fn as_bytes(&self) -> &[u8] {
        let ptr = self as *const Zobrist as *const Bytes;
        unsafe { &*ptr }
    }

    /// Returns the zobrist keys as a contiguous mutable slice of bytes.
    #[inline]
    pub fn as_bytes_mut(&mut self) -> &mut [u8] {
        let ptr = self as *mut Zobrist as *mut Bytes;
        unsafe { &mut *ptr }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use rand::{Rng, SeedableRng, ChaChaRng};

    assert_eq_size!(type_size; Zobrist, Keys, Bytes);

    #[test]
    fn keys_init() {
        const SEED: u32 = 0xDEAD_BEEF;

        let mut rng = ChaChaRng::from_seed(&[SEED]);
        let zobrist = rng.gen::<Zobrist>();
        assert_eq!(zobrist, KEYS);
    }
}