fastnum/decimal/udec.rs
1mod consts;
2mod impls;
3
4pub(crate) mod extras;
5
6use core::{cmp::Ordering, num::FpCategory};
7
8#[cfg(not(feature = "std"))]
9use alloc::string::String;
10
11use crate::{
12 bint::UInt,
13 decimal,
14 decimal::{
15 doc, signals::Signals, udec::consts::consts_impl, Context, Decimal, DecimalError,
16 ParseError, RoundingMode, Sign,
17 },
18};
19
20/// # Unsigned Decimal
21///
22/// Generic unsigned N-bits decimal number.
23#[derive(Copy, Clone)]
24#[repr(transparent)]
25pub struct UnsignedDecimal<const N: usize>(Decimal<N>);
26
27consts_impl!();
28
29impl<const N: usize> UnsignedDecimal<N> {
30 /// Creates and initializes unsigned decimal from parts.
31 ///
32 /// # Examples
33 ///
34 /// ```
35 /// use fastnum::{*, decimal::*};
36 ///
37 /// assert_eq!(UD256::from_parts(u256!(12345), -4, Context::default()), udec256!(1.2345));
38 /// ```
39 #[must_use]
40 #[inline]
41 pub const fn from_parts(digits: UInt<N>, exp: i32, ctx: Context) -> Self {
42 Self::from_signed(Decimal::from_parts(digits, exp, Sign::Plus, ctx))
43 }
44
45 /// Creates and initializes an unsigned decimal from string.
46 ///
47 /// # Examples
48 ///
49 /// ```
50 /// use fastnum::{*, decimal::*};
51 ///
52 /// assert_eq!(UD256::from_str("1.2345", Context::default()), Ok(udec256!(1.2345)));
53 /// assert_eq!(UD256::from_str("-1.2345", Context::default()), Err(ParseError::Signed));
54 /// ```
55 #[track_caller]
56 #[inline]
57 pub const fn from_str(s: &str, ctx: Context) -> Result<Self, ParseError> {
58 match Decimal::<N>::from_str(s, ctx) {
59 Ok(d) => {
60 if d.is_negative() {
61 Err(ParseError::Signed)
62 } else {
63 Ok(Self::new(d))
64 }
65 }
66 Err(e) => Err(e),
67 }
68 }
69
70 /// Parse an unsigned decimal from string.
71 ///
72 /// # Panics
73 ///
74 /// This function will panic if `UnsignedDecimal<N>` can't be constructed
75 /// from a given string.
76 ///
77 /// # Examples
78 ///
79 /// Basic usage:
80 ///
81 /// ```
82 /// use fastnum::{*, decimal::*};
83 ///
84 /// assert_eq!(UD256::parse_str("1.2345", Context::default()), udec256!(1.2345));
85 /// ```
86 ///
87 /// Should panic:
88 ///
89 /// ```should_panic
90 /// use fastnum::{*, decimal::*};
91 ///
92 /// let _ = UD256::parse_str("-1.2345", Context::default());
93 /// ```
94 #[track_caller]
95 #[must_use]
96 #[inline]
97 pub const fn parse_str(s: &str, ctx: Context) -> Self {
98 match Self::from_str(s, ctx) {
99 Ok(n) => n,
100 Err(e) => panic!("{}", e.description()),
101 }
102 }
103
104 /// Returns the internal big integer, representing the
105 /// [_Coefficient_](crate#representation) of a given `UnsignedDecimal`,
106 /// including significant trailing zeros.
107 ///
108 /// # Examples
109 ///
110 /// ```
111 /// use fastnum::{udec256, u256};
112 ///
113 /// let a = udec256!(123.45);
114 /// assert_eq!(a.digits(), u256!(12345));
115 ///
116 /// let b = udec256!(1.0);
117 /// assert_eq!(b.digits(), u256!(10));
118 /// ```
119 #[inline]
120 pub const fn digits(&self) -> UInt<N> {
121 self.0.digits()
122 }
123
124 /// Returns the count of digits in the non-scaled integer representation
125 #[inline]
126 pub const fn digits_count(&self) -> usize {
127 self.0.digits_count()
128 }
129
130 /// Returns the scale of the `UnsignedDecimal`, the total number of
131 /// digits to the right of the decimal point (including insignificant
132 /// leading zeros).
133 ///
134 /// # Examples
135 ///
136 /// ```
137 /// use fastnum::udec256;
138 ///
139 /// let a = udec256!(12345); // No fractional part
140 /// let b = udec256!(123.45); // Fractional part
141 /// let c = udec256!(0.0000012345); // Completely fractional part
142 /// let d = udec256!(500000000); // No fractional part
143 /// let e = udec256!(5e9); // Negative-fractional part
144 ///
145 /// assert_eq!(a.fractional_digits_count(), 0);
146 /// assert_eq!(b.fractional_digits_count(), 2);
147 /// assert_eq!(c.fractional_digits_count(), 10);
148 /// assert_eq!(d.fractional_digits_count(), 0);
149 /// assert_eq!(e.fractional_digits_count(), -9);
150 /// ```
151 #[inline]
152 pub const fn fractional_digits_count(&self) -> i16 {
153 self.0.fractional_digits_count()
154 }
155
156 /// Return if the referenced unsigned decimal is zero.
157 ///
158 /// # Examples
159 ///
160 /// ```
161 /// use fastnum::{udec256};
162 ///
163 /// let a = udec256!(0);
164 /// assert!(a.is_zero());
165 ///
166 /// let b = udec256!(0.0);
167 /// assert!(b.is_zero());
168 ///
169 /// let c = udec256!(0.00);
170 /// assert!(c.is_zero());
171 ///
172 /// let d = udec256!(0.1);
173 /// assert!(!d.is_zero());
174 /// ```
175 #[inline]
176 pub const fn is_zero(&self) -> bool {
177 self.0.is_zero()
178 }
179
180 /// Return if the referenced unsigned decimal is strictly [Self::ONE].
181 ///
182 /// # Examples
183 ///
184 /// ```
185 /// use fastnum::{udec256};
186 ///
187 /// let a = udec256!(1);
188 /// assert!(a.is_one());
189 ///
190 /// let b = udec256!(10e-1);
191 /// assert!(!b.is_one());
192 /// ```
193 #[inline]
194 pub const fn is_one(&self) -> bool {
195 self.0.is_one()
196 }
197
198 /// Returns `true` if the given decimal number is the result of division by
199 /// zero and `false` otherwise.
200 ///
201 /// # Examples
202 ///
203 /// ```
204 /// use fastnum::{*, decimal::*};
205 ///
206 /// let ctx = Context::default().without_traps();
207 /// let res = udec256!(1.0).with_ctx(ctx) / udec256!(0).with_ctx(ctx);
208 ///
209 /// assert!(res.is_op_div_by_zero());
210 /// ```
211 ///
212 /// More about [`OP_DIV_BY_ZERO`](Signals::OP_DIV_BY_ZERO) signal.
213 #[must_use]
214 #[inline]
215 pub const fn is_op_div_by_zero(&self) -> bool {
216 self.0.is_op_div_by_zero()
217 }
218
219 /// Return `true` if the argument has [Signals::OP_INVALID] signal flag, and
220 /// `false` otherwise.
221 #[must_use]
222 #[inline]
223 pub const fn is_op_invalid(&self) -> bool {
224 self.0.is_op_invalid()
225 }
226
227 /// Return `true` if the argument has [Signals::OP_SUBNORMAL] signal flag,
228 /// and `false` otherwise.
229 #[must_use]
230 #[inline]
231 pub const fn is_op_subnormal(&self) -> bool {
232 self.0.is_op_subnormal()
233 }
234
235 /// Return `true` if the argument has [Signals::OP_INEXACT] signal flag, and
236 /// `false` otherwise.
237 #[must_use]
238 #[inline]
239 pub const fn is_op_inexact(&self) -> bool {
240 self.0.is_op_inexact()
241 }
242
243 /// Return `true` if the argument has [Signals::OP_ROUNDED] signal flag, and
244 /// `false` otherwise.
245 #[must_use]
246 #[inline]
247 pub const fn is_op_rounded(&self) -> bool {
248 self.0.is_op_rounded()
249 }
250
251 /// Return `true` if the argument has [Signals::OP_CLAMPED] signal flag, and
252 /// `false` otherwise.
253 #[must_use]
254 #[inline]
255 pub const fn is_op_clamped(&self) -> bool {
256 self.0.is_op_clamped()
257 }
258
259 /// Return `true` if the argument has [Signals::OP_OVERFLOW] signal flag,
260 /// and `false` otherwise.
261 #[must_use]
262 #[inline]
263 pub const fn is_op_overflow(&self) -> bool {
264 self.0.is_op_overflow()
265 }
266
267 /// Return `true` if the argument has [Signals::OP_UNDERFLOW] signal flag,
268 /// and `false` otherwise.
269 #[must_use]
270 #[inline]
271 pub const fn is_op_underflow(&self) -> bool {
272 self.0.is_op_underflow()
273 }
274
275 /// Return `true` if the argument has no signal flags, and `false`
276 /// otherwise.
277 #[must_use]
278 #[inline]
279 pub const fn is_op_ok(&self) -> bool {
280 self.0.is_op_ok()
281 }
282
283 /// Return the [`signaling block`](Signals) of given unsigned decimal.
284 #[must_use]
285 #[inline]
286 pub const fn op_signals(&self) -> Signals {
287 self.signals()
288 }
289
290 /// Return the decimal category of the number.
291 /// If only one property is going to be tested, it is generally faster to
292 /// use the specific predicate instead.
293 ///
294 /// # Examples
295 ///
296 /// ```
297 /// use core::num::FpCategory;
298 /// use fastnum::{udec256, UD256};
299 ///
300 /// let num = udec256!(12.4);
301 /// let inf = UD256::INFINITY;
302 ///
303 /// assert_eq!(num.classify(), FpCategory::Normal);
304 /// assert_eq!(inf.classify(), FpCategory::Infinite);
305 /// ```
306 #[must_use]
307 #[inline]
308 pub const fn classify(&self) -> FpCategory {
309 self.0.classify()
310 }
311
312 /// Return `true` if the number is neither [zero], [`Infinity`],
313 /// [subnormal], or [`NaN`] and `false` otherwise.
314 ///
315 /// # Examples
316 ///
317 /// ```
318 /// use fastnum::*;
319 ///
320 /// let num = udec256!(12.4);
321 /// let subnormal = udec256!(1E-30000) / udec256!(1E2768);
322 /// let inf = UD256::INFINITY;
323 /// let nan = UD256::NAN;
324 /// let zero = UD256::ZERO;
325 ///
326 /// assert!(num.is_normal());
327 ///
328 /// assert!(!zero.is_normal());
329 /// assert!(!nan.is_normal());
330 /// assert!(!nan.is_normal());
331 /// assert!(!subnormal.is_normal());
332 /// ```
333 ///
334 /// [subnormal]: crate#normal-numbers-subnormal-numbers-and-underflow
335 /// [zero]: crate#signed-zero
336 /// [`Infinity`]: crate#special-values
337 /// [`NaN`]: crate#special-values
338 #[must_use]
339 #[inline]
340 pub const fn is_normal(self) -> bool {
341 self.0.is_normal()
342 }
343
344 /// Return `true` if the number is [subnormal] and `false` otherwise.
345 ///
346 /// # Examples
347 ///
348 /// ```
349 /// use fastnum::*;
350 ///
351 /// let num = udec256!(12.4);
352 /// let subnormal = udec256!(1E-30000) / udec256!(1E2768);
353 /// let inf = UD256::INFINITY;
354 /// let nan = UD256::NAN;
355 /// let zero = UD256::ZERO;
356 ///
357 /// assert!(subnormal.is_subnormal());
358 ///
359 /// assert!(!num.is_subnormal());
360 /// assert!(!zero.is_subnormal());
361 /// assert!(!nan.is_subnormal());
362 /// assert!(!nan.is_subnormal());
363 /// ```
364 ///
365 /// [subnormal]: crate#normal-numbers-subnormal-numbers-and-underflow
366 #[must_use]
367 #[inline]
368 pub const fn is_subnormal(self) -> bool {
369 self.0.is_subnormal()
370 }
371
372 /// Return `true` if this number is neither [`Infinity`] nor [`NaN`] and
373 /// `false` otherwise.
374 ///
375 /// # Examples
376 ///
377 /// ```
378 /// use fastnum::{UD256, udec256};
379 ///
380 /// let d = udec256!(7.0);
381 /// let inf = UD256::INFINITY;
382 /// let nan = UD256::NAN;
383 ///
384 /// assert!(d.is_finite());
385 ///
386 /// assert!(!nan.is_finite());
387 /// assert!(!inf.is_finite());
388 /// ```
389 ///
390 /// [`Infinity`]: crate#special-values
391 /// [`NaN`]: crate#special-values
392 #[must_use]
393 #[inline]
394 pub const fn is_finite(self) -> bool {
395 self.0.is_finite()
396 }
397
398 /// Return `true` if this value is [`Infinity`] and `false` otherwise.
399 ///
400 /// # Examples
401 ///
402 /// ```
403 /// use fastnum::{UD256, udec256};
404 ///
405 /// let d = udec256!(7.0);
406 /// let inf = UD256::INFINITY;
407 /// let nan = UD256::NAN;
408 ///
409 /// assert!(inf.is_infinite());
410 ///
411 /// assert!(!d.is_infinite());
412 /// assert!(!nan.is_infinite());
413 /// ```
414 ///
415 /// [`Infinity`]: crate#special-values
416 #[must_use]
417 #[inline]
418 pub const fn is_infinite(self) -> bool {
419 self.0.is_infinite()
420 }
421
422 /// Return `true` if this value is [`NaN`] and `false` otherwise.
423 ///
424 /// # Examples
425 ///
426 /// ```
427 /// use fastnum::{UD256, udec256};
428 ///
429 /// let nan = UD256::NAN;
430 /// let d = udec256!(7.0);
431 ///
432 /// assert!(nan.is_nan());
433 /// assert!(!d.is_nan());
434 /// ```
435 ///
436 /// [`NaN`]: crate#special-values
437 #[must_use]
438 #[inline]
439 pub const fn is_nan(self) -> bool {
440 self.0.is_nan()
441 }
442
443 #[doc = doc::with_ctx::with_ctx!(256 U)]
444 #[must_use = doc::must_use_op!()]
445 #[inline(always)]
446 pub const fn with_ctx(mut self, ctx: Context) -> Self {
447 self.0 = self.0.with_ctx(ctx);
448 self
449 }
450
451 #[doc = doc::with_rounding_mode::with_rounding_mode!(256 U)]
452 #[must_use = doc::must_use_op!()]
453 #[inline(always)]
454 pub const fn with_rounding_mode(mut self, rm: RoundingMode) -> Self {
455 self.0 = self.0.with_rounding_mode(rm);
456 self
457 }
458
459 /// The quantum of a finite number is given by: 1 × 10<sup>exp</sup>.
460 /// This is the value of a unit in the least significant position of the
461 /// coefficient of a finite number.
462 ///
463 /// # Examples
464 ///
465 /// ```
466 /// use fastnum::{*, decimal::*};
467 ///
468 /// let ctx = Context::default();
469 ///
470 /// assert_eq!(UD256::quantum(0, ctx), udec256!(1));
471 /// assert_eq!(UD256::quantum(-0, ctx), udec256!(1));
472 /// assert_eq!(UD256::quantum(-3, ctx), udec256!(0.001));
473 /// assert_eq!(UD256::quantum(3, ctx), udec256!(1000));
474 /// ```
475 #[must_use]
476 #[track_caller]
477 #[inline]
478 pub const fn quantum(exp: i32, ctx: Context) -> Self {
479 Self::new(Decimal::<N>::quantum(exp, ctx))
480 }
481
482 /// Reduces a decimal number to its shortest (coefficient)
483 /// form shifting all significant trailing zeros into the exponent.
484 ///
485 /// # Examples
486 ///
487 /// ```
488 /// use fastnum::{udec256, u256, decimal::Context};
489 ///
490 /// let a = udec256!(1234500);
491 /// assert_eq!(a.digits(), u256!(1234500));
492 /// assert_eq!(a.fractional_digits_count(), 0);
493 ///
494 /// let b = a.reduce();
495 /// assert_eq!(b.digits(), u256!(12345));
496 /// assert_eq!(b.fractional_digits_count(), -2);
497 /// ```
498 #[must_use = doc::must_use_op!()]
499 #[track_caller]
500 #[inline]
501 pub const fn reduce(self) -> Self {
502 Self::new(self.0.reduce())
503 }
504
505 /// Invert sign of the given unsigned decimal.
506 ///
507 /// # Examples
508 ///
509 /// ```
510 /// use fastnum::*;
511 ///
512 /// assert_eq!(udec256!(1.0).neg(), dec256!(-1.0));
513 /// ```
514 #[must_use]
515 #[inline]
516 pub const fn neg(self) -> Decimal<N> {
517 self.0.neg()
518 }
519
520 /// Tests for `self` and `other` values to be equal, and is used by `==`
521 /// operator.
522 #[must_use]
523 #[inline]
524 pub const fn eq(&self, other: &Self) -> bool {
525 self.0.eq(&other.0)
526 }
527
528 /// Tests for `self` and `other` values to be equal, and is used by `==`
529 /// operator.
530 #[must_use]
531 #[inline]
532 pub const fn ne(&self, other: &Self) -> bool {
533 self.0.ne(&other.0)
534 }
535
536 /// Compares and returns the maximum of two unsigned decimal values.
537 ///
538 /// Returns the second argument if the comparison determines them to be
539 /// equal.
540 ///
541 /// # Examples
542 ///
543 /// ```
544 /// use fastnum::{udec256};
545 ///
546 /// assert_eq!(udec256!(1).max(udec256!(2)), udec256!(2));
547 /// assert_eq!(udec256!(2).max(udec256!(2)), udec256!(2));
548 /// ```
549 #[must_use]
550 #[inline]
551 pub const fn max(self, other: Self) -> Self {
552 match self.cmp(&other) {
553 Ordering::Less | Ordering::Equal => other,
554 _ => self,
555 }
556 }
557
558 /// Compares and returns the minimum of two undecimal values.
559 ///
560 /// Returns the first argument if the comparison determines them to be
561 /// equal.
562 ///
563 /// # Examples
564 ///
565 /// ```
566 /// use fastnum::udec256;
567 ///
568 /// assert_eq!(udec256!(1).min(udec256!(2)), udec256!(1));
569 /// assert_eq!(udec256!(2).min(udec256!(2)), udec256!(2));
570 /// ```
571 #[must_use]
572 #[inline]
573 pub const fn min(self, other: Self) -> Self {
574 match self.cmp(&other) {
575 Ordering::Less | Ordering::Equal => self,
576 _ => other,
577 }
578 }
579
580 /// Restrict an unsigned decimal value to a certain interval.
581 ///
582 /// Returns `max` if `self` is greater than `max`, and `min` if `self` is
583 /// less than `min`. Otherwise, this returns `self`.
584 ///
585 /// # Panics
586 ///
587 /// Panics if `min > max`.
588 ///
589 /// # Examples
590 ///
591 /// ```
592 /// use fastnum::udec256;
593 ///
594 /// assert_eq!(udec256!(0).clamp(udec256!(3), udec256!(5)), udec256!(3));
595 /// assert_eq!(udec256!(3).clamp(udec256!(1), udec256!(5)), udec256!(3));
596 /// assert_eq!(udec256!(6).clamp(udec256!(1), udec256!(5)), udec256!(5));
597 /// ```
598 #[must_use]
599 #[inline]
600 pub const fn clamp(self, min: Self, max: Self) -> Self {
601 assert!(min.le(&max));
602 if let Ordering::Less = self.cmp(&min) {
603 min
604 } else if let Ordering::Greater = self.cmp(&max) {
605 max
606 } else {
607 self
608 }
609 }
610
611 /// Tests unsigned decimal `self` less than `other` and is used by the `<`
612 /// operator.
613 ///
614 /// # Examples
615 ///
616 /// ```
617 /// use fastnum::udec256;
618 ///
619 /// assert_eq!(udec256!(1.0).lt(&udec256!(1.0)), false);
620 /// assert_eq!(udec256!(1.0).lt(&udec256!(2.0)), true);
621 /// assert_eq!(udec256!(2.0).lt(&udec256!(1.0)), false);
622 /// ```
623 #[must_use]
624 #[inline]
625 pub const fn lt(&self, other: &Self) -> bool {
626 #[allow(clippy::match_like_matches_macro)]
627 match self.cmp(other) {
628 Ordering::Less => true,
629 _ => false,
630 }
631 }
632
633 /// Tests unsigned decimal `self` less than or equal to `other` and is used
634 /// by the `<=` operator.
635 ///
636 /// # Examples
637 ///
638 /// ```
639 /// use fastnum::udec256;
640 ///
641 /// assert_eq!(udec256!(1.0).le(&udec256!(1.0)), true);
642 /// assert_eq!(udec256!(1.0).le(&udec256!(2.0)), true);
643 /// assert_eq!(udec256!(2.0).le(&udec256!(1.0)), false);
644 /// ```
645 #[must_use]
646 #[inline]
647 pub const fn le(&self, other: &Self) -> bool {
648 #[allow(clippy::match_like_matches_macro)]
649 match self.cmp(other) {
650 Ordering::Less | Ordering::Equal => true,
651 _ => false,
652 }
653 }
654
655 /// Tests unsigned decimal `self` greater than `other` and is used by the
656 /// `>` operator.
657 ///
658 /// # Examples
659 ///
660 /// ```
661 /// use fastnum::udec256;
662 ///
663 /// assert_eq!(udec256!(1.0).gt(&udec256!(1.0)), false);
664 /// assert_eq!(udec256!(1.0).gt(&udec256!(2.0)), false);
665 /// assert_eq!(udec256!(2.0).gt(&udec256!(1.0)), true);
666 /// ```
667 #[must_use]
668 #[inline]
669 pub const fn gt(&self, other: &Self) -> bool {
670 #[allow(clippy::match_like_matches_macro)]
671 match self.cmp(other) {
672 Ordering::Greater => true,
673 _ => false,
674 }
675 }
676
677 /// Tests unsigned decimal `self` greater than or equal to `other` and is
678 /// used by the `>=` operator.
679 ///
680 /// # Examples
681 ///
682 /// ```
683 /// use fastnum::udec256;
684 ///
685 /// assert_eq!(udec256!(1.0).ge(&udec256!(1.0)), true);
686 /// assert_eq!(udec256!(1.0).ge(&udec256!(2.0)), false);
687 /// assert_eq!(udec256!(2.0).ge(&udec256!(1.0)), true);
688 /// ```
689 #[must_use]
690 #[inline]
691 pub const fn ge(&self, other: &Self) -> bool {
692 #[allow(clippy::match_like_matches_macro)]
693 match self.cmp(other) {
694 Ordering::Greater | Ordering::Equal => true,
695 _ => false,
696 }
697 }
698
699 /// This method returns an [`Ordering`] between `self` and `other`.
700 ///
701 /// By convention, `self.cmp(&other)` returns the ordering matching the
702 /// expression `self <operator> other` if true.
703 ///
704 /// # Examples
705 ///
706 /// ```
707 /// use fastnum::udec256;
708 /// use std::cmp::Ordering;
709 ///
710 /// assert_eq!(udec256!(5).cmp(&udec256!(10)), Ordering::Less);
711 /// assert_eq!(udec256!(10).cmp(&udec256!(5)), Ordering::Greater);
712 /// assert_eq!(udec256!(5).cmp(&udec256!(5)), Ordering::Equal);
713 /// ```
714 #[must_use]
715 #[inline]
716 pub const fn cmp(&self, other: &Self) -> Ordering {
717 self.0.cmp(&other.0)
718 }
719
720 /// Calculates `self` + `rhs`.
721 ///
722 /// Is internally used by the `+` operator.
723 ///
724 /// # Panics:
725 #[doc = doc::decimal_operation_panics!("addition operation")]
726 /// # Examples
727 ///
728 /// Basic usage:
729 ///
730 /// ```
731 /// use fastnum::*;
732 ///
733 /// let a = UD256::ONE;
734 /// let b = UD256::TWO;
735 ///
736 /// let c = a + b;
737 /// assert_eq!(c, udec256!(3));
738 /// ```
739 ///
740 /// Panics if overflowed:
741 ///
742 /// ```should_panic
743 /// use fastnum::*;
744 ///
745 /// let a = UD256::MAX;
746 /// let b = UD256::MAX;
747 ///
748 /// let c = a + b;
749 /// ```
750 /// See more about [add and subtract](crate#addition-and-subtraction).
751 #[must_use = doc::must_use_op!()]
752 #[track_caller]
753 #[inline]
754 pub const fn add(self, rhs: Self) -> Self {
755 Self::new(self.0.add(rhs.0))
756 }
757
758 /// Calculates `self` – `rhs`.
759 ///
760 /// Is internally used by the `-` operator.
761 ///
762 /// # Panics:
763 #[doc = doc::decimal_operation_panics!("subtract operation")]
764 /// # Examples
765 ///
766 /// Basic usage:
767 ///
768 /// ```
769 /// use fastnum::*;
770 ///
771 /// let a = UD256::FIVE;
772 /// let b = UD256::TWO;
773 ///
774 /// let c = a - b;
775 /// assert_eq!(c, udec256!(3));
776 /// ```
777 ///
778 /// Panics if overflowed:
779 ///
780 /// ```should_panic
781 /// use fastnum::*;
782 ///
783 /// let a = UD256::ZERO;
784 /// let b = UD256::ONE;
785 ///
786 /// let c = a - b;
787 /// ```
788 /// See more about [add and subtract](crate#addition-and-subtraction).
789 #[must_use = doc::must_use_op!()]
790 #[track_caller]
791 #[inline]
792 pub const fn sub(self, rhs: Self) -> Self {
793 let res = self.0.sub(rhs.0);
794 Self::from_signed(res)
795 }
796
797 /// Calculates `self` × `rhs`.
798 ///
799 /// Is internally used by the `*` operator.
800 ///
801 /// # Panics:
802 #[doc = doc::decimal_operation_panics!("multiplication operation")]
803 /// # Examples
804 ///
805 /// Basic usage:
806 ///
807 /// ```
808 /// use fastnum::*;
809 ///
810 /// let a = UD256::FIVE;
811 /// let b = UD256::TWO;
812 ///
813 /// let c = a * b;
814 /// assert_eq!(c, udec256!(10));
815 /// ```
816 ///
817 /// Panics if overflowed:
818 ///
819 /// ```should_panic
820 /// use fastnum::*;
821 ///
822 /// let a = UD256::MAX;
823 /// let b = UD256::MAX;
824 ///
825 /// let c = a * b;
826 /// ```
827 ///
828 /// See more about [multiplication](crate#multiplication).
829 #[must_use = doc::must_use_op!()]
830 #[track_caller]
831 #[inline(always)]
832 pub const fn mul(self, rhs: Self) -> Self {
833 Self::new(self.0.mul(rhs.0))
834 }
835
836 /// Calculates `self` ÷ `rhs`.
837 ///
838 /// Is internally used by the `/` operator.
839 ///
840 /// # Panics:
841 #[doc = doc::decimal_operation_panics!("divide operation")]
842 /// # Examples
843 ///
844 /// Basic usage:
845 ///
846 /// ```
847 /// use fastnum::*;
848 ///
849 /// let a = UD256::FIVE;
850 /// let b = UD256::TWO;
851 ///
852 /// let c = a / b;
853 /// assert_eq!(c, udec256!(2.5));
854 /// ```
855 ///
856 /// Panics if divided by zero:
857 ///
858 /// ```should_panic
859 /// use fastnum::*;
860 ///
861 /// let a = UD256::ONE;
862 /// let b = UD256::ZERO;
863 ///
864 /// let c = a / b;
865 /// ```
866 ///
867 /// See more about [division](crate#division).
868 #[must_use = doc::must_use_op!()]
869 #[track_caller]
870 #[inline(always)]
871 pub const fn div(self, rhs: Self) -> Self {
872 Self::new(self.0.div(rhs.0))
873 }
874
875 /// Calculates `self` % `rhs`.
876 ///
877 /// Is internally used by the `%` operator.
878 ///
879 /// # Panics:
880 #[doc = doc::decimal_operation_panics!("reminder operation")]
881 /// # Examples
882 ///
883 /// Basic usage:
884 ///
885 /// ```
886 /// use fastnum::*;
887 ///
888 /// let a = UD256::FIVE;
889 /// let b = UD256::TWO;
890 ///
891 /// let c = a % b;
892 /// assert_eq!(c, udec256!(1));
893 /// ```
894 #[must_use = doc::must_use_op!()]
895 #[track_caller]
896 #[inline]
897 pub const fn rem(self, rhs: Self) -> Self {
898 Self::new(self.0.rem(rhs.0))
899 }
900
901 /// Takes the reciprocal (inverse) of a number, `1/x`.
902 ///
903 /// # Panics:
904 #[doc = doc::decimal_operation_panics!("reciprocal operation")]
905 #[doc = doc::decimal_inexact!("reciprocal")]
906 /// # Examples
907 ///
908 /// ```
909 /// use fastnum::*;
910 ///
911 /// assert_eq!(udec256!(2).recip(), udec256!(0.5));
912 /// ```
913 #[must_use = doc::must_use_op!()]
914 #[track_caller]
915 #[inline]
916 pub const fn recip(self) -> Self {
917 Self::new(self.0.recip())
918 }
919
920 /// Raise an unsigned decimal number to decimal power.
921 ///
922 /// Using this function is generally slower than using `powi` for integer
923 /// exponents or `sqrt` method for `1/2` exponent.
924 ///
925 /// # Panics:
926 #[doc = doc::decimal_operation_panics!("power operation")]
927 /// # Examples
928 ///
929 /// Basic usage:
930 ///
931 /// ```
932 /// use fastnum::*;
933 ///
934 /// assert_eq!(udec256!(4).pow(dec256!(0.5)), udec256!(2));
935 /// assert_eq!(udec256!(8).pow(dec256!(1) / dec256!(3)), udec256!(2));
936 /// ```
937 ///
938 /// See more about the [power](crate#power) operation.
939 #[must_use = doc::must_use_op!()]
940 #[track_caller]
941 #[inline]
942 pub const fn pow(self, n: Decimal<N>) -> Self {
943 Self::new(self.0.pow(n))
944 }
945
946 /// Raise an unsigned decimal number to an integer power.
947 ///
948 /// Using this function is generally faster than using `pow`
949 ///
950 /// # Panics:
951 #[doc = doc::decimal_operation_panics!("power operation")]
952 /// # Examples
953 ///
954 /// Basic usage:
955 ///
956 /// ```
957 /// use fastnum::*;
958 ///
959 /// assert_eq!(udec256!(2).powi(3), udec256!(8));
960 /// assert_eq!(udec256!(9).powi(2), udec256!(81));
961 /// assert_eq!(udec256!(1).powi(-2), udec256!(1));
962 /// assert_eq!(udec256!(10).powi(20), udec256!(1e20));
963 /// assert_eq!(udec256!(4).powi(-2), udec256!(0.0625));
964 /// ```
965 ///
966 /// See more about the [power](crate#power) operation.
967 #[must_use = doc::must_use_op!()]
968 #[track_caller]
969 #[inline]
970 pub const fn powi(self, n: i32) -> Self {
971 Self::new(self.0.powi(n))
972 }
973
974 /// Take the square root of the unsigned decimal number.
975 ///
976 /// Square-root can also be calculated by using the `power` operation (with
977 /// a second operand of `0.5`). The result in that case will not be exact
978 /// and may not be correctly rounded.
979 ///
980 /// # Panics:
981 #[doc = doc::decimal_operation_panics!("sqrt operation")]
982 /// # Examples
983 ///
984 /// Basic usage:
985 ///
986 /// ```
987 /// use fastnum::*;
988 ///
989 /// assert_eq!(udec128!(4).sqrt(), udec128!(2));
990 /// assert_eq!(udec128!(1).sqrt(), udec128!(1));
991 /// assert_eq!(udec128!(16).sqrt(), udec128!(4));
992 /// ```
993 ///
994 /// See more about the [square-root](crate#square-root) operation.
995 #[must_use = doc::must_use_op!()]
996 #[track_caller]
997 #[inline]
998 pub const fn sqrt(self) -> Self {
999 Self::new(self.0.sqrt())
1000 }
1001
1002 /// Returns _e<sup>self</sup>_, (the exponential function).
1003 ///
1004 /// # Panics:
1005 #[doc = doc::decimal_operation_panics!("exponent operation")]
1006 /// # Examples
1007 ///
1008 /// Basic usage:
1009 ///
1010 /// ```
1011 /// use fastnum::*;
1012 ///
1013 /// assert_eq!(udec128!(1).exp(), UD128::E);
1014 /// ```
1015 ///
1016 /// See more about the [exponential function](crate#exponential-function).
1017 #[must_use = doc::must_use_op!()]
1018 #[track_caller]
1019 #[inline]
1020 pub const fn exp(self) -> Self {
1021 Self::new(self.0.exp())
1022 }
1023
1024 #[doc = doc::log::ln!(256 U)]
1025 #[must_use = doc::must_use_op!()]
1026 #[inline(always)]
1027 pub const fn ln(self) -> Decimal<N> {
1028 self.0.ln()
1029 }
1030
1031 #[doc = doc::log::ln_1p!(256 U)]
1032 #[must_use = doc::must_use_op!()]
1033 #[inline(always)]
1034 pub const fn ln_1p(self) -> Decimal<N> {
1035 self.0.ln_1p()
1036 }
1037
1038 #[doc = doc::log::log!(256 U)]
1039 #[must_use = doc::must_use_op!()]
1040 #[inline(always)]
1041 pub const fn log(self, base: Self) -> Decimal<N> {
1042 self.0.log(base.0)
1043 }
1044
1045 #[doc = doc::log::log2!(256 U)]
1046 #[must_use = doc::must_use_op!()]
1047 #[inline(always)]
1048 pub const fn log2(self) -> Decimal<N> {
1049 self.0.log2()
1050 }
1051
1052 #[doc = doc::log::log10!(256 U)]
1053 #[must_use = doc::must_use_op!()]
1054 #[inline(always)]
1055 pub const fn log10(self) -> Decimal<N> {
1056 self.0.log10()
1057 }
1058
1059 /// Fused multiply-add. Computes `(self * a) + b` with only one rounding
1060 /// error, yielding a more accurate result than an unfused multiply-add.
1061 ///
1062 /// # Panics:
1063 #[doc = doc::decimal_operation_panics!("multiply-add operation")]
1064 /// # Examples
1065 ///
1066 /// Basic usage:
1067 ///
1068 /// ```
1069 /// use fastnum::*;
1070 ///
1071 /// assert_eq!(udec128!(10.0).mul_add(udec128!(4.0), udec128!(60)), udec128!(100));
1072 /// ```
1073 ///
1074 /// See more about the [fused multiply-add function](crate#multiply-add).
1075 #[must_use = doc::must_use_op!()]
1076 #[track_caller]
1077 #[inline]
1078 pub const fn mul_add(self, a: Self, b: Self) -> Self {
1079 Self::new(self.0.mul_add(a.0, b.0))
1080 }
1081
1082 /// Returns the given decimal number rounded to `digits` precision after the
1083 /// decimal point, using [RoundingMode] from it [Context].
1084 ///
1085 /// # Panics:
1086 #[doc = doc::decimal_operation_panics!("round operation (up-scale or down-scale)")]
1087 /// # Examples
1088 ///
1089 /// ```
1090 /// use fastnum::{*, decimal::{*, RoundingMode::*}};
1091 ///
1092 /// let n = udec256!(129.41675);
1093 ///
1094 /// // Default rounding mode is `HalfUp`
1095 /// assert_eq!(n.round(2), udec256!(129.42));
1096 ///
1097 /// assert_eq!(n.with_rounding_mode(Up).round(2), udec256!(129.42));
1098 /// assert_eq!(n.with_rounding_mode(Down).round(-1), udec256!(120));
1099 /// assert_eq!(n.with_rounding_mode(HalfEven).round(4), udec256!(129.4168));
1100 /// ```
1101 /// See also:
1102 /// - More about [`round`](crate#rounding) decimals.
1103 /// - [RoundingMode].
1104 #[must_use = doc::must_use_op!()]
1105 #[track_caller]
1106 #[inline]
1107 pub const fn round(self, digits: i16) -> Self {
1108 Self::new(self.0.round(digits))
1109 }
1110
1111 /// Returns the largest integer less than or equal to a number.
1112 ///
1113 /// # Examples
1114 ///
1115 /// ```
1116 /// use fastnum::*;
1117 ///
1118 /// assert_eq!(udec256!(3.99).floor(), udec256!(3));
1119 /// assert_eq!(udec256!(3.0).floor(), udec256!(3.0));
1120 /// assert_eq!(udec256!(3.01).floor(), udec256!(3));
1121 /// assert_eq!(udec256!(3.5).floor(), udec256!(3));
1122 /// assert_eq!(udec256!(4.0).floor(), udec256!(4));
1123 /// ```
1124 #[must_use = doc::must_use_op!()]
1125 #[track_caller]
1126 #[inline]
1127 pub const fn floor(self) -> Self {
1128 Self::new(self.0.floor())
1129 }
1130
1131 /// Finds the nearest integer greater than or equal to `x`.
1132 ///
1133 /// # Examples
1134 ///
1135 /// ```
1136 /// use fastnum::*;
1137 ///
1138 /// assert_eq!(udec256!(3.01).ceil(), udec256!(4));
1139 /// assert_eq!(udec256!(3.99).ceil(), udec256!(4));
1140 /// assert_eq!(udec256!(4.0).ceil(), udec256!(4));
1141 /// assert_eq!(udec256!(1.0001).ceil(), udec256!(2));
1142 /// assert_eq!(udec256!(1.00001).ceil(), udec256!(2));
1143 /// assert_eq!(udec256!(1.000001).ceil(), udec256!(2));
1144 /// assert_eq!(udec256!(1.00000000000001).ceil(), udec256!(2));
1145 /// ```
1146 #[must_use = doc::must_use_op!()]
1147 #[track_caller]
1148 #[inline]
1149 pub const fn ceil(self) -> Self {
1150 Self::new(self.0.ceil())
1151 }
1152
1153 /// Returns the given decimal number _re-scaled_ to `digits` precision after
1154 /// the decimal point.
1155 ///
1156 /// # Panics:
1157 #[doc = doc::decimal_operation_panics!("rescale operation")]
1158 /// # Examples
1159 ///
1160 /// ```
1161 /// use fastnum::{*, decimal::*};
1162 ///
1163 /// assert_eq!(udec256!(2.17).rescale(3), udec256!(2.170));
1164 /// assert_eq!(udec256!(2.17).rescale(2), udec256!(2.17));
1165 /// assert_eq!(udec256!(2.17).rescale(1), udec256!(2.2));
1166 /// assert_eq!(udec256!(2.17).rescale(0), udec256!(2));
1167 /// assert_eq!(udec256!(2.17).rescale(-1), udec256!(0));
1168 ///
1169 /// let ctx = Context::default().without_traps();
1170 ///
1171 /// assert!(UD256::INFINITY.with_ctx(ctx).rescale(2).is_nan());
1172 /// assert!(UD256::NAN.with_ctx(ctx).rescale(1).is_nan());
1173 /// ```
1174 ///
1175 /// See also:
1176 /// - More about [`rescale`](crate#rescale) decimals.
1177 /// - [Self::quantize].
1178 #[must_use = doc::must_use_op!()]
1179 #[track_caller]
1180 #[inline]
1181 pub const fn rescale(mut self, new_scale: i16) -> Self {
1182 self.0 = self.0.rescale(new_scale);
1183 self
1184 }
1185
1186 /// Returns a value equal to `self` (rounded), having the exponent of
1187 /// `other`.
1188 ///
1189 /// # Panics:
1190 #[doc = doc::decimal_operation_panics!("quantize operation")]
1191 /// # Examples
1192 ///
1193 /// ```
1194 /// use fastnum::{*, decimal::*};
1195 ///
1196 /// let ctx = Context::default().without_traps();
1197 ///
1198 /// assert_eq!(udec256!(2.17).quantize(udec256!(0.001)), udec256!(2.170));
1199 /// assert_eq!(udec256!(2.17).quantize(udec256!(0.01)), udec256!(2.17));
1200 /// assert_eq!(udec256!(2.17).quantize(udec256!(0.1)), udec256!(2.2));
1201 /// assert_eq!(udec256!(2.17).quantize(udec256!(1e+0)), udec256!(2));
1202 /// assert_eq!(udec256!(2.17).quantize(udec256!(1e+1)), udec256!(0));
1203 ///
1204 /// assert_eq!(UD256::INFINITY.quantize(UD256::INFINITY), UD256::INFINITY);
1205 ///
1206 /// assert!(udec256!(2).with_ctx(ctx).quantize(UD256::INFINITY).is_nan());
1207 ///
1208 /// assert_eq!(udec256!(0.1).quantize(udec256!(1)), udec256!(0));
1209 /// assert_eq!(udec256!(0).quantize(udec256!(1e+5)), udec256!(0E+5));
1210 ///
1211 /// assert!(udec128!(0.34028).with_ctx(ctx).quantize(udec128!(1e-32765)).is_nan());
1212 ///
1213 /// assert_eq!(udec256!(217).quantize(udec256!(1e-1)), udec256!(217.0));
1214 /// assert_eq!(udec256!(217).quantize(udec256!(1e+0)), udec256!(217));
1215 /// assert_eq!(udec256!(217).quantize(udec256!(1e+1)), udec256!(2.2E+2));
1216 /// assert_eq!(udec256!(217).quantize(udec256!(1e+2)), udec256!(2E+2));
1217 /// ```
1218 ///
1219 /// See also:
1220 /// - More about [`quantize`](crate#quantize) decimals.
1221 /// - [Self::rescale].
1222 #[must_use = doc::must_use_op!()]
1223 #[track_caller]
1224 #[inline]
1225 pub const fn quantize(mut self, other: Self) -> Self {
1226 self.0 = self.0.quantize(other.0);
1227 self
1228 }
1229
1230 #[doc = doc::trunc::trunc!(256 U)]
1231 #[must_use = doc::must_use_op!()]
1232 #[inline(always)]
1233 pub const fn trunc(self) -> Self {
1234 Self::new(self.0.trunc())
1235 }
1236
1237 #[doc = doc::trunc::trunc_with_scale!(256 U)]
1238 #[must_use = doc::must_use_op!()]
1239 #[inline(always)]
1240 pub const fn trunc_with_scale(self, scale: i16) -> Self {
1241 Self::new(self.0.trunc_with_scale(scale))
1242 }
1243
1244 /// Returns:
1245 /// - `true` if no [Exceptional condition] [Signals] flag has been trapped
1246 /// by [Context] trap-enabler, and
1247 /// - `false` otherwise.
1248 ///
1249 /// [Exceptional condition]: crate#signaling-flags-and-trap-enablers
1250 #[inline(always)]
1251 pub const fn is_ok(&self) -> bool {
1252 self.0.is_ok()
1253 }
1254
1255 /// Returns:
1256 /// - `Some(Self)` if no [Exceptional condition] [Signals] flag has been
1257 /// trapped by [Context] trap-enabler, and
1258 /// - `None` otherwise.
1259 ///
1260 /// [Exceptional condition]: crate#signaling-flags-and-trap-enablers
1261 #[must_use]
1262 #[inline]
1263 pub const fn ok(self) -> Option<Self> {
1264 if self.is_ok() {
1265 None
1266 } else {
1267 Some(self)
1268 }
1269 }
1270
1271 /// Create a string of this unsigned decimal in scientific notation.
1272 ///
1273 /// # Examples
1274 ///
1275 /// ```
1276 /// use fastnum::udec256;
1277 ///
1278 /// let n = udec256!(12345678);
1279 /// assert_eq!(&n.to_scientific_notation(), "1.2345678e7");
1280 /// ```
1281 #[inline]
1282 pub fn to_scientific_notation(&self) -> String {
1283 self.0.to_scientific_notation()
1284 }
1285
1286 /// Create a string of this unsigned decimal in engineering notation.
1287 ///
1288 /// Engineering notation is scientific notation with the exponent
1289 /// coerced to a multiple of three.
1290 ///
1291 /// # Examples
1292 ///
1293 /// ```
1294 /// use fastnum::udec256;
1295 ///
1296 /// let n = udec256!(12345678);
1297 /// assert_eq!(&n.to_engineering_notation(), "12.345678e6");
1298 /// ```
1299 #[inline]
1300 pub fn to_engineering_notation(&self) -> String {
1301 self.0.to_engineering_notation()
1302 }
1303
1304 /// Converts the given unsigned decimal to a signed decimal number.
1305 ///
1306 /// # Examples
1307 ///
1308 /// ```
1309 /// use fastnum::*;
1310 ///
1311 /// let d = udec256!(1.2345);
1312 ///
1313 /// assert_eq!(d.to_signed(), dec256!(1.2345));
1314 /// ```
1315 #[must_use = doc::must_use_op!()]
1316 #[inline]
1317 pub const fn to_signed(self) -> Decimal<N> {
1318 self.0
1319 }
1320
1321 /// Try converts from [Decimal] to [UnsignedDecimal].
1322 ///
1323 /// # Examples
1324 ///
1325 /// ```
1326 /// use fastnum::*;
1327 ///
1328 /// assert_eq!(UD256::try_from_signed(dec256!(1.2345)), Ok(udec256!(1.2345)));
1329 /// assert!(UD256::try_from_signed(dec256!(-1.2345)).is_err());
1330 /// ```
1331 #[inline]
1332 pub const fn try_from_signed(d: Decimal<N>) -> Result<Self, DecimalError> {
1333 if d.is_negative() {
1334 return Err(DecimalError::Invalid);
1335 }
1336 Ok(Self::new(d))
1337 }
1338
1339 /// _Deprecated_, use [`resize`](Self::resize) instead.
1340 #[deprecated(since = "0.5.0")]
1341 #[must_use = doc::must_use_op!()]
1342 #[inline(always)]
1343 pub const fn transmute<const M: usize>(self) -> UnsignedDecimal<M> {
1344 self.resize()
1345 }
1346
1347 #[doc = doc::resize::resize!(64 U)]
1348 #[must_use = doc::must_use_op!()]
1349 #[inline(always)]
1350 pub const fn resize<const M: usize>(self) -> UnsignedDecimal<M> {
1351 UnsignedDecimal::new(self.0.resize())
1352 }
1353}
1354
1355#[doc(hidden)]
1356impl<const N: usize> UnsignedDecimal<N> {
1357 const TYPE_NAME: &'static str = decimal::utils::fmt::type_name!("UD");
1358
1359 #[inline(always)]
1360 pub(crate) const fn new(dec: Decimal<N>) -> Self {
1361 debug_assert!(!dec.is_negative());
1362 Self(dec)
1363 }
1364
1365 #[inline]
1366 pub(crate) const fn from_signed(d: Decimal<N>) -> Self {
1367 match Self::try_from_signed(d) {
1368 Ok(ud) => ud,
1369 Err(_) => Self::new(Decimal::SIGNALING_NAN.check()),
1370 }
1371 }
1372
1373 #[inline]
1374 pub(crate) const fn type_name() -> &'static str {
1375 Self::TYPE_NAME
1376 }
1377
1378 #[inline(always)]
1379 pub(crate) const fn signals(&self) -> Signals {
1380 self.0.signals()
1381 }
1382
1383 #[inline]
1384 #[allow(dead_code)]
1385 pub(crate) const fn ok_or_err(self) -> Result<Self, DecimalError> {
1386 match self.0.ok_or_err() {
1387 Ok(ok) => Ok(Self::new(ok)),
1388 Err(e) => Err(e),
1389 }
1390 }
1391}