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
// This file is part of the shakmaty-syzygy library.
// Copyright (C) 2017-2018 Niklas Fiekas <niklas.fiekas@backscattering.de>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.

use std::ops::{Neg, Add, AddAssign, Sub, SubAssign};
use std::option::NoneError;
use std::io;

use arrayvec::ArrayVec;

use shakmaty::{Color, Piece, Outcome, Chess};

use material::Material;

/// A chess variant with Syzygy support.
pub trait Syzygy {
    /// Extension of WDL table files, e.g. `rtbw`.
    const TBW_EXTENSION: &'static str;
    /// Extension of DTZ table files, e.g. `rtbz`.
    const TBZ_EXTENSION: &'static str;
    /// Alternative extension of WDL table files.
    const PAWNLESS_TBW_EXTENSION: &'static str;
    /// Alternative extension of DTZ table files.
    const PAWNLESS_TBZ_EXTENSION: &'static str;

    /// Magic initial bytes of a WDL table.
    const WDL_MAGIC: [u8; 4];
    /// Magic initial bytes of a DTZ table.
    const DTZ_MAGIC: [u8; 4];
    /// Alternative WDL magic.
    const PAWNLESS_WDL_MAGIC: [u8; 4];
    /// Alternative DTZ magic.
    const PAWNLESS_DTZ_MAGIC: [u8; 4];

    /// Whether both players will have exactly one king unless the game
    /// is over.
    const ONE_KING: bool;
    /// Wether kings are allowed to be on adjacent squares.
    const CONNECTED_KINGS: bool;
    /// Whether captures are compulsory.
    const CAPTURES_COMPULSORY: bool;
}

impl Syzygy for Chess {
    const TBW_EXTENSION: &'static str = "rtbw";
    const TBZ_EXTENSION: &'static str = "rtbz";
    const PAWNLESS_TBW_EXTENSION: &'static str = "rtbw";
    const PAWNLESS_TBZ_EXTENSION: &'static str = "rtbz";

    const WDL_MAGIC: [u8; 4] = [0x71, 0xe8, 0x23, 0x5d];
    const DTZ_MAGIC: [u8; 4] = [0xd7, 0x66, 0x0c, 0xa5];
    const PAWNLESS_WDL_MAGIC: [u8; 4] = [0x71, 0xe8, 0x23, 0x5d];
    const PAWNLESS_DTZ_MAGIC: [u8; 4] = [0xd7, 0x66, 0x0c, 0xa5];

    const ONE_KING: bool = true;
    const CONNECTED_KINGS: bool = false;
    const CAPTURES_COMPULSORY: bool = false;
}

/// 5-valued evaluation of a position in the context of the 50-move drawing
/// rule.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
#[repr(i8)]
pub enum Wdl {
    /// Unconditional loss for the side to move.
    Loss = -2,
    /// Loss that can be saved by the 50-move rule.
    BlessedLoss = -1,
    /// Unconditional draw.
    Draw = 0,
    /// Win that can be frustrated by the 50-move rule.
    CursedWin = 1,
    /// Unconditional win.
    Win = 2,
}

impl Wdl {
    pub fn from_outcome(outcome: &Outcome, pov: Color) -> Wdl {
        match *outcome {
            Outcome::Draw => Wdl::Draw,
            Outcome::Decisive { winner } if winner == pov => Wdl::Win,
            _ => Wdl::Loss,
        }
    }
}

impl Neg for Wdl {
    type Output = Wdl;

    fn neg(self) -> Wdl {
        match self {
            Wdl::Loss => Wdl::Win,
            Wdl::BlessedLoss => Wdl::CursedWin,
            Wdl::Draw => Wdl::Draw,
            Wdl::CursedWin => Wdl::BlessedLoss,
            Wdl::Win => Wdl::Loss,
        }
    }
}

macro_rules! from_wdl_impl {
    ($($t:ty)+) => {
        $(impl From<Wdl> for $t {
            #[inline]
            fn from(wdl: Wdl) -> $t {
                wdl as $t
            }
        })+
    }
}

