1use dashu_base::AbsOrd;
4
5use crate::{
6 arch::word::Word,
7 ibig::IBig,
8 repr::TypedReprRef::{self, *},
9 ubig::UBig,
10 Sign::*,
11};
12use core::cmp::Ordering;
13
14#[inline]
16pub fn cmp_same_len(lhs: &[Word], rhs: &[Word]) -> Ordering {
17 debug_assert!(lhs.len() == rhs.len());
18 lhs.iter().rev().cmp(rhs.iter().rev())
19}
20
21pub fn cmp_in_place(lhs: &[Word], rhs: &[Word]) -> Ordering {
27 debug_assert!(*lhs.last().unwrap() != 0 && *rhs.last().unwrap() != 0);
28 lhs.len()
29 .cmp(&rhs.len())
30 .then_with(|| cmp_same_len(lhs, rhs))
31}
32
33impl<'a> PartialOrd for TypedReprRef<'a> {
34 #[inline]
35 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
36 Some(self.cmp(other))
37 }
38}
39
40impl<'a> Ord for TypedReprRef<'a> {
41 #[inline]
42 fn cmp(&self, other: &Self) -> Ordering {
43 match (*self, *other) {
44 (RefSmall(dword0), RefSmall(dword1)) => dword0.cmp(&dword1),
45 (RefSmall(_), RefLarge(_)) => Ordering::Less,
46 (RefLarge(_), RefSmall(_)) => Ordering::Greater,
47 (RefLarge(words0), RefLarge(words1)) => cmp_in_place(words0, words1),
48 }
49 }
50}
51
52impl Ord for UBig {
53 #[inline]
54 fn cmp(&self, other: &UBig) -> Ordering {
55 self.repr().cmp(&other.repr())
56 }
57}
58
59impl PartialOrd for UBig {
60 #[inline]
61 fn partial_cmp(&self, other: &UBig) -> Option<Ordering> {
62 Some(self.cmp(other))
63 }
64}
65
66impl Ord for IBig {
67 #[inline]
68 fn cmp(&self, other: &IBig) -> Ordering {
69 let (lhs_sign, lhs_mag) = self.as_sign_repr();
70 let (rhs_sign, rhs_mag) = other.as_sign_repr();
71 match (lhs_sign, rhs_sign) {
72 (Positive, Positive) => lhs_mag.cmp(&rhs_mag),
73 (Positive, Negative) => Ordering::Greater,
74 (Negative, Positive) => Ordering::Less,
75 (Negative, Negative) => rhs_mag.cmp(&lhs_mag),
76 }
77 }
78}
79
80impl PartialOrd for IBig {
81 #[inline]
82 fn partial_cmp(&self, other: &IBig) -> Option<Ordering> {
83 Some(self.cmp(other))
84 }
85}
86
87impl AbsOrd for UBig {
88 #[inline]
89 fn abs_cmp(&self, rhs: &Self) -> Ordering {
90 self.0.as_typed().cmp(&rhs.0.as_typed())
91 }
92}
93impl AbsOrd for IBig {
94 #[inline]
95 fn abs_cmp(&self, rhs: &Self) -> Ordering {
96 self.0.as_sign_typed().1.cmp(&rhs.0.as_sign_typed().1)
97 }
98}
99impl AbsOrd<UBig> for IBig {
100 #[inline]
101 fn abs_cmp(&self, rhs: &UBig) -> Ordering {
102 self.0.as_sign_typed().1.cmp(&rhs.0.as_typed())
103 }
104}
105impl AbsOrd<IBig> for UBig {
106 #[inline]
107 fn abs_cmp(&self, rhs: &IBig) -> Ordering {
108 self.0.as_typed().cmp(&rhs.0.as_sign_typed().1)
109 }
110}