ethnum/uint/
cmp.rs

1//! Module with comparison implementations for `U256`.
2//!
3//! `PartialEq` and `PartialOrd` implementations for `u128` are also provided
4//! to allow notation such as:
5//!
6//! ```
7//! # use ethnum::U256;
8//!
9//! assert_eq!(U256::new(42), 42);
10//! assert!(U256::ONE > 0 && U256::ZERO == 0);
11//! ```
12
13use crate::uint::U256;
14use core::cmp::Ordering;
15
16impl Ord for U256 {
17    #[inline]
18    fn cmp(&self, other: &Self) -> Ordering {
19        self.into_words().cmp(&other.into_words())
20    }
21}
22
23impl_cmp! {
24    impl Cmp for U256 (u128);
25}
26
27#[cfg(test)]
28mod tests {
29    use super::*;
30    use core::cmp::Ordering;
31
32    #[test]
33    fn cmp() {
34        // 1e38
35        let x = U256::from_words(0, 100000000000000000000000000000000000000);
36        // 1e48
37        let y = U256::from_words(2938735877, 18960114910927365649471927446130393088);
38        assert!(x < y);
39        assert_eq!(x.cmp(&y), Ordering::Less);
40        assert!(y > x);
41        assert_eq!(y.cmp(&x), Ordering::Greater);
42
43        let x = U256::new(100);
44        let y = U256::new(100);
45        assert!(x <= y);
46        assert_eq!(x.cmp(&y), Ordering::Equal);
47    }
48}