f-office-units 0.2.4

Integer lengths and unit conversions for F-Office.
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
//! Numbers in binary single precision (IEEE 754 binary32), made of whole numbers.
//!
//! Word's PDF writers hold some numbers in single precision: the page coordinates that they
//! print and the counts of their text adjustments. The layout crates use no floating-point
//! arithmetic, so this type gives the same numbers with integer
//! arithmetic: each operation takes the exact result and rounds it once, to the nearest number
//! with a mantissa of 24 bits, a tie to the even mantissa, as a processor rounds it. The
//! operations named `below` round down instead, toward negative infinity, as a processor does in
//! that rounding mode: Word for Windows's device computes the frame side of a page in it.
//! Numbers below the smallest normal number
//! and above the largest do not occur in these counts and are not modelled.

/// A number in binary single precision, `mantissa * 2^exponent`, with a sign and a mantissa of
/// exactly [`Binary32::BITS`] bits, from 2^23 to 2^24 - 1, as binary32 holds a normal number.
/// Zero has the mantissa 0 and the exponent 0. So each number has one form, and two equal
/// numbers are equal values of the type.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Binary32 {
    mantissa: i64,
    exponent: i32,
}

/// How an operation rounds its exact result to a mantissa of [`Binary32::BITS`] bits.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Rounding {
    /// To the nearest number, a tie to the even mantissa.
    Nearest,
    /// Down, toward negative infinity: to the largest number at or below the result.
    Down,
}

impl Binary32 {
    /// The bits of a mantissa, with its leading one.
    pub const BITS: u32 = 24;

    /// Zero.
    pub const ZERO: Self = Self {
        mantissa: 0,
        exponent: 0,
    };

    /// The mantissa, with the number's sign.
    #[must_use]
    pub const fn mantissa(self) -> i64 {
        self.mantissa
    }

    /// The power of two by which the mantissa is multiplied.
    #[must_use]
    pub const fn exponent(self) -> i32 {
        self.exponent
    }

    /// The number nearest to `numerator / denominator`, for a positive denominator; zero for a
    /// denominator that is not positive.
    #[must_use]
    pub fn nearest(numerator: i128, denominator: i128) -> Self {
        Self::quotient(numerator, denominator, Rounding::Nearest)
    }

    /// The largest number at or below `numerator / denominator`, for a positive denominator;
    /// zero for a denominator that is not positive.
    #[must_use]
    pub fn below(numerator: i128, denominator: i128) -> Self {
        Self::quotient(numerator, denominator, Rounding::Down)
    }

    /// `numerator / denominator` rounded by `rounding`, for a positive denominator; zero for a
    /// denominator that is not positive.
    fn quotient(numerator: i128, denominator: i128, rounding: Rounding) -> Self {
        if numerator == 0 || denominator <= 0 {
            return Self::ZERO;
        }
        let (quotient, rest, scale) =
            scaled_quotient(numerator.unsigned_abs(), denominator.unsigned_abs());
        // A rest of the division sits below the last bit of the quotient, and keeps a half
        // from being a tie. The quotient is below 2^(BITS + 2), so its shift loses no bit.
        Self::rounded(
            (quotient << 1) | u128::from(rest),
            -scale - 1,
            numerator < 0,
            rounding,
        )
    }

    /// `magnitude * 2^exponent`, negative when `negative`, rounded by `rounding` to a mantissa
    /// of [`Self::BITS`] bits, in the one form of the number ([`Binary32`]).
    fn rounded(magnitude: u128, exponent: i32, negative: bool, rounding: Rounding) -> Self {
        if magnitude == 0 {
            return Self::ZERO;
        }
        // A magnitude of fewer bits than a mantissa, such as a difference of two near
        // numbers, moves up until its leading one is the mantissa's: exact, so nothing rounds.
        let short = magnitude
            .leading_zeros()
            .saturating_sub(u128::BITS - Self::BITS);
        let mut magnitude = magnitude << short;
        let mut exponent = exponent - short.cast_signed();
        let mut lost = false;
        while magnitude >= (1 << (Self::BITS + 1)) {
            lost |= magnitude & 1 == 1;
            magnitude >>= 1;
            exponent += 1;
        }
        if magnitude >= (1 << Self::BITS) {
            // One bit more than the mantissa holds.
            let half = magnitude & 1 == 1;
            magnitude >>= 1;
            exponent += 1;
            let up = match rounding {
                // To the nearest, a tie to the even.
                Rounding::Nearest => half && (lost || magnitude & 1 == 1),
                // Toward negative infinity: a positive number drops what it loses, and a
                // negative one that loses anything grows by one unit of its mantissa.
                Rounding::Down => negative && (half || lost),
            };
            if up {
                magnitude += 1;
            }
            // A carry out of the mantissa makes it a power of two of one bit more.
            if magnitude == 1 << Self::BITS {
                magnitude >>= 1;
                exponent += 1;
            }
        }
        let mantissa = i64::try_from(magnitude).unwrap_or(i64::MAX);
        Self {
            mantissa: if negative { -mantissa } else { mantissa },
            exponent,
        }
    }

