flow-lang-value 0.1.0

The Flow runtime value model: data values, their equality, order and text, and the operations std's built-in types declare.
Documentation
//! `Decimal`: every number with a finite decimal expansion (`data.md`,
//! *Decimal*).

use std::cmp::Ordering;
use std::fmt;

use num_bigint::BigInt;
use num_integer::Integer;
use num_traits::{One, Pow, Signed, Zero};

use crate::error::Fault;
use crate::int::Int;

/// How many significant digits a quotient with no finite expansion keeps.
pub const DIVISION_DIGITS: u32 = 34;

/// An exact decimal number.
///
/// A value is `coefficient × 10^exponent`, held **normalized**: a nonzero
/// coefficient is not a multiple of ten, and zero is `0 × 10^0`. That makes
/// the representation a function of the number, so `1.50` and `1.5` are one
/// value with one text and the derived equality and hash are the number's.
/// Zero has no sign, because a `BigInt` zero has none.
///
/// Addition, subtraction, multiplication and negation are exact. Division is
/// exact when the quotient has a finite expansion and is otherwise rounded to
/// [`DIVISION_DIGITS`] significant digits, half to even.
///
/// The exponent is a signed 64-bit integer. A result whose exponent would leave
/// that range is reported as [`Fault::Limit`]: the number exists, but this host
/// cannot represent its scale.
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct Decimal {
    coefficient: BigInt,
    exponent: i64,
}

impl Decimal {
    /// Returns the number `coefficient × 10^exponent`, normalized.
    ///
    /// Normalizing raises the exponent once per trailing zero stripped, and a
    /// number whose normalized exponent would pass `i64::MAX` is
    /// [`Fault::Limit`].
    pub fn new(coefficient: BigInt, exponent: i64) -> Result<Self, Fault> {
        if coefficient.is_zero() {
            return Ok(Decimal {
                coefficient,
                exponent: 0,
            });
        }
        let digits = coefficient.magnitude().to_string();
        let zeros = digits.len() - digits.trim_end_matches('0').len();
        let raised = i64::try_from(zeros)
            .ok()
            .and_then(|zeros| exponent.checked_add(zeros))
            .ok_or(Fault::Limit)?;
        // The power of ten divided out is no longer than the coefficient.
        let zeros = u64::try_from(zeros).expect("a count of digits fits 64 bits");
        Ok(Decimal {
            coefficient: coefficient / pow10(zeros),
            exponent: raised,
        })
    }

    /// Returns the number a decoded literal spells: ASCII digits with an
    /// optional leading `-`, then optionally `.` and at least one digit.
    ///
    /// This reads what `flow-ir` writes for a decimal literal; `+`, an
    /// exponent, separators and a bare point are refused.
    pub fn parse(spelling: &str) -> Option<Self> {
        let (whole, fraction) = spelling.split_once('.').unwrap_or((spelling, "0"));
        Int::parse(whole)?;
        if fraction.is_empty() || !fraction.bytes().all(|byte| byte.is_ascii_digit()) {
            return None;
        }
        let coefficient = Int::parse(&format!("{whole}{fraction}"))?.into_bigint();
        let exponent = i64::try_from(fraction.len()).ok()?;
        Decimal::new(coefficient, -exponent).ok()
    }

    /// Returns the coefficient of the normalized form.
    pub fn coefficient(&self) -> &BigInt {
        &self.coefficient
    }

    /// Returns the power of ten of the normalized form.
    pub fn exponent(&self) -> i64 {
        self.exponent
    }

    /// Returns whether this is zero.
    pub fn is_zero(&self) -> bool {
        self.coefficient.is_zero()
    }

    /// Returns `self + other`, exactly.
    ///
    /// The two are aligned to the lower exponent first, so the sum of numbers
    /// whose scales are far apart is written out in full, as exactness
    /// requires.
    pub fn add(&self, other: &Decimal) -> Result<Decimal, Fault> {
        // Zero is `0 × 10^0`, whatever the other number's scale: adding it
        // aligns nothing.
        if self.is_zero() {
            return Ok(other.clone());
        }
        if other.is_zero() {
            return Ok(self.clone());
        }
        let exponent = self.exponent.min(other.exponent);
        let left = &self.coefficient * pow10(self.exponent.abs_diff(exponent));
        let right = &other.coefficient * pow10(other.exponent.abs_diff(exponent));
        Decimal::new(left + right, exponent)
    }

    /// Returns `self - other`, exactly.
    pub fn sub(&self, other: &Decimal) -> Result<Decimal, Fault> {
        self.add(&other.neg())
    }

    /// Returns `-self`.
    #[must_use]
    pub fn neg(&self) -> Decimal {
        Decimal {
            coefficient: -&self.coefficient,
            exponent: self.exponent,
        }
    }

