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
//! Implements `MoveStack`.

use moves::{Move, MoveDigest, AddMove};


/// Stores a list of moves for each position in a given line of play.
///
/// # Examples:
///
/// ```rust
/// # use alcibiades::Move;
/// # use alcibiades::utils::MoveStack;
/// let mut s = MoveStack::new();
/// assert_eq!(s.ply(), 0);
/// assert_eq!(s.list().len(), 0);
/// s.push(Move::invalid());
/// s.push(Move::invalid());
/// assert_eq!(s.list().len(), 2);
/// let first_move = s.pull_best();
/// assert_eq!(s.list().len(), 1);
/// s.save();
/// assert_eq!(s.ply(), 1);
/// assert_eq!(s.list().len(), 0);
/// s.restore();
/// assert_eq!(s.ply(), 0);
/// assert_eq!(s.list().len(), 1);
/// let second_move = s.pull_best();
/// assert_eq!(s.list().len(), 0);
/// ```
pub struct MoveStack {
    moves: Vec<Move>,
    savepoints: Vec<usize>,
    first_move_index: usize,
}


impl AddMove for MoveStack {
    /// Appends a move to the end of the current move list.
    #[inline]
    fn add_move(&mut self, m: Move) {
        self.push(m);
    }
}


impl MoveStack {
    /// Creates a new (empty) instance.
    pub fn new() -> MoveStack {
        MoveStack {
            moves: Vec::with_capacity(32 * 64),
            savepoints: Vec::with_capacity(32),
            first_move_index: 0,
        }
    }

    /// Saves the current move list and replaces it with an empty one.
    ///
    /// This method can be called many times. At each call the current
    /// move list will be saved to the stack of lists that can later
    /// be restored. After calling `save` the new current move list
    /// will be empty.
    #[inline]
    pub fn save(&mut self) {
        self.savepoints.push(self.first_move_index);
        self.first_move_index = self.moves.len();
    }

    /// Restores the last saved move list.
    ///
    /// The current move list is lost.
    ///
    /// # Panics
    ///
    /// Panics if there are no saved move lists left.
    #[inline]
    pub fn restore(&mut self) {
        self.moves.truncate(self.first_move_index);
        self.first_move_index = self.savepoints.pop().unwrap();
    }

    /// Returns the number of saved move lists.
    ///
    /// The number of saved move lists starts at zero. It is
    /// incremented on each call to `save`, and decremented on each
    /// call to `restore`.
    #[inline]
    pub fn ply(&self) -> usize {
        self.savepoints.len()
    }

    /// Clears the current move list, removing all moves from it.
    #[inline]
    pub fn clear(&mut self) {
        self.moves.truncate(self.first_move_index);
    }

    /// Clears the current move list and deletes all saved move lists.
    #[inline]
    pub fn clear_all(&mut self) {
        self.moves.clear();
        self.savepoints.clear();
        self.first_move_index = 0;
    }

    /// Appends a move to the end of the current move list.
    #[inline]
    pub fn push(&mut self, m: Move) {
        debug_assert!(self.moves.len() >= self.first_move_index);
        self.moves.push(m);
    }

    /// Removes the last move from the current move list and returns it.
    ///
    /// If the current move list is empty, `None` is returned.
    #[inline]
    pub fn pop(&mut self) -> Option<Move> {
        debug_assert!(self.moves.len() >= self.first_move_index);
        if self.moves.len() > self.first_move_index {
            self.moves.pop()
        } else {
            None
        }
    }

    /// Removes the move at given index from the current move list and
    /// returns it.
    ///
    /// Move's slot is taken by the last move in the current list, and
    /// the last slot is discarded.
    ///
    /// # Panics
    ///
    /// Panics if there is no move at the given index.
    #[inline]
    pub fn pull(&mut self, index: usize) -> Move {
        let last_move = *self.moves.last().unwrap();
        let m;
        {
            let requested_slot = &mut self.moves[self.first_move_index + index];
            m = *requested_slot;
            *requested_slot = last_move;
        }
        self.moves.pop();
        m
    }

