f-office-units 0.2.3

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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
//! Integer lengths for layout.
//!
//! F-Office lays out pages in one integer unit, half an EMU, which is 1/25,400 of a point.
//! Office Open XML files give lengths in twips, half-points, eighth-points and EMUs, and each
//! of these is a whole number of half-EMUs, so a value read from a file converts without
//! rounding. Integer layout also gives the same result on every machine.

#![deny(clippy::float_arithmetic)]

use std::iter::Sum;
use std::ops::{Add, AddAssign, Mul, Neg, Sub, SubAssign};

pub mod binary32;
mod edges;
pub mod fixed;
pub mod measure;
pub mod scale;

pub use edges::Edges;

/// A length in half-EMUs, which is 1/25,400 of a point.
///
/// The constructors that scale a value from a file return `None` when the result lies beyond
/// [`Length::FILE_LIMIT`], so untrusted input cannot overflow. The operators behave as the `i64`
/// arithmetic that they stand for; a factor that the file gives without a bound takes
/// [`Length::checked_mul`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Length(i64);

impl Length {
    /// A length of zero.
    pub const ZERO: Self = Self(0);

    /// Half-EMUs in one point.
    pub const UNITS_PER_POINT: i64 = 25_400;

    /// Half-EMUs in one twip, which is 1/20 of a point.
    pub const UNITS_PER_TWIP: i64 = 1_270;

    /// Half-EMUs in one half-point, the unit of font sizes.
    pub const UNITS_PER_HALF_POINT: i64 = 12_700;

    /// Half-EMUs in one eighth of a point, the unit of border widths.
    pub const UNITS_PER_EIGHTH_POINT: i64 = 3_175;

    /// Half-EMUs in one EMU, the DrawingML unit, which is 1/12,700 of a point.
    pub const UNITS_PER_EMU: i64 = 2;

    /// Half-EMUs in one dot of Word's device grid, which is 1/300 inch.
    pub const UNITS_PER_DOT: i64 = 6_096;

    /// Half-EMUs in one inch.
    pub const UNITS_PER_INCH: i64 = Self::UNITS_PER_POINT * scale::POINTS_PER_INCH;

    /// The largest distance from zero of a length that a constructor reads from a file: 2^46
    /// half-EMUs, about 2.8 billion points. It lies above the largest DrawingML coordinate
    /// (`ST_Coordinate`, 27,273,042,316,900 EMUs) and far above any page, and a sum of 131,071
    /// lengths within it fits in an `i64`, so the layout adds them with the plain operators.
    pub const FILE_LIMIT: i64 = 1 << 46;

    /// Makes a length from a count of half-EMUs.
    #[must_use]
    pub const fn from_units(units: i64) -> Self {
        Self(units)
    }

    /// Returns the length as a count of half-EMUs.
    #[must_use]
    pub const fn units(self) -> i64 {
        self.0
    }

    /// Makes a length from whole points.
    #[must_use]
    pub const fn from_points(points: i64) -> Option<Self> {
        Self::scaled(points, Self::UNITS_PER_POINT)
    }

    /// Makes a length from twips.
    #[must_use]
    pub const fn from_twips(twips: i64) -> Option<Self> {
        Self::scaled(twips, Self::UNITS_PER_TWIP)
    }

    /// Makes a length from half-points.
    #[must_use]
    pub const fn from_half_points(half_points: i64) -> Option<Self> {
        Self::scaled(half_points, Self::UNITS_PER_HALF_POINT)
    }

    /// Makes a length from eighths of a point.
    #[must_use]
    pub const fn from_eighth_points(eighth_points: i64) -> Option<Self> {
        Self::scaled(eighth_points, Self::UNITS_PER_EIGHTH_POINT)
    }

    /// Makes a length from EMUs.
    #[must_use]
    pub const fn from_emus(emus: i64) -> Option<Self> {
        Self::scaled(emus, Self::UNITS_PER_EMU)
    }

    /// Adds two lengths, or returns `None` when the sum does not fit.
    #[must_use]
    pub const fn checked_add(self, other: Self) -> Option<Self> {
        match self.0.checked_add(other.0) {
            Some(units) => Some(Self(units)),
            None => None,
        }
    }

