malachite_nz/integer/comparison/
partial_cmp_natural.rs

1// Copyright © 2025 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::integer::Integer;
10use crate::natural::Natural;
11use core::cmp::Ordering::{self, *};
12
13impl PartialOrd<Natural> for Integer {
14    /// Compares an [`Integer`] to a [`Natural`].
15    ///
16    /// # Worst-case complexity
17    /// $T(n) = O(n)$
18    ///
19    /// $M(n) = O(1)$
20    ///
21    /// where n = `min(self.significant_bits(), other.significant_bits())`.
22    ///
23    /// # Examples
24    /// ```
25    /// use malachite_nz::integer::Integer;
26    /// use malachite_nz::natural::Natural;
27    ///
28    /// assert!(Integer::from(123) > Natural::from(122u32));
29    /// assert!(Integer::from(123) >= Natural::from(122u32));
30    /// assert!(Integer::from(123) < Natural::from(124u32));
31    /// assert!(Integer::from(123) <= Natural::from(124u32));
32    /// assert!(Integer::from(-123) < Natural::from(123u32));
33    /// assert!(Integer::from(-123) <= Natural::from(123u32));
34    /// ```
35    fn partial_cmp(&self, other: &Natural) -> Option<Ordering> {
36        if self.sign {
37            self.abs.partial_cmp(other)
38        } else {
39            Some(Less)
40        }
41    }
42}
43
44impl PartialOrd<Integer> for Natural {
45    /// Compares a [`Natural`] to an [`Integer`].
46    ///
47    /// # Worst-case complexity
48    /// $T(n) = O(n)$
49    ///
50    /// $M(n) = O(1)$
51    ///
52    /// where n = `min(self.significant_bits(), other.significant_bits())`.
53    ///
54    /// # Examples
55    /// ```
56    /// use malachite_nz::integer::Integer;
57    /// use malachite_nz::natural::Natural;
58    ///
59    /// assert!(Natural::from(123u32) > Integer::from(122));
60    /// assert!(Natural::from(123u32) >= Integer::from(122));
61    /// assert!(Natural::from(123u32) < Integer::from(124));
62    /// assert!(Natural::from(123u32) <= Integer::from(124));
63    /// assert!(Natural::from(123u32) > Integer::from(-123));
64    /// assert!(Natural::from(123u32) >= Integer::from(-123));
65    /// ```
66    fn partial_cmp(&self, other: &Integer) -> Option<Ordering> {
67        if other.sign {
68            self.partial_cmp(&other.abs)
69        } else {
70            Some(Greater)
71        }
72    }
73}