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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
// This file is part of the shakmaty library.
// Copyright (C) 2017-2019 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::cmp::{Ord, Ordering, PartialOrd};
use std::fmt;
use std::error::Error;
use std::iter::FromIterator;
use std::mem;
use std::str::FromStr;
use std::ops::{Add, AddAssign, Sub, SubAssign};

use crate::types::{Color, Piece, Role, ROLES};

/// Error when parsing an invalid material key.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ParseMaterialError;

impl fmt::Display for ParseMaterialError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        "invalid material key".fmt(f)
    }
}

impl Error for ParseMaterialError {
    fn description(&self) -> &str {
        "invalid square name"
    }
}

impl From<()> for ParseMaterialError {
    fn from(_: ()) -> ParseMaterialError {
        ParseMaterialError
    }
}

/// The material configuration of one side.
#[derive(Clone, Default, Eq, PartialEq, Hash)]
pub struct MaterialSide {
    pub pawns: u8,
    pub knights: u8,
    pub bishops: u8,
    pub rooks: u8,
    pub queens: u8,
    pub kings: u8,
}

impl MaterialSide {
    pub fn new() -> MaterialSide {
        MaterialSide::default()
    }

    pub fn by_role(&self, role: Role) -> u8 {
        match role {
            Role::Pawn => self.pawns,
            Role::Knight => self.knights,
            Role::Bishop => self.bishops,
            Role::Rook => self.rooks,
            Role::Queen => self.queens,
            Role::King => self.kings,
        }
    }

    pub fn by_role_mut(&mut self, role: Role) -> &mut u8 {
        match role {
            Role::Pawn => &mut self.pawns,
            Role::Knight => &mut self.knights,
            Role::Bishop => &mut self.bishops,
            Role::Rook => &mut self.rooks,
            Role::Queen => &mut self.queens,
            Role::King => &mut self.kings,
        }
    }

    pub fn is_empty(&self) -> bool {
        self.pawns == 0 &&
        self.knights == 0 &&
        self.bishops == 0 &&
        self.rooks == 0 &&
        self.queens == 0 &&
        self.kings == 0
    }

    pub fn count(&self) -> usize {
        usize::from(self.pawns) +
        usize::from(self.knights) +
        usize::from(self.bishops) +
        usize::from(self.rooks) +
        usize::from(self.queens) +
        usize::from(self.kings)
    }

    pub fn has_pawns(&self) -> bool {
        self.pawns > 0
    }

    pub fn from_ascii(s: &[u8]) -> Result<MaterialSide, ParseMaterialError> {
        if s.len() > 64 {
            return Err(ParseMaterialError);
        }

        let mut result = MaterialSide::new();

        for &ch in s {
            let role = Role::from_char(char::from(ch)).ok_or(ParseMaterialError)?;
            *result.by_role_mut(role) += 1;
        }

        Ok(result)
    }
}

impl fmt::Display for MaterialSide {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for &role in ROLES.iter().rev() {
            write!(f, "{}", role.char().to_uppercase().to_string().repeat(usize::from(self.by_role(role))))?;
        }
        Ok(())
    }
}

impl fmt::Debug for MaterialSide {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.count() > 0 {
            write!(f, "{}", self)
        } else {
            f.write_str("-")
        }
    }
}

impl Extend<Role> for MaterialSide {
    fn extend<T: IntoIterator<Item = Role>>(&mut self, iter: T) {
        for role in iter.into_iter().take(64 - self.count()) {
            *self.by_role_mut(role) += 1;
        }
    }
}

impl FromIterator<Role> for MaterialSide {
    fn from_iter<T>(iter: T) -> Self
    where
        T: IntoIterator<Item = Role>,
    {
        let mut result = MaterialSide::new();
        result.extend(iter);
        result
    }
}

impl Ord for MaterialSide {
    fn cmp(&self, other: &MaterialSide) -> Ordering {
        self.count().cmp(&other.count())
            .then(self.kings.cmp(&other.kings))
            .then(self.queens.cmp(&other.queens))
            .then(self.rooks.cmp(&other.rooks))
            .then(self.bishops.cmp(&other.bishops))
            .then(self.knights.cmp(&other.knights))
            .then(self.pawns.cmp(&other.pawns))
    }
}

impl PartialOrd for MaterialSide {
    fn partial_cmp(&self, other: &MaterialSide) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl FromStr for MaterialSide {
    type Err = ParseMaterialError;

    fn from_str(s: &str) -> Result<MaterialSide, ParseMaterialError> {
        MaterialSide::from_ascii(s.as_bytes())
    }
}

impl<'a> AddAssign<&'a MaterialSide> for MaterialSide {
    fn add_assign(&mut self, other: &'a MaterialSide) {
        self.pawns += other.pawns;
        self.knights += other.knights;
        self.bishops += other.bishops;
        self.rooks += other.rooks;
        self.queens += other.queens;
        self.kings += other.kings;
    }
}

impl AddAssign for MaterialSide {
    fn add_assign(&mut self, other: MaterialSide) {
        *self += &other;
    }
}

impl<'a> Add<&'a MaterialSide> for MaterialSide {
    type Output = MaterialSide;

    fn add(mut self, other: &'a MaterialSide) -> MaterialSide {
        self += other;
        self
    }
}

impl Add for MaterialSide {
    type Output = MaterialSide;

