syzygy1 / Rustfish

Rust port of Stockfish
GNU General Public License v3.0
30 stars 4 forks source link

Shift right would overflow #4

Closed sengerts closed 3 years ago

sengerts commented 3 years ago

I am getting the following errors in the bitboard module while compiling the source code: image

The code affected by these errors is the following:

// Compute the attack's index using the 'magic bitboards' approach
fn index_bishop(s: Square, occupied: Bitboard) -> usize {
    unsafe {
        u64::wrapping_mul((occupied & BISHOP_MAGICS.masks[s.0 as usize]).0,
            BISHOP_MAGICS.magics[s.0 as usize]) as usize >> (64-9)
    }
}

fn index_rook(s: Square, occupied: Bitboard) -> usize {
    unsafe {
        u64::wrapping_mul((occupied & ROOK_MAGICS.masks[s.0 as usize]).0,
            ROOK_MAGICS.magics[s.0 as usize]) as usize >> (64-12)
    }
}

Do you know why this error occurs or what I can do to fix the overflow?

sengerts commented 3 years ago

Can I jsut use a wrapping_shr on the usize value or will this differ from the intended semantics?

niklasf commented 3 years ago

Looks like usize has less than 64 bits on your platform. The intention is to do the shift first in u64, then cast to usize:

(u64::wrapping_mul(
    (occupied & ROOK_MAGICS.masks[s.0 as usize]).0,
    ROOK_MAGICS.magics[s.0 as usize]
) >> (64-12)) as usize
syzygy1 commented 3 years ago

Yes, this looks like a bug, and @niklasf 's fix seems correct.

sengerts commented 3 years ago

Thank you both! I have forked the repo and created a pull request.