cosmwasm_std/math/
signed_decimal.rs

1use alloc::string::ToString;
2use core::cmp::Ordering;
3use core::fmt::{self, Write};
4use core::ops::{
5    Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Rem, RemAssign, Sub, SubAssign,
6};
7use core::str::FromStr;
8use serde::{de, ser, Deserialize, Deserializer, Serialize};
9
10use crate::errors::{
11    CheckedFromRatioError, CheckedMultiplyRatioError, DivideByZeroError, ErrorKind, OverflowError,
12    OverflowOperation, RoundDownOverflowError, RoundUpOverflowError, StdError,
13};
14use crate::forward_ref::{forward_ref_binop, forward_ref_op_assign};
15use crate::{Decimal, Decimal256, Int256, SignedDecimal256, __internal::forward_ref_partial_eq};
16
17use super::Fraction;
18use super::Int128;
19
20/// A signed fixed-point decimal value with 18 fractional digits, i.e. SignedDecimal(1_000_000_000_000_000_000) == 1.0
21///
22/// The greatest possible value that can be represented is 170141183460469231731.687303715884105727 (which is (2^127 - 1) / 10^18)
23/// and the smallest is -170141183460469231731.687303715884105728 (which is -2^127 / 10^18).
24#[derive(
25    Copy,
26    Clone,
27    Default,
28    PartialEq,
29    Eq,
30    PartialOrd,
31    Ord,
32    schemars::JsonSchema,
33    cw_schema::Schemaifier,
34)]
35#[schemaifier(type = cw_schema::NodeType::Decimal { precision: 128, signed: true })]
36pub struct SignedDecimal(#[schemars(with = "String")] Int128);
37
38forward_ref_partial_eq!(SignedDecimal, SignedDecimal);
39
40#[derive(Debug, PartialEq, Eq, thiserror::Error)]
41#[error("SignedDecimal range exceeded")]
42pub struct SignedDecimalRangeExceeded;
43
44impl SignedDecimal {
45    const DECIMAL_FRACTIONAL: Int128 = Int128::new(1_000_000_000_000_000_000i128); // 1*10**18
46    const DECIMAL_FRACTIONAL_SQUARED: Int128 =
47        Int128::new(1_000_000_000_000_000_000_000_000_000_000_000_000i128); // (1*10**18)**2 = 1*10**36
48
49    /// The number of decimal places. Since decimal types are fixed-point rather than
50    /// floating-point, this is a constant.
51    pub const DECIMAL_PLACES: u32 = 18; // This needs to be an even number.
52
53    /// The largest value that can be represented by this signed decimal type.
54    ///
55    /// # Examples
56    ///
57    /// ```
58    /// # use cosmwasm_std::SignedDecimal;
59    /// assert_eq!(SignedDecimal::MAX.to_string(), "170141183460469231731.687303715884105727");
60    /// ```
61    pub const MAX: Self = Self(Int128::MAX);
62
63    /// The smallest value that can be represented by this signed decimal type.
64    ///
65    /// # Examples
66    ///
67    /// ```
68    /// # use cosmwasm_std::SignedDecimal;
69    /// assert_eq!(SignedDecimal::MIN.to_string(), "-170141183460469231731.687303715884105728");
70    /// ```
71    pub const MIN: Self = Self(Int128::MIN);
72
73    /// Creates a SignedDecimal(value)
74    /// This is equivalent to `SignedDecimal::from_atomics(value, 18)` but usable in a const context.
75    ///
76    /// # Examples
77    ///
78    /// ```
79    /// # use cosmwasm_std::{SignedDecimal, Int128};
80    /// assert_eq!(SignedDecimal::new(Int128::one()).to_string(), "0.000000000000000001");
81    ///
82    /// let atoms = Int128::new(-141_183_460_469_231_731_687_303_715_884_105_727_125);
83    /// let value = SignedDecimal::new(atoms);
84    /// assert_eq!(value.to_string(), "-141183460469231731687.303715884105727125");
85    /// ```
86    #[inline]
87    #[must_use]
88    pub const fn new(value: Int128) -> Self {
89        Self(value)
90    }
91
92    /// Creates a SignedDecimal(Int128(value))
93    /// This is equivalent to `SignedDecimal::from_atomics(value, 18)` but usable in a const context.
94    ///
95    /// # Examples
96    ///
97    /// ```
98    /// # use cosmwasm_std::SignedDecimal;
99    /// assert_eq!(SignedDecimal::raw(1234i128).to_string(), "0.000000000000001234");
100    /// ```
101    #[deprecated(
102        since = "3.0.0",
103        note = "Use SignedDecimal::new(Int128::new(value)) instead"
104    )]
105    pub const fn raw(value: i128) -> Self {
106        Self(Int128::new(value))
107    }
108
109    /// Create a 1.0 SignedDecimal
110    #[inline]
111    pub const fn one() -> Self {
112        Self(Self::DECIMAL_FRACTIONAL)
113    }
114
115    /// Create a -1.0 SignedDecimal
116    #[inline]
117    pub const fn negative_one() -> Self {
118        Self(Int128::new(-Self::DECIMAL_FRACTIONAL.i128()))
119    }
120
121    /// Create a 0.0 SignedDecimal
122    #[inline]
123    pub const fn zero() -> Self {
124        Self(Int128::zero())
125    }
126
127    /// Convert x% into SignedDecimal
128    pub fn percent(x: i64) -> Self {
129        Self(((x as i128) * 10_000_000_000_000_000).into())
130    }
131
132    /// Convert permille (x/1000) into SignedDecimal
133    pub fn permille(x: i64) -> Self {
134        Self(((x as i128) * 1_000_000_000_000_000).into())
135    }
136
137    /// Convert basis points (x/10000) into SignedDecimal
138    pub fn bps(x: i64) -> Self {
139        Self(((x as i128) * 100_000_000_000_000).into())
140    }
141
142    /// Creates a signed decimal from a number of atomic units and the number
143    /// of decimal places. The inputs will be converted internally to form
144    /// a signed decimal with 18 decimal places. So the input 123 and 2 will create
145    /// the decimal 1.23.
146    ///
147    /// Using 18 decimal places is slightly more efficient than other values
148    /// as no internal conversion is necessary.
149    ///
150    /// ## Examples
151    ///
152    /// ```
153    /// # use cosmwasm_std::{SignedDecimal, Int128};
154    /// let a = SignedDecimal::from_atomics(Int128::new(1234), 3).unwrap();
155    /// assert_eq!(a.to_string(), "1.234");
156    ///
157    /// let a = SignedDecimal::from_atomics(1234i128, 0).unwrap();
158    /// assert_eq!(a.to_string(), "1234");
159    ///
160    /// let a = SignedDecimal::from_atomics(1i64, 18).unwrap();
161    /// assert_eq!(a.to_string(), "0.000000000000000001");
162    ///
163    /// let a = SignedDecimal::from_atomics(-1i64, 18).unwrap();
164    /// assert_eq!(a.to_string(), "-0.000000000000000001");
165    /// ```
166    pub fn from_atomics(
167        atomics: impl Into<Int128>,
168        decimal_places: u32,
169    ) -> Result<Self, SignedDecimalRangeExceeded> {
170        let atomics = atomics.into();
171        const TEN: Int128 = Int128::new(10);
172        Ok(match decimal_places.cmp(&(Self::DECIMAL_PLACES)) {
173            Ordering::Less => {
174                let digits = (Self::DECIMAL_PLACES) - decimal_places; // No overflow because decimal_places < DECIMAL_PLACES
175                let factor = TEN.checked_pow(digits).unwrap(); // Safe because digits <= 17
176                Self(
177                    atomics
178                        .checked_mul(factor)
179                        .map_err(|_| SignedDecimalRangeExceeded)?,
180                )
181            }
182            Ordering::Equal => Self(atomics),
183            Ordering::Greater => {
184                let digits = decimal_places - (Self::DECIMAL_PLACES); // No overflow because decimal_places > DECIMAL_PLACES
185                if let Ok(factor) = TEN.checked_pow(digits) {
186                    Self(atomics.checked_div(factor).unwrap()) // Safe because factor cannot be zero
187                } else {
188                    // In this case `factor` exceeds the Int128 range.
189                    // Any Int128 `x` divided by `factor` with `factor > Int128::MAX` is 0.
190                    // Try e.g. Python3: `(2**128-1) // 2**128`
191                    Self(Int128::zero())
192                }
193            }
194        })
195    }
196
197    /// Returns the ratio (numerator / denominator) as a SignedDecimal
198    ///
199    /// # Examples
200    ///
201    /// ```
202    /// # use cosmwasm_std::SignedDecimal;
203    /// assert_eq!(
204    ///     SignedDecimal::from_ratio(1, 3).to_string(),
205    ///     "0.333333333333333333"
206    /// );
207    /// ```
208    pub fn from_ratio(numerator: impl Into<Int128>, denominator: impl Into<Int128>) -> Self {
209        match SignedDecimal::checked_from_ratio(numerator, denominator) {
210            Ok(value) => value,
211            Err(CheckedFromRatioError::DivideByZero) => {
212                panic!("Denominator must not be zero")
213            }
214            Err(CheckedFromRatioError::Overflow) => panic!("Multiplication overflow"),
215        }
216    }
217
218    /// Returns the ratio (numerator / denominator) as a SignedDecimal
219    ///
220    /// # Examples
221    ///
222    /// ```
223    /// # use cosmwasm_std::{SignedDecimal, CheckedFromRatioError};
224    /// assert_eq!(
225    ///     SignedDecimal::checked_from_ratio(1, 3).unwrap().to_string(),
226    ///     "0.333333333333333333"
227    /// );
228    /// assert_eq!(
229    ///     SignedDecimal::checked_from_ratio(1, 0),
230    ///     Err(CheckedFromRatioError::DivideByZero)
231    /// );
232    /// ```
233    pub fn checked_from_ratio(
234        numerator: impl Into<Int128>,
235        denominator: impl Into<Int128>,
236    ) -> Result<Self, CheckedFromRatioError> {
237        let numerator: Int128 = numerator.into();
238        let denominator: Int128 = denominator.into();
239        match numerator.checked_multiply_ratio(Self::DECIMAL_FRACTIONAL, denominator) {
240            Ok(ratio) => {
241                // numerator * DECIMAL_FRACTIONAL / denominator
242                Ok(SignedDecimal(ratio))
243            }
244            Err(CheckedMultiplyRatioError::Overflow) => Err(CheckedFromRatioError::Overflow),
245            Err(CheckedMultiplyRatioError::DivideByZero) => {
246                Err(CheckedFromRatioError::DivideByZero)
247            }
248        }
249    }
250
251    /// Returns `true` if the number is 0
252    #[must_use]
253    pub const fn is_zero(&self) -> bool {
254        self.0.is_zero()
255    }
256
257    /// Returns `true` if the number is negative (< 0)
258    #[must_use]
259    pub const fn is_negative(&self) -> bool {
260        self.0.i128() < 0
261    }
262
263    /// A decimal is an integer of atomic units plus a number that specifies the
264    /// position of the decimal dot. So any decimal can be expressed as two numbers.
265    ///
266    /// ## Examples
267    ///
268    /// ```
269    /// # use cosmwasm_std::{SignedDecimal, Int128};
270    /// # use core::str::FromStr;
271    /// // Value with whole and fractional part
272    /// let a = SignedDecimal::from_str("1.234").unwrap();
273    /// assert_eq!(a.decimal_places(), 18);
274    /// assert_eq!(a.atomics(), Int128::new(1234000000000000000));
275    ///
276    /// // Smallest possible value
277    /// let b = SignedDecimal::from_str("0.000000000000000001").unwrap();
278    /// assert_eq!(b.decimal_places(), 18);
279    /// assert_eq!(b.atomics(), Int128::new(1));
280    /// ```
281    #[must_use]
282    #[inline]
283    pub const fn atomics(&self) -> Int128 {
284        self.0
285    }
286
287    /// The number of decimal places. This is a constant value for now
288    /// but this could potentially change as the type evolves.
289    ///
290    /// See also [`SignedDecimal::atomics()`].
291    #[must_use]
292    #[inline]
293    pub const fn decimal_places(&self) -> u32 {
294        Self::DECIMAL_PLACES
295    }
296
297    /// Rounds value by truncating the decimal places.
298    ///
299    /// # Examples
300    ///
301    /// ```
302    /// # use cosmwasm_std::SignedDecimal;
303    /// # use core::str::FromStr;
304    /// assert!(SignedDecimal::from_str("0.6").unwrap().trunc().is_zero());
305    /// assert_eq!(SignedDecimal::from_str("-5.8").unwrap().trunc().to_string(), "-5");
306    /// ```
307    #[must_use = "this returns the result of the operation, without modifying the original"]
308    pub fn trunc(&self) -> Self {
309        Self((self.0 / Self::DECIMAL_FRACTIONAL) * Self::DECIMAL_FRACTIONAL)
310    }
311
312    /// Rounds value down after decimal places. Panics on overflow.
313    ///
314    /// # Examples
315    ///
316    /// ```
317    /// # use cosmwasm_std::SignedDecimal;
318    /// # use core::str::FromStr;
319    /// assert!(SignedDecimal::from_str("0.6").unwrap().floor().is_zero());
320    /// assert_eq!(SignedDecimal::from_str("-5.2").unwrap().floor().to_string(), "-6");
321    /// ```
322    #[must_use = "this returns the result of the operation, without modifying the original"]
323    pub fn floor(&self) -> Self {
324        match self.checked_floor() {
325            Ok(value) => value,
326            Err(_) => panic!("attempt to floor with overflow"),
327        }
328    }
329
330    /// Rounds value down after decimal places.
331    pub fn checked_floor(&self) -> Result<Self, RoundDownOverflowError> {
332        if self.is_negative() {
333            let truncated = self.trunc();
334
335            if truncated != self {
336                truncated
337                    .checked_sub(SignedDecimal::one())
338                    .map_err(|_| RoundDownOverflowError)
339            } else {
340                Ok(truncated)
341            }
342        } else {
343            Ok(self.trunc())
344        }
345    }
346
347    /// Rounds value up after decimal places. Panics on overflow.
348    ///
349    /// # Examples
350    ///
351    /// ```
352    /// # use cosmwasm_std::SignedDecimal;
353    /// # use core::str::FromStr;
354    /// assert_eq!(SignedDecimal::from_str("0.2").unwrap().ceil(), SignedDecimal::one());
355    /// assert_eq!(SignedDecimal::from_str("-5.8").unwrap().ceil().to_string(), "-5");
356    /// ```
357    #[must_use = "this returns the result of the operation, without modifying the original"]
358    pub fn ceil(&self) -> Self {
359        match self.checked_ceil() {
360            Ok(value) => value,
361            Err(_) => panic!("attempt to ceil with overflow"),
362        }
363    }
364
365    /// Rounds value up after decimal places. Returns OverflowError on overflow.
366    pub fn checked_ceil(&self) -> Result<Self, RoundUpOverflowError> {
367        let floor = self.floor();
368        if floor == self {
369            Ok(floor)
370        } else {
371            floor
372                .checked_add(SignedDecimal::one())
373                .map_err(|_| RoundUpOverflowError)
374        }
375    }
376
377    /// Computes `self + other`, returning an `OverflowError` if an overflow occurred.
378    pub fn checked_add(self, other: Self) -> Result<Self, OverflowError> {
379        self.0
380            .checked_add(other.0)
381            .map(Self)
382            .map_err(|_| OverflowError::new(OverflowOperation::Add))
383    }
384
385    /// Computes `self - other`, returning an `OverflowError` if an overflow occurred.
386    pub fn checked_sub(self, other: Self) -> Result<Self, OverflowError> {
387        self.0
388            .checked_sub(other.0)
389            .map(Self)
390            .map_err(|_| OverflowError::new(OverflowOperation::Sub))
391    }
392
393    /// Multiplies one `SignedDecimal` by another, returning an `OverflowError` if an overflow occurred.
394    pub fn checked_mul(self, other: Self) -> Result<Self, OverflowError> {
395        let result_as_int256 =
396            self.numerator().full_mul(other.numerator()) / Int256::from(Self::DECIMAL_FRACTIONAL);
397        result_as_int256
398            .try_into()
399            .map(Self)
400            .map_err(|_| OverflowError::new(OverflowOperation::Mul))
401    }
402
403    /// Raises a value to the power of `exp`, panics if an overflow occurred.
404    #[must_use = "this returns the result of the operation, without modifying the original"]
405    pub fn pow(self, exp: u32) -> Self {
406        match self.checked_pow(exp) {
407            Ok(value) => value,
408            Err(_) => panic!("Multiplication overflow"),
409        }
410    }
411
412    /// Raises a value to the power of `exp`, returning an `OverflowError` if an overflow occurred.
413    pub fn checked_pow(self, exp: u32) -> Result<Self, OverflowError> {
414        // This uses the exponentiation by squaring algorithm:
415        // https://en.wikipedia.org/wiki/Exponentiation_by_squaring#Basic_method
416
417        fn inner(mut x: SignedDecimal, mut n: u32) -> Result<SignedDecimal, OverflowError> {
418            if n == 0 {
419                return Ok(SignedDecimal::one());
420            }
421
422            let mut y = SignedDecimal::one();
423
424            while n > 1 {
425                if n % 2 == 0 {
426                    x = x.checked_mul(x)?;
427                    n /= 2;
428                } else {
429                    y = x.checked_mul(y)?;
430                    x = x.checked_mul(x)?;
431                    n = (n - 1) / 2;
432                }
433            }
434
435            Ok(x * y)
436        }
437
438        inner(self, exp).map_err(|_| OverflowError::new(OverflowOperation::Pow))
439    }
440
441    pub fn checked_div(self, other: Self) -> Result<Self, CheckedFromRatioError> {
442        SignedDecimal::checked_from_ratio(self.numerator(), other.numerator())
443    }
444
445    /// Computes `self % other`, returning an `DivideByZeroError` if `other == 0`.
446    pub fn checked_rem(self, other: Self) -> Result<Self, DivideByZeroError> {
447        self.0
448            .checked_rem(other.0)
449            .map(Self)
450            .map_err(|_| DivideByZeroError)
451    }
452
453    #[must_use = "this returns the result of the operation, without modifying the original"]
454    pub const fn abs_diff(self, other: Self) -> Decimal {
455        Decimal::new(self.0.abs_diff(other.0))
456    }
457
458    #[must_use = "this returns the result of the operation, without modifying the original"]
459    pub fn saturating_add(self, other: Self) -> Self {
460        Self(self.0.saturating_add(other.0))
461    }
462
463    #[must_use = "this returns the result of the operation, without modifying the original"]
464    pub fn saturating_sub(self, other: Self) -> Self {
465        Self(self.0.saturating_sub(other.0))
466    }
467
468    #[must_use = "this returns the result of the operation, without modifying the original"]
469    pub fn saturating_mul(self, other: Self) -> Self {
470        match self.checked_mul(other) {
471            Ok(value) => value,
472            Err(_) => {
473                // both negative or both positive results in positive number, otherwise negative
474                if self.is_negative() == other.is_negative() {
475                    Self::MAX
476                } else {
477                    Self::MIN
478                }
479            }
480        }
481    }
482
483    #[must_use = "this returns the result of the operation, without modifying the original"]
484    pub fn saturating_pow(self, exp: u32) -> Self {
485        match self.checked_pow(exp) {
486            Ok(value) => value,
487            Err(_) => {
488                // odd exponent of negative number results in negative number
489                // everything else results in positive number
490                if self.is_negative() && exp % 2 == 1 {
491                    Self::MIN
492                } else {
493                    Self::MAX
494                }
495            }
496        }
497    }
498
499    /// Converts this decimal to a signed integer by rounding down
500    /// to the next integer, e.g. 22.5 becomes 22 and -1.2 becomes -2.
501    ///
502    /// ## Examples
503    ///
504    /// ```
505    /// use core::str::FromStr;
506    /// use cosmwasm_std::{SignedDecimal, Int128};
507    ///
508    /// let d = SignedDecimal::from_str("12.345").unwrap();
509    /// assert_eq!(d.to_int_floor(), Int128::new(12));
510    ///
511    /// let d = SignedDecimal::from_str("-12.999").unwrap();
512    /// assert_eq!(d.to_int_floor(), Int128::new(-13));
513    ///
514    /// let d = SignedDecimal::from_str("-0.05").unwrap();
515    /// assert_eq!(d.to_int_floor(), Int128::new(-1));
516    /// ```
517    #[must_use = "this returns the result of the operation, without modifying the original"]
518    pub fn to_int_floor(self) -> Int128 {
519        if self.is_negative() {
520            // Using `x.to_int_floor() = -(-x).to_int_ceil()` for a negative `x`,
521            // but avoiding overflow by implementing the formula from `to_int_ceil` directly.
522            let x = self.0;
523            let y = Self::DECIMAL_FRACTIONAL;
524            // making sure not to negate `x`, as this would overflow
525            -Int128::one() - ((-Int128::one() - x) / y)
526        } else {
527            self.to_int_trunc()
528        }
529    }
530
531    /// Converts this decimal to a signed integer by truncating
532    /// the fractional part, e.g. 22.5 becomes 22.
533    ///
534    /// ## Examples
535    ///
536    /// ```
537    /// use core::str::FromStr;
538    /// use cosmwasm_std::{SignedDecimal, Int128};
539    ///
540    /// let d = SignedDecimal::from_str("12.345").unwrap();
541    /// assert_eq!(d.to_int_trunc(), Int128::new(12));
542    ///
543    /// let d = SignedDecimal::from_str("-12.999").unwrap();
544    /// assert_eq!(d.to_int_trunc(), Int128::new(-12));
545    ///
546    /// let d = SignedDecimal::from_str("75.0").unwrap();
547    /// assert_eq!(d.to_int_trunc(), Int128::new(75));
548    /// ```
549    #[must_use = "this returns the result of the operation, without modifying the original"]
550    pub fn to_int_trunc(self) -> Int128 {
551        self.0 / Self::DECIMAL_FRACTIONAL
552    }
553
554    /// Converts this decimal to a signed integer by rounding up
555    /// to the next integer, e.g. 22.3 becomes 23 and -1.2 becomes -1.
556    ///
557    /// ## Examples
558    ///
559    /// ```
560    /// use core::str::FromStr;
561    /// use cosmwasm_std::{SignedDecimal, Int128};
562    ///
563    /// let d = SignedDecimal::from_str("12.345").unwrap();
564    /// assert_eq!(d.to_int_ceil(), Int128::new(13));
565    ///
566    /// let d = SignedDecimal::from_str("-12.999").unwrap();
567    /// assert_eq!(d.to_int_ceil(), Int128::new(-12));
568    ///
569    /// let d = SignedDecimal::from_str("75.0").unwrap();
570    /// assert_eq!(d.to_int_ceil(), Int128::new(75));
571    /// ```
572    #[must_use = "this returns the result of the operation, without modifying the original"]
573    pub fn to_int_ceil(self) -> Int128 {
574        if self.is_negative() {
575            self.to_int_trunc()
576        } else {
577            // Using `q = 1 + ((x - 1) / y); // if x != 0` with unsigned integers x, y, q
578            // from https://stackoverflow.com/a/2745086/2013738. We know `x + y` CAN overflow.
579            let x = self.0;
580            let y = Self::DECIMAL_FRACTIONAL;
581            if x.is_zero() {
582                Int128::zero()
583            } else {
584                Int128::one() + ((x - Int128::one()) / y)
585            }
586        }
587    }
588}
589
590impl Fraction<Int128> for SignedDecimal {
591    #[inline]
592    fn numerator(&self) -> Int128 {
593        self.0
594    }
595
596    #[inline]
597    fn denominator(&self) -> Int128 {
598        Self::DECIMAL_FRACTIONAL
599    }
600
601    /// Returns the multiplicative inverse `1/d` for decimal `d`.
602    ///
603    /// If `d` is zero, none is returned.
604    fn inv(&self) -> Option<Self> {
605        if self.is_zero() {
606            None
607        } else {
608            // Let self be p/q with p = self.0 and q = DECIMAL_FRACTIONAL.
609            // Now we calculate the inverse a/b = q/p such that b = DECIMAL_FRACTIONAL. Then
610            // `a = DECIMAL_FRACTIONAL*DECIMAL_FRACTIONAL / self.0`.
611            Some(SignedDecimal(Self::DECIMAL_FRACTIONAL_SQUARED / self.0))
612        }
613    }
614}
615
616impl Neg for SignedDecimal {
617    type Output = Self;
618
619    fn neg(self) -> Self::Output {
620        Self(-self.0)
621    }
622}
623
624impl TryFrom<SignedDecimal256> for SignedDecimal {
625    type Error = SignedDecimalRangeExceeded;
626
627    fn try_from(value: SignedDecimal256) -> Result<Self, Self::Error> {
628        value
629            .atomics()
630            .try_into()
631            .map(SignedDecimal)
632            .map_err(|_| SignedDecimalRangeExceeded)
633    }
634}
635
636impl TryFrom<Decimal> for SignedDecimal {
637    type Error = SignedDecimalRangeExceeded;
638
639    fn try_from(value: Decimal) -> Result<Self, Self::Error> {
640        value
641            .atomics()
642            .try_into()
643            .map(SignedDecimal)
644            .map_err(|_| SignedDecimalRangeExceeded)
645    }
646}
647
648impl TryFrom<Decimal256> for SignedDecimal {
649    type Error = SignedDecimalRangeExceeded;
650
651    fn try_from(value: Decimal256) -> Result<Self, Self::Error> {
652        value
653            .atomics()
654            .try_into()
655            .map(SignedDecimal)
656            .map_err(|_| SignedDecimalRangeExceeded)
657    }
658}
659
660impl TryFrom<Int128> for SignedDecimal {
661    type Error = SignedDecimalRangeExceeded;
662
663    #[inline]
664    fn try_from(value: Int128) -> Result<Self, Self::Error> {
665        Self::from_atomics(value, 0)
666    }
667}
668
669impl FromStr for SignedDecimal {
670    type Err = StdError;
671
672    /// Converts the decimal string to a SignedDecimal
673    /// Possible inputs: "1.23", "1", "000012", "1.123000000", "-1.12300"
674    /// Disallowed: "", ".23"
675    ///
676    /// This never performs any kind of rounding.
677    /// More than DECIMAL_PLACES fractional digits, even zeros, result in an error.
678    fn from_str(input: &str) -> Result<Self, Self::Err> {
679        let mut parts_iter = input.split('.');
680
681        let whole_part = parts_iter.next().unwrap(); // split always returns at least one element
682        let is_neg = whole_part.starts_with('-');
683
684        let whole = whole_part.parse::<Int128>()?;
685        let mut atomics = whole.checked_mul(Self::DECIMAL_FRACTIONAL)?;
686
687        if let Some(fractional_part) = parts_iter.next() {
688            let fractional = fractional_part.parse::<u64>()?; // u64 is enough for 18 decimal places
689            let exp = (Self::DECIMAL_PLACES.checked_sub(fractional_part.len() as u32)).ok_or_else(
690                || {
691                    StdError::msg(format_args!(
692                        "Cannot parse more than {} fractional digits",
693                        Self::DECIMAL_PLACES
694                    ))
695                },
696            )?;
697            debug_assert!(exp <= Self::DECIMAL_PLACES);
698            let fractional_factor = Int128::from(10i128.pow(exp));
699
700            // This multiplication can't overflow because
701            // fractional < 10^DECIMAL_PLACES && fractional_factor <= 10^DECIMAL_PLACES
702            let fractional_part = Int128::from(fractional)
703                .checked_mul(fractional_factor)
704                .unwrap();
705
706            // for negative numbers, we need to subtract the fractional part
707            atomics = if is_neg {
708                atomics.checked_sub(fractional_part)
709            } else {
710                atomics.checked_add(fractional_part)
711            }?;
712        }
713
714        if parts_iter.next().is_some() {
715            return Err(StdError::msg("Unexpected number of dots").with_kind(ErrorKind::Parsing));
716        }
717
718        Ok(SignedDecimal(atomics))
719    }
720}
721
722impl fmt::Display for SignedDecimal {
723    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
724        let whole = (self.0) / Self::DECIMAL_FRACTIONAL;
725        let fractional = (self.0).checked_rem(Self::DECIMAL_FRACTIONAL).unwrap();
726
727        if fractional.is_zero() {
728            write!(f, "{whole}")
729        } else {
730            let fractional_string = format!(
731                "{:0>padding$}",
732                fractional.abs(), // fractional should always be printed as positive
733                padding = Self::DECIMAL_PLACES as usize
734            );
735            if self.is_negative() {
736                f.write_char('-')?;
737            }
738            write!(
739                f,
740                "{whole}.{fractional}",
741                whole = whole.abs(),
742                fractional = fractional_string.trim_end_matches('0')
743            )
744        }
745    }
746}
747
748impl fmt::Debug for SignedDecimal {
749    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
750        write!(f, "SignedDecimal({self})")
751    }
752}
753
754impl Add for SignedDecimal {
755    type Output = Self;
756
757    fn add(self, other: Self) -> Self {
758        SignedDecimal(self.0 + other.0)
759    }
760}
761forward_ref_binop!(impl Add, add for SignedDecimal, SignedDecimal);
762
763impl AddAssign for SignedDecimal {
764    fn add_assign(&mut self, rhs: SignedDecimal) {
765        *self = *self + rhs;
766    }
767}
768forward_ref_op_assign!(impl AddAssign, add_assign for SignedDecimal, SignedDecimal);
769
770impl Sub for SignedDecimal {
771    type Output = Self;
772
773    fn sub(self, other: Self) -> Self {
774        SignedDecimal(self.0 - other.0)
775    }
776}
777forward_ref_binop!(impl Sub, sub for SignedDecimal, SignedDecimal);
778
779impl SubAssign for SignedDecimal {
780    fn sub_assign(&mut self, rhs: SignedDecimal) {
781        *self = *self - rhs;
782    }
783}
784forward_ref_op_assign!(impl SubAssign, sub_assign for SignedDecimal, SignedDecimal);
785
786impl Mul for SignedDecimal {
787    type Output = Self;
788
789    #[allow(clippy::suspicious_arithmetic_impl)]
790    fn mul(self, other: Self) -> Self {
791        // SignedDecimals are fractions. We can multiply two decimals a and b
792        // via
793        //       (a.numerator() * b.numerator()) / (a.denominator() * b.denominator())
794        //     = (a.numerator() * b.numerator()) / a.denominator() / b.denominator()
795
796        let result_as_int256 =
797            self.numerator().full_mul(other.numerator()) / Int256::from(Self::DECIMAL_FRACTIONAL);
798        match result_as_int256.try_into() {
799            Ok(result) => Self(result),
800            Err(_) => panic!("attempt to multiply with overflow"),
801        }
802    }
803}
804forward_ref_binop!(impl Mul, mul for SignedDecimal, SignedDecimal);
805
806impl MulAssign for SignedDecimal {
807    fn mul_assign(&mut self, rhs: SignedDecimal) {
808        *self = *self * rhs;
809    }
810}
811forward_ref_op_assign!(impl MulAssign, mul_assign for SignedDecimal, SignedDecimal);
812
813impl Div for SignedDecimal {
814    type Output = Self;
815
816    fn div(self, other: Self) -> Self {
817        match SignedDecimal::checked_from_ratio(self.numerator(), other.numerator()) {
818            Ok(ratio) => ratio,
819            Err(CheckedFromRatioError::DivideByZero) => {
820                panic!("Division failed - denominator must not be zero")
821            }
822            Err(CheckedFromRatioError::Overflow) => {
823                panic!("Division failed - multiplication overflow")
824            }
825        }
826    }
827}
828forward_ref_binop!(impl Div, div for SignedDecimal, SignedDecimal);
829
830impl DivAssign for SignedDecimal {
831    fn div_assign(&mut self, rhs: SignedDecimal) {
832        *self = *self / rhs;
833    }
834}
835forward_ref_op_assign!(impl DivAssign, div_assign for SignedDecimal, SignedDecimal);
836
837impl Div<Int128> for SignedDecimal {
838    type Output = Self;
839
840    fn div(self, rhs: Int128) -> Self::Output {
841        SignedDecimal(self.0 / rhs)
842    }
843}
844
845impl DivAssign<Int128> for SignedDecimal {
846    fn div_assign(&mut self, rhs: Int128) {
847        self.0 /= rhs;
848    }
849}
850
851impl Rem for SignedDecimal {
852    type Output = Self;
853
854    /// # Panics
855    ///
856    /// This operation will panic if `rhs` is zero
857    #[inline]
858    fn rem(self, rhs: Self) -> Self {
859        Self(self.0.rem(rhs.0))
860    }
861}
862forward_ref_binop!(impl Rem, rem for SignedDecimal, SignedDecimal);
863
864impl RemAssign<SignedDecimal> for SignedDecimal {
865    fn rem_assign(&mut self, rhs: SignedDecimal) {
866        *self = *self % rhs;
867    }
868}
869forward_ref_op_assign!(impl RemAssign, rem_assign for SignedDecimal, SignedDecimal);
870
871impl<A> core::iter::Sum<A> for SignedDecimal
872where
873    Self: Add<A, Output = Self>,
874{
875    fn sum<I: Iterator<Item = A>>(iter: I) -> Self {
876        iter.fold(Self::zero(), Add::add)
877    }
878}
879
880/// Serializes as a decimal string
881impl Serialize for SignedDecimal {
882    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
883    where
884        S: ser::Serializer,
885    {
886        serializer.serialize_str(&self.to_string())
887    }
888}
889
890/// Deserializes as a base64 string
891impl<'de> Deserialize<'de> for SignedDecimal {
892    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
893    where
894        D: Deserializer<'de>,
895    {
896        deserializer.deserialize_str(SignedDecimalVisitor)
897    }
898}
899
900struct SignedDecimalVisitor;
901
902impl de::Visitor<'_> for SignedDecimalVisitor {
903    type Value = SignedDecimal;
904
905    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
906        formatter.write_str("string-encoded decimal")
907    }
908
909    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
910    where
911        E: de::Error,
912    {
913        match SignedDecimal::from_str(v) {
914            Ok(d) => Ok(d),
915            Err(e) => Err(E::custom(format_args!("Error parsing decimal '{v}': {e}"))),
916        }
917    }
918}
919
920#[cfg(test)]
921mod tests {
922    use crate::Uint128;
923
924    use super::*;
925
926    use alloc::vec::Vec;
927
928    fn dec(input: &str) -> SignedDecimal {
929        SignedDecimal::from_str(input).unwrap()
930    }
931
932    #[test]
933    fn signed_decimal_new() {
934        let expected = Int128::from(300i128);
935        assert_eq!(SignedDecimal::new(expected).0, expected);
936
937        let expected = Int128::from(-300i128);
938        assert_eq!(SignedDecimal::new(expected).0, expected);
939    }
940
941    #[test]
942    #[allow(deprecated)]
943    fn signed_decimal_raw() {
944        let value = 300i128;
945        assert_eq!(SignedDecimal::raw(value).0.i128(), value);
946
947        let value = -300i128;
948        assert_eq!(SignedDecimal::raw(value).0.i128(), value);
949    }
950
951    #[test]
952    fn signed_decimal_one() {
953        let value = SignedDecimal::one();
954        assert_eq!(value.0, SignedDecimal::DECIMAL_FRACTIONAL);
955    }
956
957    #[test]
958    fn signed_decimal_zero() {
959        let value = SignedDecimal::zero();
960        assert!(value.0.is_zero());
961    }
962
963    #[test]
964    fn signed_decimal_percent() {
965        let value = SignedDecimal::percent(50);
966        assert_eq!(
967            value.0,
968            SignedDecimal::DECIMAL_FRACTIONAL / Int128::from(2u8)
969        );
970
971        let value = SignedDecimal::percent(-50);
972        assert_eq!(
973            value.0,
974            SignedDecimal::DECIMAL_FRACTIONAL / Int128::from(-2i8)
975        );
976    }
977
978    #[test]
979    fn signed_decimal_permille() {
980        let value = SignedDecimal::permille(125);
981        assert_eq!(
982            value.0,
983            SignedDecimal::DECIMAL_FRACTIONAL / Int128::from(8u8)
984        );
985
986        let value = SignedDecimal::permille(-125);
987        assert_eq!(
988            value.0,
989            SignedDecimal::DECIMAL_FRACTIONAL / Int128::from(-8i8)
990        );
991    }
992
993    #[test]
994    fn signed_decimal_bps() {
995        let value = SignedDecimal::bps(125);
996        assert_eq!(
997            value.0,
998            SignedDecimal::DECIMAL_FRACTIONAL / Int128::from(80u8)
999        );
1000
1001        let value = SignedDecimal::bps(-125);
1002        assert_eq!(
1003            value.0,
1004            SignedDecimal::DECIMAL_FRACTIONAL / Int128::from(-80i8)
1005        );
1006    }
1007
1008    #[test]
1009    fn try_from_integer() {
1010        let int = Int128::new(0xDEADBEEF);
1011        let decimal = SignedDecimal::try_from(int).unwrap();
1012        assert_eq!(int.to_string(), decimal.to_string());
1013    }
1014
1015    #[test]
1016    fn signed_decimal_from_atomics_works() {
1017        let one = SignedDecimal::one();
1018        let two = one + one;
1019        let neg_one = SignedDecimal::negative_one();
1020
1021        assert_eq!(SignedDecimal::from_atomics(1i128, 0).unwrap(), one);
1022        assert_eq!(SignedDecimal::from_atomics(10i128, 1).unwrap(), one);
1023        assert_eq!(SignedDecimal::from_atomics(100i128, 2).unwrap(), one);
1024        assert_eq!(SignedDecimal::from_atomics(1000i128, 3).unwrap(), one);
1025        assert_eq!(
1026            SignedDecimal::from_atomics(1000000000000000000i128, 18).unwrap(),
1027            one
1028        );
1029        assert_eq!(
1030            SignedDecimal::from_atomics(10000000000000000000i128, 19).unwrap(),
1031            one
1032        );
1033        assert_eq!(
1034            SignedDecimal::from_atomics(100000000000000000000i128, 20).unwrap(),
1035            one
1036        );
1037
1038        assert_eq!(SignedDecimal::from_atomics(2i128, 0).unwrap(), two);
1039        assert_eq!(SignedDecimal::from_atomics(20i128, 1).unwrap(), two);
1040        assert_eq!(SignedDecimal::from_atomics(200i128, 2).unwrap(), two);
1041        assert_eq!(SignedDecimal::from_atomics(2000i128, 3).unwrap(), two);
1042        assert_eq!(
1043            SignedDecimal::from_atomics(2000000000000000000i128, 18).unwrap(),
1044            two
1045        );
1046        assert_eq!(
1047            SignedDecimal::from_atomics(20000000000000000000i128, 19).unwrap(),
1048            two
1049        );
1050        assert_eq!(
1051            SignedDecimal::from_atomics(200000000000000000000i128, 20).unwrap(),
1052            two
1053        );
1054
1055        assert_eq!(SignedDecimal::from_atomics(-1i128, 0).unwrap(), neg_one);
1056        assert_eq!(SignedDecimal::from_atomics(-10i128, 1).unwrap(), neg_one);
1057        assert_eq!(
1058            SignedDecimal::from_atomics(-100000000000000000000i128, 20).unwrap(),
1059            neg_one
1060        );
1061
1062        // Cuts decimal digits (20 provided but only 18 can be stored)
1063        assert_eq!(
1064            SignedDecimal::from_atomics(4321i128, 20).unwrap(),
1065            SignedDecimal::from_str("0.000000000000000043").unwrap()
1066        );
1067        assert_eq!(
1068            SignedDecimal::from_atomics(-4321i128, 20).unwrap(),
1069            SignedDecimal::from_str("-0.000000000000000043").unwrap()
1070        );
1071        assert_eq!(
1072            SignedDecimal::from_atomics(6789i128, 20).unwrap(),
1073            SignedDecimal::from_str("0.000000000000000067").unwrap()
1074        );
1075        assert_eq!(
1076            SignedDecimal::from_atomics(i128::MAX, 38).unwrap(),
1077            SignedDecimal::from_str("1.701411834604692317").unwrap()
1078        );
1079        assert_eq!(
1080            SignedDecimal::from_atomics(i128::MAX, 39).unwrap(),
1081            SignedDecimal::from_str("0.170141183460469231").unwrap()
1082        );
1083        assert_eq!(
1084            SignedDecimal::from_atomics(i128::MAX, 45).unwrap(),
1085            SignedDecimal::from_str("0.000000170141183460").unwrap()
1086        );
1087        assert_eq!(
1088            SignedDecimal::from_atomics(i128::MAX, 51).unwrap(),
1089            SignedDecimal::from_str("0.000000000000170141").unwrap()
1090        );
1091        assert_eq!(
1092            SignedDecimal::from_atomics(i128::MAX, 56).unwrap(),
1093            SignedDecimal::from_str("0.000000000000000001").unwrap()
1094        );
1095        assert_eq!(
1096            SignedDecimal::from_atomics(i128::MAX, 57).unwrap(),
1097            SignedDecimal::from_str("0.000000000000000000").unwrap()
1098        );
1099        assert_eq!(
1100            SignedDecimal::from_atomics(i128::MAX, u32::MAX).unwrap(),
1101            SignedDecimal::from_str("0.000000000000000000").unwrap()
1102        );
1103
1104        // Can be used with max value
1105        let max = SignedDecimal::MAX;
1106        assert_eq!(
1107            SignedDecimal::from_atomics(max.atomics(), max.decimal_places()).unwrap(),
1108            max
1109        );
1110
1111        // Can be used with min value
1112        let min = SignedDecimal::MIN;
1113        assert_eq!(
1114            SignedDecimal::from_atomics(min.atomics(), min.decimal_places()).unwrap(),
1115            min
1116        );
1117
1118        // Overflow is only possible with digits < 18
1119        let result = SignedDecimal::from_atomics(i128::MAX, 17);
1120        assert_eq!(result.unwrap_err(), SignedDecimalRangeExceeded);
1121    }
1122
1123    #[test]
1124    fn signed_decimal_from_ratio_works() {
1125        // 1.0
1126        assert_eq!(
1127            SignedDecimal::from_ratio(1i128, 1i128),
1128            SignedDecimal::one()
1129        );
1130        assert_eq!(
1131            SignedDecimal::from_ratio(53i128, 53i128),
1132            SignedDecimal::one()
1133        );
1134        assert_eq!(
1135            SignedDecimal::from_ratio(125i128, 125i128),
1136            SignedDecimal::one()
1137        );
1138
1139        // -1.0
1140        assert_eq!(
1141            SignedDecimal::from_ratio(-1i128, 1i128),
1142            SignedDecimal::negative_one()
1143        );
1144        assert_eq!(
1145            SignedDecimal::from_ratio(-53i128, 53i128),
1146            SignedDecimal::negative_one()
1147        );
1148        assert_eq!(
1149            SignedDecimal::from_ratio(125i128, -125i128),
1150            SignedDecimal::negative_one()
1151        );
1152
1153        // 1.5
1154        assert_eq!(
1155            SignedDecimal::from_ratio(3i128, 2i128),
1156            SignedDecimal::percent(150)
1157        );
1158        assert_eq!(
1159            SignedDecimal::from_ratio(150i128, 100i128),
1160            SignedDecimal::percent(150)
1161        );
1162        assert_eq!(
1163            SignedDecimal::from_ratio(333i128, 222i128),
1164            SignedDecimal::percent(150)
1165        );
1166
1167        // 0.125
1168        assert_eq!(
1169            SignedDecimal::from_ratio(1i64, 8i64),
1170            SignedDecimal::permille(125)
1171        );
1172        assert_eq!(
1173            SignedDecimal::from_ratio(125i64, 1000i64),
1174            SignedDecimal::permille(125)
1175        );
1176
1177        // -0.125
1178        assert_eq!(
1179            SignedDecimal::from_ratio(-1i64, 8i64),
1180            SignedDecimal::permille(-125)
1181        );
1182        assert_eq!(
1183            SignedDecimal::from_ratio(125i64, -1000i64),
1184            SignedDecimal::permille(-125)
1185        );
1186
1187        // 1/3 (result floored)
1188        assert_eq!(
1189            SignedDecimal::from_ratio(1i64, 3i64),
1190            SignedDecimal(Int128::from(333_333_333_333_333_333i128))
1191        );
1192
1193        // 2/3 (result floored)
1194        assert_eq!(
1195            SignedDecimal::from_ratio(2i64, 3i64),
1196            SignedDecimal(Int128::from(666_666_666_666_666_666i128))
1197        );
1198
1199        // large inputs
1200        assert_eq!(
1201            SignedDecimal::from_ratio(0i128, i128::MAX),
1202            SignedDecimal::zero()
1203        );
1204        assert_eq!(
1205            SignedDecimal::from_ratio(i128::MAX, i128::MAX),
1206            SignedDecimal::one()
1207        );
1208        // 170141183460469231731 is the largest integer <= SignedDecimal::MAX
1209        assert_eq!(
1210            SignedDecimal::from_ratio(170141183460469231731i128, 1i128),
1211            SignedDecimal::from_str("170141183460469231731").unwrap()
1212        );
1213    }
1214
1215    #[test]
1216    #[should_panic(expected = "Denominator must not be zero")]
1217    fn signed_decimal_from_ratio_panics_for_zero_denominator() {
1218        SignedDecimal::from_ratio(1i128, 0i128);
1219    }
1220
1221    #[test]
1222    #[should_panic(expected = "Multiplication overflow")]
1223    fn signed_decimal_from_ratio_panics_for_mul_overflow() {
1224        SignedDecimal::from_ratio(i128::MAX, 1i128);
1225    }
1226
1227    #[test]
1228    fn signed_decimal_checked_from_ratio_does_not_panic() {
1229        assert_eq!(
1230            SignedDecimal::checked_from_ratio(1i128, 0i128),
1231            Err(CheckedFromRatioError::DivideByZero)
1232        );
1233
1234        assert_eq!(
1235            SignedDecimal::checked_from_ratio(i128::MAX, 1i128),
1236            Err(CheckedFromRatioError::Overflow)
1237        );
1238    }
1239
1240    #[test]
1241    fn signed_decimal_implements_fraction() {
1242        let fraction = SignedDecimal::from_str("1234.567").unwrap();
1243        assert_eq!(
1244            fraction.numerator(),
1245            Int128::from(1_234_567_000_000_000_000_000i128)
1246        );
1247        assert_eq!(
1248            fraction.denominator(),
1249            Int128::from(1_000_000_000_000_000_000i128)
1250        );
1251
1252        let fraction = SignedDecimal::from_str("-1234.567").unwrap();
1253        assert_eq!(
1254            fraction.numerator(),
1255            Int128::from(-1_234_567_000_000_000_000_000i128)
1256        );
1257        assert_eq!(
1258            fraction.denominator(),
1259            Int128::from(1_000_000_000_000_000_000i128)
1260        );
1261    }
1262
1263    #[test]
1264    fn signed_decimal_from_str_works() {
1265        // Integers
1266        assert_eq!(
1267            SignedDecimal::from_str("0").unwrap(),
1268            SignedDecimal::percent(0)
1269        );
1270        assert_eq!(
1271            SignedDecimal::from_str("1").unwrap(),
1272            SignedDecimal::percent(100)
1273        );
1274        assert_eq!(
1275            SignedDecimal::from_str("5").unwrap(),
1276            SignedDecimal::percent(500)
1277        );
1278        assert_eq!(
1279            SignedDecimal::from_str("42").unwrap(),
1280            SignedDecimal::percent(4200)
1281        );
1282        assert_eq!(
1283            SignedDecimal::from_str("000").unwrap(),
1284            SignedDecimal::percent(0)
1285        );
1286        assert_eq!(
1287            SignedDecimal::from_str("001").unwrap(),
1288            SignedDecimal::percent(100)
1289        );
1290        assert_eq!(
1291            SignedDecimal::from_str("005").unwrap(),
1292            SignedDecimal::percent(500)
1293        );
1294        assert_eq!(
1295            SignedDecimal::from_str("0042").unwrap(),
1296            SignedDecimal::percent(4200)
1297        );
1298
1299        // Positive decimals
1300        assert_eq!(
1301            SignedDecimal::from_str("1.0").unwrap(),
1302            SignedDecimal::percent(100)
1303        );
1304        assert_eq!(
1305            SignedDecimal::from_str("1.5").unwrap(),
1306            SignedDecimal::percent(150)
1307        );
1308        assert_eq!(
1309            SignedDecimal::from_str("0.5").unwrap(),
1310            SignedDecimal::percent(50)
1311        );
1312        assert_eq!(
1313            SignedDecimal::from_str("0.123").unwrap(),
1314            SignedDecimal::permille(123)
1315        );
1316
1317        assert_eq!(
1318            SignedDecimal::from_str("40.00").unwrap(),
1319            SignedDecimal::percent(4000)
1320        );
1321        assert_eq!(
1322            SignedDecimal::from_str("04.00").unwrap(),
1323            SignedDecimal::percent(400)
1324        );
1325        assert_eq!(
1326            SignedDecimal::from_str("00.40").unwrap(),
1327            SignedDecimal::percent(40)
1328        );
1329        assert_eq!(
1330            SignedDecimal::from_str("00.04").unwrap(),
1331            SignedDecimal::percent(4)
1332        );
1333        // Negative decimals
1334        assert_eq!(
1335            SignedDecimal::from_str("-00.04").unwrap(),
1336            SignedDecimal::percent(-4)
1337        );
1338        assert_eq!(
1339            SignedDecimal::from_str("-00.40").unwrap(),
1340            SignedDecimal::percent(-40)
1341        );
1342        assert_eq!(
1343            SignedDecimal::from_str("-04.00").unwrap(),
1344            SignedDecimal::percent(-400)
1345        );
1346
1347        // Can handle DECIMAL_PLACES fractional digits
1348        assert_eq!(
1349            SignedDecimal::from_str("7.123456789012345678").unwrap(),
1350            SignedDecimal(Int128::from(7123456789012345678i128))
1351        );
1352        assert_eq!(
1353            SignedDecimal::from_str("7.999999999999999999").unwrap(),
1354            SignedDecimal(Int128::from(7999999999999999999i128))
1355        );
1356
1357        // Works for documented max value
1358        assert_eq!(
1359            SignedDecimal::from_str("170141183460469231731.687303715884105727").unwrap(),
1360            SignedDecimal::MAX
1361        );
1362        // Works for documented min value
1363        assert_eq!(
1364            SignedDecimal::from_str("-170141183460469231731.687303715884105728").unwrap(),
1365            SignedDecimal::MIN
1366        );
1367        assert_eq!(
1368            SignedDecimal::from_str("-1").unwrap(),
1369            SignedDecimal::negative_one()
1370        );
1371    }
1372
1373    #[test]
1374    fn signed_decimal_from_str_errors_for_broken_whole_part() {
1375        assert!(SignedDecimal::from_str("").is_err());
1376        assert!(SignedDecimal::from_str(" ").is_err());
1377        assert!(SignedDecimal::from_str("-").is_err());
1378    }
1379
1380    #[test]
1381    fn signed_decimal_from_str_errors_for_broken_fractional_part() {
1382        assert!(SignedDecimal::from_str("1.").is_err());
1383        assert!(SignedDecimal::from_str("1. ").is_err());
1384        assert!(SignedDecimal::from_str("1.e").is_err());
1385        assert!(SignedDecimal::from_str("1.2e3").is_err());
1386        assert!(SignedDecimal::from_str("1.-2").is_err());
1387    }
1388
1389    #[test]
1390    fn signed_decimal_from_str_errors_for_more_than_18_fractional_digits() {
1391        assert!(SignedDecimal::from_str("7.1234567890123456789").is_err());
1392        // No special rules for trailing zeros. This could be changed but adds gas cost for the happy path.
1393        assert!(SignedDecimal::from_str("7.1230000000000000000").is_err());
1394    }
1395
1396    #[test]
1397    fn signed_decimal_from_str_errors_for_invalid_number_of_dots() {
1398        assert!(SignedDecimal::from_str("1.2.3")
1399            .unwrap_err()
1400            .to_string()
1401            .ends_with("Unexpected number of dots"));
1402
1403        assert!(SignedDecimal::from_str("1.2.3.4")
1404            .unwrap_err()
1405            .to_string()
1406            .ends_with("Unexpected number of dots"));
1407    }
1408
1409    #[test]
1410    fn signed_decimal_from_str_errors_for_more_than_max_value() {
1411        // Integer
1412        assert!(SignedDecimal::from_str("170141183460469231732").is_err());
1413        assert!(SignedDecimal::from_str("-170141183460469231732").is_err());
1414
1415        // SignedDecimal
1416        assert!(SignedDecimal::from_str("170141183460469231732.0").is_err());
1417        assert!(SignedDecimal::from_str("170141183460469231731.687303715884105728").is_err());
1418        assert!(SignedDecimal::from_str("-170141183460469231731.687303715884105729").is_err());
1419    }
1420
1421    #[test]
1422    fn signed_decimal_conversions_work() {
1423        // signed decimal to signed decimal
1424        assert_eq!(
1425            SignedDecimal::try_from(SignedDecimal256::MAX).unwrap_err(),
1426            SignedDecimalRangeExceeded
1427        );
1428        assert_eq!(
1429            SignedDecimal::try_from(SignedDecimal256::MIN).unwrap_err(),
1430            SignedDecimalRangeExceeded
1431        );
1432        assert_eq!(
1433            SignedDecimal::try_from(SignedDecimal256::zero()).unwrap(),
1434            SignedDecimal::zero()
1435        );
1436        assert_eq!(
1437            SignedDecimal::try_from(SignedDecimal256::one()).unwrap(),
1438            SignedDecimal::one()
1439        );
1440        assert_eq!(
1441            SignedDecimal::try_from(SignedDecimal256::percent(50)).unwrap(),
1442            SignedDecimal::percent(50)
1443        );
1444        assert_eq!(
1445            SignedDecimal::try_from(SignedDecimal256::percent(-200)).unwrap(),
1446            SignedDecimal::percent(-200)
1447        );
1448
1449        // unsigned to signed decimal
1450        assert_eq!(
1451            SignedDecimal::try_from(Decimal::MAX).unwrap_err(),
1452            SignedDecimalRangeExceeded
1453        );
1454        let max = Decimal::new(Uint128::new(SignedDecimal::MAX.atomics().i128() as u128));
1455        let too_big = max + Decimal::new(Uint128::one());
1456        assert_eq!(
1457            SignedDecimal::try_from(too_big).unwrap_err(),
1458            SignedDecimalRangeExceeded
1459        );
1460        assert_eq!(
1461            SignedDecimal::try_from(Decimal::zero()).unwrap(),
1462            SignedDecimal::zero()
1463        );
1464        assert_eq!(SignedDecimal::try_from(max).unwrap(), SignedDecimal::MAX);
1465    }
1466
1467    #[test]
1468    fn signed_decimal_atomics_works() {
1469        let zero = SignedDecimal::zero();
1470        let one = SignedDecimal::one();
1471        let half = SignedDecimal::percent(50);
1472        let two = SignedDecimal::percent(200);
1473        let max = SignedDecimal::MAX;
1474        let neg_half = SignedDecimal::percent(-50);
1475        let neg_two = SignedDecimal::percent(-200);
1476        let min = SignedDecimal::MIN;
1477
1478        assert_eq!(zero.atomics(), Int128::new(0));
1479        assert_eq!(one.atomics(), Int128::new(1000000000000000000));
1480        assert_eq!(half.atomics(), Int128::new(500000000000000000));
1481        assert_eq!(two.atomics(), Int128::new(2000000000000000000));
1482        assert_eq!(max.atomics(), Int128::MAX);
1483        assert_eq!(neg_half.atomics(), Int128::new(-500000000000000000));
1484        assert_eq!(neg_two.atomics(), Int128::new(-2000000000000000000));
1485        assert_eq!(min.atomics(), Int128::MIN);
1486    }
1487
1488    #[test]
1489    fn signed_decimal_decimal_places_works() {
1490        let zero = SignedDecimal::zero();
1491        let one = SignedDecimal::one();
1492        let half = SignedDecimal::percent(50);
1493        let two = SignedDecimal::percent(200);
1494        let max = SignedDecimal::MAX;
1495        let neg_one = SignedDecimal::negative_one();
1496
1497        assert_eq!(zero.decimal_places(), 18);
1498        assert_eq!(one.decimal_places(), 18);
1499        assert_eq!(half.decimal_places(), 18);
1500        assert_eq!(two.decimal_places(), 18);
1501        assert_eq!(max.decimal_places(), 18);
1502        assert_eq!(neg_one.decimal_places(), 18);
1503    }
1504
1505    #[test]
1506    fn signed_decimal_is_zero_works() {
1507        assert!(SignedDecimal::zero().is_zero());
1508        assert!(SignedDecimal::percent(0).is_zero());
1509        assert!(SignedDecimal::permille(0).is_zero());
1510
1511        assert!(!SignedDecimal::one().is_zero());
1512        assert!(!SignedDecimal::percent(123).is_zero());
1513        assert!(!SignedDecimal::permille(-1234).is_zero());
1514    }
1515
1516    #[test]
1517    fn signed_decimal_inv_works() {
1518        // d = 0
1519        assert_eq!(SignedDecimal::zero().inv(), None);
1520
1521        // d == 1
1522        assert_eq!(SignedDecimal::one().inv(), Some(SignedDecimal::one()));
1523
1524        // d == -1
1525        assert_eq!(
1526            SignedDecimal::negative_one().inv(),
1527            Some(SignedDecimal::negative_one())
1528        );
1529
1530        // d > 1 exact
1531        assert_eq!(
1532            SignedDecimal::from_str("2").unwrap().inv(),
1533            Some(SignedDecimal::from_str("0.5").unwrap())
1534        );
1535        assert_eq!(
1536            SignedDecimal::from_str("20").unwrap().inv(),
1537            Some(SignedDecimal::from_str("0.05").unwrap())
1538        );
1539        assert_eq!(
1540            SignedDecimal::from_str("200").unwrap().inv(),
1541            Some(SignedDecimal::from_str("0.005").unwrap())
1542        );
1543        assert_eq!(
1544            SignedDecimal::from_str("2000").unwrap().inv(),
1545            Some(SignedDecimal::from_str("0.0005").unwrap())
1546        );
1547
1548        // d > 1 rounded
1549        assert_eq!(
1550            SignedDecimal::from_str("3").unwrap().inv(),
1551            Some(SignedDecimal::from_str("0.333333333333333333").unwrap())
1552        );
1553        assert_eq!(
1554            SignedDecimal::from_str("6").unwrap().inv(),
1555            Some(SignedDecimal::from_str("0.166666666666666666").unwrap())
1556        );
1557
1558        // d < 1 exact
1559        assert_eq!(
1560            SignedDecimal::from_str("0.5").unwrap().inv(),
1561            Some(SignedDecimal::from_str("2").unwrap())
1562        );
1563        assert_eq!(
1564            SignedDecimal::from_str("0.05").unwrap().inv(),
1565            Some(SignedDecimal::from_str("20").unwrap())
1566        );
1567        assert_eq!(
1568            SignedDecimal::from_str("0.005").unwrap().inv(),
1569            Some(SignedDecimal::from_str("200").unwrap())
1570        );
1571        assert_eq!(
1572            SignedDecimal::from_str("0.0005").unwrap().inv(),
1573            Some(SignedDecimal::from_str("2000").unwrap())
1574        );
1575
1576        // d < 0
1577        assert_eq!(
1578            SignedDecimal::from_str("-0.5").unwrap().inv(),
1579            Some(SignedDecimal::from_str("-2").unwrap())
1580        );
1581        // d < 0 rounded
1582        assert_eq!(
1583            SignedDecimal::from_str("-3").unwrap().inv(),
1584            Some(SignedDecimal::from_str("-0.333333333333333333").unwrap())
1585        );
1586    }
1587
1588    #[test]
1589    #[allow(clippy::op_ref)]
1590    fn signed_decimal_add_works() {
1591        let value = SignedDecimal::one() + SignedDecimal::percent(50); // 1.5
1592        assert_eq!(
1593            value.0,
1594            SignedDecimal::DECIMAL_FRACTIONAL * Int128::from(3u8) / Int128::from(2u8)
1595        );
1596
1597        assert_eq!(
1598            SignedDecimal::percent(5) + SignedDecimal::percent(4),
1599            SignedDecimal::percent(9)
1600        );
1601        assert_eq!(
1602            SignedDecimal::percent(5) + SignedDecimal::zero(),
1603            SignedDecimal::percent(5)
1604        );
1605        assert_eq!(
1606            SignedDecimal::zero() + SignedDecimal::zero(),
1607            SignedDecimal::zero()
1608        );
1609        // negative numbers
1610        assert_eq!(
1611            SignedDecimal::percent(-5) + SignedDecimal::percent(-4),
1612            SignedDecimal::percent(-9)
1613        );
1614        assert_eq!(
1615            SignedDecimal::percent(-5) + SignedDecimal::percent(4),
1616            SignedDecimal::percent(-1)
1617        );
1618        assert_eq!(
1619            SignedDecimal::percent(5) + SignedDecimal::percent(-4),
1620            SignedDecimal::percent(1)
1621        );
1622
1623        // works for refs
1624        let a = SignedDecimal::percent(15);
1625        let b = SignedDecimal::percent(25);
1626        let expected = SignedDecimal::percent(40);
1627        assert_eq!(a + b, expected);
1628        assert_eq!(&a + b, expected);
1629        assert_eq!(a + &b, expected);
1630        assert_eq!(&a + &b, expected);
1631    }
1632
1633    #[test]
1634    #[should_panic]
1635    fn signed_decimal_add_overflow_panics() {
1636        let _value = SignedDecimal::MAX + SignedDecimal::percent(50);
1637    }
1638
1639    #[test]
1640    fn signed_decimal_add_assign_works() {
1641        let mut a = SignedDecimal::percent(30);
1642        a += SignedDecimal::percent(20);
1643        assert_eq!(a, SignedDecimal::percent(50));
1644
1645        // works for refs
1646        let mut a = SignedDecimal::percent(15);
1647        let b = SignedDecimal::percent(3);
1648        let expected = SignedDecimal::percent(18);
1649        a += &b;
1650        assert_eq!(a, expected);
1651    }
1652
1653    #[test]
1654    #[allow(clippy::op_ref)]
1655    fn signed_decimal_sub_works() {
1656        let value = SignedDecimal::one() - SignedDecimal::percent(50); // 0.5
1657        assert_eq!(
1658            value.0,
1659            SignedDecimal::DECIMAL_FRACTIONAL / Int128::from(2u8)
1660        );
1661
1662        assert_eq!(
1663            SignedDecimal::percent(9) - SignedDecimal::percent(4),
1664            SignedDecimal::percent(5)
1665        );
1666        assert_eq!(
1667            SignedDecimal::percent(16) - SignedDecimal::zero(),
1668            SignedDecimal::percent(16)
1669        );
1670        assert_eq!(
1671            SignedDecimal::percent(16) - SignedDecimal::percent(16),
1672            SignedDecimal::zero()
1673        );
1674        assert_eq!(
1675            SignedDecimal::zero() - SignedDecimal::zero(),
1676            SignedDecimal::zero()
1677        );
1678
1679        // negative numbers
1680        assert_eq!(
1681            SignedDecimal::percent(-5) - SignedDecimal::percent(-4),
1682            SignedDecimal::percent(-1)
1683        );
1684        assert_eq!(
1685            SignedDecimal::percent(-5) - SignedDecimal::percent(4),
1686            SignedDecimal::percent(-9)
1687        );
1688        assert_eq!(
1689            SignedDecimal::percent(500) - SignedDecimal::percent(-4),
1690            SignedDecimal::percent(504)
1691        );
1692
1693        // works for refs
1694        let a = SignedDecimal::percent(13);
1695        let b = SignedDecimal::percent(6);
1696        let expected = SignedDecimal::percent(7);
1697        assert_eq!(a - b, expected);
1698        assert_eq!(&a - b, expected);
1699        assert_eq!(a - &b, expected);
1700        assert_eq!(&a - &b, expected);
1701    }
1702
1703    #[test]
1704    #[should_panic]
1705    fn signed_decimal_sub_overflow_panics() {
1706        let _value = SignedDecimal::MIN - SignedDecimal::percent(50);
1707    }
1708
1709    #[test]
1710    fn signed_decimal_sub_assign_works() {
1711        let mut a = SignedDecimal::percent(20);
1712        a -= SignedDecimal::percent(2);
1713        assert_eq!(a, SignedDecimal::percent(18));
1714
1715        // works for refs
1716        let mut a = SignedDecimal::percent(33);
1717        let b = SignedDecimal::percent(13);
1718        let expected = SignedDecimal::percent(20);
1719        a -= &b;
1720        assert_eq!(a, expected);
1721    }
1722
1723    #[test]
1724    #[allow(clippy::op_ref)]
1725    fn signed_decimal_implements_mul() {
1726        let one = SignedDecimal::one();
1727        let two = one + one;
1728        let half = SignedDecimal::percent(50);
1729
1730        // 1*x and x*1
1731        assert_eq!(one * SignedDecimal::percent(0), SignedDecimal::percent(0));
1732        assert_eq!(one * SignedDecimal::percent(1), SignedDecimal::percent(1));
1733        assert_eq!(one * SignedDecimal::percent(10), SignedDecimal::percent(10));
1734        assert_eq!(
1735            one * SignedDecimal::percent(100),
1736            SignedDecimal::percent(100)
1737        );
1738        assert_eq!(
1739            one * SignedDecimal::percent(1000),
1740            SignedDecimal::percent(1000)
1741        );
1742        assert_eq!(one * SignedDecimal::MAX, SignedDecimal::MAX);
1743        assert_eq!(SignedDecimal::percent(0) * one, SignedDecimal::percent(0));
1744        assert_eq!(SignedDecimal::percent(1) * one, SignedDecimal::percent(1));
1745        assert_eq!(SignedDecimal::percent(10) * one, SignedDecimal::percent(10));
1746        assert_eq!(
1747            SignedDecimal::percent(100) * one,
1748            SignedDecimal::percent(100)
1749        );
1750        assert_eq!(
1751            SignedDecimal::percent(1000) * one,
1752            SignedDecimal::percent(1000)
1753        );
1754        assert_eq!(SignedDecimal::MAX * one, SignedDecimal::MAX);
1755        assert_eq!(SignedDecimal::percent(-1) * one, SignedDecimal::percent(-1));
1756        assert_eq!(
1757            one * SignedDecimal::percent(-10),
1758            SignedDecimal::percent(-10)
1759        );
1760
1761        // double
1762        assert_eq!(two * SignedDecimal::percent(0), SignedDecimal::percent(0));
1763        assert_eq!(two * SignedDecimal::percent(1), SignedDecimal::percent(2));
1764        assert_eq!(two * SignedDecimal::percent(10), SignedDecimal::percent(20));
1765        assert_eq!(
1766            two * SignedDecimal::percent(100),
1767            SignedDecimal::percent(200)
1768        );
1769        assert_eq!(
1770            two * SignedDecimal::percent(1000),
1771            SignedDecimal::percent(2000)
1772        );
1773        assert_eq!(SignedDecimal::percent(0) * two, SignedDecimal::percent(0));
1774        assert_eq!(SignedDecimal::percent(1) * two, SignedDecimal::percent(2));
1775        assert_eq!(SignedDecimal::percent(10) * two, SignedDecimal::percent(20));
1776        assert_eq!(
1777            SignedDecimal::percent(100) * two,
1778            SignedDecimal::percent(200)
1779        );
1780        assert_eq!(
1781            SignedDecimal::percent(1000) * two,
1782            SignedDecimal::percent(2000)
1783        );
1784        assert_eq!(SignedDecimal::percent(-1) * two, SignedDecimal::percent(-2));
1785        assert_eq!(
1786            two * SignedDecimal::new(Int128::MIN / Int128::new(2)),
1787            SignedDecimal::MIN
1788        );
1789
1790        // half
1791        assert_eq!(half * SignedDecimal::percent(0), SignedDecimal::percent(0));
1792        assert_eq!(half * SignedDecimal::percent(1), SignedDecimal::permille(5));
1793        assert_eq!(half * SignedDecimal::percent(10), SignedDecimal::percent(5));
1794        assert_eq!(
1795            half * SignedDecimal::percent(100),
1796            SignedDecimal::percent(50)
1797        );
1798        assert_eq!(
1799            half * SignedDecimal::percent(1000),
1800            SignedDecimal::percent(500)
1801        );
1802        assert_eq!(SignedDecimal::percent(0) * half, SignedDecimal::percent(0));
1803        assert_eq!(SignedDecimal::percent(1) * half, SignedDecimal::permille(5));
1804        assert_eq!(SignedDecimal::percent(10) * half, SignedDecimal::percent(5));
1805        assert_eq!(
1806            SignedDecimal::percent(100) * half,
1807            SignedDecimal::percent(50)
1808        );
1809        assert_eq!(
1810            SignedDecimal::percent(1000) * half,
1811            SignedDecimal::percent(500)
1812        );
1813
1814        // Move left
1815        let a = dec("123.127726548762582");
1816        assert_eq!(a * dec("1"), dec("123.127726548762582"));
1817        assert_eq!(a * dec("10"), dec("1231.27726548762582"));
1818        assert_eq!(a * dec("100"), dec("12312.7726548762582"));
1819        assert_eq!(a * dec("1000"), dec("123127.726548762582"));
1820        assert_eq!(a * dec("1000000"), dec("123127726.548762582"));
1821        assert_eq!(a * dec("1000000000"), dec("123127726548.762582"));
1822        assert_eq!(a * dec("1000000000000"), dec("123127726548762.582"));
1823        assert_eq!(a * dec("1000000000000000"), dec("123127726548762582"));
1824        assert_eq!(a * dec("1000000000000000000"), dec("123127726548762582000"));
1825        assert_eq!(dec("1") * a, dec("123.127726548762582"));
1826        assert_eq!(dec("10") * a, dec("1231.27726548762582"));
1827        assert_eq!(dec("100") * a, dec("12312.7726548762582"));
1828        assert_eq!(dec("1000") * a, dec("123127.726548762582"));
1829        assert_eq!(dec("1000000") * a, dec("123127726.548762582"));
1830        assert_eq!(dec("1000000000") * a, dec("123127726548.762582"));
1831        assert_eq!(dec("1000000000000") * a, dec("123127726548762.582"));
1832        assert_eq!(dec("1000000000000000") * a, dec("123127726548762582"));
1833        assert_eq!(dec("1000000000000000000") * a, dec("123127726548762582000"));
1834        assert_eq!(
1835            dec("-1000000000000000000") * a,
1836            dec("-123127726548762582000")
1837        );
1838
1839        // Move right
1840        let max = SignedDecimal::MAX;
1841        assert_eq!(
1842            max * dec("1.0"),
1843            dec("170141183460469231731.687303715884105727")
1844        );
1845        assert_eq!(
1846            max * dec("0.1"),
1847            dec("17014118346046923173.168730371588410572")
1848        );
1849        assert_eq!(
1850            max * dec("0.01"),
1851            dec("1701411834604692317.316873037158841057")
1852        );
1853        assert_eq!(
1854            max * dec("0.001"),
1855            dec("170141183460469231.731687303715884105")
1856        );
1857        assert_eq!(
1858            max * dec("0.000001"),
1859            dec("170141183460469.231731687303715884")
1860        );
1861        assert_eq!(
1862            max * dec("0.000000001"),
1863            dec("170141183460.469231731687303715")
1864        );
1865        assert_eq!(
1866            max * dec("0.000000000001"),
1867            dec("170141183.460469231731687303")
1868        );
1869        assert_eq!(
1870            max * dec("0.000000000000001"),
1871            dec("170141.183460469231731687")
1872        );
1873        assert_eq!(
1874            max * dec("0.000000000000000001"),
1875            dec("170.141183460469231731")
1876        );
1877
1878        // works for refs
1879        let a = SignedDecimal::percent(20);
1880        let b = SignedDecimal::percent(30);
1881        let expected = SignedDecimal::percent(6);
1882        assert_eq!(a * b, expected);
1883        assert_eq!(&a * b, expected);
1884        assert_eq!(a * &b, expected);
1885        assert_eq!(&a * &b, expected);
1886    }
1887
1888    #[test]
1889    fn signed_decimal_mul_assign_works() {
1890        let mut a = SignedDecimal::percent(15);
1891        a *= SignedDecimal::percent(60);
1892        assert_eq!(a, SignedDecimal::percent(9));
1893
1894        // works for refs
1895        let mut a = SignedDecimal::percent(50);
1896        let b = SignedDecimal::percent(20);
1897        a *= &b;
1898        assert_eq!(a, SignedDecimal::percent(10));
1899    }
1900
1901    #[test]
1902    #[should_panic(expected = "attempt to multiply with overflow")]
1903    fn signed_decimal_mul_overflow_panics() {
1904        let _value = SignedDecimal::MAX * SignedDecimal::percent(101);
1905    }
1906
1907    #[test]
1908    fn signed_decimal_checked_mul() {
1909        let test_data = [
1910            (SignedDecimal::zero(), SignedDecimal::zero()),
1911            (SignedDecimal::zero(), SignedDecimal::one()),
1912            (SignedDecimal::one(), SignedDecimal::zero()),
1913            (SignedDecimal::percent(10), SignedDecimal::zero()),
1914            (SignedDecimal::percent(10), SignedDecimal::percent(5)),
1915            (SignedDecimal::MAX, SignedDecimal::one()),
1916            (
1917                SignedDecimal::MAX / Int128::new(2),
1918                SignedDecimal::percent(200),
1919            ),
1920            (SignedDecimal::permille(6), SignedDecimal::permille(13)),
1921            (SignedDecimal::permille(-6), SignedDecimal::permille(0)),
1922            (SignedDecimal::MAX, SignedDecimal::negative_one()),
1923        ];
1924
1925        // The regular core::ops::Mul is our source of truth for these tests.
1926        for (x, y) in test_data.into_iter() {
1927            assert_eq!(x * y, x.checked_mul(y).unwrap());
1928        }
1929    }
1930
1931    #[test]
1932    fn signed_decimal_checked_mul_overflow() {
1933        assert_eq!(
1934            SignedDecimal::MAX.checked_mul(SignedDecimal::percent(200)),
1935            Err(OverflowError::new(OverflowOperation::Mul))
1936        );
1937    }
1938
1939    #[test]
1940    #[allow(clippy::op_ref)]
1941    fn signed_decimal_implements_div() {
1942        let one = SignedDecimal::one();
1943        let two = one + one;
1944        let half = SignedDecimal::percent(50);
1945
1946        // 1/x and x/1
1947        assert_eq!(
1948            one / SignedDecimal::percent(1),
1949            SignedDecimal::percent(10_000)
1950        );
1951        assert_eq!(
1952            one / SignedDecimal::percent(10),
1953            SignedDecimal::percent(1_000)
1954        );
1955        assert_eq!(
1956            one / SignedDecimal::percent(100),
1957            SignedDecimal::percent(100)
1958        );
1959        assert_eq!(
1960            one / SignedDecimal::percent(1000),
1961            SignedDecimal::percent(10)
1962        );
1963        assert_eq!(SignedDecimal::percent(0) / one, SignedDecimal::percent(0));
1964        assert_eq!(SignedDecimal::percent(1) / one, SignedDecimal::percent(1));
1965        assert_eq!(SignedDecimal::percent(10) / one, SignedDecimal::percent(10));
1966        assert_eq!(
1967            SignedDecimal::percent(100) / one,
1968            SignedDecimal::percent(100)
1969        );
1970        assert_eq!(
1971            SignedDecimal::percent(1000) / one,
1972            SignedDecimal::percent(1000)
1973        );
1974        assert_eq!(
1975            one / SignedDecimal::percent(-1),
1976            SignedDecimal::percent(-10_000)
1977        );
1978        assert_eq!(
1979            one / SignedDecimal::percent(-10),
1980            SignedDecimal::percent(-1_000)
1981        );
1982
1983        // double
1984        assert_eq!(
1985            two / SignedDecimal::percent(1),
1986            SignedDecimal::percent(20_000)
1987        );
1988        assert_eq!(
1989            two / SignedDecimal::percent(10),
1990            SignedDecimal::percent(2_000)
1991        );
1992        assert_eq!(
1993            two / SignedDecimal::percent(100),
1994            SignedDecimal::percent(200)
1995        );
1996        assert_eq!(
1997            two / SignedDecimal::percent(1000),
1998            SignedDecimal::percent(20)
1999        );
2000        assert_eq!(SignedDecimal::percent(0) / two, SignedDecimal::percent(0));
2001        assert_eq!(SignedDecimal::percent(1) / two, dec("0.005"));
2002        assert_eq!(SignedDecimal::percent(10) / two, SignedDecimal::percent(5));
2003        assert_eq!(
2004            SignedDecimal::percent(100) / two,
2005            SignedDecimal::percent(50)
2006        );
2007        assert_eq!(
2008            SignedDecimal::percent(1000) / two,
2009            SignedDecimal::percent(500)
2010        );
2011        assert_eq!(
2012            two / SignedDecimal::percent(-1),
2013            SignedDecimal::percent(-20_000)
2014        );
2015        assert_eq!(
2016            SignedDecimal::percent(-10000) / two,
2017            SignedDecimal::percent(-5000)
2018        );
2019
2020        // half
2021        assert_eq!(
2022            half / SignedDecimal::percent(1),
2023            SignedDecimal::percent(5_000)
2024        );
2025        assert_eq!(
2026            half / SignedDecimal::percent(10),
2027            SignedDecimal::percent(500)
2028        );
2029        assert_eq!(
2030            half / SignedDecimal::percent(100),
2031            SignedDecimal::percent(50)
2032        );
2033        assert_eq!(
2034            half / SignedDecimal::percent(1000),
2035            SignedDecimal::percent(5)
2036        );
2037        assert_eq!(SignedDecimal::percent(0) / half, SignedDecimal::percent(0));
2038        assert_eq!(SignedDecimal::percent(1) / half, SignedDecimal::percent(2));
2039        assert_eq!(
2040            SignedDecimal::percent(10) / half,
2041            SignedDecimal::percent(20)
2042        );
2043        assert_eq!(
2044            SignedDecimal::percent(100) / half,
2045            SignedDecimal::percent(200)
2046        );
2047        assert_eq!(
2048            SignedDecimal::percent(1000) / half,
2049            SignedDecimal::percent(2000)
2050        );
2051
2052        // Move right
2053        let a = dec("123127726548762582");
2054        assert_eq!(a / dec("1"), dec("123127726548762582"));
2055        assert_eq!(a / dec("10"), dec("12312772654876258.2"));
2056        assert_eq!(a / dec("100"), dec("1231277265487625.82"));
2057        assert_eq!(a / dec("1000"), dec("123127726548762.582"));
2058        assert_eq!(a / dec("1000000"), dec("123127726548.762582"));
2059        assert_eq!(a / dec("1000000000"), dec("123127726.548762582"));
2060        assert_eq!(a / dec("1000000000000"), dec("123127.726548762582"));
2061        assert_eq!(a / dec("1000000000000000"), dec("123.127726548762582"));
2062        assert_eq!(a / dec("1000000000000000000"), dec("0.123127726548762582"));
2063        assert_eq!(dec("1") / a, dec("0.000000000000000008"));
2064        assert_eq!(dec("10") / a, dec("0.000000000000000081"));
2065        assert_eq!(dec("100") / a, dec("0.000000000000000812"));
2066        assert_eq!(dec("1000") / a, dec("0.000000000000008121"));
2067        assert_eq!(dec("1000000") / a, dec("0.000000000008121647"));
2068        assert_eq!(dec("1000000000") / a, dec("0.000000008121647560"));
2069        assert_eq!(dec("1000000000000") / a, dec("0.000008121647560868"));
2070        assert_eq!(dec("1000000000000000") / a, dec("0.008121647560868164"));
2071        assert_eq!(dec("1000000000000000000") / a, dec("8.121647560868164773"));
2072        // negative
2073        let a = dec("-123127726548762582");
2074        assert_eq!(a / dec("1"), dec("-123127726548762582"));
2075        assert_eq!(a / dec("10"), dec("-12312772654876258.2"));
2076        assert_eq!(a / dec("100"), dec("-1231277265487625.82"));
2077        assert_eq!(a / dec("1000"), dec("-123127726548762.582"));
2078        assert_eq!(a / dec("1000000"), dec("-123127726548.762582"));
2079        assert_eq!(a / dec("1000000000"), dec("-123127726.548762582"));
2080        assert_eq!(a / dec("1000000000000"), dec("-123127.726548762582"));
2081        assert_eq!(a / dec("1000000000000000"), dec("-123.127726548762582"));
2082        assert_eq!(a / dec("1000000000000000000"), dec("-0.123127726548762582"));
2083        assert_eq!(dec("1") / a, dec("-0.000000000000000008"));
2084
2085        // Move left
2086        let a = dec("0.123127726548762582");
2087        assert_eq!(a / dec("1.0"), dec("0.123127726548762582"));
2088        assert_eq!(a / dec("0.1"), dec("1.23127726548762582"));
2089        assert_eq!(a / dec("0.01"), dec("12.3127726548762582"));
2090        assert_eq!(a / dec("0.001"), dec("123.127726548762582"));
2091        assert_eq!(a / dec("0.000001"), dec("123127.726548762582"));
2092        assert_eq!(a / dec("0.000000001"), dec("123127726.548762582"));
2093        assert_eq!(a / dec("0.000000000001"), dec("123127726548.762582"));
2094        assert_eq!(a / dec("0.000000000000001"), dec("123127726548762.582"));
2095        assert_eq!(a / dec("0.000000000000000001"), dec("123127726548762582"));
2096        // negative
2097        let a = dec("-0.123127726548762582");
2098        assert_eq!(a / dec("1.0"), dec("-0.123127726548762582"));
2099        assert_eq!(a / dec("0.1"), dec("-1.23127726548762582"));
2100        assert_eq!(a / dec("0.01"), dec("-12.3127726548762582"));
2101        assert_eq!(a / dec("0.001"), dec("-123.127726548762582"));
2102        assert_eq!(a / dec("0.000001"), dec("-123127.726548762582"));
2103        assert_eq!(a / dec("0.000000001"), dec("-123127726.548762582"));
2104
2105        assert_eq!(
2106            SignedDecimal::percent(15) / SignedDecimal::percent(60),
2107            SignedDecimal::percent(25)
2108        );
2109
2110        // works for refs
2111        let a = SignedDecimal::percent(100);
2112        let b = SignedDecimal::percent(20);
2113        let expected = SignedDecimal::percent(500);
2114        assert_eq!(a / b, expected);
2115        assert_eq!(&a / b, expected);
2116        assert_eq!(a / &b, expected);
2117        assert_eq!(&a / &b, expected);
2118    }
2119
2120    #[test]
2121    fn signed_decimal_div_assign_works() {
2122        let mut a = SignedDecimal::percent(15);
2123        a /= SignedDecimal::percent(20);
2124        assert_eq!(a, SignedDecimal::percent(75));
2125
2126        // works for refs
2127        let mut a = SignedDecimal::percent(50);
2128        let b = SignedDecimal::percent(20);
2129        a /= &b;
2130        assert_eq!(a, SignedDecimal::percent(250));
2131    }
2132
2133    #[test]
2134    #[should_panic(expected = "Division failed - multiplication overflow")]
2135    fn signed_decimal_div_overflow_panics() {
2136        let _value = SignedDecimal::MAX / SignedDecimal::percent(10);
2137    }
2138
2139    #[test]
2140    #[should_panic(expected = "Division failed - denominator must not be zero")]
2141    fn signed_decimal_div_by_zero_panics() {
2142        let _value = SignedDecimal::one() / SignedDecimal::zero();
2143    }
2144
2145    #[test]
2146    fn signed_decimal_int128_division() {
2147        // a/b
2148        let left = SignedDecimal::percent(150); // 1.5
2149        let right = Int128::new(3);
2150        assert_eq!(left / right, SignedDecimal::percent(50));
2151
2152        // negative
2153        let left = SignedDecimal::percent(-150); // -1.5
2154        let right = Int128::new(3);
2155        assert_eq!(left / right, SignedDecimal::percent(-50));
2156
2157        // 0/a
2158        let left = SignedDecimal::zero();
2159        let right = Int128::new(300);
2160        assert_eq!(left / right, SignedDecimal::zero());
2161    }
2162
2163    #[test]
2164    #[should_panic]
2165    fn signed_decimal_int128_divide_by_zero() {
2166        let left = SignedDecimal::percent(150); // 1.5
2167        let right = Int128::new(0);
2168        let _result = left / right;
2169    }
2170
2171    #[test]
2172    fn signed_decimal_int128_div_assign() {
2173        // a/b
2174        let mut dec = SignedDecimal::percent(150); // 1.5
2175        dec /= Int128::new(3);
2176        assert_eq!(dec, SignedDecimal::percent(50));
2177
2178        // 0/a
2179        let mut dec = SignedDecimal::zero();
2180        dec /= Int128::new(300);
2181        assert_eq!(dec, SignedDecimal::zero());
2182    }
2183
2184    #[test]
2185    #[should_panic]
2186    fn signed_decimal_int128_div_assign_by_zero() {
2187        // a/0
2188        let mut dec = SignedDecimal::percent(50);
2189        dec /= Int128::new(0);
2190    }
2191
2192    #[test]
2193    fn signed_decimal_checked_pow() {
2194        for exp in 0..10 {
2195            assert_eq!(
2196                SignedDecimal::one().checked_pow(exp).unwrap(),
2197                SignedDecimal::one()
2198            );
2199        }
2200
2201        // This case is mathematically undefined but we ensure consistency with Rust standard types
2202        // https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=20df6716048e77087acd40194b233494
2203        assert_eq!(
2204            SignedDecimal::zero().checked_pow(0).unwrap(),
2205            SignedDecimal::one()
2206        );
2207
2208        for exp in 1..10 {
2209            assert_eq!(
2210                SignedDecimal::zero().checked_pow(exp).unwrap(),
2211                SignedDecimal::zero()
2212            );
2213        }
2214
2215        for exp in 1..10 {
2216            assert_eq!(
2217                SignedDecimal::negative_one().checked_pow(exp).unwrap(),
2218                // alternates between 1 and -1
2219                if exp % 2 == 0 {
2220                    SignedDecimal::one()
2221                } else {
2222                    SignedDecimal::negative_one()
2223                }
2224            )
2225        }
2226
2227        for num in &[
2228            SignedDecimal::percent(50),
2229            SignedDecimal::percent(99),
2230            SignedDecimal::percent(200),
2231        ] {
2232            assert_eq!(num.checked_pow(0).unwrap(), SignedDecimal::one())
2233        }
2234
2235        assert_eq!(
2236            SignedDecimal::percent(20).checked_pow(2).unwrap(),
2237            SignedDecimal::percent(4)
2238        );
2239
2240        assert_eq!(
2241            SignedDecimal::percent(20).checked_pow(3).unwrap(),
2242            SignedDecimal::permille(8)
2243        );
2244
2245        assert_eq!(
2246            SignedDecimal::percent(200).checked_pow(4).unwrap(),
2247            SignedDecimal::percent(1600)
2248        );
2249
2250        assert_eq!(
2251            SignedDecimal::percent(200).checked_pow(4).unwrap(),
2252            SignedDecimal::percent(1600)
2253        );
2254
2255        assert_eq!(
2256            SignedDecimal::percent(700).checked_pow(5).unwrap(),
2257            SignedDecimal::percent(1680700)
2258        );
2259
2260        assert_eq!(
2261            SignedDecimal::percent(700).checked_pow(8).unwrap(),
2262            SignedDecimal::percent(576480100)
2263        );
2264
2265        assert_eq!(
2266            SignedDecimal::percent(700).checked_pow(10).unwrap(),
2267            SignedDecimal::percent(28247524900)
2268        );
2269
2270        assert_eq!(
2271            SignedDecimal::percent(120).checked_pow(123).unwrap(),
2272            SignedDecimal(5486473221892422150877397607i128.into())
2273        );
2274
2275        assert_eq!(
2276            SignedDecimal::percent(10).checked_pow(2).unwrap(),
2277            SignedDecimal(10000000000000000i128.into())
2278        );
2279
2280        assert_eq!(
2281            SignedDecimal::percent(10).checked_pow(18).unwrap(),
2282            SignedDecimal(1i128.into())
2283        );
2284
2285        let decimals = [
2286            SignedDecimal::percent(-50),
2287            SignedDecimal::percent(-99),
2288            SignedDecimal::percent(-200),
2289        ];
2290        let exponents = [1, 2, 3, 4, 5, 8, 10];
2291
2292        for d in decimals {
2293            for e in exponents {
2294                // use multiplication as source of truth
2295                let mut mul = Ok(d);
2296                for _ in 1..e {
2297                    mul = mul.and_then(|mul| mul.checked_mul(d));
2298                }
2299                assert_eq!(mul, d.checked_pow(e));
2300            }
2301        }
2302    }
2303
2304    #[test]
2305    fn signed_decimal_checked_pow_overflow() {
2306        assert_eq!(
2307            SignedDecimal::MAX.checked_pow(2),
2308            Err(OverflowError::new(OverflowOperation::Pow))
2309        );
2310    }
2311
2312    #[test]
2313    fn signed_decimal_to_string() {
2314        // Integers
2315        assert_eq!(SignedDecimal::zero().to_string(), "0");
2316        assert_eq!(SignedDecimal::one().to_string(), "1");
2317        assert_eq!(SignedDecimal::percent(500).to_string(), "5");
2318        assert_eq!(SignedDecimal::percent(-500).to_string(), "-5");
2319
2320        // SignedDecimals
2321        assert_eq!(SignedDecimal::percent(125).to_string(), "1.25");
2322        assert_eq!(SignedDecimal::percent(42638).to_string(), "426.38");
2323        assert_eq!(SignedDecimal::percent(3).to_string(), "0.03");
2324        assert_eq!(SignedDecimal::permille(987).to_string(), "0.987");
2325        assert_eq!(SignedDecimal::percent(-125).to_string(), "-1.25");
2326        assert_eq!(SignedDecimal::percent(-42638).to_string(), "-426.38");
2327        assert_eq!(SignedDecimal::percent(-3).to_string(), "-0.03");
2328        assert_eq!(SignedDecimal::permille(-987).to_string(), "-0.987");
2329
2330        assert_eq!(
2331            SignedDecimal(Int128::from(1i128)).to_string(),
2332            "0.000000000000000001"
2333        );
2334        assert_eq!(
2335            SignedDecimal(Int128::from(10i128)).to_string(),
2336            "0.00000000000000001"
2337        );
2338        assert_eq!(
2339            SignedDecimal(Int128::from(100i128)).to_string(),
2340            "0.0000000000000001"
2341        );
2342        assert_eq!(
2343            SignedDecimal(Int128::from(1000i128)).to_string(),
2344            "0.000000000000001"
2345        );
2346        assert_eq!(
2347            SignedDecimal(Int128::from(10000i128)).to_string(),
2348            "0.00000000000001"
2349        );
2350        assert_eq!(
2351            SignedDecimal(Int128::from(100000i128)).to_string(),
2352            "0.0000000000001"
2353        );
2354        assert_eq!(
2355            SignedDecimal(Int128::from(1000000i128)).to_string(),
2356            "0.000000000001"
2357        );
2358        assert_eq!(
2359            SignedDecimal(Int128::from(10000000i128)).to_string(),
2360            "0.00000000001"
2361        );
2362        assert_eq!(
2363            SignedDecimal(Int128::from(100000000i128)).to_string(),
2364            "0.0000000001"
2365        );
2366        assert_eq!(
2367            SignedDecimal(Int128::from(1000000000i128)).to_string(),
2368            "0.000000001"
2369        );
2370        assert_eq!(
2371            SignedDecimal(Int128::from(10000000000i128)).to_string(),
2372            "0.00000001"
2373        );
2374        assert_eq!(
2375            SignedDecimal(Int128::from(100000000000i128)).to_string(),
2376            "0.0000001"
2377        );
2378        assert_eq!(
2379            SignedDecimal(Int128::from(10000000000000i128)).to_string(),
2380            "0.00001"
2381        );
2382        assert_eq!(
2383            SignedDecimal(Int128::from(100000000000000i128)).to_string(),
2384            "0.0001"
2385        );
2386        assert_eq!(
2387            SignedDecimal(Int128::from(1000000000000000i128)).to_string(),
2388            "0.001"
2389        );
2390        assert_eq!(
2391            SignedDecimal(Int128::from(10000000000000000i128)).to_string(),
2392            "0.01"
2393        );
2394        assert_eq!(
2395            SignedDecimal(Int128::from(100000000000000000i128)).to_string(),
2396            "0.1"
2397        );
2398        assert_eq!(
2399            SignedDecimal(Int128::from(-1i128)).to_string(),
2400            "-0.000000000000000001"
2401        );
2402        assert_eq!(
2403            SignedDecimal(Int128::from(-100000000000000i128)).to_string(),
2404            "-0.0001"
2405        );
2406        assert_eq!(
2407            SignedDecimal(Int128::from(-100000000000000000i128)).to_string(),
2408            "-0.1"
2409        );
2410    }
2411
2412    #[test]
2413    fn signed_decimal_iter_sum() {
2414        let items = vec![
2415            SignedDecimal::zero(),
2416            SignedDecimal(Int128::from(2i128)),
2417            SignedDecimal(Int128::from(2i128)),
2418            SignedDecimal(Int128::from(-2i128)),
2419        ];
2420        assert_eq!(
2421            items.iter().sum::<SignedDecimal>(),
2422            SignedDecimal(Int128::from(2i128))
2423        );
2424        assert_eq!(
2425            items.into_iter().sum::<SignedDecimal>(),
2426            SignedDecimal(Int128::from(2i128))
2427        );
2428
2429        let empty: Vec<SignedDecimal> = vec![];
2430        assert_eq!(SignedDecimal::zero(), empty.iter().sum::<SignedDecimal>());
2431    }
2432
2433    #[test]
2434    fn signed_decimal_serialize() {
2435        assert_eq!(
2436            serde_json::to_vec(&SignedDecimal::zero()).unwrap(),
2437            br#""0""#
2438        );
2439        assert_eq!(
2440            serde_json::to_vec(&SignedDecimal::one()).unwrap(),
2441            br#""1""#
2442        );
2443        assert_eq!(
2444            serde_json::to_vec(&SignedDecimal::percent(8)).unwrap(),
2445            br#""0.08""#
2446        );
2447        assert_eq!(
2448            serde_json::to_vec(&SignedDecimal::percent(87)).unwrap(),
2449            br#""0.87""#
2450        );
2451        assert_eq!(
2452            serde_json::to_vec(&SignedDecimal::percent(876)).unwrap(),
2453            br#""8.76""#
2454        );
2455        assert_eq!(
2456            serde_json::to_vec(&SignedDecimal::percent(8765)).unwrap(),
2457            br#""87.65""#
2458        );
2459        assert_eq!(
2460            serde_json::to_vec(&SignedDecimal::percent(-87654)).unwrap(),
2461            br#""-876.54""#
2462        );
2463        assert_eq!(
2464            serde_json::to_vec(&SignedDecimal::negative_one()).unwrap(),
2465            br#""-1""#
2466        );
2467        assert_eq!(
2468            serde_json::to_vec(&-SignedDecimal::percent(8)).unwrap(),
2469            br#""-0.08""#
2470        );
2471    }
2472
2473    #[test]
2474    fn signed_decimal_deserialize() {
2475        assert_eq!(
2476            serde_json::from_slice::<SignedDecimal>(br#""0""#).unwrap(),
2477            SignedDecimal::zero()
2478        );
2479        assert_eq!(
2480            serde_json::from_slice::<SignedDecimal>(br#""1""#).unwrap(),
2481            SignedDecimal::one()
2482        );
2483        assert_eq!(
2484            serde_json::from_slice::<SignedDecimal>(br#""000""#).unwrap(),
2485            SignedDecimal::zero()
2486        );
2487        assert_eq!(
2488            serde_json::from_slice::<SignedDecimal>(br#""001""#).unwrap(),
2489            SignedDecimal::one()
2490        );
2491
2492        assert_eq!(
2493            serde_json::from_slice::<SignedDecimal>(br#""0.08""#).unwrap(),
2494            SignedDecimal::percent(8)
2495        );
2496        assert_eq!(
2497            serde_json::from_slice::<SignedDecimal>(br#""0.87""#).unwrap(),
2498            SignedDecimal::percent(87)
2499        );
2500        assert_eq!(
2501            serde_json::from_slice::<SignedDecimal>(br#""8.76""#).unwrap(),
2502            SignedDecimal::percent(876)
2503        );
2504        assert_eq!(
2505            serde_json::from_slice::<SignedDecimal>(br#""87.65""#).unwrap(),
2506            SignedDecimal::percent(8765)
2507        );
2508
2509        // negative numbers
2510        assert_eq!(
2511            serde_json::from_slice::<SignedDecimal>(br#""-0""#).unwrap(),
2512            SignedDecimal::zero()
2513        );
2514        assert_eq!(
2515            serde_json::from_slice::<SignedDecimal>(br#""-1""#).unwrap(),
2516            SignedDecimal::negative_one()
2517        );
2518        assert_eq!(
2519            serde_json::from_slice::<SignedDecimal>(br#""-001""#).unwrap(),
2520            SignedDecimal::negative_one()
2521        );
2522        assert_eq!(
2523            serde_json::from_slice::<SignedDecimal>(br#""-0.08""#).unwrap(),
2524            SignedDecimal::percent(-8)
2525        );
2526    }
2527
2528    #[test]
2529    fn signed_decimal_abs_diff_works() {
2530        let a = SignedDecimal::percent(285);
2531        let b = SignedDecimal::percent(200);
2532        let expected = Decimal::percent(85);
2533        assert_eq!(a.abs_diff(b), expected);
2534        assert_eq!(b.abs_diff(a), expected);
2535
2536        let a = SignedDecimal::percent(-200);
2537        let b = SignedDecimal::percent(200);
2538        let expected = Decimal::percent(400);
2539        assert_eq!(a.abs_diff(b), expected);
2540        assert_eq!(b.abs_diff(a), expected);
2541
2542        let a = SignedDecimal::percent(-200);
2543        let b = SignedDecimal::percent(-240);
2544        let expected = Decimal::percent(40);
2545        assert_eq!(a.abs_diff(b), expected);
2546        assert_eq!(b.abs_diff(a), expected);
2547    }
2548
2549    #[test]
2550    #[allow(clippy::op_ref)]
2551    fn signed_decimal_rem_works() {
2552        // 4.02 % 1.11 = 0.69
2553        assert_eq!(
2554            SignedDecimal::percent(402) % SignedDecimal::percent(111),
2555            SignedDecimal::percent(69)
2556        );
2557
2558        // 15.25 % 4 = 3.25
2559        assert_eq!(
2560            SignedDecimal::percent(1525) % SignedDecimal::percent(400),
2561            SignedDecimal::percent(325)
2562        );
2563
2564        // -20.25 % 5 = -25
2565        assert_eq!(
2566            SignedDecimal::percent(-2025) % SignedDecimal::percent(500),
2567            SignedDecimal::percent(-25)
2568        );
2569
2570        let a = SignedDecimal::percent(318);
2571        let b = SignedDecimal::percent(317);
2572        let expected = SignedDecimal::percent(1);
2573        assert_eq!(a % b, expected);
2574        assert_eq!(a % &b, expected);
2575        assert_eq!(&a % b, expected);
2576        assert_eq!(&a % &b, expected);
2577    }
2578
2579    #[test]
2580    fn signed_decimal_rem_assign_works() {
2581        let mut a = SignedDecimal::percent(17673);
2582        a %= SignedDecimal::percent(2362);
2583        assert_eq!(a, SignedDecimal::percent(1139)); // 176.73 % 23.62 = 11.39
2584
2585        let mut a = SignedDecimal::percent(4262);
2586        let b = SignedDecimal::percent(1270);
2587        a %= &b;
2588        assert_eq!(a, SignedDecimal::percent(452)); // 42.62 % 12.7 = 4.52
2589
2590        let mut a = SignedDecimal::percent(-4262);
2591        let b = SignedDecimal::percent(1270);
2592        a %= &b;
2593        assert_eq!(a, SignedDecimal::percent(-452)); // -42.62 % 12.7 = -4.52
2594    }
2595
2596    #[test]
2597    #[should_panic(expected = "divisor of zero")]
2598    fn signed_decimal_rem_panics_for_zero() {
2599        let _ = SignedDecimal::percent(777) % SignedDecimal::zero();
2600    }
2601
2602    #[test]
2603    fn signed_decimal_checked_methods() {
2604        // checked add
2605        assert_eq!(
2606            SignedDecimal::percent(402)
2607                .checked_add(SignedDecimal::percent(111))
2608                .unwrap(),
2609            SignedDecimal::percent(513)
2610        );
2611        assert!(matches!(
2612            SignedDecimal::MAX.checked_add(SignedDecimal::percent(1)),
2613            Err(OverflowError { .. })
2614        ));
2615        assert!(matches!(
2616            SignedDecimal::MIN.checked_add(SignedDecimal::percent(-1)),
2617            Err(OverflowError { .. })
2618        ));
2619
2620        // checked sub
2621        assert_eq!(
2622            SignedDecimal::percent(1111)
2623                .checked_sub(SignedDecimal::percent(111))
2624                .unwrap(),
2625            SignedDecimal::percent(1000)
2626        );
2627        assert_eq!(
2628            SignedDecimal::zero()
2629                .checked_sub(SignedDecimal::percent(1))
2630                .unwrap(),
2631            SignedDecimal::percent(-1)
2632        );
2633        assert!(matches!(
2634            SignedDecimal::MIN.checked_sub(SignedDecimal::percent(1)),
2635            Err(OverflowError { .. })
2636        ));
2637        assert!(matches!(
2638            SignedDecimal::MAX.checked_sub(SignedDecimal::percent(-1)),
2639            Err(OverflowError { .. })
2640        ));
2641
2642        // checked div
2643        assert_eq!(
2644            SignedDecimal::percent(30)
2645                .checked_div(SignedDecimal::percent(200))
2646                .unwrap(),
2647            SignedDecimal::percent(15)
2648        );
2649        assert_eq!(
2650            SignedDecimal::percent(88)
2651                .checked_div(SignedDecimal::percent(20))
2652                .unwrap(),
2653            SignedDecimal::percent(440)
2654        );
2655        assert!(matches!(
2656            SignedDecimal::MAX.checked_div(SignedDecimal::zero()),
2657            Err(CheckedFromRatioError::DivideByZero)
2658        ));
2659        assert!(matches!(
2660            SignedDecimal::MAX.checked_div(SignedDecimal::percent(1)),
2661            Err(CheckedFromRatioError::Overflow)
2662        ));
2663        assert_eq!(
2664            SignedDecimal::percent(-88)
2665                .checked_div(SignedDecimal::percent(20))
2666                .unwrap(),
2667            SignedDecimal::percent(-440)
2668        );
2669        assert_eq!(
2670            SignedDecimal::percent(-88)
2671                .checked_div(SignedDecimal::percent(-20))
2672                .unwrap(),
2673            SignedDecimal::percent(440)
2674        );
2675
2676        // checked rem
2677        assert_eq!(
2678            SignedDecimal::percent(402)
2679                .checked_rem(SignedDecimal::percent(111))
2680                .unwrap(),
2681            SignedDecimal::percent(69)
2682        );
2683        assert_eq!(
2684            SignedDecimal::percent(1525)
2685                .checked_rem(SignedDecimal::percent(400))
2686                .unwrap(),
2687            SignedDecimal::percent(325)
2688        );
2689        assert_eq!(
2690            SignedDecimal::percent(-1525)
2691                .checked_rem(SignedDecimal::percent(400))
2692                .unwrap(),
2693            SignedDecimal::percent(-325)
2694        );
2695        assert_eq!(
2696            SignedDecimal::percent(-1525)
2697                .checked_rem(SignedDecimal::percent(-400))
2698                .unwrap(),
2699            SignedDecimal::percent(-325)
2700        );
2701        assert!(matches!(
2702            SignedDecimal::MAX.checked_rem(SignedDecimal::zero()),
2703            Err(DivideByZeroError { .. })
2704        ));
2705    }
2706
2707    #[test]
2708    fn signed_decimal_pow_works() {
2709        assert_eq!(
2710            SignedDecimal::percent(200).pow(2),
2711            SignedDecimal::percent(400)
2712        );
2713        assert_eq!(
2714            SignedDecimal::percent(-200).pow(2),
2715            SignedDecimal::percent(400)
2716        );
2717        assert_eq!(
2718            SignedDecimal::percent(-200).pow(3),
2719            SignedDecimal::percent(-800)
2720        );
2721        assert_eq!(
2722            SignedDecimal::percent(200).pow(10),
2723            SignedDecimal::percent(102400)
2724        );
2725    }
2726
2727    #[test]
2728    #[should_panic]
2729    fn signed_decimal_pow_overflow_panics() {
2730        _ = SignedDecimal::MAX.pow(2u32);
2731    }
2732
2733    #[test]
2734    fn signed_decimal_saturating_works() {
2735        assert_eq!(
2736            SignedDecimal::percent(200).saturating_add(SignedDecimal::percent(200)),
2737            SignedDecimal::percent(400)
2738        );
2739        assert_eq!(
2740            SignedDecimal::percent(-200).saturating_add(SignedDecimal::percent(200)),
2741            SignedDecimal::zero()
2742        );
2743        assert_eq!(
2744            SignedDecimal::percent(-200).saturating_add(SignedDecimal::percent(-200)),
2745            SignedDecimal::percent(-400)
2746        );
2747        assert_eq!(
2748            SignedDecimal::MAX.saturating_add(SignedDecimal::percent(200)),
2749            SignedDecimal::MAX
2750        );
2751        assert_eq!(
2752            SignedDecimal::MIN.saturating_add(SignedDecimal::percent(-1)),
2753            SignedDecimal::MIN
2754        );
2755        assert_eq!(
2756            SignedDecimal::percent(200).saturating_sub(SignedDecimal::percent(100)),
2757            SignedDecimal::percent(100)
2758        );
2759        assert_eq!(
2760            SignedDecimal::percent(-200).saturating_sub(SignedDecimal::percent(100)),
2761            SignedDecimal::percent(-300)
2762        );
2763        assert_eq!(
2764            SignedDecimal::percent(-200).saturating_sub(SignedDecimal::percent(-100)),
2765            SignedDecimal::percent(-100)
2766        );
2767        assert_eq!(
2768            SignedDecimal::zero().saturating_sub(SignedDecimal::percent(200)),
2769            SignedDecimal::from_str("-2").unwrap()
2770        );
2771        assert_eq!(
2772            SignedDecimal::MIN.saturating_sub(SignedDecimal::percent(200)),
2773            SignedDecimal::MIN
2774        );
2775        assert_eq!(
2776            SignedDecimal::MAX.saturating_sub(SignedDecimal::percent(-200)),
2777            SignedDecimal::MAX
2778        );
2779        assert_eq!(
2780            SignedDecimal::percent(200).saturating_mul(SignedDecimal::percent(50)),
2781            SignedDecimal::percent(100)
2782        );
2783        assert_eq!(
2784            SignedDecimal::percent(-200).saturating_mul(SignedDecimal::percent(50)),
2785            SignedDecimal::percent(-100)
2786        );
2787        assert_eq!(
2788            SignedDecimal::percent(-200).saturating_mul(SignedDecimal::percent(-50)),
2789            SignedDecimal::percent(100)
2790        );
2791        assert_eq!(
2792            SignedDecimal::MAX.saturating_mul(SignedDecimal::percent(200)),
2793            SignedDecimal::MAX
2794        );
2795        assert_eq!(
2796            SignedDecimal::MIN.saturating_mul(SignedDecimal::percent(200)),
2797            SignedDecimal::MIN
2798        );
2799        assert_eq!(
2800            SignedDecimal::MIN.saturating_mul(SignedDecimal::percent(-200)),
2801            SignedDecimal::MAX
2802        );
2803        assert_eq!(
2804            SignedDecimal::percent(400).saturating_pow(2u32),
2805            SignedDecimal::percent(1600)
2806        );
2807        assert_eq!(SignedDecimal::MAX.saturating_pow(2u32), SignedDecimal::MAX);
2808        assert_eq!(SignedDecimal::MAX.saturating_pow(3u32), SignedDecimal::MAX);
2809        assert_eq!(SignedDecimal::MIN.saturating_pow(2u32), SignedDecimal::MAX);
2810        assert_eq!(SignedDecimal::MIN.saturating_pow(3u32), SignedDecimal::MIN);
2811    }
2812
2813    #[test]
2814    fn signed_decimal_rounding() {
2815        assert_eq!(SignedDecimal::one().floor(), SignedDecimal::one());
2816        assert_eq!(SignedDecimal::percent(150).floor(), SignedDecimal::one());
2817        assert_eq!(SignedDecimal::percent(199).floor(), SignedDecimal::one());
2818        assert_eq!(
2819            SignedDecimal::percent(200).floor(),
2820            SignedDecimal::percent(200)
2821        );
2822        assert_eq!(SignedDecimal::percent(99).floor(), SignedDecimal::zero());
2823        assert_eq!(
2824            SignedDecimal(Int128::from(1i128)).floor(),
2825            SignedDecimal::zero()
2826        );
2827        assert_eq!(
2828            SignedDecimal(Int128::from(-1i128)).floor(),
2829            SignedDecimal::negative_one()
2830        );
2831        assert_eq!(
2832            SignedDecimal::permille(-1234).floor(),
2833            SignedDecimal::percent(-200)
2834        );
2835
2836        assert_eq!(SignedDecimal::one().ceil(), SignedDecimal::one());
2837        assert_eq!(
2838            SignedDecimal::percent(150).ceil(),
2839            SignedDecimal::percent(200)
2840        );
2841        assert_eq!(
2842            SignedDecimal::percent(199).ceil(),
2843            SignedDecimal::percent(200)
2844        );
2845        assert_eq!(SignedDecimal::percent(99).ceil(), SignedDecimal::one());
2846        assert_eq!(
2847            SignedDecimal(Int128::from(1i128)).ceil(),
2848            SignedDecimal::one()
2849        );
2850        assert_eq!(
2851            SignedDecimal(Int128::from(-1i128)).ceil(),
2852            SignedDecimal::zero()
2853        );
2854        assert_eq!(
2855            SignedDecimal::permille(-1234).ceil(),
2856            SignedDecimal::negative_one()
2857        );
2858
2859        assert_eq!(SignedDecimal::one().trunc(), SignedDecimal::one());
2860        assert_eq!(SignedDecimal::percent(150).trunc(), SignedDecimal::one());
2861        assert_eq!(SignedDecimal::percent(199).trunc(), SignedDecimal::one());
2862        assert_eq!(
2863            SignedDecimal::percent(200).trunc(),
2864            SignedDecimal::percent(200)
2865        );
2866        assert_eq!(SignedDecimal::percent(99).trunc(), SignedDecimal::zero());
2867        assert_eq!(
2868            SignedDecimal(Int128::from(1i128)).trunc(),
2869            SignedDecimal::zero()
2870        );
2871        assert_eq!(
2872            SignedDecimal(Int128::from(-1i128)).trunc(),
2873            SignedDecimal::zero()
2874        );
2875        assert_eq!(
2876            SignedDecimal::permille(-1234).trunc(),
2877            SignedDecimal::negative_one()
2878        );
2879    }
2880
2881    #[test]
2882    #[should_panic(expected = "attempt to ceil with overflow")]
2883    fn signed_decimal_ceil_panics() {
2884        let _ = SignedDecimal::MAX.ceil();
2885    }
2886
2887    #[test]
2888    #[should_panic(expected = "attempt to floor with overflow")]
2889    fn signed_decimal_floor_panics() {
2890        let _ = SignedDecimal::MIN.floor();
2891    }
2892
2893    #[test]
2894    fn signed_decimal_checked_ceil() {
2895        assert_eq!(
2896            SignedDecimal::percent(199).checked_ceil(),
2897            Ok(SignedDecimal::percent(200))
2898        );
2899        assert_eq!(SignedDecimal::MAX.checked_ceil(), Err(RoundUpOverflowError));
2900    }
2901
2902    #[test]
2903    fn signed_decimal_checked_floor() {
2904        assert_eq!(
2905            SignedDecimal::percent(199).checked_floor(),
2906            Ok(SignedDecimal::one())
2907        );
2908        assert_eq!(
2909            SignedDecimal::percent(-199).checked_floor(),
2910            Ok(SignedDecimal::percent(-200))
2911        );
2912        assert_eq!(
2913            SignedDecimal::MIN.checked_floor(),
2914            Err(RoundDownOverflowError)
2915        );
2916        assert_eq!(
2917            SignedDecimal::negative_one().checked_floor(),
2918            Ok(SignedDecimal::negative_one())
2919        );
2920    }
2921
2922    #[test]
2923    fn signed_decimal_to_int_floor_works() {
2924        let d = SignedDecimal::from_str("12.000000000000000001").unwrap();
2925        assert_eq!(d.to_int_floor(), Int128::new(12));
2926        let d = SignedDecimal::from_str("12.345").unwrap();
2927        assert_eq!(d.to_int_floor(), Int128::new(12));
2928        let d = SignedDecimal::from_str("12.999").unwrap();
2929        assert_eq!(d.to_int_floor(), Int128::new(12));
2930        let d = SignedDecimal::from_str("0.98451384").unwrap();
2931        assert_eq!(d.to_int_floor(), Int128::new(0));
2932        let d = SignedDecimal::from_str("-12.000000000000000001").unwrap();
2933        assert_eq!(d.to_int_floor(), Int128::new(-13));
2934        let d = SignedDecimal::from_str("-12.345").unwrap();
2935        assert_eq!(d.to_int_floor(), Int128::new(-13));
2936        let d = SignedDecimal::from_str("75.0").unwrap();
2937        assert_eq!(d.to_int_floor(), Int128::new(75));
2938        let d = SignedDecimal::from_str("0.0001").unwrap();
2939        assert_eq!(d.to_int_floor(), Int128::new(0));
2940        let d = SignedDecimal::from_str("0.0").unwrap();
2941        assert_eq!(d.to_int_floor(), Int128::new(0));
2942        let d = SignedDecimal::from_str("-0.0").unwrap();
2943        assert_eq!(d.to_int_floor(), Int128::new(0));
2944        let d = SignedDecimal::from_str("-0.0001").unwrap();
2945        assert_eq!(d.to_int_floor(), Int128::new(-1));
2946        let d = SignedDecimal::from_str("-75.0").unwrap();
2947        assert_eq!(d.to_int_floor(), Int128::new(-75));
2948        let d = SignedDecimal::MAX;
2949        assert_eq!(d.to_int_floor(), Int128::new(170141183460469231731));
2950        let d = SignedDecimal::MIN;
2951        assert_eq!(d.to_int_floor(), Int128::new(-170141183460469231732));
2952    }
2953
2954    #[test]
2955    fn signed_decimal_to_int_ceil_works() {
2956        let d = SignedDecimal::from_str("12.000000000000000001").unwrap();
2957        assert_eq!(d.to_int_ceil(), Int128::new(13));
2958        let d = SignedDecimal::from_str("12.345").unwrap();
2959        assert_eq!(d.to_int_ceil(), Int128::new(13));
2960        let d = SignedDecimal::from_str("12.999").unwrap();
2961        assert_eq!(d.to_int_ceil(), Int128::new(13));
2962        let d = SignedDecimal::from_str("-12.000000000000000001").unwrap();
2963        assert_eq!(d.to_int_ceil(), Int128::new(-12));
2964        let d = SignedDecimal::from_str("-12.345").unwrap();
2965        assert_eq!(d.to_int_ceil(), Int128::new(-12));
2966
2967        let d = SignedDecimal::from_str("75.0").unwrap();
2968        assert_eq!(d.to_int_ceil(), Int128::new(75));
2969        let d = SignedDecimal::from_str("0.0").unwrap();
2970        assert_eq!(d.to_int_ceil(), Int128::new(0));
2971        let d = SignedDecimal::from_str("-75.0").unwrap();
2972        assert_eq!(d.to_int_ceil(), Int128::new(-75));
2973
2974        let d = SignedDecimal::MAX;
2975        assert_eq!(d.to_int_ceil(), Int128::new(170141183460469231732));
2976        let d = SignedDecimal::MIN;
2977        assert_eq!(d.to_int_ceil(), Int128::new(-170141183460469231731));
2978    }
2979
2980    #[test]
2981    fn signed_decimal_to_int_trunc_works() {
2982        let d = SignedDecimal::from_str("12.000000000000000001").unwrap();
2983        assert_eq!(d.to_int_trunc(), Int128::new(12));
2984        let d = SignedDecimal::from_str("12.345").unwrap();
2985        assert_eq!(d.to_int_trunc(), Int128::new(12));
2986        let d = SignedDecimal::from_str("12.999").unwrap();
2987        assert_eq!(d.to_int_trunc(), Int128::new(12));
2988        let d = SignedDecimal::from_str("-12.000000000000000001").unwrap();
2989        assert_eq!(d.to_int_trunc(), Int128::new(-12));
2990        let d = SignedDecimal::from_str("-12.345").unwrap();
2991        assert_eq!(d.to_int_trunc(), Int128::new(-12));
2992
2993        let d = SignedDecimal::from_str("75.0").unwrap();
2994        assert_eq!(d.to_int_trunc(), Int128::new(75));
2995        let d = SignedDecimal::from_str("0.0").unwrap();
2996        assert_eq!(d.to_int_trunc(), Int128::new(0));
2997        let d = SignedDecimal::from_str("-75.0").unwrap();
2998        assert_eq!(d.to_int_trunc(), Int128::new(-75));
2999
3000        let d = SignedDecimal::MAX;
3001        assert_eq!(d.to_int_trunc(), Int128::new(170141183460469231731));
3002        let d = SignedDecimal::MIN;
3003        assert_eq!(d.to_int_trunc(), Int128::new(-170141183460469231731));
3004    }
3005
3006    #[test]
3007    fn signed_decimal_neg_works() {
3008        assert_eq!(-SignedDecimal::percent(50), SignedDecimal::percent(-50));
3009        assert_eq!(-SignedDecimal::one(), SignedDecimal::negative_one());
3010    }
3011
3012    #[test]
3013    fn signed_decimal_partial_eq() {
3014        let test_cases = [
3015            ("1", "1", true),
3016            ("0.5", "0.5", true),
3017            ("0.5", "0.51", false),
3018            ("0", "0.00000", true),
3019            ("-1", "-1", true),
3020            ("-0.5", "-0.5", true),
3021            ("-0.5", "0.5", false),
3022            ("-0.5", "-0.51", false),
3023            ("-0", "-0.00000", true),
3024        ]
3025        .into_iter()
3026        .map(|(lhs, rhs, expected)| (dec(lhs), dec(rhs), expected));
3027
3028        #[allow(clippy::op_ref)]
3029        for (lhs, rhs, expected) in test_cases {
3030            assert_eq!(lhs == rhs, expected);
3031            assert_eq!(&lhs == rhs, expected);
3032            assert_eq!(lhs == &rhs, expected);
3033            assert_eq!(&lhs == &rhs, expected);
3034        }
3035    }
3036
3037    #[test]
3038    fn signed_decimal_implements_debug() {
3039        let decimal = SignedDecimal::from_str("123.45").unwrap();
3040        assert_eq!(format!("{decimal:?}"), "SignedDecimal(123.45)");
3041
3042        let test_cases = ["5", "5.01", "42", "0", "2", "-0.000001"];
3043        for s in test_cases {
3044            let decimal = SignedDecimal::from_str(s).unwrap();
3045            let expected = format!("SignedDecimal({s})");
3046            assert_eq!(format!("{decimal:?}"), expected);
3047        }
3048    }
3049
3050    #[test]
3051    fn signed_decimal_can_be_instantiated_from_decimal256() {
3052        let d: SignedDecimal = Decimal256::zero().try_into().unwrap();
3053        assert_eq!(d, SignedDecimal::zero());
3054    }
3055
3056    #[test]
3057    fn signed_decimal_may_fail_when_instantiated_from_decimal256() {
3058        let err = <Decimal256 as TryInto<SignedDecimal>>::try_into(Decimal256::MAX).unwrap_err();
3059        assert_eq!("SignedDecimalRangeExceeded", format!("{err:?}"));
3060        assert_eq!("SignedDecimal range exceeded", format!("{err}"));
3061    }
3062
3063    #[test]
3064    fn signed_decimal_can_be_serialized_and_deserialized() {
3065        // properly deserialized
3066        let value: SignedDecimal = serde_json::from_str(r#""123""#).unwrap();
3067        assert_eq!(SignedDecimal::from_str("123").unwrap(), value);
3068
3069        // properly serialized
3070        let value = SignedDecimal::from_str("456").unwrap();
3071        assert_eq!(r#""456""#, serde_json::to_string(&value).unwrap());
3072
3073        // invalid: not a string encoded decimal
3074        assert_eq!(
3075            "invalid type: integer `123`, expected string-encoded decimal at line 1 column 3",
3076            serde_json::from_str::<SignedDecimal>("123")
3077                .err()
3078                .unwrap()
3079                .to_string()
3080        );
3081
3082        // invalid: not properly defined signed decimal value
3083        assert_eq!(
3084            "Error parsing decimal '1.e': kind: Parsing, error: invalid digit found in string at line 1 column 5",
3085            serde_json::from_str::<SignedDecimal>(r#""1.e""#)
3086                .err()
3087                .unwrap()
3088                .to_string()
3089        );
3090    }
3091
3092    #[test]
3093    fn signed_decimal_has_defined_json_schema() {
3094        let schema = schemars::schema_for!(SignedDecimal);
3095        assert_eq!(
3096            "SignedDecimal",
3097            schema.schema.metadata.unwrap().title.unwrap()
3098        );
3099    }
3100}