    /// Returns `self * other`, exactly.
    pub fn mul(&self, other: &Decimal) -> Result<Decimal, Fault> {
        let exponent = self
            .exponent
            .checked_add(other.exponent)
            .ok_or(Fault::Limit)?;
        Decimal::new(&self.coefficient * &other.coefficient, exponent)
    }

    /// Returns `self / divisor`.
    ///
    /// A quotient with a finite decimal expansion is exact. Any other is
    /// rounded to [`DIVISION_DIGITS`] significant digits, half to even. A
    /// quotient with no finite expansion is never exactly halfway between two
    /// such neighbours — a halfway point has a finite expansion — so rounding
    /// to nearest decides every case and the tie rule never has to choose.
    pub fn div(&self, divisor: &Decimal) -> Result<Decimal, Fault> {
        if divisor.is_zero() {
            return Err(Fault::DivisionByZero);
        }
        let negative = self.coefficient.is_negative() != divisor.coefficient.is_negative();
        let shared = self.coefficient.gcd(&divisor.coefficient);
        let numerator = self.coefficient.abs() / &shared;
        let denominator = divisor.coefficient.abs() / &shared;
        let exponent = self
            .exponent
            .checked_sub(divisor.exponent)
            .ok_or(Fault::Limit)?;

        let (twos, fives, rest) = twos_and_fives(&denominator);
        let (magnitude, exponent) = if rest.is_one() {
            // `denominator` is 2^twos * 5^fives, so 10^k / denominator is
            // whole for k = max(twos, fives).
            let k = twos.max(fives);
            let factor = pow10(k) / &denominator;
            let shifted = exponent
                .checked_sub(i64::try_from(k).map_err(|_| Fault::Limit)?)
                .ok_or(Fault::Limit)?;
            (numerator * factor, shifted)
        } else {
            rounded_quotient(&numerator, &denominator, exponent)?
        };
        let signed = if negative { -magnitude } else { magnitude };
        Decimal::new(signed, exponent)
    }

    /// Returns the greatest integer not above this number.
    pub fn floor(&self) -> Int {
        if self.adjusted_exponent() <= 0 {
            // Every digit is after the point, so the magnitude is below one.
            // Answering here also keeps a tiny number such as `0.1` raised to a
            // high power from building a power of ten as long as its exponent.
            return Int::from(if self.coefficient.is_negative() {
                BigInt::from(-1)
            } else {
                BigInt::zero()
            });
        }
        let up = pow10(self.exponent.max(0).unsigned_abs());
        let down = pow10(self.exponent.min(0).unsigned_abs());
        Int::from((&self.coefficient * up).div_floor(&down))
    }

    /// Returns [`Decimal::floor`] when its magnitude takes at most `max_bits`
    /// bits, and `None` otherwise.
    ///
    /// A number with `d` digits before the point has a floor of at least
    /// `10^(d-1)`, which takes more than `d - 1` bits, so a number too large
    /// is refused before its floor is built: a huge exponent costs nothing.
    pub fn floor_within(&self, max_bits: u64) -> Option<Int> {
        if self.adjusted_exponent() > i128::from(max_bits) {
            return None;
        }
        let floor = self.floor();
        (floor.bits() <= max_bits).then_some(floor)
    }

    /// Returns how many bytes this number's text takes, without writing it:
    /// a number with a vast exponent has a text far too long to build.
    pub fn text_len(&self) -> u128 {
        let digits = u128::from(digit_count(&self.coefficient));
        let places = u128::from(self.exponent.unsigned_abs());
        let plain = if self.exponent >= 0 {
            digits + places
        } else if digits > places {
            // The digits with a point among them.
            digits + 1
        } else {
            // `0.`, zeros, and the digits.
            places + 2
        };
        plain + u128::from(self.coefficient.is_negative())
    }

    /// The power of ten of this number's leading digit.
    fn adjusted_exponent(&self) -> i128 {
        i128::from(self.exponent) + i128::from(digit_count(&self.coefficient))
    }
}

impl From<&Int> for Decimal {
    fn from(value: &Int) -> Self {
        Decimal::new(value.as_bigint().clone(), 0)
            .expect("an integer has fewer trailing zeros than an exponent can count")
    }
}

