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