decorum 0.4.0

Total ordering, equivalence, hashing, and constraints for floating-point types.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
//! Ordering and comparisons of IEEE 754 floating-point and other partially ordered types.
//!
//! This module provides traits and functions for partial and total orderings, in particular of
//! floating-point types. For primitive floating-point types, the following total ordering is
//! provided via the [`CanonicalEq`] and [`CanonicalOrd`] traits:
//!
//! $$-\infin<\cdots<0<\cdots<\infin<\text{NaN}$$
//!
//! Note that both zero and `NaN` have more than one representation in IEEE 754 encoding. Given the
//! set of zero representations $Z$ and set of `NaN` representations $N$, this ordering coalesces
//! `-0`, `+0`, and `NaN`s such that:
//!
//! $$
//! \begin{aligned}
//! a=b&\mid a\in{Z},~b\in{Z}\cr\[1em\]
//! a=b&\mid a\in{N},~b\in{N}\cr\[1em\]
//! n>x&\mid n\in{N},~x\notin{N}
//! \end{aligned}
//! $$
//!
//! These same semantics are used in the [`Eq`] and [`Ord`] implementations for the [`Total`]
//! proxy.
//!
//! The [`EmptyOrd`] trait provides a particular ordering for types with a notion of empty
//! inhabitants. These inhabitants are considered incomparable, regardless of whether or not they
//! are ordered with respect to [`PartialOrd`] and [`Ord`]. For example, `None` is the empty
//! inhabitant of [`Option`] and so cannot be compared with [`EmptyOrd`].
//!
//! For floating-point types, `NaN`s are considered empty inhabitants. In this context, _empty_ can
//! be thought of as _undefined_, but note that **empty inhabitants are unrelated to proxy
//! constraints**. Unlike the standard ordering traits, [`EmptyOrd`] forwards empty inhabitants in
//! comparisons. For floating-point types, this importantly means that `NaN`s are forwarded
//! consistently in comparisons.
//!
//! # Examples
//!
//! Comparing `f64` values using a total ordering:
//!
//! ```rust
//! use core::cmp::Ordering;
//! use decorum::cmp::CanonicalOrd;
//! use decorum::NanEncoding;
//!
//! let x = f64::NAN;
//! let y = 1.0f64;
//!
//! let (min, max) = match x.cmp_canonical(&y) {
//!     Ordering::Less | Ordering::Equal => (x, y),
//!     _ => (y, x),
//! };
//! ```
//!
//! Computing a pairwise minimum that propagates `NaN`s with [`EmptyOrd`]:
//!
//! ```rust
//! use decorum::cmp;
//! use decorum::NanEncoding;
//!
//! let x = f64::NAN;
//! let y = 1.0f64;
//!
//! // `NaN` is considered an empty inhabitant in this ordering, so `min` is assigned `NaN` in this
//! // example, regardless of the order of parameters.
//! let min = cmp::min_or_empty(x, y);
//! ```
//!
//! [`Total`]: crate::Total

use core::cmp::Ordering;
use core::convert::Infallible;

use crate::{with_primitives, Primitive, ToCanonical};

/// Total equivalence relation of IEEE 754 floating-point encoded types.
///
/// `CanonicalEq` agrees with the total ordering provided by `CanonicalOrd`. See the module
/// documentation for more. Given the set of `NaN` representations $N$, `CanonicalEq` expresses:
///
/// $$
/// \begin{aligned}
/// a=b&\mid a\in{N},~b\in{N}\cr\[1em\]
/// n\ne x&\mid n\in{N},~x\notin{N}
/// \end{aligned}
/// $$
///
/// # Examples
///
/// Comparing `NaN`s using primitive floating-point types:
///
/// ```rust
/// use decorum::cmp::CanonicalEq;
///
/// let x = 0.0f64 / 0.0; // `NaN`.
/// let y = f64::INFINITY - f64::INFINITY; // `NaN`.
///
/// assert!(x.eq_canonical(&y));
/// ```
pub trait CanonicalEq {
    fn eq_canonical(&self, other: &Self) -> bool;
}