/// Numbers by value (`data.md`).
impl Ord for Decimal {
    fn cmp(&self, other: &Self) -> Ordering {
        let by_sign = self.coefficient.sign().cmp(&other.coefficient.sign());
        if by_sign != Ordering::Equal {
            return by_sign;
        }
        // Same sign. The leading digit's place decides unless it is shared;
        // then the digits, read from the leading one, are aligned, and since
        // neither coefficient ends in a zero, the one that is a proper prefix
        // of the other is the smaller. No power of ten is built, however far
        // apart the two exponents are.
        let magnitude = self
            .adjusted_exponent()
            .cmp(&other.adjusted_exponent())
            .then_with(|| {
                let left = self.coefficient.magnitude().to_string();
                left.cmp(&other.coefficient.magnitude().to_string())
            });
        if self.coefficient.is_negative() {
            magnitude.reverse()
        } else {
            magnitude
        }
    }
}

impl PartialOrd for Decimal {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

/// The text form: plain decimal notation with no exponent, no trailing zero
/// after the point, no point when the number is whole, `-` before a negative
/// number and `0` for zero (`data.md`, *Decimal*).
impl fmt::Display for Decimal {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let sign = if self.coefficient.is_negative() {
            "-"
        } else {
            ""
        };
        let digits = self.coefficient.magnitude().to_string();
        let Ok(places) = usize::try_from(-self.exponent) else {
            // A non-negative exponent: the number is whole.
            let zeros = "0".repeat(usize::try_from(self.exponent).unwrap_or(usize::MAX));
            return write!(f, "{sign}{digits}{zeros}");
        };
        if places >= digits.len() {
            let zeros = "0".repeat(places - digits.len());
            write!(f, "{sign}0.{zeros}{digits}")
        } else {
            let (whole, fraction) = digits.split_at(digits.len() - places);
            if fraction.is_empty() {
                write!(f, "{sign}{whole}")
            } else {
                write!(f, "{sign}{whole}.{fraction}")
            }
        }
    }
}

impl fmt::Debug for Decimal {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(self, f)
    }
}

/// Returns `10^places`.
///
/// Every caller asks for a power no longer than a number it already holds or
/// the result it must produce, so building it costs no more than the answer.
fn pow10(places: u64) -> BigInt {
    Pow::pow(BigInt::from(10), places)
}

/// Returns how many decimal digits `value`'s magnitude has; zero has one.
fn digit_count(value: &BigInt) -> u64 {
    u64::try_from(value.magnitude().to_string().len()).unwrap_or(u64::MAX)
}

/// Splits a positive `value` into `2^twos × 5^fives × rest`.
fn twos_and_fives(value: &BigInt) -> (u64, u64, BigInt) {
    let mut rest = value.clone();
    let twos = rest.trailing_zeros().unwrap_or(0);
    rest >>= twos;
    let five = BigInt::from(5);
    let mut fives = 0;
    // A number has fewer factors of five than bits, which bounds the search
    // even for an argument it was never meant to see, such as zero.
    for _ in 0..value.bits() {
        let (quotient, remainder) = rest.div_rem(&five);
        if !remainder.is_zero() {
            break;
        }
        rest = quotient;
        fives += 1;
    }
    (twos, fives, rest)
}

/// Returns `numerator / denominator × 10^exponent` rounded to
/// [`DIVISION_DIGITS`] significant digits, as a magnitude and an exponent.
///
/// Both operands are positive, and the quotient has no finite expansion.
fn rounded_quotient(
    numerator: &BigInt,
    denominator: &BigInt,
    exponent: i64,
) -> Result<(BigInt, i64), Fault> {
    let digits = i64::from(DIVISION_DIGITS);
    let low = pow10(u64::from(DIVISION_DIGITS));
    // A shift `s` with 10^34 ≤ ⌊numerator × 10^s / denominator⌋ < 10^35,
    // that is one guard digit past the 34 kept. The first guess lands within
    // one place below it.
    let mut shift = digits + digits_i64(denominator) - digits_i64(numerator);
    let mut guarded = shifted_quotient(numerator, denominator, shift);
    if guarded < low {
        shift += 1;
        guarded = shifted_quotient(numerator, denominator, shift);
    }
    // The guard digit rounds: five or more goes up. Exactly five with nothing
    // after it would be a tie, which a quotient with no finite expansion never
    // is, so nothing after it is ever zero.
    let rounded = (guarded + 5) / 10;
    let exponent = exponent.checked_sub(shift - 1).ok_or(Fault::Limit)?;
    Ok((rounded, exponent))
}

/// Returns `⌊numerator × 10^shift / denominator⌋` for a shift of either sign.
fn shifted_quotient(numerator: &BigInt, denominator: &BigInt, shift: i64) -> BigInt {
    let places = shift.unsigned_abs();
    if shift >= 0 {
        (numerator * pow10(places)) / denominator
    } else {
        numerator / (denominator * pow10(places))
    }
}

fn digits_i64(value: &BigInt) -> i64 {
    i64::try_from(digit_count(value)).unwrap_or(i64::MAX)
}