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