impl<T> CanonicalEq for T
where
    T: ToCanonical,
{
    fn eq_canonical(&self, other: &Self) -> bool {
        self.to_canonical() == other.to_canonical()
    }
}

impl<T, const N: usize> CanonicalEq for [T; N]
where
    T: CanonicalEq,
{
    fn eq_canonical(&self, other: &Self) -> bool {
        self.iter()
            .zip(other.iter())
            .all(|(a, b)| a.eq_canonical(b))
    }
}

impl<T> CanonicalEq for [T]
where
    T: CanonicalEq,
{
    fn eq_canonical(&self, other: &Self) -> bool {
        if self.len() == other.len() {
            self.iter()
                .zip(other.iter())
                .all(|(a, b)| a.eq_canonical(b))
        }
        else {
            false
        }
    }
}

/// Total ordering of IEEE 754 floating-point encoded types.
///
/// `CanonicalOrd` expresses the total ordering:
///
/// $$-\infin<\cdots<0<\cdots<\infin<\text{NaN}$$
///
/// This trait can be used to compare primitive floating-point types without the need to wrap them
/// within a proxy type. See the module documentation for more about the ordering used by
/// `CanonicalOrd` and proxy types.
pub trait CanonicalOrd {
    fn cmp_canonical(&self, other: &Self) -> Ordering;
}

impl<T> CanonicalOrd for T
where
    // This implementation is bound on `Primitive` rather than something more general to exclude
    // `PartialOrd` implementations that do not comply with IEEE 754 floating-point partial
    // ordering. This must be implemented independently for proxy types.
    T: Primitive,
{
    fn cmp_canonical(&self, other: &Self) -> Ordering {
        match self.partial_cmp(other) {
            Some(ordering) => ordering,
            None => {
                if self.is_nan() {
                    if other.is_nan() {
                        Ordering::Equal
                    }
                    else {
                        Ordering::Greater
                    }
                }
                else {
                    Ordering::Less
                }
            }
        }
    }
}

impl<T> CanonicalOrd for [T]
where
    T: CanonicalOrd,
{
    fn cmp_canonical(&self, other: &Self) -> Ordering {
        match self
            .iter()
            .zip(other.iter())
            .map(|(a, b)| a.cmp_canonical(b))
            .find(|ordering| *ordering != Ordering::Equal)
        {
            Some(ordering) => ordering,
            None => self.len().cmp(&other.len()),
        }
    }
}

pub trait EmptyInhabitant {
    fn empty() -> Self;
}

impl EmptyInhabitant for () {
    fn empty() -> Self {}
}

impl<T> EmptyInhabitant for Option<T> {
    #[inline(always)]
    fn empty() -> Self {
        None
    }
}

impl<T, E> EmptyInhabitant for Result<T, E>
where
    E: EmptyInhabitant,
{
    #[inline(always)]
    fn empty() -> Self {
        Err(E::empty())
    }
}

/// Defines an ordering for types that (may) have empty inhabitants.
///
/// An empty inhabitant is an intrinsic value of a type that is considered incomparable in this
/// ordering, regardless of [`PartialOrd`] and [`Ord`] implementations. If an empty inhabitant is
/// compared, then the comparison is considered undefined and the output is an empty inhabitant.
///
/// For floating-point types, `NaN`s are considered empty inhabitants.
///
/// `EmptyOrd` can be implemented for types with no empty inhabitants. Notably, this trait is
/// implemented by totally ordered primitive numeric types. This better supports types that are
/// defined by conditional compilation.
///
/// See [`min_or_empty`] and [`max_or_empty`].
pub trait EmptyOrd: PartialOrd {
    type Empty;

    fn from_empty(empty: Self::Empty) -> Self;

