malachite_nz/natural/comparison/partial_cmp_abs_primitive_float.rs
1// Copyright © 2026 Mikhail Hogrefe
2//
3// This file is part of Malachite.
4//
5// Malachite is free software: you can redistribute it and/or modify it under the terms of the GNU
6// Lesser General Public License (LGPL) as published by the Free Software Foundation; either version
7// 3 of the License, or (at your option) any later version. See <https://www.gnu.org/licenses/>.
8
9use crate::natural::Natural;
10use core::cmp::Ordering::{self, *};
11use malachite_base::num::comparison::traits::PartialOrdAbs;
12use malachite_base::num::conversion::traits::{ExactFrom, IntegerMantissaAndExponent};
13use malachite_base::num::logic::traits::SignificantBits;
14
15macro_rules! impl_float {
16 ($t: ident) => {
17 impl PartialOrdAbs<$t> for Natural {
18 /// Compares a [`Natural`] to the absolute value of a primitive float.
19 ///
20 /// # Worst-case complexity
21 /// $T(n) = O(n)$
22 ///
23 /// $M(n) = O(1)$
24 ///
25 /// where $T$ is time, $M$ is additional memory, and $n$ is `self.significant_bits()`.
26 ///
27 /// # Examples
28 /// See [here](super::partial_cmp_abs_primitive_float#partial_cmp_abs).
29 fn partial_cmp_abs(&self, other: &$t) -> Option<Ordering> {
30 if other.is_nan() {
31 None
32 } else if !other.is_finite() {
33 Some(Less)
34 } else if *other == 0.0 {
35 self.partial_cmp_abs(&0u32)
36 } else if *self == 0u32 {
37 Some(Less)
38 } else {
39 let (m, e) = other.integer_mantissa_and_exponent();
40 let log_cmp = i64::exact_from(self.significant_bits())
41 .cmp(&(i64::exact_from(m.significant_bits()) + e));
42 Some(if log_cmp != Equal {
43 log_cmp
44 } else {
45 self.cmp_normalized(&Natural::from(m))
46 })
47 }
48 }
49 }
50
51 impl PartialOrdAbs<Natural> for $t {
52 /// Compares the absolute value of a primitive float to a [`Natural`].
53 ///
54 /// # Worst-case complexity
55 /// $T(n) = O(n)$
56 ///
57 /// $M(n) = O(1)$
58 ///
59 /// where $T$ is time, $M$ is additional memory, and $n$ is `other.significant_bits()`.
60 ///
61 /// See [here](super::partial_cmp_abs_primitive_float#partial_cmp_abs).
62 #[inline]
63 fn partial_cmp_abs(&self, other: &Natural) -> Option<Ordering> {
64 other.partial_cmp_abs(self).map(Ordering::reverse)
65 }
66 }
67 };
68}
69apply_to_primitive_floats!(impl_float);