    /// Subtracts a length, or returns `None` when the difference does not fit.
    #[must_use]
    pub const fn checked_sub(self, other: Self) -> Option<Self> {
        match self.0.checked_sub(other.0) {
            Some(units) => Some(Self(units)),
            None => None,
        }
    }

    /// Subtracts a length, and stays at the smallest or largest length when the difference does
    /// not fit, as a limit at the largest length does.
    #[must_use]
    pub const fn saturating_sub(self, other: Self) -> Self {
        Self(self.0.saturating_sub(other.0))
    }

    /// Multiplies by a factor that the file gives without a bound, such as a count, or returns
    /// `None` when the product does not fit.
    #[must_use]
    pub const fn checked_mul(self, factor: i64) -> Option<Self> {
        match self.0.checked_mul(factor) {
            Some(units) => Some(Self(units)),
            None => None,
        }
    }

    /// This length divided by `divisor`, rounded toward zero as integer division rounds: the
    /// named form of the division that the layout's bare half-EMU code did with `/`. A divisor
    /// of 0 panics, as that division does.
    #[must_use]
    pub const fn div_toward_zero(self, divisor: i64) -> Self {
        Self(self.0 / divisor)
    }

    /// This length rounded up to a whole number of steps of `units_per_step` half-EMUs, such as
    /// [`Self::UNITS_PER_TWIP`] for whole twips: a negative length rounds up toward zero. A step
    /// of 0 panics, as integer division by 0 does.
    #[must_use]
    pub const fn up_to_whole(self, units_per_step: i64) -> Self {
        Self((self.0 + units_per_step - 1).div_euclid(units_per_step) * units_per_step)
    }

    /// This length rounded down to a whole number of steps of `units_per_step` half-EMUs, such
    /// as [`Self::UNITS_PER_TWIP`] for whole twips: a negative length rounds down away from
    /// zero. A step of 0 panics, as integer division by 0 does.
    #[must_use]
    pub const fn down_to_whole(self, units_per_step: i64) -> Self {
        Self(self.0.div_euclid(units_per_step) * units_per_step)
    }

    /// This length rounded toward zero to a whole number of steps of `units_per_step`
    /// half-EMUs, such as [`Self::UNITS_PER_TWIP`] for whole twips: a positive length rounds
    /// down and a negative one up. A step of 0 panics, as integer division by 0 does.
    #[must_use]
    pub const fn toward_zero_whole(self, units_per_step: i64) -> Self {
        Self(self.0 / units_per_step * units_per_step)
    }

    /// This length rounded to the nearest whole number of steps of `units_per_step` half-EMUs,
    /// such as [`Self::UNITS_PER_TWIP`] for whole twips, a half step up toward the larger value,
    /// as [`div_round`] rounds. A step of 0 gives 0, as [`div_round`] does.
    #[must_use]
    pub const fn nearest_whole(self, units_per_step: i64) -> Self {
        Self(div_round(self.0, units_per_step) * units_per_step)
    }

    /// This length divided by `divisor` to the nearest half-EMU, as [`div_round`] rounds: the
    /// named form of the rounded division that the layout's bare half-EMU code did with
    /// [`div_round`]. A divisor of 0 gives 0, as [`div_round`] does.
    #[must_use]
    pub const fn div_round(self, divisor: i64) -> Self {
        Self(div_round(self.0, divisor))
    }

    /// This length divided by `divisor` to the nearest half-EMU, as [`checked_div_round`]
    /// rounds, for a length that a factor from a file scaled: `None` when the terms of the
    /// division do not fit in an `i64`, or when the divisor is 0.
    #[must_use]
    pub fn checked_div_round(self, divisor: i64) -> Option<Self> {
        checked_div_round(self.0, divisor).map(Self)
    }

    const fn scaled(value: i64, units_per_value: i64) -> Option<Self> {
        match value.checked_mul(units_per_value) {
            Some(units) if -Self::FILE_LIMIT <= units && units <= Self::FILE_LIMIT => {
                Some(Self(units))
            }
            _ => None,
        }
    }
}

impl Add for Length {
    type Output = Self;

    fn add(self, other: Self) -> Self {
        Self(self.0 + other.0)
    }
}

