search_core/heuristic.rs
1//! Cost-to-go estimates: the [`Heuristic`] trait, [`heuristic_fn`] for closures and the blind
2//! heuristic [`Zero`].
3
4#[cfg(feature = "alloc")]
5use alloc::boxed::Box;
6
7use crate::cost::Cost;
8
9/// An estimate of the cost from a state of type `S` to the nearest goal, in cost type `C`.
10///
11/// `estimate` takes `&mut self`, so a heuristic can keep a reusable workspace (scratch
12/// buffers, caches) without interior mutability. Searches take the heuristic by value and own
13/// it for the run; pass `&mut h` to keep `h` and its workspace afterwards. Share read-only
14/// tables by reference and create one heuristic per thread.
15///
16/// `C` defaults to `u32` and is deliberately unbounded: scalar searches use a [`Cost`],
17/// multi-objective searches a cost vector such as `[u32; 2]`, and probabilistic planners an
18/// expected cost such as `f64`. Each algorithm states what it requires (admissibility,
19/// consistency).
20///
21/// Implemented for `&mut H` and (feature `alloc`) `Box<H>` of any heuristic `H`, so
22/// `Box<dyn Heuristic<S, C>>` works; for [`Zero`]; and for closures through
23/// [`heuristic_fn`]. A blanket impl for closures cannot coexist with the one for `&mut H`,
24/// because `&mut F` is itself a closure (E0119).
25///
26/// # Examples
27///
28/// A heuristic with a workspace:
29///
30/// ```
31/// use search_core::Heuristic;
32///
33/// /// Counts how often it was asked; a real heuristic would reuse buffers here.
34/// struct Distance {
35/// target: u32,
36/// calls: usize,
37/// }
38///
39/// impl Heuristic<u32> for Distance {
40/// fn estimate(&mut self, state: &u32) -> Option<u32> {
41/// self.calls += 1;
42/// self.target.checked_sub(*state)
43/// }
44/// }
45///
46/// let mut h = Distance { target: 10, calls: 0 };
47/// assert_eq!(h.estimate(&4), Some(6));
48/// assert_eq!((&mut h).estimate(&11), None);
49/// assert_eq!(h.calls, 2);
50/// ```
51pub trait Heuristic<S, C = u32> {
52 /// Estimates the remaining cost from `state` to a goal.
53 ///
54 /// `None` means no goal is reachable from `state` (a proven dead end). Searches drop such
55 /// states, so a heuristic must only return `None` when that is certain.
56 fn estimate(&mut self, state: &S) -> Option<C>;
57}
58
59impl<S, C, H: Heuristic<S, C> + ?Sized> Heuristic<S, C> for &mut H {
60 fn estimate(&mut self, state: &S) -> Option<C> {
61 (**self).estimate(state)
62 }
63}
64
65#[cfg(feature = "alloc")]
66impl<S, C, H: Heuristic<S, C> + ?Sized> Heuristic<S, C> for Box<H> {
67 fn estimate(&mut self, state: &S) -> Option<C> {
68 (**self).estimate(state)
69 }
70}
71
72/// Turns a closure `FnMut(&S) -> Option<C>` into a [`Heuristic`].
73///
74/// # Examples
75///
76/// ```
77/// use search_core::{Heuristic, heuristic_fn};
78///
79/// let mut calls = 0;
80/// let mut h = heuristic_fn(|n: &u32| {
81/// calls += 1;
82/// 10_u32.checked_sub(*n)
83/// });
84///
85/// assert_eq!(h.estimate(&3), Some(7));
86/// assert_eq!(h.estimate(&12), None);
87/// drop(h);
88/// assert_eq!(calls, 2);
89/// ```
90pub fn heuristic_fn<S, C, F: FnMut(&S) -> Option<C>>(f: F) -> HeuristicFn<F> {
91 HeuristicFn(f)
92}
93
94/// A closure used as a [`Heuristic`]; created by [`heuristic_fn`].
95#[derive(Debug, Clone, Copy)]
96pub struct HeuristicFn<F>(F);
97
98impl<S, C, F: FnMut(&S) -> Option<C>> Heuristic<S, C> for HeuristicFn<F> {
99 fn estimate(&mut self, state: &S) -> Option<C> {
100 (self.0)(state)
101 }
102}
103
104/// The blind heuristic: estimates [`Cost::ZERO`] everywhere. Turns A* into Dijkstra's
105/// algorithm and is admissible and consistent for every non-negative cost.
106///
107/// Implemented for every scalar [`Cost`] and for raw `f64` values, which are not a `Cost`
108/// (they are not `Ord`) but are what value-iteration style searches estimate in. Cost
109/// vectors keep their own zero heuristic (see `MIGRATION.md`).
110///
111/// # Examples
112///
113/// ```
114/// use search_core::{Decimal, Heuristic, Zero};
115///
116/// assert_eq!(Heuristic::<&str>::estimate(&mut Zero, &"any"), Some(0_u32));
117/// assert_eq!(Heuristic::<u8, Decimal<2>>::estimate(&mut Zero, &1), Some(Decimal::from_raw(0)));
118/// assert_eq!(Heuristic::<u8, f64>::estimate(&mut Zero, &1), Some(0.0));
119/// ```
120#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
121pub struct Zero;
122
123impl<S, C: Cost> Heuristic<S, C> for Zero {
124 fn estimate(&mut self, _state: &S) -> Option<C> {
125 Some(C::ZERO)
126 }
127}
128
129/// Raw `f64` estimates: `f64` is not a [`Cost`], so this does not overlap the impl above.
130impl<S> Heuristic<S, f64> for Zero {
131 fn estimate(&mut self, _state: &S) -> Option<f64> {
132 Some(0.0)
133 }
134}