    fn is_empty(&self) -> bool;

    fn cmp_empty(&self, other: &Self) -> Result<Ordering, Self::Empty>;
}

impl<T> EmptyOrd for Option<T>
where
    T: Ord,
{
    type Empty = Self;

    #[inline(always)]
    fn from_empty(empty: <Self as EmptyOrd>::Empty) -> Self {
        empty
    }

    fn is_empty(&self) -> bool {
        self.is_none()
    }

    fn cmp_empty(&self, other: &Self) -> Result<Ordering, Self::Empty> {
        self.as_ref()
            .zip(other.as_ref())
            .map_or_else(|| Err(EmptyInhabitant::empty()), |(a, b)| Ok(a.cmp(b)))
    }
}

impl<T, E> EmptyOrd for Result<T, E>
where
    Self: PartialOrd,
    T: Ord,
    E: EmptyInhabitant,
{
    type Empty = Self;

    #[inline(always)]
    fn from_empty(empty: Self::Empty) -> Self {
        empty
    }

    fn is_empty(&self) -> bool {
        self.is_err()
    }

    fn cmp_empty(&self, other: &Self) -> Result<Ordering, Self::Empty> {
        match (self.as_ref(), other.as_ref()) {
            (Ok(a), Ok(b)) => Ok(a.cmp(b)),
            _ => Err(EmptyInhabitant::empty()),
        }
    }
}

macro_rules! impl_empty_ord_for_float_primitive {
    () => {
        with_primitives!(impl_empty_ord_for_float_primitive);
    };
    (primitive => $t:ty) => {
        impl EmptyOrd for $t {
            type Empty = Self;

            #[inline(always)]
            fn from_empty(empty: Self::Empty) -> Self {
                empty
            }

            fn is_empty(&self) -> bool {
                self.is_nan()
            }

            fn cmp_empty(&self, other: &Self) -> Result<Ordering, Self::Empty> {
                self.partial_cmp(other)
                    .ok_or_else(|| EmptyInhabitant::empty())
            }
        }
    };
}
impl_empty_ord_for_float_primitive!();

macro_rules! impl_empty_ord_for_total_primitive {
    () => {
        impl_empty_ord_for_total_primitive!(primitive => isize);
        impl_empty_ord_for_total_primitive!(primitive => i8);
        impl_empty_ord_for_total_primitive!(primitive => i16);
        impl_empty_ord_for_total_primitive!(primitive => i32);
        impl_empty_ord_for_total_primitive!(primitive => i64);
        impl_empty_ord_for_total_primitive!(primitive => i128);
        impl_empty_ord_for_total_primitive!(primitive => usize);
        impl_empty_ord_for_total_primitive!(primitive => u8);
        impl_empty_ord_for_total_primitive!(primitive => u16);
        impl_empty_ord_for_total_primitive!(primitive => u32);
        impl_empty_ord_for_total_primitive!(primitive => u64);
        impl_empty_ord_for_total_primitive!(primitive => u128);
    };
    (primitive => $t:ty) => {
        impl EmptyOrd for $t {
            type Empty = Infallible;

            fn from_empty(_: Self::Empty) -> Self {
                unreachable!()
            }

            #[inline(always)]
            fn is_empty(&self) -> bool {
                false
            }

            #[inline(always)]
            fn cmp_empty(&self, other: &Self) -> Result<Ordering, Self::Empty> {
                Ok(self.cmp(other))
            }
        }
    };
}
impl_empty_ord_for_total_primitive!();

macro_rules! impl_empty_inhabitant_for_float_primitive {
    () => {
        with_primitives!(impl_empty_inhabitant_for_float_primitive);
    };
    (primitive => $t:ty) => {
        impl EmptyInhabitant for $t {
            #[inline(always)]
            fn empty() -> Self {
                Self::NAN
            }
        }
    };
}
impl_empty_inhabitant_for_float_primitive!();