impl Sub for Length {
    type Output = Self;

    fn sub(self, other: Self) -> Self {
        Self(self.0 - other.0)
    }
}

impl AddAssign for Length {
    fn add_assign(&mut self, other: Self) {
        self.0 += other.0;
    }
}

impl SubAssign for Length {
    fn sub_assign(&mut self, other: Self) {
        self.0 -= other.0;
    }
}

impl Neg for Length {
    type Output = Self;

    fn neg(self) -> Self {
        Self(-self.0)
    }
}

/// A length times a factor that the code knows, or that a reader bounded at the border.
impl Mul<i64> for Length {
    type Output = Self;

    fn mul(self, factor: i64) -> Self {
        Self(self.0 * factor)
    }
}

impl Sum for Length {
    fn sum<I: Iterator<Item = Self>>(lengths: I) -> Self {
        lengths.fold(Self::ZERO, Add::add)
    }
}

/// `numerator / denominator` to the nearest whole number, with a half toward positive
/// infinity: 5 / 2 gives 3 and -5 / 2 gives -2. A denominator of 0 gives 0.
///
/// The three divisions are `#[inline]`: the layout calls them in its inner loops from other
/// crates, and the compiler does not inline a function across crates on its own when it calls
/// another one, here `div_euclid`.
#[must_use]
#[inline]
pub const fn div_round(numerator: i64, denominator: i64) -> i64 {
    if denominator == 0 {
        return 0;
    }
    (numerator * 2 + denominator).div_euclid(denominator * 2)
}

/// [`div_round`] for products that need more than 64 bits.
#[must_use]
#[inline]
pub const fn div_round_i128(numerator: i128, denominator: i128) -> i128 {
    if denominator == 0 {
        return 0;
    }
    (numerator * 2 + denominator).div_euclid(denominator * 2)
}

/// `value` as an `i64`, or the end of the range of an `i64` that is nearer to it: a count that
/// the arithmetic makes in `i128`.
#[must_use]
pub fn saturated(value: i128) -> i64 {
    i64::try_from(value).unwrap_or(if value < 0 { i64::MIN } else { i64::MAX })
}

/// The fraction `numerator / denominator` in its lowest terms: both divided by the greatest
/// common divisor of their magnitudes, so that each keeps its sign. A fraction of two zeros,
/// and one whose divisor does not fit in an `i128` (2^127, when each part is 0 or
/// `i128::MIN`), stays as it is.
#[must_use]
pub fn lowest_terms(numerator: i128, denominator: i128) -> (i128, i128) {
    let divisor = gcd(numerator.unsigned_abs(), denominator.unsigned_abs());
    match i128::try_from(divisor) {
        Ok(divisor) if divisor > 0 => (numerator / divisor, denominator / divisor),
        _ => (numerator, denominator),
    }
}

/// The greatest common divisor of `a` and `b`, by Euclid's algorithm: 0 only when both are 0.
const fn gcd(mut a: u128, mut b: u128) -> u128 {
    while b != 0 {
        (a, b) = (b, a % b);
    }
    a
}

/// [`div_round`] for values from a file: `None` when `2 × numerator + denominator` or
/// `2 × denominator` does not fit in an `i64`, or when the denominator is 0.
#[must_use]
#[inline]
pub fn checked_div_round(numerator: i64, denominator: i64) -> Option<i64> {
    numerator
        .checked_mul(2)?
        .checked_add(denominator)?
        .checked_div_euclid(denominator.checked_mul(2)?)
}

/// A count of things that the program holds, such as pages or the pieces of a line, as an
/// `i64`, for a factor of a length or a term of a sum. A count of a `Vec` is at most
/// `isize::MAX`, so it fits; the saturation at `i64::MAX` keeps the conversion total.
#[must_use]
#[inline]
pub fn count_factor(count: usize) -> i64 {
    i64::try_from(count).unwrap_or(i64::MAX)
}

#[cfg(test)]
mod tests {
    use super::{
        Length, checked_div_round, count_factor, div_round, div_round_i128, gcd, lowest_terms,
    };

    #[test]
    fn gives_a_count_as_an_i64() {
        assert_eq!(count_factor(0), 0);
        assert_eq!(count_factor(12), 12);
    }

