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
use crate::*;

/// A compact structure representing multiple moves for a piece on the board.
/// Iterate it to unpack its moves.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct PieceMoves {
    /// The [`Piece`] that is moved.
    pub piece: Piece,
    /// The square to move the piece from.
    pub from: Square,
    /// The possible destination squares.
    pub to: BitBoard
}

impl IntoIterator for PieceMoves {
    type Item = Move;

    type IntoIter = PieceMovesIter;

    fn into_iter(self) -> Self::IntoIter {
        PieceMovesIter {
            moves: self,
            promotion: 0
        }
    }
}

impl PieceMoves {
    /// Get the number of [`Move`]s.
    pub fn len(&self) -> usize {
        const PROMOTION_MASK: BitBoard = BitBoard(
            Rank::First.bitboard().0 | Rank::Eighth.bitboard().0
        );
        let moves = if self.piece == Piece::Pawn {
            (self.to & !PROMOTION_MASK).len() +
            (self.to & PROMOTION_MASK).len() * 4
        } else {
            self.to.len()
        };
        moves as usize
    }

    /// Check if there are no [`Move`]s.
    pub fn is_empty(&self) -> bool {
        self.to.is_empty()
    }

    /// Check if it contains a given [`Move`].
    pub fn has(&self, mv: Move) -> bool {
        let has_promotion = mv.promotion.is_some();
        let is_promotion = self.piece == Piece::Pawn &&
            matches!(mv.to.rank(), Rank::First | Rank::Eighth);
        self.from == mv.from
            && self.to.has(mv.to)
            && (has_promotion == is_promotion)
    }
}

/// Iterator over the moves in a [`PieceMoves`] instance.
pub struct PieceMovesIter {
    moves: PieceMoves,
    promotion: u8
}

impl Iterator for PieceMovesIter {
    type Item = Move;

    #[inline(always)]
    fn next(&mut self) -> Option<Self::Item> {
        let from = self.moves.from;
        let to = self.moves.to.next_square()?;
        let is_promotion = self.moves.piece == Piece::Pawn &&
            matches!(to.rank(), Rank::First | Rank::Eighth);
        let promotion = if is_promotion {
            let promotion = match self.promotion {
                0 => Piece::Knight,
                1 => Piece::Bishop,
                2 => Piece::Rook,
                3 => Piece::Queen,
                _ => unreachable!()
            };
            if self.promotion < 3 {
                self.promotion += 1;
            } else {
                self.promotion = 0;
                self.moves.to ^= to.bitboard();
            }
            Some(promotion)
        } else {
            self.moves.to ^= to.bitboard();
            None
        };
        Some(Move {
            from,
            to,
            promotion
        })
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let len = self.len();
        (len, Some(len))
    }
}

impl ExactSizeIterator for PieceMovesIter {
    fn len(&self) -> usize {
        self.moves.len() - self.promotion as usize
    }
}

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

    #[test]
    fn len_handles_promotions() {
        let mv = PieceMoves {
            piece: Piece::Pawn,
            from: Square::A7,
            to: Square::A8.bitboard() | Square::B8.bitboard()
        };
        assert_eq!(mv.len(), 8);
        let mut iter = mv.into_iter();
        assert_eq!(iter.len(), 8);
        for len in (0..8).rev() {
            iter.next();
            assert_eq!(iter.len(), len);
        }
    }
    
    #[test]
    fn has_works() {
        let mv = PieceMoves {
            piece: Piece::King,
            from: Square::A7,
            to: get_king_moves(Square::A7)
        };
        assert!(!mv.has(Move {
            from: Square::A7,
            to: Square::A8,
            promotion: Some(Piece::Queen)
        }));
        assert!(mv.has(Move {
            from: Square::A7,
            to: Square::A8,
            promotion: None
        }));
    }

    #[test]
    fn has_handles_promotions() {
        let mv = PieceMoves {
            piece: Piece::Pawn,
            from: Square::A7,
            to: Square::A8.bitboard() | Square::B8.bitboard()
        };
        assert!(mv.has(Move {
            from: Square::A7,
            to: Square::A8,
            promotion: Some(Piece::Queen)
        }));
        assert!(!mv.has(Move {
            from: Square::A7,
            to: Square::A8,
            promotion: None
        }));
    }
}