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