Skip to main content

search_core/
cost.rs

1//! Scalar path costs: the [`Cost`] trait, its integer implementations, the fixed-point
2//! [`Decimal`] and, behind the `float` feature, the checked float `NonNegF64`; and the exact
3//! cost-by-cost product [`WideMul`]; the priority arithmetic [`CostExt`]; and, with `alloc`,
4//! exact arithmetic of any size through [`ExactArith`].
5
6mod decimal;
7#[cfg(feature = "alloc")]
8mod exact;
9mod ext;
10#[cfg(feature = "float")]
11mod float;
12mod lexicographic;
13mod wide;
14
15use core::ops::Add;
16
17pub use decimal::{Decimal, ParseDecimalError};
18#[cfg(feature = "alloc")]
19pub use exact::{BigInt, BigUint, ExactArith, ExactNumber};
20pub use ext::CostExt;
21#[cfg(feature = "float")]
22pub use float::NonNegF64;
23pub use lexicographic::Lexicographic;
24pub use wide::WideMul;
25
26/// A non-negative scalar edge or path cost.
27///
28/// Searches add costs along a path and compare the sums. The default cost type of this
29/// ecosystem is `u32`.
30///
31/// # Contract
32///
33/// - **Non-negative.** Every value is `>=` [`Cost::ZERO`], so extending a path never makes it
34///   cheaper. This is why only unsigned integers implement the trait: a negative edge cost
35///   silently voids the optimality of Dijkstra, A* and their relatives.
36/// - **Total order.** [`Ord`] is the cost order; smaller is cheaper.
37/// - **`+` follows the underlying integer.** For the integer types and [`Decimal`], an
38///   overflowing `+` panics in debug builds and wraps in release builds, exactly like the
39///   primitive. Pick a type wide enough for the longest path, or use
40///   [`Cost::saturating_add`] where a sum only serves as a priority. `NonNegF64` never
41///   overflows; it reaches infinity instead.
42///
43/// Implemented for `u8`, `u16`, `u32`, `u64`, `u128`, `usize`, [`Decimal`], the pair
44/// [`Lexicographic`] and (feature `float`) `NonNegF64`.
45///
46/// # Examples
47///
48/// A function generic over the cost type:
49///
50/// ```
51/// use search_core::Cost;
52///
53/// fn path_cost<C: Cost>(edges: &[C]) -> C {
54///     edges.iter().fold(C::ZERO, |sum, &edge| sum + edge)
55/// }
56///
57/// assert_eq!(path_cost(&[3_u32, 4, 5]), 12);
58/// assert_eq!(path_cost::<u8>(&[]), 0);
59/// ```
60pub trait Cost: Copy + Ord + Add<Output = Self> {
61    /// The cost of the empty path, and the smallest value of the type.
62    const ZERO: Self;
63
64    /// Adds two costs, saturating at the largest value instead of overflowing.
65    ///
66    /// Used where a sum only serves as a priority, such as a weighted A* key.
67    #[must_use]
68    fn saturating_add(self, other: Self) -> Self;
69
70    /// Multiplies the cost by a small integer factor, saturating at the largest value.
71    ///
72    /// Used to compare weighted sums such as `den * g + num * h` without division. A factor
73    /// of `0` always yields [`Cost::ZERO`].
74    #[must_use]
75    fn saturating_times(self, factor: u32) -> Self;
76}
77
78/// Implements [`Cost`] for unsigned integer types that `u32` converts into losslessly.
79macro_rules! unsigned_cost {
80    ($($ty:ty),*) => {
81        $(
82            impl Cost for $ty {
83                const ZERO: Self = 0;
84
85                fn saturating_add(self, other: Self) -> Self {
86                    <$ty>::saturating_add(self, other)
87                }
88
89                fn saturating_times(self, factor: u32) -> Self {
90                    self.saturating_mul(<$ty>::from(factor))
91                }
92            }
93        )*
94    };
95}
96
97unsigned_cost!(u32, u64, u128);
98
99/// Implements [`Cost`] for unsigned integer types narrower than `u32`, where a factor that
100/// does not fit saturates the product unless the cost is zero.
101macro_rules! narrow_unsigned_cost {
102    ($($ty:ty),*) => {
103        $(
104            impl Cost for $ty {
105                const ZERO: Self = 0;
106
107                fn saturating_add(self, other: Self) -> Self {
108                    <$ty>::saturating_add(self, other)
109                }
110
111                fn saturating_times(self, factor: u32) -> Self {
112                    match <$ty>::try_from(factor) {
113                        Ok(factor) => self.saturating_mul(factor),
114                        Err(_) if self == 0 => 0,
115                        Err(_) => <$ty>::MAX,
116                    }
117                }
118            }
119        )*
120    };
121}
122
123narrow_unsigned_cost!(u8, u16, usize);
124
125#[cfg(test)]
126mod tests {
127    //! Unit and property tests for the integer [`Cost`] implementations.
128
129    use super::Cost;
130    use proptest::prelude::*;
131
132    /// Saturating addition stops at the maximum.
133    #[test]
134    fn saturating_add_saturates() {
135        assert_eq!(Cost::saturating_add(u8::MAX, 1), u8::MAX);
136        assert_eq!(Cost::saturating_add(3_u32, 4), 7);
137    }
138
139    /// Narrow types saturate on factors they cannot represent, except for a zero cost.
140    #[test]
141    fn narrow_times_saturates_on_wide_factor() {
142        assert_eq!(2_u8.saturating_times(300), u8::MAX);
143        assert_eq!(0_u8.saturating_times(300), 0);
144        assert_eq!(7_u16.saturating_times(3), 21);
145        assert_eq!(0_u16.saturating_times(u32::MAX), 0);
146    }
147
148    /// Wide types multiply exactly when the product fits.
149    #[test]
150    fn wide_times_is_exact() {
151        assert_eq!(5_u64.saturating_times(u32::MAX), 5 * u64::from(u32::MAX));
152        assert_eq!(u32::MAX.saturating_times(2), u32::MAX);
153        assert_eq!(9_u128.saturating_times(0), 0);
154    }
155
156    /// `ZERO` is the smallest value.
157    #[test]
158    fn zero_is_minimum() {
159        assert_eq!(<u8 as Cost>::ZERO, u8::MIN);
160        assert_eq!(<usize as Cost>::ZERO, usize::MIN);
161    }
162
163    proptest! {
164        /// `saturating_times` matches the exact product clamped to the type's range.
165        #[test]
166        fn u16_times_matches_clamped_product(cost: u16, factor: u32) {
167            let exact = u64::from(cost) * u64::from(factor);
168            let expected = u16::try_from(exact).unwrap_or(u16::MAX);
169            prop_assert_eq!(cost.saturating_times(factor), expected);
170        }
171
172        /// `saturating_add` matches the exact sum clamped to the type's range.
173        #[test]
174        fn u32_add_matches_clamped_sum(a: u32, b: u32) {
175            let exact = u64::from(a) + u64::from(b);
176            let expected = u32::try_from(exact).unwrap_or(u32::MAX);
177            prop_assert_eq!(Cost::saturating_add(a, b), expected);
178        }
179    }
180}