    #[cfg(target_pointer_width = "64")]
    #[test]
    fn saturates_a_count_beyond_an_i64() {
        let largest = usize::try_from(i64::MAX).unwrap();
        assert_eq!(count_factor(largest), i64::MAX);
        assert_eq!(count_factor(largest + 1), i64::MAX);
        assert_eq!(count_factor(usize::MAX), i64::MAX);
    }

    #[test]
    fn divides_toward_zero() {
        let length = |units| Length::from_units(units);
        assert_eq!(length(5).div_toward_zero(2), length(2));
        assert_eq!(length(-5).div_toward_zero(2), length(-2));
        assert_eq!(length(6).div_toward_zero(3), length(2));
    }

    #[test]
    fn rounds_up_to_whole_steps() {
        let length = |units| Length::from_units(units);
        let twip = Length::UNITS_PER_TWIP;
        assert_eq!(length(0).up_to_whole(twip), length(0));
        assert_eq!(length(1).up_to_whole(twip), length(twip));
        assert_eq!(length(twip).up_to_whole(twip), length(twip));
        assert_eq!(length(twip + 1).up_to_whole(twip), length(2 * twip));
        assert_eq!(length(-1).up_to_whole(twip), length(0));
        assert_eq!(length(-twip - 1).up_to_whole(twip), length(-twip));
    }

    #[test]
    fn rounds_down_to_whole_steps() {
        let length = |units| Length::from_units(units);
        let twip = Length::UNITS_PER_TWIP;
        assert_eq!(length(0).down_to_whole(twip), length(0));
        assert_eq!(length(twip - 1).down_to_whole(twip), length(0));
        assert_eq!(length(twip).down_to_whole(twip), length(twip));
        assert_eq!(length(5 * twip / 2).down_to_whole(twip), length(2 * twip));
        assert_eq!(length(-1).down_to_whole(twip), length(-twip));
        assert_eq!(length(-twip).down_to_whole(twip), length(-twip));
    }

    /// The roundings to whole twips that the layout spelled out, toward zero with
    /// [`Length::div_toward_zero`] and to the nearest with [`Length::div_round`], give the values
    /// of [`Length::toward_zero_whole`] and [`Length::nearest_whole`], for negative and positive
    /// lengths.
    #[test]
    fn rounds_toward_zero_and_to_the_nearest_whole_step() {
        let twip = Length::UNITS_PER_TWIP;
        for units in -3 * twip..=3 * twip {
            let length = Length::from_units(units);
            assert_eq!(
                length.toward_zero_whole(twip),
                length.div_toward_zero(twip) * twip,
                "{units}"
            );
            assert_eq!(
                length.nearest_whole(twip),
                length.div_round(twip) * twip,
                "{units}"
            );
        }
    }

    #[test]
    fn rounds_a_part_step_toward_zero_and_a_half_step_up() {
        let length = |units| Length::from_units(units);
        let twip = Length::UNITS_PER_TWIP;
        assert_eq!(length(twip - 1).toward_zero_whole(twip), length(0));
        assert_eq!(length(1 - twip).toward_zero_whole(twip), length(0));
        assert_eq!(length(twip / 2).nearest_whole(twip), length(twip));
        assert_eq!(length(-twip / 2).nearest_whole(twip), length(0));
        assert_eq!(length(twip / 2 - 1).nearest_whole(twip), length(0));
    }

    /// The two roundings up that the layout spelled in half-EMUs, to whole twips in its tables
    /// (for any length) and to whole points in the limit step of balanced columns (for a length
    /// of 0 or more), give the values of [`Length::up_to_whole`].
    #[test]
    fn rounds_up_as_the_tables_and_the_balanced_columns_did() {
        let twip = Length::UNITS_PER_TWIP;
        let point = Length::UNITS_PER_POINT;
        let tables = |units: i64| (units + twip - 1).div_euclid(twip) * twip;
        let columns = |units: i64| (units + point - 1) / point * point;
        for units in (-3 * point..=3 * point).chain([1_000_003 * point - 1, 1_000_003 * point]) {
            let length = Length::from_units(units);
            assert_eq!(length.up_to_whole(twip).units(), tables(units), "{units}");
            if units >= 0 {
                assert_eq!(length.up_to_whole(point).units(), columns(units), "{units}");
            }
        }
    }

