Move RNG code to its own module

This commit is contained in:
Bruno BELANYI 2024-04-06 17:56:09 +01:00
parent b2560aa183
commit a667e6b7f2
5 changed files with 52 additions and 36 deletions

View file

@ -5,10 +5,10 @@ use crate::{
movegen::{
naive,
wizardry::{
generate_bishop_magics, generate_rook_magics, MagicMoves, RandGen, BISHOP_SEED,
ROOK_SEED,
generate_bishop_magics, generate_rook_magics, MagicMoves, BISHOP_SEED, ROOK_SEED,
},
},
utils::RandGen,
};
// A pre-rolled RNG for magic bitboard generation, using pre-determined values.

View file

@ -1,14 +1,10 @@
use crate::board::{Bitboard, Square};
use crate::movegen::naive::{bishop_moves, rook_moves};
use crate::utils::RandGen;
use super::mask::{generate_bishop_mask, generate_rook_mask};
use super::Magic;
/// A trait to represent RNG for u64 values.
pub(crate) trait RandGen {
fn gen(&mut self) -> u64;
}
type MagicGenerationType = (Vec<Magic>, Vec<Bitboard>);
pub fn generate_bishop_magics(rng: &mut dyn RandGen) -> MagicGenerationType {

View file

@ -200,35 +200,7 @@ mod test {
use std::fmt::Write as _;
use super::*;
// A simple XOR-shift RNG implementation.
struct SimpleRng(u64);
impl SimpleRng {
pub fn new() -> Self {
Self(4) // https://xkcd.com/221/
}
}
impl RandGen for SimpleRng {
fn gen(&mut self) -> u64 {
self.0 ^= self.0 >> 12;
self.0 ^= self.0 << 25;
self.0 ^= self.0 >> 27;
self.0
}
}
#[test]
fn rng() {
let mut rng = SimpleRng::new();
assert_eq!(rng.gen(), 134217733);
assert_eq!(rng.gen(), 4504699139039237);
assert_eq!(rng.gen(), 13512173405898766);
assert_eq!(rng.gen(), 9225626310854853124);
assert_eq!(rng.gen(), 29836777971867270);
}
use crate::utils::SimpleRng;
fn split_twice<'a>(
text: &'a str,

View file

@ -1,2 +1,5 @@
pub(crate) mod rand;
pub(crate) use rand::*;
pub mod static_assert;
pub use static_assert::*;

45
src/utils/rand.rs Normal file
View file

@ -0,0 +1,45 @@
/// A trait to represent RNG for u64 values.
pub trait RandGen {
fn gen(&mut self) -> u64;
}
// A simple XOR-shift RNG implementation, for code-generation.
#[cfg(test)]
pub struct SimpleRng(u64);
#[cfg(test)]
impl SimpleRng {
pub fn new() -> Self {
Self(4) // https://xkcd.com/221/
}
pub fn gen(&mut self) -> u64 {
self.0 ^= self.0 >> 12;
self.0 ^= self.0 << 25;
self.0 ^= self.0 >> 27;
self.0
}
}
#[cfg(test)]
impl RandGen for SimpleRng {
fn gen(&mut self) -> u64 {
self.gen()
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn rng() {
let mut rng = SimpleRng::new();
assert_eq!(rng.gen(), 134217733);
assert_eq!(rng.gen(), 4504699139039237);
assert_eq!(rng.gen(), 13512173405898766);
assert_eq!(rng.gen(), 9225626310854853124);
assert_eq!(rng.gen(), 29836777971867270);
}
}