| @@ -0,0 +1,374 @@ |
| 1 | +//! `Dec` (`std/dec`, ADR 0070): a 128-bit fixed-point decimal, an `i128` |
| 2 | +//! counting units of 10^-18 (18 places, an integral part up to about |
| 3 | +//! ±1.7·10^20 — Roc's choice). The fixed scale is the canonicalization |
| 4 | +//! rule: every value has exactly one `i128`, so equality, comparison and |
| 5 | +//! the hash read the raw integer, and there is no negative zero. |
| 6 | +//! |
| 7 | +//! Every inexact operation rounds to the nearest, ties to even |
| 8 | +//! (`div_round_half_even`): `*` and `/`, `parse` past 18 places, |
| 9 | +//! `from_float` and `round`. Operators panic on overflow (the backends |
| 10 | +//! turn `None` into the panic); conversions report it as a value. |
| 11 | + |
| 12 | +use num_bigint::{BigInt, Sign}; |
| 13 | +use num_traits::{Signed, ToPrimitive}; |
| 14 | + |
| 15 | +use crate::{hash_limbs, mix}; |
| 16 | + |
| 17 | +/// The decimal places of a `Dec`, and its scale: `10^DEC_PLACES`. |
| 18 | +pub const DEC_PLACES: u32 = 18; |
| 19 | +pub const DEC_SCALE: i128 = 1_000_000_000_000_000_000; |
| 20 | + |
| 21 | +pub const DEC_DIVISION_BY_ZERO: &str = "dec.div: division by zero"; |
| 22 | +pub const DEC_REMAINDER_BY_ZERO: &str = "dec.rem: division by zero"; |
| 23 | + |
| 24 | +/// The panic of an overflowing `dec` operation (`op` is `add`, `mul`, ...). |
| 25 | +pub fn dec_overflow(op: &str) -> String { |
| 26 | + format!("dec.{op}: overflow") |
| 27 | +} |
| 28 | + |
| 29 | +/// The panic of `dec.round` with `places` outside `0..=DEC_PLACES`. |
| 30 | +pub fn dec_bad_places(places: &str) -> String { |
| 31 | + format!("dec.round: places must be in 0..={DEC_PLACES}, got {places}") |
| 32 | +} |
| 33 | + |
| 34 | +/// `n / d` (truncating), with the remainder rounded to the nearest |
| 35 | +/// quotient, ties to even. `d` must be positive; the rounding is |
| 36 | +/// sign-symmetric, so a negative `n` rounds away from zero on a tie only |
| 37 | +/// when the truncated quotient is odd. |
| 38 | +fn div_round_half_even(n: &BigInt, d: &BigInt) -> BigInt { |
| 39 | + debug_assert!(d.sign() == Sign::Plus); |
| 40 | + // `/` and `%` on BigInt truncate toward zero, as div_rem does. |
| 41 | + let (q, r) = (n / d, n % d); |
| 42 | + let up = match (r.abs() << 1u32).cmp(d) { |
| 43 | + std::cmp::Ordering::Less => false, |
| 44 | + std::cmp::Ordering::Greater => true, |
| 45 | + // A tie rounds to an even quotient. |
| 46 | + std::cmp::Ordering::Equal => q.bit(0), |
| 47 | + }; |
| 48 | + if up { |
| 49 | + q + if n.sign() == Sign::Minus { -1 } else { 1 } |
| 50 | + } else { |
| 51 | + q |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | +pub fn dec_add(a: i128, b: i128) -> Option<i128> { |
| 56 | + a.checked_add(b) |
| 57 | +} |
| 58 | + |
| 59 | +pub fn dec_sub(a: i128, b: i128) -> Option<i128> { |
| 60 | + a.checked_sub(b) |
| 61 | +} |
| 62 | + |
| 63 | +pub fn dec_neg(a: i128) -> Option<i128> { |
| 64 | + a.checked_neg() |
| 65 | +} |
| 66 | + |
| 67 | +/// `a * b`, rounded; `None` on overflow. The exact product has up to 36 |
| 68 | +/// places, so it is computed as a big integer and halved back into range |
| 69 | +/// by the division. |
| 70 | +pub fn dec_mul(a: i128, b: i128) -> Option<i128> { |
| 71 | + let n = BigInt::from(a) * BigInt::from(b); |
| 72 | + div_round_half_even(&n, &BigInt::from(DEC_SCALE)).to_i128() |
| 73 | +} |
| 74 | + |
| 75 | +/// `a / b`, rounded; `None` on overflow, and on `b == 0` (the caller |
| 76 | +/// reports division by zero first, with [`DEC_DIVISION_BY_ZERO`]). |
| 77 | +pub fn dec_div(a: i128, b: i128) -> Option<i128> { |
| 78 | + if b == 0 { |
| 79 | + return None; |
| 80 | + } |
| 81 | + let n = BigInt::from(a) * BigInt::from(DEC_SCALE); |
| 82 | + div_round_half_even(&n, &BigInt::from(b)).to_i128() |
| 83 | +} |
| 84 | + |
| 85 | +/// The remainder of a truncating division (`a - (a / b) * b`, exact: |
| 86 | +/// the scales cancel); `None` on `b == 0` (the caller reports it). |
| 87 | +pub fn dec_rem(a: i128, b: i128) -> Option<i128> { |
| 88 | + a.checked_rem(b) |
| 89 | +} |
| 90 | + |
| 91 | +/// `n` units of 1 as a `Dec` (`n * 10^18`); `None` when out of range. |
| 92 | +pub fn dec_from_int(n: &BigInt) -> Option<i128> { |
| 93 | + (n * DEC_SCALE).to_i128() |
| 94 | +} |
| 95 | + |
| 96 | +/// The whole units of `v`, truncated toward zero. |
| 97 | +pub fn dec_to_int(v: i128) -> i128 { |
| 98 | + v / DEC_SCALE |
| 99 | +} |
| 100 | + |
| 101 | +/// The raw count of 10^-18 units `n` as a `Dec`: `n` itself, when it |
| 102 | +/// fits in 128 bits. |
| 103 | +pub fn dec_from_scaled(n: &BigInt) -> Option<i128> { |
| 104 | + n.to_i128() |
| 105 | +} |
| 106 | + |
| 107 | +/// The `Dec` written in `s`: an optional sign, decimal digits, an |
| 108 | +/// optional point and more digits (`"1"`, `"1.20"`, `".5"`, `"1."`; no |
| 109 | +/// exponent). More than 18 fractional digits round half-even. `None` |
| 110 | +/// when `s` is not such a text or the value is out of range. `"-0"` and |
| 111 | +/// its forms are `0` (there is no negative zero). |
| 112 | +pub fn dec_parse(s: &str) -> Option<i128> { |
| 113 | + let (neg, t) = match s.strip_prefix('-') { |
| 114 | + Some(t) => (true, t), |
| 115 | + None => (false, s.strip_prefix('+').unwrap_or(s)), |
| 116 | + }; |
| 117 | + let (int_part, frac) = t.split_once('.').unwrap_or((t, "")); |
| 118 | + if int_part.is_empty() && frac.is_empty() { |
| 119 | + return None; |
| 120 | + } |
| 121 | + if !int_part.bytes().all(|b| b.is_ascii_digit()) || !frac.bytes().all(|b| b.is_ascii_digit()) { |
| 122 | + return None; |
| 123 | + } |
| 124 | + let integral: u128 = match int_part { |
| 125 | + "" => 0, |
| 126 | + digits => digits.parse().ok()?, |
| 127 | + }; |
| 128 | + // The first 18 fractional digits, right-padded to 18 places. |
| 129 | + let mut kept: u128 = 0; |
| 130 | + for (i, b) in frac.bytes().enumerate() { |
| 131 | + if i < DEC_PLACES as usize { |
| 132 | + kept = kept * 10 + u128::from(b - b'0'); |
| 133 | + } |
| 134 | + } |
| 135 | + kept *= 10u128.pow(DEC_PLACES - frac.len().min(DEC_PLACES as usize) as u32); |
| 136 | + // The dropped digits round the kept ones, half-even (a carry into the |
| 137 | + // integral part is the checked_add below). |
| 138 | + let dropped = &frac.as_bytes()[frac.len().min(DEC_PLACES as usize)..]; |
| 139 | + if let Some((first, rest)) = dropped.split_first() { |
| 140 | + let up = |
| 141 | + *first > b'5' || (*first == b'5' && (rest.iter().any(|b| *b != b'0') || kept % 2 == 1)); |
| 142 | + if up { |
| 143 | + kept += 1; |
| 144 | + } |
| 145 | + } |
| 146 | + // The magnitude is unsigned, so the minimum stays representable |
| 147 | + // (-2^127/10^18 is a Dec; its magnitude is not an i128). |
| 148 | + let v = integral.checked_mul(DEC_SCALE as u128)?.checked_add(kept)?; |
| 149 | + if neg { |
| 150 | + if v > (i128::MAX as u128) + 1 { |
| 151 | + return None; |
| 152 | + } |
| 153 | + Some((v as i128).wrapping_neg()) |
| 154 | + } else { |
| 155 | + i128::try_from(v).ok() |
| 156 | + } |
| 157 | +} |
| 158 | + |
| 159 | +/// `v` in decimal: the integral part, then the fractional digits with |
| 160 | +/// trailing zeros trimmed; an integral value has no point (`1.20` shows |
| 161 | +/// as `"1.2"`, `42` as `"42"`). |
| 162 | +pub fn dec_show(v: i128) -> String { |
| 163 | + let sign = if v < 0 { "-" } else { "" }; |
| 164 | + let a = v.unsigned_abs(); |
| 165 | + let s = DEC_SCALE as u128; |
| 166 | + let (integral, frac) = (a / s, a % s); |
| 167 | + if frac == 0 { |
| 168 | + return format!("{sign}{integral}"); |
| 169 | + } |
| 170 | + let mut digits = format!("{frac:018}"); |
| 171 | + while digits.ends_with('0') { |
| 172 | + digits.pop(); |
| 173 | + } |
| 174 | + format!("{sign}{integral}.{digits}") |
| 175 | +} |
| 176 | + |
| 177 | +/// `v` rounded to `places` decimal places, half-even; `None` when |
| 178 | +/// `places > DEC_PLACES` (the caller checks the range first, with |
| 179 | +/// [`dec_bad_places`]) or the rounded value overflows. |
| 180 | +pub fn dec_round(v: i128, places: u32) -> Option<i128> { |
| 181 | + if places > DEC_PLACES { |
| 182 | + return None; |
| 183 | + } |
| 184 | + let quantum = 10i128.pow(DEC_PLACES - places); |
| 185 | + let r = v % quantum; // the sign of v |
| 186 | + let base = v - r; |
| 187 | + let up = match (r.unsigned_abs() * 2).cmp(&(quantum as u128)) { |
| 188 | + std::cmp::Ordering::Less => false, |
| 189 | + std::cmp::Ordering::Greater => true, |
| 190 | + std::cmp::Ordering::Equal => (base / quantum) % 2 != 0, |
| 191 | + }; |
| 192 | + if up { |
| 193 | + base.checked_add(if v < 0 { -quantum } else { quantum }) |
| 194 | + } else { |
| 195 | + Some(base) |
| 196 | + } |
| 197 | +} |
| 198 | + |
| 199 | +/// The nearest `Dec` to `f`, through its shortest decimal text (`0.1` |
| 200 | +/// the float is `"0.1"` the string is `0.1` the `Dec` — not the binary |
| 201 | +/// expansion). `None` for NaN, an infinity, or a float out of range. |
| 202 | +pub fn dec_from_f64(f: f64) -> Option<i128> { |
| 203 | + if !f.is_finite() { |
| 204 | + return None; |
| 205 | + } |
| 206 | + // Display for f64 is the shortest round-trip decimal, never in |
| 207 | + // scientific notation, so `dec_parse` reads it. |
| 208 | + dec_parse(&format!("{f}")) |
| 209 | +} |
| 210 | + |
| 211 | +/// The nearest double to `v` (`dec_show` is exact; the parse is |
| 212 | +/// correctly rounded). |
| 213 | +pub fn dec_to_f64(v: i128) -> f64 { |
| 214 | + dec_show(v) |
| 215 | + .parse() |
| 216 | + .expect("louise: dec_show's output is a float") |
| 217 | +} |
| 218 | + |
| 219 | +/// The `Dec`'s hash: the big-integer scheme over its two limbs, so both |
| 220 | +/// backends agree (pinned in the tests below). |
| 221 | +pub fn dec_hash(v: i128) -> i64 { |
| 222 | + mix(hash_limbs(v < 0, &[v as u64, (v >> 64) as u64])) |
| 223 | +} |
| 224 | + |
| 225 | +#[cfg(test)] |
| 226 | +mod tests { |
| 227 | + use super::*; |
| 228 | + |
| 229 | + fn dec(s: &str) -> i128 { |
| 230 | + dec_parse(s).unwrap_or_else(|| panic!("a decimal: {s:?}")) |
| 231 | + } |
| 232 | + |
| 233 | + #[test] |
| 234 | + fn parse_and_show_round_trip() { |
| 235 | + for (text, shown) in [ |
| 236 | + ("0", "0"), |
| 237 | + ("-0", "0"), |
| 238 | + ("1", "1"), |
| 239 | + ("-1", "-1"), |
| 240 | + ("1.20", "1.2"), |
| 241 | + ("0.1", "0.1"), |
| 242 | + ("-0.5", "-0.5"), |
| 243 | + ("+42", "42"), |
| 244 | + (".5", "0.5"), |
| 245 | + ("1.", "1"), |
| 246 | + ("0.000000000000000001", "0.000000000000000001"), |
| 247 | + ( |
| 248 | + "170141183460469231731.687303715884105727", |
| 249 | + "170141183460469231731.687303715884105727", |
| 250 | + ), |
| 251 | + ] { |
| 252 | + assert_eq!(dec_show(dec(text)), shown, "{text:?}"); |
| 253 | + assert_eq!(dec(text), dec(shown)); |
| 254 | + } |
| 255 | + } |
| 256 | + |
| 257 | + #[test] |
| 258 | + fn parse_rounds_half_even_past_18_places() { |
| 259 | + // Ties: to the even last kept digit. |
| 260 | + assert_eq!(dec_parse("0.0000000000000000005"), Some(0)); |
| 261 | + assert_eq!(dec_parse("0.0000000000000000015"), Some(2)); |
| 262 | + assert_eq!(dec_parse("0.0000000000000000025"), Some(2)); |
| 263 | + assert_eq!(dec_parse("-0.0000000000000000015"), Some(-2)); |
| 264 | + // Not ties. |
| 265 | + assert_eq!(dec_parse("0.00000000000000000050001"), Some(1)); |
| 266 | + assert_eq!(dec_parse("0.00000000000000000049999"), Some(0)); |
| 267 | + // A carry into the integral part. |
| 268 | + assert_eq!(dec_parse("0.9999999999999999995"), Some(DEC_SCALE)); |
| 269 | + assert_eq!(dec_show(dec("0.9999999999999999995")), "1"); |
| 270 | + } |
| 271 | + |
| 272 | + #[test] |
| 273 | + fn parse_refuses_non_decimals_and_overflow() { |
| 274 | + for bad in ["", ".", "-", "abc", "1.2.3", "1e3", "0x10", "NaN", "1,5"] { |
| 275 | + assert_eq!(dec_parse(bad), None, "{bad:?}"); |
| 276 | + } |
| 277 | + assert_eq!(dec_parse("170141183460469231732"), None); |
| 278 | + assert_eq!(dec_parse("-170141183460469231732"), None); |
| 279 | + // One quantum past the maximum. |
| 280 | + assert_eq!(dec_parse("170141183460469231731.687303715884105728"), None); |
| 281 | + assert_eq!( |
| 282 | + dec_parse("-170141183460469231731.687303715884105728"), |
| 283 | + Some(i128::MIN) |
| 284 | + ); |
| 285 | + } |
| 286 | + |
| 287 | + #[test] |
| 288 | + fn arithmetic_rounds_half_even() { |
| 289 | + // 0.335 * 0.5 = 0.1675 → 0.1675 (exact); 1/3 and 2/3 round. |
| 290 | + assert_eq!(dec_mul(dec("0.335"), dec("0.5")), Some(dec("0.1675"))); |
| 291 | + assert_eq!( |
| 292 | + dec_show(dec_div(dec("1"), dec("3")).unwrap()), |
| 293 | + "0.333333333333333333" |
| 294 | + ); |
| 295 | + assert_eq!( |
| 296 | + dec_show(dec_div(dec("2"), dec("3")).unwrap()), |
| 297 | + "0.666666666666666667" |
| 298 | + ); |
| 299 | + // A tie at the last place: 0.000000000000000001 * 1.5. |
| 300 | + assert_eq!(dec_mul(1, dec("1.5")), Some(2)); // 1.5e-18 → 2e-18 (even) |
| 301 | + assert_eq!(dec_mul(3, dec("0.5")), Some(2)); // 1.5e-18 → 2e-18 (even) |
| 302 | + assert_eq!(dec_mul(5, dec("0.5")), Some(2)); // 2.5e-18 → 2e-18 (even) |
| 303 | + // Division by zero and overflow are None (the callers panic). |
| 304 | + assert_eq!(dec_div(dec("1"), 0), None); |
| 305 | + assert_eq!(dec_rem(dec("7"), dec("2")), Some(dec("1"))); |
| 306 | + assert_eq!(dec_rem(dec("7.5"), dec("2")), Some(dec("1.5"))); |
| 307 | + assert_eq!(dec_rem(dec("-7"), dec("2")), Some(dec("-1"))); |
| 308 | + assert_eq!(dec_rem(dec("7"), 0), None); |
| 309 | + assert_eq!(dec_mul(i128::MAX, i128::MAX), None); |
| 310 | + assert_eq!(dec_add(i128::MAX, 1), None); |
| 311 | + assert_eq!(dec_div(i128::MAX, 1), None); // * 10^18 overflows |
| 312 | + } |
| 313 | + |
| 314 | + #[test] |
| 315 | + fn round_to_places_is_half_even() { |
| 316 | + assert_eq!(dec_show(dec_round(dec("1.5"), 0).unwrap()), "2"); |
| 317 | + assert_eq!(dec_show(dec_round(dec("2.5"), 0).unwrap()), "2"); |
| 318 | + assert_eq!(dec_show(dec_round(dec("-1.5"), 0).unwrap()), "-2"); |
| 319 | + assert_eq!(dec_show(dec_round(dec("-2.5"), 0).unwrap()), "-2"); |
| 320 | + assert_eq!(dec_show(dec_round(dec("1.005"), 2).unwrap()), "1"); |
| 321 | + assert_eq!(dec_show(dec_round(dec("1.015"), 2).unwrap()), "1.02"); |
| 322 | + assert_eq!(dec_show(dec_round(dec("12.345"), 18).unwrap()), "12.345"); |
| 323 | + assert_eq!(dec_round(dec("1"), 19), None); |
| 324 | + assert_eq!(dec_round(i128::MAX - 1, 0), None); |
| 325 | + } |
| 326 | + |
| 327 | + #[test] |
| 328 | + fn int_conversions() { |
| 329 | + assert_eq!(dec_from_int(&BigInt::from(42)), Some(42 * DEC_SCALE)); |
| 330 | + assert_eq!( |
| 331 | + dec_from_int(&BigInt::from(170141183460469231731i128)), |
| 332 | + Some(170141183460469231731i128 * DEC_SCALE) |
| 333 | + ); |
| 334 | + assert_eq!(dec_from_int(&BigInt::from(170141183460469231732i128)), None); |
| 335 | + assert_eq!(dec_to_int(dec("12.99")), 12); |
| 336 | + assert_eq!(dec_to_int(dec("-12.99")), -12); |
| 337 | + assert_eq!(dec_to_int(dec("0.5")), 0); |
| 338 | + } |
| 339 | + |
| 340 | + #[test] |
| 341 | + fn float_conversions_go_through_the_shortest_decimal() { |
| 342 | + assert_eq!(dec_from_f64(0.1), dec_parse("0.1")); |
| 343 | + assert_eq!(dec_from_f64(-0.0), Some(0)); |
| 344 | + assert_eq!(dec_from_f64(1.5e-10), dec_parse("0.00000000015")); |
| 345 | + assert_eq!(dec_from_f64(f64::NAN), None); |
| 346 | + assert_eq!(dec_from_f64(f64::INFINITY), None); |
| 347 | + assert_eq!(dec_from_f64(1e300), None); |
| 348 | + assert_eq!(dec_to_f64(dec("0.1")), 0.1); |
| 349 | + assert_eq!(dec_to_f64(dec("-2.5")), -2.5); |
| 350 | + } |
| 351 | + |
| 352 | + /// Hashes are observable; pin the formula (`hash_limbs` over the two |
| 353 | + /// limbs, then `mix`). |
| 354 | + #[test] |
| 355 | + fn hashes_are_stable() { |
| 356 | + assert_eq!(dec_hash(0), mix(crate::hash_limbs(false, &[0, 0]))); |
| 357 | + assert_eq!( |
| 358 | + dec_hash(DEC_SCALE), |
| 359 | + mix(crate::hash_limbs(false, &[0x0DE0B6B3A7640000, 0])) |
| 360 | + ); |
| 361 | + assert_eq!( |
| 362 | + dec_hash(-1), |
| 363 | + mix(!crate::hash_limbs(false, &[u64::MAX, u64::MAX])) |
| 364 | + ); |
| 365 | + assert_eq!( |
| 366 | + dec_hash(dec("1.5")), |
| 367 | + mix(crate::hash_limbs(false, &[0x14D1120D7B160000, 0])) |
| 368 | + ); |
| 369 | + // Distinct values hash distinctly here (the formula's point), and |
| 370 | + // the canonical form makes "1" and "1.0" one hash. |
| 371 | + assert_ne!(dec_hash(dec("1")), dec_hash(dec("-1"))); |
| 372 | + assert_eq!(dec_hash(dec("1")), dec_hash(dec("1.0"))); |
| 373 | + } |
| 374 | +} |