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
//! Comparisons operators.

use crate::{
    arch::word::Word,
    ibig::IBig,
    sign::Sign::*,
    ubig::{Repr::*, UBig},
};
use core::cmp::Ordering;

impl Ord for UBig {
    fn cmp(&self, other: &UBig) -> Ordering {
        match (self.repr(), other.repr()) {
            (Small(word), Small(other_word)) => word.cmp(other_word),
            (Small(_), Large(_)) => Ordering::Less,
            (Large(_), Small(_)) => Ordering::Greater,
            (Large(buffer), Large(other_buffer)) => buffer
                .len()
                .cmp(&other_buffer.len())
                .then_with(|| cmp_same_len(buffer, other_buffer)),
        }
    }
}

impl PartialOrd for UBig {
    fn partial_cmp(&self, other: &UBig) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for IBig {
    fn cmp(&self, other: &IBig) -> Ordering {
        match (self.sign(), other.sign()) {
            (Positive, Positive) => self.magnitude().cmp(other.magnitude()),
            (Positive, Negative) => Ordering::Greater,
            (Negative, Positive) => Ordering::Less,
            (Negative, Negative) => other.magnitude().cmp(self.magnitude()),
        }
    }
}

impl PartialOrd for IBig {
    fn partial_cmp(&self, other: &IBig) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

/// Compare lhs with rhs as numbers.
pub(crate) fn cmp_same_len(lhs: &[Word], rhs: &[Word]) -> Ordering {
    assert!(lhs.len() == rhs.len());
    lhs.iter().rev().cmp(rhs.iter().rev())
}