jordanbray / chess

A rust library to manage chess move generation
https://jordanbray.github.io/chess/
MIT License
231 stars 54 forks source link

Out of bounds square can cause out of bounds access. #56

Closed analog-hors closed 1 year ago

analog-hors commented 3 years ago
fn main() {
    println!("{}", chess::get_king_moves(chess::EMPTY.to_square()));
}

prints garbage:

. . . . . . X X 
X X X . X . . .
X X . X X X X .
. . . . X . X .
. X X . X X X X
X X X X X X X .
. . . . . . . .
. . . . . . . .

BitBoard::to_square creates an out of bounds Square(64) on an empty bitboard. This can be used to access out of bounds memory. Another somewhat irrelevant thing that can be considered is making Square an enum instead. This would allow the compiler to automatically elide all bounds checks when indexing by Squares. It would allow it to be used for niche space optimizations.

jordanbray commented 1 year ago

The UB is resolved, but making square an enum is a good idea.