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