Debian Codegraph @

third_party/rust/rust_decimal/src/decimal.rs

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