    /// Removes a specific move from the current move list and returns it.
    ///
    /// This method tries to find a move `m` for which `m.digest() ==
    /// move_digest`. If such move is found, `Some(m)` is returned,
    /// move's slot is taken by the last move in the current list, and
    /// the last slot is discarded. If no such move is found, `None`
    /// is returned.
    #[inline]
    pub fn pull_move(&mut self, move_digest: MoveDigest) -> Option<Move> {
        debug_assert!(self.moves.len() >= self.first_move_index);

        // The last move in `self.moves` will take the place of the
        // removed move.
        let last_move = if let Some(last) = self.moves.last() {
            *last
        } else {
            return None;
        };

        let m;
        'moves: loop {
            for curr in self.list_mut().iter_mut() {
                if curr.digest() == move_digest {
                    m = *curr;
                    *curr = last_move;
                    break 'moves;
                }
            }
            return None;
        }
        debug_assert!(!self.moves.is_empty());
        self.moves.pop();
        Some(m)
    }

    /// Removes the move with the highest value from the current move
    /// list and returns it.
    ///
    /// Best move's slot is taken by the last move in the current
    /// list, and the last slot is discarded. `None` is returned if
    /// the current move list is empty.
    #[inline]
    pub fn pull_best(&mut self) -> Option<Move> {
        debug_assert!(self.moves.len() >= self.first_move_index);
        let moves = &mut self.moves;
        let n = moves.len();
        if n > self.first_move_index {
            let last = n - 1;
            unsafe {
                let mut best_move = *moves.get_unchecked(last);
                let mut best = last;
                let mut i = last;
                while i > self.first_move_index {
                    i -= 1;
                    let m = *moves.get_unchecked(i);
                    if m > best_move {
                        best_move = m;
                        best = i;
                    }
                }
                *moves.get_unchecked_mut(best) = *moves.get_unchecked(last);
                moves.pop();
                return Some(best_move);
            }
        }
        None
    }

    /// Returns the current move list as a slice.
    #[inline]
    pub fn list(&self) -> &[Move] {
        debug_assert!(self.moves.len() >= self.first_move_index);
        &self.moves[self.first_move_index..]
    }

    /// Returns the current move list as a mutable slice.
    #[inline]
    pub fn list_mut(&mut self) -> &mut [Move] {
        debug_assert!(self.moves.len() >= self.first_move_index);
        &mut self.moves[self.first_move_index..]
    }
}


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

    #[should_panic]
    #[test]
    fn move_stack_pull_panic() {
        let mut s = MoveStack::new();
        s.pull(0);
    }

    #[test]
    fn move_stack() {
        let cr = CastlingRights::new(0);
        let m = Move::new(MOVE_NORMAL, E2, E4, 0, PIECE_NONE, PAWN, cr, 8, 0);
        let mut s = MoveStack::new();
        assert_eq!(s.ply(), 0);
        assert!(s.pull_best().is_none());
        s.save();
        assert_eq!(s.ply(), 1);
        s.push(m);
        assert_eq!(s.pull(0), m);
        assert!(s.pull_best().is_none());
        s.restore();
        assert!(s.pull_best().is_none());
        assert_eq!(s.list().len(), 0);
        assert!(s.pop().is_none());
        assert!(s.pull_move(m.digest()).is_none());
        s.push(m);
        s.push(m);
        assert_eq!(s.list().len(), 2);
        assert_eq!(s.pop().unwrap(), m);
        assert_eq!(s.list().len(), 1);
        s.push(m);
        assert_eq!(s.pull_move(m.digest()).unwrap(), m);
        assert_eq!(s.list().len(), 1);
        s.push(m);
        assert_eq!(s.list().iter().count(), 2);
        s.save();
        s.push(m);
        s.restore();
        assert_eq!(s.pull_best().unwrap(), m);
        assert_eq!(s.pull_best().unwrap(), m);
        assert!(s.pull_best().is_none());
        assert_eq!(s.ply(), 0);
        s.push(m);
        s.clear();
        assert_eq!(s.ply(), 0);
        assert_eq!(s.list().len(), 0);
        s.save();
        s.save();
        s.push(m);
        assert_eq!(s.ply(), 2);
        s.clear_all();
        assert_eq!(s.ply(), 0);
        assert_eq!(s.list().len(), 0);
    }
}