    fn add(mut self, other: MaterialSide) -> MaterialSide {
        self += other;
        self
    }
}

impl<'a> SubAssign<&'a MaterialSide> for MaterialSide {
    fn sub_assign(&mut self, other: &'a MaterialSide) {
        self.pawns -= other.pawns;
        self.knights -= other.knights;
        self.bishops -= other.bishops;
        self.rooks -= other.rooks;
        self.queens -= other.queens;
        self.kings -= other.kings;
    }
}

impl SubAssign for MaterialSide {
    fn sub_assign(&mut self, other: MaterialSide) {
        *self -= &other;
    }
}

impl<'a> Sub<&'a MaterialSide> for MaterialSide {
    type Output = MaterialSide;

    fn sub(mut self, other: &'a MaterialSide) -> MaterialSide {
        self -= other;
        self
    }
}

impl Sub for MaterialSide {
    type Output = MaterialSide;

    fn sub(mut self, other: MaterialSide) -> MaterialSide {
        self -= other;
        self
    }
}

/// The material configuration of both sides.
#[derive(Clone, Default, Eq, PartialEq, Hash)]
pub struct Material {
    pub white: MaterialSide,
    pub black: MaterialSide,
}

impl Material {
    pub fn new() -> Material {
        Material::default()
    }

    pub fn flip(&mut self) {
        mem::swap(&mut self.white, &mut self.black);
    }

    pub fn flipped(&self) -> Material {
        let mut material = self.clone();
        material.flip();
        material
    }

    pub fn normalize(&mut self) {
        if self.white < self.black {
            self.flip();
        }
    }

    pub fn normalized(&self) -> Material {
        let mut material = self.clone();
        material.normalize();
        material
    }

    pub fn is_symmetric(&self) -> bool {
        self.white == self.black
    }

    pub fn by_color(&self, color: Color) -> &MaterialSide {
        match color {
            Color::Black => &self.black,
            Color::White => &self.white,
        }
    }

    pub fn by_color_mut(&mut self, color: Color) -> &mut MaterialSide {
        match color {
            Color::Black => &mut self.black,
            Color::White => &mut self.white,
        }
    }

    pub fn by_piece(&self, piece: Piece) -> u8 {
        self.by_color(piece.color).by_role(piece.role)
    }

    pub fn by_piece_mut(&mut self, piece: Piece) -> &mut u8 {
        self.by_color_mut(piece.color).by_role_mut(piece.role)
    }

    pub fn is_empty(&self) -> bool {
        self.white.is_empty() && self.black.is_empty()
    }

    pub fn count(&self) -> usize {
        self.white.count() + self.black.count()
    }

    pub fn has_pawns(&self) -> bool {
        self.white.has_pawns() || self.black.has_pawns()
    }

    pub fn from_ascii(s: &[u8]) -> Result<Material, ParseMaterialError> {
        let mut parts = s.splitn(2, |ch| *ch == b'v');

        Ok(Material {
            white: match parts.next() {
                Some(w) => MaterialSide::from_ascii(w)?,
                None => MaterialSide::new(),
            },
            black: match parts.next() {
                Some(b) => MaterialSide::from_ascii(b)?,
                None => MaterialSide::new(),
            },
        })
    }

    pub fn from_ascii_fen(s: &[u8]) -> Result<Material, ParseMaterialError> {
        if s.len() > 64 {
            return Err(ParseMaterialError);
        }

        let mut material = Material::new();
        for &ch in s {
            *material.by_piece_mut(Piece::from_char(char::from(ch)).ok_or(ParseMaterialError)?) += 1;
        }
        Ok(material)
    }

    pub fn fen(&self) -> String {
        let mut fen = String::with_capacity(self.count());

        for &color in &[Color::White, Color::Black] {
            for &role in &ROLES {
                let piece = Piece { color, role };
                for _ in 0..self.by_piece(piece) {
                    fen.push(piece.char());
                }
            }
        }

        fen
    }
}

impl fmt::Display for Material {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}v{}", self.white, self.black)
    }
}

impl fmt::Debug for Material {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:?}v{:?}", self.white, self.black)
    }
}

impl Extend<Piece> for Material {
    fn extend<T: IntoIterator<Item = Piece>>(&mut self, iter: T) {
        for piece in iter.into_iter().take(64 - self.count()) {
            *self.by_piece_mut(piece) += 1;
        }
    }
}

impl FromIterator<Piece> for Material {
    fn from_iter<T>(iter: T) -> Self
    where
        T: IntoIterator<Item = Piece>,
    {
        let mut result = Material::new();
        result.extend(iter);
        result
    }
}

impl FromStr for Material {
    type Err = ParseMaterialError;

    fn from_str(s: &str) -> Result<Material, ParseMaterialError> {
        Material::from_ascii(s.as_bytes())
    }
}

impl<'a> AddAssign<&'a Material> for Material {
    fn add_assign(&mut self, other: &'a Material) {
        self.white += &other.white;
        self.black += &other.black;
    }
}

impl AddAssign for Material {
    fn add_assign(&mut self, other: Material) {
        *self += &other;
    }
}

impl<'a> Add<&'a Material> for Material {
    type Output = Material;

    fn add(mut self, other: &'a Material) -> Material {
        self += other;
        self
    }
}

impl Add for Material {
    type Output = Material;

    fn add(mut self, other: Material) -> Material {
        self += other;
        self
    }
}

impl<'a> SubAssign<&'a Material> for Material {
    fn sub_assign(&mut self, other: &'a Material) {
        self.white -= &other.white;
        self.black -= &other.black;
    }
}

impl SubAssign for Material {
    fn sub_assign(&mut self, other: Material) {
        *self -= &other;
    }
}

impl<'a> Sub<&'a Material> for Material {
    type Output = Material;

    fn sub(mut self, other: &'a Material) -> Material {
        self -= other;
        self
    }
}

impl Sub for Material {
    type Output = Material;

    fn sub(mut self, other: Material) -> Material {
        self -= other;
        self
    }
}