from_wdl_impl! { i8 i16 i32 i64 isize }

#[cfg(feature="serde-1")]
impl ::serde::Serialize for Wdl {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: ::serde::Serializer,
    {
        serializer.serialize_i8(i8::from(*self))
    }
}

#[cfg(feature="serde-1")]
impl<'de> ::serde::Deserialize<'de> for Wdl {
    fn deserialize<D>(deserializer: D) -> Result<Wdl, D::Error>
    where
        D: ::serde::Deserializer<'de>,
    {
        struct Visitor;

        impl<'de> ::serde::de::Visitor<'de> for Visitor {
            type Value = Wdl;

            fn expecting(&self, formatter: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
                formatter.write_str("wdl value (-2, -1, 0, 1, 2)")
            }

            fn visit_i64<E>(self, value: i64) -> Result<Wdl, E>
            where
                E: ::serde::de::Error,
            {
                if -2 <= value && value <= 2 {
                    Ok(unsafe { ::std::mem::transmute(value as i8) })
                } else {
                    Err(E::custom(format!("wdl out of range: {}", value)))
                }
            }

            fn visit_u64<E>(self, value: u64) -> Result<Wdl, E>
            where
                E: ::serde::de::Error,
            {
                if value <= 2 {
                    Ok(unsafe { ::std::mem::transmute(value as i8) })
                } else {
                    Err(E::custom(format!("wdl out of range: {}", value)))
                }
            }
        }

        deserializer.deserialize_i8(Visitor)
    }
}

/// Distance to zeroing of the half-move clock.
///
/// Can be off by one: `Dtz(-n)` can mean a loss in `n + 1` plies and `Dtz(n)`
/// can mean a win in `n + 1` plies. This is guaranteed not to happen for
/// positions exactly on the edge of the 50-move rule, so that this never
/// impacts results of practical play.
///
/// | DTZ | WDL | |
/// | --- | --- | --- |
/// | `-100 <= n <= -1` | Loss | Unconditional loss (assuming the 50-move counter is zero). Zeroing move can be forced in `-n` plies. |
/// | `n < -100` | Blessed loss | Loss, but draw under the 50-move rule. A zeroing move can be forced in `-n` plies or `-n - 100` plies (if a later phase is responsible for the blessing). |
/// | 0 | Draw | |
/// | `100 < n` | Cursed win | Win, but draw under the 50-move rule. A zeroing move can be forced in `n` or `n - 100` plies (if a later phase is responsible for the curse). |
/// | `1 <= n <= 100` | Win | Unconditional win (assuming the 50-move counter is zero). Zeroing move can be forced in `n` plies. |
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
pub struct Dtz(pub i16);

impl Dtz {
    pub fn before_zeroing(wdl: Wdl) -> Dtz {
        match wdl {
            Wdl::Loss => Dtz(-1),
            Wdl::BlessedLoss => Dtz(-101),
            Wdl::Draw => Dtz(0),
            Wdl::CursedWin => Dtz(101),
            Wdl::Win => Dtz(1),
        }
    }

    pub fn add_plies(&self, plies: i16) -> Dtz {
        Dtz(self.0.signum() * (self.0.abs() + plies))
    }
}

macro_rules! from_dtz_impl {
    ($($t:ty)+) => {
        $(impl From<Dtz> for $t {
            #[inline]
            fn from(wdl: Dtz) -> $t {
                wdl.0.into()
            }
        })+
    }
}

from_dtz_impl! { i16 i32 i64 isize }

macro_rules! dtz_from_impl {
    ($($t:ty)+) => {
        $(impl From<$t> for Dtz {
            #[inline]
            fn from(dtz: $t) -> Dtz {
                Dtz(i16::from(dtz))
            }
        })+
    }
}

dtz_from_impl! { u8 i8 i16 }

impl From<Dtz> for Wdl {
    fn from(dtz: Dtz) -> Wdl {
        match dtz.0 {
            n if -100 <= n && n <= -1 => Wdl::Loss,
            n if n < -100 => Wdl::BlessedLoss,
            0 => Wdl::Draw,
            n if 100 < n => Wdl::CursedWin,
            _ => Wdl::Win,
        }
    }
}

