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