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
//! Contains the `PieceLocations` structure that maps from squares of a board to a player / piece at that square.
//!
//! This is useful mainly for the [`Board`] to use internally for fast square lookups.
//!
//! [`Board`]: ../struct.Board.html
//! [`PieceLocations`]: struct.PieceLocations.html

use std::mem;

use core::*;
use core::masks::*;
use core::sq::SQ;
use super::FenBuildError;

/// Struct to allow fast lookups for any square. Given a square, allows for determining if there
/// is a piece currently there, and if so, allows for determining it's color and type of piece.
///
/// Piece Locations is a BLIND structure, Providing a function of  |sq| -> |Piece AND/OR Player|
/// The reverse cannot be done Looking up squares from a piece / player.
pub struct PieceLocations {
    // Pieces are represented by the following bit_patterns:
    // x000 -> Pawn (P)
    // x001 -> Knight(N)
    // x010 -> Bishop (B)
    // x011 -> Rook(R)
    // x100 -> Queen(Q)
    // x101 -> King (K)
    // x110 -> ??? Undefined ??
    // x111 -> None
    // 0xxx -> White Piece
    // 1xxx -> Black Piece

    // array of u8's, with standard ordering mapping index to square
    data: [Piece; SQ_CNT],
}



impl PieceLocations {
    /// Constructs a new `PieceLocations` with a default of no pieces on the board.
    pub const fn blank() -> PieceLocations {
        PieceLocations { data: [Piece::None; 64] }
    }

    /// Places a given piece for a given player at a certain square.
    ///
    /// # Panics
    ///
    /// Panics if Square is of index higher than 63.
    #[inline]
    pub fn place(&mut self, square: SQ, player: Player, piece: PieceType) {
        debug_assert!(square.is_okay());
        debug_assert!(piece.is_real());
        self.data[square.0 as usize] = Piece::make_lossy(player, piece);
    }

    /// Removes a Square.
    ///
    /// # Panics
    ///
    /// Panics if Square is of index higher than 63.
    #[inline]
    pub fn remove(&mut self, square: SQ) {
        debug_assert!(square.is_okay());
        self.data[square.0 as usize] = Piece::None;
    }

    /// Returns the Piece at a `SQ`, Or None if the square is empty.
    ///
    /// # Panics
    ///
    /// Panics if square is of index higher than 63.
    #[inline]
    pub fn piece_at(&self, square: SQ) -> Piece {
        debug_assert!(square.is_okay());
        self.data[square.0 as usize]
    }

    /// Returns if a square is occupied.
    #[inline]
    pub fn at_square(&self, square: SQ) -> bool {
        assert!(square.is_okay());
        self.data[square.0 as usize] != Piece::None

    }

    /// Returns the first square (if any) that a piece / player is at.
    #[inline]
    pub fn first_square(&self, piece: PieceType, player: Player) -> Option<SQ> {
        let target = Piece::make_lossy(player, piece);
        for x in 0..64 {
            if target == self.data[x as usize] {
                return Some(SQ(x));
            }
        }
        None
    }

    /// Returns if the Board contains a particular piece / player.
    #[inline]
    pub fn contains(&self, piece: PieceType, player: Player) -> bool {
        self.first_square(piece,player).is_some()
    }

    /// Generates a `PieceLocations` from a partial fen. A partial fen is defined as the first part of a
    /// fen, where the piece positions are available.
    pub(crate) fn from_partial_fen(ranks: &[&str]) -> Result<Vec<(SQ,Player,PieceType)>, FenBuildError> {
        let mut loc = Vec::with_capacity(64);
        for (i, rank) in ranks.iter().enumerate() {
            let min_sq = (7 - i) * 8;
            let max_sq = min_sq + 7;
            let mut idx = min_sq;
            for ch in rank.chars() {
                if idx < min_sq {
                    return Err(FenBuildError::SquareSmallerRank{rank: i, square: SQ(idx as u8).to_string()})
                } else if idx > max_sq {
                    return Err(FenBuildError::SquareLargerRank{rank: i, square: SQ(idx as u8).to_string()})
                }

                let dig = ch.to_digit(10);
                if let Some(digit) = dig {
                    idx += digit as usize;
                } else {
                    // if no space, then there is a piece here
                    let piece = match ch {
                        'p' | 'P' => PieceType::P,
                        'n' | 'N' => PieceType::N,
                        'b' | 'B' => PieceType::B,
                        'r' | 'R' => PieceType::R,
                        'q' | 'Q' => PieceType::Q,
                        'k' | 'K' => PieceType::K,
                        _ => {return Err(FenBuildError::UnrecognizedPiece{piece: ch})},
                    };
                    let player = if ch.is_lowercase() {
                        Player::Black
                    } else {
                        Player::White
                    };
                    loc.push((SQ(idx as u8), player, piece));
                    idx += 1;
                }
            }
        }
        Ok(loc)
    }
}

impl Clone for PieceLocations {
    // Need to use transmute copy as [_;64] does not automatically implement Clone.
    fn clone(&self) -> PieceLocations {
        unsafe { mem::transmute_copy(&self.data) }
    }
}

impl PartialEq for PieceLocations {
    fn eq(&self, other: &PieceLocations) -> bool {
        for sq in 0..64 {
            if self.data[sq] != other.data[sq] {
                return false;
            }
        }
        true
    }
}


pub struct PieceLocationsIter {
    locations: PieceLocations,
    sq: SQ
}

impl Iterator for PieceLocationsIter {
    type Item = (SQ,Piece);

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        if self.sq >= SQ::NONE {
            None
        } else {
            let piece = self.locations.piece_at(self.sq);
            if piece != Piece::None {
                let sq = self.sq;
                self.sq += SQ(1);
                return Some((sq, piece));
            } else {
                return self.next();
            }
        }
    }
}

impl IntoIterator for PieceLocations {
    type Item = (SQ,Piece);
    type IntoIter = PieceLocationsIter;

    #[inline(always)]
    fn into_iter(self) -> Self::IntoIter {
        PieceLocationsIter {
            locations: self,
            sq: SQ(0),
        }
    }
}