Skip to main content

search_core/
budget.rs

1//! Early stopping: the [`Budget`] trait over a crate's own statistics type.
2
3/// Decides when a search must stop before it finishes, given its counters so far.
4///
5/// `T` is the statistics type of the algorithm, such as a struct with `expanded` and
6/// `generated` counters. Each search crate defines its own statistics and limits (the
7/// counters differ between graph search and MDP solvers) and implements `Budget<Stats>` for
8/// them; this trait lets budget adapters, such as a wall-clock deadline in a `std` crate, be
9/// written once for every algorithm.
10///
11/// Algorithms ask the budget before each unit of work, so a limit of `n` stops after exactly
12/// `n` units. Implemented for every `FnMut(&T) -> bool`; annotate the closure argument
13/// (`|stats: &Stats| ...`), since the type cannot be inferred through the blanket impl.
14///
15/// # Examples
16///
17/// ```
18/// use search_core::Budget;
19///
20/// /// The counters of some search.
21/// struct Stats {
22///     expanded: u64,
23/// }
24///
25/// /// A search crate's limits.
26/// struct Limits {
27///     max_expansions: Option<u64>,
28/// }
29///
30/// impl Budget<Stats> for Limits {
31///     fn exhausted(&mut self, stats: &Stats) -> bool {
32///         self.max_expansions.is_some_and(|max| stats.expanded >= max)
33///     }
34/// }
35///
36/// fn stops(mut budget: impl Budget<Stats>, expanded: u64) -> bool {
37///     budget.exhausted(&Stats { expanded })
38/// }
39///
40/// assert!(stops(Limits { max_expansions: Some(3) }, 3));
41/// assert!(!stops(Limits { max_expansions: None }, 3));
42/// assert!(stops(|stats: &Stats| stats.expanded > 1, 2));
43/// ```
44pub trait Budget<T> {
45    /// Returns `true` if the search must stop now, given the counters so far.
46    fn exhausted(&mut self, stats: &T) -> bool;
47}
48
49impl<T, F: FnMut(&T) -> bool> Budget<T> for F {
50    fn exhausted(&mut self, stats: &T) -> bool {
51        self(stats)
52    }
53}