search_core/budget.rs
1//! Early stopping and time slicing: the [`Budget`] trait over a crate's own statistics type,
2//! the never-exhausted budget [`Unlimited`], and the [`Status`] a sliced search reports.
3
4/// Decides when a search must stop before it finishes, given its counters so far.
5///
6/// `T` is the statistics type of the algorithm, such as a struct with `expanded` and
7/// `generated` counters. Each search crate defines its own statistics and limits (the
8/// counters differ between graph search and MDP solvers) and implements `Budget<Stats>` for
9/// them; this trait lets budget adapters, such as a wall-clock deadline in a `std` crate, be
10/// written once for every algorithm.
11///
12/// Algorithms ask the budget before each unit of work, so a limit of `n` stops after exactly
13/// `n` units. In a time-sliced search the counters start from zero in each start or resume
14/// call, so a budget is the allowance of one slice (see [`Status`]). Budgets are taken by
15/// value; to keep a struct budget's state across slices, pass a closure that borrows it:
16/// `&mut |s: &T| limits.exhausted(s)`.
17///
18/// Implemented for every `FnMut(&T) -> bool`; annotate the closure argument
19/// (`|stats: &Stats| ...`), since the type cannot be inferred through the blanket impl.
20///
21/// # Examples
22///
23/// ```
24/// use search_core::Budget;
25///
26/// /// The counters of some search.
27/// struct Stats {
28/// expanded: u64,
29/// }
30///
31/// /// A search crate's limits.
32/// struct Limits {
33/// max_expansions: Option<u64>,
34/// }
35///
36/// impl Budget<Stats> for Limits {
37/// fn exhausted(&mut self, stats: &Stats) -> bool {
38/// self.max_expansions.is_some_and(|max| stats.expanded >= max)
39/// }
40/// }
41///
42/// fn stops(mut budget: impl Budget<Stats>, expanded: u64) -> bool {
43/// budget.exhausted(&Stats { expanded })
44/// }
45///
46/// assert!(stops(Limits { max_expansions: Some(3) }, 3));
47/// assert!(!stops(Limits { max_expansions: None }, 3));
48/// assert!(stops(|stats: &Stats| stats.expanded > 1, 2));
49/// ```
50pub trait Budget<T> {
51 /// Returns `true` if the search must stop now, given the counters so far.
52 fn exhausted(&mut self, stats: &T) -> bool;
53}
54
55impl<T, F: FnMut(&T) -> bool> Budget<T> for F {
56 fn exhausted(&mut self, stats: &T) -> bool {
57 self(stats)
58 }
59}
60
61/// A budget that is never exhausted: the search runs until it finishes.
62///
63/// # Examples
64///
65/// ```
66/// use search_core::{Budget, Unlimited};
67///
68/// assert!(!Unlimited.exhausted(&u64::MAX));
69/// ```
70#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
71pub struct Unlimited;
72
73impl<T> Budget<T> for Unlimited {
74 fn exhausted(&mut self, _stats: &T) -> bool {
75 false
76 }
77}
78
79/// How one call of a time-sliced search ended: it finished, or its [`Budget`] stopped it.
80///
81/// A search that can be spread over several frames returns this from its start and resume
82/// calls. After [`Status::OutOfBudget`], the search keeps its state in its workspace, and
83/// the crate's resume call continues where it stopped. The resume call itself is
84/// crate-specific, since what a search needs to continue differs between algorithms.
85///
86/// Non-exhaustive, so that searches can gain further outcomes without a breaking change;
87/// matches outside this crate need a `_` arm.
88///
89/// # Examples
90///
91/// A countdown sliced over two frames, then run to the end:
92///
93/// ```
94/// use search_core::{Budget, Status, Unlimited};
95///
96/// /// A resumable search: counts `left` down to zero, one unit of work per step.
97/// struct Countdown {
98/// left: u32,
99/// }
100///
101/// impl Countdown {
102/// /// Continues the run. The budget sees the units done in this call only.
103/// fn resume(&mut self, mut budget: impl Budget<u32>) -> Status {
104/// let mut done = 0;
105/// while self.left > 0 {
106/// if budget.exhausted(&done) {
107/// return Status::OutOfBudget;
108/// }
109///
110/// self.left -= 1;
111/// done += 1;
112/// }
113///
114/// Status::Finished
115/// }
116/// }
117///
118/// let mut search = Countdown { left: 5 };
119/// let mut frames = 0;
120/// let mut per_frame = |done: &u32| {
121/// frames += 1;
122/// *done >= 2
123/// };
124///
125/// assert_eq!(search.resume(&mut per_frame), Status::OutOfBudget);
126/// assert_eq!(search.left, 3);
127/// assert_eq!(search.resume(&mut per_frame), Status::OutOfBudget);
128/// assert_eq!(search.left, 1);
129/// assert_eq!(search.resume(Unlimited), Status::Finished);
130/// assert_eq!(frames, 6);
131/// ```
132#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
133#[non_exhaustive]
134pub enum Status {
135 /// The search did all its work.
136 Finished,
137 /// The budget stopped the search before it finished; resuming continues it.
138 OutOfBudget,
139}