    /// The two numbers as whole multiples of one power of two, in their order, and that
    /// power's exponent.
    ///
    /// When the exponents differ by 64 or less, the multiples are the numbers exactly: a
    /// mantissa shifted 64 bits up has at most 88 bits. When they differ by more, the larger
    /// number's mantissa goes 40 bits up, to at most 64 bits, and the smaller number becomes
    /// one unit of that power with its sign. The smaller number lies below
    /// `2^(BITS + low.exponent)`, at most `2^(high.exponent - 41)`: less than half that unit,
    /// so it and the unit lie among the bits that a rounding of the sum to [`Self::BITS`] bits
    /// drops, at least 39, and round it alike. That makes the sum of the two multiples exact
    /// for [`Self::plus`] and [`Self::plus_below`], their order of magnitude exact for
    /// [`Self::reaches`], and their difference exact for [`Self::differs_by`], which gives the
    /// reason.
    fn aligned(self, other: Self) -> (i128, i128, i32) {
        if self.mantissa == 0 {
            return (0, other.mantissa.into(), other.exponent);
        }
        if other.mantissa == 0 {
            return (self.mantissa.into(), 0, self.exponent);
        }
        let by = self.exponent.abs_diff(other.exponent);
        if by <= i64::BITS {
            let exponent = self.exponent.min(other.exponent);
            let shift =
                |number: Self| i128::from(number.mantissa) << number.exponent.abs_diff(exponent);
            return (shift(self), shift(other), exponent);
        }
        let up = i64::BITS - Self::BITS;
        let exponent = self.exponent.max(other.exponent) - up.cast_signed();
        let multiple = |number: Self| {
            if number.exponent > exponent {
                i128::from(number.mantissa) << up
            } else {
                i128::from(number.mantissa.signum())
            }
        };
        (multiple(self), multiple(other), exponent)
    }

    /// The sum of the two numbers, rounded by `rounding`.
    fn sum(self, other: Self, rounding: Rounding) -> Self {
        let (first, second, exponent) = self.aligned(other);
        let sum = first + second;
        Self::rounded(sum.unsigned_abs(), exponent, sum < 0, rounding)
    }

    /// The sum of the two numbers, rounded.
    #[must_use]
    pub fn plus(self, other: Self) -> Self {
        self.sum(other, Rounding::Nearest)
    }

    /// The sum of the two numbers, rounded down.
    #[must_use]
    pub fn plus_below(self, other: Self) -> Self {
        self.sum(other, Rounding::Down)
    }

    /// The difference of the two numbers, rounded.
    #[must_use]
    pub fn minus(self, other: Self) -> Self {
        self.plus(Self {
            mantissa: -other.mantissa,
            ..other
        })
    }

    /// The product with the whole number `factor`, rounded.
    #[must_use]
    pub fn times(self, factor: i64) -> Self {
        self.scaled(i128::from(factor), 0, Rounding::Nearest)
    }

    /// The product with the whole number `factor`, rounded down.
    #[must_use]
    pub fn times_below(self, factor: i64) -> Self {
        self.scaled(i128::from(factor), 0, Rounding::Down)
    }

    /// The product of the two numbers, rounded down.
    #[must_use]
    pub fn product_below(self, other: Self) -> Self {
        self.scaled(i128::from(other.mantissa), other.exponent, Rounding::Down)
    }

    /// The number times `factor * 2^exponent`, rounded by `rounding`. The product of a
    /// mantissa and an `i64` fits an `i128`.
    fn scaled(self, factor: i128, exponent: i32, rounding: Rounding) -> Self {
        let product = i128::from(self.mantissa) * factor;
        Self::rounded(
            product.unsigned_abs(),
            self.exponent + exponent,
            product < 0,
            rounding,
        )
    }

