use search_core::Budget;
use crate::table::Memory;
use crate::{Deepening, Game, SearchResult, Searcher, Stats};
pub trait Incremental: Game {
type Undo;
fn make(&self, position: &mut Self::Position, mv: &Self::Move) -> Self::Undo;
fn unmake(&self, position: &mut Self::Position, mv: &Self::Move, undo: Self::Undo);
}
pub(crate) trait Place<G: Game> {
type Child: Place<G>;
fn position(&self) -> &G::Position;
fn descend<R>(&mut self, game: &G, mv: &G::Move, then: impl FnOnce(&mut Self::Child) -> R)
-> R;
}
pub(crate) struct Borrowed<'a, P>(pub(crate) &'a P);
pub(crate) struct Owned<P>(P);
pub(crate) struct InPlace<P>(pub(crate) P);
impl<G: Game> Place<G> for Borrowed<'_, G::Position> {
type Child = Owned<G::Position>;
#[inline]
fn position(&self) -> &G::Position {
self.0
}
#[inline]
fn descend<R>(
&mut self,
game: &G,
mv: &G::Move,
then: impl FnOnce(&mut Owned<G::Position>) -> R,
) -> R {
then(&mut Owned(game.play(self.0, mv)))
}
}
impl<G: Game> Place<G> for Owned<G::Position> {
type Child = Self;
#[inline]
fn position(&self) -> &G::Position {
&self.0
}
#[inline]
fn descend<R>(&mut self, game: &G, mv: &G::Move, then: impl FnOnce(&mut Self) -> R) -> R {
then(&mut Self(game.play(&self.0, mv)))
}
}
impl<G: Incremental> Place<G> for InPlace<G::Position> {
type Child = Self;
#[inline]
fn position(&self) -> &G::Position {
&self.0
}
#[inline]
fn descend<R>(&mut self, game: &G, mv: &G::Move, then: impl FnOnce(&mut Self) -> R) -> R {
let undo = game.make(&mut self.0, mv);
let result = then(self);
game.unmake(&mut self.0, mv, undo);
result
}
}
impl<G: Incremental, T: Memory<G>> Searcher<G, T>
where
G::Position: Clone,
{
#[must_use]
pub fn search_in_place(
&mut self,
game: &G,
position: &G::Position,
depth: u32,
) -> SearchResult<G::Move, G::Score> {
self.search_from(game, &mut InPlace(position.clone()), depth)
}
#[must_use]
pub fn deepen_in_place(
&mut self,
game: &G,
position: &G::Position,
max_depth: u32,
budget: impl Budget<Stats>,
) -> SearchResult<G::Move, G::Score> {
let always = |_: &SearchResult<G::Move, G::Score>| true;
self.deepen_in_place_with(game, position, max_depth, budget, always)
}
#[must_use]
pub fn deepen_in_place_with(
&mut self,
game: &G,
position: &G::Position,
max_depth: u32,
budget: impl Budget<Stats>,
deepening: impl Deepening<G::Move, G::Score>,
) -> SearchResult<G::Move, G::Score> {
let mut here = InPlace(position.clone());
self.deepen_from(game, &mut here, max_depth, budget, deepening)
}
}