search_core/cost/ext.rs
1//! Priority arithmetic on costs: [`CostExt`] adds saturating subtraction and a
2//! conversion to `f64`, which [`Cost`] deliberately lacks.
3
4#[cfg(feature = "float")]
5use super::NonNegF64;
6use super::{Cost, Decimal};
7
8/// Priority arithmetic that [`Cost`] lacks: subtraction and conversion to `f64`.
9///
10/// Some searches order nodes by priorities that subtract or divide costs: the `(G - g) / h`
11/// order of anytime nonparametric A*, the `2g + h - h_opposite` key of front-to-end
12/// bidirectional searches, or a potential such as dynamic potential search. Those searches
13/// require this trait; every other search needs [`Cost`] alone. Like [`WideMul`] and
14/// [`ExactArith`], it is a separate trait, so cost types without it keep working.
15///
16/// | Cost | `saturating_sub` | `to_f64` |
17/// |---|---|---|
18/// | `u8` to `u128`, `usize` | saturates at `0` | nearest float; exact up to `2^53` |
19/// | [`Decimal<K>`] | on raw units, saturates at `0` | the raw unit count, **not** divided by `10^K` |
20/// | `NonNegF64` (feature `float`) | clamps at `0`, also `∞ - ∞` | the value itself |
21///
22/// A user-defined cost type implements it next to [`Cost`].
23///
24/// [`WideMul`]: crate::WideMul
25/// [`ExactArith`]: crate::ExactArith
26///
27/// # Examples
28///
29/// ```
30/// use search_core::{CostExt, Decimal};
31///
32/// assert_eq!(CostExt::saturating_sub(3_u32, 5), 0);
33/// assert_eq!(7_u64.to_f64(), 7.0);
34///
35/// // Decimal converts its raw units: 1.50 at scale 10^2 is 150.
36/// assert_eq!(Decimal::<2>::from_raw(150).to_f64(), 150.0);
37/// ```
38pub trait CostExt: Cost {
39 /// Subtracts `other`, saturating at [`Cost::ZERO`].
40 ///
41 /// For priorities that subtract one estimate from another, such as a `G - g` slack.
42 #[must_use]
43 fn saturating_sub(self, other: Self) -> Self;
44
45 /// The cost as a float, possibly rounded; for [`Decimal<K>`] the raw units, scaled by
46 /// `10^K`.
47 ///
48 /// Only for priorities that divide costs, such as a `(G - g) / h` order. Rounding can
49 /// change the expansion order among nearly equal priorities, but never a returned cost.
50 /// Within one cost type the result is proportional to the cost, so quotients and the
51 /// order of differences are what the exact values give, up to rounding. Do not compare
52 /// the result against a threshold in cost units: for [`Decimal<K>`] it is off by `10^K`.
53 #[must_use]
54 fn to_f64(self) -> f64;
55}
56
57/// Implements [`CostExt`] for unsigned integer types, each with its conversion to `f64`.
58macro_rules! integer_cost_ext {
59 ($($ty:ty => $to_f64:path),*) => {
60 $(
61 impl CostExt for $ty {
62 fn saturating_sub(self, other: Self) -> Self {
63 <$ty>::saturating_sub(self, other)
64 }
65
66 fn to_f64(self) -> f64 {
67 $to_f64(self)
68 }
69 }
70 )*
71 };
72}
73
74integer_cost_ext!(
75 u8 => f64::from,
76 u16 => f64::from,
77 u32 => f64::from,
78 u64 => u64_to_f64,
79 u128 => u128_to_f64,
80 usize => usize_to_f64
81);
82
83/// Converts a `u64` cost to the nearest float, for priorities only.
84#[expect(clippy::cast_precision_loss, reason = "only used for priorities")]
85fn u64_to_f64(cost: u64) -> f64 {
86 cost as f64
87}
88
89/// Converts a `u128` cost to the nearest float, for priorities only.
90#[expect(clippy::cast_precision_loss, reason = "only used for priorities")]
91fn u128_to_f64(cost: u128) -> f64 {
92 cost as f64
93}
94
95/// Converts a `usize` cost to the nearest float, for priorities only.
96#[expect(clippy::cast_precision_loss, reason = "only used for priorities")]
97fn usize_to_f64(cost: usize) -> f64 {
98 cost as f64
99}
100
101impl<const K: u32> CostExt for Decimal<K> {
102 fn saturating_sub(self, other: Self) -> Self {
103 Self::from_raw(self.raw().saturating_sub(other.raw()))
104 }
105
106 /// The raw unit count as a float: the value scaled by `10^K`.
107 ///
108 /// Priorities only compare quotients and differences of costs of one type, so the common
109 /// factor `10^K` cancels, and dividing it out would only add rounding.
110 fn to_f64(self) -> f64 {
111 u64_to_f64(self.raw())
112 }
113}
114
115#[cfg(feature = "float")]
116impl CostExt for NonNegF64 {
117 /// Subtracts `other`, clamping at zero; `∞ - ∞` is zero.
118 fn saturating_sub(self, other: Self) -> Self {
119 // `f64::max` returns `0.0` for a NaN difference, which only `∞ - ∞` produces.
120 Self::new((self.get() - other.get()).max(0.0)).unwrap_or(Self::ZERO)
121 }
122
123 fn to_f64(self) -> f64 {
124 self.get()
125 }
126}
127
128#[cfg(test)]
129mod tests {
130 //! Unit and property tests for the [`CostExt`] implementations.
131
132 use proptest::prelude::*;
133
134 use super::{CostExt, Decimal};
135
136 /// Integer subtraction saturates at zero and converts exactly for small values.
137 #[test]
138 fn integers_saturate_and_convert() {
139 assert_eq!(CostExt::saturating_sub(2_u8, 5), 0);
140 assert_eq!(CostExt::saturating_sub(9_u128, 4), 5);
141 assert_eq!(CostExt::saturating_sub(7_usize, 7), 0);
142 assert!((CostExt::to_f64(3_u16) - 3.0).abs() < f64::EPSILON);
143 assert!((CostExt::to_f64(u64::from(u32::MAX)) - f64::from(u32::MAX)).abs() < 1.0);
144 }
145
146 /// Decimals subtract on raw units and convert to the raw unit count.
147 #[test]
148 fn decimals_use_raw_units() {
149 let a = Decimal::<2>::from_raw(150);
150 let b = Decimal::<2>::from_raw(25);
151
152 assert_eq!(a.saturating_sub(b), Decimal::from_raw(125));
153 assert_eq!(b.saturating_sub(a), Decimal::from_raw(0));
154 assert!((a.to_f64() - 150.0).abs() < f64::EPSILON);
155 }
156
157 /// Float subtraction clamps at zero, also for `∞ - ∞`.
158 #[cfg(feature = "float")]
159 #[test]
160 fn floats_clamp_at_zero() {
161 use crate::{Cost, NonNegF64};
162
163 let half = NonNegF64::new(0.5).expect("non-negative");
164 let two = NonNegF64::new(2.0).expect("non-negative");
165
166 assert_eq!(
167 two.saturating_sub(half),
168 NonNegF64::new(1.5).expect("non-negative")
169 );
170 assert_eq!(half.saturating_sub(two), NonNegF64::ZERO);
171 assert_eq!(
172 NonNegF64::INFINITY.saturating_sub(NonNegF64::INFINITY),
173 NonNegF64::ZERO
174 );
175 assert_eq!(NonNegF64::INFINITY.saturating_sub(two), NonNegF64::INFINITY);
176 assert!((two.to_f64() - 2.0).abs() < f64::EPSILON);
177 }
178
179 proptest! {
180 /// Subtraction undoes addition and never goes below zero.
181 #[test]
182 fn subtraction_inverts_addition(a in 0..u64::MAX / 2, b in 0..u64::MAX / 2) {
183 prop_assert_eq!(CostExt::saturating_sub(a + b, b), a);
184 prop_assert_eq!(CostExt::saturating_sub(b, a + b + 1), 0);
185 }
186
187 /// The float conversion preserves the order of costs.
188 #[test]
189 fn conversion_is_monotone(a: u64, b: u64) {
190 if a <= b {
191 prop_assert!(a.to_f64() <= b.to_f64());
192 }
193 }
194 }
195}