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