Skip to main content

flow_value/
decimal.rs

1//! `Decimal`: every number with a finite decimal expansion (`data.md`,
2//! *Decimal*).
3
4use std::cmp::Ordering;
5use std::fmt;
6
7use num_bigint::BigInt;
8use num_integer::Integer;
9use num_traits::{One, Pow, Signed, ToPrimitive, Zero};
10
11use crate::error::Fault;
12use crate::int::Int;
13
14/// How many significant digits a quotient with no finite expansion keeps.
15pub const DIVISION_DIGITS: u32 = 34;
16
17/// An exact decimal number.
18///
19/// A value is `coefficient × 10^exponent`, held **normalized**: a nonzero
20/// coefficient is not a multiple of ten, and zero is `0 × 10^0`. That makes
21/// the representation a function of the number, so `1.50` and `1.5` are one
22/// value with one text and the derived equality and hash are the number's.
23/// Zero has no sign, because a `BigInt` zero has none.
24///
25/// Addition, subtraction, multiplication and negation are exact. Division is
26/// exact when the quotient has a finite expansion and is otherwise rounded to
27/// [`DIVISION_DIGITS`] significant digits, half to even.
28///
29/// The exponent is a signed 64-bit integer. A result whose exponent would leave
30/// that range is reported as [`Fault::Limit`]: the number exists, but this host
31/// cannot represent its scale.
32#[derive(Clone, PartialEq, Eq, Hash)]
33pub struct Decimal {
34    coefficient: BigInt,
35    exponent: i64,
36}
37
38impl Decimal {
39    /// Returns the number `coefficient × 10^exponent`, normalized.
40    ///
41    /// Normalizing raises the exponent once per trailing zero stripped, and a
42    /// number whose normalized exponent would pass `i64::MAX` is
43    /// [`Fault::Limit`].
44    ///
45    /// # Errors
46    ///
47    /// [`Fault::Limit`] when the normalized exponent would pass `i64::MAX`.
48    pub fn new(coefficient: BigInt, exponent: i64) -> Result<Self, Fault> {
49        if coefficient.is_zero() {
50            return Ok(Decimal {
51                coefficient,
52                exponent: 0,
53            });
54        }
55        let (coefficient, zeros) = strip_zeros(coefficient);
56        let raised = i64::try_from(zeros)
57            .ok()
58            .and_then(|zeros| exponent.checked_add(zeros))
59            .ok_or(Fault::Limit)?;
60        Ok(Decimal {
61            coefficient,
62            exponent: raised,
63        })
64    }
65
66    /// Returns the number a decoded literal spells: ASCII digits with an
67    /// optional leading `-`, then optionally `.` and at least one digit.
68    ///
69    /// This reads what `flow-ir` writes for a decimal literal; `+`, an
70    /// exponent, separators and a bare point are refused.
71    pub fn parse(spelling: &str) -> Option<Self> {
72        let (whole, fraction) = spelling.split_once('.').unwrap_or((spelling, "0"));
73        Int::parse(whole)?;
74        if fraction.is_empty() || !fraction.bytes().all(|byte| byte.is_ascii_digit()) {
75            return None;
76        }
77        let coefficient = Int::parse(&format!("{whole}{fraction}"))?.into_bigint();
78        let exponent = i64::try_from(fraction.len()).ok()?;
79        Decimal::new(coefficient, -exponent).ok()
80    }
81
82    /// Returns the coefficient of the normalized form.
83    pub fn coefficient(&self) -> &BigInt {
84        &self.coefficient
85    }
86
87    /// Returns the power of ten of the normalized form.
88    pub fn exponent(&self) -> i64 {
89        self.exponent
90    }
91
92    /// Returns whether this is zero.
93    pub fn is_zero(&self) -> bool {
94        self.coefficient.is_zero()
95    }
96
97    /// Returns `self + other`, exactly.
98    ///
99    /// The two are aligned to the lower exponent first, so the sum of numbers
100    /// whose scales are far apart is written out in full, as exactness
101    /// requires.
102    ///
103    /// # Errors
104    ///
105    /// [`Fault::Limit`] when the result's exponent would leave the `i64` range.
106    pub fn add(&self, other: &Decimal) -> Result<Decimal, Fault> {
107        // Zero is `0 × 10^0`, whatever the other number's scale: adding it
108        // aligns nothing.
109        if self.is_zero() {
110            return Ok(other.clone());
111        }
112        if other.is_zero() {
113            return Ok(self.clone());
114        }
115        let exponent = self.exponent.min(other.exponent);
116        let left = &self.coefficient * pow10(self.exponent.abs_diff(exponent));
117        let right = &other.coefficient * pow10(other.exponent.abs_diff(exponent));
118        Decimal::new(left + right, exponent)
119    }
120
121    /// Returns `self - other`, exactly.
122    ///
123    /// # Errors
124    ///
125    /// [`Fault::Limit`] when the result's exponent would leave the `i64` range.
126    pub fn sub(&self, other: &Decimal) -> Result<Decimal, Fault> {
127        self.add(&other.neg())
128    }
129
130    /// Returns `-self`.
131    #[must_use]
132    pub fn neg(&self) -> Decimal {
133        Decimal {
134            coefficient: -&self.coefficient,
135            exponent: self.exponent,
136        }
137    }
138
139    /// Returns `self * other`, exactly.
140    ///
141    /// # Errors
142    ///
143    /// [`Fault::Limit`] when the result's exponent would leave the `i64` range.
144    pub fn mul(&self, other: &Decimal) -> Result<Decimal, Fault> {
145        let exponent = self
146            .exponent
147            .checked_add(other.exponent)
148            .ok_or(Fault::Limit)?;
149        Decimal::new(&self.coefficient * &other.coefficient, exponent)
150    }
151
152    /// Returns `self / divisor`.
153    ///
154    /// A quotient with a finite decimal expansion is exact. Any other is
155    /// rounded to [`DIVISION_DIGITS`] significant digits, half to even. A
156    /// quotient with no finite expansion is never exactly halfway between two
157    /// such neighbours — a halfway point has a finite expansion — so rounding
158    /// to nearest decides every case and the tie rule never has to choose.
159    ///
160    /// # Errors
161    ///
162    /// [`Fault::DivisionByZero`] for a zero divisor, and [`Fault::Limit`] when
163    /// the quotient's exponent would leave the `i64` range.
164    pub fn div(&self, divisor: &Decimal) -> Result<Decimal, Fault> {
165        if divisor.is_zero() {
166            return Err(Fault::DivisionByZero);
167        }
168        let negative = self.coefficient.is_negative() != divisor.coefficient.is_negative();
169        let shared = self.coefficient.gcd(&divisor.coefficient);
170        let numerator = self.coefficient.abs() / &shared;
171        let denominator = divisor.coefficient.abs() / &shared;
172        let exponent = self
173            .exponent
174            .checked_sub(divisor.exponent)
175            .ok_or(Fault::Limit)?;
176
177        let (twos, fives, rest) = twos_and_fives(&denominator);
178        let (magnitude, exponent) = if rest.is_one() {
179            // `denominator` is 2^twos * 5^fives, so 10^k / denominator is
180            // whole for k = max(twos, fives).
181            let k = twos.max(fives);
182            let factor = pow10(k) / &denominator;
183            let shifted = exponent
184                .checked_sub(i64::try_from(k).map_err(|_| Fault::Limit)?)
185                .ok_or(Fault::Limit)?;
186            (numerator * factor, shifted)
187        } else {
188            rounded_quotient(&numerator, &denominator, exponent)?
189        };
190        let signed = if negative { -magnitude } else { magnitude };
191        Decimal::new(signed, exponent)
192    }
193
194    /// Returns the greatest integer not above this number.
195    pub fn floor(&self) -> Int {
196        if self.adjusted_exponent() <= 0 {
197            // Every digit is after the point, so the magnitude is below one.
198            // Answering here also keeps a tiny number such as `0.1` raised to a
199            // high power from building a power of ten as long as its exponent.
200            return Int::from(if self.coefficient.is_negative() {
201                BigInt::from(-1)
202            } else {
203                BigInt::zero()
204            });
205        }
206        let up = pow10(self.exponent.max(0).unsigned_abs());
207        let down = pow10(self.exponent.min(0).unsigned_abs());
208        Int::from((&self.coefficient * up).div_floor(&down))
209    }
210
211    /// Returns [`Decimal::floor`] when its magnitude takes at most `max_bits`
212    /// bits, and `None` otherwise.
213    ///
214    /// A number with `d` digits before the point has a floor of at least
215    /// `10^(d-1)`, which takes more than `d - 1` bits, so a number too large
216    /// is refused before its floor is built: a huge exponent costs nothing.
217    pub fn floor_within(&self, max_bits: u64) -> Option<Int> {
218        if self.adjusted_exponent() > i128::from(max_bits) {
219            return None;
220        }
221        let floor = self.floor();
222        (floor.bits() <= max_bits).then_some(floor)
223    }
224
225    /// Returns how many bytes this number's text takes, without writing it:
226    /// a number with a vast exponent has a text far too long to build.
227    pub fn text_len(&self) -> u128 {
228        let digits = u128::from(digit_count(&self.coefficient));
229        let places = u128::from(self.exponent.unsigned_abs());
230        let plain = if self.exponent >= 0 {
231            digits + places
232        } else if digits > places {
233            // The digits with a point among them.
234            digits + 1
235        } else {
236            // `0.`, zeros, and the digits.
237            places + 2
238        };
239        plain + u128::from(self.coefficient.is_negative())
240    }
241
242    /// The power of ten of this number's leading digit.
243    fn adjusted_exponent(&self) -> i128 {
244        i128::from(self.exponent) + i128::from(digit_count(&self.coefficient))
245    }
246}
247
248impl From<&Int> for Decimal {
249    fn from(value: &Int) -> Self {
250        Decimal::new(value.as_bigint().clone(), 0)
251            .expect("an integer has fewer trailing zeros than an exponent can count")
252    }
253}
254
255/// Numbers by value (`data.md`).
256impl Ord for Decimal {
257    fn cmp(&self, other: &Self) -> Ordering {
258        let by_sign = self.coefficient.sign().cmp(&other.coefficient.sign());
259        if by_sign != Ordering::Equal {
260            return by_sign;
261        }
262        // Same sign. The leading digit's place decides unless it is shared;
263        // then the two magnitudes are aligned and compared. Sharing the
264        // leading digit's place puts the exponents no further apart than
265        // the longer coefficient has digits, so the power of ten that aligns
266        // them is no longer than a number already held, however far apart
267        // the exponents of two numbers of different places are.
268        let magnitude = self
269            .adjusted_exponent()
270            .cmp(&other.adjusted_exponent())
271            .then_with(|| {
272                let (left, right) = (self.coefficient.magnitude(), other.coefficient.magnitude());
273                let shift = pow10(self.exponent.abs_diff(other.exponent)).into_parts().1;
274                if self.exponent > other.exponent {
275                    (left * shift).cmp(right)
276                } else {
277                    left.cmp(&(right * shift))
278                }
279            });
280        if self.coefficient.is_negative() {
281            magnitude.reverse()
282        } else {
283            magnitude
284        }
285    }
286}
287
288impl PartialOrd for Decimal {
289    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
290        Some(self.cmp(other))
291    }
292}
293
294/// The text form: plain decimal notation with no exponent, no trailing zero
295/// after the point, no point when the number is whole, `-` before a negative
296/// number and `0` for zero (`data.md`, *Decimal*).
297impl fmt::Display for Decimal {
298    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
299        let sign = if self.coefficient.is_negative() {
300            "-"
301        } else {
302            ""
303        };
304        let digits = self.coefficient.magnitude().to_string();
305        let Ok(places) = usize::try_from(-self.exponent) else {
306            // A non-negative exponent: the number is whole.
307            let zeros = "0".repeat(usize::try_from(self.exponent).unwrap_or(usize::MAX));
308            return write!(f, "{sign}{digits}{zeros}");
309        };
310        if places >= digits.len() {
311            let zeros = "0".repeat(places - digits.len());
312            write!(f, "{sign}0.{zeros}{digits}")
313        } else {
314            let (whole, fraction) = digits.split_at(digits.len() - places);
315            if fraction.is_empty() {
316                write!(f, "{sign}{whole}")
317            } else {
318                write!(f, "{sign}{whole}.{fraction}")
319            }
320        }
321    }
322}
323
324impl fmt::Debug for Decimal {
325    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
326        fmt::Display::fmt(self, f)
327    }
328}
329
330/// Returns `10^places`.
331///
332/// Every caller asks for a power no longer than a number it already holds or
333/// the result it must produce, so building it costs no more than the answer.
334fn pow10(places: u64) -> BigInt {
335    Pow::pow(BigInt::from(10), places)
336}
337
338/// Returns how many decimal digits `value`'s magnitude has; zero has one.
339///
340/// No text is written: a magnitude of `b` bits has at least
341/// `⌊(b - 1) · log10 2⌋ + 1` digits, and at most two more, which comparing
342/// with powers of ten settles.
343fn digit_count(value: &BigInt) -> u64 {
344    let magnitude = value.magnitude();
345    if let Some(small) = magnitude.to_u64() {
346        return small
347            .checked_ilog10()
348            .map_or(1, |below| u64::from(below) + 1);
349    }
350    // log10 2 = 0.301029995663981195..., rounded down, so the estimate is
351    // never above the true count: `10^(digits - 1) ≤ 2^(bits - 1) ≤ magnitude`.
352    let bits = u128::from(magnitude.bits());
353    let estimate = (bits - 1) * 301_029_995_663_981 / 1_000_000_000_000_000;
354    let mut digits = u64::try_from(estimate).expect("a third of a bit count fits 64 bits") + 1;
355    let mut next = pow10(digits);
356    while magnitude >= next.magnitude() {
357        digits += 1;
358        next *= 10;
359    }
360    digits
361}
362
363/// Returns `coefficient` with its trailing decimal zeros divided out, and how
364/// many there were. A nonzero number has no more of them than factors of
365/// two, so an odd one, the common case, is answered at once.
366fn strip_zeros(coefficient: BigInt) -> (BigInt, u64) {
367    let twos = coefficient.trailing_zeros().unwrap_or(0);
368    let mut rest = coefficient;
369    let mut zeros = 0;
370    // Nineteen zeros at a time, then one at a time.
371    for (step, power) in [(19, 10_000_000_000_000_000_000_u64), (1, 10)] {
372        while twos - zeros >= step {
373            let (quotient, remainder) = rest.div_rem(&BigInt::from(power));
374            if !remainder.is_zero() {
375                break;
376            }
377            rest = quotient;
378            zeros += step;
379        }
380    }
381    (rest, zeros)
382}
383
384/// Splits a positive `value` into `2^twos × 5^fives × rest`.
385fn twos_and_fives(value: &BigInt) -> (u64, u64, BigInt) {
386    let mut rest = value.clone();
387    let twos = rest.trailing_zeros().unwrap_or(0);
388    rest >>= twos;
389    let five = BigInt::from(5);
390    let mut fives = 0;
391    // A number has fewer factors of five than bits, which bounds the search
392    // even for an argument it was never meant to see, such as zero.
393    for _ in 0..value.bits() {
394        let (quotient, remainder) = rest.div_rem(&five);
395        if !remainder.is_zero() {
396            break;
397        }
398        rest = quotient;
399        fives += 1;
400    }
401    (twos, fives, rest)
402}
403
404/// Returns `numerator / denominator × 10^exponent` rounded to
405/// [`DIVISION_DIGITS`] significant digits, as a magnitude and an exponent.
406///
407/// Both operands are positive, and the quotient has no finite expansion.
408fn rounded_quotient(
409    numerator: &BigInt,
410    denominator: &BigInt,
411    exponent: i64,
412) -> Result<(BigInt, i64), Fault> {
413    let digits = i64::from(DIVISION_DIGITS);
414    let low = pow10(u64::from(DIVISION_DIGITS));
415    // A shift `s` with 10^34 ≤ ⌊numerator × 10^s / denominator⌋ < 10^35,
416    // that is one guard digit past the 34 kept. The first guess lands within
417    // one place below it.
418    let mut shift = digits + digits_i64(denominator) - digits_i64(numerator);
419    let mut guarded = shifted_quotient(numerator, denominator, shift);
420    if guarded < low {
421        shift += 1;
422        guarded = shifted_quotient(numerator, denominator, shift);
423    }
424    // The guard digit rounds: five or more goes up. Exactly five with nothing
425    // after it would be a tie, which a quotient with no finite expansion never
426    // is, so nothing after it is ever zero.
427    let rounded = (guarded + 5) / 10;
428    let exponent = exponent.checked_sub(shift - 1).ok_or(Fault::Limit)?;
429    Ok((rounded, exponent))
430}
431
432/// Returns `⌊numerator × 10^shift / denominator⌋` for a shift of either sign.
433fn shifted_quotient(numerator: &BigInt, denominator: &BigInt, shift: i64) -> BigInt {
434    let places = shift.unsigned_abs();
435    if shift >= 0 {
436        (numerator * pow10(places)) / denominator
437    } else {
438        numerator / (denominator * pow10(places))
439    }
440}
441
442fn digits_i64(value: &BigInt) -> i64 {
443    i64::try_from(digit_count(value)).unwrap_or(i64::MAX)
444}