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)
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 exponent(&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 From<DynamicDecimal> for f64 {
268    fn from(value: DynamicDecimal) -> Self {
269        value.significand() as f64 / pow10(value.exponent() as usize) as f64
270    }
271}
272
273impl From<DynamicDecimal> for f32 {
274    fn from(value: DynamicDecimal) -> Self {
275        value.significand() as f32 / pow10(value.exponent() as usize) as f32
276    }
277}
278
279impl TryFrom<f64> for DynamicDecimal {
280    type Error = OutOfRange;
281
282    /// Convert `value` to `DynamicDecimal`, reporting an error if `value` is
283    /// out of range.
284    fn try_from(value: f64) -> Result<Self, Self::Error> {
285        // We need to convert binary to decimal.  We could do better, in theory,
286        // than formatting to a string and parsing back, but possibly not much
287        // better.  If this shows up as important in profiles, then we can
288        // improve it, especially if there are important special cases
289        // (e.g. integers).
290        let mut buf = SmallString::<[u8; 64]>::new();
291        write!(&mut buf, "{value:.15e}").unwrap();
292        buf.parse().map_err(|_| OutOfRange)
293    }
294}
295
296impl PartialOrd for DynamicDecimal {
297    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
298        Some(self.cmp(other))
299    }
300}
301
302impl Ord for DynamicDecimal {
303    fn cmp(&self, other: &Self) -> Ordering {
304        match self.exponent.cmp(&other.exponent) {
305            Ordering::Less => {
306                if let Some(multiplier) =
307                    checked_pow10(other.exponent as u32 - self.exponent as u32)
308                {
309                    I256::from_product(self.sig, multiplier).cmp(&I256::from(other.sig))
310                } else {
311                    match self.sig.cmp(&0) {
312                        Ordering::Equal => 0.cmp(&other.sig),
313                        ordering => ordering,
314                    }
315                }
316            }
317            Ordering::Equal => self.sig.cmp(&other.sig),
318            Ordering::Greater => {
319                if let Some(multiplier) =
320                    checked_pow10(self.exponent as u32 - other.exponent as u32)
321                {
322                    I256::from(self.sig).cmp(&I256::from_product(other.sig, multiplier))
323                } else {
324                    match other.sig.cmp(&0) {
325                        Ordering::Equal => self.sig.cmp(&0),
326                        ordering => ordering.reverse(),
327                    }
328                }
329            }
330        }
331    }
332}
333
334#[cfg(test)]
335mod test {
336    use crate::{DynamicDecimal, OutOfRange, ParseDecimalError};
337
338    #[test]
339    fn eq() {
340        assert_eq!(DynamicDecimal::new(123, 2), DynamicDecimal::new(1230, 3));
341        assert_eq!(DynamicDecimal::new(1230, 3), DynamicDecimal::new(123, 2));
342        assert_eq!(DynamicDecimal::new(123, 2), DynamicDecimal::new(123, 2));
343        assert_ne!(DynamicDecimal::new(123, 2), DynamicDecimal::new(123, 3));
344    }
345
346    #[test]
347    fn compare() {
348        type DD = DynamicDecimal;
349        fn check_comparisons(dx: DD, dy: DD, x: i128, y: i128) {
350            assert_eq!(dx == dy, x == y);
351            assert_eq!(dx != dy, x != y);
352            assert_eq!(dx > dy, x > y);
353            assert_eq!(dx >= dy, x >= y);
354            assert_eq!(dx < dy, x < y);
355            assert_eq!(dx <= dy, x <= y);
356        }
357
358        for x in -999..=999 {
359            let fx = DD::new(x, 1);
360            for y in -999..=999 {
361                check_comparisons(fx, DD::new(y, 0), x, y * 10);
362                check_comparisons(fx, DD::new(y, 1), x, y);
363                check_comparisons(fx, DD::new(y, 2), x * 10, y);
364            }
365        }
366
367        // Some handwritten overflow cases.
368        check_comparisons(DD::new(0, 40), DD::new(0, 0), 0, 0);
369        check_comparisons(DD::new(0, 0), DD::new(0, 40), 0, 0);
370
371        check_comparisons(DD::new(1, 40), DD::new(1, 0), 0, 1);
372        check_comparisons(DD::new(1, 40), DD::new(-1, 0), 1, 0);
373        check_comparisons(DD::new(-1, 40), DD::new(1, 0), 0, 1);
374        check_comparisons(DD::new(-1, 40), DD::new(-1, 0), 1, 0);
375
376        check_comparisons(DD::new(1, 0), DD::new(1, 40), 1, 0);
377        check_comparisons(DD::new(1, 0), DD::new(-1, 40), 1, 0);
378        check_comparisons(DD::new(-1, 0), DD::new(1, 40), 0, 1);
379        check_comparisons(DD::new(-1, 0), DD::new(-1, 40), 0, 1);
380    }
381
382    #[test]
383    fn from_str() {
384        for (s, expect) in [
385            ("0", Ok("0")),
386            ("0.", Ok("0")),
387            (".0", Ok("0")),
388            ("-0", Ok("0")),
389            ("+0", Ok("0")),
390            ("--0", Err(ParseDecimalError::SyntaxError)),
391            ("-+0", Err(ParseDecimalError::SyntaxError)),
392            ("0x", Err(ParseDecimalError::SyntaxError)),
393            ("0e5x", Err(ParseDecimalError::SyntaxError)),
394            ("1.23", Ok("1.23")),
395            ("-1.23", Ok("-1.23")),
396            ("+1.23", Ok("1.23")),
397            ("99999999", Ok("99999999")),
398            ("999999999", Ok("999999999")),
399            ("999999999E-1", Ok("99999999.9")),
400            ("9999999999e-1", Ok("999999999.9")),
401            ("9999999999E-2", Ok("99999999.99")),
402            ("99999999999e-2", Ok("999999999.99")),
403            ("99999999999e-3", Ok("99999999.999")),
404            ("99999999991e-3", Ok("99999999.991")),
405            // This value overflows the range of `i128` as an integer, so it
406            // triggers the case where we stop accepting digits and simply
407            // adjust the exponent instead.
408            (
409                "111111111111111111111111111111111111111111e-34",
410                Ok("11111111.1111111111111111111111111111111"),
411            ),
412            // This value overflows the range of `i128` in the fraction, so it
413            // triggers the case where we stop accepting digits and simply
414            // adjust the exponent instead.
415            (
416                "1.23456788901234567890123456789012345678890123456",
417                Ok("1.23456788901234567890123456789012345678"),
418            ),
419            // This value positively overflows the exponent.
420            ("1e999999999999999", Err(ParseDecimalError::OutOfRange)),
421            // This value positively overflows the exponent but the value is 0.
422            ("0e999999999999999", Ok("0")),
423            // This value negatively overflows the exponent.
424            ("1e-999999999999999", Ok("0")),
425            // This value overflows the range of `i128` as an integer, which
426            // starts adjusting the exponent, and then it overflows the exponent
427            // with `e`.
428            (
429                "111111111111111111111111111111111111111111e2147483644",
430                Err(ParseDecimalError::OutOfRange),
431            ),
432            // This value adjusts the exponent downward, and then it negatively
433            // overflows the exponent with `e`.
434            (
435                ".1111111111111111111111111111111111111111e-2147483648",
436                Ok("0"),
437            ),
438            ("123e5", Ok("12300000")),
439            ("123E4", Ok("1230000")),
440            ("123e3", Ok("123000")),
441            ("123e2", Ok("12300")),
442            ("123e1", Ok("1230")),
443            ("123e0", Ok("123")),
444            ("123e-1", Ok("12.3")),
445            ("123e-2", Ok("1.23")),
446            (".123", Ok("0.123")),
447            (".124", Ok("0.124")),
448            (".125", Ok("0.125")),
449            (".126", Ok("0.126")),
450            (".133", Ok("0.133")),
451            (".134", Ok("0.134")),
452            (".135", Ok("0.135")),
453            (".136", Ok("0.136")),
454            ("1e38", Ok("100000000000000000000000000000000000000")),
455            ("1e39", Err(ParseDecimalError::OutOfRange)),
456            ("1e-255", Ok("0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001")),
457            ("1e-256", Ok("0")),
458        ] {
459            println!("{s}: {:?}", s.parse::<DynamicDecimal>());
460            assert_eq!(
461                s.parse::<DynamicDecimal>().map(|d| d.to_string()),
462                expect.map(|d| d.to_string())
463            );
464        }
465    }
466
467    #[test]
468    fn to_integer() {
469        for x in -9999..=9999 {
470            let f = DynamicDecimal::new(x, 1);
471            assert_eq!(i128::from(f), x / 10);
472            assert_eq!(i64::try_from(f).unwrap(), (x / 10) as i64);
473            assert_eq!(i32::try_from(f).unwrap(), (x / 10) as i32);
474            assert_eq!(i16::try_from(f).unwrap(), (x / 10) as i16);
475            assert_eq!(
476                i8::try_from(f).ok(),
477                (-1289..=1279).contains(&x).then_some((x / 10) as i8)
478            );
479            assert_eq!(
480                u128::try_from(f).ok(),
481                (x > -10).then_some((x / 10) as u128)
482            );
483            assert_eq!(u64::try_from(f).ok(), (x > -10).then_some((x / 10) as u64));
484            assert_eq!(u32::try_from(f).ok(), (x > -10).then_some((x / 10) as u32));
485            assert_eq!(u16::try_from(f).ok(), (x > -10).then_some((x / 10) as u16));
486            assert_eq!(
487                u8::try_from(f).ok(),
488                (-9..=2559).contains(&x).then_some((x / 10) as u8)
489            );
490        }
491
492        assert_eq!(i128::from(DynamicDecimal::new(1, 40)), 0);
493        assert_eq!(i128::from(DynamicDecimal::new(i128::MAX, 0)), i128::MAX);
494        assert_eq!(i64::try_from(DynamicDecimal::new(1, 40)), Ok(0));
495        assert_eq!(
496            i64::try_from(DynamicDecimal::new(i128::MAX, 0)),
497            Err(OutOfRange)
498        );
499        assert_eq!(
500            i64::try_from(DynamicDecimal::new(i128::MIN, 0)),
501            Err(OutOfRange)
502        );
503    }
504}