cosmwasm_std/math/
uint256.rs

1use alloc::string::{String, ToString};
2use core::fmt;
3use core::ops::{
4    Add, AddAssign, Div, DivAssign, Mul, MulAssign, Not, Rem, RemAssign, Shl, ShlAssign, Shr,
5    ShrAssign, Sub, SubAssign,
6};
7use core::str::FromStr;
8
9use crate::errors::{
10    CheckedMultiplyFractionError, CheckedMultiplyRatioError, ConversionOverflowError,
11    DivideByZeroError, ErrorKind, OverflowError, OverflowOperation, StdError,
12};
13use crate::forward_ref::{forward_ref_binop, forward_ref_op_assign};
14use crate::{
15    __internal::forward_ref_partial_eq, impl_mul_fraction, Fraction, Int128, Int256, Int512, Int64,
16    Uint128, Uint512, Uint64,
17};
18
19/// Used internally - we don't want to leak this type since we might change
20/// the implementation in the future.
21use bnum::types::U256;
22
23use super::conversion::{forward_try_from, primitive_to_wrapped_int, try_from_int_to_uint};
24use super::impl_int_serde;
25use super::num_consts::NumConsts;
26
27/// An implementation of u256 that is using strings for JSON encoding/decoding,
28/// such that the full u256 range can be used for clients that convert JSON numbers to floats,
29/// like JavaScript and jq.
30///
31/// # Examples
32///
33/// Use `new` to create instances out of u128, `from` for other primitive uint types
34/// or `from_be_bytes` to provide big endian bytes:
35///
36/// ```
37/// # use cosmwasm_std::Uint256;
38/// let a = Uint256::new(258u128);
39/// let b = Uint256::from(258u16);
40/// let c = Uint256::from_be_bytes([
41///     0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8,
42///     0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8,
43///     0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8,
44///     0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 1u8, 2u8,
45/// ]);
46/// assert_eq!(a, b);
47/// assert_eq!(a, c);
48/// ```
49#[derive(
50    Copy,
51    Clone,
52    Default,
53    Debug,
54    PartialEq,
55    Eq,
56    PartialOrd,
57    Ord,
58    schemars::JsonSchema,
59    cw_schema::Schemaifier,
60)]
61#[schemaifier(type = cw_schema::NodeType::Integer { precision: 256, signed: false })]
62pub struct Uint256(#[schemars(with = "String")] pub(crate) U256);
63
64impl_int_serde!(Uint256);
65forward_ref_partial_eq!(Uint256, Uint256);
66
67impl Uint256 {
68    pub const MAX: Uint256 = Uint256(U256::MAX);
69    pub const MIN: Uint256 = Uint256(U256::ZERO);
70
71    /// Creates a Uint256(value).
72    ///
73    /// This method is less flexible than `from` but can be called in a const context.
74    ///
75    /// Before CosmWasm 3 this took a byte array as an argument. You can get this behaviour
76    /// with [`from_be_bytes`].
77    ///
78    /// [`from_be_bytes`]: Self::from_be_bytes
79    #[must_use]
80    pub const fn new(value: u128) -> Self {
81        let b = value.to_be_bytes();
82        Self::from_be_bytes([
83            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, b[0], b[1], b[2], b[3], b[4], b[5],
84            b[6], b[7], b[8], b[9], b[10], b[11], b[12], b[13], b[14], b[15],
85        ])
86    }
87
88    /// Creates a Uint256(0)
89    #[inline]
90    pub const fn zero() -> Self {
91        Self(U256::ZERO)
92    }
93
94    /// Creates a Uint256(1)
95    #[inline]
96    pub const fn one() -> Self {
97        Self(U256::ONE)
98    }
99
100    #[must_use]
101    pub const fn from_be_bytes(data: [u8; 32]) -> Self {
102        let words: [u64; 4] = [
103            u64::from_le_bytes([
104                data[31], data[30], data[29], data[28], data[27], data[26], data[25], data[24],
105            ]),
106            u64::from_le_bytes([
107                data[23], data[22], data[21], data[20], data[19], data[18], data[17], data[16],
108            ]),
109            u64::from_le_bytes([
110                data[15], data[14], data[13], data[12], data[11], data[10], data[9], data[8],
111            ]),
112            u64::from_le_bytes([
113                data[7], data[6], data[5], data[4], data[3], data[2], data[1], data[0],
114            ]),
115        ];
116        Self(U256::from_digits(words))
117    }
118
119    #[must_use]
120    pub const fn from_le_bytes(data: [u8; 32]) -> Self {
121        let words: [u64; 4] = [
122            u64::from_le_bytes([
123                data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7],
124            ]),
125            u64::from_le_bytes([
126                data[8], data[9], data[10], data[11], data[12], data[13], data[14], data[15],
127            ]),
128            u64::from_le_bytes([
129                data[16], data[17], data[18], data[19], data[20], data[21], data[22], data[23],
130            ]),
131            u64::from_le_bytes([
132                data[24], data[25], data[26], data[27], data[28], data[29], data[30], data[31],
133            ]),
134        ];
135        Self(U256::from_digits(words))
136    }
137
138    /// A conversion from `u128` that, unlike the one provided by the `From` trait,
139    /// can be used in a `const` context.
140    #[must_use]
141    #[deprecated(since = "3.0.0", note = "Use Uint256::new(value) instead")]
142    pub const fn from_u128(value: u128) -> Self {
143        Self::new(value)
144    }
145
146    /// A conversion from `Uint128` that, unlike the one provided by the `From` trait,
147    /// can be used in a `const` context.
148    #[must_use]
149    pub const fn from_uint128(num: Uint128) -> Self {
150        Self::new(num.u128())
151    }
152
153    /// Returns a copy of the number as big endian bytes.
154    #[must_use = "this returns the result of the operation, without modifying the original"]
155    pub const fn to_be_bytes(self) -> [u8; 32] {
156        let words = self.0.digits();
157        let words = [
158            words[3].to_be_bytes(),
159            words[2].to_be_bytes(),
160            words[1].to_be_bytes(),
161            words[0].to_be_bytes(),
162        ];
163        unsafe { core::mem::transmute::<[[u8; 8]; 4], [u8; 32]>(words) }
164    }
165
166    /// Returns a copy of the number as little endian bytes.
167    #[must_use = "this returns the result of the operation, without modifying the original"]
168    pub const fn to_le_bytes(self) -> [u8; 32] {
169        let words = self.0.digits();
170        let words = [
171            words[0].to_le_bytes(),
172            words[1].to_le_bytes(),
173            words[2].to_le_bytes(),
174            words[3].to_le_bytes(),
175        ];
176        unsafe { core::mem::transmute::<[[u8; 8]; 4], [u8; 32]>(words) }
177    }
178
179    #[must_use]
180    pub const fn is_zero(&self) -> bool {
181        self.0.is_zero()
182    }
183
184    #[must_use = "this returns the result of the operation, without modifying the original"]
185    pub const fn pow(self, exp: u32) -> Self {
186        match self.0.checked_pow(exp) {
187            Some(val) => Self(val),
188            None => panic!("attempt to exponentiate with overflow"),
189        }
190    }
191
192    /// Returns the base 2 logarithm of the number, rounded down.
193    ///
194    /// # Panics
195    ///
196    /// This function will panic if `self` is zero.
197    #[must_use = "this returns the result of the operation, without modifying the original"]
198    pub fn ilog2(self) -> u32 {
199        self.0.checked_ilog2().unwrap()
200    }
201
202    /// Returns `self * numerator / denominator`.
203    ///
204    /// Due to the nature of the integer division involved, the result is always floored.
205    /// E.g. 5 * 99/100 = 4.
206    #[must_use = "this returns the result of the operation, without modifying the original"]
207    pub fn multiply_ratio<A: Into<Uint256>, B: Into<Uint256>>(
208        &self,
209        numerator: A,
210        denominator: B,
211    ) -> Uint256 {
212        match self.checked_multiply_ratio(numerator, denominator) {
213            Ok(value) => value,
214            Err(CheckedMultiplyRatioError::DivideByZero) => {
215                panic!("Denominator must not be zero")
216            }
217            Err(CheckedMultiplyRatioError::Overflow) => panic!("Multiplication overflow"),
218        }
219    }
220
221    /// Returns `self * numerator / denominator`.
222    ///
223    /// Due to the nature of the integer division involved, the result is always floored.
224    /// E.g. 5 * 99/100 = 4.
225    pub fn checked_multiply_ratio<A: Into<Uint256>, B: Into<Uint256>>(
226        &self,
227        numerator: A,
228        denominator: B,
229    ) -> Result<Uint256, CheckedMultiplyRatioError> {
230        let numerator: Uint256 = numerator.into();
231        let denominator: Uint256 = denominator.into();
232        if denominator.is_zero() {
233            return Err(CheckedMultiplyRatioError::DivideByZero);
234        }
235        match (self.full_mul(numerator) / Uint512::from(denominator)).try_into() {
236            Ok(ratio) => Ok(ratio),
237            Err(_) => Err(CheckedMultiplyRatioError::Overflow),
238        }
239    }
240
241    /// Multiplies two u256 values without overflow, producing an
242    /// [`Uint512`].
243    ///
244    /// # Examples
245    ///
246    /// ```
247    /// use cosmwasm_std::Uint256;
248    ///
249    /// let a = Uint256::MAX;
250    /// let result = a.full_mul(2u32);
251    /// assert_eq!(
252    ///     result.to_string(),
253    ///     "231584178474632390847141970017375815706539969331281128078915168015826259279870",
254    /// );
255    /// ```
256    #[must_use = "this returns the result of the operation, without modifying the original"]
257    pub fn full_mul(self, rhs: impl Into<Self>) -> Uint512 {
258        Uint512::from(self)
259            .checked_mul(Uint512::from(rhs.into()))
260            .unwrap()
261    }
262
263    pub fn checked_add(self, other: Self) -> Result<Self, OverflowError> {
264        self.0
265            .checked_add(other.0)
266            .map(Self)
267            .ok_or_else(|| OverflowError::new(OverflowOperation::Add))
268    }
269
270    pub fn checked_sub(self, other: Self) -> Result<Self, OverflowError> {
271        self.0
272            .checked_sub(other.0)
273            .map(Self)
274            .ok_or_else(|| OverflowError::new(OverflowOperation::Sub))
275    }
276
277    pub fn checked_mul(self, other: Self) -> Result<Self, OverflowError> {
278        self.0
279            .checked_mul(other.0)
280            .map(Self)
281            .ok_or_else(|| OverflowError::new(OverflowOperation::Mul))
282    }
283
284    pub fn checked_pow(self, exp: u32) -> Result<Self, OverflowError> {
285        self.0
286            .checked_pow(exp)
287            .map(Self)
288            .ok_or_else(|| OverflowError::new(OverflowOperation::Pow))
289    }
290
291    pub fn checked_div(self, other: Self) -> Result<Self, DivideByZeroError> {
292        self.0
293            .checked_div(other.0)
294            .map(Self)
295            .ok_or(DivideByZeroError)
296    }
297
298    pub fn checked_div_euclid(self, other: Self) -> Result<Self, DivideByZeroError> {
299        self.checked_div(other)
300    }
301
302    pub fn checked_rem(self, other: Self) -> Result<Self, DivideByZeroError> {
303        self.0
304            .checked_rem(other.0)
305            .map(Self)
306            .ok_or(DivideByZeroError)
307    }
308
309    pub fn checked_shr(self, other: u32) -> Result<Self, OverflowError> {
310        if other >= 256 {
311            return Err(OverflowError::new(OverflowOperation::Shr));
312        }
313
314        Ok(Self(self.0.shr(other)))
315    }
316
317    pub fn checked_shl(self, other: u32) -> Result<Self, OverflowError> {
318        if other >= 256 {
319            return Err(OverflowError::new(OverflowOperation::Shl));
320        }
321
322        Ok(Self(self.0.shl(other)))
323    }
324
325    #[must_use = "this returns the result of the operation, without modifying the original"]
326    #[inline]
327    pub fn wrapping_add(self, other: Self) -> Self {
328        Self(self.0.wrapping_add(other.0))
329    }
330
331    #[must_use = "this returns the result of the operation, without modifying the original"]
332    #[inline]
333    pub fn wrapping_sub(self, other: Self) -> Self {
334        Self(self.0.wrapping_sub(other.0))
335    }
336
337    #[must_use = "this returns the result of the operation, without modifying the original"]
338    #[inline]
339    pub fn wrapping_mul(self, other: Self) -> Self {
340        Self(self.0.wrapping_mul(other.0))
341    }
342
343    #[must_use = "this returns the result of the operation, without modifying the original"]
344    #[inline]
345    pub fn wrapping_pow(self, other: u32) -> Self {
346        Self(self.0.wrapping_pow(other))
347    }
348
349    #[must_use = "this returns the result of the operation, without modifying the original"]
350    pub fn saturating_add(self, other: Self) -> Self {
351        Self(self.0.saturating_add(other.0))
352    }
353
354    #[must_use = "this returns the result of the operation, without modifying the original"]
355    pub fn saturating_sub(self, other: Self) -> Self {
356        Self(self.0.saturating_sub(other.0))
357    }
358
359    #[must_use = "this returns the result of the operation, without modifying the original"]
360    pub fn saturating_mul(self, other: Self) -> Self {
361        Self(self.0.saturating_mul(other.0))
362    }
363
364    #[must_use = "this returns the result of the operation, without modifying the original"]
365    pub fn saturating_pow(self, exp: u32) -> Self {
366        Self(self.0.saturating_pow(exp))
367    }
368
369    /// Strict integer addition. Computes `self + rhs`, panicking if overflow occurred.
370    ///
371    /// This is the same as [`Uint256::add`] but const.
372    #[must_use = "this returns the result of the operation, without modifying the original"]
373    pub const fn strict_add(self, rhs: Self) -> Self {
374        match self.0.checked_add(rhs.0) {
375            None => panic!("attempt to add with overflow"),
376            Some(sum) => Self(sum),
377        }
378    }
379
380    /// Strict integer subtraction. Computes `self - rhs`, panicking if overflow occurred.
381    ///
382    /// This is the same as [`Uint256::sub`] but const.
383    #[must_use = "this returns the result of the operation, without modifying the original"]
384    pub const fn strict_sub(self, other: Self) -> Self {
385        match self.0.checked_sub(other.0) {
386            None => panic!("attempt to subtract with overflow"),
387            Some(diff) => Self(diff),
388        }
389    }
390
391    #[must_use = "this returns the result of the operation, without modifying the original"]
392    pub const fn abs_diff(self, other: Self) -> Self {
393        Self(self.0.abs_diff(other.0))
394    }
395}
396
397impl NumConsts for Uint256 {
398    const ZERO: Self = Self::zero();
399    const ONE: Self = Self::one();
400    const MAX: Self = Self::MAX;
401    const MIN: Self = Self::MIN;
402}
403
404impl_mul_fraction!(Uint256);
405
406// uint to Uint
407primitive_to_wrapped_int!(u8, Uint256);
408primitive_to_wrapped_int!(u16, Uint256);
409primitive_to_wrapped_int!(u32, Uint256);
410primitive_to_wrapped_int!(u64, Uint256);
411primitive_to_wrapped_int!(u128, Uint256);
412
413impl From<Uint128> for Uint256 {
414    fn from(val: Uint128) -> Self {
415        val.u128().into()
416    }
417}
418
419impl From<Uint64> for Uint256 {
420    fn from(val: Uint64) -> Self {
421        val.u64().into()
422    }
423}
424
425forward_try_from!(Uint256, Uint128);
426forward_try_from!(Uint256, Uint64);
427
428// Int to Uint
429try_from_int_to_uint!(Int64, Uint256);
430try_from_int_to_uint!(Int128, Uint256);
431try_from_int_to_uint!(Int256, Uint256);
432try_from_int_to_uint!(Int512, Uint256);
433
434impl TryFrom<&str> for Uint256 {
435    type Error = StdError;
436
437    fn try_from(val: &str) -> Result<Self, Self::Error> {
438        Self::from_str(val)
439    }
440}
441
442impl FromStr for Uint256 {
443    type Err = StdError;
444
445    fn from_str(s: &str) -> Result<Self, Self::Err> {
446        if s.is_empty() {
447            return Err(
448                StdError::msg("Parsing u256: received empty string").with_kind(ErrorKind::Parsing)
449            );
450        }
451
452        match U256::from_str_radix(s, 10) {
453            Ok(u) => Ok(Uint256(u)),
454            Err(e) => {
455                Err(StdError::msg(format_args!("Parsing u256: {e}")).with_kind(ErrorKind::Parsing))
456            }
457        }
458    }
459}
460
461impl From<Uint256> for String {
462    fn from(original: Uint256) -> Self {
463        original.to_string()
464    }
465}
466
467impl fmt::Display for Uint256 {
468    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
469        self.0.fmt(f)
470    }
471}
472
473impl Add<Uint256> for Uint256 {
474    type Output = Self;
475
476    fn add(self, rhs: Self) -> Self {
477        self.strict_add(rhs)
478    }
479}
480forward_ref_binop!(impl Add, add for Uint256, Uint256);
481
482impl Sub<Uint256> for Uint256 {
483    type Output = Self;
484
485    fn sub(self, rhs: Self) -> Self {
486        self.strict_sub(rhs)
487    }
488}
489forward_ref_binop!(impl Sub, sub for Uint256, Uint256);
490
491impl SubAssign<Uint256> for Uint256 {
492    fn sub_assign(&mut self, rhs: Uint256) {
493        *self = *self - rhs;
494    }
495}
496forward_ref_op_assign!(impl SubAssign, sub_assign for Uint256, Uint256);
497
498impl Div<Uint256> for Uint256 {
499    type Output = Self;
500
501    fn div(self, rhs: Self) -> Self::Output {
502        Self(
503            self.0
504                .checked_div(rhs.0)
505                .expect("attempt to divide by zero"),
506        )
507    }
508}
509
510impl<'a> Div<&'a Uint256> for Uint256 {
511    type Output = Self;
512
513    fn div(self, rhs: &'a Uint256) -> Self::Output {
514        self / *rhs
515    }
516}
517
518impl Rem for Uint256 {
519    type Output = Self;
520
521    /// # Panics
522    ///
523    /// This operation will panic if `rhs` is zero.
524    #[inline]
525    fn rem(self, rhs: Self) -> Self {
526        Self(self.0.rem(rhs.0))
527    }
528}
529forward_ref_binop!(impl Rem, rem for Uint256, Uint256);
530
531impl Not for Uint256 {
532    type Output = Self;
533
534    fn not(self) -> Self::Output {
535        Self(!self.0)
536    }
537}
538
539impl RemAssign<Uint256> for Uint256 {
540    fn rem_assign(&mut self, rhs: Uint256) {
541        *self = *self % rhs;
542    }
543}
544forward_ref_op_assign!(impl RemAssign, rem_assign for Uint256, Uint256);
545
546impl Mul<Uint256> for Uint256 {
547    type Output = Self;
548
549    fn mul(self, rhs: Self) -> Self::Output {
550        Self(
551            self.0
552                .checked_mul(rhs.0)
553                .expect("attempt to multiply with overflow"),
554        )
555    }
556}
557forward_ref_binop!(impl Mul, mul for Uint256, Uint256);
558
559impl MulAssign<Uint256> for Uint256 {
560    fn mul_assign(&mut self, rhs: Self) {
561        *self = *self * rhs;
562    }
563}
564forward_ref_op_assign!(impl MulAssign, mul_assign for Uint256, Uint256);
565
566impl Shr<u32> for Uint256 {
567    type Output = Self;
568
569    fn shr(self, rhs: u32) -> Self::Output {
570        self.checked_shr(rhs).unwrap_or_else(|_| {
571            panic!(
572                "right shift error: {rhs} is larger or equal than the number of bits in Uint256",
573            )
574        })
575    }
576}
577
578impl<'a> Shr<&'a u32> for Uint256 {
579    type Output = Self;
580
581    fn shr(self, rhs: &'a u32) -> Self::Output {
582        self.shr(*rhs)
583    }
584}
585
586impl Shl<u32> for Uint256 {
587    type Output = Self;
588
589    fn shl(self, rhs: u32) -> Self::Output {
590        self.checked_shl(rhs)
591            .expect("attempt to shift left with overflow")
592    }
593}
594
595impl<'a> Shl<&'a u32> for Uint256 {
596    type Output = Self;
597
598    fn shl(self, rhs: &'a u32) -> Self::Output {
599        self.shl(*rhs)
600    }
601}
602
603impl AddAssign<Uint256> for Uint256 {
604    fn add_assign(&mut self, rhs: Uint256) {
605        *self = *self + rhs;
606    }
607}
608
609impl<'a> AddAssign<&'a Uint256> for Uint256 {
610    fn add_assign(&mut self, rhs: &'a Uint256) {
611        *self = *self + rhs;
612    }
613}
614
615impl DivAssign<Uint256> for Uint256 {
616    fn div_assign(&mut self, rhs: Self) {
617        *self = *self / rhs;
618    }
619}
620
621impl<'a> DivAssign<&'a Uint256> for Uint256 {
622    fn div_assign(&mut self, rhs: &'a Uint256) {
623        *self = *self / rhs;
624    }
625}
626
627impl ShrAssign<u32> for Uint256 {
628    fn shr_assign(&mut self, rhs: u32) {
629        *self = Shr::<u32>::shr(*self, rhs);
630    }
631}
632
633impl<'a> ShrAssign<&'a u32> for Uint256 {
634    fn shr_assign(&mut self, rhs: &'a u32) {
635        *self = Shr::<u32>::shr(*self, *rhs);
636    }
637}
638
639impl ShlAssign<u32> for Uint256 {
640    fn shl_assign(&mut self, rhs: u32) {
641        *self = self.shl(rhs);
642    }
643}
644
645impl<'a> ShlAssign<&'a u32> for Uint256 {
646    fn shl_assign(&mut self, rhs: &'a u32) {
647        *self = self.shl(*rhs);
648    }
649}
650
651impl<A> core::iter::Sum<A> for Uint256
652where
653    Self: Add<A, Output = Self>,
654{
655    fn sum<I: Iterator<Item = A>>(iter: I) -> Self {
656        iter.fold(Self::zero(), Add::add)
657    }
658}
659
660#[cfg(test)]
661mod tests {
662    use super::*;
663    use crate::errors::CheckedMultiplyFractionError::{ConversionOverflow, DivideByZero};
664    use crate::math::conversion::test_try_from_int_to_uint;
665    use crate::{Decimal, Decimal256};
666
667    #[test]
668    fn size_of_works() {
669        assert_eq!(core::mem::size_of::<Uint256>(), 32);
670    }
671
672    #[test]
673    fn uint256_new_works() {
674        let num = Uint256::new(1);
675        assert_eq!(
676            num.to_be_bytes(),
677            [
678                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
679                0, 0, 0, 1
680            ]
681        );
682
683        for v in [0, 1, 18, 875786576, u128::MAX] {
684            // From is implemented by bnum, so we test two independent implementations against each other
685            let uut = Uint256::new(v);
686            assert_eq!(uut, Uint256::from(v));
687        }
688    }
689
690    #[test]
691    fn uint256_from_be_bytes_works() {
692        let num = Uint256::from_be_bytes([1; 32]);
693        let a: [u8; 32] = num.to_be_bytes();
694        assert_eq!(a, [1; 32]);
695
696        let be_bytes = [
697            0u8, 222u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8,
698            0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 1u8, 2u8, 3u8,
699        ];
700        let num = Uint256::from_be_bytes(be_bytes);
701        let resulting_bytes: [u8; 32] = num.to_be_bytes();
702        assert_eq!(be_bytes, resulting_bytes);
703    }
704
705    #[test]
706    fn uint256_not_works() {
707        let num = Uint256::from_be_bytes([1; 32]);
708        let a = (!num).to_be_bytes();
709        assert_eq!(a, [254; 32]);
710
711        assert_eq!(!Uint256::MAX, Uint256::MIN);
712        assert_eq!(!Uint256::MIN, Uint256::MAX);
713    }
714
715    #[test]
716    fn uint256_zero_works() {
717        let zero = Uint256::zero();
718        assert_eq!(
719            zero.to_be_bytes(),
720            [
721                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
722                0, 0, 0, 0
723            ]
724        );
725    }
726
727    #[test]
728    fn uin256_one_works() {
729        let one = Uint256::one();
730        assert_eq!(
731            one.to_be_bytes(),
732            [
733                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
734                0, 0, 0, 1,
735            ]
736        );
737    }
738
739    #[test]
740    fn uint256_from_be_bytes() {
741        let a = Uint256::from_be_bytes([
742            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
743            0, 0, 0,
744        ]);
745        assert_eq!(a, Uint256::from(0u128));
746        let a = Uint256::from_be_bytes([
747            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
748            0, 0, 42,
749        ]);
750        assert_eq!(a, Uint256::from(42u128));
751        let a = Uint256::from_be_bytes([
752            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
753            0, 0, 1,
754        ]);
755        assert_eq!(a, Uint256::from(1u128));
756        let a = Uint256::from_be_bytes([
757            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
758            0, 1, 0,
759        ]);
760        assert_eq!(a, Uint256::from(256u128));
761        let a = Uint256::from_be_bytes([
762            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
763            1, 0, 0,
764        ]);
765        assert_eq!(a, Uint256::from(65536u128));
766        let a = Uint256::from_be_bytes([
767            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
768            0, 0, 0,
769        ]);
770        assert_eq!(a, Uint256::from(16777216u128));
771        let a = Uint256::from_be_bytes([
772            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0,
773            0, 0, 0,
774        ]);
775        assert_eq!(a, Uint256::from(4294967296u128));
776        let a = Uint256::from_be_bytes([
777            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0,
778            0, 0, 0,
779        ]);
780        assert_eq!(a, Uint256::from(1099511627776u128));
781        let a = Uint256::from_be_bytes([
782            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0,
783            0, 0, 0,
784        ]);
785        assert_eq!(a, Uint256::from(281474976710656u128));
786        let a = Uint256::from_be_bytes([
787            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0,
788            0, 0, 0,
789        ]);
790        assert_eq!(a, Uint256::from(72057594037927936u128));
791        let a = Uint256::from_be_bytes([
792            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0,
793            0, 0, 0,
794        ]);
795        assert_eq!(a, Uint256::from(18446744073709551616u128));
796        let a = Uint256::from_be_bytes([
797            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0,
798            0, 0, 0,
799        ]);
800        assert_eq!(a, Uint256::from(4722366482869645213696u128));
801        let a = Uint256::from_be_bytes([
802            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0,
803            0, 0, 0,
804        ]);
805        assert_eq!(a, Uint256::from(1208925819614629174706176u128));
806        let a = Uint256::from_be_bytes([
807            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
808            0, 0, 0,
809        ]);
810        assert_eq!(a, Uint256::from(1329227995784915872903807060280344576u128));
811
812        // Values > u128::MAX
813        let a = Uint256::from_be_bytes([
814            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
815            0, 0, 0,
816        ]);
817        assert_eq!(a, Uint256::from(1u128) << (8 * 16));
818        let a = Uint256::from_be_bytes([
819            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
820            0, 0, 0,
821        ]);
822        assert_eq!(a, Uint256::from(1u128) << (8 * 17));
823        let a = Uint256::from_be_bytes([
824            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
825            0, 0, 0,
826        ]);
827        assert_eq!(a, Uint256::from(1u128) << (8 * 18));
828        let a = Uint256::from_be_bytes([
829            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
830            0, 0, 0,
831        ]);
832        assert_eq!(a, Uint256::from(1u128) << (8 * 19));
833        let a = Uint256::from_be_bytes([
834            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
835            0, 0, 0,
836        ]);
837        assert_eq!(a, Uint256::from(1u128) << (8 * 20));
838        let a = Uint256::from_be_bytes([
839            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
840            0, 0, 0,
841        ]);
842        assert_eq!(a, Uint256::from(1u128) << (8 * 21));
843        let a = Uint256::from_be_bytes([
844            0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
845            0, 0, 0,
846        ]);
847        assert_eq!(a, Uint256::from(1u128) << (8 * 22));
848        let a = Uint256::from_be_bytes([
849            0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
850            0, 0, 0,
851        ]);
852        assert_eq!(a, Uint256::from(1u128) << (8 * 23));
853        let a = Uint256::from_be_bytes([
854            0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
855            0, 0, 0,
856        ]);
857        assert_eq!(a, Uint256::from(1u128) << (8 * 24));
858        let a = Uint256::from_be_bytes([
859            0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
860            0, 0, 0,
861        ]);
862        assert_eq!(a, Uint256::from(1u128) << (8 * 25));
863        let a = Uint256::from_be_bytes([
864            0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
865            0, 0, 0,
866        ]);
867        assert_eq!(a, Uint256::from(1u128) << (8 * 26));
868        let a = Uint256::from_be_bytes([
869            0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
870            0, 0, 0,
871        ]);
872        assert_eq!(a, Uint256::from(1u128) << (8 * 27));
873        let a = Uint256::from_be_bytes([
874            0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
875            0, 0, 0,
876        ]);
877        assert_eq!(a, Uint256::from(1u128) << (8 * 28));
878        let a = Uint256::from_be_bytes([
879            0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
880            0, 0, 0,
881        ]);
882        assert_eq!(a, Uint256::from(1u128) << (8 * 29));
883        let a = Uint256::from_be_bytes([
884            0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
885            0, 0, 0,
886        ]);
887        assert_eq!(a, Uint256::from(1u128) << (8 * 30));
888        let a = Uint256::from_be_bytes([
889            1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
890            0, 0, 0,
891        ]);
892        assert_eq!(a, Uint256::from(1u128) << (8 * 31));
893    }
894
895    #[test]
896    fn uint256_from_le_bytes() {
897        let a = Uint256::from_le_bytes([
898            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
899            0, 0, 0,
900        ]);
901        assert_eq!(a, Uint256::from(0u128));
902        let a = Uint256::from_le_bytes([
903            42, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
904            0, 0, 0,
905        ]);
906        assert_eq!(a, Uint256::from(42u128));
907        let a = Uint256::from_le_bytes([
908            1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
909            0, 0, 0,
910        ]);
911        assert_eq!(a, Uint256::from(1u128));
912        let a = Uint256::from_le_bytes([
913            0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
914            0, 0, 0,
915        ]);
916        assert_eq!(a, Uint256::from(256u128));
917        let a = Uint256::from_le_bytes([
918            0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
919            0, 0, 0,
920        ]);
921        assert_eq!(a, Uint256::from(65536u128));
922        let a = Uint256::from_le_bytes([
923            0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
924            0, 0, 0,
925        ]);
926        assert_eq!(a, Uint256::from(16777216u128));
927        let a = Uint256::from_le_bytes([
928            0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
929            0, 0, 0,
930        ]);
931        assert_eq!(a, Uint256::from(4294967296u128));
932        let a = Uint256::from_le_bytes([
933            0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
934            0, 0, 0,
935        ]);
936        assert_eq!(a, Uint256::from(72057594037927936u128));
937        let a = Uint256::from_le_bytes([
938            0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
939            0, 0, 0,
940        ]);
941        assert_eq!(a, Uint256::from(18446744073709551616u128));
942        let a = Uint256::from_le_bytes([
943            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
944            0, 0, 0,
945        ]);
946        assert_eq!(a, Uint256::from(1329227995784915872903807060280344576u128));
947
948        // Values > u128::MAX
949        let a = Uint256::from_le_bytes([
950            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
951            0, 0, 0,
952        ]);
953        assert_eq!(a, Uint256::from(1u128) << (8 * 16));
954        let a = Uint256::from_le_bytes([
955            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
956            0, 0, 0,
957        ]);
958        assert_eq!(a, Uint256::from(1u128) << (8 * 17));
959        let a = Uint256::from_le_bytes([
960            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
961            0, 0, 0,
962        ]);
963        assert_eq!(a, Uint256::from(1u128) << (8 * 18));
964        let a = Uint256::from_le_bytes([
965            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
966            0, 0, 0,
967        ]);
968        assert_eq!(a, Uint256::from(1u128) << (8 * 19));
969        let a = Uint256::from_le_bytes([
970            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
971            0, 0, 0,
972        ]);
973        assert_eq!(a, Uint256::from(1u128) << (8 * 20));
974        let a = Uint256::from_le_bytes([
975            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0,
976            0, 0, 0,
977        ]);
978        assert_eq!(a, Uint256::from(1u128) << (8 * 21));
979        let a = Uint256::from_le_bytes([
980            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0,
981            0, 0, 0,
982        ]);
983        assert_eq!(a, Uint256::from(1u128) << (8 * 22));
984        let a = Uint256::from_le_bytes([
985            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0,
986            0, 0, 0,
987        ]);
988        assert_eq!(a, Uint256::from(1u128) << (8 * 23));
989        let a = Uint256::from_le_bytes([
990            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0,
991            0, 0, 0,
992        ]);
993        assert_eq!(a, Uint256::from(1u128) << (8 * 24));
994        let a = Uint256::from_le_bytes([
995            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0,
996            0, 0, 0,
997        ]);
998        assert_eq!(a, Uint256::from(1u128) << (8 * 25));
999        let a = Uint256::from_le_bytes([
1000            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0,
1001            0, 0, 0,
1002        ]);
1003        assert_eq!(a, Uint256::from(1u128) << (8 * 26));
1004        let a = Uint256::from_le_bytes([
1005            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0,
1006            0, 0, 0,
1007        ]);
1008        assert_eq!(a, Uint256::from(1u128) << (8 * 27));
1009        let a = Uint256::from_le_bytes([
1010            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
1011            0, 0, 0,
1012        ]);
1013        assert_eq!(a, Uint256::from(1u128) << (8 * 28));
1014        let a = Uint256::from_le_bytes([
1015            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1016            1, 0, 0,
1017        ]);
1018        assert_eq!(a, Uint256::from(1u128) << (8 * 29));
1019        let a = Uint256::from_le_bytes([
1020            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1021            0, 1, 0,
1022        ]);
1023        assert_eq!(a, Uint256::from(1u128) << (8 * 30));
1024        let a = Uint256::from_le_bytes([
1025            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1026            0, 0, 1,
1027        ]);
1028        assert_eq!(a, Uint256::from(1u128) << (8 * 31));
1029    }
1030
1031    #[test]
1032    fn uint256_endianness() {
1033        let be_bytes = [
1034            0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8,
1035            0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 1u8, 2u8, 3u8,
1036        ];
1037        let le_bytes = [
1038            3u8, 2u8, 1u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8,
1039            0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8,
1040        ];
1041
1042        // These should all be the same.
1043        let a = Uint256::from_be_bytes(be_bytes);
1044        let b = Uint256::from_le_bytes(le_bytes);
1045        assert_eq!(a, Uint256::from(65536u32 + 512 + 3));
1046        assert_eq!(a, b);
1047    }
1048
1049    #[test]
1050    fn uint256_convert_from() {
1051        let a = Uint256::from(5u128);
1052        assert_eq!(a.0, U256::from(5u32));
1053
1054        let a = Uint256::from(5u64);
1055        assert_eq!(a.0, U256::from(5u32));
1056
1057        let a = Uint256::from(5u32);
1058        assert_eq!(a.0, U256::from(5u32));
1059
1060        let a = Uint256::from(5u16);
1061        assert_eq!(a.0, U256::from(5u32));
1062
1063        let a = Uint256::from(5u8);
1064        assert_eq!(a.0, U256::from(5u32));
1065
1066        let result = Uint256::try_from("34567");
1067        assert_eq!(
1068            result.unwrap().0,
1069            U256::from_str_radix("34567", 10).unwrap()
1070        );
1071
1072        let result = Uint256::try_from("1.23");
1073        assert!(result.is_err());
1074    }
1075
1076    #[test]
1077    fn uint256_try_from_signed_works() {
1078        test_try_from_int_to_uint::<Int64, Uint256>("Int64", "Uint256");
1079        test_try_from_int_to_uint::<Int128, Uint256>("Int128", "Uint256");
1080        test_try_from_int_to_uint::<Int256, Uint256>("Int256", "Uint256");
1081        test_try_from_int_to_uint::<Int512, Uint256>("Int512", "Uint256");
1082    }
1083
1084    #[test]
1085    fn uint256_try_into() {
1086        assert!(Uint64::try_from(Uint256::MAX).is_err());
1087        assert!(Uint128::try_from(Uint256::MAX).is_err());
1088
1089        assert_eq!(Uint64::try_from(Uint256::zero()), Ok(Uint64::zero()));
1090        assert_eq!(Uint128::try_from(Uint256::zero()), Ok(Uint128::zero()));
1091
1092        assert_eq!(
1093            Uint64::try_from(Uint256::from(42u64)),
1094            Ok(Uint64::from(42u64))
1095        );
1096        assert_eq!(
1097            Uint128::try_from(Uint256::from(42u128)),
1098            Ok(Uint128::from(42u128))
1099        );
1100    }
1101
1102    #[test]
1103    fn uint256_convert_to_uint128() {
1104        let source = Uint256::from(42u128);
1105        let target = Uint128::try_from(source);
1106        assert_eq!(target, Ok(Uint128::new(42u128)));
1107
1108        let source = Uint256::MAX;
1109        let target = Uint128::try_from(source);
1110        assert_eq!(
1111            target,
1112            Err(ConversionOverflowError::new("Uint256", "Uint128"))
1113        );
1114    }
1115
1116    #[test]
1117    #[allow(deprecated)]
1118    fn uint256_from_u128() {
1119        assert_eq!(
1120            Uint256::from_u128(123u128),
1121            Uint256::from_str("123").unwrap()
1122        );
1123
1124        assert_eq!(
1125            Uint256::from_u128(9785746283745u128),
1126            Uint256::from_str("9785746283745").unwrap()
1127        );
1128    }
1129
1130    #[test]
1131    fn uint256_from_uint128() {
1132        assert_eq!(
1133            Uint256::from_uint128(Uint128::new(123)),
1134            Uint256::from_str("123").unwrap()
1135        );
1136
1137        assert_eq!(
1138            Uint256::from_uint128(Uint128::new(9785746283745)),
1139            Uint256::from_str("9785746283745").unwrap()
1140        );
1141    }
1142
1143    #[test]
1144    fn uint256_implements_display() {
1145        let a = Uint256::from(12345u32);
1146        assert_eq!(format!("Embedded: {a}"), "Embedded: 12345");
1147        assert_eq!(a.to_string(), "12345");
1148
1149        let a = Uint256::zero();
1150        assert_eq!(format!("Embedded: {a}"), "Embedded: 0");
1151        assert_eq!(a.to_string(), "0");
1152    }
1153
1154    #[test]
1155    fn uint256_display_padding_works() {
1156        // width > natural representation
1157        let a = Uint256::from(123u64);
1158        assert_eq!(format!("Embedded: {a:05}"), "Embedded: 00123");
1159
1160        // width < natural representation
1161        let a = Uint256::from(123u64);
1162        assert_eq!(format!("Embedded: {a:02}"), "Embedded: 123");
1163    }
1164
1165    #[test]
1166    fn uint256_to_be_bytes_works() {
1167        assert_eq!(
1168            Uint256::zero().to_be_bytes(),
1169            [
1170                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1171                0, 0, 0, 0,
1172            ]
1173        );
1174        assert_eq!(
1175            Uint256::MAX.to_be_bytes(),
1176            [
1177                0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
1178                0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
1179                0xff, 0xff, 0xff, 0xff,
1180            ]
1181        );
1182        assert_eq!(
1183            Uint256::from(1u128).to_be_bytes(),
1184            [
1185                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1186                0, 0, 0, 1
1187            ]
1188        );
1189        // Python: `[b for b in (240282366920938463463374607431768124608).to_bytes(32, "big")]`
1190        assert_eq!(
1191            Uint256::from(240282366920938463463374607431768124608u128).to_be_bytes(),
1192            [
1193                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 180, 196, 179, 87, 165, 121, 59,
1194                133, 246, 117, 221, 191, 255, 254, 172, 192
1195            ]
1196        );
1197        assert_eq!(
1198            Uint256::from_be_bytes([
1199                233, 2, 240, 200, 115, 150, 240, 218, 88, 106, 45, 208, 134, 238, 119, 85, 22, 14,
1200                88, 166, 195, 154, 73, 64, 10, 44, 252, 96, 230, 187, 38, 29
1201            ])
1202            .to_be_bytes(),
1203            [
1204                233, 2, 240, 200, 115, 150, 240, 218, 88, 106, 45, 208, 134, 238, 119, 85, 22, 14,
1205                88, 166, 195, 154, 73, 64, 10, 44, 252, 96, 230, 187, 38, 29
1206            ]
1207        );
1208    }
1209
1210    #[test]
1211    fn uint256_to_le_bytes_works() {
1212        assert_eq!(
1213            Uint256::zero().to_le_bytes(),
1214            [
1215                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1216                0, 0, 0, 0
1217            ]
1218        );
1219        assert_eq!(
1220            Uint256::MAX.to_le_bytes(),
1221            [
1222                0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
1223                0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
1224                0xff, 0xff, 0xff, 0xff
1225            ]
1226        );
1227        assert_eq!(
1228            Uint256::from(1u128).to_le_bytes(),
1229            [
1230                1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1231                0, 0, 0, 0
1232            ]
1233        );
1234        // Python: `[b for b in (240282366920938463463374607431768124608).to_bytes(32, "little")]`
1235        assert_eq!(
1236            Uint256::from(240282366920938463463374607431768124608u128).to_le_bytes(),
1237            [
1238                192, 172, 254, 255, 191, 221, 117, 246, 133, 59, 121, 165, 87, 179, 196, 180, 0, 0,
1239                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
1240            ]
1241        );
1242        assert_eq!(
1243            Uint256::from_be_bytes([
1244                233, 2, 240, 200, 115, 150, 240, 218, 88, 106, 45, 208, 134, 238, 119, 85, 22, 14,
1245                88, 166, 195, 154, 73, 64, 10, 44, 252, 96, 230, 187, 38, 29
1246            ])
1247            .to_le_bytes(),
1248            [
1249                29, 38, 187, 230, 96, 252, 44, 10, 64, 73, 154, 195, 166, 88, 14, 22, 85, 119, 238,
1250                134, 208, 45, 106, 88, 218, 240, 150, 115, 200, 240, 2, 233
1251            ]
1252        );
1253    }
1254
1255    #[test]
1256    fn uint256_is_zero_works() {
1257        assert!(Uint256::zero().is_zero());
1258        assert!(Uint256(U256::from(0u32)).is_zero());
1259
1260        assert!(!Uint256::from(1u32).is_zero());
1261        assert!(!Uint256::from(123u32).is_zero());
1262    }
1263
1264    #[test]
1265    fn uint256_wrapping_methods() {
1266        // wrapping_add
1267        assert_eq!(
1268            Uint256::from(2u32).wrapping_add(Uint256::from(2u32)),
1269            Uint256::from(4u32)
1270        ); // non-wrapping
1271        assert_eq!(
1272            Uint256::MAX.wrapping_add(Uint256::from(1u32)),
1273            Uint256::from(0u32)
1274        ); // wrapping
1275
1276        // wrapping_sub
1277        assert_eq!(
1278            Uint256::from(7u32).wrapping_sub(Uint256::from(5u32)),
1279            Uint256::from(2u32)
1280        ); // non-wrapping
1281        assert_eq!(
1282            Uint256::from(0u32).wrapping_sub(Uint256::from(1u32)),
1283            Uint256::MAX
1284        ); // wrapping
1285
1286        // wrapping_mul
1287        assert_eq!(
1288            Uint256::from(3u32).wrapping_mul(Uint256::from(2u32)),
1289            Uint256::from(6u32)
1290        ); // non-wrapping
1291        assert_eq!(
1292            Uint256::MAX.wrapping_mul(Uint256::from(2u32)),
1293            Uint256::MAX - Uint256::one()
1294        ); // wrapping
1295
1296        // wrapping_pow
1297        assert_eq!(Uint256::from(2u32).wrapping_pow(3), Uint256::from(8u32)); // non-wrapping
1298        assert_eq!(Uint256::MAX.wrapping_pow(2), Uint256::from(1u32)); // wrapping
1299    }
1300
1301    #[test]
1302    fn uint256_json() {
1303        let orig = Uint256::from(1234567890987654321u128);
1304        let serialized = serde_json::to_vec(&orig).unwrap();
1305        assert_eq!(serialized.as_slice(), b"\"1234567890987654321\"");
1306        let parsed: Uint256 = serde_json::from_slice(&serialized).unwrap();
1307        assert_eq!(parsed, orig);
1308    }
1309
1310    #[test]
1311    fn uint256_compare() {
1312        let a = Uint256::from(12345u32);
1313        let b = Uint256::from(23456u32);
1314
1315        assert!(a < b);
1316        assert!(b > a);
1317        assert_eq!(a, Uint256::from(12345u32));
1318    }
1319
1320    #[test]
1321    #[allow(clippy::op_ref)]
1322    fn uint256_math() {
1323        let a = Uint256::from(12345u32);
1324        let b = Uint256::from(23456u32);
1325
1326        // test - with owned and reference right hand side
1327        assert_eq!(b - a, Uint256::from(11111u32));
1328        assert_eq!(b - &a, Uint256::from(11111u32));
1329
1330        // test += with owned and reference right hand side
1331        let mut c = Uint256::from(300000u32);
1332        c += b;
1333        assert_eq!(c, Uint256::from(323456u32));
1334        let mut d = Uint256::from(300000u32);
1335        d += &b;
1336        assert_eq!(d, Uint256::from(323456u32));
1337
1338        // test -= with owned and reference right hand side
1339        let mut c = Uint256::from(300000u32);
1340        c -= b;
1341        assert_eq!(c, Uint256::from(276544u32));
1342        let mut d = Uint256::from(300000u32);
1343        d -= &b;
1344        assert_eq!(d, Uint256::from(276544u32));
1345
1346        // error result on underflow (- would produce negative result)
1347        let underflow_result = a.checked_sub(b);
1348        let OverflowError { operation } = underflow_result.unwrap_err();
1349        assert_eq!(operation, OverflowOperation::Sub);
1350    }
1351
1352    #[test]
1353    #[allow(clippy::op_ref)]
1354    fn uint256_add_works() {
1355        assert_eq!(
1356            Uint256::from(2u32) + Uint256::from(1u32),
1357            Uint256::from(3u32)
1358        );
1359        assert_eq!(
1360            Uint256::from(2u32) + Uint256::from(0u32),
1361            Uint256::from(2u32)
1362        );
1363
1364        // works for refs
1365        let a = Uint256::from(10u32);
1366        let b = Uint256::from(3u32);
1367        let expected = Uint256::from(13u32);
1368        assert_eq!(a + b, expected);
1369        assert_eq!(a + &b, expected);
1370        assert_eq!(&a + b, expected);
1371        assert_eq!(&a + &b, expected);
1372    }
1373
1374    #[test]
1375    #[should_panic(expected = "attempt to add with overflow")]
1376    fn uint256_add_overflow_panics() {
1377        let max = Uint256::from_be_bytes([255u8; 32]);
1378        let _ = max + Uint256::from(12u32);
1379    }
1380
1381    #[test]
1382    #[allow(clippy::op_ref)]
1383    fn uint256_sub_works() {
1384        assert_eq!(
1385            Uint256::from(2u32) - Uint256::from(1u32),
1386            Uint256::from(1u32)
1387        );
1388        assert_eq!(
1389            Uint256::from(2u32) - Uint256::from(0u32),
1390            Uint256::from(2u32)
1391        );
1392        assert_eq!(
1393            Uint256::from(2u32) - Uint256::from(2u32),
1394            Uint256::from(0u32)
1395        );
1396
1397        // works for refs
1398        let a = Uint256::from(10u32);
1399        let b = Uint256::from(3u32);
1400        let expected = Uint256::from(7u32);
1401        assert_eq!(a - b, expected);
1402        assert_eq!(a - &b, expected);
1403        assert_eq!(&a - b, expected);
1404        assert_eq!(&a - &b, expected);
1405    }
1406
1407    #[test]
1408    #[should_panic]
1409    fn uint256_sub_overflow_panics() {
1410        let _ = Uint256::from(1u32) - Uint256::from(2u32);
1411    }
1412
1413    #[test]
1414    fn uint256_sub_assign_works() {
1415        let mut a = Uint256::from(14u32);
1416        a -= Uint256::from(2u32);
1417        assert_eq!(a, Uint256::from(12u32));
1418
1419        // works for refs
1420        let mut a = Uint256::from(10u32);
1421        let b = Uint256::from(3u32);
1422        let expected = Uint256::from(7u32);
1423        a -= &b;
1424        assert_eq!(a, expected);
1425    }
1426
1427    #[test]
1428    #[allow(clippy::op_ref)]
1429    fn uint256_mul_works() {
1430        assert_eq!(
1431            Uint256::from(2u32) * Uint256::from(3u32),
1432            Uint256::from(6u32)
1433        );
1434        assert_eq!(Uint256::from(2u32) * Uint256::zero(), Uint256::zero());
1435
1436        // works for refs
1437        let a = Uint256::from(11u32);
1438        let b = Uint256::from(3u32);
1439        let expected = Uint256::from(33u32);
1440        assert_eq!(a * b, expected);
1441        assert_eq!(a * &b, expected);
1442        assert_eq!(&a * b, expected);
1443        assert_eq!(&a * &b, expected);
1444    }
1445
1446    #[test]
1447    fn uint256_mul_assign_works() {
1448        let mut a = Uint256::from(14u32);
1449        a *= Uint256::from(2u32);
1450        assert_eq!(a, Uint256::from(28u32));
1451
1452        // works for refs
1453        let mut a = Uint256::from(10u32);
1454        let b = Uint256::from(3u32);
1455        a *= &b;
1456        assert_eq!(a, Uint256::from(30u32));
1457    }
1458
1459    #[test]
1460    fn uint256_pow_works() {
1461        assert_eq!(Uint256::from(2u32).pow(2), Uint256::from(4u32));
1462        assert_eq!(Uint256::from(2u32).pow(10), Uint256::from(1024u32));
1463    }
1464
1465    #[test]
1466    #[should_panic]
1467    fn uint256_pow_overflow_panics() {
1468        _ = Uint256::MAX.pow(2u32);
1469    }
1470
1471    #[test]
1472    fn uint256_multiply_ratio_works() {
1473        let base = Uint256::from(500u32);
1474
1475        // factor 1/1
1476        assert_eq!(base.multiply_ratio(1u128, 1u128), base);
1477        assert_eq!(base.multiply_ratio(3u128, 3u128), base);
1478        assert_eq!(base.multiply_ratio(654321u128, 654321u128), base);
1479        assert_eq!(base.multiply_ratio(Uint256::MAX, Uint256::MAX), base);
1480
1481        // factor 3/2
1482        assert_eq!(base.multiply_ratio(3u128, 2u128), Uint256::from(750u32));
1483        assert_eq!(
1484            base.multiply_ratio(333333u128, 222222u128),
1485            Uint256::from(750u32)
1486        );
1487
1488        // factor 2/3 (integer division always floors the result)
1489        assert_eq!(base.multiply_ratio(2u128, 3u128), Uint256::from(333u32));
1490        assert_eq!(
1491            base.multiply_ratio(222222u128, 333333u128),
1492            Uint256::from(333u32)
1493        );
1494
1495        // factor 5/6 (integer division always floors the result)
1496        assert_eq!(base.multiply_ratio(5u128, 6u128), Uint256::from(416u32));
1497        assert_eq!(base.multiply_ratio(100u128, 120u128), Uint256::from(416u32));
1498    }
1499
1500    #[test]
1501    fn uint256_multiply_ratio_does_not_overflow_when_result_fits() {
1502        // Almost max value for Uint256.
1503        let base = Uint256::MAX - Uint256::from(9u8);
1504
1505        assert_eq!(base.multiply_ratio(2u128, 2u128), base);
1506    }
1507
1508    #[test]
1509    #[should_panic]
1510    fn uint256_multiply_ratio_panicks_on_overflow() {
1511        // Almost max value for Uint256.
1512        let base = Uint256::MAX - Uint256::from(9u8);
1513
1514        assert_eq!(base.multiply_ratio(2u128, 1u128), base);
1515    }
1516
1517    #[test]
1518    #[should_panic(expected = "Denominator must not be zero")]
1519    fn uint256_multiply_ratio_panics_for_zero_denominator() {
1520        _ = Uint256::from(500u32).multiply_ratio(1u128, 0u128);
1521    }
1522
1523    #[test]
1524    fn uint256_checked_multiply_ratio_does_not_panic() {
1525        assert_eq!(
1526            Uint256::from(500u32).checked_multiply_ratio(1u128, 0u128),
1527            Err(CheckedMultiplyRatioError::DivideByZero),
1528        );
1529        assert_eq!(
1530            Uint256::from(500u32).checked_multiply_ratio(Uint256::MAX, 1u128),
1531            Err(CheckedMultiplyRatioError::Overflow),
1532        );
1533    }
1534
1535    #[test]
1536    fn uint256_shr_works() {
1537        let original = Uint256::from_be_bytes([
1538            0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8,
1539            0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 2u8, 0u8, 4u8, 2u8,
1540        ]);
1541
1542        let shifted = Uint256::from_be_bytes([
1543            0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8,
1544            0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 128u8, 1u8, 0u8,
1545        ]);
1546
1547        assert_eq!(original >> 2u32, shifted);
1548    }
1549
1550    #[test]
1551    #[should_panic]
1552    fn uint256_shr_overflow_panics() {
1553        let _ = Uint256::from(1u32) >> 256u32;
1554    }
1555
1556    #[test]
1557    fn uint256_shl_works() {
1558        let original = Uint256::from_be_bytes([
1559            64u8, 128u8, 1u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8,
1560            0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8,
1561        ]);
1562
1563        let shifted = Uint256::from_be_bytes([
1564            2u8, 0u8, 4u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8,
1565            0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8,
1566        ]);
1567
1568        assert_eq!(original << 2u32, shifted);
1569    }
1570
1571    #[test]
1572    #[should_panic]
1573    fn uint256_shl_overflow_panics() {
1574        let _ = Uint256::from(1u32) << 256u32;
1575    }
1576
1577    #[test]
1578    fn sum_works() {
1579        let nums = vec![
1580            Uint256::from(17u32),
1581            Uint256::from(123u32),
1582            Uint256::from(540u32),
1583            Uint256::from(82u32),
1584        ];
1585        let expected = Uint256::from(762u32);
1586
1587        let sum_as_ref: Uint256 = nums.iter().sum();
1588        assert_eq!(expected, sum_as_ref);
1589
1590        let sum_as_owned: Uint256 = nums.into_iter().sum();
1591        assert_eq!(expected, sum_as_owned);
1592    }
1593
1594    #[test]
1595    fn uint256_methods() {
1596        // checked_*
1597        assert!(matches!(
1598            Uint256::MAX.checked_add(Uint256::from(1u32)),
1599            Err(OverflowError { .. })
1600        ));
1601        assert_eq!(
1602            Uint256::from(1u32).checked_add(Uint256::from(1u32)),
1603            Ok(Uint256::from(2u32)),
1604        );
1605        assert!(matches!(
1606            Uint256::from(0u32).checked_sub(Uint256::from(1u32)),
1607            Err(OverflowError { .. })
1608        ));
1609        assert_eq!(
1610            Uint256::from(2u32).checked_sub(Uint256::from(1u32)),
1611            Ok(Uint256::from(1u32)),
1612        );
1613        assert!(matches!(
1614            Uint256::MAX.checked_mul(Uint256::from(2u32)),
1615            Err(OverflowError { .. })
1616        ));
1617        assert_eq!(
1618            Uint256::from(2u32).checked_mul(Uint256::from(2u32)),
1619            Ok(Uint256::from(4u32)),
1620        );
1621        assert!(matches!(
1622            Uint256::MAX.checked_pow(2u32),
1623            Err(OverflowError { .. })
1624        ));
1625        assert_eq!(
1626            Uint256::from(2u32).checked_pow(3u32),
1627            Ok(Uint256::from(8u32)),
1628        );
1629        assert!(matches!(
1630            Uint256::MAX.checked_div(Uint256::from(0u32)),
1631            Err(DivideByZeroError { .. })
1632        ));
1633        assert_eq!(
1634            Uint256::from(6u32).checked_div(Uint256::from(2u32)),
1635            Ok(Uint256::from(3u32)),
1636        );
1637        assert!(matches!(
1638            Uint256::MAX.checked_div_euclid(Uint256::from(0u32)),
1639            Err(DivideByZeroError { .. })
1640        ));
1641        assert_eq!(
1642            Uint256::from(6u32).checked_div_euclid(Uint256::from(2u32)),
1643            Ok(Uint256::from(3u32)),
1644        );
1645        assert_eq!(
1646            Uint256::from(7u32).checked_div_euclid(Uint256::from(2u32)),
1647            Ok(Uint256::from(3u32)),
1648        );
1649        assert!(matches!(
1650            Uint256::MAX.checked_rem(Uint256::from(0u32)),
1651            Err(DivideByZeroError { .. })
1652        ));
1653
1654        // saturating_*
1655        assert_eq!(
1656            Uint256::MAX.saturating_add(Uint256::from(1u32)),
1657            Uint256::MAX
1658        );
1659        assert_eq!(
1660            Uint256::from(0u32).saturating_sub(Uint256::from(1u32)),
1661            Uint256::from(0u32)
1662        );
1663        assert_eq!(
1664            Uint256::MAX.saturating_mul(Uint256::from(2u32)),
1665            Uint256::MAX
1666        );
1667        assert_eq!(
1668            Uint256::from(4u32).saturating_pow(2u32),
1669            Uint256::from(16u32)
1670        );
1671        assert_eq!(Uint256::MAX.saturating_pow(2u32), Uint256::MAX);
1672    }
1673
1674    #[test]
1675    #[allow(clippy::op_ref)]
1676    fn uint256_implements_rem() {
1677        let a = Uint256::from(10u32);
1678        assert_eq!(a % Uint256::from(10u32), Uint256::zero());
1679        assert_eq!(a % Uint256::from(2u32), Uint256::zero());
1680        assert_eq!(a % Uint256::from(1u32), Uint256::zero());
1681        assert_eq!(a % Uint256::from(3u32), Uint256::from(1u32));
1682        assert_eq!(a % Uint256::from(4u32), Uint256::from(2u32));
1683
1684        // works for refs
1685        let a = Uint256::from(10u32);
1686        let b = Uint256::from(3u32);
1687        let expected = Uint256::from(1u32);
1688        assert_eq!(a % b, expected);
1689        assert_eq!(a % &b, expected);
1690        assert_eq!(&a % b, expected);
1691        assert_eq!(&a % &b, expected);
1692    }
1693
1694    #[test]
1695    #[should_panic(expected = "divisor of zero")]
1696    fn uint256_rem_panics_for_zero() {
1697        let _ = Uint256::from(10u32) % Uint256::zero();
1698    }
1699
1700    #[test]
1701    #[allow(clippy::op_ref)]
1702    fn uint256_rem_works() {
1703        assert_eq!(
1704            Uint256::from(12u32) % Uint256::from(10u32),
1705            Uint256::from(2u32)
1706        );
1707        assert_eq!(Uint256::from(50u32) % Uint256::from(5u32), Uint256::zero());
1708
1709        // works for refs
1710        let a = Uint256::from(42u32);
1711        let b = Uint256::from(5u32);
1712        let expected = Uint256::from(2u32);
1713        assert_eq!(a % b, expected);
1714        assert_eq!(a % &b, expected);
1715        assert_eq!(&a % b, expected);
1716        assert_eq!(&a % &b, expected);
1717    }
1718
1719    #[test]
1720    fn uint256_rem_assign_works() {
1721        let mut a = Uint256::from(30u32);
1722        a %= Uint256::from(4u32);
1723        assert_eq!(a, Uint256::from(2u32));
1724
1725        // works for refs
1726        let mut a = Uint256::from(25u32);
1727        let b = Uint256::from(6u32);
1728        a %= &b;
1729        assert_eq!(a, Uint256::from(1u32));
1730    }
1731
1732    #[test]
1733    fn uint256_strict_add_works() {
1734        let a = Uint256::from(5u32);
1735        let b = Uint256::from(3u32);
1736        assert_eq!(a.strict_add(b), Uint256::from(8u32));
1737        assert_eq!(b.strict_add(a), Uint256::from(8u32));
1738    }
1739
1740    #[test]
1741    #[should_panic(expected = "attempt to add with overflow")]
1742    fn uint256_strict_add_panics_on_overflow() {
1743        let a = Uint256::MAX;
1744        let b = Uint256::ONE;
1745        let _ = a.strict_add(b);
1746    }
1747
1748    #[test]
1749    fn uint256_strict_sub_works() {
1750        let a = Uint256::from(5u32);
1751        let b = Uint256::from(3u32);
1752        assert_eq!(a.strict_sub(b), Uint256::from(2u32));
1753    }
1754
1755    #[test]
1756    #[should_panic(expected = "attempt to subtract with overflow")]
1757    fn uint256_strict_sub_panics_on_overflow() {
1758        let a = Uint256::ZERO;
1759        let b = Uint256::ONE;
1760        let _ = a.strict_sub(b);
1761    }
1762
1763    #[test]
1764    fn uint256_abs_diff_works() {
1765        let a = Uint256::from(42u32);
1766        let b = Uint256::from(5u32);
1767        let expected = Uint256::from(37u32);
1768        assert_eq!(a.abs_diff(b), expected);
1769        assert_eq!(b.abs_diff(a), expected);
1770    }
1771
1772    #[test]
1773    fn uint256_partial_eq() {
1774        let test_cases = [(1, 1, true), (42, 42, true), (42, 24, false), (0, 0, true)]
1775            .into_iter()
1776            .map(|(lhs, rhs, expected): (u64, u64, bool)| {
1777                (Uint256::from(lhs), Uint256::from(rhs), expected)
1778            });
1779
1780        #[allow(clippy::op_ref)]
1781        for (lhs, rhs, expected) in test_cases {
1782            assert_eq!(lhs == rhs, expected);
1783            assert_eq!(&lhs == rhs, expected);
1784            assert_eq!(lhs == &rhs, expected);
1785            assert_eq!(&lhs == &rhs, expected);
1786        }
1787    }
1788
1789    #[test]
1790    fn mul_floor_works_with_zero() {
1791        let fraction = (Uint256::zero(), Uint256::from(21u32));
1792        let res = Uint256::from(123456u32).mul_floor(fraction);
1793        assert_eq!(Uint256::zero(), res)
1794    }
1795
1796    #[test]
1797    fn mul_floor_does_nothing_with_one() {
1798        let fraction = (Uint256::one(), Uint256::one());
1799        let res = Uint256::from(123456u32).mul_floor(fraction);
1800        assert_eq!(Uint256::from(123456u32), res)
1801    }
1802
1803    #[test]
1804    fn mul_floor_rounds_down_with_normal_case() {
1805        let fraction = (Uint256::from(8u128), Uint256::from(21u128));
1806        let res = Uint256::from(123456u32).mul_floor(fraction); // 47030.8571
1807        assert_eq!(Uint256::from(47030u32), res)
1808    }
1809
1810    #[test]
1811    fn mul_floor_does_not_round_on_even_divide() {
1812        let fraction = (2u128, 5u128);
1813        let res = Uint256::from(25u32).mul_floor(fraction);
1814        assert_eq!(Uint256::from(10u32), res)
1815    }
1816
1817    #[test]
1818    fn mul_floor_works_when_operation_temporarily_takes_above_max() {
1819        let fraction = (8u128, 21u128);
1820        let res = Uint256::MAX.mul_floor(fraction); // 44_111_272_090_406_169_685_169_899_050_928_726_801_245_708_444_053_548_205_507_651_050_633_573_196_165.71428571
1821        assert_eq!(
1822            Uint256::from_str(
1823                "44111272090406169685169899050928726801245708444053548205507651050633573196165"
1824            )
1825            .unwrap(),
1826            res
1827        )
1828    }
1829
1830    #[test]
1831    fn mul_floor_works_with_decimal() {
1832        let decimal = Decimal::from_ratio(8u128, 21u128);
1833        let res = Uint256::from(123456u32).mul_floor(decimal); // 47030.8571
1834        assert_eq!(Uint256::from(47030u32), res)
1835    }
1836
1837    #[test]
1838    fn mul_floor_works_with_decimal256() {
1839        let decimal = Decimal256::from_ratio(8u128, 21u128);
1840        let res = Uint256::from(123456u32).mul_floor(decimal); // 47030.8571
1841        assert_eq!(Uint256::from(47030u32), res)
1842    }
1843
1844    #[test]
1845    #[should_panic(expected = "ConversionOverflowError")]
1846    fn mul_floor_panics_on_overflow() {
1847        let fraction = (21u128, 8u128);
1848        _ = Uint256::MAX.mul_floor(fraction);
1849    }
1850
1851    #[test]
1852    fn checked_mul_floor_does_not_panic_on_overflow() {
1853        let fraction = (21u128, 8u128);
1854        assert_eq!(
1855            Uint256::MAX.checked_mul_floor(fraction),
1856            Err(ConversionOverflow(ConversionOverflowError {
1857                source_type: "Uint512",
1858                target_type: "Uint256",
1859            })),
1860        );
1861    }
1862
1863    #[test]
1864    #[should_panic(expected = "DivideByZeroError")]
1865    fn mul_floor_panics_on_zero_div() {
1866        let fraction = (21u128, 0u128);
1867        _ = Uint256::from(123456u32).mul_floor(fraction);
1868    }
1869
1870    #[test]
1871    fn checked_mul_floor_does_not_panic_on_zero_div() {
1872        let fraction = (21u128, 0u128);
1873        assert_eq!(
1874            Uint256::from(123456u32).checked_mul_floor(fraction),
1875            Err(DivideByZero(DivideByZeroError)),
1876        );
1877    }
1878
1879    #[test]
1880    fn mul_ceil_works_with_zero() {
1881        let fraction = (Uint256::zero(), Uint256::from(21u32));
1882        let res = Uint256::from(123456u32).mul_ceil(fraction);
1883        assert_eq!(Uint256::zero(), res)
1884    }
1885
1886    #[test]
1887    fn mul_ceil_does_nothing_with_one() {
1888        let fraction = (Uint256::one(), Uint256::one());
1889        let res = Uint256::from(123456u32).mul_ceil(fraction);
1890        assert_eq!(Uint256::from(123456u32), res)
1891    }
1892
1893    #[test]
1894    fn mul_ceil_rounds_up_with_normal_case() {
1895        let fraction = (8u128, 21u128);
1896        let res = Uint256::from(123456u32).mul_ceil(fraction); // 47030.8571
1897        assert_eq!(Uint256::from(47031u32), res)
1898    }
1899
1900    #[test]
1901    fn mul_ceil_does_not_round_on_even_divide() {
1902        let fraction = (2u128, 5u128);
1903        let res = Uint256::from(25u32).mul_ceil(fraction);
1904        assert_eq!(Uint256::from(10u32), res)
1905    }
1906
1907    #[test]
1908    fn mul_ceil_works_when_operation_temporarily_takes_above_max() {
1909        let fraction = (8u128, 21u128);
1910        let res = Uint256::MAX.mul_ceil(fraction); // 44_111_272_090_406_169_685_169_899_050_928_726_801_245_708_444_053_548_205_507_651_050_633_573_196_165.71428571
1911        assert_eq!(
1912            Uint256::from_str(
1913                "44111272090406169685169899050928726801245708444053548205507651050633573196166"
1914            )
1915            .unwrap(),
1916            res
1917        )
1918    }
1919
1920    #[test]
1921    fn mul_ceil_works_with_decimal() {
1922        let decimal = Decimal::from_ratio(8u128, 21u128);
1923        let res = Uint256::from(123456u32).mul_ceil(decimal); // 47030.8571
1924        assert_eq!(Uint256::from(47031u32), res)
1925    }
1926
1927    #[test]
1928    fn mul_ceil_works_with_decimal256() {
1929        let decimal = Decimal256::from_ratio(8u128, 21u128);
1930        let res = Uint256::from(123456u32).mul_ceil(decimal); // 47030.8571
1931        assert_eq!(Uint256::from(47031u32), res)
1932    }
1933
1934    #[test]
1935    #[should_panic(expected = "ConversionOverflowError")]
1936    fn mul_ceil_panics_on_overflow() {
1937        let fraction = (21u128, 8u128);
1938        _ = Uint256::MAX.mul_ceil(fraction);
1939    }
1940
1941    #[test]
1942    fn checked_mul_ceil_does_not_panic_on_overflow() {
1943        let fraction = (21u128, 8u128);
1944        assert_eq!(
1945            Uint256::MAX.checked_mul_ceil(fraction),
1946            Err(ConversionOverflow(ConversionOverflowError {
1947                source_type: "Uint512",
1948                target_type: "Uint256",
1949            })),
1950        );
1951    }
1952
1953    #[test]
1954    #[should_panic(expected = "DivideByZeroError")]
1955    fn mul_ceil_panics_on_zero_div() {
1956        let fraction = (21u128, 0u128);
1957        _ = Uint256::from(123456u32).mul_ceil(fraction);
1958    }
1959
1960    #[test]
1961    fn checked_mul_ceil_does_not_panic_on_zero_div() {
1962        let fraction = (21u128, 0u128);
1963        assert_eq!(
1964            Uint256::from(123456u32).checked_mul_ceil(fraction),
1965            Err(DivideByZero(DivideByZeroError)),
1966        );
1967    }
1968
1969    #[test]
1970    #[should_panic(expected = "DivideByZeroError")]
1971    fn div_floor_raises_with_zero() {
1972        let fraction = (Uint256::zero(), Uint256::from(21u32));
1973        _ = Uint256::from(123456u128).div_floor(fraction);
1974    }
1975
1976    #[test]
1977    fn div_floor_does_nothing_with_one() {
1978        let fraction = (Uint256::one(), Uint256::one());
1979        let res = Uint256::from(123456u128).div_floor(fraction);
1980        assert_eq!(Uint256::from(123456u128), res)
1981    }
1982
1983    #[test]
1984    fn div_floor_rounds_down_with_normal_case() {
1985        let fraction = (5u128, 21u128);
1986        let res = Uint256::from(123456u128).div_floor(fraction); // 518515.2
1987        assert_eq!(Uint256::from(518515u128), res)
1988    }
1989
1990    #[test]
1991    fn div_floor_does_not_round_on_even_divide() {
1992        let fraction = (5u128, 2u128);
1993        let res = Uint256::from(25u128).div_floor(fraction);
1994        assert_eq!(Uint256::from(10u128), res)
1995    }
1996
1997    #[test]
1998    fn div_floor_works_when_operation_temporarily_takes_above_max() {
1999        let fraction = (21u128, 8u128);
2000        let res = Uint256::MAX.div_floor(fraction); // 44_111_272_090_406_169_685_169_899_050_928_726_801_245_708_444_053_548_205_507_651_050_633_573_196_165.71428571
2001        assert_eq!(
2002            Uint256::from_str(
2003                "44111272090406169685169899050928726801245708444053548205507651050633573196165"
2004            )
2005            .unwrap(),
2006            res
2007        )
2008    }
2009
2010    #[test]
2011    fn div_floor_works_with_decimal() {
2012        let decimal = Decimal::from_ratio(21u128, 8u128);
2013        let res = Uint256::from(123456u128).div_floor(decimal); // 47030.8571
2014        assert_eq!(Uint256::from(47030u128), res)
2015    }
2016
2017    #[test]
2018    fn div_floor_works_with_decimal_evenly() {
2019        let res = Uint256::from(60u128).div_floor(Decimal::from_atomics(6u128, 0).unwrap());
2020        assert_eq!(res, Uint256::from(10u128));
2021    }
2022
2023    #[test]
2024    #[should_panic(expected = "ConversionOverflowError")]
2025    fn div_floor_panics_on_overflow() {
2026        let fraction = (8u128, 21u128);
2027        _ = Uint256::MAX.div_floor(fraction);
2028    }
2029
2030    #[test]
2031    fn div_floor_does_not_panic_on_overflow() {
2032        let fraction = (8u128, 21u128);
2033        assert_eq!(
2034            Uint256::MAX.checked_div_floor(fraction),
2035            Err(ConversionOverflow(ConversionOverflowError {
2036                source_type: "Uint512",
2037                target_type: "Uint256",
2038            })),
2039        );
2040    }
2041
2042    #[test]
2043    #[should_panic(expected = "DivideByZeroError")]
2044    fn div_ceil_raises_with_zero() {
2045        let fraction = (Uint256::zero(), Uint256::from(21u128));
2046        _ = Uint256::from(123456u128).div_ceil(fraction);
2047    }
2048
2049    #[test]
2050    fn div_ceil_does_nothing_with_one() {
2051        let fraction = (Uint256::one(), Uint256::one());
2052        let res = Uint256::from(123456u128).div_ceil(fraction);
2053        assert_eq!(Uint256::from(123456u128), res)
2054    }
2055
2056    #[test]
2057    fn div_ceil_rounds_up_with_normal_case() {
2058        let fraction = (5u128, 21u128);
2059        let res = Uint256::from(123456u128).div_ceil(fraction); // 518515.2
2060        assert_eq!(Uint256::from(518516u128), res)
2061    }
2062
2063    #[test]
2064    fn div_ceil_does_not_round_on_even_divide() {
2065        let fraction = (5u128, 2u128);
2066        let res = Uint256::from(25u128).div_ceil(fraction);
2067        assert_eq!(Uint256::from(10u128), res)
2068    }
2069
2070    #[test]
2071    fn div_ceil_works_when_operation_temporarily_takes_above_max() {
2072        let fraction = (21u128, 8u128);
2073        let res = Uint256::MAX.div_ceil(fraction); // 44_111_272_090_406_169_685_169_899_050_928_726_801_245_708_444_053_548_205_507_651_050_633_573_196_165.71428571
2074        assert_eq!(
2075            Uint256::from_str(
2076                "44111272090406169685169899050928726801245708444053548205507651050633573196166"
2077            )
2078            .unwrap(),
2079            res
2080        )
2081    }
2082
2083    #[test]
2084    fn div_ceil_works_with_decimal() {
2085        let decimal = Decimal::from_ratio(21u128, 8u128);
2086        let res = Uint256::from(123456u128).div_ceil(decimal); // 47030.8571
2087        assert_eq!(Uint256::from(47031u128), res)
2088    }
2089
2090    #[test]
2091    fn div_ceil_works_with_decimal_evenly() {
2092        let res = Uint256::from(60u128).div_ceil(Decimal::from_atomics(6u128, 0).unwrap());
2093        assert_eq!(res, Uint256::from(10u128));
2094    }
2095
2096    #[test]
2097    #[should_panic(expected = "ConversionOverflowError")]
2098    fn div_ceil_panics_on_overflow() {
2099        let fraction = (8u128, 21u128);
2100        _ = Uint256::MAX.div_ceil(fraction);
2101    }
2102
2103    #[test]
2104    fn div_ceil_does_not_panic_on_overflow() {
2105        let fraction = (8u128, 21u128);
2106        assert_eq!(
2107            Uint256::MAX.checked_div_ceil(fraction),
2108            Err(ConversionOverflow(ConversionOverflowError {
2109                source_type: "Uint512",
2110                target_type: "Uint256",
2111            })),
2112        );
2113    }
2114}