flow-lang-value 0.1.0-rc.5

The Flow runtime value model: data values, their equality, order and text, and the operations std's built-in types declare.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
//! `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, ToPrimitive, 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`].
    ///
    /// # Errors
    ///
    /// [`Fault::Limit`] when the normalized exponent would pass `i64::MAX`.
    pub fn new(coefficient: BigInt, exponent: i64) -> Result<Self, Fault> {
        if coefficient.is_zero() {
            return Ok(Decimal {
                coefficient,
                exponent: 0,
            });
        }
        let (coefficient, zeros) = strip_zeros(coefficient);
        let raised = i64::try_from(zeros)
            .ok()
            .and_then(|zeros| exponent.checked_add(zeros))
            .ok_or(Fault::Limit)?;
        Ok(Decimal {
            coefficient,
            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.
    ///
    /// # Errors
    ///
    /// [`Fault::Limit`] when the result's exponent would leave the `i64` range.
    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.
    ///
    /// # Errors
    ///
    /// [`Fault::Limit`] when the result's exponent would leave the `i64` range.
    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.
    ///
    /// # Errors
    ///
    /// [`Fault::Limit`] when the result's exponent would leave the `i64` range.
    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.
    ///
    /// # Errors
    ///
    /// [`Fault::DivisionByZero`] for a zero divisor, and [`Fault::Limit`] when
    /// the quotient's exponent would leave the `i64` range.
    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 two magnitudes are aligned and compared. Sharing the
        // leading digit's place puts the exponents no further apart than
        // the longer coefficient has digits, so the power of ten that aligns
        // them is no longer than a number already held, however far apart
        // the exponents of two numbers of different places are.
        let magnitude = self
            .adjusted_exponent()
            .cmp(&other.adjusted_exponent())
            .then_with(|| {
                let (left, right) = (self.coefficient.magnitude(), other.coefficient.magnitude());
                let shift = pow10(self.exponent.abs_diff(other.exponent)).into_parts().1;
                if self.exponent > other.exponent {
                    (left * shift).cmp(right)
                } else {
                    left.cmp(&(right * shift))
                }
            });
        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.
///
/// No text is written: a magnitude of `b` bits has at least
/// `⌊(b - 1) · log10 2⌋ + 1` digits, and at most two more, which comparing
/// with powers of ten settles.
fn digit_count(value: &BigInt) -> u64 {
    let magnitude = value.magnitude();
    if let Some(small) = magnitude.to_u64() {
        return small
            .checked_ilog10()
            .map_or(1, |below| u64::from(below) + 1);
    }
    // log10 2 = 0.301029995663981195..., rounded down, so the estimate is
    // never above the true count: `10^(digits - 1) ≤ 2^(bits - 1) ≤ magnitude`.
    let bits = u128::from(magnitude.bits());
    let estimate = (bits - 1) * 301_029_995_663_981 / 1_000_000_000_000_000;
    let mut digits = u64::try_from(estimate).expect("a third of a bit count fits 64 bits") + 1;
    let mut next = pow10(digits);
    while magnitude >= next.magnitude() {
        digits += 1;
        next *= 10;
    }
    digits
}

/// Returns `coefficient` with its trailing decimal zeros divided out, and how
/// many there were. A nonzero number has no more of them than factors of
/// two, so an odd one, the common case, is answered at once.
fn strip_zeros(coefficient: BigInt) -> (BigInt, u64) {
    let twos = coefficient.trailing_zeros().unwrap_or(0);
    let mut rest = coefficient;
    let mut zeros = 0;
    // Nineteen zeros at a time, then one at a time.
    for (step, power) in [(19, 10_000_000_000_000_000_000_u64), (1, 10)] {
        while twos - zeros >= step {
            let (quotient, remainder) = rest.div_rem(&BigInt::from(power));
            if !remainder.is_zero() {
                break;
            }
            rest = quotient;
            zeros += step;
        }
    }
    (rest, zeros)
}

/// 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)
}