Skip to main content

search_core/
lib.rs

1//! # Search core
2//!
3//! Shared cost, heuristic, goal and budget traits for search and planning crates, with exact
4//! `no_std` cost types.
5//!
6//! The crate holds what at least two independent search crates need, so that a heuristic,
7//! goal test or budget written once works with every algorithm of the ecosystem, plus the
8//! small vocabulary types of the shared [conventions](#many-agents-threads-and-frames):
9//!
10//! - [`Cost`]: a non-negative, totally ordered scalar path cost. Implemented for the unsigned
11//!   integers (the ecosystem default is `u32`), the fixed-point [`Decimal`] with scale `10^K`,
12//!   the tie-breaking pair [`Lexicographic`], and, behind the `float` feature, the checked
13//!   float `NonNegF64`.
14//! - [`CostExt`]: saturating subtraction and a (possibly rounding) conversion to `f64`, for
15//!   priorities that subtract or divide costs; also separate from [`Cost`].
16//! - [`WideMul`]: the exact product of two costs in a wider type, for comparing cost ratios
17//!   by cross-multiplication. Separate from [`Cost`], so cost types without it still work.
18//! - [`ExactArith`] (feature `alloc`): costs into an exact number type ([`BigUint`]) for
19//!   sums of products and longer products; also separate from [`Cost`]. [`BigInt`] holds
20//!   their differences, which may be negative.
21//! - [`Heuristic`]: a cost-to-go estimate with a mutable workspace, plus [`heuristic_fn`] for
22//!   closures and the blind heuristic [`Zero`].
23//! - [`Goal`]: a goal test, implemented for closures.
24//! - [`Budget`]: early stopping over a crate's own statistics type, implemented for closures,
25//!   with the never-exhausted [`Unlimited`] and the [`Status`] of a time-sliced search.
26//!
27//! There is no single "search problem" trait. Each algorithm asks for the capabilities it
28//! needs, and successor generation stays in the algorithm crates, whose graph shapes differ.
29//!
30//! ```mermaid
31//! graph LR
32//!     algo[search algorithm] -->|estimate| Heuristic
33//!     algo -->|is_goal| Goal
34//!     algo -->|exhausted| Budget
35//!     algo -->|sums, compares| Cost
36//!     Heuristic -.->|"C: Cost (for Zero)"| Cost
37//! ```
38//!
39//! ## Many agents, threads and frames
40//!
41//! Game AI and simulations run many searches per frame, for many entities. The planning
42//! crates follow the same conventions for that:
43//!
44//! 1. **Shareable inputs.** Graphs, maps, games and models are `Send + Sync` and free of
45//!    interior mutability, so one instance serves every thread by reference.
46//! 2. **Reusable workspaces.** Everything a query mutates (open list, closed set, tables,
47//!    heuristic caches) lives in an explicit workspace that is reused across queries, so a
48//!    warmed-up query allocates nothing. Each thread owns its workspaces; [`Heuristic`]
49//!    takes `&mut self` for this reason.
50//! 3. **Time slicing.** Searches ask their [`Budget`] before each unit of work, so a limit
51//!    of `n` stops after exactly `n` units, and report a [`Status`]. The counters the budget
52//!    sees start from zero in every call, so a budget is the allowance of one slice. After
53//!    [`Status::OutOfBudget`], a crate-specific resume call continues from the workspace;
54//!    resuming a finished search should do no work. [`Unlimited`] runs to the end. Budgets are
55//!    taken by value: pass `&mut closure` to keep a closure's state across slices.
56//! 4. **Opt-in parallelism.** Parallel algorithms live behind a `parallel` feature; the
57//!    default build stays `no_std`.
58//!
59//! Every type of this crate is `Send + Sync` when its type parameters are.
60//!
61//! ## Features
62//!
63//! - `alloc` (default): `Heuristic` for `Box<H>`; [`ExactArith`] with [`BigUint`] and
64//!   [`BigInt`].
65//! - `float`: the `NonNegF64` cost.
66//!
67//! The crate is `no_std` in every configuration.
68//!
69//! ## Example
70//!
71//! ```
72//! use search_core::{Budget, Cost, Goal, Heuristic, heuristic_fn};
73//!
74//! /// Greedy descent on a number line: a toy algorithm using all four traits.
75//! fn descend<C: Cost>(
76//!     mut state: u32,
77//!     goal: &impl Goal<u32>,
78//!     mut h: impl Heuristic<u32, C>,
79//!     mut budget: impl Budget<u64>,
80//! ) -> Option<u32> {
81//!     let mut steps = 0_u64;
82//!     while !goal.is_goal(&state) {
83//!         if budget.exhausted(&steps) {
84//!             return None;
85//!         }
86//!
87//!         h.estimate(&state)?;
88//!         state -= 1;
89//!         steps += 1;
90//!     }
91//!
92//!     Some(state)
93//! }
94//!
95//! let h = heuristic_fn(|s: &u32| Some(*s));
96//! assert_eq!(descend(5, &|s: &u32| *s == 2, h, |n: &u64| *n >= 10), Some(2));
97//! assert_eq!(descend(5, &|s: &u32| *s == 2, h, |n: &u64| *n >= 1), None);
98//! ```
99//!
100//! Repository: <https://github.com/sunsided/search-core>
101
102#![no_std]
103#![forbid(unsafe_code)]
104
105#[cfg(feature = "alloc")]
106extern crate alloc;
107
108mod budget;
109mod cost;
110mod goal;
111mod heuristic;
112
113pub use budget::{Budget, Status, Unlimited};
114#[cfg(feature = "float")]
115pub use cost::NonNegF64;
116#[cfg(feature = "alloc")]
117pub use cost::{BigInt, BigUint, ExactArith, ExactNumber};
118pub use cost::{Cost, CostExt, Decimal, Lexicographic, ParseDecimalError, WideMul};
119pub use goal::Goal;
120pub use heuristic::{Heuristic, HeuristicFn, Zero, heuristic_fn};
121
122/// Doctests for the code examples in README.md (not part of the API).
123#[cfg(doctest)]
124#[doc = include_str!("../README.md")]
125mod readme_doctests {}