[CHAPTER 01 // crates/core · engine, SPEC 001] Implemented in engine code

Bitboards, Magic Rays & Make/Unmake

64-bit board bitmasks, precomputed magic sliding-piece attack lookups, and bit-exact state restoration across search plies.

Why does BalouChess do this?

A chessboard has 64 squares — exactly the width of a modern 64-bit CPU register. Instead of looping over square arrays to ask where pieces stand, BalouChess stores 64-bit integer bitboards per color and piece kind so entire ranks, files, and attack sets can be intersected in a single bitwise instruction.

Sliding pieces (rooks, bishops, queens) depend on blockers along their rays. Precomputed magic bitboard tables turn any blocker configuration on a square into a constant-time array lookup, while synchronized board state restoration ensures every explored search branch leaves the parent position untouched.

Data Layout, Invariants & Common Pitfalls

Memory & State Layout

Board and Position maintain per-color occupancy bitboards occupied: [u64; 2], color-by-piece bitboards pieces: [[u64; 6]; 2], a redundant 64-entry mailbox array squares: [Option<Piece>; 64] for O(1) piece-on-square queries, standard 4-bit castling rights castling: u8 (KQkq for standard chess; rook-file Chess960 castling is specified in engine, SPEC 001/R15 but not built yet), optional en-passant square, saturating u32 halfmove/fullmove counters, and a deterministic 64-bit Zobrist PositionKey.

Formal Invariants

  • Dual representation consistency (engine, SPEC 001/R1): after every make, unmake, make_null, or from_fen operation, occupied, pieces, and the 64-square mailbox table agree on every square, and crates/core compiles under #![forbid(unsafe_code)].
  • Bit-exact roundtrip (engine, SPEC 001/R6, R7): make followed by unmake restores castling rights, en-passant target, clocks, and PositionKey bit-for-bit, and the incrementally updated Zobrist key matches a full recomputation from scratch.

Typical Pitfalls & Edge Cases

  • Hashing phantom en-passant squares: FEN strings record an en-passant target after any double pawn push even when no opposing pawn can legally capture it. BalouChess hashes the en-passant file into PositionKey only when an en-passant capture is actually legal (engine, SPEC 001/R8), preventing false transposition misses.
  • Heap allocations in hot move generation: MoveList uses a fixed stack capacity sufficient for every legal chess position (engine, SPEC 001 §4), avoiding allocator contention inside recursive alpha-beta search.