impl Neg for Dtz {
    type Output = Dtz;

    #[inline]
    fn neg(self) -> Dtz {
        Dtz(-self.0)
    }
}

impl Add for Dtz {
    type Output = Dtz;

    #[inline]
    fn add(self, other: Dtz) -> Dtz {
        Dtz(self.0 + other.0)
    }
}

impl AddAssign for Dtz {
    #[inline]
    fn add_assign(&mut self, other: Dtz) {
        self.0 += other.0;
    }
}

impl Sub for Dtz {
    type Output = Dtz;

    #[inline]
    fn sub(self, other: Dtz) -> Dtz {
        Dtz(self.0 - other.0)
    }
}

impl SubAssign for Dtz {
    #[inline]
    fn sub_assign(&mut self, other: Dtz) {
        self.0 -= other.0;
    }
}

#[cfg(feature="serde-1")]
impl ::serde::Serialize for Dtz {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: ::serde::Serializer,
    {
        serializer.serialize_i16(i16::from(*self))
    }
}

#[cfg(feature="serde-1")]
impl<'de> ::serde::Deserialize<'de> for Dtz {
    fn deserialize<D>(deserializer: D) -> Result<Dtz, D::Error>
    where
        D: ::serde::Deserializer<'de>,
    {
        struct Visitor;

        impl<'de> ::serde::de::Visitor<'de> for Visitor {
            type Value = Dtz;

            fn expecting(&self, formatter: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
                formatter.write_str("dtz value (i16)")
            }

            fn visit_i64<E>(self, value: i64) -> Result<Dtz, E>
            where
                E: ::serde::de::Error,
            {
                if i64::from(i16::min_value()) <= value && value <= i64::from(i16::max_value()) {
                    Ok(Dtz(value as i16))
                } else {
                    Err(E::custom(format!("dtz out of range: {}", value)))
                }
            }

            fn visit_u64<E>(self, value: u64) -> Result<Dtz, E>
            where
                E: ::serde::de::Error,
            {
                if value <= i16::max_value() as u64 {
                    Ok(Dtz(value as i16))
                } else {
                    Err(E::custom(format!("dtz out of range: {}", value)))
                }
            }
        }

        deserializer.deserialize_i16(Visitor)
    }
}

/// Syzygy tables are available for up to 7 pieces.
pub const MAX_PIECES: usize = 7;

/// List of up to 7 pieces.
pub type Pieces = ArrayVec<[Piece; MAX_PIECES]>;

/// Error when probing a table.
#[derive(Debug, Fail)]
pub enum SyzygyError {
    /// Position has castling rights.
    #[fail(display = "syzygy tables do not contain positions with castling rights")]
    Castling,
    /// Position has too many pieces.
    #[fail(display = "syzygy tables only contain positions with up to 7 pieces")]
    TooManyPieces,
    /// Missing table.
    #[fail(display = "required table not found: {}", material)]
    MissingTable {
        material: Material,
    },
    /// I/O error.
    #[fail(display = "i/o error when reading a table: {}", error)]
    Read {
        error: io::Error,
    },
    /// Unexpected magic header bytes.
    #[fail(display = "invalid magic bytes")]
    Magic,
    /// Corrupted table.
    #[fail(display = "corrupted table")]
    CorruptedTable,
}

impl From<NoneError> for SyzygyError {
    fn from(_: NoneError) -> SyzygyError {
        SyzygyError::CorruptedTable
    }
}

impl From<io::Error> for SyzygyError {
    fn from(error: io::Error) -> SyzygyError {
        match error.kind() {
            io::ErrorKind::UnexpectedEof => SyzygyError::CorruptedTable,
            _ => SyzygyError::Read { error },
        }
    }
}

/// A [`Result`] type for Syzygy tablebase probes.
///
/// [`Result`]: https://doc.rust-lang.org/std/result/enum.Result.html
pub type SyzygyResult<T> = Result<T, SyzygyError>;