Safely generating legal chess moves at 475,000,000 nodes/s
09/07/26 • prepare to read for a long time
When a chess engine thinks, it explores positions many moves ahead to determine the best move.
This takes a while, as there could be millions of positions after only four moves! The number of positions you explore increases exponentially. You could prune the paths you have to explore, but the overhead of generating, playing, and undoing all these legal moves is still noticeable.
Therefore, I've set out to write a fast legal move generator in Rust as a practical, safe, and standalone API. For the sake of giving it a name, it's called Watermelon. I'll show you what went into it, how fast is it compared to others, and how I'm using it in my own chess engine Strawberry :)
This chart shows nodes per second, a statistic that I'll explain later, obtained across multiple move generators. As you can see, Watermelon scores 475 million nodes per second, which is really fast! There are much faster ones, but there are very special things about this one.
Board representation
Obviously we need some way to represent a configuration of pieces on the board. Naively, you would represent this as an array of 64 squares which each encode whatever's on them. However, there's a better way that can be done with bitboards. These are 64-bit integers where each bit represents a square:
To store a chess position, we need six bitboards for each piece kind (pawn, knight, rook, bishop, queen, and king) and two bitboards for each color (white, black), totalling eight bitboards. This representation is only 64 bytes!
#[derive(Clone, PartialEq, Eq)]
#[repr(align(64))]
pub struct RawPosition {
piece_bitboards: [Bitboard; 6],
color_bitboards: [Bitboard; 2],
}
This representation allows for complicated queries to be made with only a few cheap bitwise operations! This makes for a really fast board representation. I'll show you some examples:
let pawns: Bitboard = // pawns
piece_bitboards[Piece::Pawn as usize];
let white_pawns: Bitboard = // white pawns = white and pawn
color_bitboards[Color::White as usize] & piece_bitboards[Piece::Pawn as usize];
let occupied: Bitboard = // occupied squares = white or black
color_bitboards[Color::White as usize] | color_bitboards[Color::Black as usize];
Helpers
There are many fundamental engine structures that I'll briefly explain. You can see their full implementation at utils.rs.
- The
Pieceenumeration:
pub enum Piece {
Pawn = 0,
Knight = 1,
Bishop = 2,
Rook = 3,
Queen = 4,
King = 5,
}
- The
Colorenumeration, which can be negated for the opposite color:
pub enum Color {
White = 0,
Black = 1,
}
- The
Squareenumeration, which identifies each square on a chessboard:
pub enum Square {
A1, B1, ..., G8, H8,
}
- The
Bitboard(u64)structure. This supports bitwise operations and can be iterated to obtain the squares for each set bit. This is important for move generation, and you'll know why in a moment. It's really fast on modern CPUs thanks to thetzcntinstruction whichtrailing_zeroscompiles down to!
impl Iterator for Bitboard {
type Item = Square;
fn next(&mut self) -> Option<Self::Item> {
if self.0 == 0 { return None; }
let index = self.0.trailing_zeros();
self.0 &= self.0 - 1; // clear lowest set bit
Some(unsafe { std::mem::transmute(index) }) // convert to square
}
}
-
The
CastlingRights(u8)structure, which uses four bits to encode each side's castling rights. -
The
Move(u16)structure, which encodes a chess move in only 16 bits: six for the from-square, six for the to-square, and four for flags that encode special characteristics. The flags are represented byMoveFlags, which you can read more about here:
pub enum MoveFlags {
Quiet = 0b0000,
DoublePawnPush = 0b0001,
KingCastle = 0b0010,
QueenCastle = 0b0011,
Capture = 0b0100,
EnPassantCapture = 0b0101,
KnightPromotion = 0b1000,
BishopPromotion = 0b1001,
RookPromotion = 0b1010,
QueenPromotion = 0b1011,
KnightPromotionCapture = 0b1100,
BishopPromotionCapture = 0b1101,
RookPromotionCapture = 0b1110,
QueenPromotionCapture = 0b1111,
}
-
The
Position(RawPosition)structure, which is a wrapper that also guarantees that there must be one of each king on the board and pawns must not be on the first or last ranks. -
The
MoveListstructure, which stores up to 271 moves in stack-allocated memory (no heap allocation). The reason for this is that no custom position can exceed 271 legal moves.
And that's about it! Sorry if that was hard to read. You don't need to remember all that.
Move generation
Time for what I've been wanting to talk about!
Given a chess position, how to generate all its legal moves as fast as possible? It starts inside this internal routine in movegen.rs:
/// Generates all legal moves from the provided arguments.
#[inline(always)]
pub unsafe fn generate_all_legal_moves<const CAPTURES_ONLY: bool>(
position: &Position,
color: Color,
castling_rights: CastlingRights,
en_passant_square: Option<Square>,
) -> MoveList {
let mut moves = MoveList::new();
let on_move = |mv| unsafe { moves.push_unchecked(mv) };
unsafe {
// Delegate based on the runtime `color` parameter to the right
// tailored implementation for that color.
match color {
Color::White => generate_all_legal_moves_impl::<White, ...>(...),
Color::Black => generate_all_legal_moves_impl::<Black, ...>(...),
}
}
moves
}
Color-specific logic
Instead of making move generation be full of slow color-independent operations, generate_all_legal_moves delegates once to either the white or black version of generate_all_legal_moves_impl (an implementation routine), each having specific move generation logic tailored for that color.
To encode this color-specific logic I made the internal White and Black types, which implement the ColorLogic trait. This trait provides operations that are different between colors.
pub trait ColorLogic {
type Opposite: ColorLogic;
const COLOR: Color;
/// Moves the provided bitboard forward one square towards
/// the opponent from our perspective.
fn forward(bitboard: Bitboard) -> Bitboard;
...
}
/// Implementation for the white side.
pub struct White;
impl ColorLogic for White {
type Opposite = Black;
const COLOR: Color = Color::White;
fn forward(bitboard: Bitboard) -> Bitboard { bitboard << 8 }
...
}
/// Implementation for the black side.
pub struct Black;
impl ColorLogic for Black {
type Opposite = White;
const COLOR: Color = Color::Black;
fn forward(bitboard: Bitboard) -> Bitboard { bitboard >> 8 }
...
}
Why does moving forward require shifting by 8? Because there are 8 squares in each row.
Generating pawn moves
The implementation routine starts by generating all legal pawn moves.
Firstly, I make four bitboards that correspond to the four kinds of pawn moves. Each bitboard holds the pawns that can move that way.
let quiet = pawns & Color::Opposite::forward(!occupied);
let double =
quiet & Color::PAWN_FIRST_RANK & Color::Opposite::double_forward(!occupied);
let left_capture = pawns & Color::Opposite::right_pawn_attack(other_occupancy);
let right_capture = pawns & Color::Opposite::left_pawn_attack(other_occupancy);
Iterating through each bitboard gives me the squares each pawn moves from, which I can use to determine what squares they move to. From the source and destination squares I can generate the relevant move. Here's an example for quiet moves:
for from in quiet {
let to = unsafe { from.offset_by_unchecked(Color::FORWARD_SQUARE_OFFSET) };
on_move(Move::new(from, to, MoveFlags::Quiet));
}
Pawn promotions only happen when coming from their 7th rank — a relatively rare occurrence in a typical game. Therefore, I branch on this so that if there aren't any pawns on that rank, we don't even check for promotion moves!
/// If there are pawns on the seventh rank, then also consider promotions.
/// `Color::PAWN_LAST_RANK` is the seventh rank.
if !(pawns & Color::PAWN_LAST_RANK).is_empty() {
std::hint::cold_path();
let quiet_promotion = quiet & Color::PAWN_LAST_RANK;
let left_capture_promotion = left_capture & Color::PAWN_LAST_RANK;
let right_capture_promotion = right_capture & Color::PAWN_LAST_RANK;
quiet &= !Color::PAWN_LAST_RANK;
left_capture &= !Color::PAWN_LAST_RANK;
right_capture &= !Color::PAWN_LAST_RANK;
// ... promotion moves generated here ...
}
// ... normal moves generated here ...
Generating knight moves
Knights are the easiest piece to generate legal moves for because they move uniformly.
Instead of calculating on the fly where a knight could potentially move to, I constructed a lookup table of 64 bitboards indexed by square. You can see these lookup tables in lookup.rs, which wraps these tables with nice API functions. The one for knights is lookup::knight_attack, which obtains the bitboard of knight attacks for a square.
When it comes around to generating the moves, I iterate through each knight, and see where it can legally move, then I iterate over that to generate the moves. The moveable variable simply keeps track of squares that are either empty or enemy-occupied, and quiet_or_capture decides whether to make the flag quiet or capture depending on if the destination is occupied.
for from in knights {
let legal = lookup::knight_attack(from) & moveable;
for to in legal {
let flags = quiet_or_capture(other_occupancy, to);
on_move(Move::new(from, to, flags));
}
}
Generating slider moves
Generating moves for slider pieces (bishop, rook, and queen) is done in a very similar way. I generate bishop and rook moves separately, and do queens together with them. Here's how I generate rook moves:
for from in rooks | queens {
let legal = lookup::rook_attack(from, occupied) & moveable;
for to in legal {
let flags = quiet_or_capture(other_occupancy, to);
on_move(Move::new(from, to, flags));
}
}
The key to this is lookup::rook_attack, which returns the squares a rook attacks given a source square and all occupied squares. The underlying table obviously cannot have entries for all possible occupancies, but we only focus on the relevant occupancy squares — those where a blocking piece actually changes what the rook can do. These are the squares that lie on the rook's rays but not on the edge.
As you can see, we extract only the occupancies that matter, which is up to 12 bits. That means the lookup table only has to encode up to 2^12 configurations for every possible rook square instead of 2^64, making it highly practical. This operation of extracting only the bits that matter is called parallel bit-extract, and it's likely that on your CPU this pext_u64 is a single native instruction. That's basically it, as bishops use similar logic!
pub fn rook_attack(from: Square, occupied: Bitboard) -> Bitboard {
let relevant_occupancy = tables::ROOK_BLOCKERS[from as usize];
let final_mask = pext_u64(occupied.0, relevant_occupancy);
let base = (from as usize) << 12;
let index = base.wrapping_add(final_mask);
// All you need is `from` and `final_mask` to lookup rook attacks!
Bitboard(unsafe { *tables::ROOK_ATTACKS.get_unchecked(index) })
}
Generating king moves
King move generation looks almost identical to the knight loop, except for one rule: the king cannot step into check. To handle this, I filter destinations using a banned bitboard, which tracks all squares attacked by enemy pieces. For this calculation, enemy slider attacks can go through our king, covering the square behind it so it cannot step back.
let king_moves = lookup::king_attack(king_square) & moveable & !banned;
for to in king_moves {
let flags = quiet_or_capture(other_occupancy, to);
on_move(Move::new(king_square, to, flags));
}
For castling, it implements standard castling rules:
if castling_rights.has_any(
Color::KINGSIDE_CASTLE_FLAG | Color::QUEENSIDE_CASTLE_FLAG
) {
if (Color::SHOULD_UNOCCUPIED_KINGSIDE_DURING_CASTLING & occupied).is_empty()
&& (Color::SHOULD_NOT_ATTACKED_KINGSIDE_DURING_CASTLING & banned).is_empty()
&& castling_rights.has_any(Color::KINGSIDE_CASTLE_FLAG)
{
on_move(Color::KINGSIDE_CASTLE_MOVE);
}
// ... repeat for queenside castling ...
}
Handling checks and pins
While reading all this you may have started to ask yourself where I handle checks and pins, as this is supposed to be a fully legal move generator. This is where the algorithm gets really interesting! I took lots of inspiration from the Gigantua move generator and its article, which is unfortunately no longer accessible at the time of writing.
When in check, the non-king moves you can make are restricted. You can only block or capture the checking piece. This is encoded in one checkmask bitboard, which depends on the number of checking pieces:
- 0: All ones, because there is no check to restrict you.
- 1: Squares between the checking piece and king (for block), including the checker (for capture).
- ≥2: All zeros, because you can only move your king.
Enemy sliders may pin pieces to our king, restricting their movement. These are called pins, and are handled through two pinmask bitboards: orthogonal and diagonal. When a piece is pinned, it has the squares between the pinning slider and our king.
A pinned piece can only move along its corresponding pinmask, and all moves must land on the checkmask. They're really similar, so I calculate them all in a single loop at the start of move generation. I put that all into a neat compute_checkmask_and_pinmasks routine:
let mut checkmask = Bitboard::FULL;
let mut orthogonal_pinmask = Bitboard::EMPTY;
let mut diagonal_pinmask = Bitboard::EMPTY;
// Find all enemy sliders that align with our king.
let ray = lookup::rook_attack(king_square, enemy_rooks);
for square in ray & enemy_rooks {
// This represents the squares in between, including the enemy slider.
let between_including_target =
(lookup::rook_attack(square, king) & ray) | Bitboard::from_square(square);
// If there are no pieces in between, this is a check.
// If there is one piece in between, this is a pin.
match (between_including_target & occupied).count_ones() {
1 => checkmask &= between_including_target,
2 => orthogonal_pinmask |= between_including_target,
_ => {}
}
}
// ... keep doing the same thing for bishops ...
// ... then simple logic for knights and pawns ...
// Successfully calculated our checkmask and pinmasks!
(checkmask, orthogonal_pinmask, diagonal_pinmask)
During move generation, I handle checks by restricting moveable with checkmask via bitwise-and, as it restricts where pieces can move. I handle pins using specialized logic to prune potential moves in all piece loops using the pinmasks. Additionally, pawns get special quick checkmask/pinmask logic, which I won't explain so you're not overwhelmed :) Click here if you want to see the implementation.
En-passant edge case
Capturing en-passant can reveal a horizontal slider attack:
In the shown situation, en-passant is illegal because it results in being checked, but the pawn isn't pinned. The move takes off two pieces at once. In the en-passant code, I manually check for this specific edge case and generate the en-passant moves.
Our move generator is now 100% legal!
Game representation
This section is more of a technical dive, so you can move on to the benchmarks if you're reading casually.
The Game struct represents a chess game in progress, and provides many useful methods! I'm not going to explain them, but they're all in game.rs.
/// Represents an active chess game.
pub struct Game {
positions: Vec<Position>,
undo_state: Vec<UndoState>,
color: Color,
}
/// Additional information about current game state.
struct UndoState {
pub castling_rights: CastlingRights,
pub en_passant_square: Option<Square>,
pub zobrist_hash: u64,
pub half_move_counter: usize,
}
Initially there is one entry in both vectors. Playing a move appends an entry to both, and undoing a move pops one out. The current position is always the last element of positions, and likewise for undo_state.
Playing a move starts from the unsafe routine Game::play_unchecked, which plays a move assuming its legality. The unsafe routine Game::undo_unchecked undoes the last move assuming there was one. The methods Game::try_play and Game::try_undo wrap their unsafe counterparts, the former verifying legality.
I'm not going to explain the logic of either, even though they're really optimized, but the way Game::play_unchecked deals with removing castling rights is elegant. If a move starts or ends on a rook's or king's starting square, the relevant castling flags are taken away. This has the same behavior as standard castling rules:
const LOOKUP: [CastlingRights; 64] = /* ... */;
undo_state.castling_rights &= !(LOOKUP[from as usize] | LOOKUP[to as usize]);
Additionally, the game incrementally keeps track of the 64-bit Zobrist hash of the current game state. This is really helpful for engines for routines like threefold repetition detection. You can explore more at zobrist.rs.
The notation.rs file provides additional functionality for FEN, UCI, SAN, and other representations with conversions between them.
Legal moves only
What if you want to look one move ahead? You first generate a list of legal moves, then for each you play, analyze, and undo. However, Game::try_play checks if the move is legal, which is very wasteful. You just generated a list of legal moves, of course they're all legal!
for mv in legal_moves {
game.try_play(mv);
// ... analyze this position ...
game.try_undo();
}
Therefore I introduced extra utilities in search.rs. The method Game::search() returns a SearchZero that borrows the game mutably, locking its state. This structure can be "promoted" to holding one (SearchOne) or more (SearchMany) moves guaranteed legal for the current position. Specifically SearchZero::legal_moves() returns a SearchMany that holds all the legal moves as a MoveList. You can temporarily extract a SearchOne from a SearchMany by SearchMany::as_one(index: usize) -> SearchOne.
The key method is SearchOne::test, which safely tests a move without checking for anything, as the move stored in it is guaranteed legal for the frozen position. Here's a simplified implementation:
pub fn test<R>(&mut self, closure: impl FnOnce(SearchZero<Exclusive>) -> R) -> R {
unsafe { self.game.play_unchecked(self.mv) };
let result = closure(SearchZero { game: self.game });
unsafe { self.game.undo_unchecked() };
result
}
This helps us write our original code as follows, which doesn't recheck legality:
let legal_moves = game.legal_moves(); // shorthand for `game.search().legal_moves()`
for i in 0..legal_moves.moves().len() {
legal_moves.as_one(i).test(|search| {
// ... analyze this position ...
});
}
Benchmarks
The time has come to finally evaluate our move generator's performance through something called perft. From a starting position, count the positions (nodes) that occur in a certain number of moves (depth), including duplication.
With our abstractions we can implement perft relatively simply, the only optimization being bulk counting. Notice that this uses no generics, no unsafe code, and materializes the move list. Many other move generators drop these for the sake of performance, but these constraints are practical for real engines. Here's the implementation:
fn perft(mut search: SearchZero<'_, Exclusive>, depth: usize) -> usize {
match depth {
0 => 1,
1 => search.legal_moves().moves().len(),
_ => {
let mut count = 0;
let mut search = search.legal_moves();
for index in 0..search.moves().len() {
search
.as_one(index)
.test(|game| count += perft(game, depth - 1));
}
count
}
}
}
Time to see how fast is our move generator, Watermelon, compared to others:
I want to make it clear that this benchmark is very sloppy, and is not intended to be conclusive. Stockfish and Rustic were only tested on one position, so I didn't include them. I used past benchmarks for Chessbit. All move generators returned the same node count, but Templechess yielded an incorrect node count for one position. Gigantua, Watermelon, MidnightMoveGen, and Surge were all tested on my computer on every single position, with the latter being too slow for two positions. Some were run with WSL, and all were run without a transposition table.
Does this project matter at all?
Edited 09/08/2026: Rewrote this section to match my response
Ladies and gentlemen, this project is in fact worthless for real-world chess engines, which is the only thing this would be realistically used for. Perft was originally designed to verify correctness, and its speed actually doesn't matter practically. Additionally, pseudolegal move generation is preferred to our legal move generation.
From my younger years I wanted to make the fastest move generator, and I think that even though this project is practically worthless, this was fulfilled in the best way possible. The API is safe, almost complete, and usable, and it's extremely fast. This article was made to encapsulate more so the journey, and not the destination.
I've made Strawberry to test this move generator out. I've tried to make the code understandable, and it's a decent engine with transposition tables, iterative deepening, alpha-beta pruning, draw detection, UCI protocol, and more! The bot is available to play on Lichess whenever it's online, which is not often. However, I plan to make it easily accessible with WebAssembly so it's always available to play.
If you want to explore the code, go check out the repository which includes the move generator (watermelon), chess engine (strawberry), its desktop interface (strawberry-uci), and the benchmarks (strawberry-perft).
Conclusion
Maybe you thought this article was a waste of your time. Possibly I explained things too slow, fast, or complicated. I could've made a mistake or sounded negative. Maybe you're viewing on mobile and it's impossible to read, or all the diagrams are suddenly in Times New Roman. Whatever it is, I'm sorry.
Hopefully you found some of it interesting. I wasn't going to write a blog post, but I realized that projects like this are worthless without anyone knowing they exist, so it means a lot to me that some people care about something I made.
Thanks so much for reading! :D
Article and illustrations made by Benyamin Bamburac; illustrations designed in Inkscape
This article's text was made by me in overwhelming proportion
Piece set “cburnett” by Colin M.L. Burnett (CC BY-SA 3.0)