ethnum/uint/
cmp.rs

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