    #[test]
    fn divides_to_the_nearest_unit_when_it_fits() {
        let length = |units| Length::from_units(units);
        assert_eq!(length(5).div_round(2), length(3));
        assert_eq!(length(-5).div_round(2), length(-2));
        assert_eq!(length(5).div_round(0), Length::ZERO);
        assert_eq!(length(5).checked_div_round(2), Some(length(3)));
        assert_eq!(length(-5).checked_div_round(2), Some(length(-2)));
        assert_eq!(length(5).checked_div_round(0), None);
        assert_eq!(length(i64::MAX).checked_div_round(2), None);
    }

    #[test]
    fn subtracts_up_to_the_bounds() {
        let length = |units| Length::from_units(units);
        assert_eq!(length(5).saturating_sub(length(2)), length(3));
        assert_eq!(
            length(i64::MAX).saturating_sub(length(-1)),
            length(i64::MAX)
        );
        assert_eq!(length(i64::MIN).saturating_sub(length(1)), length(i64::MIN));
    }

    #[test]
    fn rounds_halves_up() {
        assert_eq!(div_round(5, 2), 3);
        assert_eq!(div_round(4, 2), 2);
        assert_eq!(div_round(7, 3), 2);
        assert_eq!(div_round(-5, 2), -2);
        assert_eq!(div_round(1, 0), 0);
    }

    #[test]
    fn rounds_halves_up_past_64_bits() {
        assert_eq!(div_round_i128(-5, 2), -2);
        // 3 times the largest i64 is odd, so its half ends in .5 and goes up.
        assert_eq!(
            div_round_i128(i128::from(i64::MAX) * 3, 2),
            13_835_058_055_282_163_711
        );
        assert_eq!(div_round_i128(1, 0), 0);
    }

    #[test]
    fn finds_the_greatest_common_divisor() {
        assert_eq!(gcd(12, 18), 6);
        assert_eq!(gcd(18, 12), 6);
        assert_eq!(gcd(17, 5), 1);
        assert_eq!((gcd(0, 5), gcd(5, 0), gcd(0, 0)), (5, 5, 0));
        // The magnitude of the lowest i128, 2^127, with 2^64.
        assert_eq!(gcd(i128::MIN.unsigned_abs(), 1 << 64), 1 << 64);
        assert_eq!(gcd(u128::MAX, u128::MAX), u128::MAX);
    }

    #[test]
    fn puts_a_fraction_in_its_lowest_terms_with_its_signs() {
        // The last three stay: two zeros, and two fractions whose divisor, 2^127, does not fit
        // in an i128.
        let fractions = [
            ((6, 4), (3, 2)),
            ((-6, 4), (-3, 2)),
            ((6, -4), (3, -2)),
            ((0, 5), (0, 1)),
            ((7, 1), (7, 1)),
            ((i128::MIN, 2), (i128::MIN / 2, 1)),
            ((0, 0), (0, 0)),
            ((i128::MIN, 0), (i128::MIN, 0)),
            ((i128::MIN, i128::MIN), (i128::MIN, i128::MIN)),
        ];
        for ((numerator, denominator), lowest) in fractions {
            assert_eq!(lowest_terms(numerator, denominator), lowest);
        }
    }

    #[test]
    fn checked_division_refuses_what_does_not_fit() {
        assert_eq!(checked_div_round(5, 2), Some(3));
        assert_eq!(checked_div_round(-5, 2), Some(-2));
        assert_eq!(checked_div_round(1, 0), None);
        assert_eq!(checked_div_round(i64::MAX / 2 - 1, 2), Some(i64::MAX / 4));
        assert_eq!(checked_div_round(i64::MAX / 2, 2), None);
        assert_eq!(checked_div_round(1, i64::MAX / 2 + 1), None);
    }

    #[test]
    fn units_round_trip() {
        assert_eq!(Length::from_units(-7).units(), -7);
        assert_eq!(Length::ZERO.units(), 0);
    }