    /// The quotient by `other`, rounded; zero when `other` is zero.
    #[must_use]
    pub fn over(self, other: Self) -> Self {
        self.divided(other, Rounding::Nearest)
    }

    /// The quotient by `other`, rounded down; zero when `other` is zero.
    #[must_use]
    pub fn over_below(self, other: Self) -> Self {
        self.divided(other, Rounding::Down)
    }

    /// The quotient by `other`, rounded by `rounding`; zero when `other` is zero.
    fn divided(self, other: Self, rounding: Rounding) -> Self {
        if other.mantissa == 0 {
            return Self::ZERO;
        }
        // The quotient of the mantissas rounds as the quotient of the numbers does, since the
        // powers of two only move the exponent.
        let sign = other.mantissa.signum();
        let quotient = Self::quotient(
            i128::from(self.mantissa * sign),
            i128::from(other.mantissa * sign),
            rounding,
        );
        if quotient.mantissa == 0 {
            return Self::ZERO;
        }
        Self {
            exponent: quotient.exponent + self.exponent - other.exponent,
            ..quotient
        }
    }

    /// The largest whole number at or below the number.
    #[must_use]
    pub fn floor(self) -> i64 {
        if self.exponent >= 0 {
            return self.whole(false);
        }
        let by = self.exponent.unsigned_abs();
        if by >= i64::BITS - 1 {
            // A mantissa below 2^24 over 2^63 or more lies strictly between -1 and 1.
            return if self.mantissa < 0 { -1 } else { 0 };
        }
        self.mantissa.div_euclid(1_i64 << by)
    }

    /// Whether the number is `other` or more away from zero.
    #[must_use]
    pub fn reaches(self, other: Self) -> bool {
        let (first, second, _) = self.aligned(other);
        first.unsigned_abs() >= second.unsigned_abs()
    }

    /// The whole part of the number, toward zero.
    #[must_use]
    pub fn toward_zero(self) -> i64 {
        if self.exponent >= 0 {
            return self.whole(false);
        }
        let by = self.exponent.unsigned_abs();
        if by >= i64::BITS - 1 {
            return 0;
        }
        // Division of whole numbers rounds toward zero.
        self.mantissa / (1_i64 << by)
    }

    /// The nearest whole number, with a half toward the lower number when `lower`, and toward
    /// the higher number otherwise.
    #[must_use]
    pub fn whole(self, lower: bool) -> i64 {
        if self.exponent >= 0 {
            // A mantissa of 24 bits shifted 39 bits up or less fits an `i64`. Shifted 40 bits
            // up or more, it is 2^63 or more away from zero, so the whole number saturates.
            let up = self.exponent.unsigned_abs();
            if up >= i64::BITS - Self::BITS {
                return if self.mantissa < 0 {
                    i64::MIN
                } else {
                    i64::MAX
                };
            }
            return self.mantissa << up;
        }
        let by = self.exponent.unsigned_abs();
        // A mantissa has at most 24 bits, so such a fraction is strictly inside a half.
        if by >= i64::BITS - 1 {
            return 0;
        }
        let divisor = 1_i64 << by;
        let whole = self.mantissa.div_euclid(divisor);
        let rest = self.mantissa.rem_euclid(divisor);
        whole
            + i64::from(if lower {
                2 * rest > divisor
            } else {
                2 * rest >= divisor
            })
    }

