secret_cosmwasm_std/math/
uint256.rs

1use forward_ref::{forward_ref_binop, forward_ref_op_assign};
2use schemars::JsonSchema;
3use serde::{de, ser, Deserialize, Deserializer, Serialize};
4use std::fmt;
5use std::ops::{
6    Add, AddAssign, Div, DivAssign, Mul, MulAssign, Rem, RemAssign, Shl, Shr, ShrAssign, Sub,
7    SubAssign,
8};
9use std::str::FromStr;
10
11use crate::errors::{
12    CheckedMultiplyRatioError, ConversionOverflowError, DivideByZeroError, OverflowError,
13    OverflowOperation, StdError,
14};
15use crate::{Uint128, Uint512, Uint64};
16
17/// This module is purely a workaround that lets us ignore lints for all the code
18/// the `construct_uint!` macro generates.
19#[allow(clippy::all)]
20mod uints {
21    uint::construct_uint! {
22        pub struct U256(4);
23    }
24}
25
26/// Used internally - we don't want to leak this type since we might change
27/// the implementation in the future.
28use uints::U256;
29
30/// An implementation of u256 that is using strings for JSON encoding/decoding,
31/// such that the full u256 range can be used for clients that convert JSON numbers to floats,
32/// like JavaScript and jq.
33///
34/// # Examples
35///
36/// Use `from` to create instances out of primitive uint types or `new` to provide big
37/// endian bytes:
38///
39/// ```
40/// # use secret_cosmwasm_std::Uint256;
41/// let a = Uint256::from(258u128);
42/// let b = Uint256::new([
43///     0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8,
44///     0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8,
45///     0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8,
46///     0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 1u8, 2u8,
47/// ]);
48/// assert_eq!(a, b);
49/// ```
50#[derive(Copy, Clone, Default, Debug, PartialEq, Eq, PartialOrd, Ord, JsonSchema)]
51pub struct Uint256(#[schemars(with = "String")] U256);
52
53impl Uint256 {
54    pub const MAX: Uint256 = Uint256(U256::MAX);
55    pub const MIN: Uint256 = Uint256(U256::zero());
56
57    /// Creates a Uint256(value) from a big endian representation. It's just an alias for
58    /// [`Uint256::from_be_bytes`].
59    ///
60    /// This method is less flexible than `from` but can be called in a const context.
61    pub const fn new(value: [u8; 32]) -> Self {
62        Self::from_be_bytes(value)
63    }
64
65    /// Creates a Uint256(0)
66    #[inline]
67    pub const fn zero() -> Self {
68        Uint256(U256::zero())
69    }
70
71    /// Creates a Uint256(1)
72    #[inline]
73    pub const fn one() -> Self {
74        Self::from_be_bytes([
75            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
76            0, 0, 1,
77        ])
78    }
79
80    pub const fn from_be_bytes(data: [u8; 32]) -> Self {
81        let words: [u64; 4] = [
82            u64::from_le_bytes([
83                data[31], data[30], data[29], data[28], data[27], data[26], data[25], data[24],
84            ]),
85            u64::from_le_bytes([
86                data[23], data[22], data[21], data[20], data[19], data[18], data[17], data[16],
87            ]),
88            u64::from_le_bytes([
89                data[15], data[14], data[13], data[12], data[11], data[10], data[9], data[8],
90            ]),
91            u64::from_le_bytes([
92                data[7], data[6], data[5], data[4], data[3], data[2], data[1], data[0],
93            ]),
94        ];
95        Self(U256(words))
96    }
97
98    pub const fn from_le_bytes(data: [u8; 32]) -> Self {
99        let words: [u64; 4] = [
100            u64::from_le_bytes([
101                data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7],
102            ]),
103            u64::from_le_bytes([
104                data[8], data[9], data[10], data[11], data[12], data[13], data[14], data[15],
105            ]),
106            u64::from_le_bytes([
107                data[16], data[17], data[18], data[19], data[20], data[21], data[22], data[23],
108            ]),
109            u64::from_le_bytes([
110                data[24], data[25], data[26], data[27], data[28], data[29], data[30], data[31],
111            ]),
112        ];
113        Uint256(U256(words))
114    }
115
116    /// A conversion from `u128` that, unlike the one provided by the `From` trait,
117    /// can be used in a `const` context.
118    pub const fn from_u128(num: u128) -> Self {
119        let bytes = num.to_le_bytes();
120
121        Self::from_le_bytes([
122            bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],
123            bytes[8], bytes[9], bytes[10], bytes[11], bytes[12], bytes[13], bytes[14], bytes[15],
124            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
125        ])
126    }
127
128    /// A conversion from `Uint128` that, unlike the one provided by the `From` trait,
129    /// can be used in a `const` context.
130    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    pub const fn to_be_bytes(self) -> [u8; 32] {
136        let words = [
137            (self.0).0[3].to_be_bytes(),
138            (self.0).0[2].to_be_bytes(),
139            (self.0).0[1].to_be_bytes(),
140            (self.0).0[0].to_be_bytes(),
141        ];
142        unsafe { std::mem::transmute::<[[u8; 8]; 4], [u8; 32]>(words) }
143    }
144
145    /// Returns a copy of the number as little endian bytes.
146    pub const fn to_le_bytes(self) -> [u8; 32] {
147        let words = [
148            (self.0).0[0].to_le_bytes(),
149            (self.0).0[1].to_le_bytes(),
150            (self.0).0[2].to_le_bytes(),
151            (self.0).0[3].to_le_bytes(),
152        ];
153        unsafe { std::mem::transmute::<[[u8; 8]; 4], [u8; 32]>(words) }
154    }
155
156    pub const fn is_zero(&self) -> bool {
157        let words = (self.0).0;
158        words[0] == 0 && words[1] == 0 && words[2] == 0 && words[3] == 0
159    }
160
161    pub fn pow(self, exp: u32) -> Self {
162        let res = self.0.pow(exp.into());
163        Self(res)
164    }
165
166    /// Returns `self * numerator / denominator`.
167    ///
168    /// Due to the nature of the integer division involved, the result is always floored.
169    /// E.g. 5 * 99/100 = 4.
170    pub fn multiply_ratio<A: Into<Uint256>, B: Into<Uint256>>(
171        &self,
172        numerator: A,
173        denominator: B,
174    ) -> Uint256 {
175        match self.checked_multiply_ratio(numerator, denominator) {
176            Ok(value) => value,
177            Err(CheckedMultiplyRatioError::DivideByZero) => {
178                panic!("Denominator must not be zero")
179            }
180            Err(CheckedMultiplyRatioError::Overflow) => panic!("Multiplication overflow"),
181        }
182    }
183
184    /// Returns `self * numerator / denominator`.
185    ///
186    /// Due to the nature of the integer division involved, the result is always floored.
187    /// E.g. 5 * 99/100 = 4.
188    pub fn checked_multiply_ratio<A: Into<Uint256>, B: Into<Uint256>>(
189        &self,
190        numerator: A,
191        denominator: B,
192    ) -> Result<Uint256, CheckedMultiplyRatioError> {
193        let numerator: Uint256 = numerator.into();
194        let denominator: Uint256 = denominator.into();
195        if denominator.is_zero() {
196            return Err(CheckedMultiplyRatioError::DivideByZero);
197        }
198        match (self.full_mul(numerator) / Uint512::from(denominator)).try_into() {
199            Ok(ratio) => Ok(ratio),
200            Err(_) => Err(CheckedMultiplyRatioError::Overflow),
201        }
202    }
203
204    /// Multiplies two u256 values without overflow, producing an
205    /// [`Uint512`].
206    ///
207    /// # Examples
208    ///
209    /// ```
210    /// use secret_cosmwasm_std::Uint256;
211    ///
212    /// let a = Uint256::MAX;
213    /// let result = a.full_mul(2u32);
214    /// assert_eq!(
215    ///     result.to_string(),
216    ///     "231584178474632390847141970017375815706539969331281128078915168015826259279870",
217    /// );
218    /// ```
219    pub fn full_mul(self, rhs: impl Into<Uint256>) -> Uint512 {
220        Uint512::from(self)
221            .checked_mul(Uint512::from(rhs.into()))
222            .unwrap()
223    }
224
225    pub fn checked_add(self, other: Self) -> Result<Self, OverflowError> {
226        self.0
227            .checked_add(other.0)
228            .map(Self)
229            .ok_or_else(|| OverflowError::new(OverflowOperation::Add, self, other))
230    }
231
232    pub fn checked_sub(self, other: Self) -> Result<Self, OverflowError> {
233        self.0
234            .checked_sub(other.0)
235            .map(Self)
236            .ok_or_else(|| OverflowError::new(OverflowOperation::Sub, self, other))
237    }
238
239    pub fn checked_mul(self, other: Self) -> Result<Self, OverflowError> {
240        self.0
241            .checked_mul(other.0)
242            .map(Self)
243            .ok_or_else(|| OverflowError::new(OverflowOperation::Mul, self, other))
244    }
245
246    pub fn checked_pow(self, exp: u32) -> Result<Self, OverflowError> {
247        self.0
248            .checked_pow(exp.into())
249            .map(Self)
250            .ok_or_else(|| OverflowError::new(OverflowOperation::Pow, self, exp))
251    }
252
253    pub fn checked_div(self, other: Self) -> Result<Self, DivideByZeroError> {
254        self.0
255            .checked_div(other.0)
256            .map(Self)
257            .ok_or_else(|| DivideByZeroError::new(self))
258    }
259
260    pub fn checked_div_euclid(self, other: Self) -> Result<Self, DivideByZeroError> {
261        self.checked_div(other)
262    }
263
264    pub fn checked_rem(self, other: Self) -> Result<Self, DivideByZeroError> {
265        self.0
266            .checked_rem(other.0)
267            .map(Self)
268            .ok_or_else(|| DivideByZeroError::new(self))
269    }
270
271    pub fn checked_shr(self, other: u32) -> Result<Self, OverflowError> {
272        if other >= 256 {
273            return Err(OverflowError::new(OverflowOperation::Shr, self, other));
274        }
275
276        Ok(Self(self.0.shr(other)))
277    }
278
279    pub fn checked_shl(self, other: u32) -> Result<Self, OverflowError> {
280        if other >= 256 {
281            return Err(OverflowError::new(OverflowOperation::Shl, self, other));
282        }
283
284        Ok(Self(self.0.shl(other)))
285    }
286
287    #[inline]
288    pub fn wrapping_add(self, other: Self) -> Self {
289        let (value, _did_overflow) = self.0.overflowing_add(other.0);
290        Self(value)
291    }
292
293    #[inline]
294    pub fn wrapping_sub(self, other: Self) -> Self {
295        let (value, _did_overflow) = self.0.overflowing_sub(other.0);
296        Self(value)
297    }
298
299    #[inline]
300    pub fn wrapping_mul(self, other: Self) -> Self {
301        let (value, _did_overflow) = self.0.overflowing_mul(other.0);
302        Self(value)
303    }
304
305    #[inline]
306    pub fn wrapping_pow(self, other: u32) -> Self {
307        let (value, _did_overflow) = self.0.overflowing_pow(other.into());
308        Self(value)
309    }
310
311    pub fn saturating_add(self, other: Self) -> Self {
312        Self(self.0.saturating_add(other.0))
313    }
314
315    pub fn saturating_sub(self, other: Self) -> Self {
316        Self(self.0.saturating_sub(other.0))
317    }
318
319    pub fn saturating_mul(self, other: Self) -> Self {
320        Self(self.0.saturating_mul(other.0))
321    }
322
323    pub fn saturating_pow(self, exp: u32) -> Self {
324        match self.checked_pow(exp) {
325            Ok(value) => value,
326            Err(_) => Self::MAX,
327        }
328    }
329
330    pub fn abs_diff(self, other: Self) -> Self {
331        if self < other {
332            other - self
333        } else {
334            self - other
335        }
336    }
337}
338
339impl From<Uint128> for Uint256 {
340    fn from(val: Uint128) -> Self {
341        val.u128().into()
342    }
343}
344
345impl From<Uint64> for Uint256 {
346    fn from(val: Uint64) -> Self {
347        val.u64().into()
348    }
349}
350
351impl From<u128> for Uint256 {
352    fn from(val: u128) -> Self {
353        Uint256(val.into())
354    }
355}
356
357impl From<u64> for Uint256 {
358    fn from(val: u64) -> Self {
359        Uint256(val.into())
360    }
361}
362
363impl From<u32> for Uint256 {
364    fn from(val: u32) -> Self {
365        Uint256(val.into())
366    }
367}
368
369impl From<u16> for Uint256 {
370    fn from(val: u16) -> Self {
371        Uint256(val.into())
372    }
373}
374
375impl From<u8> for Uint256 {
376    fn from(val: u8) -> Self {
377        Uint256(val.into())
378    }
379}
380
381impl TryFrom<Uint256> for Uint128 {
382    type Error = ConversionOverflowError;
383
384    fn try_from(value: Uint256) -> Result<Self, Self::Error> {
385        Ok(Uint128::new(value.0.try_into().map_err(|_| {
386            ConversionOverflowError::new("Uint256", "Uint128", value.to_string())
387        })?))
388    }
389}
390
391impl TryFrom<&str> for Uint256 {
392    type Error = StdError;
393
394    fn try_from(val: &str) -> Result<Self, Self::Error> {
395        Self::from_str(val)
396    }
397}
398
399impl FromStr for Uint256 {
400    type Err = StdError;
401
402    fn from_str(s: &str) -> Result<Self, Self::Err> {
403        if s.is_empty() {
404            return Err(StdError::generic_err("Parsing u256: received empty string"));
405        }
406
407        match U256::from_dec_str(s) {
408            Ok(u) => Ok(Uint256(u)),
409            Err(e) => Err(StdError::generic_err(format!("Parsing u256: {}", e))),
410        }
411    }
412}
413
414impl From<Uint256> for String {
415    fn from(original: Uint256) -> Self {
416        original.to_string()
417    }
418}
419
420impl fmt::Display for Uint256 {
421    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
422        // The inner type doesn't work as expected with padding, so we
423        // work around that.
424        let unpadded = self.0.to_string();
425
426        f.pad_integral(true, "", &unpadded)
427    }
428}
429
430impl Add<Uint256> for Uint256 {
431    type Output = Self;
432
433    fn add(self, rhs: Self) -> Self {
434        Self(
435            self.0
436                .checked_add(rhs.0)
437                .expect("attempt to add with overflow"),
438        )
439    }
440}
441
442impl<'a> Add<&'a Uint256> for Uint256 {
443    type Output = Self;
444
445    fn add(self, rhs: &'a Uint256) -> Self {
446        self + *rhs
447    }
448}
449
450impl Sub<Uint256> for Uint256 {
451    type Output = Self;
452
453    fn sub(self, rhs: Self) -> Self {
454        Self(
455            self.0
456                .checked_sub(rhs.0)
457                .expect("attempt to subtract with overflow"),
458        )
459    }
460}
461forward_ref_binop!(impl Sub, sub for Uint256, Uint256);
462
463impl SubAssign<Uint256> for Uint256 {
464    fn sub_assign(&mut self, rhs: Uint256) {
465        *self = *self - rhs;
466    }
467}
468forward_ref_op_assign!(impl SubAssign, sub_assign for Uint256, Uint256);
469
470impl Div<Uint256> for Uint256 {
471    type Output = Self;
472
473    fn div(self, rhs: Self) -> Self::Output {
474        Self(
475            self.0
476                .checked_div(rhs.0)
477                .expect("attempt to divide by zero"),
478        )
479    }
480}
481
482impl<'a> Div<&'a Uint256> for Uint256 {
483    type Output = Self;
484
485    fn div(self, rhs: &'a Uint256) -> Self::Output {
486        self / *rhs
487    }
488}
489
490impl Rem for Uint256 {
491    type Output = Self;
492
493    /// # Panics
494    ///
495    /// This operation will panic if `rhs` is zero.
496    #[inline]
497    fn rem(self, rhs: Self) -> Self {
498        Self(self.0.rem(rhs.0))
499    }
500}
501forward_ref_binop!(impl Rem, rem for Uint256, Uint256);
502
503impl RemAssign<Uint256> for Uint256 {
504    fn rem_assign(&mut self, rhs: Uint256) {
505        *self = *self % rhs;
506    }
507}
508forward_ref_op_assign!(impl RemAssign, rem_assign for Uint256, Uint256);
509
510impl Mul<Uint256> for Uint256 {
511    type Output = Self;
512
513    fn mul(self, rhs: Self) -> Self::Output {
514        Self(
515            self.0
516                .checked_mul(rhs.0)
517                .expect("attempt to multiply with overflow"),
518        )
519    }
520}
521forward_ref_binop!(impl Mul, mul for Uint256, Uint256);
522
523impl MulAssign<Uint256> for Uint256 {
524    fn mul_assign(&mut self, rhs: Self) {
525        *self = *self * rhs;
526    }
527}
528forward_ref_op_assign!(impl MulAssign, mul_assign for Uint256, Uint256);
529
530impl Shr<u32> for Uint256 {
531    type Output = Self;
532
533    fn shr(self, rhs: u32) -> Self::Output {
534        self.checked_shr(rhs).unwrap_or_else(|_| {
535            panic!(
536                "right shift error: {} is larger or equal than the number of bits in Uint256",
537                rhs,
538            )
539        })
540    }
541}
542
543impl<'a> Shr<&'a u32> for Uint256 {
544    type Output = Self;
545
546    fn shr(self, rhs: &'a u32) -> Self::Output {
547        self.shr(*rhs)
548    }
549}
550
551impl Shl<u32> for Uint256 {
552    type Output = Self;
553
554    fn shl(self, rhs: u32) -> Self::Output {
555        self.checked_shl(rhs).unwrap_or_else(|_| {
556            panic!(
557                "left shift error: {} is larger or equal than the number of bits in Uint256",
558                rhs,
559            )
560        })
561    }
562}
563
564impl<'a> Shl<&'a u32> for Uint256 {
565    type Output = Self;
566
567    fn shl(self, rhs: &'a u32) -> Self::Output {
568        self.shl(*rhs)
569    }
570}
571
572impl AddAssign<Uint256> for Uint256 {
573    fn add_assign(&mut self, rhs: Uint256) {
574        *self = *self + rhs;
575    }
576}
577
578impl<'a> AddAssign<&'a Uint256> for Uint256 {
579    fn add_assign(&mut self, rhs: &'a Uint256) {
580        *self = *self + rhs;
581    }
582}
583
584impl DivAssign<Uint256> for Uint256 {
585    fn div_assign(&mut self, rhs: Self) {
586        *self = *self / rhs;
587    }
588}
589
590impl<'a> DivAssign<&'a Uint256> for Uint256 {
591    fn div_assign(&mut self, rhs: &'a Uint256) {
592        *self = *self / rhs;
593    }
594}
595
596impl ShrAssign<u32> for Uint256 {
597    fn shr_assign(&mut self, rhs: u32) {
598        *self = Shr::<u32>::shr(*self, rhs);
599    }
600}
601
602impl<'a> ShrAssign<&'a u32> for Uint256 {
603    fn shr_assign(&mut self, rhs: &'a u32) {
604        *self = Shr::<u32>::shr(*self, *rhs);
605    }
606}
607
608impl Serialize for Uint256 {
609    /// Serializes as an integer string using base 10
610    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
611    where
612        S: ser::Serializer,
613    {
614        serializer.serialize_str(&self.to_string())
615    }
616}
617
618impl<'de> Deserialize<'de> for Uint256 {
619    /// Deserialized from an integer string using base 10
620    fn deserialize<D>(deserializer: D) -> Result<Uint256, D::Error>
621    where
622        D: Deserializer<'de>,
623    {
624        deserializer.deserialize_str(Uint256Visitor)
625    }
626}
627
628struct Uint256Visitor;
629
630impl<'de> de::Visitor<'de> for Uint256Visitor {
631    type Value = Uint256;
632
633    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
634        formatter.write_str("string-encoded integer")
635    }
636
637    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
638    where
639        E: de::Error,
640    {
641        Uint256::try_from(v).map_err(|e| E::custom(format!("invalid Uint256 '{}' - {}", v, e)))
642    }
643}
644
645impl<A> std::iter::Sum<A> for Uint256
646where
647    Self: Add<A, Output = Self>,
648{
649    fn sum<I: Iterator<Item = A>>(iter: I) -> Self {
650        iter.fold(Self::zero(), Add::add)
651    }
652}
653
654impl PartialEq<&Uint256> for Uint256 {
655    fn eq(&self, rhs: &&Uint256) -> bool {
656        self == *rhs
657    }
658}
659
660impl PartialEq<Uint256> for &Uint256 {
661    fn eq(&self, rhs: &Uint256) -> bool {
662        *self == rhs
663    }
664}
665
666#[cfg(test)]
667mod tests {
668    use super::*;
669    use crate::{from_slice, to_vec};
670
671    #[test]
672    fn uint256_new_works() {
673        let num = Uint256::new([1; 32]);
674        let a: [u8; 32] = num.to_be_bytes();
675        assert_eq!(a, [1; 32]);
676
677        let be_bytes = [
678            0u8, 222u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8,
679            0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 1u8, 2u8, 3u8,
680        ];
681        let num = Uint256::new(be_bytes);
682        let resulting_bytes: [u8; 32] = num.to_be_bytes();
683        assert_eq!(be_bytes, resulting_bytes);
684    }
685
686    #[test]
687    fn uint256_zero_works() {
688        let zero = Uint256::zero();
689        assert_eq!(
690            zero.to_be_bytes(),
691            [
692                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
693                0, 0, 0, 0
694            ]
695        );
696    }
697
698    #[test]
699    fn uin256_one_works() {
700        let one = Uint256::one();
701        assert_eq!(
702            one.to_be_bytes(),
703            [
704                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
705                0, 0, 0, 1,
706            ]
707        );
708    }
709
710    #[test]
711    fn uint256_from_be_bytes() {
712        let a = Uint256::from_be_bytes([
713            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
714            0, 0, 0,
715        ]);
716        assert_eq!(a, Uint256::from(0u128));
717        let a = Uint256::from_be_bytes([
718            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
719            0, 0, 42,
720        ]);
721        assert_eq!(a, Uint256::from(42u128));
722        let a = Uint256::from_be_bytes([
723            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
724            0, 0, 1,
725        ]);
726        assert_eq!(a, Uint256::from(1u128));
727        let a = Uint256::from_be_bytes([
728            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
729            0, 1, 0,
730        ]);
731        assert_eq!(a, Uint256::from(256u128));
732        let a = Uint256::from_be_bytes([
733            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
734            1, 0, 0,
735        ]);
736        assert_eq!(a, Uint256::from(65536u128));
737        let a = Uint256::from_be_bytes([
738            0, 0, 0, 0, 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,
739            0, 0, 0,
740        ]);
741        assert_eq!(a, Uint256::from(16777216u128));
742        let a = Uint256::from_be_bytes([
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, 1, 0,
744            0, 0, 0,
745        ]);
746        assert_eq!(a, Uint256::from(4294967296u128));
747        let a = Uint256::from_be_bytes([
748            0, 0, 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,
749            0, 0, 0,
750        ]);
751        assert_eq!(a, Uint256::from(1099511627776u128));
752        let a = Uint256::from_be_bytes([
753            0, 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,
754            0, 0, 0,
755        ]);
756        assert_eq!(a, Uint256::from(281474976710656u128));
757        let a = Uint256::from_be_bytes([
758            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,
759            0, 0, 0,
760        ]);
761        assert_eq!(a, Uint256::from(72057594037927936u128));
762        let a = Uint256::from_be_bytes([
763            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,
764            0, 0, 0,
765        ]);
766        assert_eq!(a, Uint256::from(18446744073709551616u128));
767        let a = Uint256::from_be_bytes([
768            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,
769            0, 0, 0,
770        ]);
771        assert_eq!(a, Uint256::from(4722366482869645213696u128));
772        let a = Uint256::from_be_bytes([
773            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,
774            0, 0, 0,
775        ]);
776        assert_eq!(a, Uint256::from(1208925819614629174706176u128));
777        let a = Uint256::from_be_bytes([
778            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,
779            0, 0, 0,
780        ]);
781        assert_eq!(a, Uint256::from(1329227995784915872903807060280344576u128));
782
783        // Values > u128::MAX
784        let a = Uint256::from_be_bytes([
785            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,
786            0, 0, 0,
787        ]);
788        assert_eq!(a, Uint256::from(1u128) << (8 * 16));
789        let a = Uint256::from_be_bytes([
790            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,
791            0, 0, 0,
792        ]);
793        assert_eq!(a, Uint256::from(1u128) << (8 * 17));
794        let a = Uint256::from_be_bytes([
795            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,
796            0, 0, 0,
797        ]);
798        assert_eq!(a, Uint256::from(1u128) << (8 * 18));
799        let a = Uint256::from_be_bytes([
800            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,
801            0, 0, 0,
802        ]);
803        assert_eq!(a, Uint256::from(1u128) << (8 * 19));
804        let a = Uint256::from_be_bytes([
805            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,
806            0, 0, 0,
807        ]);
808        assert_eq!(a, Uint256::from(1u128) << (8 * 20));
809        let a = Uint256::from_be_bytes([
810            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,
811            0, 0, 0,
812        ]);
813        assert_eq!(a, Uint256::from(1u128) << (8 * 21));
814        let a = Uint256::from_be_bytes([
815            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,
816            0, 0, 0,
817        ]);
818        assert_eq!(a, Uint256::from(1u128) << (8 * 22));
819        let a = Uint256::from_be_bytes([
820            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,
821            0, 0, 0,
822        ]);
823        assert_eq!(a, Uint256::from(1u128) << (8 * 23));
824        let a = Uint256::from_be_bytes([
825            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,
826            0, 0, 0,
827        ]);
828        assert_eq!(a, Uint256::from(1u128) << (8 * 24));
829        let a = Uint256::from_be_bytes([
830            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,
831            0, 0, 0,
832        ]);
833        assert_eq!(a, Uint256::from(1u128) << (8 * 25));
834        let a = Uint256::from_be_bytes([
835            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,
836            0, 0, 0,
837        ]);
838        assert_eq!(a, Uint256::from(1u128) << (8 * 26));
839        let a = Uint256::from_be_bytes([
840            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,
841            0, 0, 0,
842        ]);
843        assert_eq!(a, Uint256::from(1u128) << (8 * 27));
844        let a = Uint256::from_be_bytes([
845            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,
846            0, 0, 0,
847        ]);
848        assert_eq!(a, Uint256::from(1u128) << (8 * 28));
849        let a = Uint256::from_be_bytes([
850            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,
851            0, 0, 0,
852        ]);
853        assert_eq!(a, Uint256::from(1u128) << (8 * 29));
854        let a = Uint256::from_be_bytes([
855            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,
856            0, 0, 0,
857        ]);
858        assert_eq!(a, Uint256::from(1u128) << (8 * 30));
859        let a = Uint256::from_be_bytes([
860            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,
861            0, 0, 0,
862        ]);
863        assert_eq!(a, Uint256::from(1u128) << (8 * 31));
864    }
865
866    #[test]
867    fn uint256_from_le_bytes() {
868        let a = Uint256::from_le_bytes([
869            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
870            0, 0, 0,
871        ]);
872        assert_eq!(a, Uint256::from(0u128));
873        let a = Uint256::from_le_bytes([
874            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,
875            0, 0, 0,
876        ]);
877        assert_eq!(a, Uint256::from(42u128));
878        let a = Uint256::from_le_bytes([
879            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,
880            0, 0, 0,
881        ]);
882        assert_eq!(a, Uint256::from(1u128));
883        let a = Uint256::from_le_bytes([
884            0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
885            0, 0, 0,
886        ]);
887        assert_eq!(a, Uint256::from(256u128));
888        let a = Uint256::from_le_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(65536u128));
893        let a = Uint256::from_le_bytes([
894            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,
895            0, 0, 0,
896        ]);
897        assert_eq!(a, Uint256::from(16777216u128));
898        let a = Uint256::from_le_bytes([
899            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,
900            0, 0, 0,
901        ]);
902        assert_eq!(a, Uint256::from(4294967296u128));
903        let a = Uint256::from_le_bytes([
904            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,
905            0, 0, 0,
906        ]);
907        assert_eq!(a, Uint256::from(72057594037927936u128));
908        let a = Uint256::from_le_bytes([
909            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,
910            0, 0, 0,
911        ]);
912        assert_eq!(a, Uint256::from(18446744073709551616u128));
913        let a = Uint256::from_le_bytes([
914            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,
915            0, 0, 0,
916        ]);
917        assert_eq!(a, Uint256::from(1329227995784915872903807060280344576u128));
918
919        // Values > u128::MAX
920        let a = Uint256::from_le_bytes([
921            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,
922            0, 0, 0,
923        ]);
924        assert_eq!(a, Uint256::from(1u128) << (8 * 16));
925        let a = Uint256::from_le_bytes([
926            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,
927            0, 0, 0,
928        ]);
929        assert_eq!(a, Uint256::from(1u128) << (8 * 17));
930        let a = Uint256::from_le_bytes([
931            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,
932            0, 0, 0,
933        ]);
934        assert_eq!(a, Uint256::from(1u128) << (8 * 18));
935        let a = Uint256::from_le_bytes([
936            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,
937            0, 0, 0,
938        ]);
939        assert_eq!(a, Uint256::from(1u128) << (8 * 19));
940        let a = Uint256::from_le_bytes([
941            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,
942            0, 0, 0,
943        ]);
944        assert_eq!(a, Uint256::from(1u128) << (8 * 20));
945        let a = Uint256::from_le_bytes([
946            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,
947            0, 0, 0,
948        ]);
949        assert_eq!(a, Uint256::from(1u128) << (8 * 21));
950        let a = Uint256::from_le_bytes([
951            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,
952            0, 0, 0,
953        ]);
954        assert_eq!(a, Uint256::from(1u128) << (8 * 22));
955        let a = Uint256::from_le_bytes([
956            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,
957            0, 0, 0,
958        ]);
959        assert_eq!(a, Uint256::from(1u128) << (8 * 23));
960        let a = Uint256::from_le_bytes([
961            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,
962            0, 0, 0,
963        ]);
964        assert_eq!(a, Uint256::from(1u128) << (8 * 24));
965        let a = Uint256::from_le_bytes([
966            0, 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,
967            0, 0, 0,
968        ]);
969        assert_eq!(a, Uint256::from(1u128) << (8 * 25));
970        let a = Uint256::from_le_bytes([
971            0, 0, 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,
972            0, 0, 0,
973        ]);
974        assert_eq!(a, Uint256::from(1u128) << (8 * 26));
975        let a = Uint256::from_le_bytes([
976            0, 0, 0, 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,
977            0, 0, 0,
978        ]);
979        assert_eq!(a, Uint256::from(1u128) << (8 * 27));
980        let a = Uint256::from_le_bytes([
981            0, 0, 0, 0, 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,
982            0, 0, 0,
983        ]);
984        assert_eq!(a, Uint256::from(1u128) << (8 * 28));
985        let a = Uint256::from_le_bytes([
986            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
987            1, 0, 0,
988        ]);
989        assert_eq!(a, Uint256::from(1u128) << (8 * 29));
990        let a = Uint256::from_le_bytes([
991            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
992            0, 1, 0,
993        ]);
994        assert_eq!(a, Uint256::from(1u128) << (8 * 30));
995        let a = Uint256::from_le_bytes([
996            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
997            0, 0, 1,
998        ]);
999        assert_eq!(a, Uint256::from(1u128) << (8 * 31));
1000    }
1001
1002    #[test]
1003    fn uint256_endianness() {
1004        let be_bytes = [
1005            0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8,
1006            0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 1u8, 2u8, 3u8,
1007        ];
1008        let le_bytes = [
1009            3u8, 2u8, 1u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8,
1010            0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8,
1011        ];
1012
1013        // These should all be the same.
1014        let num1 = Uint256::new(be_bytes);
1015        let num2 = Uint256::from_be_bytes(be_bytes);
1016        let num3 = Uint256::from_le_bytes(le_bytes);
1017        assert_eq!(num1, Uint256::from(65536u32 + 512 + 3));
1018        assert_eq!(num1, num2);
1019        assert_eq!(num1, num3);
1020    }
1021
1022    #[test]
1023    fn uint256_convert_from() {
1024        let a = Uint256::from(5u128);
1025        assert_eq!(a.0, U256::from(5));
1026
1027        let a = Uint256::from(5u64);
1028        assert_eq!(a.0, U256::from(5));
1029
1030        let a = Uint256::from(5u32);
1031        assert_eq!(a.0, U256::from(5));
1032
1033        let a = Uint256::from(5u16);
1034        assert_eq!(a.0, U256::from(5));
1035
1036        let a = Uint256::from(5u8);
1037        assert_eq!(a.0, U256::from(5));
1038
1039        let result = Uint256::try_from("34567");
1040        assert_eq!(result.unwrap().0, U256::from_dec_str("34567").unwrap());
1041
1042        let result = Uint256::try_from("1.23");
1043        assert!(result.is_err());
1044    }
1045
1046    #[test]
1047    fn uint256_convert_to_uint128() {
1048        let source = Uint256::from(42u128);
1049        let target = Uint128::try_from(source);
1050        assert_eq!(target, Ok(Uint128::new(42u128)));
1051
1052        let source = Uint256::MAX;
1053        let target = Uint128::try_from(source);
1054        assert_eq!(
1055            target,
1056            Err(ConversionOverflowError::new(
1057                "Uint256",
1058                "Uint128",
1059                Uint256::MAX.to_string()
1060            ))
1061        );
1062    }
1063
1064    #[test]
1065    fn uint256_from_u128() {
1066        assert_eq!(
1067            Uint256::from_u128(123u128),
1068            Uint256::from_str("123").unwrap()
1069        );
1070
1071        assert_eq!(
1072            Uint256::from_u128(9785746283745u128),
1073            Uint256::from_str("9785746283745").unwrap()
1074        );
1075    }
1076
1077    #[test]
1078    fn uint256_from_uint128() {
1079        assert_eq!(
1080            Uint256::from_uint128(Uint128::new(123)),
1081            Uint256::from_str("123").unwrap()
1082        );
1083
1084        assert_eq!(
1085            Uint256::from_uint128(Uint128::new(9785746283745)),
1086            Uint256::from_str("9785746283745").unwrap()
1087        );
1088    }
1089
1090    #[test]
1091    fn uint256_implements_display() {
1092        let a = Uint256::from(12345u32);
1093        assert_eq!(format!("Embedded: {}", a), "Embedded: 12345");
1094        assert_eq!(a.to_string(), "12345");
1095
1096        let a = Uint256::zero();
1097        assert_eq!(format!("Embedded: {}", a), "Embedded: 0");
1098        assert_eq!(a.to_string(), "0");
1099    }
1100
1101    #[test]
1102    fn uint256_display_padding_works() {
1103        let a = Uint256::from(123u64);
1104        assert_eq!(format!("Embedded: {:05}", a), "Embedded: 00123");
1105    }
1106
1107    #[test]
1108    fn uint256_to_be_bytes_works() {
1109        assert_eq!(
1110            Uint256::zero().to_be_bytes(),
1111            [
1112                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1113                0, 0, 0, 0,
1114            ]
1115        );
1116        assert_eq!(
1117            Uint256::MAX.to_be_bytes(),
1118            [
1119                0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
1120                0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
1121                0xff, 0xff, 0xff, 0xff,
1122            ]
1123        );
1124        assert_eq!(
1125            Uint256::from(1u128).to_be_bytes(),
1126            [
1127                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1128                0, 0, 0, 1
1129            ]
1130        );
1131        // Python: `[b for b in (240282366920938463463374607431768124608).to_bytes(32, "big")]`
1132        assert_eq!(
1133            Uint256::from(240282366920938463463374607431768124608u128).to_be_bytes(),
1134            [
1135                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 180, 196, 179, 87, 165, 121, 59,
1136                133, 246, 117, 221, 191, 255, 254, 172, 192
1137            ]
1138        );
1139        assert_eq!(
1140            Uint256::from_be_bytes([
1141                233, 2, 240, 200, 115, 150, 240, 218, 88, 106, 45, 208, 134, 238, 119, 85, 22, 14,
1142                88, 166, 195, 154, 73, 64, 10, 44, 252, 96, 230, 187, 38, 29
1143            ])
1144            .to_be_bytes(),
1145            [
1146                233, 2, 240, 200, 115, 150, 240, 218, 88, 106, 45, 208, 134, 238, 119, 85, 22, 14,
1147                88, 166, 195, 154, 73, 64, 10, 44, 252, 96, 230, 187, 38, 29
1148            ]
1149        );
1150    }
1151
1152    #[test]
1153    fn uint256_to_le_bytes_works() {
1154        assert_eq!(
1155            Uint256::zero().to_le_bytes(),
1156            [
1157                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1158                0, 0, 0, 0
1159            ]
1160        );
1161        assert_eq!(
1162            Uint256::MAX.to_le_bytes(),
1163            [
1164                0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
1165                0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
1166                0xff, 0xff, 0xff, 0xff
1167            ]
1168        );
1169        assert_eq!(
1170            Uint256::from(1u128).to_le_bytes(),
1171            [
1172                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,
1173                0, 0, 0, 0
1174            ]
1175        );
1176        // Python: `[b for b in (240282366920938463463374607431768124608).to_bytes(32, "little")]`
1177        assert_eq!(
1178            Uint256::from(240282366920938463463374607431768124608u128).to_le_bytes(),
1179            [
1180                192, 172, 254, 255, 191, 221, 117, 246, 133, 59, 121, 165, 87, 179, 196, 180, 0, 0,
1181                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
1182            ]
1183        );
1184        assert_eq!(
1185            Uint256::from_be_bytes([
1186                233, 2, 240, 200, 115, 150, 240, 218, 88, 106, 45, 208, 134, 238, 119, 85, 22, 14,
1187                88, 166, 195, 154, 73, 64, 10, 44, 252, 96, 230, 187, 38, 29
1188            ])
1189            .to_le_bytes(),
1190            [
1191                29, 38, 187, 230, 96, 252, 44, 10, 64, 73, 154, 195, 166, 88, 14, 22, 85, 119, 238,
1192                134, 208, 45, 106, 88, 218, 240, 150, 115, 200, 240, 2, 233
1193            ]
1194        );
1195    }
1196
1197    #[test]
1198    fn uint256_is_zero_works() {
1199        assert!(Uint256::zero().is_zero());
1200        assert!(Uint256(U256::from(0)).is_zero());
1201
1202        assert!(!Uint256::from(1u32).is_zero());
1203        assert!(!Uint256::from(123u32).is_zero());
1204    }
1205
1206    #[test]
1207    fn uint256_wrapping_methods() {
1208        // wrapping_add
1209        assert_eq!(
1210            Uint256::from(2u32).wrapping_add(Uint256::from(2u32)),
1211            Uint256::from(4u32)
1212        ); // non-wrapping
1213        assert_eq!(
1214            Uint256::MAX.wrapping_add(Uint256::from(1u32)),
1215            Uint256::from(0u32)
1216        ); // wrapping
1217
1218        // wrapping_sub
1219        assert_eq!(
1220            Uint256::from(7u32).wrapping_sub(Uint256::from(5u32)),
1221            Uint256::from(2u32)
1222        ); // non-wrapping
1223        assert_eq!(
1224            Uint256::from(0u32).wrapping_sub(Uint256::from(1u32)),
1225            Uint256::MAX
1226        ); // wrapping
1227
1228        // wrapping_mul
1229        assert_eq!(
1230            Uint256::from(3u32).wrapping_mul(Uint256::from(2u32)),
1231            Uint256::from(6u32)
1232        ); // non-wrapping
1233        assert_eq!(
1234            Uint256::MAX.wrapping_mul(Uint256::from(2u32)),
1235            Uint256::MAX - Uint256::one()
1236        ); // wrapping
1237
1238        // wrapping_pow
1239        assert_eq!(Uint256::from(2u32).wrapping_pow(3), Uint256::from(8u32)); // non-wrapping
1240        assert_eq!(Uint256::MAX.wrapping_pow(2), Uint256::from(1u32)); // wrapping
1241    }
1242
1243    #[test]
1244    fn uint256_json() {
1245        let orig = Uint256::from(1234567890987654321u128);
1246        let serialized = to_vec(&orig).unwrap();
1247        assert_eq!(serialized.as_slice(), b"\"1234567890987654321\"");
1248        let parsed: Uint256 = from_slice(&serialized).unwrap();
1249        assert_eq!(parsed, orig);
1250    }
1251
1252    #[test]
1253    fn uint256_compare() {
1254        let a = Uint256::from(12345u32);
1255        let b = Uint256::from(23456u32);
1256
1257        assert!(a < b);
1258        assert!(b > a);
1259        assert_eq!(a, Uint256::from(12345u32));
1260    }
1261
1262    #[test]
1263    #[allow(clippy::op_ref)]
1264    fn uint256_math() {
1265        let a = Uint256::from(12345u32);
1266        let b = Uint256::from(23456u32);
1267
1268        // test + with owned and reference right hand side
1269        assert_eq!(a + b, Uint256::from(35801u32));
1270        assert_eq!(a + &b, Uint256::from(35801u32));
1271
1272        // test - with owned and reference right hand side
1273        assert_eq!(b - a, Uint256::from(11111u32));
1274        assert_eq!(b - &a, Uint256::from(11111u32));
1275
1276        // test += with owned and reference right hand side
1277        let mut c = Uint256::from(300000u32);
1278        c += b;
1279        assert_eq!(c, Uint256::from(323456u32));
1280        let mut d = Uint256::from(300000u32);
1281        d += &b;
1282        assert_eq!(d, Uint256::from(323456u32));
1283
1284        // test -= with owned and reference right hand side
1285        let mut c = Uint256::from(300000u32);
1286        c -= b;
1287        assert_eq!(c, Uint256::from(276544u32));
1288        let mut d = Uint256::from(300000u32);
1289        d -= &b;
1290        assert_eq!(d, Uint256::from(276544u32));
1291
1292        // error result on underflow (- would produce negative result)
1293        let underflow_result = a.checked_sub(b);
1294        let OverflowError {
1295            operand1, operand2, ..
1296        } = underflow_result.unwrap_err();
1297        assert_eq!((operand1, operand2), (a.to_string(), b.to_string()));
1298    }
1299
1300    #[test]
1301    #[should_panic]
1302    fn uint256_add_overflow_panics() {
1303        let max = Uint256::new([255u8; 32]);
1304        let _ = max + Uint256::from(12u32);
1305    }
1306
1307    #[test]
1308    #[allow(clippy::op_ref)]
1309    fn uint256_sub_works() {
1310        assert_eq!(
1311            Uint256::from(2u32) - Uint256::from(1u32),
1312            Uint256::from(1u32)
1313        );
1314        assert_eq!(
1315            Uint256::from(2u32) - Uint256::from(0u32),
1316            Uint256::from(2u32)
1317        );
1318        assert_eq!(
1319            Uint256::from(2u32) - Uint256::from(2u32),
1320            Uint256::from(0u32)
1321        );
1322
1323        // works for refs
1324        let a = Uint256::from(10u32);
1325        let b = Uint256::from(3u32);
1326        let expected = Uint256::from(7u32);
1327        assert_eq!(a - b, expected);
1328        assert_eq!(a - &b, expected);
1329        assert_eq!(&a - b, expected);
1330        assert_eq!(&a - &b, expected);
1331    }
1332
1333    #[test]
1334    #[should_panic]
1335    fn uint256_sub_overflow_panics() {
1336        let _ = Uint256::from(1u32) - Uint256::from(2u32);
1337    }
1338
1339    #[test]
1340    fn uint256_sub_assign_works() {
1341        let mut a = Uint256::from(14u32);
1342        a -= Uint256::from(2u32);
1343        assert_eq!(a, Uint256::from(12u32));
1344
1345        // works for refs
1346        let mut a = Uint256::from(10u32);
1347        let b = Uint256::from(3u32);
1348        let expected = Uint256::from(7u32);
1349        a -= &b;
1350        assert_eq!(a, expected);
1351    }
1352
1353    #[test]
1354    #[allow(clippy::op_ref)]
1355    fn uint256_mul_works() {
1356        assert_eq!(
1357            Uint256::from(2u32) * Uint256::from(3u32),
1358            Uint256::from(6u32)
1359        );
1360        assert_eq!(Uint256::from(2u32) * Uint256::zero(), Uint256::zero());
1361
1362        // works for refs
1363        let a = Uint256::from(11u32);
1364        let b = Uint256::from(3u32);
1365        let expected = Uint256::from(33u32);
1366        assert_eq!(a * b, expected);
1367        assert_eq!(a * &b, expected);
1368        assert_eq!(&a * b, expected);
1369        assert_eq!(&a * &b, expected);
1370    }
1371
1372    #[test]
1373    fn uint256_mul_assign_works() {
1374        let mut a = Uint256::from(14u32);
1375        a *= Uint256::from(2u32);
1376        assert_eq!(a, Uint256::from(28u32));
1377
1378        // works for refs
1379        let mut a = Uint256::from(10u32);
1380        let b = Uint256::from(3u32);
1381        a *= &b;
1382        assert_eq!(a, Uint256::from(30u32));
1383    }
1384
1385    #[test]
1386    fn uint256_pow_works() {
1387        assert_eq!(Uint256::from(2u32).pow(2), Uint256::from(4u32));
1388        assert_eq!(Uint256::from(2u32).pow(10), Uint256::from(1024u32));
1389    }
1390
1391    #[test]
1392    #[should_panic]
1393    fn uint256_pow_overflow_panics() {
1394        Uint256::MAX.pow(2u32);
1395    }
1396
1397    #[test]
1398    fn uint256_multiply_ratio_works() {
1399        let base = Uint256::from(500u32);
1400
1401        // factor 1/1
1402        assert_eq!(base.multiply_ratio(1u128, 1u128), base);
1403        assert_eq!(base.multiply_ratio(3u128, 3u128), base);
1404        assert_eq!(base.multiply_ratio(654321u128, 654321u128), base);
1405        assert_eq!(base.multiply_ratio(Uint256::MAX, Uint256::MAX), base);
1406
1407        // factor 3/2
1408        assert_eq!(base.multiply_ratio(3u128, 2u128), Uint256::from(750u32));
1409        assert_eq!(
1410            base.multiply_ratio(333333u128, 222222u128),
1411            Uint256::from(750u32)
1412        );
1413
1414        // factor 2/3 (integer devision always floors the result)
1415        assert_eq!(base.multiply_ratio(2u128, 3u128), Uint256::from(333u32));
1416        assert_eq!(
1417            base.multiply_ratio(222222u128, 333333u128),
1418            Uint256::from(333u32)
1419        );
1420
1421        // factor 5/6 (integer devision always floors the result)
1422        assert_eq!(base.multiply_ratio(5u128, 6u128), Uint256::from(416u32));
1423        assert_eq!(base.multiply_ratio(100u128, 120u128), Uint256::from(416u32));
1424    }
1425
1426    #[test]
1427    fn uint256_multiply_ratio_does_not_overflow_when_result_fits() {
1428        // Almost max value for Uint256.
1429        let base = Uint256::MAX - Uint256::from(9u8);
1430
1431        assert_eq!(base.multiply_ratio(2u128, 2u128), base);
1432    }
1433
1434    #[test]
1435    #[should_panic]
1436    fn uint256_multiply_ratio_panicks_on_overflow() {
1437        // Almost max value for Uint256.
1438        let base = Uint256::MAX - Uint256::from(9u8);
1439
1440        assert_eq!(base.multiply_ratio(2u128, 1u128), base);
1441    }
1442
1443    #[test]
1444    #[should_panic(expected = "Denominator must not be zero")]
1445    fn uint256_multiply_ratio_panics_for_zero_denominator() {
1446        Uint256::from(500u32).multiply_ratio(1u128, 0u128);
1447    }
1448
1449    #[test]
1450    fn uint256_checked_multiply_ratio_does_not_panic() {
1451        assert_eq!(
1452            Uint256::from(500u32).checked_multiply_ratio(1u128, 0u128),
1453            Err(CheckedMultiplyRatioError::DivideByZero),
1454        );
1455        assert_eq!(
1456            Uint256::from(500u32).checked_multiply_ratio(Uint256::MAX, 1u128),
1457            Err(CheckedMultiplyRatioError::Overflow),
1458        );
1459    }
1460
1461    #[test]
1462    fn uint256_shr_works() {
1463        let original = Uint256::new([
1464            0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8,
1465            0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 2u8, 0u8, 4u8, 2u8,
1466        ]);
1467
1468        let shifted = Uint256::new([
1469            0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8,
1470            0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 128u8, 1u8, 0u8,
1471        ]);
1472
1473        assert_eq!(original >> 2u32, shifted);
1474    }
1475
1476    #[test]
1477    #[should_panic]
1478    fn uint256_shr_overflow_panics() {
1479        let _ = Uint256::from(1u32) >> 256u32;
1480    }
1481
1482    #[test]
1483    fn sum_works() {
1484        let nums = vec![
1485            Uint256::from(17u32),
1486            Uint256::from(123u32),
1487            Uint256::from(540u32),
1488            Uint256::from(82u32),
1489        ];
1490        let expected = Uint256::from(762u32);
1491
1492        let sum_as_ref: Uint256 = nums.iter().sum();
1493        assert_eq!(expected, sum_as_ref);
1494
1495        let sum_as_owned: Uint256 = nums.into_iter().sum();
1496        assert_eq!(expected, sum_as_owned);
1497    }
1498
1499    #[test]
1500    fn uint256_methods() {
1501        // checked_*
1502        assert!(matches!(
1503            Uint256::MAX.checked_add(Uint256::from(1u32)),
1504            Err(OverflowError { .. })
1505        ));
1506        assert_eq!(
1507            Uint256::from(1u32).checked_add(Uint256::from(1u32)),
1508            Ok(Uint256::from(2u32)),
1509        );
1510        assert!(matches!(
1511            Uint256::from(0u32).checked_sub(Uint256::from(1u32)),
1512            Err(OverflowError { .. })
1513        ));
1514        assert_eq!(
1515            Uint256::from(2u32).checked_sub(Uint256::from(1u32)),
1516            Ok(Uint256::from(1u32)),
1517        );
1518        assert!(matches!(
1519            Uint256::MAX.checked_mul(Uint256::from(2u32)),
1520            Err(OverflowError { .. })
1521        ));
1522        assert_eq!(
1523            Uint256::from(2u32).checked_mul(Uint256::from(2u32)),
1524            Ok(Uint256::from(4u32)),
1525        );
1526        assert!(matches!(
1527            Uint256::MAX.checked_pow(2u32),
1528            Err(OverflowError { .. })
1529        ));
1530        assert_eq!(
1531            Uint256::from(2u32).checked_pow(3u32),
1532            Ok(Uint256::from(8u32)),
1533        );
1534        assert!(matches!(
1535            Uint256::MAX.checked_div(Uint256::from(0u32)),
1536            Err(DivideByZeroError { .. })
1537        ));
1538        assert_eq!(
1539            Uint256::from(6u32).checked_div(Uint256::from(2u32)),
1540            Ok(Uint256::from(3u32)),
1541        );
1542        assert!(matches!(
1543            Uint256::MAX.checked_div_euclid(Uint256::from(0u32)),
1544            Err(DivideByZeroError { .. })
1545        ));
1546        assert_eq!(
1547            Uint256::from(6u32).checked_div_euclid(Uint256::from(2u32)),
1548            Ok(Uint256::from(3u32)),
1549        );
1550        assert_eq!(
1551            Uint256::from(7u32).checked_div_euclid(Uint256::from(2u32)),
1552            Ok(Uint256::from(3u32)),
1553        );
1554        assert!(matches!(
1555            Uint256::MAX.checked_rem(Uint256::from(0u32)),
1556            Err(DivideByZeroError { .. })
1557        ));
1558
1559        // saturating_*
1560        assert_eq!(
1561            Uint256::MAX.saturating_add(Uint256::from(1u32)),
1562            Uint256::MAX
1563        );
1564        assert_eq!(
1565            Uint256::from(0u32).saturating_sub(Uint256::from(1u32)),
1566            Uint256::from(0u32)
1567        );
1568        assert_eq!(
1569            Uint256::MAX.saturating_mul(Uint256::from(2u32)),
1570            Uint256::MAX
1571        );
1572        assert_eq!(
1573            Uint256::from(4u32).saturating_pow(2u32),
1574            Uint256::from(16u32)
1575        );
1576        assert_eq!(Uint256::MAX.saturating_pow(2u32), Uint256::MAX);
1577    }
1578
1579    #[test]
1580    #[allow(clippy::op_ref)]
1581    fn uint256_implements_rem() {
1582        let a = Uint256::from(10u32);
1583        assert_eq!(a % Uint256::from(10u32), Uint256::zero());
1584        assert_eq!(a % Uint256::from(2u32), Uint256::zero());
1585        assert_eq!(a % Uint256::from(1u32), Uint256::zero());
1586        assert_eq!(a % Uint256::from(3u32), Uint256::from(1u32));
1587        assert_eq!(a % Uint256::from(4u32), Uint256::from(2u32));
1588
1589        // works for refs
1590        let a = Uint256::from(10u32);
1591        let b = Uint256::from(3u32);
1592        let expected = Uint256::from(1u32);
1593        assert_eq!(a % b, expected);
1594        assert_eq!(a % &b, expected);
1595        assert_eq!(&a % b, expected);
1596        assert_eq!(&a % &b, expected);
1597    }
1598
1599    #[test]
1600    #[should_panic(expected = "division by zero")]
1601    fn uint256_rem_panics_for_zero() {
1602        let _ = Uint256::from(10u32) % Uint256::zero();
1603    }
1604
1605    #[test]
1606    #[allow(clippy::op_ref)]
1607    fn uint256_rem_works() {
1608        assert_eq!(
1609            Uint256::from(12u32) % Uint256::from(10u32),
1610            Uint256::from(2u32)
1611        );
1612        assert_eq!(Uint256::from(50u32) % Uint256::from(5u32), Uint256::zero());
1613
1614        // works for refs
1615        let a = Uint256::from(42u32);
1616        let b = Uint256::from(5u32);
1617        let expected = Uint256::from(2u32);
1618        assert_eq!(a % b, expected);
1619        assert_eq!(a % &b, expected);
1620        assert_eq!(&a % b, expected);
1621        assert_eq!(&a % &b, expected);
1622    }
1623
1624    #[test]
1625    fn uint256_rem_assign_works() {
1626        let mut a = Uint256::from(30u32);
1627        a %= Uint256::from(4u32);
1628        assert_eq!(a, Uint256::from(2u32));
1629
1630        // works for refs
1631        let mut a = Uint256::from(25u32);
1632        let b = Uint256::from(6u32);
1633        a %= &b;
1634        assert_eq!(a, Uint256::from(1u32));
1635    }
1636
1637    #[test]
1638    fn uint256_abs_diff_works() {
1639        let a = Uint256::from(42u32);
1640        let b = Uint256::from(5u32);
1641        let expected = Uint256::from(37u32);
1642        assert_eq!(a.abs_diff(b), expected);
1643        assert_eq!(b.abs_diff(a), expected);
1644    }
1645
1646    #[test]
1647    fn uint256_partial_eq() {
1648        let test_cases = [(1, 1, true), (42, 42, true), (42, 24, false), (0, 0, true)]
1649            .into_iter()
1650            .map(|(lhs, rhs, expected): (u64, u64, bool)| {
1651                (Uint256::from(lhs), Uint256::from(rhs), expected)
1652            });
1653
1654        #[allow(clippy::op_ref)]
1655        for (lhs, rhs, expected) in test_cases {
1656            assert_eq!(lhs == rhs, expected);
1657            assert_eq!(&lhs == rhs, expected);
1658            assert_eq!(lhs == &rhs, expected);
1659            assert_eq!(&lhs == &rhs, expected);
1660        }
1661    }
1662}