rust_decimal/
decimal.rs

1use crate::constants::{
2    MAX_I128_REPR, MAX_SCALE_U32, POWERS_10, SCALE_MASK, SCALE_SHIFT, SIGN_MASK, SIGN_SHIFT, U32_MASK, U8_MASK,
3    UNSIGN_MASK,
4};
5use crate::ops;
6use crate::Error;
7use core::{
8    cmp::{Ordering::Equal, *},
9    fmt,
10    hash::{Hash, Hasher},
11    iter::{Product, Sum},
12    ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Rem, RemAssign, Sub, SubAssign},
13    str::FromStr,
14};
15
16// Diesel configuration
17#[cfg(feature = "diesel")]
18use diesel::{deserialize::FromSqlRow, expression::AsExpression, sql_types::Numeric};
19
20#[allow(unused_imports)] // It's not actually dead code below, but the compiler thinks it is.
21#[cfg(not(feature = "std"))]
22use num_traits::float::FloatCore;
23use num_traits::{FromPrimitive, Num, One, Signed, ToPrimitive, Zero};
24#[cfg(feature = "rkyv")]
25use rkyv::{Archive, Deserialize, Serialize};
26
27/// The smallest value that can be represented by this decimal type.
28const MIN: Decimal = Decimal {
29    flags: 2_147_483_648,
30    lo: 4_294_967_295,
31    mid: 4_294_967_295,
32    hi: 4_294_967_295,
33};
34
35/// The largest value that can be represented by this decimal type.
36const MAX: Decimal = Decimal {
37    flags: 0,
38    lo: 4_294_967_295,
39    mid: 4_294_967_295,
40    hi: 4_294_967_295,
41};
42
43const ZERO: Decimal = Decimal {
44    flags: 0,
45    lo: 0,
46    mid: 0,
47    hi: 0,
48};
49const ONE: Decimal = Decimal {
50    flags: 0,
51    lo: 1,
52    mid: 0,
53    hi: 0,
54};
55const TWO: Decimal = Decimal {
56    flags: 0,
57    lo: 2,
58    mid: 0,
59    hi: 0,
60};
61const TEN: Decimal = Decimal {
62    flags: 0,
63    lo: 10,
64    mid: 0,
65    hi: 0,
66};
67const ONE_HUNDRED: Decimal = Decimal {
68    flags: 0,
69    lo: 100,
70    mid: 0,
71    hi: 0,
72};
73const ONE_THOUSAND: Decimal = Decimal {
74    flags: 0,
75    lo: 1000,
76    mid: 0,
77    hi: 0,
78};
79const NEGATIVE_ONE: Decimal = Decimal {
80    flags: 2147483648,
81    lo: 1,
82    mid: 0,
83    hi: 0,
84};
85
86/// `UnpackedDecimal` contains unpacked representation of `Decimal` where each component
87/// of decimal-format stored in it's own field
88#[derive(Clone, Copy, Debug, PartialEq)]
89pub struct UnpackedDecimal {
90    pub negative: bool,
91    pub scale: u32,
92    pub hi: u32,
93    pub mid: u32,
94    pub lo: u32,
95}
96
97/// `Decimal` represents a 128 bit representation of a fixed-precision decimal number.
98/// The finite set of values of type `Decimal` are of the form m / 10<sup>e</sup>,
99/// where m is an integer such that -2<sup>96</sup> < m < 2<sup>96</sup>, and e is an integer
100/// between 0 and 28 inclusive.
101#[derive(Clone, Copy)]
102#[cfg_attr(feature = "diesel", derive(FromSqlRow, AsExpression), diesel(sql_type = Numeric))]
103#[cfg_attr(feature = "c-repr", repr(C))]
104#[cfg_attr(
105    feature = "borsh",
106    derive(borsh::BorshDeserialize, borsh::BorshSerialize, borsh::BorshSchema)
107)]
108#[cfg_attr(
109    feature = "rkyv",
110    derive(Archive, Deserialize, Serialize),
111    archive(compare(PartialEq)),
112    archive_attr(derive(Clone, Copy, Debug))
113)]
114#[cfg_attr(feature = "rkyv-safe", archive(check_bytes))]
115pub struct Decimal {
116    // Bits 0-15: unused
117    // Bits 16-23: Contains "e", a value between 0-28 that indicates the scale
118    // Bits 24-30: unused
119    // Bit 31: the sign of the Decimal value, 0 meaning positive and 1 meaning negative.
120    flags: u32,
121    // The lo, mid, hi, and flags fields contain the representation of the
122    // Decimal value as a 96-bit integer.
123    hi: u32,
124    lo: u32,
125    mid: u32,
126}
127
128#[cfg(feature = "ndarray")]
129impl ndarray::ScalarOperand for Decimal {}
130
131/// `RoundingStrategy` represents the different rounding strategies that can be used by
132/// `round_dp_with_strategy`.
133#[derive(Clone, Copy, PartialEq, Eq, Debug)]
134pub enum RoundingStrategy {
135    /// When a number is halfway between two others, it is rounded toward the nearest even number.
136    /// Also known as "Bankers Rounding".
137    /// e.g.
138    /// 6.5 -> 6, 7.5 -> 8
139    MidpointNearestEven,
140    /// When a number is halfway between two others, it is rounded toward the nearest number that
141    /// is away from zero. e.g. 6.4 -> 6, 6.5 -> 7, -6.5 -> -7
142    MidpointAwayFromZero,
143    /// When a number is halfway between two others, it is rounded toward the nearest number that
144    /// is toward zero. e.g. 6.4 -> 6, 6.5 -> 6, -6.5 -> -6
145    MidpointTowardZero,
146    /// The number is always rounded toward zero. e.g. -6.8 -> -6, 6.8 -> 6
147    ToZero,
148    /// The number is always rounded away from zero. e.g. -6.8 -> -7, 6.8 -> 7
149    AwayFromZero,
150    /// The number is always rounded towards negative infinity. e.g. 6.8 -> 6, -6.8 -> -7
151    ToNegativeInfinity,
152    /// The number is always rounded towards positive infinity. e.g. 6.8 -> 7, -6.8 -> -6
153    ToPositiveInfinity,
154
155    /// When a number is halfway between two others, it is rounded toward the nearest even number.
156    /// e.g.
157    /// 6.5 -> 6, 7.5 -> 8
158    #[deprecated(since = "1.11.0", note = "Please use RoundingStrategy::MidpointNearestEven instead")]
159    BankersRounding,
160    /// Rounds up if the value >= 5, otherwise rounds down, e.g. 6.5 -> 7
161    #[deprecated(since = "1.11.0", note = "Please use RoundingStrategy::MidpointAwayFromZero instead")]
162    RoundHalfUp,
163    /// Rounds down if the value =< 5, otherwise rounds up, e.g. 6.5 -> 6, 6.51 -> 7 1.4999999 -> 1
164    #[deprecated(since = "1.11.0", note = "Please use RoundingStrategy::MidpointTowardZero instead")]
165    RoundHalfDown,
166    /// Always round down.
167    #[deprecated(since = "1.11.0", note = "Please use RoundingStrategy::ToZero instead")]
168    RoundDown,
169    /// Always round up.
170    #[deprecated(since = "1.11.0", note = "Please use RoundingStrategy::AwayFromZero instead")]
171    RoundUp,
172}
173
174#[allow(dead_code)]
175impl Decimal {
176    /// The smallest value that can be represented by this decimal type.
177    ///
178    /// # Examples
179    ///
180    /// Basic usage:
181    /// ```
182    /// # use rust_decimal::Decimal;
183    /// # use rust_decimal_macros::dec;
184    /// assert_eq!(Decimal::MIN, dec!(-79_228_162_514_264_337_593_543_950_335));
185    /// ```
186    pub const MIN: Decimal = MIN;
187    /// The largest value that can be represented by this decimal type.
188    ///
189    /// # Examples
190    ///
191    /// Basic usage:
192    /// ```
193    /// # use rust_decimal::Decimal;
194    /// # use rust_decimal_macros::dec;
195    /// assert_eq!(Decimal::MAX, dec!(79_228_162_514_264_337_593_543_950_335));
196    /// ```
197    pub const MAX: Decimal = MAX;
198    /// A constant representing 0.
199    ///
200    /// # Examples
201    ///
202    /// Basic usage:
203    /// ```
204    /// # use rust_decimal::Decimal;
205    /// # use rust_decimal_macros::dec;
206    /// assert_eq!(Decimal::ZERO, dec!(0));
207    /// ```
208    pub const ZERO: Decimal = ZERO;
209    /// A constant representing 1.
210    ///
211    /// # Examples
212    ///
213    /// Basic usage:
214    /// ```
215    /// # use rust_decimal::Decimal;
216    /// # use rust_decimal_macros::dec;
217    /// assert_eq!(Decimal::ONE, dec!(1));
218    /// ```
219    pub const ONE: Decimal = ONE;
220    /// A constant representing -1.
221    ///
222    /// # Examples
223    ///
224    /// Basic usage:
225    /// ```
226    /// # use rust_decimal::Decimal;
227    /// # use rust_decimal_macros::dec;
228    /// assert_eq!(Decimal::NEGATIVE_ONE, dec!(-1));
229    /// ```
230    pub const NEGATIVE_ONE: Decimal = NEGATIVE_ONE;
231    /// A constant representing 2.
232    ///
233    /// # Examples
234    ///
235    /// Basic usage:
236    /// ```
237    /// # use rust_decimal::Decimal;
238    /// # use rust_decimal_macros::dec;
239    /// assert_eq!(Decimal::TWO, dec!(2));
240    /// ```
241    pub const TWO: Decimal = TWO;
242    /// A constant representing 10.
243    ///
244    /// # Examples
245    ///
246    /// Basic usage:
247    /// ```
248    /// # use rust_decimal::Decimal;
249    /// # use rust_decimal_macros::dec;
250    /// assert_eq!(Decimal::TEN, dec!(10));
251    /// ```
252    pub const TEN: Decimal = TEN;
253    /// A constant representing 100.
254    ///
255    /// # Examples
256    ///
257    /// Basic usage:
258    /// ```
259    /// # use rust_decimal::Decimal;
260    /// # use rust_decimal_macros::dec;
261    /// assert_eq!(Decimal::ONE_HUNDRED, dec!(100));
262    /// ```
263    pub const ONE_HUNDRED: Decimal = ONE_HUNDRED;
264    /// A constant representing 1000.
265    ///
266    /// # Examples
267    ///
268    /// Basic usage:
269    /// ```
270    /// # use rust_decimal::Decimal;
271    /// # use rust_decimal_macros::dec;
272    /// assert_eq!(Decimal::ONE_THOUSAND, dec!(1000));
273    /// ```
274    pub const ONE_THOUSAND: Decimal = ONE_THOUSAND;
275    /// The maximum supported scale value.
276    ///
277    /// Some operations, such as [`Self::rescale`] may accept larger scale values, but  these
278    /// operations will result in a final value with a scale no larger than this.
279    ///
280    /// Note that the maximum scale is _not_ the same as the maximum possible numeric precision in
281    /// base-10.
282    pub const MAX_SCALE: u32 = MAX_SCALE_U32;
283
284    /// A constant representing π as 3.1415926535897932384626433833
285    ///
286    /// # Examples
287    ///
288    /// Basic usage:
289    /// ```
290    /// # use rust_decimal::Decimal;
291    /// # use rust_decimal_macros::dec;
292    /// assert_eq!(Decimal::PI, dec!(3.1415926535897932384626433833));
293    /// ```
294    #[cfg(feature = "maths")]
295    pub const PI: Decimal = Decimal {
296        flags: 1835008,
297        lo: 1102470953,
298        mid: 185874565,
299        hi: 1703060790,
300    };
301    /// A constant representing π/2 as 1.5707963267948966192313216916
302    ///
303    /// # Examples
304    ///
305    /// Basic usage:
306    /// ```
307    /// # use rust_decimal::Decimal;
308    /// # use rust_decimal_macros::dec;
309    /// assert_eq!(Decimal::HALF_PI, dec!(1.5707963267948966192313216916));
310    /// ```
311    #[cfg(feature = "maths")]
312    pub const HALF_PI: Decimal = Decimal {
313        flags: 1835008,
314        lo: 2698719124,
315        mid: 92937282,
316        hi: 851530395,
317    };
318    /// A constant representing π/4 as 0.7853981633974483096156608458
319    ///
320    /// # Examples
321    ///
322    /// Basic usage:
323    /// ```
324    /// # use rust_decimal::Decimal;
325    /// # use rust_decimal_macros::dec;
326    /// assert_eq!(Decimal::QUARTER_PI, dec!(0.7853981633974483096156608458));
327    /// ```
328    #[cfg(feature = "maths")]
329    pub const QUARTER_PI: Decimal = Decimal {
330        flags: 1835008,
331        lo: 1349359562,
332        mid: 2193952289,
333        hi: 425765197,
334    };
335    /// A constant representing 2π as 6.2831853071795864769252867666
336    ///
337    /// # Examples
338    ///
339    /// Basic usage:
340    /// ```
341    /// # use rust_decimal::Decimal;
342    /// # use rust_decimal_macros::dec;
343    /// assert_eq!(Decimal::TWO_PI, dec!(6.2831853071795864769252867666));
344    /// ```
345    #[cfg(feature = "maths")]
346    pub const TWO_PI: Decimal = Decimal {
347        flags: 1835008,
348        lo: 2204941906,
349        mid: 371749130,
350        hi: 3406121580,
351    };
352    /// A constant representing Euler's number (e) as 2.7182818284590452353602874714
353    ///
354    /// # Examples
355    ///
356    /// Basic usage:
357    /// ```
358    /// # use rust_decimal::Decimal;
359    /// # use rust_decimal_macros::dec;
360    /// assert_eq!(Decimal::E, dec!(2.7182818284590452353602874714));
361    /// ```
362    #[cfg(feature = "maths")]
363    pub const E: Decimal = Decimal {
364        flags: 1835008,
365        lo: 2239425882,
366        mid: 3958169141,
367        hi: 1473583531,
368    };
369    /// A constant representing the inverse of Euler's number (1/e) as 0.3678794411714423215955237702
370    ///
371    /// # Examples
372    ///
373    /// Basic usage:
374    /// ```
375    /// # use rust_decimal::Decimal;
376    /// # use rust_decimal_macros::dec;
377    /// assert_eq!(Decimal::E_INVERSE, dec!(0.3678794411714423215955237702));
378    /// ```
379    #[cfg(feature = "maths")]
380    pub const E_INVERSE: Decimal = Decimal {
381        flags: 1835008,
382        lo: 2384059206,
383        mid: 2857938002,
384        hi: 199427844,
385    };
386
387    /// Returns a `Decimal` with a 64 bit `m` representation and corresponding `e` scale.
388    ///
389    /// # Arguments
390    ///
391    /// * `num` - An i64 that represents the `m` portion of the decimal number
392    /// * `scale` - A u32 representing the `e` portion of the decimal number.
393    ///
394    /// # Panics
395    ///
396    /// This function panics if `scale` is > [`Self::MAX_SCALE`].
397    ///
398    /// # Example
399    ///
400    /// ```
401    /// # use rust_decimal::Decimal;
402    /// #
403    /// let pi = Decimal::new(3141, 3);
404    /// assert_eq!(pi.to_string(), "3.141");
405    /// ```
406    #[must_use]
407    pub fn new(num: i64, scale: u32) -> Decimal {
408        match Self::try_new(num, scale) {
409            Err(e) => panic!("{}", e),
410            Ok(d) => d,
411        }
412    }
413
414    /// Checked version of [`Self::new`]. Will return an error instead of panicking at run-time.
415    ///
416    /// # Example
417    ///
418    /// ```rust
419    /// # use rust_decimal::Decimal;
420    /// #
421    /// let max = Decimal::try_new(i64::MAX, u32::MAX);
422    /// assert!(max.is_err());
423    /// ```
424    pub const fn try_new(num: i64, scale: u32) -> crate::Result<Decimal> {
425        if scale > Self::MAX_SCALE {
426            return Err(Error::ScaleExceedsMaximumPrecision(scale));
427        }
428        let flags: u32 = scale << SCALE_SHIFT;
429        if num < 0 {
430            let pos_num = num.wrapping_neg() as u64;
431            return Ok(Decimal {
432                flags: flags | SIGN_MASK,
433                hi: 0,
434                lo: (pos_num & U32_MASK) as u32,
435                mid: ((pos_num >> 32) & U32_MASK) as u32,
436            });
437        }
438        Ok(Decimal {
439            flags,
440            hi: 0,
441            lo: (num as u64 & U32_MASK) as u32,
442            mid: ((num as u64 >> 32) & U32_MASK) as u32,
443        })
444    }
445
446    /// Creates a `Decimal` using a 128 bit signed `m` representation and corresponding `e` scale.
447    ///
448    /// # Arguments
449    ///
450    /// * `num` - An i128 that represents the `m` portion of the decimal number
451    /// * `scale` - A u32 representing the `e` portion of the decimal number.
452    ///
453    /// # Panics
454    ///
455    /// This function panics if `scale` is > [`Self::MAX_SCALE`] or if `num` exceeds the maximum
456    /// supported 96 bits.
457    ///
458    /// # Example
459    ///
460    /// ```rust
461    /// # use rust_decimal::Decimal;
462    /// #
463    /// let pi = Decimal::from_i128_with_scale(3141i128, 3);
464    /// assert_eq!(pi.to_string(), "3.141");
465    /// ```
466    #[must_use]
467    pub fn from_i128_with_scale(num: i128, scale: u32) -> Decimal {
468        match Self::try_from_i128_with_scale(num, scale) {
469            Ok(d) => d,
470            Err(e) => panic!("{}", e),
471        }
472    }
473
474    /// Checked version of `Decimal::from_i128_with_scale`. Will return `Err` instead
475    /// of panicking at run-time.
476    ///
477    /// # Example
478    ///
479    /// ```rust
480    /// # use rust_decimal::Decimal;
481    /// #
482    /// let max = Decimal::try_from_i128_with_scale(i128::MAX, u32::MAX);
483    /// assert!(max.is_err());
484    /// ```
485    pub const fn try_from_i128_with_scale(num: i128, scale: u32) -> crate::Result<Decimal> {
486        if scale > Self::MAX_SCALE {
487            Err(Error::ScaleExceedsMaximumPrecision(scale))
488        } else if num > MAX_I128_REPR {
489            Err(Error::ExceedsMaximumPossibleValue)
490        } else if num < -MAX_I128_REPR {
491            Err(Error::LessThanMinimumPossibleValue)
492        } else {
493            Ok(Self::from_i128_with_scale_unchecked(num, scale))
494        }
495    }
496
497    #[inline]
498    pub(crate) const fn from_i128_with_scale_unchecked(num: i128, scale: u32) -> Decimal {
499        let flags = flags(num < 0, scale);
500        let num = num.unsigned_abs();
501        Decimal {
502            flags,
503            lo: (num as u64 & U32_MASK) as u32,
504            mid: ((num as u64 >> 32) & U32_MASK) as u32,
505            hi: ((num >> 64) as u64 & U32_MASK) as u32,
506        }
507    }
508
509    /// Returns a `Decimal` using the instances constituent parts.
510    ///
511    /// # Arguments
512    ///
513    /// * `lo` - The low 32 bits of a 96-bit integer.
514    /// * `mid` - The middle 32 bits of a 96-bit integer.
515    /// * `hi` - The high 32 bits of a 96-bit integer.
516    /// * `negative` - `true` to indicate a negative number.
517    /// * `scale` - A power of 10 ranging from 0 to [`Self::MAX_SCALE`].
518    ///
519    /// # Example
520    ///
521    /// ```
522    /// # use rust_decimal::Decimal;
523    /// #
524    /// let pi = Decimal::from_parts(1102470952, 185874565, 1703060790, false, 28);
525    /// assert_eq!(pi.to_string(), "3.1415926535897932384626433832");
526    /// ```
527    #[must_use]
528    pub const fn from_parts(lo: u32, mid: u32, hi: u32, negative: bool, scale: u32) -> Decimal {
529        assert!(scale <= Self::MAX_SCALE, "Scale exceeds maximum supported scale");
530        Decimal {
531            lo,
532            mid,
533            hi,
534            flags: flags(
535                if lo == 0 && mid == 0 && hi == 0 {
536                    false
537                } else {
538                    negative
539                },
540                scale,
541            ),
542        }
543    }
544
545    #[must_use]
546    pub(crate) const fn from_parts_raw(lo: u32, mid: u32, hi: u32, flags: u32) -> Decimal {
547        if lo == 0 && mid == 0 && hi == 0 {
548            Decimal {
549                lo,
550                mid,
551                hi,
552                flags: flags & SCALE_MASK,
553            }
554        } else {
555            Decimal { flags, hi, lo, mid }
556        }
557    }
558
559    /// Returns a `Result` which if successful contains the `Decimal` constitution of
560    /// the scientific notation provided by `value`.
561    ///
562    /// # Arguments
563    ///
564    /// * `value` - The scientific notation of the `Decimal`.
565    ///
566    /// # Example
567    ///
568    /// ```
569    /// # use rust_decimal::Decimal;
570    /// #
571    /// # fn main() -> Result<(), rust_decimal::Error> {
572    /// let value = Decimal::from_scientific("9.7e-7")?;
573    /// assert_eq!(value.to_string(), "0.00000097");
574    /// #     Ok(())
575    /// # }
576    /// ```
577    pub fn from_scientific(value: &str) -> Result<Decimal, Error> {
578        const ERROR_MESSAGE: &str = "Failed to parse";
579
580        let mut split = value.splitn(2, ['e', 'E']);
581
582        let base = split.next().ok_or_else(|| Error::from(ERROR_MESSAGE))?;
583        let exp = split.next().ok_or_else(|| Error::from(ERROR_MESSAGE))?;
584
585        let mut ret = Decimal::from_str(base)?;
586        let current_scale = ret.scale();
587
588        if let Some(stripped) = exp.strip_prefix('-') {
589            let exp: u32 = stripped.parse().map_err(|_| Error::from(ERROR_MESSAGE))?;
590            if exp > Self::MAX_SCALE {
591                return Err(Error::ScaleExceedsMaximumPrecision(exp));
592            }
593            ret.set_scale(current_scale + exp)?;
594        } else {
595            let exp: u32 = exp.parse().map_err(|_| Error::from(ERROR_MESSAGE))?;
596            if exp <= current_scale {
597                ret.set_scale(current_scale - exp)?;
598            } else if exp > 0 {
599                use crate::constants::BIG_POWERS_10;
600
601                // This is a case whereby the mantissa needs to be larger to be correctly
602                // represented within the decimal type. A good example is 1.2E10. At this point,
603                // we've parsed 1.2 as the base and 10 as the exponent. To represent this within a
604                // Decimal type we effectively store the mantissa as 12,000,000,000 and scale as
605                // zero.
606                if exp > Self::MAX_SCALE {
607                    return Err(Error::ScaleExceedsMaximumPrecision(exp));
608                }
609                let mut exp = exp as usize;
610                // Max two iterations. If exp is 1 then it needs to index position 0 of the array.
611                while exp > 0 {
612                    let pow;
613                    if exp >= BIG_POWERS_10.len() {
614                        pow = BIG_POWERS_10[BIG_POWERS_10.len() - 1];
615                        exp -= BIG_POWERS_10.len();
616                    } else {
617                        pow = BIG_POWERS_10[exp - 1];
618                        exp = 0;
619                    }
620
621                    let pow = Decimal {
622                        flags: 0,
623                        lo: pow as u32,
624                        mid: (pow >> 32) as u32,
625                        hi: 0,
626                    };
627                    match ret.checked_mul(pow) {
628                        Some(r) => ret = r,
629                        None => return Err(Error::ExceedsMaximumPossibleValue),
630                    };
631                }
632                ret.normalize_assign();
633            }
634        }
635        Ok(ret)
636    }
637
638    /// Converts a string slice in a given base to a decimal.
639    ///
640    /// The string is expected to be an optional + sign followed by digits.
641    /// Digits are a subset of these characters, depending on radix, and will return an error if outside
642    /// the expected range:
643    ///
644    /// * 0-9
645    /// * a-z
646    /// * A-Z
647    ///
648    /// # Examples
649    ///
650    /// Basic usage:
651    ///
652    /// ```
653    /// # use rust_decimal::prelude::*;
654    /// #
655    /// # fn main() -> Result<(), rust_decimal::Error> {
656    /// assert_eq!(Decimal::from_str_radix("A", 16)?.to_string(), "10");
657    /// #     Ok(())
658    /// # }
659    /// ```
660    pub fn from_str_radix(str: &str, radix: u32) -> Result<Self, crate::Error> {
661        if radix == 10 {
662            crate::str::parse_str_radix_10(str)
663        } else {
664            crate::str::parse_str_radix_n(str, radix)
665        }
666    }
667
668    /// Parses a string slice into a decimal. If the value underflows and cannot be represented with the
669    /// given scale then this will return an error.
670    ///
671    /// # Examples
672    ///
673    /// Basic usage:
674    ///
675    /// ```
676    /// # use rust_decimal::prelude::*;
677    /// # use rust_decimal::Error;
678    /// #
679    /// # fn main() -> Result<(), rust_decimal::Error> {
680    /// assert_eq!(Decimal::from_str_exact("0.001")?.to_string(), "0.001");
681    /// assert_eq!(Decimal::from_str_exact("0.00000_00000_00000_00000_00000_001")?.to_string(), "0.0000000000000000000000000001");
682    /// assert_eq!(Decimal::from_str_exact("0.00000_00000_00000_00000_00000_0001"), Err(Error::Underflow));
683    /// #     Ok(())
684    /// # }
685    /// ```
686    pub fn from_str_exact(str: &str) -> Result<Self, crate::Error> {
687        crate::str::parse_str_radix_10_exact(str)
688    }
689
690    /// Returns the scale of the decimal number, otherwise known as `e`.
691    ///
692    /// # Example
693    ///
694    /// ```
695    /// # use rust_decimal::Decimal;
696    /// #
697    /// let num = Decimal::new(1234, 3);
698    /// assert_eq!(num.scale(), 3u32);
699    /// ```
700    #[inline]
701    #[must_use]
702    pub const fn scale(&self) -> u32 {
703        (self.flags & SCALE_MASK) >> SCALE_SHIFT
704    }
705
706    /// Returns the mantissa of the decimal number.
707    ///
708    /// # Example
709    ///
710    /// ```
711    /// # use rust_decimal::prelude::*;
712    /// # use rust_decimal_macros::dec;
713    ///
714    /// let num = dec!(-1.2345678);
715    /// assert_eq!(num.mantissa(), -12345678i128);
716    /// assert_eq!(num.scale(), 7);
717    /// ```
718    #[must_use]
719    pub const fn mantissa(&self) -> i128 {
720        let raw = (self.lo as i128) | ((self.mid as i128) << 32) | ((self.hi as i128) << 64);
721        if self.is_sign_negative() {
722            -raw
723        } else {
724            raw
725        }
726    }
727
728    /// Returns true if this Decimal number is equivalent to zero.
729    ///
730    /// # Example
731    ///
732    /// ```
733    /// # use rust_decimal::prelude::*;
734    /// #
735    /// let num = Decimal::ZERO;
736    /// assert!(num.is_zero());
737    /// ```
738    #[must_use]
739    pub const fn is_zero(&self) -> bool {
740        self.lo == 0 && self.mid == 0 && self.hi == 0
741    }
742
743    /// Returns true if this Decimal number has zero fractional part (is equal to an integer)
744    ///
745    /// # Example
746    ///
747    /// ```
748    /// # use rust_decimal::prelude::*;
749    /// # use rust_decimal_macros::dec;
750    /// #
751    /// assert_eq!(dec!(5).is_integer(), true);
752    /// // Trailing zeros are also ignored
753    /// assert_eq!(dec!(5.0000).is_integer(), true);
754    /// // If there is a fractional part then it is not an integer
755    /// assert_eq!(dec!(5.1).is_integer(), false);
756    /// ```
757    #[must_use]
758    pub fn is_integer(&self) -> bool {
759        let scale = self.scale();
760        if scale == 0 || self.is_zero() {
761            return true;
762        }
763
764        // Check if it can be divided by 10^scale without remainder
765        let mut bits = self.mantissa_array3();
766        let mut scale = scale;
767        while scale > 0 {
768            let remainder = if scale > 9 {
769                scale -= 9;
770                ops::array::div_by_u32(&mut bits, POWERS_10[9])
771            } else {
772                let power = POWERS_10[scale as usize];
773                scale = 0;
774                ops::array::div_by_u32(&mut bits, power)
775            };
776            if remainder > 0 {
777                return false;
778            }
779        }
780        true
781    }
782
783    /// An optimized method for changing the sign of a decimal number.
784    ///
785    /// # Arguments
786    ///
787    /// * `positive`: true if the resulting decimal should be positive.
788    ///
789    /// # Example
790    ///
791    /// ```
792    /// # use rust_decimal::Decimal;
793    /// #
794    /// let mut one = Decimal::ONE;
795    /// one.set_sign(false);
796    /// assert_eq!(one.to_string(), "-1");
797    /// ```
798    #[deprecated(since = "1.4.0", note = "please use `set_sign_positive` instead")]
799    pub fn set_sign(&mut self, positive: bool) {
800        self.set_sign_positive(positive);
801    }
802
803    /// An optimized method for changing the sign of a decimal number.
804    ///
805    /// # Arguments
806    ///
807    /// * `positive`: true if the resulting decimal should be positive.
808    ///
809    /// # Example
810    ///
811    /// ```
812    /// # use rust_decimal::Decimal;
813    /// #
814    /// let mut one = Decimal::ONE;
815    /// one.set_sign_positive(false);
816    /// assert_eq!(one.to_string(), "-1");
817    /// ```
818    #[inline(always)]
819    pub fn set_sign_positive(&mut self, positive: bool) {
820        if positive {
821            self.flags &= UNSIGN_MASK;
822        } else {
823            self.flags |= SIGN_MASK;
824        }
825    }
826
827    /// An optimized method for changing the sign of a decimal number.
828    ///
829    /// # Arguments
830    ///
831    /// * `negative`: true if the resulting decimal should be negative.
832    ///
833    /// # Example
834    ///
835    /// ```
836    /// # use rust_decimal::Decimal;
837    /// #
838    /// let mut one = Decimal::ONE;
839    /// one.set_sign_negative(true);
840    /// assert_eq!(one.to_string(), "-1");
841    /// ```
842    #[inline(always)]
843    pub fn set_sign_negative(&mut self, negative: bool) {
844        self.set_sign_positive(!negative);
845    }
846
847    /// An optimized method for changing the scale of a decimal number.
848    ///
849    /// # Arguments
850    ///
851    /// * `scale`: the new scale of the number
852    ///
853    /// # Example
854    ///
855    /// ```
856    /// # use rust_decimal::Decimal;
857    /// #
858    /// # fn main() -> Result<(), rust_decimal::Error> {
859    /// let mut one = Decimal::ONE;
860    /// one.set_scale(5)?;
861    /// assert_eq!(one.to_string(), "0.00001");
862    /// #    Ok(())
863    /// # }
864    /// ```
865    pub fn set_scale(&mut self, scale: u32) -> Result<(), Error> {
866        if scale > Self::MAX_SCALE {
867            return Err(Error::ScaleExceedsMaximumPrecision(scale));
868        }
869        self.flags = (scale << SCALE_SHIFT) | (self.flags & SIGN_MASK);
870        Ok(())
871    }
872
873    /// Modifies the `Decimal` towards the desired scale, attempting to do so without changing the
874    /// underlying number itself.
875    ///
876    /// Setting the scale to something less then the current `Decimal`s scale will
877    /// cause the newly created `Decimal` to perform rounding using the `MidpointAwayFromZero` strategy.
878    ///
879    /// Scales greater than the maximum precision that can be represented by `Decimal` will be
880    /// automatically rounded to either [`Self::MAX_SCALE`] or the maximum precision that can
881    /// be represented with the given mantissa.
882    ///
883    /// # Arguments
884    /// * `scale`: The desired scale to use for the new `Decimal` number.
885    ///
886    /// # Example
887    ///
888    /// ```
889    /// # use rust_decimal::prelude::*;
890    /// # use rust_decimal_macros::dec;
891    ///
892    /// // Rescaling to a higher scale preserves the value
893    /// let mut number = dec!(1.123);
894    /// assert_eq!(number.scale(), 3);
895    /// number.rescale(6);
896    /// assert_eq!(number.to_string(), "1.123000");
897    /// assert_eq!(number.scale(), 6);
898    ///
899    /// // Rescaling to a lower scale forces the number to be rounded
900    /// let mut number = dec!(1.45);
901    /// assert_eq!(number.scale(), 2);
902    /// number.rescale(1);
903    /// assert_eq!(number.to_string(), "1.5");
904    /// assert_eq!(number.scale(), 1);
905    ///
906    /// // This function never fails. Consequently, if a scale is provided that is unable to be
907    /// // represented using the given mantissa, then the maximum possible scale is used.
908    /// let mut number = dec!(11.76470588235294);
909    /// assert_eq!(number.scale(), 14);
910    /// number.rescale(28);
911    /// // A scale of 28 cannot be represented given this mantissa, however it was able to represent
912    /// // a number with a scale of 27
913    /// assert_eq!(number.to_string(), "11.764705882352940000000000000");
914    /// assert_eq!(number.scale(), 27);
915    /// ```
916    pub fn rescale(&mut self, scale: u32) {
917        let mut array = [self.lo, self.mid, self.hi];
918        let mut value_scale = self.scale();
919        ops::array::rescale_internal(&mut array, &mut value_scale, scale);
920        self.lo = array[0];
921        self.mid = array[1];
922        self.hi = array[2];
923        self.flags = flags(self.is_sign_negative(), value_scale);
924    }
925
926    /// Returns a serialized version of the decimal number.
927    /// The resulting byte array will have the following representation:
928    ///
929    /// * Bytes 1-4: flags
930    /// * Bytes 5-8: lo portion of `m`
931    /// * Bytes 9-12: mid portion of `m`
932    /// * Bytes 13-16: high portion of `m`
933    #[must_use]
934    pub const fn serialize(&self) -> [u8; 16] {
935        [
936            (self.flags & U8_MASK) as u8,
937            ((self.flags >> 8) & U8_MASK) as u8,
938            ((self.flags >> 16) & U8_MASK) as u8,
939            ((self.flags >> 24) & U8_MASK) as u8,
940            (self.lo & U8_MASK) as u8,
941            ((self.lo >> 8) & U8_MASK) as u8,
942            ((self.lo >> 16) & U8_MASK) as u8,
943            ((self.lo >> 24) & U8_MASK) as u8,
944            (self.mid & U8_MASK) as u8,
945            ((self.mid >> 8) & U8_MASK) as u8,
946            ((self.mid >> 16) & U8_MASK) as u8,
947            ((self.mid >> 24) & U8_MASK) as u8,
948            (self.hi & U8_MASK) as u8,
949            ((self.hi >> 8) & U8_MASK) as u8,
950            ((self.hi >> 16) & U8_MASK) as u8,
951            ((self.hi >> 24) & U8_MASK) as u8,
952        ]
953    }
954
955    /// Deserializes the given bytes into a decimal number.
956    /// The deserialized byte representation must be 16 bytes and adhere to the following convention:
957    ///
958    /// * Bytes 1-4: flags
959    /// * Bytes 5-8: lo portion of `m`
960    /// * Bytes 9-12: mid portion of `m`
961    /// * Bytes 13-16: high portion of `m`
962    #[must_use]
963    pub fn deserialize(bytes: [u8; 16]) -> Decimal {
964        // We can bound flags by a bitwise mask to correspond to:
965        //   Bits 0-15: unused
966        //   Bits 16-23: Contains "e", a value between 0-28 that indicates the scale
967        //   Bits 24-30: unused
968        //   Bit 31: the sign of the Decimal value, 0 meaning positive and 1 meaning negative.
969        let mut raw = Decimal {
970            flags: ((bytes[0] as u32)
971                | ((bytes[1] as u32) << 8)
972                | ((bytes[2] as u32) << 16)
973                | ((bytes[3] as u32) << 24))
974                & 0x801F_0000,
975            lo: (bytes[4] as u32) | ((bytes[5] as u32) << 8) | ((bytes[6] as u32) << 16) | ((bytes[7] as u32) << 24),
976            mid: (bytes[8] as u32) | ((bytes[9] as u32) << 8) | ((bytes[10] as u32) << 16) | ((bytes[11] as u32) << 24),
977            hi: (bytes[12] as u32)
978                | ((bytes[13] as u32) << 8)
979                | ((bytes[14] as u32) << 16)
980                | ((bytes[15] as u32) << 24),
981        };
982        // Scale must be bound to maximum precision. Only two values can be greater than this
983        if raw.scale() > Self::MAX_SCALE {
984            let mut bits = raw.mantissa_array3();
985            let remainder = match raw.scale() {
986                29 => ops::array::div_by_power::<1>(&mut bits),
987                30 => ops::array::div_by_power::<2>(&mut bits),
988                31 => ops::array::div_by_power::<3>(&mut bits),
989                _ => 0,
990            };
991            if remainder >= 5 {
992                ops::array::add_one_internal(&mut bits);
993            }
994            raw.lo = bits[0];
995            raw.mid = bits[1];
996            raw.hi = bits[2];
997            raw.flags = flags(raw.is_sign_negative(), Self::MAX_SCALE);
998        }
999        raw
1000    }
1001
1002    /// Returns `true` if the decimal is negative.
1003    #[deprecated(since = "0.6.3", note = "please use `is_sign_negative` instead")]
1004    #[must_use]
1005    pub fn is_negative(&self) -> bool {
1006        self.is_sign_negative()
1007    }
1008
1009    /// Returns `true` if the decimal is positive.
1010    #[deprecated(since = "0.6.3", note = "please use `is_sign_positive` instead")]
1011    #[must_use]
1012    pub fn is_positive(&self) -> bool {
1013        self.is_sign_positive()
1014    }
1015
1016    /// Returns `true` if the sign bit of the decimal is negative.
1017    ///
1018    /// # Example
1019    /// ```
1020    /// # use rust_decimal::prelude::*;
1021    /// #
1022    /// assert_eq!(true, Decimal::new(-1, 0).is_sign_negative());
1023    /// assert_eq!(false, Decimal::new(1, 0).is_sign_negative());
1024    /// ```
1025    #[inline(always)]
1026    #[must_use]
1027    pub const fn is_sign_negative(&self) -> bool {
1028        self.flags & SIGN_MASK > 0
1029    }
1030
1031    /// Returns `true` if the sign bit of the decimal is positive.
1032    ///
1033    /// # Example
1034    /// ```
1035    /// # use rust_decimal::prelude::*;
1036    /// #
1037    /// assert_eq!(false, Decimal::new(-1, 0).is_sign_positive());
1038    /// assert_eq!(true, Decimal::new(1, 0).is_sign_positive());
1039    /// ```
1040    #[inline(always)]
1041    #[must_use]
1042    pub const fn is_sign_positive(&self) -> bool {
1043        self.flags & SIGN_MASK == 0
1044    }
1045
1046    /// Returns the minimum possible number that `Decimal` can represent.
1047    #[deprecated(since = "1.12.0", note = "Use the associated constant Decimal::MIN")]
1048    #[must_use]
1049    pub const fn min_value() -> Decimal {
1050        MIN
1051    }
1052
1053    /// Returns the maximum possible number that `Decimal` can represent.
1054    #[deprecated(since = "1.12.0", note = "Use the associated constant Decimal::MAX")]
1055    #[must_use]
1056    pub const fn max_value() -> Decimal {
1057        MAX
1058    }
1059
1060    /// Returns a new `Decimal` integral with no fractional portion.
1061    /// This is a true truncation whereby no rounding is performed.
1062    ///
1063    /// # Example
1064    ///
1065    /// ```
1066    /// # use rust_decimal::Decimal;
1067    /// # use rust_decimal_macros::dec;
1068    /// #
1069    /// let pi = dec!(3.141);
1070    /// assert_eq!(pi.trunc(), dec!(3));
1071    ///
1072    /// // Negative numbers are similarly truncated without rounding
1073    /// let neg = dec!(-1.98765);
1074    /// assert_eq!(neg.trunc(), Decimal::NEGATIVE_ONE);
1075    /// ```
1076    #[must_use]
1077    pub fn trunc(&self) -> Decimal {
1078        let mut working = [self.lo, self.mid, self.hi];
1079        let mut working_scale = self.scale();
1080        ops::array::truncate_internal(&mut working, &mut working_scale, 0);
1081        Decimal {
1082            lo: working[0],
1083            mid: working[1],
1084            hi: working[2],
1085            flags: flags(self.is_sign_negative(), working_scale),
1086        }
1087    }
1088
1089    /// Returns a new `Decimal` with the fractional portion delimited by `scale`.
1090    /// This is a true truncation whereby no rounding is performed.
1091    ///
1092    /// # Example
1093    ///
1094    /// ```
1095    /// # use rust_decimal::Decimal;
1096    /// # use rust_decimal_macros::dec;
1097    /// #
1098    /// let pi = dec!(3.141592);
1099    /// assert_eq!(pi.trunc_with_scale(2), dec!(3.14));
1100    ///
1101    /// // Negative numbers are similarly truncated without rounding
1102    /// let neg = dec!(-1.98765);
1103    /// assert_eq!(neg.trunc_with_scale(1), dec!(-1.9));
1104    /// ```
1105    #[must_use]
1106    pub fn trunc_with_scale(&self, scale: u32) -> Decimal {
1107        let mut working = [self.lo, self.mid, self.hi];
1108        let mut working_scale = self.scale();
1109        ops::array::truncate_internal(&mut working, &mut working_scale, scale);
1110        Decimal {
1111            lo: working[0],
1112            mid: working[1],
1113            hi: working[2],
1114            flags: flags(self.is_sign_negative(), working_scale),
1115        }
1116    }
1117
1118    /// Returns a new `Decimal` representing the fractional portion of the number.
1119    ///
1120    /// # Example
1121    ///
1122    /// ```
1123    /// # use rust_decimal::Decimal;
1124    /// #
1125    /// let pi = Decimal::new(3141, 3);
1126    /// let fract = Decimal::new(141, 3);
1127    /// // note that it returns a decimal
1128    /// assert_eq!(pi.fract(), fract);
1129    /// ```
1130    #[must_use]
1131    pub fn fract(&self) -> Decimal {
1132        // This is essentially the original number minus the integral.
1133        // Could possibly be optimized in the future
1134        *self - self.trunc()
1135    }
1136
1137    /// Computes the absolute value of `self`.
1138    ///
1139    /// # Example
1140    ///
1141    /// ```
1142    /// # use rust_decimal::Decimal;
1143    /// #
1144    /// let num = Decimal::new(-3141, 3);
1145    /// assert_eq!(num.abs().to_string(), "3.141");
1146    /// ```
1147    #[must_use]
1148    pub fn abs(&self) -> Decimal {
1149        let mut me = *self;
1150        me.set_sign_positive(true);
1151        me
1152    }
1153
1154    /// Returns the largest integer less than or equal to a number.
1155    ///
1156    /// # Example
1157    ///
1158    /// ```
1159    /// # use rust_decimal::Decimal;
1160    /// #
1161    /// let num = Decimal::new(3641, 3);
1162    /// assert_eq!(num.floor().to_string(), "3");
1163    /// ```
1164    #[must_use]
1165    pub fn floor(&self) -> Decimal {
1166        let scale = self.scale();
1167        if scale == 0 {
1168            // Nothing to do
1169            return *self;
1170        }
1171
1172        // Opportunity for optimization here
1173        let floored = self.trunc();
1174        if self.is_sign_negative() && !self.fract().is_zero() {
1175            floored - ONE
1176        } else {
1177            floored
1178        }
1179    }
1180
1181    /// Returns the smallest integer greater than or equal to a number.
1182    ///
1183    /// # Example
1184    ///
1185    /// ```
1186    /// # use rust_decimal::Decimal;
1187    /// #
1188    /// let num = Decimal::new(3141, 3);
1189    /// assert_eq!(num.ceil().to_string(), "4");
1190    /// let num = Decimal::new(3, 0);
1191    /// assert_eq!(num.ceil().to_string(), "3");
1192    /// ```
1193    #[must_use]
1194    pub fn ceil(&self) -> Decimal {
1195        let scale = self.scale();
1196        if scale == 0 {
1197            // Nothing to do
1198            return *self;
1199        }
1200
1201        // Opportunity for optimization here
1202        if self.is_sign_positive() && !self.fract().is_zero() {
1203            self.trunc() + ONE
1204        } else {
1205            self.trunc()
1206        }
1207    }
1208
1209    /// Returns the maximum of the two numbers.
1210    ///
1211    /// ```
1212    /// # use rust_decimal::Decimal;
1213    /// #
1214    /// let x = Decimal::new(1, 0);
1215    /// let y = Decimal::new(2, 0);
1216    /// assert_eq!(y, x.max(y));
1217    /// ```
1218    #[must_use]
1219    pub fn max(self, other: Decimal) -> Decimal {
1220        if self < other {
1221            other
1222        } else {
1223            self
1224        }
1225    }
1226
1227    /// Returns the minimum of the two numbers.
1228    ///
1229    /// ```
1230    /// # use rust_decimal::Decimal;
1231    /// #
1232    /// let x = Decimal::new(1, 0);
1233    /// let y = Decimal::new(2, 0);
1234    /// assert_eq!(x, x.min(y));
1235    /// ```
1236    #[must_use]
1237    pub fn min(self, other: Decimal) -> Decimal {
1238        if self > other {
1239            other
1240        } else {
1241            self
1242        }
1243    }
1244
1245    /// Strips any trailing zero's from a `Decimal` and converts -0 to 0.
1246    ///
1247    /// # Example
1248    ///
1249    /// ```
1250    /// # use rust_decimal::prelude::*;
1251    /// # fn main() -> Result<(), rust_decimal::Error> {
1252    /// let number = Decimal::from_str("3.100")?;
1253    /// assert_eq!(number.normalize().to_string(), "3.1");
1254    /// # Ok(())
1255    /// # }
1256    /// ```
1257    #[must_use]
1258    pub fn normalize(&self) -> Decimal {
1259        let mut result = *self;
1260        result.normalize_assign();
1261        result
1262    }
1263
1264    /// An in place version of `normalize`. Strips any trailing zero's from a `Decimal` and converts -0 to 0.
1265    ///
1266    /// # Example
1267    ///
1268    /// ```
1269    /// # use rust_decimal::prelude::*;
1270    /// # fn main() -> Result<(), rust_decimal::Error> {
1271    /// let mut number = Decimal::from_str("3.100")?;
1272    /// assert_eq!(number.to_string(), "3.100");
1273    /// number.normalize_assign();
1274    /// assert_eq!(number.to_string(), "3.1");
1275    /// # Ok(())
1276    /// # }
1277    /// ```
1278    pub fn normalize_assign(&mut self) {
1279        if self.is_zero() {
1280            self.flags = 0;
1281            return;
1282        }
1283
1284        let mut scale = self.scale();
1285        if scale == 0 {
1286            return;
1287        }
1288
1289        let mut result = self.mantissa_array3();
1290        let mut working = self.mantissa_array3();
1291        while scale > 0 {
1292            if ops::array::div_by_u32(&mut working, 10) > 0 {
1293                break;
1294            }
1295            scale -= 1;
1296            result.copy_from_slice(&working);
1297        }
1298        self.lo = result[0];
1299        self.mid = result[1];
1300        self.hi = result[2];
1301        self.flags = flags(self.is_sign_negative(), scale);
1302    }
1303
1304    /// Returns a new `Decimal` number with no fractional portion (i.e. an integer).
1305    /// Rounding currently follows "Bankers Rounding" rules. e.g. 6.5 -> 6, 7.5 -> 8
1306    ///
1307    /// # Example
1308    ///
1309    /// ```
1310    /// # use rust_decimal::Decimal;
1311    /// #
1312    /// // Demonstrating bankers rounding...
1313    /// let number_down = Decimal::new(65, 1);
1314    /// let number_up   = Decimal::new(75, 1);
1315    /// assert_eq!(number_down.round().to_string(), "6");
1316    /// assert_eq!(number_up.round().to_string(), "8");
1317    /// ```
1318    #[must_use]
1319    pub fn round(&self) -> Decimal {
1320        self.round_dp(0)
1321    }
1322
1323    /// Returns a new `Decimal` number with the specified number of decimal points for fractional
1324    /// portion.
1325    /// Rounding is performed using the provided [`RoundingStrategy`]
1326    ///
1327    /// # Arguments
1328    /// * `dp`: the number of decimal points to round to.
1329    /// * `strategy`: the [`RoundingStrategy`] to use.
1330    ///
1331    /// # Example
1332    ///
1333    /// ```
1334    /// # use rust_decimal::{Decimal, RoundingStrategy};
1335    /// # use rust_decimal_macros::dec;
1336    /// #
1337    /// let tax = dec!(3.4395);
1338    /// assert_eq!(tax.round_dp_with_strategy(2, RoundingStrategy::MidpointAwayFromZero).to_string(), "3.44");
1339    /// ```
1340    #[must_use]
1341    pub fn round_dp_with_strategy(&self, dp: u32, strategy: RoundingStrategy) -> Decimal {
1342        let old_scale = self.scale();
1343
1344        // return early if decimal has a smaller number of fractional places than dp
1345        // e.g. 2.51 rounded to 3 decimal places is 2.51
1346        if old_scale <= dp {
1347            return *self;
1348        }
1349
1350        // Short circuit for zero
1351        if self.is_zero() {
1352            return Decimal {
1353                lo: 0,
1354                mid: 0,
1355                hi: 0,
1356                flags: flags(self.is_sign_negative(), dp),
1357            };
1358        }
1359
1360        let mut value = [self.lo, self.mid, self.hi];
1361        let mut value_scale = self.scale();
1362        let negative = self.is_sign_negative();
1363
1364        value_scale -= dp;
1365
1366        // Rescale to zero so it's easier to work with
1367        while value_scale > 0 {
1368            if value_scale < 10 {
1369                ops::array::div_by_u32(&mut value, POWERS_10[value_scale as usize]);
1370                value_scale = 0;
1371            } else {
1372                ops::array::div_by_u32(&mut value, POWERS_10[9]);
1373                value_scale -= 9;
1374            }
1375        }
1376
1377        // Do some midpoint rounding checks
1378        // We're actually doing two things here.
1379        //  1. Figuring out midpoint rounding when we're right on the boundary. e.g. 2.50000
1380        //  2. Figuring out whether to add one or not e.g. 2.51
1381        // For this, we need to figure out the fractional portion that is additional to
1382        // the rounded number. e.g. for 0.12345 rounding to 2dp we'd want 345.
1383        // We're doing the equivalent of losing precision (e.g. to get 0.12)
1384        // then increasing the precision back up to 0.12000
1385        let mut offset = [self.lo, self.mid, self.hi];
1386        let mut diff = old_scale - dp;
1387
1388        while diff > 0 {
1389            if diff < 10 {
1390                ops::array::div_by_u32(&mut offset, POWERS_10[diff as usize]);
1391                break;
1392            } else {
1393                ops::array::div_by_u32(&mut offset, POWERS_10[9]);
1394                // Only 9 as this array starts with 1
1395                diff -= 9;
1396            }
1397        }
1398
1399        let mut diff = old_scale - dp;
1400
1401        while diff > 0 {
1402            if diff < 10 {
1403                ops::array::mul_by_u32(&mut offset, POWERS_10[diff as usize]);
1404                break;
1405            } else {
1406                ops::array::mul_by_u32(&mut offset, POWERS_10[9]);
1407                // Only 9 as this array starts with 1
1408                diff -= 9;
1409            }
1410        }
1411
1412        let mut decimal_portion = [self.lo, self.mid, self.hi];
1413        ops::array::sub_by_internal(&mut decimal_portion, &offset);
1414
1415        // If the decimal_portion is zero then we round based on the other data
1416        let mut cap = [5, 0, 0];
1417        for _ in 0..(old_scale - dp - 1) {
1418            ops::array::mul_by_u32(&mut cap, 10);
1419        }
1420        let order = ops::array::cmp_internal(&decimal_portion, &cap);
1421
1422        #[allow(deprecated)]
1423        match strategy {
1424            RoundingStrategy::BankersRounding | RoundingStrategy::MidpointNearestEven => {
1425                match order {
1426                    Ordering::Equal => {
1427                        if (value[0] & 1) == 1 {
1428                            ops::array::add_one_internal(&mut value);
1429                        }
1430                    }
1431                    Ordering::Greater => {
1432                        // Doesn't matter about the decimal portion
1433                        ops::array::add_one_internal(&mut value);
1434                    }
1435                    _ => {}
1436                }
1437            }
1438            RoundingStrategy::RoundHalfDown | RoundingStrategy::MidpointTowardZero => {
1439                if let Ordering::Greater = order {
1440                    ops::array::add_one_internal(&mut value);
1441                }
1442            }
1443            RoundingStrategy::RoundHalfUp | RoundingStrategy::MidpointAwayFromZero => {
1444                // when Ordering::Equal, decimal_portion is 0.5 exactly
1445                // when Ordering::Greater, decimal_portion is > 0.5
1446                match order {
1447                    Ordering::Equal => {
1448                        ops::array::add_one_internal(&mut value);
1449                    }
1450                    Ordering::Greater => {
1451                        // Doesn't matter about the decimal portion
1452                        ops::array::add_one_internal(&mut value);
1453                    }
1454                    _ => {}
1455                }
1456            }
1457            RoundingStrategy::RoundUp | RoundingStrategy::AwayFromZero => {
1458                if !ops::array::is_all_zero(&decimal_portion) {
1459                    ops::array::add_one_internal(&mut value);
1460                }
1461            }
1462            RoundingStrategy::ToPositiveInfinity => {
1463                if !negative && !ops::array::is_all_zero(&decimal_portion) {
1464                    ops::array::add_one_internal(&mut value);
1465                }
1466            }
1467            RoundingStrategy::ToNegativeInfinity => {
1468                if negative && !ops::array::is_all_zero(&decimal_portion) {
1469                    ops::array::add_one_internal(&mut value);
1470                }
1471            }
1472            RoundingStrategy::RoundDown | RoundingStrategy::ToZero => (),
1473        }
1474
1475        Decimal::from_parts(value[0], value[1], value[2], negative, dp)
1476    }
1477
1478    /// Returns a new `Decimal` number with the specified number of decimal points for fractional portion.
1479    /// Rounding currently follows "Bankers Rounding" rules. e.g. 6.5 -> 6, 7.5 -> 8
1480    ///
1481    /// # Arguments
1482    /// * `dp`: the number of decimal points to round to.
1483    ///
1484    /// # Example
1485    ///
1486    /// ```
1487    /// # use rust_decimal::Decimal;
1488    /// # use rust_decimal_macros::dec;
1489    /// #
1490    /// let pi = dec!(3.1415926535897932384626433832);
1491    /// assert_eq!(pi.round_dp(2).to_string(), "3.14");
1492    /// ```
1493    #[must_use]
1494    pub fn round_dp(&self, dp: u32) -> Decimal {
1495        self.round_dp_with_strategy(dp, RoundingStrategy::MidpointNearestEven)
1496    }
1497
1498    /// Returns `Some(Decimal)` number rounded to the specified number of significant digits. If
1499    /// the resulting number is unable to be represented by the `Decimal` number then `None` will
1500    /// be returned.
1501    /// When the number of significant figures of the `Decimal` being rounded is greater than the requested
1502    /// number of significant digits then rounding will be performed using `MidpointNearestEven` strategy.
1503    ///
1504    /// # Arguments
1505    /// * `digits`: the number of significant digits to round to.
1506    ///
1507    /// # Remarks
1508    /// A significant figure is determined using the following rules:
1509    /// 1. Non-zero digits are always significant.
1510    /// 2. Zeros between non-zero digits are always significant.
1511    /// 3. Leading zeros are never significant.
1512    /// 4. Trailing zeros are only significant if the number contains a decimal point.
1513    ///
1514    /// # Example
1515    ///
1516    /// ```
1517    /// # use rust_decimal::Decimal;
1518    /// # use rust_decimal_macros::dec;
1519    ///
1520    /// let value = dec!(305.459);
1521    /// assert_eq!(value.round_sf(0), Some(dec!(0)));
1522    /// assert_eq!(value.round_sf(1), Some(dec!(300)));
1523    /// assert_eq!(value.round_sf(2), Some(dec!(310)));
1524    /// assert_eq!(value.round_sf(3), Some(dec!(305)));
1525    /// assert_eq!(value.round_sf(4), Some(dec!(305.5)));
1526    /// assert_eq!(value.round_sf(5), Some(dec!(305.46)));
1527    /// assert_eq!(value.round_sf(6), Some(dec!(305.459)));
1528    /// assert_eq!(value.round_sf(7), Some(dec!(305.4590)));
1529    /// assert_eq!(Decimal::MAX.round_sf(1), None);
1530    ///
1531    /// let value = dec!(0.012301);
1532    /// assert_eq!(value.round_sf(3), Some(dec!(0.0123)));
1533    /// ```
1534    #[must_use]
1535    pub fn round_sf(&self, digits: u32) -> Option<Decimal> {
1536        self.round_sf_with_strategy(digits, RoundingStrategy::MidpointNearestEven)
1537    }
1538
1539    /// Returns `Some(Decimal)` number rounded to the specified number of significant digits. If
1540    /// the resulting number is unable to be represented by the `Decimal` number then `None` will
1541    /// be returned.
1542    /// When the number of significant figures of the `Decimal` being rounded is greater than the requested
1543    /// number of significant digits then rounding will be performed using the provided [RoundingStrategy].
1544    ///
1545    /// # Arguments
1546    /// * `digits`: the number of significant digits to round to.
1547    /// * `strategy`: if required, the rounding strategy to use.
1548    ///
1549    /// # Remarks
1550    /// A significant figure is determined using the following rules:
1551    /// 1. Non-zero digits are always significant.
1552    /// 2. Zeros between non-zero digits are always significant.
1553    /// 3. Leading zeros are never significant.
1554    /// 4. Trailing zeros are only significant if the number contains a decimal point.
1555    ///
1556    /// # Example
1557    ///
1558    /// ```
1559    /// # use rust_decimal::{Decimal, RoundingStrategy};
1560    /// # use rust_decimal_macros::dec;
1561    ///
1562    /// let value = dec!(305.459);
1563    /// assert_eq!(value.round_sf_with_strategy(0, RoundingStrategy::ToZero), Some(dec!(0)));
1564    /// assert_eq!(value.round_sf_with_strategy(1, RoundingStrategy::ToZero), Some(dec!(300)));
1565    /// assert_eq!(value.round_sf_with_strategy(2, RoundingStrategy::ToZero), Some(dec!(300)));
1566    /// assert_eq!(value.round_sf_with_strategy(3, RoundingStrategy::ToZero), Some(dec!(305)));
1567    /// assert_eq!(value.round_sf_with_strategy(4, RoundingStrategy::ToZero), Some(dec!(305.4)));
1568    /// assert_eq!(value.round_sf_with_strategy(5, RoundingStrategy::ToZero), Some(dec!(305.45)));
1569    /// assert_eq!(value.round_sf_with_strategy(6, RoundingStrategy::ToZero), Some(dec!(305.459)));
1570    /// assert_eq!(value.round_sf_with_strategy(7, RoundingStrategy::ToZero), Some(dec!(305.4590)));
1571    /// assert_eq!(Decimal::MAX.round_sf_with_strategy(1, RoundingStrategy::ToZero), Some(dec!(70000000000000000000000000000)));
1572    ///
1573    /// let value = dec!(0.012301);
1574    /// assert_eq!(value.round_sf_with_strategy(3, RoundingStrategy::AwayFromZero), Some(dec!(0.0124)));
1575    /// ```
1576    #[must_use]
1577    pub fn round_sf_with_strategy(&self, digits: u32, strategy: RoundingStrategy) -> Option<Decimal> {
1578        if self.is_zero() || digits == 0 {
1579            return Some(Decimal::ZERO);
1580        }
1581
1582        // We start by grabbing the mantissa and figuring out how many significant figures it is
1583        // made up of. We do this by just dividing by 10 and checking remainders - effectively
1584        // we're performing a naive log10.
1585        let mut working = self.mantissa_array3();
1586        let mut mantissa_sf = 0;
1587        while !ops::array::is_all_zero(&working) {
1588            let _remainder = ops::array::div_by_u32(&mut working, 10u32);
1589            mantissa_sf += 1;
1590            if working[2] == 0 && working[1] == 0 && working[0] == 1 {
1591                mantissa_sf += 1;
1592                break;
1593            }
1594        }
1595        let scale = self.scale();
1596
1597        match digits.cmp(&mantissa_sf) {
1598            Ordering::Greater => {
1599                // If we're requesting a higher number of significant figures, we rescale
1600                let mut array = [self.lo, self.mid, self.hi];
1601                let mut value_scale = scale;
1602                ops::array::rescale_internal(&mut array, &mut value_scale, scale + digits - mantissa_sf);
1603                Some(Decimal {
1604                    lo: array[0],
1605                    mid: array[1],
1606                    hi: array[2],
1607                    flags: flags(self.is_sign_negative(), value_scale),
1608                })
1609            }
1610            Ordering::Less => {
1611                // We're requesting a lower number of significant digits.
1612                let diff = mantissa_sf - digits;
1613                // If the diff is greater than the scale we're focused on the integral. Otherwise, we can
1614                // just round.
1615                if diff > scale {
1616                    use crate::constants::BIG_POWERS_10;
1617                    // We need to adjust the integral portion. This also should be rounded, consequently
1618                    // we reduce the number down, round it, and then scale back up.
1619                    // E.g. If we have 305.459 scaling to a sf of 2 - we first reduce the number
1620                    // down to 30.5459, round it to 31 and then scale it back up to 310.
1621                    // Likewise, if we have 12301 scaling to a sf of 3 - we first reduce the number
1622                    // down to 123.01, round it to 123 and then scale it back up to 12300.
1623                    let mut num = *self;
1624                    let mut exp = (diff - scale) as usize;
1625                    while exp > 0 {
1626                        let pow;
1627                        if exp >= BIG_POWERS_10.len() {
1628                            pow = Decimal::from(BIG_POWERS_10[BIG_POWERS_10.len() - 1]);
1629                            exp -= BIG_POWERS_10.len();
1630                        } else {
1631                            pow = Decimal::from(BIG_POWERS_10[exp - 1]);
1632                            exp = 0;
1633                        }
1634                        num = num.checked_div(pow)?;
1635                    }
1636                    let mut num = num.round_dp_with_strategy(0, strategy).trunc();
1637                    let mut exp = (mantissa_sf - digits - scale) as usize;
1638                    while exp > 0 {
1639                        let pow;
1640                        if exp >= BIG_POWERS_10.len() {
1641                            pow = Decimal::from(BIG_POWERS_10[BIG_POWERS_10.len() - 1]);
1642                            exp -= BIG_POWERS_10.len();
1643                        } else {
1644                            pow = Decimal::from(BIG_POWERS_10[exp - 1]);
1645                            exp = 0;
1646                        }
1647                        num = num.checked_mul(pow)?;
1648                    }
1649                    Some(num)
1650                } else {
1651                    Some(self.round_dp_with_strategy(scale - diff, strategy))
1652                }
1653            }
1654            Ordering::Equal => {
1655                // Case where significant figures = requested significant digits.
1656                Some(*self)
1657            }
1658        }
1659    }
1660
1661    /// Convert `Decimal` to an internal representation of the underlying struct. This is useful
1662    /// for debugging the internal state of the object.
1663    ///
1664    /// # Important Disclaimer
1665    /// This is primarily intended for library maintainers. The internal representation of a
1666    /// `Decimal` is considered "unstable" for public use.
1667    ///
1668    /// # Example
1669    ///
1670    /// ```
1671    /// # use rust_decimal::Decimal;
1672    /// # use rust_decimal_macros::dec;
1673    ///
1674    /// let pi = dec!(3.1415926535897932384626433832);
1675    /// assert_eq!(format!("{:?}", pi), "3.1415926535897932384626433832");
1676    /// assert_eq!(format!("{:?}", pi.unpack()), "UnpackedDecimal { \
1677    ///     negative: false, scale: 28, hi: 1703060790, mid: 185874565, lo: 1102470952 \
1678    /// }");
1679    /// ```
1680    #[must_use]
1681    pub const fn unpack(&self) -> UnpackedDecimal {
1682        UnpackedDecimal {
1683            negative: self.is_sign_negative(),
1684            scale: self.scale(),
1685            hi: self.hi,
1686            lo: self.lo,
1687            mid: self.mid,
1688        }
1689    }
1690
1691    #[inline(always)]
1692    pub(crate) const fn lo(&self) -> u32 {
1693        self.lo
1694    }
1695
1696    #[inline(always)]
1697    pub(crate) const fn mid(&self) -> u32 {
1698        self.mid
1699    }
1700
1701    #[inline(always)]
1702    pub(crate) const fn hi(&self) -> u32 {
1703        self.hi
1704    }
1705
1706    #[inline(always)]
1707    pub(crate) const fn flags(&self) -> u32 {
1708        self.flags
1709    }
1710
1711    #[inline(always)]
1712    pub(crate) const fn mantissa_array3(&self) -> [u32; 3] {
1713        [self.lo, self.mid, self.hi]
1714    }
1715
1716    #[inline(always)]
1717    pub(crate) const fn mantissa_array4(&self) -> [u32; 4] {
1718        [self.lo, self.mid, self.hi, 0]
1719    }
1720
1721    /// Parses a 32-bit float into a Decimal number whilst retaining any non-guaranteed precision.
1722    ///
1723    /// Typically when a float is parsed in Rust Decimal, any excess bits (after ~7.22 decimal points for
1724    /// f32 as per IEEE-754) are removed due to any digits following this are considered an approximation
1725    /// at best. This function bypasses this additional step and retains these excess bits.
1726    ///
1727    /// # Example
1728    ///
1729    /// ```
1730    /// # use rust_decimal::prelude::*;
1731    /// #
1732    /// // Usually floats are parsed leveraging float guarantees. i.e. 0.1_f32 => 0.1
1733    /// assert_eq!("0.1", Decimal::from_f32(0.1_f32).unwrap().to_string());
1734    ///
1735    /// // Sometimes, we may want to represent the approximation exactly.
1736    /// assert_eq!("0.100000001490116119384765625", Decimal::from_f32_retain(0.1_f32).unwrap().to_string());
1737    /// ```
1738    pub fn from_f32_retain(n: f32) -> Option<Self> {
1739        from_f32(n, false)
1740    }
1741
1742    /// Parses a 64-bit float into a Decimal number whilst retaining any non-guaranteed precision.
1743    ///
1744    /// Typically when a float is parsed in Rust Decimal, any excess bits (after ~15.95 decimal points for
1745    /// f64 as per IEEE-754) are removed due to any digits following this are considered an approximation
1746    /// at best. This function bypasses this additional step and retains these excess bits.
1747    ///
1748    /// # Example
1749    ///
1750    /// ```
1751    /// # use rust_decimal::prelude::*;
1752    /// #
1753    /// // Usually floats are parsed leveraging float guarantees. i.e. 0.1_f64 => 0.1
1754    /// assert_eq!("0.1", Decimal::from_f64(0.1_f64).unwrap().to_string());
1755    ///
1756    /// // Sometimes, we may want to represent the approximation exactly.
1757    /// assert_eq!("0.1000000000000000055511151231", Decimal::from_f64_retain(0.1_f64).unwrap().to_string());
1758    /// ```
1759    pub fn from_f64_retain(n: f64) -> Option<Self> {
1760        from_f64(n, false)
1761    }
1762}
1763
1764impl Default for Decimal {
1765    /// Returns the default value for a `Decimal` (equivalent to `Decimal::ZERO`). [Read more]
1766    ///
1767    /// [Read more]: core::default::Default#tymethod.default
1768    #[inline]
1769    fn default() -> Self {
1770        ZERO
1771    }
1772}
1773
1774pub(crate) enum CalculationResult {
1775    Ok(Decimal),
1776    Overflow,
1777    DivByZero,
1778}
1779
1780#[inline]
1781const fn flags(neg: bool, scale: u32) -> u32 {
1782    (scale << SCALE_SHIFT) | ((neg as u32) << SIGN_SHIFT)
1783}
1784
1785macro_rules! integer_docs {
1786    ( true ) => {
1787        " by truncating and returning the integer component"
1788    };
1789    ( false ) => {
1790        ""
1791    };
1792}
1793
1794// #[doc] attributes are formatted poorly with rustfmt so skip for now.
1795// See https://github.com/rust-lang/rustfmt/issues/5062 for more information.
1796#[rustfmt::skip]
1797macro_rules! impl_try_from_decimal {
1798    ($TInto:ty, $conversion_fn:path, $additional_docs:expr) => {
1799        #[doc = concat!(
1800            "Try to convert a `Decimal` to `",
1801            stringify!($TInto),
1802            "`",
1803            $additional_docs,
1804            ".\n\nCan fail if the `Decimal` is out of range for `",
1805            stringify!($TInto),
1806            "`.",
1807        )]
1808        impl TryFrom<Decimal> for $TInto {
1809            type Error = crate::Error;
1810
1811            #[inline]
1812            fn try_from(t: Decimal) -> Result<Self, Error> {
1813                $conversion_fn(&t).ok_or_else(|| Error::ConversionTo(stringify!($TInto).into()))
1814            }
1815        }
1816    };
1817}
1818
1819impl_try_from_decimal!(f32, Decimal::to_f32, integer_docs!(false));
1820impl_try_from_decimal!(f64, Decimal::to_f64, integer_docs!(false));
1821impl_try_from_decimal!(isize, Decimal::to_isize, integer_docs!(true));
1822impl_try_from_decimal!(i8, Decimal::to_i8, integer_docs!(true));
1823impl_try_from_decimal!(i16, Decimal::to_i16, integer_docs!(true));
1824impl_try_from_decimal!(i32, Decimal::to_i32, integer_docs!(true));
1825impl_try_from_decimal!(i64, Decimal::to_i64, integer_docs!(true));
1826impl_try_from_decimal!(i128, Decimal::to_i128, integer_docs!(true));
1827impl_try_from_decimal!(usize, Decimal::to_usize, integer_docs!(true));
1828impl_try_from_decimal!(u8, Decimal::to_u8, integer_docs!(true));
1829impl_try_from_decimal!(u16, Decimal::to_u16, integer_docs!(true));
1830impl_try_from_decimal!(u32, Decimal::to_u32, integer_docs!(true));
1831impl_try_from_decimal!(u64, Decimal::to_u64, integer_docs!(true));
1832impl_try_from_decimal!(u128, Decimal::to_u128, integer_docs!(true));
1833
1834// #[doc] attributes are formatted poorly with rustfmt so skip for now.
1835// See https://github.com/rust-lang/rustfmt/issues/5062 for more information.
1836#[rustfmt::skip]
1837macro_rules! impl_try_from_primitive {
1838    ($TFrom:ty, $conversion_fn:path $(, $err:expr)?) => {
1839        #[doc = concat!(
1840            "Try to convert a `",
1841            stringify!($TFrom),
1842            "` into a `Decimal`.\n\nCan fail if the value is out of range for `Decimal`."
1843        )]
1844        impl TryFrom<$TFrom> for Decimal {
1845            type Error = crate::Error;
1846
1847            #[inline]
1848            fn try_from(t: $TFrom) -> Result<Self, Error> {
1849                $conversion_fn(t) $( .ok_or_else(|| $err) )?
1850            }
1851        }
1852    };
1853}
1854
1855impl_try_from_primitive!(f32, Self::from_f32, Error::ConversionTo("Decimal".into()));
1856impl_try_from_primitive!(f64, Self::from_f64, Error::ConversionTo("Decimal".into()));
1857impl_try_from_primitive!(&str, core::str::FromStr::from_str);
1858
1859macro_rules! impl_from {
1860    ($T:ty, $from_ty:path) => {
1861        ///
1862        /// Conversion to `Decimal`.
1863        ///
1864        impl core::convert::From<$T> for Decimal {
1865            #[inline]
1866            fn from(t: $T) -> Self {
1867                $from_ty(t).unwrap()
1868            }
1869        }
1870    };
1871}
1872
1873impl_from!(isize, FromPrimitive::from_isize);
1874impl_from!(i8, FromPrimitive::from_i8);
1875impl_from!(i16, FromPrimitive::from_i16);
1876impl_from!(i32, FromPrimitive::from_i32);
1877impl_from!(i64, FromPrimitive::from_i64);
1878impl_from!(usize, FromPrimitive::from_usize);
1879impl_from!(u8, FromPrimitive::from_u8);
1880impl_from!(u16, FromPrimitive::from_u16);
1881impl_from!(u32, FromPrimitive::from_u32);
1882impl_from!(u64, FromPrimitive::from_u64);
1883
1884impl_from!(i128, FromPrimitive::from_i128);
1885impl_from!(u128, FromPrimitive::from_u128);
1886
1887impl Zero for Decimal {
1888    fn zero() -> Decimal {
1889        ZERO
1890    }
1891
1892    fn is_zero(&self) -> bool {
1893        self.is_zero()
1894    }
1895}
1896
1897impl One for Decimal {
1898    fn one() -> Decimal {
1899        ONE
1900    }
1901}
1902
1903impl Signed for Decimal {
1904    fn abs(&self) -> Self {
1905        self.abs()
1906    }
1907
1908    fn abs_sub(&self, other: &Self) -> Self {
1909        if self <= other {
1910            ZERO
1911        } else {
1912            self - other
1913        }
1914    }
1915
1916    fn signum(&self) -> Self {
1917        if self.is_zero() {
1918            ZERO
1919        } else {
1920            let mut value = ONE;
1921            if self.is_sign_negative() {
1922                value.set_sign_negative(true);
1923            }
1924            value
1925        }
1926    }
1927
1928    fn is_positive(&self) -> bool {
1929        self.is_sign_positive()
1930    }
1931
1932    fn is_negative(&self) -> bool {
1933        self.is_sign_negative()
1934    }
1935}
1936
1937impl Num for Decimal {
1938    type FromStrRadixErr = Error;
1939
1940    fn from_str_radix(str: &str, radix: u32) -> Result<Self, Self::FromStrRadixErr> {
1941        Decimal::from_str_radix(str, radix)
1942    }
1943}
1944
1945impl FromStr for Decimal {
1946    type Err = Error;
1947
1948    fn from_str(value: &str) -> Result<Decimal, Self::Err> {
1949        crate::str::parse_str_radix_10(value)
1950    }
1951}
1952
1953impl FromPrimitive for Decimal {
1954    fn from_i32(n: i32) -> Option<Decimal> {
1955        let flags: u32;
1956        let value_copy: i64;
1957        if n >= 0 {
1958            flags = 0;
1959            value_copy = n as i64;
1960        } else {
1961            flags = SIGN_MASK;
1962            value_copy = -(n as i64);
1963        }
1964        Some(Decimal {
1965            flags,
1966            lo: value_copy as u32,
1967            mid: 0,
1968            hi: 0,
1969        })
1970    }
1971
1972    fn from_i64(n: i64) -> Option<Decimal> {
1973        let flags: u32;
1974        let value_copy: i128;
1975        if n >= 0 {
1976            flags = 0;
1977            value_copy = n as i128;
1978        } else {
1979            flags = SIGN_MASK;
1980            value_copy = -(n as i128);
1981        }
1982        Some(Decimal {
1983            flags,
1984            lo: value_copy as u32,
1985            mid: (value_copy >> 32) as u32,
1986            hi: 0,
1987        })
1988    }
1989
1990    fn from_i128(n: i128) -> Option<Decimal> {
1991        let flags;
1992        let unsigned;
1993        if n >= 0 {
1994            unsigned = n as u128;
1995            flags = 0;
1996        } else {
1997            unsigned = n.unsigned_abs();
1998            flags = SIGN_MASK;
1999        };
2000        // Check if we overflow
2001        if unsigned >> 96 != 0 {
2002            return None;
2003        }
2004        Some(Decimal {
2005            flags,
2006            lo: unsigned as u32,
2007            mid: (unsigned >> 32) as u32,
2008            hi: (unsigned >> 64) as u32,
2009        })
2010    }
2011
2012    fn from_u32(n: u32) -> Option<Decimal> {
2013        Some(Decimal {
2014            flags: 0,
2015            lo: n,
2016            mid: 0,
2017            hi: 0,
2018        })
2019    }
2020
2021    fn from_u64(n: u64) -> Option<Decimal> {
2022        Some(Decimal {
2023            flags: 0,
2024            lo: n as u32,
2025            mid: (n >> 32) as u32,
2026            hi: 0,
2027        })
2028    }
2029
2030    fn from_u128(n: u128) -> Option<Decimal> {
2031        // Check if we overflow
2032        if n >> 96 != 0 {
2033            return None;
2034        }
2035        Some(Decimal {
2036            flags: 0,
2037            lo: n as u32,
2038            mid: (n >> 32) as u32,
2039            hi: (n >> 64) as u32,
2040        })
2041    }
2042
2043    fn from_f32(n: f32) -> Option<Decimal> {
2044        // By default, we remove excess bits. This allows 0.1_f64 == dec!(0.1).
2045        from_f32(n, true)
2046    }
2047
2048    fn from_f64(n: f64) -> Option<Decimal> {
2049        // By default, we remove excess bits. This allows 0.1_f64 == dec!(0.1).
2050        from_f64(n, true)
2051    }
2052}
2053
2054#[inline]
2055fn from_f64(n: f64, remove_excess_bits: bool) -> Option<Decimal> {
2056    // Handle the case if it is NaN, Infinity or -Infinity
2057    if !n.is_finite() {
2058        return None;
2059    }
2060
2061    // It's a shame we can't use a union for this due to it being broken up by bits
2062    // i.e. 1/11/52 (sign, exponent, mantissa)
2063    // See https://en.wikipedia.org/wiki/IEEE_754-1985
2064    // n = (sign*-1) * 2^exp * mantissa
2065    // Decimal of course stores this differently... 10^-exp * significand
2066    let raw = n.to_bits();
2067    let positive = (raw >> 63) == 0;
2068    let biased_exponent = ((raw >> 52) & 0x7FF) as i32;
2069    let mantissa = raw & 0x000F_FFFF_FFFF_FFFF;
2070
2071    // Handle the special zero case
2072    if biased_exponent == 0 && mantissa == 0 {
2073        let mut zero = ZERO;
2074        if !positive {
2075            zero.set_sign_negative(true);
2076        }
2077        return Some(zero);
2078    }
2079
2080    // Get the bits and exponent2
2081    let mut exponent2 = biased_exponent - 1023;
2082    let mut bits = [
2083        (mantissa & 0xFFFF_FFFF) as u32,
2084        ((mantissa >> 32) & 0xFFFF_FFFF) as u32,
2085        0u32,
2086    ];
2087    if biased_exponent == 0 {
2088        // Denormalized number - correct the exponent
2089        exponent2 += 1;
2090    } else {
2091        // Add extra hidden bit to mantissa
2092        bits[1] |= 0x0010_0000;
2093    }
2094
2095    // The act of copying a mantissa as integer bits is equivalent to shifting
2096    // left the mantissa 52 bits. The exponent is reduced to compensate.
2097    exponent2 -= 52;
2098
2099    // Convert to decimal
2100    base2_to_decimal(&mut bits, exponent2, positive, true, remove_excess_bits)
2101}
2102
2103#[inline]
2104fn from_f32(n: f32, remove_excess_bits: bool) -> Option<Decimal> {
2105    // Handle the case if it is NaN, Infinity or -Infinity
2106    if !n.is_finite() {
2107        return None;
2108    }
2109
2110    // It's a shame we can't use a union for this due to it being broken up by bits
2111    // i.e. 1/8/23 (sign, exponent, mantissa)
2112    // See https://en.wikipedia.org/wiki/IEEE_754-1985
2113    // n = (sign*-1) * 2^exp * mantissa
2114    // Decimal of course stores this differently... 10^-exp * significand
2115    let raw = n.to_bits();
2116    let positive = (raw >> 31) == 0;
2117    let biased_exponent = ((raw >> 23) & 0xFF) as i32;
2118    let mantissa = raw & 0x007F_FFFF;
2119
2120    // Handle the special zero case
2121    if biased_exponent == 0 && mantissa == 0 {
2122        let mut zero = ZERO;
2123        if !positive {
2124            zero.set_sign_negative(true);
2125        }
2126        return Some(zero);
2127    }
2128
2129    // Get the bits and exponent2
2130    let mut exponent2 = biased_exponent - 127;
2131    let mut bits = [mantissa, 0u32, 0u32];
2132    if biased_exponent == 0 {
2133        // Denormalized number - correct the exponent
2134        exponent2 += 1;
2135    } else {
2136        // Add extra hidden bit to mantissa
2137        bits[0] |= 0x0080_0000;
2138    }
2139
2140    // The act of copying a mantissa as integer bits is equivalent to shifting
2141    // left the mantissa 23 bits. The exponent is reduced to compensate.
2142    exponent2 -= 23;
2143
2144    // Convert to decimal
2145    base2_to_decimal(&mut bits, exponent2, positive, false, remove_excess_bits)
2146}
2147
2148fn base2_to_decimal(
2149    bits: &mut [u32; 3],
2150    exponent2: i32,
2151    positive: bool,
2152    is64: bool,
2153    remove_excess_bits: bool,
2154) -> Option<Decimal> {
2155    // 2^exponent2 = (10^exponent2)/(5^exponent2)
2156    //             = (5^-exponent2)*(10^exponent2)
2157    let mut exponent5 = -exponent2;
2158    let mut exponent10 = exponent2; // Ultimately, we want this for the scale
2159
2160    while exponent5 > 0 {
2161        // Check to see if the mantissa is divisible by 2
2162        if bits[0] & 0x1 == 0 {
2163            exponent10 += 1;
2164            exponent5 -= 1;
2165
2166            // We can divide by 2 without losing precision
2167            let hi_carry = bits[2] & 0x1 == 1;
2168            bits[2] >>= 1;
2169            let mid_carry = bits[1] & 0x1 == 1;
2170            bits[1] = (bits[1] >> 1) | if hi_carry { SIGN_MASK } else { 0 };
2171            bits[0] = (bits[0] >> 1) | if mid_carry { SIGN_MASK } else { 0 };
2172        } else {
2173            // The mantissa is NOT divisible by 2. Therefore the mantissa should
2174            // be multiplied by 5, unless the multiplication overflows.
2175            exponent5 -= 1;
2176
2177            let mut temp = [bits[0], bits[1], bits[2]];
2178            if ops::array::mul_by_u32(&mut temp, 5) == 0 {
2179                // Multiplication succeeded without overflow, so copy result back
2180                bits[0] = temp[0];
2181                bits[1] = temp[1];
2182                bits[2] = temp[2];
2183            } else {
2184                // Multiplication by 5 overflows. The mantissa should be divided
2185                // by 2, and therefore will lose significant digits.
2186                exponent10 += 1;
2187
2188                // Shift right
2189                let hi_carry = bits[2] & 0x1 == 1;
2190                bits[2] >>= 1;
2191                let mid_carry = bits[1] & 0x1 == 1;
2192                bits[1] = (bits[1] >> 1) | if hi_carry { SIGN_MASK } else { 0 };
2193                bits[0] = (bits[0] >> 1) | if mid_carry { SIGN_MASK } else { 0 };
2194            }
2195        }
2196    }
2197
2198    // In order to divide the value by 5, it is best to multiply by 2/10.
2199    // Therefore, exponent10 is decremented, and the mantissa should be multiplied by 2
2200    while exponent5 < 0 {
2201        if bits[2] & SIGN_MASK == 0 {
2202            // No far left bit, the mantissa can withstand a shift-left without overflowing
2203            exponent10 -= 1;
2204            exponent5 += 1;
2205            ops::array::shl1_internal(bits, 0);
2206        } else if exponent10 * 2 > -exponent5 {
2207            // Multiplying by >=2 which, due to the previous condition, means an overflow.
2208            return None;
2209        } else {
2210            // The mantissa would overflow if shifted. Therefore it should be
2211            // directly divided by 5. This will lose significant digits, unless
2212            // by chance the mantissa happens to be divisible by 5.
2213            exponent5 += 1;
2214            ops::array::div_by_u32(bits, 5);
2215        }
2216    }
2217
2218    // At this point, the mantissa has assimilated the exponent5, but
2219    // exponent10 might not be suitable for assignment. exponent10 must be
2220    // in the range [-MAX_SCALE..0], so the mantissa must be scaled up or
2221    // down appropriately.
2222    while exponent10 > 0 {
2223        // In order to bring exponent10 down to 0, the mantissa should be
2224        // multiplied by 10 to compensate. If the exponent10 is too big, this
2225        // will cause the mantissa to overflow.
2226        if ops::array::mul_by_u32(bits, 10) == 0 {
2227            exponent10 -= 1;
2228        } else {
2229            // Overflowed - return?
2230            return None;
2231        }
2232    }
2233
2234    // In order to bring exponent up to -MAX_SCALE, the mantissa should
2235    // be divided by 10 to compensate. If the exponent10 is too small, this
2236    // will cause the mantissa to underflow and become 0.
2237    while exponent10 < -(Decimal::MAX_SCALE as i32) {
2238        let rem10 = ops::array::div_by_u32(bits, 10);
2239        exponent10 += 1;
2240        if ops::array::is_all_zero(bits) {
2241            // Underflow, unable to keep dividing
2242            exponent10 = 0;
2243        } else if rem10 >= 5 {
2244            ops::array::add_one_internal(bits);
2245        }
2246    }
2247
2248    if remove_excess_bits {
2249        // This step is required in order to remove excess bits of precision from the
2250        // end of the bit representation, down to the precision guaranteed by the
2251        // floating point number (see IEEE-754).
2252        if is64 {
2253            // Guaranteed to approx 15/16 dp
2254            while exponent10 < 0 && (bits[2] != 0 || (bits[1] & 0xFFF0_0000) != 0) {
2255                let rem10 = ops::array::div_by_u32(bits, 10);
2256                exponent10 += 1;
2257                if rem10 >= 5 {
2258                    ops::array::add_one_internal(bits);
2259                }
2260            }
2261        } else {
2262            // Guaranteed to about 7/8 dp
2263            while exponent10 < 0 && ((bits[0] & 0xFF00_0000) != 0 || bits[1] != 0 || bits[2] != 0) {
2264                let rem10 = ops::array::div_by_u32(bits, 10);
2265                exponent10 += 1;
2266                if rem10 >= 5 {
2267                    ops::array::add_one_internal(bits);
2268                }
2269            }
2270        }
2271
2272        // Remove multiples of 10 from the representation
2273        while exponent10 < 0 {
2274            let mut temp = [bits[0], bits[1], bits[2]];
2275            let remainder = ops::array::div_by_u32(&mut temp, 10);
2276            if remainder == 0 {
2277                exponent10 += 1;
2278                bits[0] = temp[0];
2279                bits[1] = temp[1];
2280                bits[2] = temp[2];
2281            } else {
2282                break;
2283            }
2284        }
2285    }
2286
2287    Some(Decimal {
2288        lo: bits[0],
2289        mid: bits[1],
2290        hi: bits[2],
2291        flags: flags(!positive, -exponent10 as u32),
2292    })
2293}
2294
2295impl ToPrimitive for Decimal {
2296    fn to_i64(&self) -> Option<i64> {
2297        let d = self.trunc();
2298        // If it is in the hi bit then it is a clear overflow.
2299        if d.hi != 0 {
2300            // Overflow
2301            return None;
2302        }
2303        let negative = self.is_sign_negative();
2304
2305        // A bit more convoluted in terms of checking when it comes to the hi bit due to twos-complement
2306        if d.mid & 0x8000_0000 > 0 {
2307            if negative && d.mid == 0x8000_0000 && d.lo == 0 {
2308                // We do this because below we try to convert the i64 to a positive first - of which
2309                // doesn't fit into an i64.
2310                return Some(i64::MIN);
2311            }
2312            return None;
2313        }
2314
2315        let raw: i64 = (i64::from(d.mid) << 32) | i64::from(d.lo);
2316        if negative {
2317            Some(raw.neg())
2318        } else {
2319            Some(raw)
2320        }
2321    }
2322
2323    fn to_i128(&self) -> Option<i128> {
2324        let d = self.trunc();
2325        let raw: i128 = ((i128::from(d.hi) << 64) | (i128::from(d.mid) << 32)) | i128::from(d.lo);
2326        if self.is_sign_negative() {
2327            Some(-raw)
2328        } else {
2329            Some(raw)
2330        }
2331    }
2332
2333    fn to_u64(&self) -> Option<u64> {
2334        if self.is_sign_negative() {
2335            return None;
2336        }
2337
2338        let d = self.trunc();
2339        if d.hi != 0 {
2340            // Overflow
2341            return None;
2342        }
2343
2344        Some((u64::from(d.mid) << 32) | u64::from(d.lo))
2345    }
2346
2347    fn to_u128(&self) -> Option<u128> {
2348        if self.is_sign_negative() {
2349            return None;
2350        }
2351
2352        let d = self.trunc();
2353        Some((u128::from(d.hi) << 64) | (u128::from(d.mid) << 32) | u128::from(d.lo))
2354    }
2355
2356    fn to_f64(&self) -> Option<f64> {
2357        if self.scale() == 0 {
2358            // If scale is zero, we are storing a 96-bit integer value, that would
2359            // always fit into i128, which in turn is always representable as f64,
2360            // albeit with loss of precision for values outside of -2^53..2^53 range.
2361            let integer = self.to_i128();
2362            integer.map(|i| i as f64)
2363        } else {
2364            let neg = self.is_sign_negative();
2365            let mut mantissa: u128 = self.lo.into();
2366            mantissa |= (self.mid as u128) << 32;
2367            mantissa |= (self.hi as u128) << 64;
2368            // scale is at most 28, so this fits comfortably into a u128.
2369            let scale = self.scale();
2370            let precision: u128 = 10_u128.pow(scale);
2371            let integral_part = mantissa / precision;
2372            let frac_part = mantissa % precision;
2373            let frac_f64 = (frac_part as f64) / (precision as f64);
2374            let integral = integral_part as f64;
2375            // If there is a fractional component then we will need to add that and remove any
2376            // inaccuracies that creep in during addition. Otherwise, if the fractional component
2377            // is zero we can exit early.
2378            if frac_f64.is_zero() {
2379                if neg {
2380                    return Some(-integral);
2381                }
2382                return Some(integral);
2383            }
2384            let value = integral + frac_f64;
2385            let round_to = 10f64.powi(self.scale() as i32);
2386            let rounded = (value * round_to).round() / round_to;
2387            if neg {
2388                Some(-rounded)
2389            } else {
2390                Some(rounded)
2391            }
2392        }
2393    }
2394}
2395
2396impl fmt::Display for Decimal {
2397    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
2398        let (rep, additional) = crate::str::to_str_internal(self, false, f.precision());
2399        if let Some(additional) = additional {
2400            let value = [rep.as_str(), "0".repeat(additional).as_str()].concat();
2401            f.pad_integral(self.is_sign_positive(), "", value.as_str())
2402        } else {
2403            f.pad_integral(self.is_sign_positive(), "", rep.as_str())
2404        }
2405    }
2406}
2407
2408impl fmt::Debug for Decimal {
2409    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
2410        fmt::Display::fmt(self, f)
2411    }
2412}
2413
2414impl fmt::LowerExp for Decimal {
2415    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2416        crate::str::fmt_scientific_notation(self, "e", f)
2417    }
2418}
2419
2420impl fmt::UpperExp for Decimal {
2421    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2422        crate::str::fmt_scientific_notation(self, "E", f)
2423    }
2424}
2425
2426impl Neg for Decimal {
2427    type Output = Decimal;
2428
2429    fn neg(self) -> Decimal {
2430        let mut copy = self;
2431        copy.set_sign_negative(self.is_sign_positive());
2432        copy
2433    }
2434}
2435
2436impl Neg for &Decimal {
2437    type Output = Decimal;
2438
2439    fn neg(self) -> Decimal {
2440        Decimal {
2441            flags: flags(!self.is_sign_negative(), self.scale()),
2442            hi: self.hi,
2443            lo: self.lo,
2444            mid: self.mid,
2445        }
2446    }
2447}
2448
2449impl AddAssign for Decimal {
2450    fn add_assign(&mut self, other: Decimal) {
2451        let result = self.add(other);
2452        self.lo = result.lo;
2453        self.mid = result.mid;
2454        self.hi = result.hi;
2455        self.flags = result.flags;
2456    }
2457}
2458
2459impl<'a> AddAssign<&'a Decimal> for Decimal {
2460    fn add_assign(&mut self, other: &'a Decimal) {
2461        Decimal::add_assign(self, *other)
2462    }
2463}
2464
2465impl AddAssign<Decimal> for &mut Decimal {
2466    fn add_assign(&mut self, other: Decimal) {
2467        Decimal::add_assign(*self, other)
2468    }
2469}
2470
2471impl<'a> AddAssign<&'a Decimal> for &'a mut Decimal {
2472    fn add_assign(&mut self, other: &'a Decimal) {
2473        Decimal::add_assign(*self, *other)
2474    }
2475}
2476
2477impl SubAssign for Decimal {
2478    fn sub_assign(&mut self, other: Decimal) {
2479        let result = self.sub(other);
2480        self.lo = result.lo;
2481        self.mid = result.mid;
2482        self.hi = result.hi;
2483        self.flags = result.flags;
2484    }
2485}
2486
2487impl<'a> SubAssign<&'a Decimal> for Decimal {
2488    fn sub_assign(&mut self, other: &'a Decimal) {
2489        Decimal::sub_assign(self, *other)
2490    }
2491}
2492
2493impl SubAssign<Decimal> for &mut Decimal {
2494    fn sub_assign(&mut self, other: Decimal) {
2495        Decimal::sub_assign(*self, other)
2496    }
2497}
2498
2499impl<'a> SubAssign<&'a Decimal> for &'a mut Decimal {
2500    fn sub_assign(&mut self, other: &'a Decimal) {
2501        Decimal::sub_assign(*self, *other)
2502    }
2503}
2504
2505impl MulAssign for Decimal {
2506    fn mul_assign(&mut self, other: Decimal) {
2507        let result = self.mul(other);
2508        self.lo = result.lo;
2509        self.mid = result.mid;
2510        self.hi = result.hi;
2511        self.flags = result.flags;
2512    }
2513}
2514
2515impl<'a> MulAssign<&'a Decimal> for Decimal {
2516    fn mul_assign(&mut self, other: &'a Decimal) {
2517        Decimal::mul_assign(self, *other)
2518    }
2519}
2520
2521impl MulAssign<Decimal> for &mut Decimal {
2522    fn mul_assign(&mut self, other: Decimal) {
2523        Decimal::mul_assign(*self, other)
2524    }
2525}
2526
2527impl<'a> MulAssign<&'a Decimal> for &'a mut Decimal {
2528    fn mul_assign(&mut self, other: &'a Decimal) {
2529        Decimal::mul_assign(*self, *other)
2530    }
2531}
2532
2533impl DivAssign for Decimal {
2534    fn div_assign(&mut self, other: Decimal) {
2535        let result = self.div(other);
2536        self.lo = result.lo;
2537        self.mid = result.mid;
2538        self.hi = result.hi;
2539        self.flags = result.flags;
2540    }
2541}
2542
2543impl<'a> DivAssign<&'a Decimal> for Decimal {
2544    fn div_assign(&mut self, other: &'a Decimal) {
2545        Decimal::div_assign(self, *other)
2546    }
2547}
2548
2549impl DivAssign<Decimal> for &mut Decimal {
2550    fn div_assign(&mut self, other: Decimal) {
2551        Decimal::div_assign(*self, other)
2552    }
2553}
2554
2555impl<'a> DivAssign<&'a Decimal> for &'a mut Decimal {
2556    fn div_assign(&mut self, other: &'a Decimal) {
2557        Decimal::div_assign(*self, *other)
2558    }
2559}
2560
2561impl RemAssign for Decimal {
2562    fn rem_assign(&mut self, other: Decimal) {
2563        let result = self.rem(other);
2564        self.lo = result.lo;
2565        self.mid = result.mid;
2566        self.hi = result.hi;
2567        self.flags = result.flags;
2568    }
2569}
2570
2571impl<'a> RemAssign<&'a Decimal> for Decimal {
2572    fn rem_assign(&mut self, other: &'a Decimal) {
2573        Decimal::rem_assign(self, *other)
2574    }
2575}
2576
2577impl RemAssign<Decimal> for &mut Decimal {
2578    fn rem_assign(&mut self, other: Decimal) {
2579        Decimal::rem_assign(*self, other)
2580    }
2581}
2582
2583impl<'a> RemAssign<&'a Decimal> for &'a mut Decimal {
2584    fn rem_assign(&mut self, other: &'a Decimal) {
2585        Decimal::rem_assign(*self, *other)
2586    }
2587}
2588
2589impl PartialEq for Decimal {
2590    #[inline]
2591    fn eq(&self, other: &Decimal) -> bool {
2592        self.cmp(other) == Equal
2593    }
2594}
2595
2596impl Eq for Decimal {}
2597
2598impl Hash for Decimal {
2599    fn hash<H: Hasher>(&self, state: &mut H) {
2600        let n = self.normalize();
2601        n.lo.hash(state);
2602        n.mid.hash(state);
2603        n.hi.hash(state);
2604        n.flags.hash(state);
2605    }
2606}
2607
2608impl PartialOrd for Decimal {
2609    #[inline]
2610    fn partial_cmp(&self, other: &Decimal) -> Option<Ordering> {
2611        Some(self.cmp(other))
2612    }
2613}
2614
2615impl Ord for Decimal {
2616    fn cmp(&self, other: &Decimal) -> Ordering {
2617        ops::cmp_impl(self, other)
2618    }
2619}
2620
2621impl Product for Decimal {
2622    /// Panics if out-of-bounds
2623    fn product<I: Iterator<Item = Decimal>>(iter: I) -> Self {
2624        let mut product = ONE;
2625        for i in iter {
2626            product *= i;
2627        }
2628        product
2629    }
2630}
2631
2632impl<'a> Product<&'a Decimal> for Decimal {
2633    /// Panics if out-of-bounds
2634    fn product<I: Iterator<Item = &'a Decimal>>(iter: I) -> Self {
2635        let mut product = ONE;
2636        for i in iter {
2637            product *= i;
2638        }
2639        product
2640    }
2641}
2642
2643impl Sum for Decimal {
2644    fn sum<I: Iterator<Item = Decimal>>(iter: I) -> Self {
2645        let mut sum = ZERO;
2646        for i in iter {
2647            sum += i;
2648        }
2649        sum
2650    }
2651}
2652
2653impl<'a> Sum<&'a Decimal> for Decimal {
2654    fn sum<I: Iterator<Item = &'a Decimal>>(iter: I) -> Self {
2655        let mut sum = ZERO;
2656        for i in iter {
2657            sum += i;
2658        }
2659        sum
2660    }
2661}