Skip to main content

cosmwasm_std/math/
uint256.rs

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