Skip to main content

fastnum/decimal/
udec.rs

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