ethnum/int/cmp.rs
1//! Module with comparison implementations for `I256`.
2//!
3//! `PartialEq` is derived and not implemented, which is important for ensuring
4//! that `match` can be used with `I256`.
5//!
6//! ```
7//! # use ethnum::I256;
8//! # let value = I256::new(42);
9//!
10//! match (value) {
11//! I256::ZERO => println!("I am zero"),
12//! I256::ONE => println!("I am one"),
13//! _ => println!("I am something else"),
14//! }
15//! ```
16//!
17//! `PartialEq` and `PartialOrd` implementations for `i128` are also provided
18//! to allow notation such as:
19//!
20//! ```
21//! # use ethnum::I256;
22//! assert_eq!(I256::new(42), 42);
23//! assert_eq!(42, I256::new(42));
24//! assert!(I256::ONE > 0 && I256::ZERO == 0);
25//! assert!(0 < I256::ONE && 0 == I256::ZERO);
26//! ```
27
28use super::I256;
29use core::cmp::Ordering;
30
31impl Ord for I256 {
32 #[inline]
33 fn cmp(&self, other: &Self) -> Ordering {
34 let (ahi, alo) = self.into_words();
35 let (bhi, blo) = other.into_words();
36 (ahi, alo as u128).cmp(&(bhi, blo as u128))
37 }
38}
39
40impl_cmp! {
41 impl Cmp for I256 (i128);
42}
43
44#[cfg(test)]
45mod tests {
46 use super::*;
47 use core::cmp::Ordering;
48
49 #[test]
50 fn cmp() {
51 // 1e38
52 let x = I256::from_words(0, 100000000000000000000000000000000000000);
53 // 1e48
54 let y = I256::from_words(2938735877, 18960114910927365649471927446130393088);
55 assert!(x < y);
56 assert_eq!(x.cmp(&y), Ordering::Less);
57 assert!(y > x);
58 assert_eq!(y.cmp(&x), Ordering::Greater);
59
60 let x = I256::new(100);
61 let y = I256::new(100);
62 assert!(x <= y);
63 assert_eq!(x.cmp(&y), Ordering::Equal);
64
65 assert!(I256::ZERO > I256::MIN);
66 assert!(I256::ZERO < I256::MAX);
67
68 assert!(I256::MAX > I256::MIN);
69 assert!(I256::MIN < I256::MAX);
70 }
71}