//! `Dec` (`std/dec`, ADR 0070): a 128-bit fixed-point decimal, an `i128` //! counting units of 10^-18 (18 places, an integral part up to about //! ±1.7·10^20 — Roc's choice). The fixed scale is the canonicalization //! rule: every value has exactly one `i128`, so equality, comparison and //! the hash read the raw integer, and there is no negative zero. //! //! Every inexact operation rounds to the nearest, ties to even //! (`div_round_half_even`): `*` and `/`, `parse` past 18 places, //! `from_float` and `round`. Operators panic on overflow (the backends //! turn `None` into the panic); conversions report it as a value. use num_bigint::{BigInt, Sign}; use num_traits::{Signed, ToPrimitive}; use crate::{hash_limbs, mix}; /// The decimal places of a `Dec`, and its scale: `10^DEC_PLACES`. pub const DEC_PLACES: u32 = 18; pub const DEC_SCALE: i128 = 1_000_000_000_000_000_000; pub const DEC_DIVISION_BY_ZERO: &str = "dec.div: division by zero"; pub const DEC_REMAINDER_BY_ZERO: &str = "dec.rem: division by zero"; /// The panic of an overflowing `dec` operation (`op` is `add`, `mul`, ...). pub fn dec_overflow(op: &str) -> String { format!("dec.{op}: overflow") } /// The panic of `dec.round` with `places` outside `0..=DEC_PLACES`. pub fn dec_bad_places(places: &str) -> String { format!("dec.round: places must be in 0..={DEC_PLACES}, got {places}") } /// `n / d` (truncating), with the remainder rounded to the nearest /// quotient, ties to even. `d` must be positive; the rounding is /// sign-symmetric, so a negative `n` rounds away from zero on a tie only /// when the truncated quotient is odd. fn div_round_half_even(n: &BigInt, d: &BigInt) -> BigInt { debug_assert!(d.sign() == Sign::Plus); // `/` and `%` on BigInt truncate toward zero, as div_rem does. let (q, r) = (n / d, n % d); let up = match (r.abs() << 1u32).cmp(d) { std::cmp::Ordering::Less => false, std::cmp::Ordering::Greater => true, // A tie rounds to an even quotient. std::cmp::Ordering::Equal => q.bit(0), }; if up { q + if n.sign() == Sign::Minus { -1 } else { 1 } } else { q } } pub fn dec_add(a: i128, b: i128) -> Option { a.checked_add(b) } pub fn dec_sub(a: i128, b: i128) -> Option { a.checked_sub(b) } pub fn dec_neg(a: i128) -> Option { a.checked_neg() } /// `a * b`, rounded; `None` on overflow. The exact product has up to 36 /// places, so it is computed as a big integer and halved back into range /// by the division. pub fn dec_mul(a: i128, b: i128) -> Option { let n = BigInt::from(a) * BigInt::from(b); div_round_half_even(&n, &BigInt::from(DEC_SCALE)).to_i128() } /// `a / b`, rounded; `None` on overflow, and on `b == 0` (the caller /// reports division by zero first, with [`DEC_DIVISION_BY_ZERO`]). pub fn dec_div(a: i128, b: i128) -> Option { if b == 0 { return None; } let n = BigInt::from(a) * BigInt::from(DEC_SCALE); div_round_half_even(&n, &BigInt::from(b)).to_i128() } /// The remainder of a truncating division (`a - (a / b) * b`, exact: /// the scales cancel); `None` on `b == 0` (the caller reports it). pub fn dec_rem(a: i128, b: i128) -> Option { a.checked_rem(b) } /// `n` units of 1 as a `Dec` (`n * 10^18`); `None` when out of range. pub fn dec_from_int(n: &BigInt) -> Option { (n * DEC_SCALE).to_i128() } /// The whole units of `v`, truncated toward zero. pub fn dec_to_int(v: i128) -> i128 { v / DEC_SCALE } /// The raw count of 10^-18 units `n` as a `Dec`: `n` itself, when it /// fits in 128 bits. pub fn dec_from_scaled(n: &BigInt) -> Option { n.to_i128() } /// The `Dec` written in `s`: an optional sign, decimal digits, an /// optional point and more digits (`"1"`, `"1.20"`, `".5"`, `"1."`; no /// exponent). More than 18 fractional digits round half-even. `None` /// when `s` is not such a text or the value is out of range. `"-0"` and /// its forms are `0` (there is no negative zero). pub fn dec_parse(s: &str) -> Option { let (neg, t) = match s.strip_prefix('-') { Some(t) => (true, t), None => (false, s.strip_prefix('+').unwrap_or(s)), }; let (int_part, frac) = t.split_once('.').unwrap_or((t, "")); if int_part.is_empty() && frac.is_empty() { return None; } if !int_part.bytes().all(|b| b.is_ascii_digit()) || !frac.bytes().all(|b| b.is_ascii_digit()) { return None; } let integral: u128 = match int_part { "" => 0, digits => digits.parse().ok()?, }; // The first 18 fractional digits, right-padded to 18 places. let mut kept: u128 = 0; for (i, b) in frac.bytes().enumerate() { if i < DEC_PLACES as usize { kept = kept * 10 + u128::from(b - b'0'); } } kept *= 10u128.pow(DEC_PLACES - frac.len().min(DEC_PLACES as usize) as u32); // The dropped digits round the kept ones, half-even (a carry into the // integral part is the checked_add below). let dropped = &frac.as_bytes()[frac.len().min(DEC_PLACES as usize)..]; if let Some((first, rest)) = dropped.split_first() { let up = *first > b'5' || (*first == b'5' && (rest.iter().any(|b| *b != b'0') || kept % 2 == 1)); if up { kept += 1; } } // The magnitude is unsigned, so the minimum stays representable // (-2^127/10^18 is a Dec; its magnitude is not an i128). let v = integral.checked_mul(DEC_SCALE as u128)?.checked_add(kept)?; if neg { if v > (i128::MAX as u128) + 1 { return None; } Some((v as i128).wrapping_neg()) } else { i128::try_from(v).ok() } } /// `v` in decimal: the integral part, then the fractional digits with /// trailing zeros trimmed; an integral value has no point (`1.20` shows /// as `"1.2"`, `42` as `"42"`). pub fn dec_show(v: i128) -> String { let sign = if v < 0 { "-" } else { "" }; let a = v.unsigned_abs(); let s = DEC_SCALE as u128; let (integral, frac) = (a / s, a % s); if frac == 0 { return format!("{sign}{integral}"); } let mut digits = format!("{frac:018}"); while digits.ends_with('0') { digits.pop(); } format!("{sign}{integral}.{digits}") } /// `v` rounded to `places` decimal places, half-even; `None` when /// `places > DEC_PLACES` (the caller checks the range first, with /// [`dec_bad_places`]) or the rounded value overflows. pub fn dec_round(v: i128, places: u32) -> Option { if places > DEC_PLACES { return None; } let quantum = 10i128.pow(DEC_PLACES - places); let r = v % quantum; // the sign of v let base = v - r; let up = match (r.unsigned_abs() * 2).cmp(&(quantum as u128)) { std::cmp::Ordering::Less => false, std::cmp::Ordering::Greater => true, std::cmp::Ordering::Equal => (base / quantum) % 2 != 0, }; if up { base.checked_add(if v < 0 { -quantum } else { quantum }) } else { Some(base) } } /// The nearest `Dec` to `f`, through its shortest decimal text (`0.1` /// the float is `"0.1"` the string is `0.1` the `Dec` — not the binary /// expansion). `None` for NaN, an infinity, or a float out of range. pub fn dec_from_f64(f: f64) -> Option { if !f.is_finite() { return None; } // Display for f64 is the shortest round-trip decimal, never in // scientific notation, so `dec_parse` reads it. dec_parse(&format!("{f}")) } /// The nearest double to `v` (`dec_show` is exact; the parse is /// correctly rounded). pub fn dec_to_f64(v: i128) -> f64 { dec_show(v) .parse() .expect("louise: dec_show's output is a float") } /// The `Dec`'s hash: the big-integer scheme over its two limbs, so both /// backends agree (pinned in the tests below). pub fn dec_hash(v: i128) -> i64 { mix(hash_limbs(v < 0, &[v as u64, (v >> 64) as u64])) } #[cfg(test)] mod tests { use super::*; fn dec(s: &str) -> i128 { dec_parse(s).unwrap_or_else(|| panic!("a decimal: {s:?}")) } #[test] fn parse_and_show_round_trip() { for (text, shown) in [ ("0", "0"), ("-0", "0"), ("1", "1"), ("-1", "-1"), ("1.20", "1.2"), ("0.1", "0.1"), ("-0.5", "-0.5"), ("+42", "42"), (".5", "0.5"), ("1.", "1"), ("0.000000000000000001", "0.000000000000000001"), ( "170141183460469231731.687303715884105727", "170141183460469231731.687303715884105727", ), ] { assert_eq!(dec_show(dec(text)), shown, "{text:?}"); assert_eq!(dec(text), dec(shown)); } } #[test] fn parse_rounds_half_even_past_18_places() { // Ties: to the even last kept digit. assert_eq!(dec_parse("0.0000000000000000005"), Some(0)); assert_eq!(dec_parse("0.0000000000000000015"), Some(2)); assert_eq!(dec_parse("0.0000000000000000025"), Some(2)); assert_eq!(dec_parse("-0.0000000000000000015"), Some(-2)); // Not ties. assert_eq!(dec_parse("0.00000000000000000050001"), Some(1)); assert_eq!(dec_parse("0.00000000000000000049999"), Some(0)); // A carry into the integral part. assert_eq!(dec_parse("0.9999999999999999995"), Some(DEC_SCALE)); assert_eq!(dec_show(dec("0.9999999999999999995")), "1"); } #[test] fn parse_refuses_non_decimals_and_overflow() { for bad in ["", ".", "-", "abc", "1.2.3", "1e3", "0x10", "NaN", "1,5"] { assert_eq!(dec_parse(bad), None, "{bad:?}"); } assert_eq!(dec_parse("170141183460469231732"), None); assert_eq!(dec_parse("-170141183460469231732"), None); // One quantum past the maximum. assert_eq!(dec_parse("170141183460469231731.687303715884105728"), None); assert_eq!( dec_parse("-170141183460469231731.687303715884105728"), Some(i128::MIN) ); } #[test] fn arithmetic_rounds_half_even() { // 0.335 * 0.5 = 0.1675 → 0.1675 (exact); 1/3 and 2/3 round. assert_eq!(dec_mul(dec("0.335"), dec("0.5")), Some(dec("0.1675"))); assert_eq!( dec_show(dec_div(dec("1"), dec("3")).unwrap()), "0.333333333333333333" ); assert_eq!( dec_show(dec_div(dec("2"), dec("3")).unwrap()), "0.666666666666666667" ); // A tie at the last place: 0.000000000000000001 * 1.5. assert_eq!(dec_mul(1, dec("1.5")), Some(2)); // 1.5e-18 → 2e-18 (even) assert_eq!(dec_mul(3, dec("0.5")), Some(2)); // 1.5e-18 → 2e-18 (even) assert_eq!(dec_mul(5, dec("0.5")), Some(2)); // 2.5e-18 → 2e-18 (even) // Division by zero and overflow are None (the callers panic). assert_eq!(dec_div(dec("1"), 0), None); assert_eq!(dec_rem(dec("7"), dec("2")), Some(dec("1"))); assert_eq!(dec_rem(dec("7.5"), dec("2")), Some(dec("1.5"))); assert_eq!(dec_rem(dec("-7"), dec("2")), Some(dec("-1"))); assert_eq!(dec_rem(dec("7"), 0), None); assert_eq!(dec_mul(i128::MAX, i128::MAX), None); assert_eq!(dec_add(i128::MAX, 1), None); assert_eq!(dec_div(i128::MAX, 1), None); // * 10^18 overflows } #[test] fn round_to_places_is_half_even() { assert_eq!(dec_show(dec_round(dec("1.5"), 0).unwrap()), "2"); assert_eq!(dec_show(dec_round(dec("2.5"), 0).unwrap()), "2"); assert_eq!(dec_show(dec_round(dec("-1.5"), 0).unwrap()), "-2"); assert_eq!(dec_show(dec_round(dec("-2.5"), 0).unwrap()), "-2"); assert_eq!(dec_show(dec_round(dec("1.005"), 2).unwrap()), "1"); assert_eq!(dec_show(dec_round(dec("1.015"), 2).unwrap()), "1.02"); assert_eq!(dec_show(dec_round(dec("12.345"), 18).unwrap()), "12.345"); assert_eq!(dec_round(dec("1"), 19), None); assert_eq!(dec_round(i128::MAX - 1, 0), None); } #[test] fn int_conversions() { assert_eq!(dec_from_int(&BigInt::from(42)), Some(42 * DEC_SCALE)); assert_eq!( dec_from_int(&BigInt::from(170141183460469231731i128)), Some(170141183460469231731i128 * DEC_SCALE) ); assert_eq!(dec_from_int(&BigInt::from(170141183460469231732i128)), None); assert_eq!(dec_to_int(dec("12.99")), 12); assert_eq!(dec_to_int(dec("-12.99")), -12); assert_eq!(dec_to_int(dec("0.5")), 0); } #[test] fn float_conversions_go_through_the_shortest_decimal() { assert_eq!(dec_from_f64(0.1), dec_parse("0.1")); assert_eq!(dec_from_f64(-0.0), Some(0)); assert_eq!(dec_from_f64(1.5e-10), dec_parse("0.00000000015")); assert_eq!(dec_from_f64(f64::NAN), None); assert_eq!(dec_from_f64(f64::INFINITY), None); assert_eq!(dec_from_f64(1e300), None); assert_eq!(dec_to_f64(dec("0.1")), 0.1); assert_eq!(dec_to_f64(dec("-2.5")), -2.5); } /// Hashes are observable; pin the formula (`hash_limbs` over the two /// limbs, then `mix`). #[test] fn hashes_are_stable() { assert_eq!(dec_hash(0), mix(crate::hash_limbs(false, &[0, 0]))); assert_eq!( dec_hash(DEC_SCALE), mix(crate::hash_limbs(false, &[0x0DE0B6B3A7640000, 0])) ); assert_eq!( dec_hash(-1), mix(!crate::hash_limbs(false, &[u64::MAX, u64::MAX])) ); assert_eq!( dec_hash(dec("1.5")), mix(crate::hash_limbs(false, &[0x14D1120D7B160000, 0])) ); // Distinct values hash distinctly here (the formula's point), and // the canonical form makes "1" and "1.0" one hash. assert_ne!(dec_hash(dec("1")), dec_hash(dec("-1"))); assert_eq!(dec_hash(dec("1")), dec_hash(dec("1.0"))); } }