Skip to main content

cosmwasm_std/math/
decimal256.rs

1use alloc::string::ToString;
2use core::cmp::Ordering;
3use core::fmt::{self, Write};
4use core::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Rem, RemAssign, Sub, SubAssign};
5use core::str::FromStr;
6use serde::{de, ser, Deserialize, Deserializer, Serialize};
7
8use crate::errors::{
9    CheckedFromRatioError, CheckedMultiplyRatioError, DivideByZeroError, OverflowError,
10    OverflowOperation, RoundUpOverflowError, StdError,
11};
12use crate::forward_ref::{forward_ref_binop, forward_ref_op_assign};
13use crate::{
14    __internal::forward_ref_partial_eq, Decimal, SignedDecimal, SignedDecimal256, Uint512,
15};
16
17use super::Fraction;
18use super::Isqrt;
19use super::Uint256;
20
21/// A fixed-point decimal value with 18 fractional digits, i.e. Decimal256(1_000_000_000_000_000_000) == 1.0
22///
23/// The greatest possible value that can be represented is
24/// 115792089237316195423570985008687907853269984665640564039457.584007913129639935
25/// (which is (2^256 - 1) / 10^18)
26#[derive(Copy, Clone, Default, PartialEq, Eq, PartialOrd, Ord, schemars::JsonSchema)]
27pub struct Decimal256(#[schemars(with = "String")] Uint256);
28
29forward_ref_partial_eq!(Decimal256, Decimal256);
30
31#[derive(Debug, PartialEq, Eq, thiserror::Error)]
32#[error("Decimal256 range exceeded")]
33pub struct Decimal256RangeExceeded;
34
35impl Decimal256 {
36    const DECIMAL_FRACTIONAL: Uint256 = // 1*10**18
37        Uint256::from_u128(1_000_000_000_000_000_000);
38    const DECIMAL_FRACTIONAL_SQUARED: Uint256 = // 1*10**36
39        Uint256::from_u128(1_000_000_000_000_000_000_000_000_000_000_000_000);
40
41    /// The number of decimal places. Since decimal types are fixed-point rather than
42    /// floating-point, this is a constant.
43    pub const DECIMAL_PLACES: u32 = 18;
44    /// The largest value that can be represented by this decimal type.
45    pub const MAX: Self = Self(Uint256::MAX);
46    /// The smallest value that can be represented by this decimal type.
47    pub const MIN: Self = Self(Uint256::MIN);
48
49    /// Creates a Decimal256 from Uint256
50    /// This is equivalent to `Decimal256::from_atomics(value, 18)` but usable in a const context.
51    pub const fn new(value: Uint256) -> Self {
52        Self(value)
53    }
54
55    /// Creates a Decimal256 from u128
56    /// This is equivalent to `Decimal256::from_atomics(value, 18)` but usable in a const context.
57    pub const fn raw(value: u128) -> Self {
58        Self(Uint256::from_u128(value))
59    }
60
61    /// Create a 1.0 Decimal256
62    #[inline]
63    pub const fn one() -> Self {
64        Self(Self::DECIMAL_FRACTIONAL)
65    }
66
67    /// Create a 0.0 Decimal256
68    #[inline]
69    pub const fn zero() -> Self {
70        Self(Uint256::zero())
71    }
72
73    /// Convert x% into Decimal256
74    ///
75    /// ## Examples
76    ///
77    /// ```
78    /// # use std::str::FromStr;
79    /// # use cosmwasm_std::Decimal256;
80    /// const HALF: Decimal256 = Decimal256::percent(50);
81    ///
82    /// assert_eq!(HALF, Decimal256::from_str("0.5").unwrap());
83    /// ```
84    pub const fn percent(x: u64) -> Self {
85        // multiplication does not overflow since `u64::MAX` * 10**16 is well in u128 range
86        let atomics = (x as u128) * 10_000_000_000_000_000;
87        Self(Uint256::from_u128(atomics))
88    }
89
90    /// Convert permille (x/1000) into Decimal256
91    ///
92    /// ## Examples
93    ///
94    /// ```
95    /// # use std::str::FromStr;
96    /// # use cosmwasm_std::Decimal256;
97    /// const HALF: Decimal256 = Decimal256::permille(500);
98    ///
99    /// assert_eq!(HALF, Decimal256::from_str("0.5").unwrap());
100    /// ```
101    pub const fn permille(x: u64) -> Self {
102        // multiplication does not overflow since `u64::MAX` * 10**15 is well in u128 range
103        let atomics = (x as u128) * 1_000_000_000_000_000;
104        Self(Uint256::from_u128(atomics))
105    }
106
107    /// Convert basis points (x/10000) into Decimal256
108    ///
109    /// ## Examples
110    ///
111    /// ```
112    /// # use std::str::FromStr;
113    /// # use cosmwasm_std::Decimal256;
114    /// const TWO_BPS: Decimal256 = Decimal256::bps(2);
115    /// const HALF: Decimal256 = Decimal256::bps(5000);
116    ///
117    /// assert_eq!(TWO_BPS, Decimal256::from_str("0.0002").unwrap());
118    /// assert_eq!(HALF, Decimal256::from_str("0.5").unwrap());
119    /// ```
120    pub const fn bps(x: u64) -> Self {
121        // multiplication does not overflow since `u64::MAX` * 10**14 is well in u128 range
122        let atomics = (x as u128) * 100_000_000_000_000;
123        Self(Uint256::from_u128(atomics))
124    }
125
126    /// Creates a decimal from a number of atomic units and the number
127    /// of decimal places. The inputs will be converted internally to form
128    /// a decimal with 18 decimal places. So the input 123 and 2 will create
129    /// the decimal 1.23.
130    ///
131    /// Using 18 decimal places is slightly more efficient than other values
132    /// as no internal conversion is necessary.
133    ///
134    /// ## Examples
135    ///
136    /// ```
137    /// # use cosmwasm_std::{Decimal256, Uint256};
138    /// let a = Decimal256::from_atomics(1234u64, 3).unwrap();
139    /// assert_eq!(a.to_string(), "1.234");
140    ///
141    /// let a = Decimal256::from_atomics(1234u128, 0).unwrap();
142    /// assert_eq!(a.to_string(), "1234");
143    ///
144    /// let a = Decimal256::from_atomics(1u64, 18).unwrap();
145    /// assert_eq!(a.to_string(), "0.000000000000000001");
146    ///
147    /// let a = Decimal256::from_atomics(Uint256::MAX, 18).unwrap();
148    /// assert_eq!(a, Decimal256::MAX);
149    /// ```
150    pub fn from_atomics(
151        atomics: impl Into<Uint256>,
152        decimal_places: u32,
153    ) -> Result<Self, Decimal256RangeExceeded> {
154        let atomics = atomics.into();
155        const TEN: Uint256 = Uint256::from_be_bytes([
156            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
157            0, 0, 10,
158        ]);
159        Ok(match decimal_places.cmp(&Self::DECIMAL_PLACES) {
160            Ordering::Less => {
161                let digits = (Self::DECIMAL_PLACES) - decimal_places; // No overflow because decimal_places < DECIMAL_PLACES
162                let factor = TEN.checked_pow(digits).unwrap(); // Safe because digits <= 17
163                Self(
164                    atomics
165                        .checked_mul(factor)
166                        .map_err(|_| Decimal256RangeExceeded)?,
167                )
168            }
169            Ordering::Equal => Self(atomics),
170            Ordering::Greater => {
171                let digits = decimal_places - (Self::DECIMAL_PLACES); // No overflow because decimal_places > DECIMAL_PLACES
172                if let Ok(factor) = TEN.checked_pow(digits) {
173                    Self(atomics.checked_div(factor).unwrap()) // Safe because factor cannot be zero
174                } else {
175                    // In this case `factor` exceeds the Uint256 range.
176                    // Any Uint256 `x` divided by `factor` with `factor > Uint256::MAX` is 0.
177                    // Try e.g. Python3: `(2**256-1) // 2**256`
178                    Self(Uint256::zero())
179                }
180            }
181        })
182    }
183
184    /// Returns the ratio (numerator / denominator) as a Decimal256
185    pub fn from_ratio(numerator: impl Into<Uint256>, denominator: impl Into<Uint256>) -> Self {
186        match Decimal256::checked_from_ratio(numerator, denominator) {
187            Ok(value) => value,
188            Err(CheckedFromRatioError::DivideByZero) => {
189                panic!("Denominator must not be zero")
190            }
191            Err(CheckedFromRatioError::Overflow) => panic!("Multiplication overflow"),
192        }
193    }
194
195    /// Returns the ratio (numerator / denominator) as a Decimal256
196    pub fn checked_from_ratio(
197        numerator: impl Into<Uint256>,
198        denominator: impl Into<Uint256>,
199    ) -> Result<Self, CheckedFromRatioError> {
200        let numerator: Uint256 = numerator.into();
201        let denominator: Uint256 = denominator.into();
202        match numerator.checked_multiply_ratio(Self::DECIMAL_FRACTIONAL, denominator) {
203            Ok(ratio) => {
204                // numerator * DECIMAL_FRACTIONAL / denominator
205                Ok(Self(ratio))
206            }
207            Err(CheckedMultiplyRatioError::Overflow) => Err(CheckedFromRatioError::Overflow),
208            Err(CheckedMultiplyRatioError::DivideByZero) => {
209                Err(CheckedFromRatioError::DivideByZero)
210            }
211        }
212    }
213
214    #[must_use]
215    pub const fn is_zero(&self) -> bool {
216        self.0.is_zero()
217    }
218
219    /// A decimal is an integer of atomic units plus a number that specifies the
220    /// position of the decimal dot. So any decimal can be expressed as two numbers.
221    ///
222    /// ## Examples
223    ///
224    /// ```
225    /// # use cosmwasm_std::{Decimal256, Uint256};
226    /// # use core::str::FromStr;
227    /// // Value with whole and fractional part
228    /// let a = Decimal256::from_str("1.234").unwrap();
229    /// assert_eq!(a.decimal_places(), 18);
230    /// assert_eq!(a.atomics(), Uint256::from(1234000000000000000u128));
231    ///
232    /// // Smallest possible value
233    /// let b = Decimal256::from_str("0.000000000000000001").unwrap();
234    /// assert_eq!(b.decimal_places(), 18);
235    /// assert_eq!(b.atomics(), Uint256::from(1u128));
236    /// ```
237    #[must_use]
238    #[inline]
239    pub const fn atomics(&self) -> Uint256 {
240        self.0
241    }
242
243    /// The number of decimal places. This is a constant value for now
244    /// but this could potentially change as the type evolves.
245    ///
246    /// See also [`Decimal256::atomics()`].
247    #[must_use]
248    #[inline]
249    pub const fn decimal_places(&self) -> u32 {
250        Self::DECIMAL_PLACES
251    }
252
253    /// Rounds value down after decimal places.
254    #[must_use = "this returns the result of the operation, without modifying the original"]
255    pub fn floor(&self) -> Self {
256        Self((self.0 / Self::DECIMAL_FRACTIONAL) * Self::DECIMAL_FRACTIONAL)
257    }
258
259    /// Rounds value up after decimal places. Panics on overflow.
260    #[must_use = "this returns the result of the operation, without modifying the original"]
261    pub fn ceil(&self) -> Self {
262        match self.checked_ceil() {
263            Ok(value) => value,
264            Err(_) => panic!("attempt to ceil with overflow"),
265        }
266    }
267
268    /// Rounds value up after decimal places. Returns OverflowError on overflow.
269    pub fn checked_ceil(&self) -> Result<Self, RoundUpOverflowError> {
270        let floor = self.floor();
271        if floor == self {
272            Ok(floor)
273        } else {
274            floor
275                .checked_add(Decimal256::one())
276                .map_err(|_| RoundUpOverflowError)
277        }
278    }
279
280    pub fn checked_add(self, other: Self) -> Result<Self, OverflowError> {
281        self.0
282            .checked_add(other.0)
283            .map(Self)
284            .map_err(|_| OverflowError::new(OverflowOperation::Add))
285    }
286
287    pub fn checked_sub(self, other: Self) -> Result<Self, OverflowError> {
288        self.0
289            .checked_sub(other.0)
290            .map(Self)
291            .map_err(|_| OverflowError::new(OverflowOperation::Sub))
292    }
293
294    /// Multiplies one `Decimal256` by another, returning an `OverflowError` if an overflow occurred.
295    pub fn checked_mul(self, other: Self) -> Result<Self, OverflowError> {
296        let result_as_uint512 = self.numerator().full_mul(other.numerator())
297            / Uint512::from_uint256(Self::DECIMAL_FRACTIONAL); // from_uint128 is a const method and should be "free"
298        result_as_uint512
299            .try_into()
300            .map(Self)
301            .map_err(|_| OverflowError::new(OverflowOperation::Mul))
302    }
303
304    /// Raises a value to the power of `exp`, panics if an overflow occurred.
305    #[must_use = "this returns the result of the operation, without modifying the original"]
306    pub fn pow(self, exp: u32) -> Self {
307        match self.checked_pow(exp) {
308            Ok(value) => value,
309            Err(_) => panic!("Multiplication overflow"),
310        }
311    }
312
313    /// Raises a value to the power of `exp`, returning an `OverflowError` if an overflow occurred.
314    #[allow(clippy::manual_is_multiple_of)]
315    pub fn checked_pow(self, exp: u32) -> Result<Self, OverflowError> {
316        // This uses the exponentiation by squaring algorithm:
317        // https://en.wikipedia.org/wiki/Exponentiation_by_squaring#Basic_method
318
319        fn inner(mut x: Decimal256, mut n: u32) -> Result<Decimal256, OverflowError> {
320            if n == 0 {
321                return Ok(Decimal256::one());
322            }
323
324            let mut y = Decimal256::one();
325
326            while n > 1 {
327                if n % 2 == 0 {
328                    x = x.checked_mul(x)?;
329                    n /= 2;
330                } else {
331                    y = x.checked_mul(y)?;
332                    x = x.checked_mul(x)?;
333                    n = (n - 1) / 2;
334                }
335            }
336
337            Ok(x * y)
338        }
339
340        inner(self, exp).map_err(|_| OverflowError::new(OverflowOperation::Pow))
341    }
342
343    pub fn checked_div(self, other: Self) -> Result<Self, CheckedFromRatioError> {
344        Decimal256::checked_from_ratio(self.numerator(), other.numerator())
345    }
346
347    pub fn checked_rem(self, other: Self) -> Result<Self, DivideByZeroError> {
348        self.0
349            .checked_rem(other.0)
350            .map(Self)
351            .map_err(|_| DivideByZeroError)
352    }
353
354    /// Returns the approximate square root as a Decimal256.
355    ///
356    /// This should not overflow or panic.
357    #[must_use = "this returns the result of the operation, without modifying the original"]
358    pub fn sqrt(&self) -> Self {
359        // Algorithm described in https://hackmd.io/@webmaster128/SJThlukj_
360        // We start with the highest precision possible and lower it until
361        // there's no overflow.
362        //
363        // TODO: This could be made more efficient once log10 is in:
364        // https://github.com/rust-lang/rust/issues/70887
365        // The max precision is something like `18 - log10(self.0) / 2`.
366        (0..=Self::DECIMAL_PLACES / 2)
367            .rev()
368            .find_map(|i| self.sqrt_with_precision(i))
369            // The last step (i = 0) is guaranteed to succeed because `isqrt(Uint256::MAX) * 10^9` does not overflow
370            .unwrap()
371    }
372
373    /// Lower precision means more aggressive rounding, but less risk of overflow.
374    /// Precision *must* be a number between 0 and 9 (inclusive).
375    ///
376    /// Returns `None` if the internal multiplication overflows.
377    #[must_use = "this returns the result of the operation, without modifying the original"]
378    fn sqrt_with_precision(&self, precision: u32) -> Option<Self> {
379        let inner_mul = Uint256::from(100u128).pow(precision);
380        self.0.checked_mul(inner_mul).ok().map(|inner| {
381            let outer_mul = Uint256::from(10u128).pow(Self::DECIMAL_PLACES / 2 - precision);
382            Self(inner.isqrt().checked_mul(outer_mul).unwrap())
383        })
384    }
385
386    #[must_use = "this returns the result of the operation, without modifying the original"]
387    pub fn abs_diff(self, other: Self) -> Self {
388        if self < other {
389            other - self
390        } else {
391            self - other
392        }
393    }
394
395    #[must_use = "this returns the result of the operation, without modifying the original"]
396    pub fn saturating_add(self, other: Self) -> Self {
397        match self.checked_add(other) {
398            Ok(value) => value,
399            Err(_) => Self::MAX,
400        }
401    }
402
403    #[must_use = "this returns the result of the operation, without modifying the original"]
404    pub fn saturating_sub(self, other: Self) -> Self {
405        match self.checked_sub(other) {
406            Ok(value) => value,
407            Err(_) => Self::zero(),
408        }
409    }
410
411    #[must_use = "this returns the result of the operation, without modifying the original"]
412    pub fn saturating_mul(self, other: Self) -> Self {
413        match self.checked_mul(other) {
414            Ok(value) => value,
415            Err(_) => Self::MAX,
416        }
417    }
418
419    #[must_use = "this returns the result of the operation, without modifying the original"]
420    pub fn saturating_pow(self, exp: u32) -> Self {
421        match self.checked_pow(exp) {
422            Ok(value) => value,
423            Err(_) => Self::MAX,
424        }
425    }
426
427    /// Converts this decimal to an unsigned integer by truncating
428    /// the fractional part, e.g. 22.5 becomes 22.
429    ///
430    /// ## Examples
431    ///
432    /// ```
433    /// use core::str::FromStr;
434    /// use cosmwasm_std::{Decimal256, Uint256};
435    ///
436    /// let d = Decimal256::from_str("12.345").unwrap();
437    /// assert_eq!(d.to_uint_floor(), Uint256::from(12u64));
438    ///
439    /// let d = Decimal256::from_str("12.999").unwrap();
440    /// assert_eq!(d.to_uint_floor(), Uint256::from(12u64));
441    ///
442    /// let d = Decimal256::from_str("75.0").unwrap();
443    /// assert_eq!(d.to_uint_floor(), Uint256::from(75u64));
444    /// ```
445    #[must_use = "this returns the result of the operation, without modifying the original"]
446    pub fn to_uint_floor(self) -> Uint256 {
447        self.0 / Self::DECIMAL_FRACTIONAL
448    }
449
450    /// Converts this decimal to an unsigned integer by rounting up
451    /// to the next integer, e.g. 22.3 becomes 23.
452    ///
453    /// ## Examples
454    ///
455    /// ```
456    /// use core::str::FromStr;
457    /// use cosmwasm_std::{Decimal256, Uint256};
458    ///
459    /// let d = Decimal256::from_str("12.345").unwrap();
460    /// assert_eq!(d.to_uint_ceil(), Uint256::from(13u64));
461    ///
462    /// let d = Decimal256::from_str("12.999").unwrap();
463    /// assert_eq!(d.to_uint_ceil(), Uint256::from(13u64));
464    ///
465    /// let d = Decimal256::from_str("75.0").unwrap();
466    /// assert_eq!(d.to_uint_ceil(), Uint256::from(75u64));
467    /// ```
468    #[must_use = "this returns the result of the operation, without modifying the original"]
469    pub fn to_uint_ceil(self) -> Uint256 {
470        // Using `q = 1 + ((x - 1) / y); // if x != 0` with unsigned integers x, y, q
471        // from https://stackoverflow.com/a/2745086/2013738. We know `x + y` CAN overflow.
472        let x = self.0;
473        let y = Self::DECIMAL_FRACTIONAL;
474        if x.is_zero() {
475            Uint256::zero()
476        } else {
477            Uint256::one() + ((x - Uint256::one()) / y)
478        }
479    }
480}
481
482impl Fraction<Uint256> for Decimal256 {
483    #[inline]
484    fn numerator(&self) -> Uint256 {
485        self.0
486    }
487
488    #[inline]
489    fn denominator(&self) -> Uint256 {
490        Self::DECIMAL_FRACTIONAL
491    }
492
493    /// Returns the multiplicative inverse `1/d` for decimal `d`.
494    ///
495    /// If `d` is zero, none is returned.
496    fn inv(&self) -> Option<Self> {
497        if self.is_zero() {
498            None
499        } else {
500            // Let self be p/q with p = self.0 and q = DECIMAL_FRACTIONAL.
501            // Now we calculate the inverse a/b = q/p such that b = DECIMAL_FRACTIONAL. Then
502            // `a = DECIMAL_FRACTIONAL*DECIMAL_FRACTIONAL / self.0`.
503            Some(Self(Self::DECIMAL_FRACTIONAL_SQUARED / self.0))
504        }
505    }
506}
507
508impl From<Decimal> for Decimal256 {
509    fn from(input: Decimal) -> Self {
510        // Unwrap is safe because Decimal256 and Decimal have the same decimal places.
511        // Every Decimal value can be stored in Decimal256.
512        Decimal256::from_atomics(input.atomics(), input.decimal_places()).unwrap()
513    }
514}
515
516impl TryFrom<SignedDecimal> for Decimal256 {
517    type Error = Decimal256RangeExceeded;
518
519    fn try_from(value: SignedDecimal) -> Result<Self, Self::Error> {
520        value
521            .atomics()
522            .try_into()
523            .map(Decimal256)
524            .map_err(|_| Decimal256RangeExceeded)
525    }
526}
527
528impl TryFrom<SignedDecimal256> for Decimal256 {
529    type Error = Decimal256RangeExceeded;
530
531    fn try_from(value: SignedDecimal256) -> Result<Self, Self::Error> {
532        value
533            .atomics()
534            .try_into()
535            .map(Decimal256)
536            .map_err(|_| Decimal256RangeExceeded)
537    }
538}
539
540impl FromStr for Decimal256 {
541    type Err = StdError;
542
543    /// Converts the decimal string to a Decimal256
544    /// Possible inputs: "1.23", "1", "000012", "1.123000000"
545    /// Disallowed: "", ".23"
546    ///
547    /// This never performs any kind of rounding.
548    /// More than DECIMAL_PLACES fractional digits, even zeros, result in an error.
549    fn from_str(input: &str) -> Result<Self, Self::Err> {
550        let mut parts_iter = input.split('.');
551
552        let whole_part = parts_iter.next().unwrap(); // split always returns at least one element
553        let whole = whole_part
554            .parse::<Uint256>()
555            .map_err(|_| StdError::generic_err("Error parsing whole"))?;
556        let mut atomics = whole
557            .checked_mul(Self::DECIMAL_FRACTIONAL)
558            .map_err(|_| StdError::generic_err("Value too big"))?;
559
560        if let Some(fractional_part) = parts_iter.next() {
561            let fractional = fractional_part
562                .parse::<Uint256>()
563                .map_err(|_| StdError::generic_err("Error parsing fractional"))?;
564            let exp = (Self::DECIMAL_PLACES.checked_sub(fractional_part.len() as u32)).ok_or_else(
565                || {
566                    StdError::generic_err(format!(
567                        "Cannot parse more than {} fractional digits",
568                        Self::DECIMAL_PLACES
569                    ))
570                },
571            )?;
572            debug_assert!(exp <= Self::DECIMAL_PLACES);
573            let fractional_factor = Uint256::from(10u128).pow(exp);
574            atomics = atomics
575                .checked_add(
576                    // The inner multiplication can't overflow because
577                    // fractional < 10^DECIMAL_PLACES && fractional_factor <= 10^DECIMAL_PLACES
578                    fractional.checked_mul(fractional_factor).unwrap(),
579                )
580                .map_err(|_| StdError::generic_err("Value too big"))?;
581        }
582
583        if parts_iter.next().is_some() {
584            return Err(StdError::generic_err("Unexpected number of dots"));
585        }
586
587        Ok(Self(atomics))
588    }
589}
590
591impl fmt::Display for Decimal256 {
592    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
593        let whole = (self.0) / Self::DECIMAL_FRACTIONAL;
594        let fractional = (self.0).checked_rem(Self::DECIMAL_FRACTIONAL).unwrap();
595
596        if fractional.is_zero() {
597            write!(f, "{whole}")
598        } else {
599            let fractional_string = format!(
600                "{:0>padding$}",
601                fractional,
602                padding = Self::DECIMAL_PLACES as usize
603            );
604            f.write_str(&whole.to_string())?;
605            f.write_char('.')?;
606            f.write_str(fractional_string.trim_end_matches('0'))?;
607            Ok(())
608        }
609    }
610}
611
612impl fmt::Debug for Decimal256 {
613    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
614        write!(f, "Decimal256({self})")
615    }
616}
617
618impl Add for Decimal256 {
619    type Output = Self;
620
621    fn add(self, other: Self) -> Self {
622        Self(self.0 + other.0)
623    }
624}
625forward_ref_binop!(impl Add, add for Decimal256, Decimal256);
626
627impl AddAssign for Decimal256 {
628    fn add_assign(&mut self, rhs: Decimal256) {
629        *self = *self + rhs;
630    }
631}
632forward_ref_op_assign!(impl AddAssign, add_assign for Decimal256, Decimal256);
633
634impl Sub for Decimal256 {
635    type Output = Self;
636
637    fn sub(self, other: Self) -> Self {
638        Self(self.0 - other.0)
639    }
640}
641forward_ref_binop!(impl Sub, sub for Decimal256, Decimal256);
642
643impl SubAssign for Decimal256 {
644    fn sub_assign(&mut self, rhs: Decimal256) {
645        *self = *self - rhs;
646    }
647}
648forward_ref_op_assign!(impl SubAssign, sub_assign for Decimal256, Decimal256);
649
650impl Mul for Decimal256 {
651    type Output = Self;
652
653    #[allow(clippy::suspicious_arithmetic_impl)]
654    fn mul(self, other: Self) -> Self {
655        // Decimals are fractions. We can multiply two decimals a and b
656        // via
657        //       (a.numerator() * b.numerator()) / (a.denominator() * b.denominator())
658        //     = (a.numerator() * b.numerator()) / a.denominator() / b.denominator()
659
660        let result_as_uint512 = self.numerator().full_mul(other.numerator())
661            / Uint512::from_uint256(Self::DECIMAL_FRACTIONAL); // from_uint256 is a const method and should be "free"
662        match result_as_uint512.try_into() {
663            Ok(result) => Self(result),
664            Err(_) => panic!("attempt to multiply with overflow"),
665        }
666    }
667}
668forward_ref_binop!(impl Mul, mul for Decimal256, Decimal256);
669
670impl MulAssign for Decimal256 {
671    fn mul_assign(&mut self, rhs: Self) {
672        *self = *self * rhs;
673    }
674}
675forward_ref_op_assign!(impl MulAssign, mul_assign for Decimal256, Decimal256);
676
677impl Div for Decimal256 {
678    type Output = Self;
679
680    fn div(self, other: Self) -> Self {
681        match Decimal256::checked_from_ratio(self.numerator(), other.numerator()) {
682            Ok(ratio) => ratio,
683            Err(CheckedFromRatioError::DivideByZero) => {
684                panic!("Division failed - denominator must not be zero")
685            }
686            Err(CheckedFromRatioError::Overflow) => {
687                panic!("Division failed - multiplication overflow")
688            }
689        }
690    }
691}
692forward_ref_binop!(impl Div, div for Decimal256, Decimal256);
693
694impl DivAssign for Decimal256 {
695    fn div_assign(&mut self, rhs: Decimal256) {
696        *self = *self / rhs;
697    }
698}
699forward_ref_op_assign!(impl DivAssign, div_assign for Decimal256, Decimal256);
700
701impl Div<Uint256> for Decimal256 {
702    type Output = Self;
703
704    fn div(self, rhs: Uint256) -> Self::Output {
705        Self(self.0 / rhs)
706    }
707}
708
709impl DivAssign<Uint256> for Decimal256 {
710    fn div_assign(&mut self, rhs: Uint256) {
711        self.0 /= rhs;
712    }
713}
714
715impl Rem for Decimal256 {
716    type Output = Self;
717
718    /// # Panics
719    ///
720    /// This operation will panic if `rhs` is zero
721    #[inline]
722    fn rem(self, rhs: Self) -> Self {
723        Self(self.0.rem(rhs.0))
724    }
725}
726forward_ref_binop!(impl Rem, rem for Decimal256, Decimal256);
727
728impl RemAssign<Decimal256> for Decimal256 {
729    fn rem_assign(&mut self, rhs: Decimal256) {
730        *self = *self % rhs;
731    }
732}
733forward_ref_op_assign!(impl RemAssign, rem_assign for Decimal256, Decimal256);
734
735impl<A> core::iter::Sum<A> for Decimal256
736where
737    Self: Add<A, Output = Self>,
738{
739    fn sum<I: Iterator<Item = A>>(iter: I) -> Self {
740        iter.fold(Self::zero(), Add::add)
741    }
742}
743
744/// Serializes as a decimal string
745impl Serialize for Decimal256 {
746    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
747    where
748        S: ser::Serializer,
749    {
750        serializer.serialize_str(&self.to_string())
751    }
752}
753
754/// Deserializes as a base64 string
755impl<'de> Deserialize<'de> for Decimal256 {
756    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
757    where
758        D: Deserializer<'de>,
759    {
760        deserializer.deserialize_str(Decimal256Visitor)
761    }
762}
763
764struct Decimal256Visitor;
765
766impl<'de> de::Visitor<'de> for Decimal256Visitor {
767    type Value = Decimal256;
768
769    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
770        formatter.write_str("string-encoded decimal")
771    }
772
773    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
774    where
775        E: de::Error,
776    {
777        match Self::Value::from_str(v) {
778            Ok(d) => Ok(d),
779            Err(e) => Err(E::custom(format_args!("Error parsing decimal '{v}': {e}"))),
780        }
781    }
782}
783
784#[cfg(test)]
785mod tests {
786    use super::*;
787    use crate::errors::StdError;
788
789    use alloc::vec::Vec;
790
791    fn dec(input: &str) -> Decimal256 {
792        Decimal256::from_str(input).unwrap()
793    }
794
795    #[test]
796    fn decimal256_new() {
797        let expected = Uint256::from(300u128);
798        assert_eq!(Decimal256::new(expected).0, expected);
799    }
800
801    #[test]
802    fn decimal256_raw() {
803        let value = 300u128;
804        let expected = Uint256::from(value);
805        assert_eq!(Decimal256::raw(value).0, expected);
806    }
807
808    #[test]
809    fn decimal256_one() {
810        let value = Decimal256::one();
811        assert_eq!(value.0, Decimal256::DECIMAL_FRACTIONAL);
812    }
813
814    #[test]
815    fn decimal256_zero() {
816        let value = Decimal256::zero();
817        assert!(value.0.is_zero());
818    }
819
820    #[test]
821    fn decimal256_percent() {
822        let value = Decimal256::percent(50);
823        assert_eq!(value.0, Decimal256::DECIMAL_FRACTIONAL / Uint256::from(2u8));
824    }
825
826    #[test]
827    fn decimal256_permille() {
828        let value = Decimal256::permille(125);
829        assert_eq!(value.0, Decimal256::DECIMAL_FRACTIONAL / Uint256::from(8u8));
830    }
831
832    #[test]
833    fn decimal256_bps() {
834        let value = Decimal256::bps(125);
835        assert_eq!(
836            value.0,
837            Decimal256::DECIMAL_FRACTIONAL / Uint256::from(80u8)
838        );
839    }
840
841    #[test]
842    fn decimal256_from_atomics_works() {
843        let one = Decimal256::one();
844        let two = one + one;
845
846        assert_eq!(Decimal256::from_atomics(1u128, 0).unwrap(), one);
847        assert_eq!(Decimal256::from_atomics(10u128, 1).unwrap(), one);
848        assert_eq!(Decimal256::from_atomics(100u128, 2).unwrap(), one);
849        assert_eq!(Decimal256::from_atomics(1000u128, 3).unwrap(), one);
850        assert_eq!(
851            Decimal256::from_atomics(1000000000000000000u128, 18).unwrap(),
852            one
853        );
854        assert_eq!(
855            Decimal256::from_atomics(10000000000000000000u128, 19).unwrap(),
856            one
857        );
858        assert_eq!(
859            Decimal256::from_atomics(100000000000000000000u128, 20).unwrap(),
860            one
861        );
862
863        assert_eq!(Decimal256::from_atomics(2u128, 0).unwrap(), two);
864        assert_eq!(Decimal256::from_atomics(20u128, 1).unwrap(), two);
865        assert_eq!(Decimal256::from_atomics(200u128, 2).unwrap(), two);
866        assert_eq!(Decimal256::from_atomics(2000u128, 3).unwrap(), two);
867        assert_eq!(
868            Decimal256::from_atomics(2000000000000000000u128, 18).unwrap(),
869            two
870        );
871        assert_eq!(
872            Decimal256::from_atomics(20000000000000000000u128, 19).unwrap(),
873            two
874        );
875        assert_eq!(
876            Decimal256::from_atomics(200000000000000000000u128, 20).unwrap(),
877            two
878        );
879
880        // Cuts decimal digits (20 provided but only 18 can be stored)
881        assert_eq!(
882            Decimal256::from_atomics(4321u128, 20).unwrap(),
883            Decimal256::from_str("0.000000000000000043").unwrap()
884        );
885        assert_eq!(
886            Decimal256::from_atomics(6789u128, 20).unwrap(),
887            Decimal256::from_str("0.000000000000000067").unwrap()
888        );
889        assert_eq!(
890            Decimal256::from_atomics(u128::MAX, 38).unwrap(),
891            Decimal256::from_str("3.402823669209384634").unwrap()
892        );
893        assert_eq!(
894            Decimal256::from_atomics(u128::MAX, 39).unwrap(),
895            Decimal256::from_str("0.340282366920938463").unwrap()
896        );
897        assert_eq!(
898            Decimal256::from_atomics(u128::MAX, 45).unwrap(),
899            Decimal256::from_str("0.000000340282366920").unwrap()
900        );
901        assert_eq!(
902            Decimal256::from_atomics(u128::MAX, 51).unwrap(),
903            Decimal256::from_str("0.000000000000340282").unwrap()
904        );
905        assert_eq!(
906            Decimal256::from_atomics(u128::MAX, 56).unwrap(),
907            Decimal256::from_str("0.000000000000000003").unwrap()
908        );
909        assert_eq!(
910            Decimal256::from_atomics(u128::MAX, 57).unwrap(),
911            Decimal256::from_str("0.000000000000000000").unwrap()
912        );
913        assert_eq!(
914            Decimal256::from_atomics(u128::MAX, u32::MAX).unwrap(),
915            Decimal256::from_str("0.000000000000000000").unwrap()
916        );
917
918        // Can be used with max value
919        let max = Decimal256::MAX;
920        assert_eq!(
921            Decimal256::from_atomics(max.atomics(), max.decimal_places()).unwrap(),
922            max
923        );
924
925        // Overflow is only possible with digits < 18
926        let result = Decimal256::from_atomics(Uint256::MAX, 17);
927        assert_eq!(result.unwrap_err(), Decimal256RangeExceeded);
928    }
929
930    #[test]
931    fn decimal256_from_ratio_works() {
932        // 1.0
933        assert_eq!(Decimal256::from_ratio(1u128, 1u128), Decimal256::one());
934        assert_eq!(Decimal256::from_ratio(53u128, 53u128), Decimal256::one());
935        assert_eq!(Decimal256::from_ratio(125u128, 125u128), Decimal256::one());
936
937        // 1.5
938        assert_eq!(
939            Decimal256::from_ratio(3u128, 2u128),
940            Decimal256::percent(150)
941        );
942        assert_eq!(
943            Decimal256::from_ratio(150u128, 100u128),
944            Decimal256::percent(150)
945        );
946        assert_eq!(
947            Decimal256::from_ratio(333u128, 222u128),
948            Decimal256::percent(150)
949        );
950
951        // 0.125
952        assert_eq!(
953            Decimal256::from_ratio(1u64, 8u64),
954            Decimal256::permille(125)
955        );
956        assert_eq!(
957            Decimal256::from_ratio(125u64, 1000u64),
958            Decimal256::permille(125)
959        );
960
961        // 1/3 (result floored)
962        assert_eq!(
963            Decimal256::from_ratio(1u64, 3u64),
964            Decimal256(Uint256::from_str("333333333333333333").unwrap())
965        );
966
967        // 2/3 (result floored)
968        assert_eq!(
969            Decimal256::from_ratio(2u64, 3u64),
970            Decimal256(Uint256::from_str("666666666666666666").unwrap())
971        );
972
973        // large inputs
974        assert_eq!(Decimal256::from_ratio(0u128, u128::MAX), Decimal256::zero());
975        assert_eq!(
976            Decimal256::from_ratio(u128::MAX, u128::MAX),
977            Decimal256::one()
978        );
979        // 340282366920938463463 is the largest integer <= Decimal256::MAX
980        assert_eq!(
981            Decimal256::from_ratio(340282366920938463463u128, 1u128),
982            Decimal256::from_str("340282366920938463463").unwrap()
983        );
984    }
985
986    #[test]
987    #[should_panic(expected = "Denominator must not be zero")]
988    fn decimal256_from_ratio_panics_for_zero_denominator() {
989        Decimal256::from_ratio(1u128, 0u128);
990    }
991
992    #[test]
993    #[should_panic(expected = "Multiplication overflow")]
994    fn decimal256_from_ratio_panics_for_mul_overflow() {
995        Decimal256::from_ratio(Uint256::MAX, 1u128);
996    }
997
998    #[test]
999    fn decimal256_checked_from_ratio_does_not_panic() {
1000        assert_eq!(
1001            Decimal256::checked_from_ratio(1u128, 0u128),
1002            Err(CheckedFromRatioError::DivideByZero)
1003        );
1004
1005        assert_eq!(
1006            Decimal256::checked_from_ratio(Uint256::MAX, 1u128),
1007            Err(CheckedFromRatioError::Overflow)
1008        );
1009    }
1010
1011    #[test]
1012    fn decimal256_implements_fraction() {
1013        let fraction = Decimal256::from_str("1234.567").unwrap();
1014        assert_eq!(
1015            fraction.numerator(),
1016            Uint256::from_str("1234567000000000000000").unwrap()
1017        );
1018        assert_eq!(
1019            fraction.denominator(),
1020            Uint256::from_str("1000000000000000000").unwrap()
1021        );
1022    }
1023
1024    #[test]
1025    fn decimal256_implements_from_decimal() {
1026        let a = Decimal::from_str("123.456").unwrap();
1027        let b = Decimal256::from(a);
1028        assert_eq!(b.to_string(), "123.456");
1029
1030        let a = Decimal::from_str("0").unwrap();
1031        let b = Decimal256::from(a);
1032        assert_eq!(b.to_string(), "0");
1033
1034        let a = Decimal::MAX;
1035        let b = Decimal256::from(a);
1036        assert_eq!(b.to_string(), "340282366920938463463.374607431768211455");
1037    }
1038
1039    #[test]
1040    fn decimal256_from_str_works() {
1041        // Integers
1042        assert_eq!(Decimal256::from_str("0").unwrap(), Decimal256::percent(0));
1043        assert_eq!(Decimal256::from_str("1").unwrap(), Decimal256::percent(100));
1044        assert_eq!(Decimal256::from_str("5").unwrap(), Decimal256::percent(500));
1045        assert_eq!(
1046            Decimal256::from_str("42").unwrap(),
1047            Decimal256::percent(4200)
1048        );
1049        assert_eq!(Decimal256::from_str("000").unwrap(), Decimal256::percent(0));
1050        assert_eq!(
1051            Decimal256::from_str("001").unwrap(),
1052            Decimal256::percent(100)
1053        );
1054        assert_eq!(
1055            Decimal256::from_str("005").unwrap(),
1056            Decimal256::percent(500)
1057        );
1058        assert_eq!(
1059            Decimal256::from_str("0042").unwrap(),
1060            Decimal256::percent(4200)
1061        );
1062
1063        // Decimals
1064        assert_eq!(
1065            Decimal256::from_str("1.0").unwrap(),
1066            Decimal256::percent(100)
1067        );
1068        assert_eq!(
1069            Decimal256::from_str("1.5").unwrap(),
1070            Decimal256::percent(150)
1071        );
1072        assert_eq!(
1073            Decimal256::from_str("0.5").unwrap(),
1074            Decimal256::percent(50)
1075        );
1076        assert_eq!(
1077            Decimal256::from_str("0.123").unwrap(),
1078            Decimal256::permille(123)
1079        );
1080
1081        assert_eq!(
1082            Decimal256::from_str("40.00").unwrap(),
1083            Decimal256::percent(4000)
1084        );
1085        assert_eq!(
1086            Decimal256::from_str("04.00").unwrap(),
1087            Decimal256::percent(400)
1088        );
1089        assert_eq!(
1090            Decimal256::from_str("00.40").unwrap(),
1091            Decimal256::percent(40)
1092        );
1093        assert_eq!(
1094            Decimal256::from_str("00.04").unwrap(),
1095            Decimal256::percent(4)
1096        );
1097
1098        // Can handle 18 fractional digits
1099        assert_eq!(
1100            Decimal256::from_str("7.123456789012345678").unwrap(),
1101            Decimal256(Uint256::from(7123456789012345678u128))
1102        );
1103        assert_eq!(
1104            Decimal256::from_str("7.999999999999999999").unwrap(),
1105            Decimal256(Uint256::from(7999999999999999999u128))
1106        );
1107
1108        // Works for documented max value
1109        assert_eq!(
1110            Decimal256::from_str(
1111                "115792089237316195423570985008687907853269984665640564039457.584007913129639935"
1112            )
1113            .unwrap(),
1114            Decimal256::MAX
1115        );
1116    }
1117
1118    #[test]
1119    fn decimal256_from_str_errors_for_broken_whole_part() {
1120        match Decimal256::from_str("").unwrap_err() {
1121            StdError::GenericErr { msg, .. } => assert_eq!(msg, "Error parsing whole"),
1122            e => panic!("Unexpected error: {e:?}"),
1123        }
1124
1125        match Decimal256::from_str(" ").unwrap_err() {
1126            StdError::GenericErr { msg, .. } => assert_eq!(msg, "Error parsing whole"),
1127            e => panic!("Unexpected error: {e:?}"),
1128        }
1129
1130        match Decimal256::from_str("-1").unwrap_err() {
1131            StdError::GenericErr { msg, .. } => assert_eq!(msg, "Error parsing whole"),
1132            e => panic!("Unexpected error: {e:?}"),
1133        }
1134    }
1135
1136    #[test]
1137    fn decimal256_from_str_errors_for_broken_fractional_part() {
1138        match Decimal256::from_str("1.").unwrap_err() {
1139            StdError::GenericErr { msg, .. } => assert_eq!(msg, "Error parsing fractional"),
1140            e => panic!("Unexpected error: {e:?}"),
1141        }
1142
1143        match Decimal256::from_str("1. ").unwrap_err() {
1144            StdError::GenericErr { msg, .. } => assert_eq!(msg, "Error parsing fractional"),
1145            e => panic!("Unexpected error: {e:?}"),
1146        }
1147
1148        match Decimal256::from_str("1.e").unwrap_err() {
1149            StdError::GenericErr { msg, .. } => assert_eq!(msg, "Error parsing fractional"),
1150            e => panic!("Unexpected error: {e:?}"),
1151        }
1152
1153        match Decimal256::from_str("1.2e3").unwrap_err() {
1154            StdError::GenericErr { msg, .. } => assert_eq!(msg, "Error parsing fractional"),
1155            e => panic!("Unexpected error: {e:?}"),
1156        }
1157    }
1158
1159    #[test]
1160    fn decimal256_from_str_errors_for_more_than_36_fractional_digits() {
1161        match Decimal256::from_str("7.1234567890123456789").unwrap_err() {
1162            StdError::GenericErr { msg, .. } => {
1163                assert_eq!(msg, "Cannot parse more than 18 fractional digits")
1164            }
1165            e => panic!("Unexpected error: {e:?}"),
1166        }
1167
1168        // No special rules for trailing zeros. This could be changed but adds gas cost for the happy path.
1169        match Decimal256::from_str("7.1230000000000000000").unwrap_err() {
1170            StdError::GenericErr { msg, .. } => {
1171                assert_eq!(msg, "Cannot parse more than 18 fractional digits")
1172            }
1173            e => panic!("Unexpected error: {e:?}"),
1174        }
1175    }
1176
1177    #[test]
1178    fn decimal256_from_str_errors_for_invalid_number_of_dots() {
1179        match Decimal256::from_str("1.2.3").unwrap_err() {
1180            StdError::GenericErr { msg, .. } => assert_eq!(msg, "Unexpected number of dots"),
1181            e => panic!("Unexpected error: {e:?}"),
1182        }
1183
1184        match Decimal256::from_str("1.2.3.4").unwrap_err() {
1185            StdError::GenericErr { msg, .. } => assert_eq!(msg, "Unexpected number of dots"),
1186            e => panic!("Unexpected error: {e:?}"),
1187        }
1188    }
1189
1190    #[test]
1191    fn decimal256_from_str_errors_for_more_than_max_value() {
1192        // Integer
1193        match Decimal256::from_str("115792089237316195423570985008687907853269984665640564039458")
1194            .unwrap_err()
1195        {
1196            StdError::GenericErr { msg, .. } => assert_eq!(msg, "Value too big"),
1197            e => panic!("Unexpected error: {e:?}"),
1198        }
1199
1200        // Decimal
1201        match Decimal256::from_str("115792089237316195423570985008687907853269984665640564039458.0")
1202            .unwrap_err()
1203        {
1204            StdError::GenericErr { msg, .. } => assert_eq!(msg, "Value too big"),
1205            e => panic!("Unexpected error: {e:?}"),
1206        }
1207        match Decimal256::from_str(
1208            "115792089237316195423570985008687907853269984665640564039457.584007913129639936",
1209        )
1210        .unwrap_err()
1211        {
1212            StdError::GenericErr { msg, .. } => assert_eq!(msg, "Value too big"),
1213            e => panic!("Unexpected error: {e:?}"),
1214        }
1215    }
1216
1217    #[test]
1218    fn decimal256_atomics_works() {
1219        let zero = Decimal256::zero();
1220        let one = Decimal256::one();
1221        let half = Decimal256::percent(50);
1222        let two = Decimal256::percent(200);
1223        let max = Decimal256::MAX;
1224
1225        assert_eq!(zero.atomics(), Uint256::from(0u128));
1226        assert_eq!(one.atomics(), Uint256::from(1000000000000000000u128));
1227        assert_eq!(half.atomics(), Uint256::from(500000000000000000u128));
1228        assert_eq!(two.atomics(), Uint256::from(2000000000000000000u128));
1229        assert_eq!(max.atomics(), Uint256::MAX);
1230    }
1231
1232    #[test]
1233    fn decimal256_decimal_places_works() {
1234        let zero = Decimal256::zero();
1235        let one = Decimal256::one();
1236        let half = Decimal256::percent(50);
1237        let two = Decimal256::percent(200);
1238        let max = Decimal256::MAX;
1239
1240        assert_eq!(zero.decimal_places(), 18);
1241        assert_eq!(one.decimal_places(), 18);
1242        assert_eq!(half.decimal_places(), 18);
1243        assert_eq!(two.decimal_places(), 18);
1244        assert_eq!(max.decimal_places(), 18);
1245    }
1246
1247    #[test]
1248    fn decimal256_is_zero_works() {
1249        assert!(Decimal256::zero().is_zero());
1250        assert!(Decimal256::percent(0).is_zero());
1251        assert!(Decimal256::permille(0).is_zero());
1252
1253        assert!(!Decimal256::one().is_zero());
1254        assert!(!Decimal256::percent(123).is_zero());
1255        assert!(!Decimal256::permille(1234).is_zero());
1256    }
1257
1258    #[test]
1259    fn decimal256_inv_works() {
1260        // d = 0
1261        assert_eq!(Decimal256::zero().inv(), None);
1262
1263        // d == 1
1264        assert_eq!(Decimal256::one().inv(), Some(Decimal256::one()));
1265
1266        // d > 1 exact
1267        assert_eq!(
1268            Decimal256::from_str("2").unwrap().inv(),
1269            Some(Decimal256::from_str("0.5").unwrap())
1270        );
1271        assert_eq!(
1272            Decimal256::from_str("20").unwrap().inv(),
1273            Some(Decimal256::from_str("0.05").unwrap())
1274        );
1275        assert_eq!(
1276            Decimal256::from_str("200").unwrap().inv(),
1277            Some(Decimal256::from_str("0.005").unwrap())
1278        );
1279        assert_eq!(
1280            Decimal256::from_str("2000").unwrap().inv(),
1281            Some(Decimal256::from_str("0.0005").unwrap())
1282        );
1283
1284        // d > 1 rounded
1285        assert_eq!(
1286            Decimal256::from_str("3").unwrap().inv(),
1287            Some(Decimal256::from_str("0.333333333333333333").unwrap())
1288        );
1289        assert_eq!(
1290            Decimal256::from_str("6").unwrap().inv(),
1291            Some(Decimal256::from_str("0.166666666666666666").unwrap())
1292        );
1293
1294        // d < 1 exact
1295        assert_eq!(
1296            Decimal256::from_str("0.5").unwrap().inv(),
1297            Some(Decimal256::from_str("2").unwrap())
1298        );
1299        assert_eq!(
1300            Decimal256::from_str("0.05").unwrap().inv(),
1301            Some(Decimal256::from_str("20").unwrap())
1302        );
1303        assert_eq!(
1304            Decimal256::from_str("0.005").unwrap().inv(),
1305            Some(Decimal256::from_str("200").unwrap())
1306        );
1307        assert_eq!(
1308            Decimal256::from_str("0.0005").unwrap().inv(),
1309            Some(Decimal256::from_str("2000").unwrap())
1310        );
1311    }
1312
1313    #[test]
1314    #[allow(clippy::op_ref)]
1315    fn decimal256_add_works() {
1316        let value = Decimal256::one() + Decimal256::percent(50); // 1.5
1317        assert_eq!(
1318            value.0,
1319            Decimal256::DECIMAL_FRACTIONAL * Uint256::from(3u8) / Uint256::from(2u8)
1320        );
1321
1322        assert_eq!(
1323            Decimal256::percent(5) + Decimal256::percent(4),
1324            Decimal256::percent(9)
1325        );
1326        assert_eq!(
1327            Decimal256::percent(5) + Decimal256::zero(),
1328            Decimal256::percent(5)
1329        );
1330        assert_eq!(Decimal256::zero() + Decimal256::zero(), Decimal256::zero());
1331
1332        // works for refs
1333        let a = Decimal256::percent(15);
1334        let b = Decimal256::percent(25);
1335        let expected = Decimal256::percent(40);
1336        assert_eq!(a + b, expected);
1337        assert_eq!(&a + b, expected);
1338        assert_eq!(a + &b, expected);
1339        assert_eq!(&a + &b, expected);
1340    }
1341
1342    #[test]
1343    #[should_panic(expected = "attempt to add with overflow")]
1344    fn decimal256_add_overflow_panics() {
1345        let _value = Decimal256::MAX + Decimal256::percent(50);
1346    }
1347
1348    #[test]
1349    fn decimal256_add_assign_works() {
1350        let mut a = Decimal256::percent(30);
1351        a += Decimal256::percent(20);
1352        assert_eq!(a, Decimal256::percent(50));
1353
1354        // works for refs
1355        let mut a = Decimal256::percent(15);
1356        let b = Decimal256::percent(3);
1357        let expected = Decimal256::percent(18);
1358        a += &b;
1359        assert_eq!(a, expected);
1360    }
1361
1362    #[test]
1363    #[allow(clippy::op_ref)]
1364    fn decimal256_sub_works() {
1365        let value = Decimal256::one() - Decimal256::percent(50); // 0.5
1366        assert_eq!(value.0, Decimal256::DECIMAL_FRACTIONAL / Uint256::from(2u8));
1367
1368        assert_eq!(
1369            Decimal256::percent(9) - Decimal256::percent(4),
1370            Decimal256::percent(5)
1371        );
1372        assert_eq!(
1373            Decimal256::percent(16) - Decimal256::zero(),
1374            Decimal256::percent(16)
1375        );
1376        assert_eq!(
1377            Decimal256::percent(16) - Decimal256::percent(16),
1378            Decimal256::zero()
1379        );
1380        assert_eq!(Decimal256::zero() - Decimal256::zero(), Decimal256::zero());
1381
1382        // works for refs
1383        let a = Decimal256::percent(13);
1384        let b = Decimal256::percent(6);
1385        let expected = Decimal256::percent(7);
1386        assert_eq!(a - b, expected);
1387        assert_eq!(&a - b, expected);
1388        assert_eq!(a - &b, expected);
1389        assert_eq!(&a - &b, expected);
1390    }
1391
1392    #[test]
1393    #[should_panic(expected = "attempt to subtract with overflow")]
1394    fn decimal256_sub_overflow_panics() {
1395        let _value = Decimal256::zero() - Decimal256::percent(50);
1396    }
1397
1398    #[test]
1399    fn decimal256_sub_assign_works() {
1400        let mut a = Decimal256::percent(20);
1401        a -= Decimal256::percent(2);
1402        assert_eq!(a, Decimal256::percent(18));
1403
1404        // works for refs
1405        let mut a = Decimal256::percent(33);
1406        let b = Decimal256::percent(13);
1407        let expected = Decimal256::percent(20);
1408        a -= &b;
1409        assert_eq!(a, expected);
1410    }
1411
1412    #[test]
1413    #[allow(clippy::op_ref)]
1414    fn decimal256_implements_mul() {
1415        let one = Decimal256::one();
1416        let two = one + one;
1417        let half = Decimal256::percent(50);
1418
1419        // 1*x and x*1
1420        assert_eq!(one * Decimal256::percent(0), Decimal256::percent(0));
1421        assert_eq!(one * Decimal256::percent(1), Decimal256::percent(1));
1422        assert_eq!(one * Decimal256::percent(10), Decimal256::percent(10));
1423        assert_eq!(one * Decimal256::percent(100), Decimal256::percent(100));
1424        assert_eq!(one * Decimal256::percent(1000), Decimal256::percent(1000));
1425        assert_eq!(one * Decimal256::MAX, Decimal256::MAX);
1426        assert_eq!(Decimal256::percent(0) * one, Decimal256::percent(0));
1427        assert_eq!(Decimal256::percent(1) * one, Decimal256::percent(1));
1428        assert_eq!(Decimal256::percent(10) * one, Decimal256::percent(10));
1429        assert_eq!(Decimal256::percent(100) * one, Decimal256::percent(100));
1430        assert_eq!(Decimal256::percent(1000) * one, Decimal256::percent(1000));
1431        assert_eq!(Decimal256::MAX * one, Decimal256::MAX);
1432
1433        // double
1434        assert_eq!(two * Decimal256::percent(0), Decimal256::percent(0));
1435        assert_eq!(two * Decimal256::percent(1), Decimal256::percent(2));
1436        assert_eq!(two * Decimal256::percent(10), Decimal256::percent(20));
1437        assert_eq!(two * Decimal256::percent(100), Decimal256::percent(200));
1438        assert_eq!(two * Decimal256::percent(1000), Decimal256::percent(2000));
1439        assert_eq!(Decimal256::percent(0) * two, Decimal256::percent(0));
1440        assert_eq!(Decimal256::percent(1) * two, Decimal256::percent(2));
1441        assert_eq!(Decimal256::percent(10) * two, Decimal256::percent(20));
1442        assert_eq!(Decimal256::percent(100) * two, Decimal256::percent(200));
1443        assert_eq!(Decimal256::percent(1000) * two, Decimal256::percent(2000));
1444
1445        // half
1446        assert_eq!(half * Decimal256::percent(0), Decimal256::percent(0));
1447        assert_eq!(half * Decimal256::percent(1), Decimal256::permille(5));
1448        assert_eq!(half * Decimal256::percent(10), Decimal256::percent(5));
1449        assert_eq!(half * Decimal256::percent(100), Decimal256::percent(50));
1450        assert_eq!(half * Decimal256::percent(1000), Decimal256::percent(500));
1451        assert_eq!(Decimal256::percent(0) * half, Decimal256::percent(0));
1452        assert_eq!(Decimal256::percent(1) * half, Decimal256::permille(5));
1453        assert_eq!(Decimal256::percent(10) * half, Decimal256::percent(5));
1454        assert_eq!(Decimal256::percent(100) * half, Decimal256::percent(50));
1455        assert_eq!(Decimal256::percent(1000) * half, Decimal256::percent(500));
1456
1457        // Move left
1458        let a = dec("123.127726548762582");
1459        assert_eq!(a * dec("1"), dec("123.127726548762582"));
1460        assert_eq!(a * dec("10"), dec("1231.27726548762582"));
1461        assert_eq!(a * dec("100"), dec("12312.7726548762582"));
1462        assert_eq!(a * dec("1000"), dec("123127.726548762582"));
1463        assert_eq!(a * dec("1000000"), dec("123127726.548762582"));
1464        assert_eq!(a * dec("1000000000"), dec("123127726548.762582"));
1465        assert_eq!(a * dec("1000000000000"), dec("123127726548762.582"));
1466        assert_eq!(a * dec("1000000000000000"), dec("123127726548762582"));
1467        assert_eq!(a * dec("1000000000000000000"), dec("123127726548762582000"));
1468        assert_eq!(dec("1") * a, dec("123.127726548762582"));
1469        assert_eq!(dec("10") * a, dec("1231.27726548762582"));
1470        assert_eq!(dec("100") * a, dec("12312.7726548762582"));
1471        assert_eq!(dec("1000") * a, dec("123127.726548762582"));
1472        assert_eq!(dec("1000000") * a, dec("123127726.548762582"));
1473        assert_eq!(dec("1000000000") * a, dec("123127726548.762582"));
1474        assert_eq!(dec("1000000000000") * a, dec("123127726548762.582"));
1475        assert_eq!(dec("1000000000000000") * a, dec("123127726548762582"));
1476        assert_eq!(dec("1000000000000000000") * a, dec("123127726548762582000"));
1477
1478        // Move right
1479        let max = Decimal256::MAX;
1480        assert_eq!(
1481            max * dec("1.0"),
1482            dec("115792089237316195423570985008687907853269984665640564039457.584007913129639935")
1483        );
1484        assert_eq!(
1485            max * dec("0.1"),
1486            dec("11579208923731619542357098500868790785326998466564056403945.758400791312963993")
1487        );
1488        assert_eq!(
1489            max * dec("0.01"),
1490            dec("1157920892373161954235709850086879078532699846656405640394.575840079131296399")
1491        );
1492        assert_eq!(
1493            max * dec("0.001"),
1494            dec("115792089237316195423570985008687907853269984665640564039.457584007913129639")
1495        );
1496        assert_eq!(
1497            max * dec("0.000001"),
1498            dec("115792089237316195423570985008687907853269984665640564.039457584007913129")
1499        );
1500        assert_eq!(
1501            max * dec("0.000000001"),
1502            dec("115792089237316195423570985008687907853269984665640.564039457584007913")
1503        );
1504        assert_eq!(
1505            max * dec("0.000000000001"),
1506            dec("115792089237316195423570985008687907853269984665.640564039457584007")
1507        );
1508        assert_eq!(
1509            max * dec("0.000000000000001"),
1510            dec("115792089237316195423570985008687907853269984.665640564039457584")
1511        );
1512        assert_eq!(
1513            max * dec("0.000000000000000001"),
1514            dec("115792089237316195423570985008687907853269.984665640564039457")
1515        );
1516
1517        // works for refs
1518        let a = Decimal256::percent(20);
1519        let b = Decimal256::percent(30);
1520        let expected = Decimal256::percent(6);
1521        assert_eq!(a * b, expected);
1522        assert_eq!(&a * b, expected);
1523        assert_eq!(a * &b, expected);
1524        assert_eq!(&a * &b, expected);
1525    }
1526
1527    #[test]
1528    fn decimal256_mul_assign_works() {
1529        let mut a = Decimal256::percent(15);
1530        a *= Decimal256::percent(60);
1531        assert_eq!(a, Decimal256::percent(9));
1532
1533        // works for refs
1534        let mut a = Decimal256::percent(50);
1535        let b = Decimal256::percent(20);
1536        a *= &b;
1537        assert_eq!(a, Decimal256::percent(10));
1538    }
1539
1540    #[test]
1541    #[should_panic(expected = "attempt to multiply with overflow")]
1542    fn decimal256_mul_overflow_panics() {
1543        let _value = Decimal256::MAX * Decimal256::percent(101);
1544    }
1545
1546    #[test]
1547    fn decimal256_checked_mul() {
1548        let test_data = [
1549            (Decimal256::zero(), Decimal256::zero()),
1550            (Decimal256::zero(), Decimal256::one()),
1551            (Decimal256::one(), Decimal256::zero()),
1552            (Decimal256::percent(10), Decimal256::zero()),
1553            (Decimal256::percent(10), Decimal256::percent(5)),
1554            (Decimal256::MAX, Decimal256::one()),
1555            (
1556                Decimal256::MAX / Uint256::from_uint128(2u128.into()),
1557                Decimal256::percent(200),
1558            ),
1559            (Decimal256::permille(6), Decimal256::permille(13)),
1560        ];
1561
1562        // The regular core::ops::Mul is our source of truth for these tests.
1563        for (x, y) in test_data.into_iter() {
1564            assert_eq!(x * y, x.checked_mul(y).unwrap());
1565        }
1566    }
1567
1568    #[test]
1569    fn decimal256_checked_mul_overflow() {
1570        assert_eq!(
1571            Decimal256::MAX.checked_mul(Decimal256::percent(200)),
1572            Err(OverflowError::new(OverflowOperation::Mul))
1573        );
1574    }
1575
1576    #[test]
1577    #[allow(clippy::op_ref)]
1578    fn decimal256_implements_div() {
1579        let one = Decimal256::one();
1580        let two = one + one;
1581        let half = Decimal256::percent(50);
1582
1583        // 1/x and x/1
1584        assert_eq!(one / Decimal256::percent(1), Decimal256::percent(10_000));
1585        assert_eq!(one / Decimal256::percent(10), Decimal256::percent(1_000));
1586        assert_eq!(one / Decimal256::percent(100), Decimal256::percent(100));
1587        assert_eq!(one / Decimal256::percent(1000), Decimal256::percent(10));
1588        assert_eq!(Decimal256::percent(0) / one, Decimal256::percent(0));
1589        assert_eq!(Decimal256::percent(1) / one, Decimal256::percent(1));
1590        assert_eq!(Decimal256::percent(10) / one, Decimal256::percent(10));
1591        assert_eq!(Decimal256::percent(100) / one, Decimal256::percent(100));
1592        assert_eq!(Decimal256::percent(1000) / one, Decimal256::percent(1000));
1593
1594        // double
1595        assert_eq!(two / Decimal256::percent(1), Decimal256::percent(20_000));
1596        assert_eq!(two / Decimal256::percent(10), Decimal256::percent(2_000));
1597        assert_eq!(two / Decimal256::percent(100), Decimal256::percent(200));
1598        assert_eq!(two / Decimal256::percent(1000), Decimal256::percent(20));
1599        assert_eq!(Decimal256::percent(0) / two, Decimal256::percent(0));
1600        assert_eq!(Decimal256::percent(1) / two, dec("0.005"));
1601        assert_eq!(Decimal256::percent(10) / two, Decimal256::percent(5));
1602        assert_eq!(Decimal256::percent(100) / two, Decimal256::percent(50));
1603        assert_eq!(Decimal256::percent(1000) / two, Decimal256::percent(500));
1604
1605        // half
1606        assert_eq!(half / Decimal256::percent(1), Decimal256::percent(5_000));
1607        assert_eq!(half / Decimal256::percent(10), Decimal256::percent(500));
1608        assert_eq!(half / Decimal256::percent(100), Decimal256::percent(50));
1609        assert_eq!(half / Decimal256::percent(1000), Decimal256::percent(5));
1610        assert_eq!(Decimal256::percent(0) / half, Decimal256::percent(0));
1611        assert_eq!(Decimal256::percent(1) / half, Decimal256::percent(2));
1612        assert_eq!(Decimal256::percent(10) / half, Decimal256::percent(20));
1613        assert_eq!(Decimal256::percent(100) / half, Decimal256::percent(200));
1614        assert_eq!(Decimal256::percent(1000) / half, Decimal256::percent(2000));
1615
1616        // Move right
1617        let a = dec("123127726548762582");
1618        assert_eq!(a / dec("1"), dec("123127726548762582"));
1619        assert_eq!(a / dec("10"), dec("12312772654876258.2"));
1620        assert_eq!(a / dec("100"), dec("1231277265487625.82"));
1621        assert_eq!(a / dec("1000"), dec("123127726548762.582"));
1622        assert_eq!(a / dec("1000000"), dec("123127726548.762582"));
1623        assert_eq!(a / dec("1000000000"), dec("123127726.548762582"));
1624        assert_eq!(a / dec("1000000000000"), dec("123127.726548762582"));
1625        assert_eq!(a / dec("1000000000000000"), dec("123.127726548762582"));
1626        assert_eq!(a / dec("1000000000000000000"), dec("0.123127726548762582"));
1627        assert_eq!(dec("1") / a, dec("0.000000000000000008"));
1628        assert_eq!(dec("10") / a, dec("0.000000000000000081"));
1629        assert_eq!(dec("100") / a, dec("0.000000000000000812"));
1630        assert_eq!(dec("1000") / a, dec("0.000000000000008121"));
1631        assert_eq!(dec("1000000") / a, dec("0.000000000008121647"));
1632        assert_eq!(dec("1000000000") / a, dec("0.000000008121647560"));
1633        assert_eq!(dec("1000000000000") / a, dec("0.000008121647560868"));
1634        assert_eq!(dec("1000000000000000") / a, dec("0.008121647560868164"));
1635        assert_eq!(dec("1000000000000000000") / a, dec("8.121647560868164773"));
1636
1637        // Move left
1638        let a = dec("0.123127726548762582");
1639        assert_eq!(a / dec("1.0"), dec("0.123127726548762582"));
1640        assert_eq!(a / dec("0.1"), dec("1.23127726548762582"));
1641        assert_eq!(a / dec("0.01"), dec("12.3127726548762582"));
1642        assert_eq!(a / dec("0.001"), dec("123.127726548762582"));
1643        assert_eq!(a / dec("0.000001"), dec("123127.726548762582"));
1644        assert_eq!(a / dec("0.000000001"), dec("123127726.548762582"));
1645        assert_eq!(a / dec("0.000000000001"), dec("123127726548.762582"));
1646        assert_eq!(a / dec("0.000000000000001"), dec("123127726548762.582"));
1647        assert_eq!(a / dec("0.000000000000000001"), dec("123127726548762582"));
1648
1649        assert_eq!(
1650            Decimal256::percent(15) / Decimal256::percent(60),
1651            Decimal256::percent(25)
1652        );
1653
1654        // works for refs
1655        let a = Decimal256::percent(100);
1656        let b = Decimal256::percent(20);
1657        let expected = Decimal256::percent(500);
1658        assert_eq!(a / b, expected);
1659        assert_eq!(&a / b, expected);
1660        assert_eq!(a / &b, expected);
1661        assert_eq!(&a / &b, expected);
1662    }
1663
1664    #[test]
1665    fn decimal256_div_assign_works() {
1666        let mut a = Decimal256::percent(15);
1667        a /= Decimal256::percent(20);
1668        assert_eq!(a, Decimal256::percent(75));
1669
1670        // works for refs
1671        let mut a = Decimal256::percent(50);
1672        let b = Decimal256::percent(20);
1673        a /= &b;
1674        assert_eq!(a, Decimal256::percent(250));
1675    }
1676
1677    #[test]
1678    #[should_panic(expected = "Division failed - multiplication overflow")]
1679    fn decimal256_div_overflow_panics() {
1680        let _value = Decimal256::MAX / Decimal256::percent(10);
1681    }
1682
1683    #[test]
1684    #[should_panic(expected = "Division failed - denominator must not be zero")]
1685    fn decimal256_div_by_zero_panics() {
1686        let _value = Decimal256::one() / Decimal256::zero();
1687    }
1688
1689    #[test]
1690    fn decimal256_uint128_division() {
1691        // a/b
1692        let left = Decimal256::percent(150); // 1.5
1693        let right = Uint256::from(3u128);
1694        assert_eq!(left / right, Decimal256::percent(50));
1695
1696        // 0/a
1697        let left = Decimal256::zero();
1698        let right = Uint256::from(300u128);
1699        assert_eq!(left / right, Decimal256::zero());
1700    }
1701
1702    #[test]
1703    #[should_panic(expected = "attempt to divide by zero")]
1704    fn decimal256_uint128_divide_by_zero() {
1705        let left = Decimal256::percent(150); // 1.5
1706        let right = Uint256::from(0u128);
1707        let _result = left / right;
1708    }
1709
1710    #[test]
1711    fn decimal256_uint128_div_assign() {
1712        // a/b
1713        let mut dec = Decimal256::percent(150); // 1.5
1714        dec /= Uint256::from(3u128);
1715        assert_eq!(dec, Decimal256::percent(50));
1716
1717        // 0/a
1718        let mut dec = Decimal256::zero();
1719        dec /= Uint256::from(300u128);
1720        assert_eq!(dec, Decimal256::zero());
1721    }
1722
1723    #[test]
1724    #[should_panic(expected = "attempt to divide by zero")]
1725    fn decimal256_uint128_div_assign_by_zero() {
1726        // a/0
1727        let mut dec = Decimal256::percent(50);
1728        dec /= Uint256::from(0u128);
1729    }
1730
1731    #[test]
1732    fn decimal256_uint128_sqrt() {
1733        assert_eq!(Decimal256::percent(900).sqrt(), Decimal256::percent(300));
1734
1735        assert!(Decimal256::percent(316) < Decimal256::percent(1000).sqrt());
1736        assert!(Decimal256::percent(1000).sqrt() < Decimal256::percent(317));
1737    }
1738
1739    /// sqrt(2) is an irrational number, i.e. all 36 decimal places should be used.
1740    #[test]
1741    fn decimal256_uint128_sqrt_is_precise() {
1742        assert_eq!(
1743            Decimal256::from_str("2").unwrap().sqrt(),
1744            Decimal256::from_str("1.414213562373095048").unwrap() // https://www.wolframalpha.com/input/?i=sqrt%282%29
1745        );
1746    }
1747
1748    #[test]
1749    fn decimal256_uint128_sqrt_does_not_overflow() {
1750        assert_eq!(
1751            Decimal256::from_str("40000000000000000000000000000000000000000000000000000000000")
1752                .unwrap()
1753                .sqrt(),
1754            Decimal256::from_str("200000000000000000000000000000").unwrap()
1755        );
1756    }
1757
1758    #[test]
1759    fn decimal256_uint128_sqrt_intermediate_precision_used() {
1760        assert_eq!(
1761            Decimal256::from_str("40000000000000000000000000000000000000000000000001")
1762                .unwrap()
1763                .sqrt(),
1764            // The last few digits (39110) are truncated below due to the algorithm
1765            // we use. Larger numbers will cause less precision.
1766            // https://www.wolframalpha.com/input/?i=sqrt%2840000000000000000000000000000000000000000000000001%29
1767            Decimal256::from_str("6324555320336758663997787.088865437067400000").unwrap()
1768        );
1769    }
1770
1771    #[test]
1772    fn decimal256_checked_pow() {
1773        for exp in 0..10 {
1774            assert_eq!(
1775                Decimal256::one().checked_pow(exp).unwrap(),
1776                Decimal256::one()
1777            );
1778        }
1779
1780        // This case is mathematically undefined but we ensure consistency with Rust standard types
1781        // https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=20df6716048e77087acd40194b233494
1782        assert_eq!(
1783            Decimal256::zero().checked_pow(0).unwrap(),
1784            Decimal256::one()
1785        );
1786
1787        for exp in 1..10 {
1788            assert_eq!(
1789                Decimal256::zero().checked_pow(exp).unwrap(),
1790                Decimal256::zero()
1791            );
1792        }
1793
1794        for num in &[
1795            Decimal256::percent(50),
1796            Decimal256::percent(99),
1797            Decimal256::percent(200),
1798        ] {
1799            assert_eq!(num.checked_pow(0).unwrap(), Decimal256::one())
1800        }
1801
1802        assert_eq!(
1803            Decimal256::percent(20).checked_pow(2).unwrap(),
1804            Decimal256::percent(4)
1805        );
1806
1807        assert_eq!(
1808            Decimal256::percent(20).checked_pow(3).unwrap(),
1809            Decimal256::permille(8)
1810        );
1811
1812        assert_eq!(
1813            Decimal256::percent(200).checked_pow(4).unwrap(),
1814            Decimal256::percent(1600)
1815        );
1816
1817        assert_eq!(
1818            Decimal256::percent(200).checked_pow(4).unwrap(),
1819            Decimal256::percent(1600)
1820        );
1821
1822        assert_eq!(
1823            Decimal256::percent(700).checked_pow(5).unwrap(),
1824            Decimal256::percent(1680700)
1825        );
1826
1827        assert_eq!(
1828            Decimal256::percent(700).checked_pow(8).unwrap(),
1829            Decimal256::percent(576480100)
1830        );
1831
1832        assert_eq!(
1833            Decimal256::percent(700).checked_pow(10).unwrap(),
1834            Decimal256::percent(28247524900)
1835        );
1836
1837        assert_eq!(
1838            Decimal256::percent(120).checked_pow(123).unwrap(),
1839            Decimal256(5486473221892422150877397607u128.into())
1840        );
1841
1842        assert_eq!(
1843            Decimal256::percent(10).checked_pow(2).unwrap(),
1844            Decimal256(10000000000000000u128.into())
1845        );
1846
1847        assert_eq!(
1848            Decimal256::percent(10).checked_pow(18).unwrap(),
1849            Decimal256(1u128.into())
1850        );
1851    }
1852
1853    #[test]
1854    fn decimal256_checked_pow_overflow() {
1855        assert_eq!(
1856            Decimal256::MAX.checked_pow(2),
1857            Err(OverflowError::new(OverflowOperation::Pow))
1858        );
1859    }
1860
1861    #[test]
1862    fn decimal256_to_string() {
1863        // Integers
1864        assert_eq!(Decimal256::zero().to_string(), "0");
1865        assert_eq!(Decimal256::one().to_string(), "1");
1866        assert_eq!(Decimal256::percent(500).to_string(), "5");
1867
1868        // Decimals
1869        assert_eq!(Decimal256::percent(125).to_string(), "1.25");
1870        assert_eq!(Decimal256::percent(42638).to_string(), "426.38");
1871        assert_eq!(Decimal256::percent(3).to_string(), "0.03");
1872        assert_eq!(Decimal256::permille(987).to_string(), "0.987");
1873
1874        assert_eq!(
1875            Decimal256(Uint256::from(1u128)).to_string(),
1876            "0.000000000000000001"
1877        );
1878        assert_eq!(
1879            Decimal256(Uint256::from(10u128)).to_string(),
1880            "0.00000000000000001"
1881        );
1882        assert_eq!(
1883            Decimal256(Uint256::from(100u128)).to_string(),
1884            "0.0000000000000001"
1885        );
1886        assert_eq!(
1887            Decimal256(Uint256::from(1000u128)).to_string(),
1888            "0.000000000000001"
1889        );
1890        assert_eq!(
1891            Decimal256(Uint256::from(10000u128)).to_string(),
1892            "0.00000000000001"
1893        );
1894        assert_eq!(
1895            Decimal256(Uint256::from(100000u128)).to_string(),
1896            "0.0000000000001"
1897        );
1898        assert_eq!(
1899            Decimal256(Uint256::from(1000000u128)).to_string(),
1900            "0.000000000001"
1901        );
1902        assert_eq!(
1903            Decimal256(Uint256::from(10000000u128)).to_string(),
1904            "0.00000000001"
1905        );
1906        assert_eq!(
1907            Decimal256(Uint256::from(100000000u128)).to_string(),
1908            "0.0000000001"
1909        );
1910        assert_eq!(
1911            Decimal256(Uint256::from(1000000000u128)).to_string(),
1912            "0.000000001"
1913        );
1914        assert_eq!(
1915            Decimal256(Uint256::from(10000000000u128)).to_string(),
1916            "0.00000001"
1917        );
1918        assert_eq!(
1919            Decimal256(Uint256::from(100000000000u128)).to_string(),
1920            "0.0000001"
1921        );
1922        assert_eq!(
1923            Decimal256(Uint256::from(10000000000000u128)).to_string(),
1924            "0.00001"
1925        );
1926        assert_eq!(
1927            Decimal256(Uint256::from(100000000000000u128)).to_string(),
1928            "0.0001"
1929        );
1930        assert_eq!(
1931            Decimal256(Uint256::from(1000000000000000u128)).to_string(),
1932            "0.001"
1933        );
1934        assert_eq!(
1935            Decimal256(Uint256::from(10000000000000000u128)).to_string(),
1936            "0.01"
1937        );
1938        assert_eq!(
1939            Decimal256(Uint256::from(100000000000000000u128)).to_string(),
1940            "0.1"
1941        );
1942    }
1943
1944    #[test]
1945    fn decimal256_iter_sum() {
1946        let items = vec![
1947            Decimal256::zero(),
1948            Decimal256::from_str("2").unwrap(),
1949            Decimal256::from_str("2").unwrap(),
1950        ];
1951        assert_eq!(
1952            items.iter().sum::<Decimal256>(),
1953            Decimal256::from_str("4").unwrap()
1954        );
1955        assert_eq!(
1956            items.into_iter().sum::<Decimal256>(),
1957            Decimal256::from_str("4").unwrap()
1958        );
1959
1960        let empty: Vec<Decimal256> = vec![];
1961        assert_eq!(Decimal256::zero(), empty.iter().sum::<Decimal256>());
1962    }
1963
1964    #[test]
1965    fn decimal256_serialize() {
1966        assert_eq!(serde_json::to_vec(&Decimal256::zero()).unwrap(), br#""0""#);
1967        assert_eq!(serde_json::to_vec(&Decimal256::one()).unwrap(), br#""1""#);
1968        assert_eq!(
1969            serde_json::to_vec(&Decimal256::percent(8)).unwrap(),
1970            br#""0.08""#
1971        );
1972        assert_eq!(
1973            serde_json::to_vec(&Decimal256::percent(87)).unwrap(),
1974            br#""0.87""#
1975        );
1976        assert_eq!(
1977            serde_json::to_vec(&Decimal256::percent(876)).unwrap(),
1978            br#""8.76""#
1979        );
1980        assert_eq!(
1981            serde_json::to_vec(&Decimal256::percent(8765)).unwrap(),
1982            br#""87.65""#
1983        );
1984    }
1985
1986    #[test]
1987    fn decimal256_deserialize() {
1988        assert_eq!(
1989            serde_json::from_slice::<Decimal256>(br#""0""#).unwrap(),
1990            Decimal256::zero()
1991        );
1992        assert_eq!(
1993            serde_json::from_slice::<Decimal256>(br#""1""#).unwrap(),
1994            Decimal256::one()
1995        );
1996        assert_eq!(
1997            serde_json::from_slice::<Decimal256>(br#""000""#).unwrap(),
1998            Decimal256::zero()
1999        );
2000        assert_eq!(
2001            serde_json::from_slice::<Decimal256>(br#""001""#).unwrap(),
2002            Decimal256::one()
2003        );
2004
2005        assert_eq!(
2006            serde_json::from_slice::<Decimal256>(br#""0.08""#).unwrap(),
2007            Decimal256::percent(8)
2008        );
2009        assert_eq!(
2010            serde_json::from_slice::<Decimal256>(br#""0.87""#).unwrap(),
2011            Decimal256::percent(87)
2012        );
2013        assert_eq!(
2014            serde_json::from_slice::<Decimal256>(br#""8.76""#).unwrap(),
2015            Decimal256::percent(876)
2016        );
2017        assert_eq!(
2018            serde_json::from_slice::<Decimal256>(br#""87.65""#).unwrap(),
2019            Decimal256::percent(8765)
2020        );
2021    }
2022
2023    #[test]
2024    fn decimal256_abs_diff_works() {
2025        let a = Decimal256::percent(285);
2026        let b = Decimal256::percent(200);
2027        let expected = Decimal256::percent(85);
2028        assert_eq!(a.abs_diff(b), expected);
2029        assert_eq!(b.abs_diff(a), expected);
2030    }
2031
2032    #[test]
2033    #[allow(clippy::op_ref)]
2034    fn decimal256_rem_works() {
2035        // 4.02 % 1.11 = 0.69
2036        assert_eq!(
2037            Decimal256::percent(402) % Decimal256::percent(111),
2038            Decimal256::percent(69)
2039        );
2040
2041        // 15.25 % 4 = 3.25
2042        assert_eq!(
2043            Decimal256::percent(1525) % Decimal256::percent(400),
2044            Decimal256::percent(325)
2045        );
2046
2047        let a = Decimal256::percent(318);
2048        let b = Decimal256::percent(317);
2049        let expected = Decimal256::percent(1);
2050        assert_eq!(a % b, expected);
2051        assert_eq!(a % &b, expected);
2052        assert_eq!(&a % b, expected);
2053        assert_eq!(&a % &b, expected);
2054    }
2055
2056    #[test]
2057    fn decimal_rem_assign_works() {
2058        let mut a = Decimal256::percent(17673);
2059        a %= Decimal256::percent(2362);
2060        assert_eq!(a, Decimal256::percent(1139)); // 176.73 % 23.62 = 11.39
2061
2062        let mut a = Decimal256::percent(4262);
2063        let b = Decimal256::percent(1270);
2064        a %= &b;
2065        assert_eq!(a, Decimal256::percent(452)); // 42.62 % 12.7 = 4.52
2066    }
2067
2068    #[test]
2069    #[should_panic(expected = "divisor of zero")]
2070    fn decimal256_rem_panics_for_zero() {
2071        let _ = Decimal256::percent(777) % Decimal256::zero();
2072    }
2073
2074    #[test]
2075    fn decimal256_checked_methods() {
2076        // checked add
2077        assert_eq!(
2078            Decimal256::percent(402)
2079                .checked_add(Decimal256::percent(111))
2080                .unwrap(),
2081            Decimal256::percent(513)
2082        );
2083        assert!(matches!(
2084            Decimal256::MAX.checked_add(Decimal256::percent(1)),
2085            Err(OverflowError { .. })
2086        ));
2087
2088        // checked sub
2089        assert_eq!(
2090            Decimal256::percent(1111)
2091                .checked_sub(Decimal256::percent(111))
2092                .unwrap(),
2093            Decimal256::percent(1000)
2094        );
2095        assert!(matches!(
2096            Decimal256::zero().checked_sub(Decimal256::percent(1)),
2097            Err(OverflowError { .. })
2098        ));
2099
2100        // checked div
2101        assert_eq!(
2102            Decimal256::percent(30)
2103                .checked_div(Decimal256::percent(200))
2104                .unwrap(),
2105            Decimal256::percent(15)
2106        );
2107        assert_eq!(
2108            Decimal256::percent(88)
2109                .checked_div(Decimal256::percent(20))
2110                .unwrap(),
2111            Decimal256::percent(440)
2112        );
2113        assert!(matches!(
2114            Decimal256::MAX.checked_div(Decimal256::zero()),
2115            Err(CheckedFromRatioError::DivideByZero)
2116        ));
2117        assert!(matches!(
2118            Decimal256::MAX.checked_div(Decimal256::percent(1)),
2119            Err(CheckedFromRatioError::Overflow)
2120        ));
2121
2122        // checked rem
2123        assert_eq!(
2124            Decimal256::percent(402)
2125                .checked_rem(Decimal256::percent(111))
2126                .unwrap(),
2127            Decimal256::percent(69)
2128        );
2129        assert_eq!(
2130            Decimal256::percent(1525)
2131                .checked_rem(Decimal256::percent(400))
2132                .unwrap(),
2133            Decimal256::percent(325)
2134        );
2135        assert!(matches!(
2136            Decimal256::MAX.checked_rem(Decimal256::zero()),
2137            Err(DivideByZeroError { .. })
2138        ));
2139    }
2140
2141    #[test]
2142    fn decimal256_pow_works() {
2143        assert_eq!(Decimal256::percent(200).pow(2), Decimal256::percent(400));
2144        assert_eq!(
2145            Decimal256::percent(200).pow(10),
2146            Decimal256::percent(102400)
2147        );
2148    }
2149
2150    #[test]
2151    #[should_panic]
2152    fn decimal256_pow_overflow_panics() {
2153        _ = Decimal256::MAX.pow(2u32);
2154    }
2155
2156    #[test]
2157    fn decimal256_saturating_works() {
2158        assert_eq!(
2159            Decimal256::percent(200).saturating_add(Decimal256::percent(200)),
2160            Decimal256::percent(400)
2161        );
2162        assert_eq!(
2163            Decimal256::MAX.saturating_add(Decimal256::percent(200)),
2164            Decimal256::MAX
2165        );
2166        assert_eq!(
2167            Decimal256::percent(200).saturating_sub(Decimal256::percent(100)),
2168            Decimal256::percent(100)
2169        );
2170        assert_eq!(
2171            Decimal256::zero().saturating_sub(Decimal256::percent(200)),
2172            Decimal256::zero()
2173        );
2174        assert_eq!(
2175            Decimal256::percent(200).saturating_mul(Decimal256::percent(50)),
2176            Decimal256::percent(100)
2177        );
2178        assert_eq!(
2179            Decimal256::MAX.saturating_mul(Decimal256::percent(200)),
2180            Decimal256::MAX
2181        );
2182        assert_eq!(
2183            Decimal256::percent(400).saturating_pow(2u32),
2184            Decimal256::percent(1600)
2185        );
2186        assert_eq!(Decimal256::MAX.saturating_pow(2u32), Decimal256::MAX);
2187    }
2188
2189    #[test]
2190    fn decimal256_rounding() {
2191        assert_eq!(Decimal256::one().floor(), Decimal256::one());
2192        assert_eq!(Decimal256::percent(150).floor(), Decimal256::one());
2193        assert_eq!(Decimal256::percent(199).floor(), Decimal256::one());
2194        assert_eq!(Decimal256::percent(200).floor(), Decimal256::percent(200));
2195        assert_eq!(Decimal256::percent(99).floor(), Decimal256::zero());
2196
2197        assert_eq!(Decimal256::one().ceil(), Decimal256::one());
2198        assert_eq!(Decimal256::percent(150).ceil(), Decimal256::percent(200));
2199        assert_eq!(Decimal256::percent(199).ceil(), Decimal256::percent(200));
2200        assert_eq!(Decimal256::percent(99).ceil(), Decimal256::one());
2201        assert_eq!(Decimal256(Uint256::from(1u128)).ceil(), Decimal256::one());
2202    }
2203
2204    #[test]
2205    #[should_panic(expected = "attempt to ceil with overflow")]
2206    fn decimal256_ceil_panics() {
2207        let _ = Decimal256::MAX.ceil();
2208    }
2209
2210    #[test]
2211    fn decimal256_checked_ceil() {
2212        assert_eq!(
2213            Decimal256::percent(199).checked_ceil(),
2214            Ok(Decimal256::percent(200))
2215        );
2216        assert_eq!(Decimal256::MAX.checked_ceil(), Err(RoundUpOverflowError));
2217    }
2218
2219    #[test]
2220    fn decimal256_to_uint_floor_works() {
2221        let d = Decimal256::from_str("12.000000000000000001").unwrap();
2222        assert_eq!(d.to_uint_floor(), Uint256::from_u128(12));
2223        let d = Decimal256::from_str("12.345").unwrap();
2224        assert_eq!(d.to_uint_floor(), Uint256::from_u128(12));
2225        let d = Decimal256::from_str("12.999").unwrap();
2226        assert_eq!(d.to_uint_floor(), Uint256::from_u128(12));
2227        let d = Decimal256::from_str("0.98451384").unwrap();
2228        assert_eq!(d.to_uint_floor(), Uint256::from_u128(0));
2229
2230        let d = Decimal256::from_str("75.0").unwrap();
2231        assert_eq!(d.to_uint_floor(), Uint256::from_u128(75));
2232        let d = Decimal256::from_str("0.0").unwrap();
2233        assert_eq!(d.to_uint_floor(), Uint256::from_u128(0));
2234
2235        let d = Decimal256::MAX;
2236        assert_eq!(
2237            d.to_uint_floor(),
2238            Uint256::from_str("115792089237316195423570985008687907853269984665640564039457")
2239                .unwrap()
2240        );
2241
2242        // Does the same as the old workaround `Uint256::one() * my_decimal`.
2243        // This block can be deleted as part of https://github.com/CosmWasm/cosmwasm/issues/1485.
2244        let tests = vec![
2245            (
2246                Decimal256::from_str("12.345").unwrap(),
2247                Uint256::from(12u128),
2248            ),
2249            (
2250                Decimal256::from_str("0.98451384").unwrap(),
2251                Uint256::from(0u128),
2252            ),
2253            (
2254                Decimal256::from_str("178.0").unwrap(),
2255                Uint256::from(178u128),
2256            ),
2257            (Decimal256::MIN, Uint256::from(0u128)),
2258            (
2259                Decimal256::MAX,
2260                Uint256::MAX / Decimal256::DECIMAL_FRACTIONAL,
2261            ),
2262        ];
2263        for (my_decimal, expected) in tests.into_iter() {
2264            assert_eq!(my_decimal.to_uint_floor(), expected);
2265        }
2266    }
2267
2268    #[test]
2269    fn decimal256_to_uint_ceil_works() {
2270        let d = Decimal256::from_str("12.000000000000000001").unwrap();
2271        assert_eq!(d.to_uint_ceil(), Uint256::from_u128(13));
2272        let d = Decimal256::from_str("12.345").unwrap();
2273        assert_eq!(d.to_uint_ceil(), Uint256::from_u128(13));
2274        let d = Decimal256::from_str("12.999").unwrap();
2275        assert_eq!(d.to_uint_ceil(), Uint256::from_u128(13));
2276
2277        let d = Decimal256::from_str("75.0").unwrap();
2278        assert_eq!(d.to_uint_ceil(), Uint256::from_u128(75));
2279        let d = Decimal256::from_str("0.0").unwrap();
2280        assert_eq!(d.to_uint_ceil(), Uint256::from_u128(0));
2281
2282        let d = Decimal256::MAX;
2283        assert_eq!(
2284            d.to_uint_ceil(),
2285            Uint256::from_str("115792089237316195423570985008687907853269984665640564039458")
2286                .unwrap()
2287        );
2288    }
2289
2290    #[test]
2291    fn decimal256_partial_eq() {
2292        let test_cases = [
2293            ("1", "1", true),
2294            ("0.5", "0.5", true),
2295            ("0.5", "0.51", false),
2296            ("0", "0.00000", true),
2297        ]
2298        .into_iter()
2299        .map(|(lhs, rhs, expected)| (dec(lhs), dec(rhs), expected));
2300
2301        #[allow(clippy::op_ref)]
2302        for (lhs, rhs, expected) in test_cases {
2303            assert_eq!(lhs == rhs, expected);
2304            assert_eq!(&lhs == rhs, expected);
2305            assert_eq!(lhs == &rhs, expected);
2306            assert_eq!(&lhs == &rhs, expected);
2307        }
2308    }
2309
2310    #[test]
2311    fn decimal256_implements_debug() {
2312        let decimal = Decimal256::from_str("123.45").unwrap();
2313        assert_eq!(format!("{decimal:?}"), "Decimal256(123.45)");
2314
2315        let test_cases = ["5", "5.01", "42", "0", "2"];
2316        for s in test_cases {
2317            let decimal256 = Decimal256::from_str(s).unwrap();
2318            let expected = format!("Decimal256({s})");
2319            assert_eq!(format!("{decimal256:?}"), expected);
2320        }
2321    }
2322}