    /// Whether the two numbers differ by `|numerator| / denominator` or more, for a numerator
    /// of magnitude below 2^32 and a denominator from 1 to 2^32 - 1. A caller passes no other
    /// parts: a debug build, as the tests run, stops at them, and a release build gives
    /// `false`, as [`Self::nearest`] gives zero for a denominator that is not positive.
    ///
    /// For such parts the answer is exact for all numbers. Where the alignment of two numbers puts one unit
    /// `u` of `2^(e - 40)` in place of the smaller number, `e` the larger number's exponent,
    /// the true difference and the aligned one lie on the same side of the larger number's
    /// magnitude `h`: the true one less than `u` from it, the aligned one `u` from it. They
    /// give different answers only for a limit `t` with `0 < |t - h| <= u`, and no limit of
    /// two `u32` parts lies there, since `h` has a mantissa of 24 bits. For `e < 0`, a nonzero
    /// `|t - h|` is at least `2^e / denominator`, above `2^(e - 32)`. For `0 <= e <= 8`, it is
    /// at least `1 / denominator`, above `2^-32`. For `e > 8`, `h` is at least `2^32` and `t`
    /// is below it, so `h - t` is at least 1, above `u` up to `e = 39`, and from `e = 40` on,
    /// where `h` is at least `2^63`, it is above `h / 2`, also above `u`. At `t = h` both
    /// answers are the same. The aligned difference has at most 89 bits, so its product with
    /// the denominator fits a `u128`.
    #[must_use]
    pub fn differs_by(self, other: Self, numerator: i64, denominator: i64) -> bool {
        let parts = (
            u32::try_from(numerator.unsigned_abs()),
            u32::try_from(denominator),
        );
        debug_assert!(
            matches!(parts, (Ok(_), Ok(1..))),
            "differs_by takes parts below 2^32 and a positive denominator, not \
             {numerator}/{denominator}"
        );
        let (Ok(numerator), Ok(denominator @ 1..)) = parts else {
            return false;
        };
        let (first, second, exponent) = self.aligned(other);
        let difference = (first - second).unsigned_abs() * u128::from(denominator);
        let limit = u128::from(numerator);
        let by = exponent.unsigned_abs();
        if exponent >= 0 {
            // `difference * 2^by >= limit`, with the limit divided and rounded up.
            let whole = limit.checked_shr(by).unwrap_or(0);
            let rest = whole.checked_shl(by) != Some(limit);
            difference >= whole + u128::from(rest)
        } else {
            // `difference >= limit * 2^by`: the whole part of the quotient decides.
            difference.checked_shr(by).unwrap_or(0) >= limit
        }
    }
}

/// The whole quotient of `top * 2^scale` by `bottom`, whether a rest remains, and the scale,
/// for a positive `top` and a `bottom` from 1 to 2^127 - 1.
///
/// The scale is the power of two that gives the quotient one bit more than a mantissa, or
/// two: for a `top` of t bits and a `bottom` of b bits it is `BITS + 1 + b - t`, and the
/// quotient is at least 2^BITS and below 2^(BITS + 2), for every `top`. The rounding reads the
/// mantissa's bits, the bit below them and whether any bit below that is set, so this one
/// quotient gives all that it reads.
///
/// A `top` of more than `BITS + 1 + b` bits has a negative scale: its last bits go before the
/// division and count only toward the rest, because a fraction below one, added to a whole
/// number, does not change that number's whole quotient by `bottom`. At most
/// 128 - (BITS + 2) bits go.
///
/// A positive shift stays inside `u128`. The shifted `top` is below `2^(BITS + 1 + b)`, which
/// is below 2^128 for every `bottom` below 2^103. The callers' denominators are below 2^73: the
/// writer counts of `f-office-docx` divide by an em of 1,000 times an `i64` size. Where the
/// shift would lose bits, which needs a `bottom` of 2^103 or more, the quotient's last bits come
/// one at a time by long division, with no shift of `top`.
fn scaled_quotient(top: u128, bottom: u128) -> (u128, bool, i32) {
    let scale = (Binary32::BITS + 1 + top.leading_zeros()).cast_signed()
        - bottom.leading_zeros().cast_signed();
    if scale < 0 {
        let down = scale.unsigned_abs();
        let (quotient, rest) = divided(top >> down, bottom);
        return (quotient, rest || top.trailing_zeros() < down, scale);
    }
    let up = scale.unsigned_abs();
    if up <= top.leading_zeros() {
        let (quotient, rest) = divided(top << up, bottom);
        return (quotient, rest, scale);
    }
    let (mut quotient, mut rest) = (top / bottom, top % bottom);
    for _ in 0..up {
        // The rest is below `bottom`, which is below 2^127, so its double fits.
        rest <<= 1;
        quotient <<= 1;
        if rest >= bottom {
            rest -= bottom;
            quotient |= 1;
        }
    }
    (quotient, rest != 0, scale)
}

/// The whole quotient of `top` by a positive `bottom`, and whether a rest remains.
fn divided(top: u128, bottom: u128) -> (u128, bool) {
    // A processor divides 64-bit numbers itself; a 128-bit division is a call into the
    // compiler's runtime.
    if let (Ok(top), Ok(bottom)) = (u64::try_from(top), u64::try_from(bottom)) {
        return (u128::from(top / bottom), top % bottom != 0);
    }
    let quotient = top / bottom;
    (quotient, top - quotient * bottom != 0)
}

#[cfg(test)]
mod tests;