Skip to main content

search_core/cost/
float.rs

1//! The checked float cost [`NonNegF64`] (feature `float`).
2
3use core::cmp::Ordering;
4use core::fmt;
5use core::hash::{Hash, Hasher};
6use core::ops::{Add, Mul};
7
8use super::Cost;
9
10/// A non-negative, non-NaN `f64` cost; `+∞` is allowed and acts as the largest cost.
11///
12/// Raw `f64` cannot implement [`Cost`]: NaN breaks [`Ord`] and negative values break the
13/// non-negativity contract. This newtype checks both once, in [`NonNegF64::new`], and keeps
14/// the invariant closed under every operation:
15///
16/// - the sum of two values in `[0, +∞]` is in `[0, +∞]` (a finite overflow becomes `+∞`;
17///   `+∞ + +∞ = +∞`), so `+` never produces NaN;
18/// - [`Cost::saturating_times`] with factor `0` returns zero instead of computing
19///   `+∞ × 0 = NaN`;
20/// - `-0.0` is stored as `+0.0`, so [`Eq`], [`Ord`] and [`Hash`] agree (bitwise hashing would
21///   otherwise tell the two zeros apart).
22///
23/// # Rounding
24///
25/// Float addition rounds and is not associative: the same path summed in a different order
26/// can differ in the last bits. Searches stay terminating and panic-free, but "optimal" then
27/// means optimal up to rounding, and ties may break differently than with exact arithmetic.
28/// Prefer an integer or [`Decimal`](crate::Decimal) cost when exact results matter.
29///
30/// # Examples
31///
32/// ```
33/// use search_core::{Cost, NonNegF64};
34///
35/// let a = NonNegF64::new(1.5).unwrap();
36/// let b = NonNegF64::new(2.25).unwrap();
37///
38/// assert_eq!((a + b).get(), 3.75);
39/// assert!(NonNegF64::ZERO < a);
40/// assert_eq!(NonNegF64::new(f64::NAN), None);
41/// assert_eq!(NonNegF64::new(-1.0), None);
42/// ```
43#[derive(Clone, Copy, Default)]
44pub struct NonNegF64(f64);
45
46impl NonNegF64 {
47    /// The cost `+∞`: larger than every finite cost.
48    pub const INFINITY: Self = Self(f64::INFINITY);
49
50    /// Wraps `value`, or returns `None` if it is NaN or negative.
51    ///
52    /// `-0.0` is accepted and stored as `+0.0`. `+∞` is accepted.
53    #[must_use]
54    pub fn new(value: f64) -> Option<Self> {
55        if value.is_nan() || value < 0.0 {
56            return None;
57        }
58
59        // `-0.0 + 0.0` is `+0.0`; every other accepted value is unchanged.
60        Some(Self(value + 0.0))
61    }
62
63    /// The wrapped value: never NaN, never negative, never `-0.0`.
64    #[must_use]
65    pub const fn get(self) -> f64 {
66        self.0
67    }
68}
69
70impl PartialEq for NonNegF64 {
71    fn eq(&self, other: &Self) -> bool {
72        self.cmp(other) == Ordering::Equal
73    }
74}
75
76impl Eq for NonNegF64 {}
77
78impl PartialOrd for NonNegF64 {
79    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
80        Some(self.cmp(other))
81    }
82}
83
84impl Ord for NonNegF64 {
85    fn cmp(&self, other: &Self) -> Ordering {
86        // Without NaN and `-0.0`, `total_cmp` is the usual numeric order.
87        self.0.total_cmp(&other.0)
88    }
89}
90
91impl Hash for NonNegF64 {
92    fn hash<H: Hasher>(&self, state: &mut H) {
93        self.0.to_bits().hash(state);
94    }
95}
96
97impl Add for NonNegF64 {
98    type Output = Self;
99
100    fn add(self, other: Self) -> Self {
101        Self(self.0 + other.0)
102    }
103}
104
105impl Mul for NonNegF64 {
106    type Output = Self;
107
108    /// The `f64` product, with `0 · ∞ = 0` instead of NaN, so the invariant holds.
109    fn mul(self, other: Self) -> Self {
110        crate::WideMul::wide_mul(self, other)
111    }
112}
113
114impl Cost for NonNegF64 {
115    const ZERO: Self = Self(0.0);
116
117    fn saturating_add(self, other: Self) -> Self {
118        self + other
119    }
120
121    fn saturating_times(self, factor: u32) -> Self {
122        if factor == 0 {
123            return Self::ZERO;
124        }
125
126        Self(self.0 * f64::from(factor))
127    }
128}
129
130impl fmt::Display for NonNegF64 {
131    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
132        fmt::Display::fmt(&self.0, f)
133    }
134}
135
136impl fmt::Debug for NonNegF64 {
137    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
138        fmt::Debug::fmt(&self.0, f)
139    }
140}
141
142impl From<NonNegF64> for f64 {
143    fn from(cost: NonNegF64) -> Self {
144        cost.0
145    }
146}
147
148#[cfg(test)]
149mod tests {
150    //! Unit and property tests for [`NonNegF64`]: the invariant survives every operation.
151
152    use super::{Cost, NonNegF64};
153    use proptest::prelude::*;
154
155    /// NaN and negative values are rejected; zeros and infinity are accepted.
156    #[test]
157    fn new_checks_invariant() {
158        assert_eq!(NonNegF64::new(f64::NAN), None);
159        assert_eq!(NonNegF64::new(-1e-300), None);
160        assert_eq!(NonNegF64::new(f64::NEG_INFINITY), None);
161        assert_eq!(NonNegF64::new(f64::INFINITY), Some(NonNegF64::INFINITY));
162        assert_eq!(NonNegF64::new(0.0), Some(NonNegF64::ZERO));
163    }
164
165    /// `-0.0` is normalized, so it equals, orders and hashes like `+0.0`.
166    #[test]
167    fn negative_zero_is_normalized() {
168        let negative = NonNegF64::new(-0.0).unwrap();
169        assert!(negative.get().is_sign_positive());
170        assert_eq!(negative, NonNegF64::ZERO);
171        assert_eq!(negative.get().to_bits(), 0.0_f64.to_bits());
172    }
173
174    /// Infinity times zero is zero, not NaN.
175    #[test]
176    fn infinity_times_zero_is_zero() {
177        assert_eq!(NonNegF64::INFINITY.saturating_times(0), NonNegF64::ZERO);
178        assert_eq!(NonNegF64::INFINITY.saturating_times(3), NonNegF64::INFINITY);
179    }
180
181    /// Finite overflow saturates at infinity.
182    #[test]
183    fn overflow_reaches_infinity() {
184        let max = NonNegF64::new(f64::MAX).unwrap();
185        assert_eq!(max + max, NonNegF64::INFINITY);
186        assert_eq!(
187            NonNegF64::INFINITY + NonNegF64::INFINITY,
188            NonNegF64::INFINITY
189        );
190    }
191
192    /// Generates any `f64` accepted by [`NonNegF64::new`], including both zeros and `+∞`.
193    fn cost() -> impl Strategy<Value = NonNegF64> {
194        prop_oneof![
195            Just(-0.0),
196            Just(f64::INFINITY),
197            Just(f64::MAX),
198            0.0..f64::MAX,
199        ]
200        .prop_map(|value| NonNegF64::new(value).expect("generated values are valid"))
201    }
202
203    proptest! {
204        /// Sums and products stay inside the invariant: not NaN, not negative, not `-0.0`.
205        #[test]
206        fn operations_preserve_invariant(a in cost(), b in cost(), factor: u32) {
207            for value in [a + b, a.saturating_add(b), a.saturating_times(factor)] {
208                prop_assert!(!value.get().is_nan());
209                prop_assert!(value.get().is_sign_positive());
210                prop_assert!(value >= NonNegF64::ZERO);
211            }
212        }
213
214        /// `Ord` agrees with the numeric order of the wrapped values.
215        #[test]
216        fn order_matches_numeric(a in cost(), b in cost()) {
217            prop_assert_eq!(a.cmp(&b), a.get().partial_cmp(&b.get()).unwrap());
218            prop_assert_eq!(a == b, a.get().to_bits() == b.get().to_bits());
219        }
220    }
221}