malachite_nz/integer/comparison/
cmp.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 core::cmp::Ordering::{self, *};
11
12impl PartialOrd for Integer {
13    /// Compares two [`Integer`]s.
14    ///
15    /// See the documentation for the [`Ord`] implementation.
16    #[inline]
17    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
18        Some(self.cmp(other))
19    }
20}
21
22impl Ord for Integer {
23    /// Compares two [`Integer`]s.
24    ///
25    /// # Worst-case complexity
26    /// $T(n) = O(n)$
27    ///
28    /// $M(n) = O(1)$
29    ///
30    /// where $T$ is time, $M$ is additional memory, and $n$ is `min(self.significant_bits(),
31    /// other.significant_bits())`.
32    ///
33    /// # Examples
34    /// ```
35    /// use malachite_nz::integer::Integer;
36    ///
37    /// assert!(Integer::from(-123) < Integer::from(-122));
38    /// assert!(Integer::from(-123) <= Integer::from(-122));
39    /// assert!(Integer::from(-123) > Integer::from(-124));
40    /// assert!(Integer::from(-123) >= Integer::from(-124));
41    /// ```
42    fn cmp(&self, other: &Self) -> Ordering {
43        if core::ptr::eq(self, other) {
44            Equal
45        } else {
46            match (self.sign, other.sign) {
47                (true, false) => Greater,
48                (false, true) => Less,
49                (true, true) => self.abs.cmp(&other.abs),
50                (false, false) => other.abs.cmp(&self.abs),
51            }
52        }
53    }
54}