/// Pairwise maximum for types that may have an empty inhabitant that is incomparable.
///
/// See the [`EmptyOrd`] trait.
pub fn max_or_empty<T>(a: T, b: T) -> T
where
    T: EmptyOrd,
{
    match a.cmp_empty(&b) {
        Ok(Ordering::Less | Ordering::Equal) => b,
        Ok(Ordering::Greater) => a,
        Err(empty) => T::from_empty(empty),
    }
}

/// Pairwise minimum for types that may have an empty inhabitant that is incomparable.
///
/// See the [`EmptyOrd`] trait.
pub fn min_or_empty<T>(a: T, b: T) -> T
where
    T: EmptyOrd,
{
    match a.cmp_empty(&b) {
        Ok(Ordering::Less | Ordering::Equal) => a,
        Ok(Ordering::Greater) => b,
        Err(empty) => T::from_empty(empty),
    }
}

/// Pairwise ordering for types that may have an empty inhabitant that is incomparable.
///
/// The output tuple contains either the minimum and maximum (in that order) or empty inhabitants.
///
/// See the [`EmptyOrd`] trait.
pub fn min_max_or_empty<T>(a: T, b: T) -> (T, T)
where
    T: EmptyOrd,
    T::Empty: Copy,
{
    match a.cmp_empty(&b) {
        Ok(Ordering::Less | Ordering::Equal) => (a, b),
        Ok(Ordering::Greater) => (b, a),
        Err(empty) => (T::from_empty(empty), T::from_empty(empty)),
    }
}

#[cfg(test)]
mod tests {
    use num_traits::{One, Zero};

    use crate::cmp::{self, CanonicalEq, EmptyOrd};
    use crate::{NanEncoding, Total};

    #[test]
    #[allow(clippy::eq_op)]
    #[allow(clippy::zero_divided_by_zero)]
    fn primitive_eq() {
        let x = 0.0f64 / 0.0f64; // `NaN`.
        let y = f64::INFINITY + f64::NEG_INFINITY; // `NaN`.
        let xs = [1.0f64, f64::NAN, f64::INFINITY];
        let ys = [1.0f64, f64::NAN, f64::INFINITY];

        assert!(x.eq_canonical(&y));
        assert!(xs.eq_canonical(&ys));
    }

    #[test]
    fn empty_ord_option() {
        let zero = Some(0u64);
        let one = Some(1u64);

        assert_eq!(zero, cmp::min_or_empty(zero, one));
        assert_eq!(one, cmp::max_or_empty(zero, one));
        assert!(cmp::min_or_empty(None, zero).is_empty());
    }

    #[test]
    #[allow(clippy::float_cmp)]
    fn empty_ord_primitive() {
        let zero = 0.0f64;
        let one = 1.0f64;

        assert_eq!(zero, cmp::min_or_empty(zero, one));
        assert_eq!(one, cmp::max_or_empty(zero, one));
        assert!(cmp::min_or_empty(f64::NAN, zero).is_empty());
    }

    #[test]
    fn empty_ord_proxy() {
        let nan = Total::<f64>::NAN;
        let zero = Total::zero();
        let one = Total::one();

        assert_eq!((zero, one), cmp::min_max_or_empty(zero, one));
        assert_eq!((zero, one), cmp::min_max_or_empty(one, zero));

        assert_eq!((nan, nan), cmp::min_max_or_empty(nan, zero));
        assert_eq!((nan, nan), cmp::min_max_or_empty(zero, nan));
        assert_eq!((nan, nan), cmp::min_max_or_empty(nan, nan));

        assert_eq!(nan, cmp::min_or_empty(nan, zero));
        assert_eq!(nan, cmp::max_or_empty(nan, zero));
        assert_eq!(nan, cmp::min_or_empty(nan, nan));
        assert_eq!(nan, cmp::max_or_empty(nan, nan));
    }
}