Skip to main content

ng_oxigraph/oxsdatatypes/
decimal.rs

1use crate::oxsdatatypes::{Boolean, Double, Float, Integer, TooLargeForIntegerError};
2use serde::{Deserialize, Serialize};
3use std::fmt;
4use std::fmt::Write;
5use std::str::FromStr;
6
7const DECIMAL_PART_DIGITS: u32 = 18;
8const DECIMAL_PART_POW: i128 = 1_000_000_000_000_000_000;
9const DECIMAL_PART_POW_MINUS_ONE: i128 = 100_000_000_000_000_000;
10
11/// [XML Schema `decimal` datatype](https://www.w3.org/TR/xmlschema11-2/#decimal)
12///
13/// It stores the decimal in a fix point encoding allowing nearly 18 digits before and 18 digits after ".".
14///
15/// It stores the value in a [`i128`] integer after multiplying it by 10¹⁸.
16#[derive(
17    Eq, PartialEq, Ord, PartialOrd, Debug, Clone, Copy, Hash, Default, Serialize, Deserialize,
18)]
19pub struct Decimal {
20    value: i128, // value * 10^18
21}
22
23impl Decimal {
24    pub const MAX: Self = Self { value: i128::MAX };
25    pub const MIN: Self = Self { value: i128::MIN };
26    #[cfg(test)]
27    pub const STEP: Self = Self { value: 1 };
28
29    /// Constructs the decimal i / 10^n
30    #[inline]
31    pub const fn new(i: i128, n: u32) -> Result<Self, TooLargeForDecimalError> {
32        let Some(shift) = DECIMAL_PART_DIGITS.checked_sub(n) else {
33            return Err(TooLargeForDecimalError);
34        };
35        let Some(value) = i.checked_mul(10_i128.pow(shift)) else {
36            return Err(TooLargeForDecimalError);
37        };
38        Ok(Self { value })
39    }
40
41    pub(crate) const fn new_from_i128_unchecked(value: i128) -> Self {
42        Self {
43            value: value * DECIMAL_PART_POW,
44        }
45    }
46
47    #[inline]
48    #[must_use]
49    pub fn from_be_bytes(bytes: [u8; 16]) -> Self {
50        Self {
51            value: i128::from_be_bytes(bytes),
52        }
53    }
54
55    #[inline]
56    #[must_use]
57    pub fn to_be_bytes(self) -> [u8; 16] {
58        self.value.to_be_bytes()
59    }
60
61    /// [op:numeric-add](https://www.w3.org/TR/xpath-functions-31/#func-numeric-add)
62    ///
63    /// Returns `None` in case of overflow ([FOAR0002](https://www.w3.org/TR/xpath-functions-31/#ERRFOAR0002)).
64    #[inline]
65    #[must_use]
66    pub fn checked_add(self, rhs: impl Into<Self>) -> Option<Self> {
67        Some(Self {
68            value: self.value.checked_add(rhs.into().value)?,
69        })
70    }
71
72    /// [op:numeric-subtract](https://www.w3.org/TR/xpath-functions-31/#func-numeric-subtract)
73    ///
74    /// Returns `None` in case of overflow ([FOAR0002](https://www.w3.org/TR/xpath-functions-31/#ERRFOAR0002)).
75    #[inline]
76    #[must_use]
77    pub fn checked_sub(self, rhs: impl Into<Self>) -> Option<Self> {
78        Some(Self {
79            value: self.value.checked_sub(rhs.into().value)?,
80        })
81    }
82
83    /// [op:numeric-multiply](https://www.w3.org/TR/xpath-functions-31/#func-numeric-multiply)
84    ///
85    /// Returns `None` in case of overflow ([FOAR0002](https://www.w3.org/TR/xpath-functions-31/#ERRFOAR0002)).
86    #[inline]
87    #[must_use]
88    pub fn checked_mul(self, rhs: impl Into<Self>) -> Option<Self> {
89        // Idea: we shift right as much as possible to keep as much precision as possible
90        // Do the multiplication and do the required left shift
91        let mut left = self.value;
92        let mut shift_left = 0_u32;
93        if left != 0 {
94            while left % 10 == 0 {
95                left /= 10;
96                shift_left += 1;
97            }
98        }
99
100        let mut right = rhs.into().value;
101        let mut shift_right = 0_u32;
102        if right != 0 {
103            while right % 10 == 0 {
104                right /= 10;
105                shift_right += 1;
106            }
107        }
108
109        // We do multiplication + shift
110        let shift = (shift_left + shift_right).checked_sub(DECIMAL_PART_DIGITS)?;
111        Some(Self {
112            value: left
113                .checked_mul(right)?
114                .checked_mul(10_i128.checked_pow(shift)?)?,
115        })
116    }
117
118    /// [op:numeric-divide](https://www.w3.org/TR/xpath-functions-31/#func-numeric-divide)
119    ///
120    /// Returns `None` in case of division by 0 ([FOAR0001](https://www.w3.org/TR/xpath-functions-31/#ERRFOAR0001)) or overflow ([FOAR0002](https://www.w3.org/TR/xpath-functions-31/#ERRFOAR0002)).
121    #[inline]
122    #[must_use]
123    pub fn checked_div(self, rhs: impl Into<Self>) -> Option<Self> {
124        // Idea: we shift the dividend left as much as possible to keep as much precision as possible
125        // And we shift right the divisor as much as possible
126        // Do the multiplication and do the required shift
127        let mut left = self.value;
128        let mut shift_left = 0_u32;
129        if left != 0 {
130            while let Some(r) = left.checked_mul(10) {
131                left = r;
132                shift_left += 1;
133            }
134        }
135        let mut right = rhs.into().value;
136        let mut shift_right = 0_u32;
137        if right != 0 {
138            while right % 10 == 0 {
139                right /= 10;
140                shift_right += 1;
141            }
142        }
143
144        // We do division + shift
145        let shift = (shift_left + shift_right).checked_sub(DECIMAL_PART_DIGITS)?;
146        Some(Self {
147            value: left
148                .checked_div(right)?
149                .checked_div(10_i128.checked_pow(shift)?)?,
150        })
151    }
152
153    /// [op:numeric-mod](https://www.w3.org/TR/xpath-functions-31/#func-numeric-mod)
154    ///
155    /// Returns `None` in case of division by 0 ([FOAR0001](https://www.w3.org/TR/xpath-functions-31/#ERRFOAR0001)) or overflow ([FOAR0002](https://www.w3.org/TR/xpath-functions-31/#ERRFOAR0002)).
156    #[inline]
157    #[must_use]
158    pub fn checked_rem(self, rhs: impl Into<Self>) -> Option<Self> {
159        Some(Self {
160            value: self.value.checked_rem(rhs.into().value)?,
161        })
162    }
163
164    /// Euclidean remainder
165    ///
166    /// Returns `None` in case of division by 0 ([FOAR0001](https://www.w3.org/TR/xpath-functions-31/#ERRFOAR0001)) or overflow ([FOAR0002](https://www.w3.org/TR/xpath-functions-31/#ERRFOAR0002)).
167    #[inline]
168    #[must_use]
169    pub fn checked_rem_euclid(self, rhs: impl Into<Self>) -> Option<Self> {
170        Some(Self {
171            value: self.value.checked_rem_euclid(rhs.into().value)?,
172        })
173    }
174
175    /// [op:numeric-unary-minus](https://www.w3.org/TR/xpath-functions-31/#func-numeric-unary-minus)
176    ///
177    /// Returns `None` in case of overflow ([FOAR0002](https://www.w3.org/TR/xpath-functions-31/#ERRFOAR0002)).
178    #[inline]
179    #[must_use]
180    pub fn checked_neg(self) -> Option<Self> {
181        Some(Self {
182            value: self.value.checked_neg()?,
183        })
184    }
185
186    /// [fn:abs](https://www.w3.org/TR/xpath-functions-31/#func-abs)
187    ///
188    /// Returns `None` in case of overflow ([FOAR0002](https://www.w3.org/TR/xpath-functions-31/#ERRFOAR0002)).
189    #[inline]
190    #[must_use]
191    pub fn checked_abs(self) -> Option<Self> {
192        Some(Self {
193            value: self.value.checked_abs()?,
194        })
195    }
196
197    /// [fn:round](https://www.w3.org/TR/xpath-functions-31/#func-round)
198    ///
199    /// Returns `None` in case of overflow ([FOAR0002](https://www.w3.org/TR/xpath-functions-31/#ERRFOAR0002)).
200    #[inline]
201    #[must_use]
202    pub fn checked_round(self) -> Option<Self> {
203        let value = self.value / DECIMAL_PART_POW_MINUS_ONE;
204        Some(Self {
205            value: if value >= 0 {
206                value / 10 + i128::from(value % 10 >= 5)
207            } else {
208                value / 10 - i128::from(-value % 10 > 5)
209            }
210            .checked_mul(DECIMAL_PART_POW)?,
211        })
212    }
213
214    /// [fn:ceiling](https://www.w3.org/TR/xpath-functions-31/#func-ceiling)
215    ///
216    /// Returns `None` in case of overflow ([FOAR0002](https://www.w3.org/TR/xpath-functions-31/#ERRFOAR0002)).
217    #[inline]
218    #[must_use]
219    pub fn checked_ceil(self) -> Option<Self> {
220        Some(Self {
221            value: if self.value > 0 && self.value % DECIMAL_PART_POW != 0 {
222                self.value / DECIMAL_PART_POW + 1
223            } else {
224                self.value / DECIMAL_PART_POW
225            }
226            .checked_mul(DECIMAL_PART_POW)?,
227        })
228    }
229
230    /// [fn:floor](https://www.w3.org/TR/xpath-functions-31/#func-floor)
231    ///
232    /// Returns `None` in case of overflow ([FOAR0002](https://www.w3.org/TR/xpath-functions-31/#ERRFOAR0002)).
233    #[inline]
234    #[must_use]
235    pub fn checked_floor(self) -> Option<Self> {
236        Some(Self {
237            value: if self.value >= 0 || self.value % DECIMAL_PART_POW == 0 {
238                self.value / DECIMAL_PART_POW
239            } else {
240                self.value / DECIMAL_PART_POW - 1
241            }
242            .checked_mul(DECIMAL_PART_POW)?,
243        })
244    }
245
246    #[inline]
247    #[must_use]
248    pub const fn is_negative(self) -> bool {
249        self.value < 0
250    }
251
252    #[inline]
253    #[must_use]
254    pub const fn is_positive(self) -> bool {
255        self.value > 0
256    }
257
258    /// Checks if the two values are [identical](https://www.w3.org/TR/xmlschema11-2/#identity).
259    #[inline]
260    #[must_use]
261    pub fn is_identical_with(self, other: Self) -> bool {
262        self == other
263    }
264
265    #[inline]
266    #[must_use]
267    pub(super) const fn as_i128(self) -> i128 {
268        self.value / DECIMAL_PART_POW
269    }
270}
271
272impl From<bool> for Decimal {
273    #[inline]
274    fn from(value: bool) -> Self {
275        Self {
276            value: i128::from(value) * DECIMAL_PART_POW,
277        }
278    }
279}
280
281impl From<i8> for Decimal {
282    #[inline]
283    fn from(value: i8) -> Self {
284        Self {
285            value: i128::from(value) * DECIMAL_PART_POW,
286        }
287    }
288}
289
290impl From<i16> for Decimal {
291    #[inline]
292    fn from(value: i16) -> Self {
293        Self {
294            value: i128::from(value) * DECIMAL_PART_POW,
295        }
296    }
297}
298
299impl From<i32> for Decimal {
300    #[inline]
301    fn from(value: i32) -> Self {
302        Self {
303            value: i128::from(value) * DECIMAL_PART_POW,
304        }
305    }
306}
307
308impl From<i64> for Decimal {
309    #[inline]
310    fn from(value: i64) -> Self {
311        Self {
312            value: i128::from(value) * DECIMAL_PART_POW,
313        }
314    }
315}
316
317impl From<u8> for Decimal {
318    #[inline]
319    fn from(value: u8) -> Self {
320        Self {
321            value: i128::from(value) * DECIMAL_PART_POW,
322        }
323    }
324}
325
326impl From<u16> for Decimal {
327    #[inline]
328    fn from(value: u16) -> Self {
329        Self {
330            value: i128::from(value) * DECIMAL_PART_POW,
331        }
332    }
333}
334
335impl From<u32> for Decimal {
336    #[inline]
337    fn from(value: u32) -> Self {
338        Self {
339            value: i128::from(value) * DECIMAL_PART_POW,
340        }
341    }
342}
343
344impl From<u64> for Decimal {
345    #[inline]
346    fn from(value: u64) -> Self {
347        Self {
348            value: i128::from(value) * DECIMAL_PART_POW,
349        }
350    }
351}
352
353impl From<Integer> for Decimal {
354    #[inline]
355    fn from(value: Integer) -> Self {
356        i64::from(value).into()
357    }
358}
359
360impl TryFrom<i128> for Decimal {
361    type Error = TooLargeForDecimalError;
362
363    #[inline]
364    fn try_from(value: i128) -> Result<Self, Self::Error> {
365        Ok(Self {
366            value: value
367                .checked_mul(DECIMAL_PART_POW)
368                .ok_or(TooLargeForDecimalError)?,
369        })
370    }
371}
372
373impl TryFrom<u128> for Decimal {
374    type Error = TooLargeForDecimalError;
375
376    #[inline]
377    fn try_from(value: u128) -> Result<Self, Self::Error> {
378        Ok(Self {
379            value: i128::try_from(value)
380                .map_err(|_| TooLargeForDecimalError)?
381                .checked_mul(DECIMAL_PART_POW)
382                .ok_or(TooLargeForDecimalError)?,
383        })
384    }
385}
386
387impl From<Boolean> for Decimal {
388    #[inline]
389    fn from(value: Boolean) -> Self {
390        bool::from(value).into()
391    }
392}
393
394impl TryFrom<Float> for Decimal {
395    type Error = TooLargeForDecimalError;
396
397    #[inline]
398    fn try_from(value: Float) -> Result<Self, Self::Error> {
399        Double::from(value).try_into()
400    }
401}
402
403impl TryFrom<Double> for Decimal {
404    type Error = TooLargeForDecimalError;
405
406    #[inline]
407    #[allow(clippy::cast_precision_loss, clippy::cast_possible_truncation)]
408    fn try_from(value: Double) -> Result<Self, Self::Error> {
409        let shifted = f64::from(value) * (DECIMAL_PART_POW as f64);
410        if (i128::MIN as f64) <= shifted && shifted <= (i128::MAX as f64) {
411            Ok(Self {
412                value: shifted as i128,
413            })
414        } else {
415            Err(TooLargeForDecimalError)
416        }
417    }
418}
419
420impl From<Decimal> for Float {
421    #[inline]
422    #[allow(clippy::cast_precision_loss)]
423    fn from(value: Decimal) -> Self {
424        Double::from(value).into()
425    }
426}
427
428impl From<Decimal> for Double {
429    #[inline]
430    #[allow(clippy::cast_precision_loss)]
431    fn from(value: Decimal) -> Self {
432        let mut value = value.value;
433        let mut shift = DECIMAL_PART_POW;
434
435        // Hack to improve precision
436        if value != 0 {
437            while shift != 1 && value % 10 == 0 {
438                value /= 10;
439                shift /= 10;
440            }
441        }
442
443        ((value as f64) / (shift as f64)).into()
444    }
445}
446
447impl TryFrom<Decimal> for Integer {
448    type Error = TooLargeForIntegerError;
449
450    #[inline]
451    fn try_from(value: Decimal) -> Result<Self, Self::Error> {
452        Ok(i64::try_from(
453            value
454                .value
455                .checked_div(DECIMAL_PART_POW)
456                .ok_or(TooLargeForIntegerError)?,
457        )
458        .map_err(|_| TooLargeForIntegerError)?
459        .into())
460    }
461}
462
463impl FromStr for Decimal {
464    type Err = ParseDecimalError;
465
466    /// Parses decimals lexical mapping
467    fn from_str(input: &str) -> Result<Self, Self::Err> {
468        // (\+|-)?([0-9]+(\.[0-9]*)?|\.[0-9]+)
469        let input = input.as_bytes();
470        if input.is_empty() {
471            return Err(PARSE_UNEXPECTED_END);
472        }
473
474        let (sign, mut input) = match input.first() {
475            Some(b'+') => (1_i128, &input[1..]),
476            Some(b'-') => (-1_i128, &input[1..]),
477            _ => (1, input),
478        };
479
480        let mut value = 0_i128;
481        let with_before_dot = input.first().map_or(false, u8::is_ascii_digit);
482        while let Some(c) = input.first() {
483            if c.is_ascii_digit() {
484                value = value
485                    .checked_mul(10)
486                    .ok_or(PARSE_OVERFLOW)?
487                    .checked_add(sign * i128::from(*c - b'0'))
488                    .ok_or(PARSE_OVERFLOW)?;
489                input = &input[1..];
490            } else {
491                break;
492            }
493        }
494
495        let mut exp = DECIMAL_PART_POW;
496        if let Some(c) = input.first() {
497            if *c != b'.' {
498                return Err(PARSE_UNEXPECTED_CHAR);
499            }
500            input = &input[1..];
501            if input.is_empty() && !with_before_dot {
502                // We only have a dot
503                return Err(PARSE_UNEXPECTED_END);
504            }
505            while input.last() == Some(&b'0') {
506                // Hack to avoid underflows
507                input = &input[..input.len() - 1];
508            }
509            while let Some(c) = input.first() {
510                if c.is_ascii_digit() {
511                    exp /= 10;
512                    value = value
513                        .checked_mul(10)
514                        .ok_or(PARSE_OVERFLOW)?
515                        .checked_add(sign * i128::from(*c - b'0'))
516                        .ok_or(PARSE_OVERFLOW)?;
517                    input = &input[1..];
518                } else {
519                    return Err(PARSE_UNEXPECTED_CHAR);
520                }
521            }
522            if exp == 0 {
523                // Underflow
524                return Err(PARSE_UNDERFLOW);
525            }
526        } else if !with_before_dot {
527            // It's empty
528            return Err(PARSE_UNEXPECTED_END);
529        }
530
531        Ok(Self {
532            value: value.checked_mul(exp).ok_or(PARSE_OVERFLOW)?,
533        })
534    }
535}
536
537impl fmt::Display for Decimal {
538    /// Formats the decimal following its canonical representation.
539    #[allow(clippy::cast_possible_truncation)]
540    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
541        if self.value == 0 {
542            return if let Some(width) = f.width() {
543                for _ in 0..width {
544                    f.write_char('0')?;
545                }
546                Ok(())
547            } else {
548                f.write_char('0')
549            };
550        }
551
552        let mut value = self.value;
553        if self.value.is_negative() {
554            f.write_char('-')?;
555        }
556
557        let mut digits = [b'0'; 40];
558        let mut i = 0;
559        while value != 0 {
560            digits[i] = b'0' + ((value % 10).unsigned_abs() as u8);
561            value /= 10;
562            i += 1;
563        }
564
565        let last_non_zero = i - 1;
566        let first_non_zero = digits
567            .iter()
568            .copied()
569            .enumerate()
570            .find_map(|(i, v)| if v == b'0' { None } else { Some(i) })
571            .unwrap_or(40);
572
573        let decimal_part_digits = usize::try_from(DECIMAL_PART_DIGITS).map_err(|_| fmt::Error)?;
574        if last_non_zero >= decimal_part_digits {
575            let end = if let Some(mut width) = f.width() {
576                if self.value.is_negative() {
577                    width -= 1;
578                }
579                if last_non_zero - decimal_part_digits + 1 < width {
580                    decimal_part_digits + width
581                } else {
582                    last_non_zero + 1
583                }
584            } else {
585                last_non_zero + 1
586            };
587            for c in digits[decimal_part_digits..end].iter().rev() {
588                f.write_char(char::from(*c))?;
589            }
590        } else {
591            f.write_char('0')?
592        }
593        if decimal_part_digits > first_non_zero {
594            f.write_char('.')?;
595            let start = if let Some(precision) = f.precision() {
596                if decimal_part_digits - first_non_zero > precision {
597                    decimal_part_digits - precision
598                } else {
599                    first_non_zero
600                }
601            } else {
602                first_non_zero
603            };
604            for c in digits[start..decimal_part_digits].iter().rev() {
605                f.write_char(char::from(*c))?;
606            }
607        }
608
609        Ok(())
610    }
611}
612
613/// An error when parsing a [`Decimal`].
614#[derive(Debug, thiserror::Error)]
615#[error(transparent)]
616pub struct ParseDecimalError(#[from] DecimalParseErrorKind);
617
618#[derive(Debug, Clone, thiserror::Error)]
619enum DecimalParseErrorKind {
620    #[error("Value overflow")]
621    Overflow,
622    #[error("Value underflow")]
623    Underflow,
624    #[error("Unexpected character")]
625    UnexpectedChar,
626    #[error("Unexpected end of string")]
627    UnexpectedEnd,
628}
629
630const PARSE_OVERFLOW: ParseDecimalError = ParseDecimalError(DecimalParseErrorKind::Overflow);
631const PARSE_UNDERFLOW: ParseDecimalError = ParseDecimalError(DecimalParseErrorKind::Underflow);
632const PARSE_UNEXPECTED_CHAR: ParseDecimalError =
633    ParseDecimalError(DecimalParseErrorKind::UnexpectedChar);
634const PARSE_UNEXPECTED_END: ParseDecimalError =
635    ParseDecimalError(DecimalParseErrorKind::UnexpectedEnd);
636
637impl From<TooLargeForDecimalError> for ParseDecimalError {
638    fn from(_: TooLargeForDecimalError) -> Self {
639        Self(DecimalParseErrorKind::Overflow)
640    }
641}
642
643/// The input is too large to fit into a [`Decimal`].
644///
645/// Matches XPath [`FOCA0001` error](https://www.w3.org/TR/xpath-functions-31/#ERRFOCA0001).
646#[derive(Debug, Clone, Copy, thiserror::Error)]
647#[error("Value too large for xsd:decimal internal representation")]
648pub struct TooLargeForDecimalError;
649
650#[cfg(test)]
651#[allow(clippy::panic_in_result_fn)]
652mod tests {
653    use super::*;
654
655    #[test]
656    fn new() -> Result<(), ParseDecimalError> {
657        assert_eq!(Decimal::new(1, 0)?.to_string(), "1");
658        assert_eq!(Decimal::new(1, 1)?.to_string(), "0.1");
659        assert_eq!(Decimal::new(10, 0)?.to_string(), "10");
660        assert_eq!(Decimal::new(10, 1)?.to_string(), "1");
661        assert_eq!(Decimal::new(10, 2)?.to_string(), "0.1");
662        Ok(())
663    }
664
665    #[test]
666    fn from_str() -> Result<(), ParseDecimalError> {
667        Decimal::from_str("").unwrap_err();
668        Decimal::from_str("+").unwrap_err();
669        Decimal::from_str("-").unwrap_err();
670        Decimal::from_str(".").unwrap_err();
671        Decimal::from_str("+.").unwrap_err();
672        Decimal::from_str("-.").unwrap_err();
673        Decimal::from_str("a").unwrap_err();
674        Decimal::from_str(".a").unwrap_err();
675        assert_eq!(Decimal::from_str("210")?.to_string(), "210");
676        assert_eq!(Decimal::from_str("1000")?.to_string(), "1000");
677        assert_eq!(Decimal::from_str("-1.23")?.to_string(), "-1.23");
678        assert_eq!(
679            Decimal::from_str("12678967.543233")?.to_string(),
680            "12678967.543233"
681        );
682        assert_eq!(Decimal::from_str("+100000.00")?.to_string(), "100000");
683        assert_eq!(Decimal::from_str("0.1220")?.to_string(), "0.122");
684        assert_eq!(Decimal::from_str(".12200")?.to_string(), "0.122");
685        assert_eq!(Decimal::from_str("1.")?.to_string(), "1");
686        assert_eq!(Decimal::from_str("1.0")?.to_string(), "1");
687        assert_eq!(Decimal::from_str("01.0")?.to_string(), "1");
688        assert_eq!(Decimal::from_str("0")?.to_string(), "0");
689        assert_eq!(Decimal::from_str("-0")?.to_string(), "0");
690        assert_eq!(Decimal::from_str(&Decimal::MAX.to_string())?, Decimal::MAX);
691        assert_eq!(Decimal::from_str(&Decimal::MIN.to_string())?, Decimal::MIN);
692        Decimal::from_str("0.0000000000000000001").unwrap_err();
693        Decimal::from_str("1000000000000000000000").unwrap_err();
694        assert_eq!(
695            Decimal::from_str("0.100000000000000000000000000").unwrap(),
696            Decimal::from_str("0.1").unwrap()
697        );
698        Ok(())
699    }
700
701    #[test]
702    fn format() {
703        assert_eq!(format!("{}", Decimal::from(0)), "0");
704        assert_eq!(format!("{}", Decimal::from(1)), "1");
705        assert_eq!(format!("{}", Decimal::from(10)), "10");
706        assert_eq!(format!("{}", Decimal::from(100)), "100");
707        assert_eq!(format!("{}", Decimal::from(-1)), "-1");
708        assert_eq!(format!("{}", Decimal::from(-10)), "-10");
709
710        assert_eq!(format!("{:02}", Decimal::from(0)), "00");
711        assert_eq!(format!("{:02}", Decimal::from(1)), "01");
712        assert_eq!(format!("{:02}", Decimal::from(10)), "10");
713        assert_eq!(format!("{:02}", Decimal::from(100)), "100");
714        assert_eq!(format!("{:02}", Decimal::from(-1)), "-1");
715        assert_eq!(format!("{:02}", Decimal::from(-10)), "-10");
716    }
717
718    #[test]
719    fn add() {
720        assert!(Decimal::MIN.checked_add(Decimal::STEP).is_some());
721        assert!(Decimal::MAX.checked_add(Decimal::STEP).is_none());
722        assert_eq!(
723            Decimal::MAX.checked_add(Decimal::MIN),
724            Decimal::STEP.checked_neg()
725        );
726    }
727
728    #[test]
729    fn sub() {
730        assert!(Decimal::MIN.checked_sub(Decimal::STEP).is_none());
731        assert!(Decimal::MAX.checked_sub(Decimal::STEP).is_some());
732    }
733
734    #[test]
735    fn mul() -> Result<(), ParseDecimalError> {
736        assert_eq!(Decimal::from(1).checked_mul(-1), Some(Decimal::from(-1)));
737        assert_eq!(
738            Decimal::from(1000).checked_mul(1000),
739            Some(Decimal::from(1_000_000))
740        );
741        assert_eq!(
742            Decimal::from_str("0.1")?.checked_mul(Decimal::from_str("0.01")?),
743            Some(Decimal::from_str("0.001")?)
744        );
745        assert_eq!(Decimal::from(0).checked_mul(1), Some(Decimal::from(0)));
746        assert_eq!(Decimal::from(1).checked_mul(0), Some(Decimal::from(0)));
747        assert_eq!(Decimal::MAX.checked_mul(1), Some(Decimal::MAX));
748        assert_eq!(Decimal::MIN.checked_mul(1), Some(Decimal::MIN));
749        assert_eq!(
750            Decimal::from(1).checked_mul(Decimal::MAX),
751            Some(Decimal::MAX)
752        );
753        assert_eq!(
754            Decimal::from(1).checked_mul(Decimal::MIN),
755            Some(Decimal::MIN)
756        );
757        assert_eq!(
758            Decimal::MAX.checked_mul(-1),
759            Some(Decimal::MIN.checked_add(Decimal::STEP).unwrap())
760        );
761        assert_eq!(Decimal::MIN.checked_mul(-1), None);
762        assert_eq!(
763            Decimal::MIN
764                .checked_add(Decimal::STEP)
765                .unwrap()
766                .checked_mul(-1),
767            Some(Decimal::MAX)
768        );
769        Ok(())
770    }
771
772    #[test]
773    fn div() -> Result<(), ParseDecimalError> {
774        assert_eq!(Decimal::from(1).checked_div(1), Some(Decimal::from(1)));
775        assert_eq!(Decimal::from(100).checked_div(10), Some(Decimal::from(10)));
776        assert_eq!(
777            Decimal::from(10).checked_div(100),
778            Some(Decimal::from_str("0.1")?)
779        );
780        assert_eq!(Decimal::from(1).checked_div(0), None);
781        assert_eq!(Decimal::from(0).checked_div(1), Some(Decimal::from(0)));
782        assert_eq!(Decimal::MAX.checked_div(1), Some(Decimal::MAX));
783        assert_eq!(Decimal::MIN.checked_div(1), Some(Decimal::MIN));
784        assert_eq!(
785            Decimal::MAX.checked_div(-1),
786            Some(Decimal::MIN.checked_add(Decimal::STEP).unwrap())
787        );
788        assert_eq!(Decimal::MIN.checked_div(-1), None);
789        assert_eq!(
790            Decimal::MIN
791                .checked_add(Decimal::STEP)
792                .unwrap()
793                .checked_div(-1),
794            Some(Decimal::MAX)
795        );
796        Ok(())
797    }
798
799    #[test]
800    fn rem() -> Result<(), ParseDecimalError> {
801        assert_eq!(Decimal::from(10).checked_rem(3), Some(Decimal::from(1)));
802        assert_eq!(Decimal::from(6).checked_rem(-2), Some(Decimal::from(0)));
803        assert_eq!(
804            Decimal::from_str("4.5")?.checked_rem(Decimal::from_str("1.2")?),
805            Some(Decimal::from_str("0.9")?)
806        );
807        assert_eq!(Decimal::from(1).checked_rem(0), None);
808        assert_eq!(
809            Decimal::MAX.checked_rem(1),
810            Some(Decimal::from_str("0.687303715884105727")?)
811        );
812        assert_eq!(
813            Decimal::MIN.checked_rem(1),
814            Some(Decimal::from_str("-0.687303715884105728")?)
815        );
816        assert_eq!(
817            Decimal::MAX.checked_rem(Decimal::STEP),
818            Some(Decimal::default())
819        );
820        assert_eq!(
821            Decimal::MIN.checked_rem(Decimal::STEP),
822            Some(Decimal::default())
823        );
824        assert_eq!(
825            Decimal::MAX.checked_rem(Decimal::MAX),
826            Some(Decimal::default())
827        );
828        assert_eq!(
829            Decimal::MIN.checked_rem(Decimal::MIN),
830            Some(Decimal::default())
831        );
832        Ok(())
833    }
834
835    #[test]
836    fn round() -> Result<(), ParseDecimalError> {
837        assert_eq!(Decimal::from(10).checked_round(), Some(Decimal::from(10)));
838        assert_eq!(Decimal::from(-10).checked_round(), Some(Decimal::from(-10)));
839        assert_eq!(
840            Decimal::from(i64::MIN).checked_round(),
841            Some(Decimal::from(i64::MIN))
842        );
843        assert_eq!(
844            Decimal::from(i64::MAX).checked_round(),
845            Some(Decimal::from(i64::MAX))
846        );
847        assert_eq!(
848            Decimal::from_str("2.5")?.checked_round(),
849            Some(Decimal::from(3))
850        );
851        assert_eq!(
852            Decimal::from_str("2.4999")?.checked_round(),
853            Some(Decimal::from(2))
854        );
855        assert_eq!(
856            Decimal::from_str("-2.5")?.checked_round(),
857            Some(Decimal::from(-2))
858        );
859        assert_eq!(Decimal::MAX.checked_round(), None);
860        assert_eq!(
861            Decimal::MAX
862                .checked_sub(Decimal::from_str("0.5")?)
863                .unwrap()
864                .checked_round(),
865            Some(Decimal::from_str("170141183460469231731")?)
866        );
867        assert_eq!(Decimal::MIN.checked_round(), None);
868        assert_eq!(
869            Decimal::MIN
870                .checked_add(Decimal::from_str("0.5")?)
871                .unwrap()
872                .checked_round(),
873            Some(Decimal::from_str("-170141183460469231731")?)
874        );
875        Ok(())
876    }
877
878    #[test]
879    fn ceil() -> Result<(), ParseDecimalError> {
880        assert_eq!(Decimal::from(10).checked_ceil(), Some(Decimal::from(10)));
881        assert_eq!(Decimal::from(-10).checked_ceil(), Some(Decimal::from(-10)));
882        assert_eq!(
883            Decimal::from_str("10.5")?.checked_ceil(),
884            Some(Decimal::from(11))
885        );
886        assert_eq!(
887            Decimal::from_str("-10.5")?.checked_ceil(),
888            Some(Decimal::from(-10))
889        );
890        assert_eq!(
891            Decimal::from(i64::MIN).checked_ceil(),
892            Some(Decimal::from(i64::MIN))
893        );
894        assert_eq!(
895            Decimal::from(i64::MAX).checked_ceil(),
896            Some(Decimal::from(i64::MAX))
897        );
898        assert_eq!(Decimal::MAX.checked_ceil(), None);
899        assert_eq!(
900            Decimal::MAX
901                .checked_sub(Decimal::from(1))
902                .unwrap()
903                .checked_ceil(),
904            Some(Decimal::from_str("170141183460469231731")?)
905        );
906        assert_eq!(
907            Decimal::MIN.checked_ceil(),
908            Some(Decimal::from_str("-170141183460469231731")?)
909        );
910        Ok(())
911    }
912
913    #[test]
914    fn floor() -> Result<(), ParseDecimalError> {
915        assert_eq!(Decimal::from(10).checked_floor(), Some(Decimal::from(10)));
916        assert_eq!(Decimal::from(-10).checked_floor(), Some(Decimal::from(-10)));
917        assert_eq!(
918            Decimal::from_str("10.5")?.checked_floor(),
919            Some(Decimal::from(10))
920        );
921        assert_eq!(
922            Decimal::from_str("-10.5")?.checked_floor(),
923            Some(Decimal::from(-11))
924        );
925        assert_eq!(
926            Decimal::from(i64::MIN).checked_floor(),
927            Some(Decimal::from(i64::MIN))
928        );
929        assert_eq!(
930            Decimal::from(i64::MAX).checked_floor(),
931            Some(Decimal::from(i64::MAX))
932        );
933        assert_eq!(
934            Decimal::MAX.checked_floor(),
935            Some(Decimal::from_str("170141183460469231731")?)
936        );
937        assert_eq!(Decimal::MIN.checked_floor(), None);
938        assert_eq!(
939            Decimal::MIN
940                .checked_add(Decimal::from_str("1")?)
941                .unwrap()
942                .checked_floor(),
943            Some(Decimal::from_str("-170141183460469231731")?)
944        );
945        Ok(())
946    }
947
948    #[test]
949    fn to_be_bytes() -> Result<(), ParseDecimalError> {
950        assert_eq!(
951            Decimal::from_be_bytes(Decimal::MIN.to_be_bytes()),
952            Decimal::MIN
953        );
954        assert_eq!(
955            Decimal::from_be_bytes(Decimal::MAX.to_be_bytes()),
956            Decimal::MAX
957        );
958        assert_eq!(
959            Decimal::from_be_bytes(Decimal::from(i64::MIN).to_be_bytes()),
960            Decimal::from(i64::MIN)
961        );
962        assert_eq!(
963            Decimal::from_be_bytes(Decimal::from(i64::MAX).to_be_bytes()),
964            Decimal::from(i64::MAX)
965        );
966        assert_eq!(
967            Decimal::from_be_bytes(Decimal::from(0).to_be_bytes()),
968            Decimal::from(0)
969        );
970        assert_eq!(
971            Decimal::from_be_bytes(Decimal::from(0).to_be_bytes()),
972            Decimal::from(0)
973        );
974        assert_eq!(
975            Decimal::from_be_bytes(Decimal::from_str("0.01")?.to_be_bytes()),
976            Decimal::from_str("0.01")?
977        );
978        Ok(())
979    }
980
981    #[test]
982    fn from_bool() {
983        assert_eq!(Decimal::from(false), Decimal::from(0_u8));
984        assert_eq!(Decimal::from(true), Decimal::from(1_u8));
985    }
986
987    #[test]
988    fn from_float() -> Result<(), ParseDecimalError> {
989        assert_eq!(
990            Decimal::try_from(Float::from(0.)).ok(),
991            Some(Decimal::from(0))
992        );
993        assert_eq!(
994            Decimal::try_from(Float::from(-0.)).ok(),
995            Some(Decimal::from(0))
996        );
997        assert_eq!(
998            Decimal::try_from(Float::from(-123.5)).ok(),
999            Some(Decimal::from_str("-123.5")?)
1000        );
1001        Decimal::try_from(Float::from(f32::NAN)).unwrap_err();
1002        Decimal::try_from(Float::from(f32::INFINITY)).unwrap_err();
1003        Decimal::try_from(Float::from(f32::NEG_INFINITY)).unwrap_err();
1004        Decimal::try_from(Float::from(f32::MIN)).unwrap_err();
1005        Decimal::try_from(Float::from(f32::MAX)).unwrap_err();
1006        assert!(
1007            Decimal::try_from(Float::from(1_672_507_300_000.))
1008                .unwrap()
1009                .checked_sub(Decimal::from(1_672_507_293_696_i64))
1010                .unwrap()
1011                .checked_abs()
1012                .unwrap()
1013                < Decimal::from(1)
1014        );
1015        Ok(())
1016    }
1017
1018    #[test]
1019    fn from_double() -> Result<(), ParseDecimalError> {
1020        assert_eq!(
1021            Decimal::try_from(Double::from(0.)).ok(),
1022            Some(Decimal::from(0))
1023        );
1024        assert_eq!(
1025            Decimal::try_from(Double::from(-0.)).ok(),
1026            Some(Decimal::from(0))
1027        );
1028        assert_eq!(
1029            Decimal::try_from(Double::from(-123.1)).ok(),
1030            Some(Decimal::from_str("-123.1")?)
1031        );
1032        assert!(
1033            Decimal::try_from(Double::from(1_672_507_302_466.))
1034                .unwrap()
1035                .checked_sub(Decimal::from(1_672_507_302_466_i64))
1036                .unwrap()
1037                .checked_abs()
1038                .unwrap()
1039                < Decimal::from(1)
1040        );
1041        Decimal::try_from(Double::from(f64::NAN)).unwrap_err();
1042        Decimal::try_from(Double::from(f64::INFINITY)).unwrap_err();
1043        Decimal::try_from(Double::from(f64::NEG_INFINITY)).unwrap_err();
1044        Decimal::try_from(Double::from(f64::MIN)).unwrap_err();
1045        Decimal::try_from(Double::from(f64::MAX)).unwrap_err();
1046        Ok(())
1047    }
1048
1049    #[test]
1050    fn to_float() -> Result<(), ParseDecimalError> {
1051        assert_eq!(Float::from(Decimal::from(0)), Float::from(0.));
1052        assert_eq!(Float::from(Decimal::from(1)), Float::from(1.));
1053        assert_eq!(Float::from(Decimal::from(10)), Float::from(10.));
1054        assert_eq!(Float::from(Decimal::from_str("0.1")?), Float::from(0.1));
1055        assert!((Float::from(Decimal::MAX) - Float::from(1.701_412e20)).abs() < Float::from(1.));
1056        assert!((Float::from(Decimal::MIN) - Float::from(-1.701_412e20)).abs() < Float::from(1.));
1057        Ok(())
1058    }
1059
1060    #[test]
1061    fn to_double() -> Result<(), ParseDecimalError> {
1062        assert_eq!(Double::from(Decimal::from(0)), Double::from(0.));
1063        assert_eq!(Double::from(Decimal::from(1)), Double::from(1.));
1064        assert_eq!(Double::from(Decimal::from(10)), Double::from(10.));
1065        assert_eq!(Double::from(Decimal::from_str("0.1")?), Double::from(0.1));
1066        assert!(
1067            (Double::from(Decimal::MAX) - Double::from(1.701_411_834_604_692_4e20)).abs()
1068                < Double::from(1.)
1069        );
1070        assert!(
1071            (Double::from(Decimal::MIN) - Double::from(-1.701_411_834_604_692_4e20)).abs()
1072                < Double::from(1.)
1073        );
1074        Ok(())
1075    }
1076
1077    #[test]
1078    fn minimally_conformant() -> Result<(), ParseDecimalError> {
1079        // All minimally conforming processors must support decimal values whose absolute value can be expressed as i / 10^k,
1080        // where i and k are nonnegative integers such that i < 10^16 and k ≤ 16 (i.e., those expressible with sixteen total digits).
1081        assert_eq!(
1082            Decimal::from_str("1234567890123456")?.to_string(),
1083            "1234567890123456"
1084        );
1085        assert_eq!(
1086            Decimal::from_str("-1234567890123456")?.to_string(),
1087            "-1234567890123456"
1088        );
1089        assert_eq!(
1090            Decimal::from_str("0.1234567890123456")?.to_string(),
1091            "0.1234567890123456"
1092        );
1093        assert_eq!(
1094            Decimal::from_str("-0.1234567890123456")?.to_string(),
1095            "-0.1234567890123456"
1096        );
1097        Ok(())
1098    }
1099}