    #[test]
    fn each_file_unit_has_its_exact_size() {
        assert_eq!(Length::from_points(1), Some(Length::from_units(25_400)));
        assert_eq!(Length::from_twips(1), Some(Length::from_units(1_270)));
        assert_eq!(
            Length::from_half_points(1),
            Some(Length::from_units(12_700))
        );
        assert_eq!(
            Length::from_eighth_points(1),
            Some(Length::from_units(3_175))
        );
        assert_eq!(Length::from_emus(1), Some(Length::from_units(2)));
    }

    #[test]
    fn file_units_agree_on_one_point_and_one_inch() {
        let point = Length::from_points(1);
        assert_eq!(Length::from_twips(20), point);
        assert_eq!(Length::from_half_points(2), point);
        assert_eq!(Length::from_eighth_points(8), point);
        assert_eq!(Length::from_emus(12_700), point);
        assert_eq!(Length::from_emus(914_400), Length::from_points(72));
        assert_eq!(Length::from_twips(1_440), Length::from_points(72));
    }

    #[test]
    fn negative_values_scale_exactly() {
        assert_eq!(Length::from_twips(-3), Some(Length::from_units(-3_810)));
    }

    #[test]
    fn scaling_that_overflows_returns_none() {
        assert_eq!(Length::from_points(i64::MAX), None);
        assert_eq!(Length::from_twips(i64::MIN), None);
        assert_eq!(Length::from_half_points(i64::MAX / 2), None);
        assert_eq!(Length::from_eighth_points(i64::MAX / 3), None);
        assert_eq!(Length::from_emus(i64::MAX), None);
    }

    #[test]
    fn file_constructors_refuse_lengths_beyond_the_limit() {
        let limit = Length::from_units(Length::FILE_LIMIT);
        assert_eq!(Length::from_emus(Length::FILE_LIMIT / 2), Some(limit));
        assert_eq!(Length::from_emus(-Length::FILE_LIMIT / 2), Some(-limit));
        assert_eq!(Length::from_emus(Length::FILE_LIMIT / 2 + 1), None);
        assert_eq!(Length::from_emus(-Length::FILE_LIMIT / 2 - 1), None);
        // The largest DrawingML coordinate reads.
        assert!(Length::from_emus(27_273_042_316_900).is_some());
        assert_eq!(Length::from_twips(i64::MIN / 1_270), None);
    }

    #[test]
    fn operators_act_as_the_arithmetic_of_half_emus() {
        let (a, b) = (Length::from_units(40), Length::from_units(15));
        assert_eq!(a + b, Length::from_units(55));
        assert_eq!(b - a, Length::from_units(-25));
        assert_eq!(-a, Length::from_units(-40));
        assert_eq!(a * 3, Length::from_units(120));
        let mut c = a;
        c += b;
        c -= a + a;
        assert_eq!(c, Length::from_units(-25));
        assert_eq!(
            [a, b, b].into_iter().sum::<Length>(),
            Length::from_units(70)
        );
        assert_eq!(
            Length::from_points(72),
            Some(Length::from_units(Length::UNITS_PER_INCH))
        );
    }

    #[test]
    fn checked_mul_refuses_products_that_do_not_fit() {
        let a = Length::from_units(40);
        assert_eq!(a.checked_mul(-2), Some(Length::from_units(-80)));
        assert_eq!(Length::from_units(i64::MAX / 2 + 1).checked_mul(2), None);
        // A sum of 131,071 lengths at the limit fits.
        let most = Length::from_units(Length::FILE_LIMIT) * 131_071;
        assert_eq!(
            most.checked_add(Length::from_units(Length::FILE_LIMIT)),
            None
        );
    }

    #[test]
    fn checked_add_and_sub() {
        let a = Length::from_units(40);
        let b = Length::from_units(15);
        assert_eq!(a.checked_add(b), Some(Length::from_units(55)));
        assert_eq!(a.checked_sub(b), Some(Length::from_units(25)));
        assert_eq!(b.checked_sub(a), Some(Length::from_units(-25)));
        assert_eq!(
            Length::from_units(i64::MAX).checked_add(Length::from_units(1)),
            None
        );
        assert_eq!(
            Length::from_units(i64::MIN).checked_sub(Length::from_units(1)),
            None
        );
    }
}