Files
zeal/src/search/transposition_table.rs

119 lines
3.0 KiB
Rust

use crate::{board::zobrist::ZobristHash, movegen::r#move::Move};
use super::TT_SIZE_IN_MB;
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct TranspositionTable {
positions: Vec<Option<TTEntry>>,
size: u64,
}
impl TranspositionTable {
pub fn new() -> Self {
Self::with_capacity(TT_SIZE_IN_MB)
}
pub fn with_capacity(size_in_mb: usize) -> Self {
let size_in_bytes = size_in_mb * 1024 * 1024;
let num_of_entries = size_in_bytes / std::mem::size_of::<TTEntry>();
Self {
positions: vec![None; num_of_entries],
size: num_of_entries as u64,
}
}
pub fn lookup(&self, zobrist_hash: ZobristHash) -> Option<TTEntry> {
self.positions
.get((zobrist_hash.0 % self.size) as usize)
.and_then(|entry| *entry)
}
pub fn insert(&mut self, entry: TTEntry) {
let idx = (entry.hash.0 % self.size) as usize;
self.positions[idx] = Some(entry);
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct TTEntry {
pub hash: ZobristHash,
pub mv: Option<Move>,
pub depth: u8,
pub score: i16,
pub node_type: NodeType,
}
impl TTEntry {
pub const fn new(
hash: ZobristHash,
mv: Option<Move>,
depth: u8,
score: i16,
node_type: NodeType,
) -> Self {
Self {
hash,
mv,
depth,
score,
node_type,
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum NodeType {
Exact,
LowerBound,
UpperBound,
}
impl NodeType {
pub fn cutoff_eligible(self, score: i16, alpha: i16, beta: i16) -> bool {
self == Self::Exact
|| self == Self::LowerBound && score >= beta
|| self == Self::UpperBound && score <= alpha
}
}
#[cfg(test)]
mod tests {
use crate::{
board::fen::from_fen,
evaluation::{MAX_SCORE, MIN_SCORE},
movegen::attack_generator::init_attacks,
search::{negamax::negamax, time::TimeInfo, INC, TIME},
};
const FEN: &str = "1r2k2r/2P1pq1p/2npb3/1p3ppP/p3P3/P2B1Q2/1P1PNPP1/R3K2R w KQk g6 0 1";
const FEN_POSSIBLE: &str = "1r2k2r/2P1pq1p/2npb3/1B3ppP/p3P3/P4Q2/1P1PNPP1/R3K2R b KQk - 0 1";
const FEN_IMPOSSIBLE: &str = "1Q2k2r/2P1pq1p/2npb3/1p3ppP/p3P3/P2B4/1P1PNPP1/R3K2R b KQk - 0 1";
#[test]
fn test_transposition_table() -> anyhow::Result<()> {
init_attacks();
let mut game = from_fen(FEN).unwrap();
let time_info = TimeInfo::new(std::time::Instant::now(), TIME, INC);
negamax(
&mut game, MIN_SCORE, MAX_SCORE, 3, 0, &time_info, &mut 0, true,
)
.expect("Expected a search result");
dbg!(time_info.instant.elapsed());
let will_be_hash = from_fen(FEN_POSSIBLE).unwrap().hash;
let entry = game.tt.lookup(will_be_hash);
assert!(entry.is_some());
let wont_be_hash = from_fen(FEN_IMPOSSIBLE).unwrap().hash;
let entry = game.tt.lookup(wont_be_hash);
assert!(entry.is_none());
Ok(())
}
}