feldera_fxp/
dynamic.rs

1use std::{
2    cmp::Ordering,
3    fmt::{Debug, Display, Write},
4    str::FromStr,
5};
6
7use smallstr::SmallString;
8
9use crate::{
10    checked_pow10, debug_decimal, display_decimal, parse_decimal, pow10, u256::I256, Fixed,
11    OutOfRange, ParseDecimalError,
12};
13
14/// Decimal real number with 38 digits of precision and dynamic scale.
15///
16/// This type is primarily meant as a serialized form of `Fixed` that does not
17/// require parameterization.  Any `Fixed` can be converted into
18/// `DynamicDecimal` and then converted back into any other `Fixed`, possibly
19/// with a different precision and scale, without loss of precision (beyond that
20/// inherent in change of scale, if any).
21///
22/// # Representation
23///
24/// The number is represented as an `i128` significand and a `u8` scale, that
25/// together express the value `significand * 10**-scale`.
26///
27/// # Invariants
28///
29/// These invariants on significand and scale ensure that the value is in
30/// canonical form:
31///
32/// * If `significand != 0 && scale != 0`, then `significand` must not be a
33///   multiple of 10.
34///
35/// * If `significand != 0 && scale == 0`, then `significand` may be a
36///   multiple of 10.  (This is a "denormalized" representation with fewer
37///   digits of precision than other forms.)
38///
39/// * If `significand == 0`, then `scale` must be zero.
40#[derive(Copy, Clone, Default, PartialEq, Eq, Hash)]
41#[cfg_attr(feature = "size_of", derive(size_of::SizeOf))]
42#[cfg_attr(
43    feature = "rkyv",
44    derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, rkyv::CheckBytes)
45)]
46pub struct DynamicDecimal {
47    /// Significand.
48    sig: i128,
49
50    /// The number of digits of the value that follow the decimal point.
51    exponent: u8,
52}
53
54impl DynamicDecimal {
55    /// The largest `DynamicDecimal` value (`i128::MAX`).
56    pub const MAX: Self = DynamicDecimal::new(i128::MAX, 0);
57
58    /// The smallest `DynamicDecimal` value (`i128::MIN`).
59    pub const MIN: Self = DynamicDecimal::new(i128::MIN, 0);
60
61    /// 0 as `DynamicDecimal`.
62    pub const ZERO: Self = DynamicDecimal::new(0, 0);
63
64    /// 1 as `DynamicDecimal`.
65    pub const ONE: Self = DynamicDecimal::new(1, 0);
66
67    /// Constructs a new `DynamicDecimal` with value `sig * 10**-exponent`.
68    pub const fn new(sig: i128, exponent: u8) -> Self {
69        if exponent == 0 {
70            Self { sig, exponent }
71        } else if sig == 0 {
72            Self { sig, exponent: 0 }
73        } else {
74            /// Returns `(sig, exponent)` divided by `10**D` as many times as
75            /// possible without dropping nonzero decimal digits.
76            const fn reduce<const D: u8>(mut sig: i128, mut exponent: u8) -> (i128, u8) {
77                // `10**D`.
78                let scale = pow10(D as usize);
79
80                // A multiple of `10**D` has at least `D` trailing zeros, since
81                // `10 == 2*5`, so if any of the `D` trailing bits is nonzero,
82                // we can skip the expensive remainder operation.
83                while exponent >= D
84                    && sig.unsigned_abs() >= scale.cast_unsigned()
85                    && (sig & ((1 << D) - 1)) == 0
86                    && sig % scale == 0
87                {
88                    sig /= scale;
89                    exponent -= D;
90                }
91                (sig, exponent)
92            }
93
94            // Canonicalize in a few stages, so that we don't have to divide as
95            // many times as otherwise for numbers that have many trailing
96            // decimal zeros.
97            let (sig, exponent) = reduce::<8>(sig, exponent);
98            let (sig, exponent) = reduce::<4>(sig, exponent);
99            let (sig, exponent) = reduce::<1>(sig, exponent);
100            debug_assert!(sig % 10 != 0 || exponent == 0);
101            Self { sig, exponent }
102        }
103    }
104
105    /// Returns the canonical [significand](Self#representation).
106    pub const fn significand(&self) -> i128 {
107        self.sig
108    }
109
110    /// Returns the canonical [scale](Self#representation).
111    pub const fn scale(&self) -> u8 {
112        self.exponent
113    }
114}
115
116impl<const P: usize, const S: usize> From<Fixed<P, S>> for DynamicDecimal {
117    /// Encodes `value`, for later deserialization into a new `Fixed` with
118    /// possibly a different precision and scale.
119    fn from(value: Fixed<P, S>) -> Self {
120        Self::new(value.0, S as u8)
121    }
122}
123
124impl<const P: usize, const S: usize> TryFrom<DynamicDecimal> for Fixed<P, S> {
125    type Error = OutOfRange;
126
127    /// Deserializes [DynamicDecimal] into `Fixed`.  If successful, returns the
128    /// original value from before serialization.  If `S < value.exponent`, then
129    /// some trailing decimals are lost, by rounding toward zero.  Returns an
130    /// error` if the value is out of range for this type.
131    fn try_from(value: DynamicDecimal) -> Result<Self, Self::Error> {
132        Self::try_new_with_exponent(value.sig, S as i32 - value.exponent as i32).ok_or(OutOfRange)
133    }
134}
135
136impl Debug for DynamicDecimal {
137    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
138        debug_decimal(self.sig, self.exponent as usize, f)
139    }
140}
141
142impl Display for DynamicDecimal {
143    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
144        display_decimal(self.sig, self.exponent as usize, f)
145    }
146}
147
148impl FromStr for DynamicDecimal {
149    type Err = ParseDecimalError;
150
151    /// Parses `s` as `DynamicDecimal`.
152    ///
153    /// This accepts the same forms as [f64::from_str], except that it rejects
154    /// infinities and NaNs (which `Fixed` does not support), as well as
155    /// out-of-range values.  Rounds overprecise values to the nearest
156    /// representable value, rounding halfway values to even.
157    fn from_str(s: &str) -> Result<Self, Self::Err> {
158        let (sig, exponent) = parse_decimal(s, 0)?;
159        match (sig, exponent) {
160            (0, _) => Ok(Self::ZERO),
161            (_, 1..) => {
162                let sig = checked_pow10(exponent.cast_unsigned())
163                    .and_then(|m| m.checked_mul(sig))
164                    .ok_or(ParseDecimalError::OutOfRange)?;
165                Ok(Self::new(sig, 0))
166            }
167            (_, 0) => Ok(Self { sig, exponent: 0 }),
168            (_, -255..0) => Ok(Self::new(sig, (-exponent) as u8)),
169            (_, ..-255) => {
170                // We could "denormalize" by dividing `sig` by a power of 10 and
171                // adjusting `exponent`, but the value would inevitably be zero
172                // when we convert to `Fixed`, which is what we really care
173                // about.
174                Ok(Self::ZERO)
175            }
176        }
177    }
178}
179
180impl TryFrom<u128> for DynamicDecimal {
181    type Error = OutOfRange;
182
183    fn try_from(value: u128) -> Result<Self, Self::Error> {
184        Ok(Self::new(value.try_into().map_err(|_| OutOfRange)?, 0))
185    }
186}
187
188macro_rules! from_int {
189    ($type_name:ty) => {
190        impl From<$type_name> for DynamicDecimal {
191            fn from(value: $type_name) -> Self {
192                Self::new(value as i128, 0)
193            }
194        }
195    };
196}
197from_int!(i128);
198from_int!(i64);
199from_int!(i32);
200from_int!(i16);
201from_int!(i8);
202from_int!(isize);
203from_int!(u64);
204from_int!(u32);
205from_int!(u16);
206from_int!(u8);
207from_int!(usize);
208
209impl From<DynamicDecimal> for i128 {
210    /// Convert from `Fixed` to integer, rounding toward zero (the same
211    /// semantics as Rust casts from float to integer).
212    fn from(value: DynamicDecimal) -> Self {
213        checked_pow10(value.exponent.into()).map_or(0, |divisor| value.sig / divisor)
214    }
215}
216
217macro_rules! try_to_signed_int {
218    ($type_name:ty) => {
219        impl TryFrom<DynamicDecimal> for $type_name {
220            type Error = OutOfRange;
221
222            /// Convert from `Fixed` to integer, rounding toward zero (the same
223            /// semantics as Rust casts from float to integer).
224            fn try_from(value: DynamicDecimal) -> Result<Self, Self::Error> {
225                match checked_pow10(value.exponent.into()) {
226                    Some(divisor) => (value.sig / divisor).try_into().map_err(|_| OutOfRange),
227                    None => Ok(0),
228                }
229            }
230        }
231    };
232}
233try_to_signed_int!(i64);
234try_to_signed_int!(i32);
235try_to_signed_int!(i16);
236try_to_signed_int!(i8);
237try_to_signed_int!(isize);
238
239/// This is the same as [try_to_signed_int] except for the documentation
240/// comment.
241macro_rules! try_to_unsigned_int {
242    ($type_name:ty) => {
243        impl TryFrom<DynamicDecimal> for $type_name {
244            type Error = OutOfRange;
245
246            /// Convert from `Fixed` to integer, rounding toward zero (the same
247            /// semantics as Rust casts from float to integer).
248            ///
249            /// Because this rounds toward zero, negative values greater than -1
250            /// will convert to 0 instead of an out-of-range error.
251            fn try_from(value: DynamicDecimal) -> Result<Self, Self::Error> {
252                match checked_pow10(value.exponent.into()) {
253                    Some(divisor) => (value.sig / divisor).try_into().map_err(|_| OutOfRange),
254                    None => Ok(0),
255                }
256            }
257        }
258    };
259}
260try_to_unsigned_int!(u128);
261try_to_unsigned_int!(u64);
262try_to_unsigned_int!(u32);
263try_to_unsigned_int!(u16);
264try_to_unsigned_int!(u8);
265try_to_unsigned_int!(usize);
266
267impl TryFrom<f64> for DynamicDecimal {
268    type Error = OutOfRange;
269
270    /// Convert `value` to `DynamicDecimal`, reporting an error if `value` is
271    /// out of range.
272    fn try_from(value: f64) -> Result<Self, Self::Error> {
273        // We need to convert binary to decimal.  We could do better, in theory,
274        // than formatting to a string and parsing back, but possibly not much
275        // better.  If this shows up as important in profiles, then we can
276        // improve it, especially if there are important special cases
277        // (e.g. integers).
278        let mut buf = SmallString::<[u8; 64]>::new();
279        write!(&mut buf, "{value:.15e}").unwrap();
280        buf.parse().map_err(|_| OutOfRange)
281    }
282}
283
284impl PartialOrd for DynamicDecimal {
285    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
286        Some(self.cmp(other))
287    }
288}
289
290impl Ord for DynamicDecimal {
291    fn cmp(&self, other: &Self) -> Ordering {
292        match self.exponent.cmp(&other.exponent) {
293            Ordering::Less => {
294                if let Some(multiplier) =
295                    checked_pow10(other.exponent as u32 - self.exponent as u32)
296                {
297                    I256::from_product(self.sig, multiplier).cmp(&I256::from(other.sig))
298                } else {
299                    match self.sig.cmp(&0) {
300                        Ordering::Equal => 0.cmp(&other.sig),
301                        ordering => ordering,
302                    }
303                }
304            }
305            Ordering::Equal => self.sig.cmp(&other.sig),
306            Ordering::Greater => {
307                if let Some(multiplier) =
308                    checked_pow10(self.exponent as u32 - other.exponent as u32)
309                {
310                    I256::from(self.sig).cmp(&I256::from_product(other.sig, multiplier))
311                } else {
312                    match other.sig.cmp(&0) {
313                        Ordering::Equal => self.sig.cmp(&0),
314                        ordering => ordering.reverse(),
315                    }
316                }
317            }
318        }
319    }
320}
321
322#[cfg(test)]
323mod test {
324    use crate::{DynamicDecimal, OutOfRange, ParseDecimalError};
325
326    #[test]
327    fn eq() {
328        assert_eq!(DynamicDecimal::new(123, 2), DynamicDecimal::new(1230, 3));
329        assert_eq!(DynamicDecimal::new(1230, 3), DynamicDecimal::new(123, 2));
330        assert_eq!(DynamicDecimal::new(123, 2), DynamicDecimal::new(123, 2));
331        assert_ne!(DynamicDecimal::new(123, 2), DynamicDecimal::new(123, 3));
332    }
333
334    #[test]
335    fn compare() {
336        type DD = DynamicDecimal;
337        fn check_comparisons(dx: DD, dy: DD, x: i128, y: i128) {
338            assert_eq!(dx == dy, x == y);
339            assert_eq!(dx != dy, x != y);
340            assert_eq!(dx > dy, x > y);
341            assert_eq!(dx >= dy, x >= y);
342            assert_eq!(dx < dy, x < y);
343            assert_eq!(dx <= dy, x <= y);
344        }
345
346        for x in -999..=999 {
347            let fx = DD::new(x, 1);
348            for y in -999..=999 {
349                check_comparisons(fx, DD::new(y, 0), x, y * 10);
350                check_comparisons(fx, DD::new(y, 1), x, y);
351                check_comparisons(fx, DD::new(y, 2), x * 10, y);
352            }
353        }
354
355        // Some handwritten overflow cases.
356        check_comparisons(DD::new(0, 40), DD::new(0, 0), 0, 0);
357        check_comparisons(DD::new(0, 0), DD::new(0, 40), 0, 0);
358
359        check_comparisons(DD::new(1, 40), DD::new(1, 0), 0, 1);
360        check_comparisons(DD::new(1, 40), DD::new(-1, 0), 1, 0);
361        check_comparisons(DD::new(-1, 40), DD::new(1, 0), 0, 1);
362        check_comparisons(DD::new(-1, 40), DD::new(-1, 0), 1, 0);
363
364        check_comparisons(DD::new(1, 0), DD::new(1, 40), 1, 0);
365        check_comparisons(DD::new(1, 0), DD::new(-1, 40), 1, 0);
366        check_comparisons(DD::new(-1, 0), DD::new(1, 40), 0, 1);
367        check_comparisons(DD::new(-1, 0), DD::new(-1, 40), 0, 1);
368    }
369
370    #[test]
371    fn from_str() {
372        for (s, expect) in [
373            ("0", Ok("0")),
374            ("0.", Ok("0")),
375            (".0", Ok("0")),
376            ("-0", Ok("0")),
377            ("+0", Ok("0")),
378            ("--0", Err(ParseDecimalError::SyntaxError)),
379            ("-+0", Err(ParseDecimalError::SyntaxError)),
380            ("0x", Err(ParseDecimalError::SyntaxError)),
381            ("0e5x", Err(ParseDecimalError::SyntaxError)),
382            ("1.23", Ok("1.23")),
383            ("-1.23", Ok("-1.23")),
384            ("+1.23", Ok("1.23")),
385            ("99999999", Ok("99999999")),
386            ("999999999", Ok("999999999")),
387            ("999999999E-1", Ok("99999999.9")),
388            ("9999999999e-1", Ok("999999999.9")),
389            ("9999999999E-2", Ok("99999999.99")),
390            ("99999999999e-2", Ok("999999999.99")),
391            ("99999999999e-3", Ok("99999999.999")),
392            ("99999999991e-3", Ok("99999999.991")),
393            // This value overflows the range of `i128` as an integer, so it
394            // triggers the case where we stop accepting digits and simply
395            // adjust the exponent instead.
396            (
397                "111111111111111111111111111111111111111111e-34",
398                Ok("11111111.1111111111111111111111111111111"),
399            ),
400            // This value overflows the range of `i128` in the fraction, so it
401            // triggers the case where we stop accepting digits and simply
402            // adjust the exponent instead.
403            (
404                "1.23456788901234567890123456789012345678890123456",
405                Ok("1.23456788901234567890123456789012345678"),
406            ),
407            // This value positively overflows the exponent.
408            ("1e999999999999999", Err(ParseDecimalError::OutOfRange)),
409            // This value positively overflows the exponent but the value is 0.
410            ("0e999999999999999", Ok("0")),
411            // This value negatively overflows the exponent.
412            ("1e-999999999999999", Ok("0")),
413            // This value overflows the range of `i128` as an integer, which
414            // starts adjusting the exponent, and then it overflows the exponent
415            // with `e`.
416            (
417                "111111111111111111111111111111111111111111e2147483644",
418                Err(ParseDecimalError::OutOfRange),
419            ),
420            // This value adjusts the exponent downward, and then it negatively
421            // overflows the exponent with `e`.
422            (
423                ".1111111111111111111111111111111111111111e-2147483648",
424                Ok("0"),
425            ),
426            ("123e5", Ok("12300000")),
427            ("123E4", Ok("1230000")),
428            ("123e3", Ok("123000")),
429            ("123e2", Ok("12300")),
430            ("123e1", Ok("1230")),
431            ("123e0", Ok("123")),
432            ("123e-1", Ok("12.3")),
433            ("123e-2", Ok("1.23")),
434            (".123", Ok("0.123")),
435            (".124", Ok("0.124")),
436            (".125", Ok("0.125")),
437            (".126", Ok("0.126")),
438            (".133", Ok("0.133")),
439            (".134", Ok("0.134")),
440            (".135", Ok("0.135")),
441            (".136", Ok("0.136")),
442            ("1e38", Ok("100000000000000000000000000000000000000")),
443            ("1e39", Err(ParseDecimalError::OutOfRange)),
444            ("1e-255", Ok("0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001")),
445            ("1e-256", Ok("0")),
446        ] {
447            println!("{s}: {:?}", s.parse::<DynamicDecimal>());
448            assert_eq!(
449                s.parse::<DynamicDecimal>().map(|d| d.to_string()),
450                expect.map(|d| d.to_string())
451            );
452        }
453    }
454
455    #[test]
456    fn to_integer() {
457        for x in -9999..=9999 {
458            let f = DynamicDecimal::new(x, 1);
459            assert_eq!(i128::from(f), x / 10);
460            assert_eq!(i64::try_from(f).unwrap(), (x / 10) as i64);
461            assert_eq!(i32::try_from(f).unwrap(), (x / 10) as i32);
462            assert_eq!(i16::try_from(f).unwrap(), (x / 10) as i16);
463            assert_eq!(
464                i8::try_from(f).ok(),
465                (-1289..=1279).contains(&x).then_some((x / 10) as i8)
466            );
467            assert_eq!(
468                u128::try_from(f).ok(),
469                (x > -10).then_some((x / 10) as u128)
470            );
471            assert_eq!(u64::try_from(f).ok(), (x > -10).then_some((x / 10) as u64));
472            assert_eq!(u32::try_from(f).ok(), (x > -10).then_some((x / 10) as u32));
473            assert_eq!(u16::try_from(f).ok(), (x > -10).then_some((x / 10) as u16));
474            assert_eq!(
475                u8::try_from(f).ok(),
476                (-9..=2559).contains(&x).then_some((x / 10) as u8)
477            );
478        }
479
480        assert_eq!(i128::from(DynamicDecimal::new(1, 40)), 0);
481        assert_eq!(i128::from(DynamicDecimal::new(i128::MAX, 0)), i128::MAX);
482        assert_eq!(i64::try_from(DynamicDecimal::new(1, 40)), Ok(0));
483        assert_eq!(
484            i64::try_from(DynamicDecimal::new(i128::MAX, 0)),
485            Err(OutOfRange)
486        );
487        assert_eq!(
488            i64::try_from(DynamicDecimal::new(i128::MIN, 0)),
489            Err(OutOfRange)
490        );
491    }
492}