Skip to main content

f_office_units/
lib.rs

1//! Integer lengths for layout.
2//!
3//! F-Office lays out pages in one integer unit, half an EMU, which is 1/25,400 of a point.
4//! Office Open XML files give lengths in twips, half-points, eighth-points and EMUs, and each
5//! of these is a whole number of half-EMUs, so a value read from a file converts without
6//! rounding. Integer layout also gives the same result on every machine.
7
8#![deny(clippy::float_arithmetic)]
9
10use std::iter::Sum;
11use std::ops::{Add, AddAssign, Mul, Neg, Sub, SubAssign};
12
13pub mod binary32;
14mod edges;
15pub mod fixed;
16pub mod measure;
17pub mod scale;
18
19pub use edges::Edges;
20
21/// A length in half-EMUs, which is 1/25,400 of a point.
22///
23/// The constructors that scale a value from a file return `None` when the result lies beyond
24/// [`Length::FILE_LIMIT`], so untrusted input cannot overflow. The operators behave as the `i64`
25/// arithmetic that they stand for; a factor that the file gives without a bound takes
26/// [`Length::checked_mul`].
27#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
28pub struct Length(i64);
29
30impl Length {
31    /// A length of zero.
32    pub const ZERO: Self = Self(0);
33
34    /// Half-EMUs in one point.
35    pub const UNITS_PER_POINT: i64 = 25_400;
36
37    /// Half-EMUs in one twip, which is 1/20 of a point.
38    pub const UNITS_PER_TWIP: i64 = 1_270;
39
40    /// Half-EMUs in one half-point, the unit of font sizes.
41    pub const UNITS_PER_HALF_POINT: i64 = 12_700;
42
43    /// Half-EMUs in one eighth of a point, the unit of border widths.
44    pub const UNITS_PER_EIGHTH_POINT: i64 = 3_175;
45
46    /// Half-EMUs in one EMU, the DrawingML unit, which is 1/12,700 of a point.
47    pub const UNITS_PER_EMU: i64 = 2;
48
49    /// Half-EMUs in one dot of Word's device grid, which is 1/300 inch.
50    pub const UNITS_PER_DOT: i64 = 6_096;
51
52    /// Half-EMUs in one inch.
53    pub const UNITS_PER_INCH: i64 = Self::UNITS_PER_POINT * scale::POINTS_PER_INCH;
54
55    /// The largest distance from zero of a length that a constructor reads from a file: 2^46
56    /// half-EMUs, about 2.8 billion points. It lies above the largest DrawingML coordinate
57    /// (`ST_Coordinate`, 27,273,042,316,900 EMUs) and far above any page, and a sum of 131,071
58    /// lengths within it fits in an `i64`, so the layout adds them with the plain operators.
59    pub const FILE_LIMIT: i64 = 1 << 46;
60
61    /// Makes a length from a count of half-EMUs.
62    #[must_use]
63    pub const fn from_units(units: i64) -> Self {
64        Self(units)
65    }
66
67    /// Returns the length as a count of half-EMUs.
68    #[must_use]
69    pub const fn units(self) -> i64 {
70        self.0
71    }
72
73    /// Makes a length from whole points.
74    #[must_use]
75    pub const fn from_points(points: i64) -> Option<Self> {
76        Self::scaled(points, Self::UNITS_PER_POINT)
77    }
78
79    /// Makes a length from twips.
80    #[must_use]
81    pub const fn from_twips(twips: i64) -> Option<Self> {
82        Self::scaled(twips, Self::UNITS_PER_TWIP)
83    }
84
85    /// Makes a length from half-points.
86    #[must_use]
87    pub const fn from_half_points(half_points: i64) -> Option<Self> {
88        Self::scaled(half_points, Self::UNITS_PER_HALF_POINT)
89    }
90
91    /// Makes a length from eighths of a point.
92    #[must_use]
93    pub const fn from_eighth_points(eighth_points: i64) -> Option<Self> {
94        Self::scaled(eighth_points, Self::UNITS_PER_EIGHTH_POINT)
95    }
96
97    /// Makes a length from EMUs.
98    #[must_use]
99    pub const fn from_emus(emus: i64) -> Option<Self> {
100        Self::scaled(emus, Self::UNITS_PER_EMU)
101    }
102
103    /// Adds two lengths, or returns `None` when the sum does not fit.
104    #[must_use]
105    pub const fn checked_add(self, other: Self) -> Option<Self> {
106        match self.0.checked_add(other.0) {
107            Some(units) => Some(Self(units)),
108            None => None,
109        }
110    }
111
112    /// Subtracts a length, or returns `None` when the difference does not fit.
113    #[must_use]
114    pub const fn checked_sub(self, other: Self) -> Option<Self> {
115        match self.0.checked_sub(other.0) {
116            Some(units) => Some(Self(units)),
117            None => None,
118        }
119    }
120
121    /// Subtracts a length, and stays at the smallest or largest length when the difference does
122    /// not fit, as a limit at the largest length does.
123    #[must_use]
124    pub const fn saturating_sub(self, other: Self) -> Self {
125        Self(self.0.saturating_sub(other.0))
126    }
127
128    /// Multiplies by a factor that the file gives without a bound, such as a count, or returns
129    /// `None` when the product does not fit.
130    #[must_use]
131    pub const fn checked_mul(self, factor: i64) -> Option<Self> {
132        match self.0.checked_mul(factor) {
133            Some(units) => Some(Self(units)),
134            None => None,
135        }
136    }
137
138    /// This length divided by `divisor`, rounded toward zero as integer division rounds: the
139    /// named form of the division that the layout's bare half-EMU code did with `/`. A divisor
140    /// of 0 panics, as that division does.
141    #[must_use]
142    pub const fn div_toward_zero(self, divisor: i64) -> Self {
143        Self(self.0 / divisor)
144    }
145
146    /// This length rounded up to a whole number of steps of `units_per_step` half-EMUs, such as
147    /// [`Self::UNITS_PER_TWIP`] for whole twips: a negative length rounds up toward zero. A step
148    /// of 0 panics, as integer division by 0 does.
149    #[must_use]
150    pub const fn up_to_whole(self, units_per_step: i64) -> Self {
151        Self((self.0 + units_per_step - 1).div_euclid(units_per_step) * units_per_step)
152    }
153
154    /// This length rounded down to a whole number of steps of `units_per_step` half-EMUs, such
155    /// as [`Self::UNITS_PER_TWIP`] for whole twips: a negative length rounds down away from
156    /// zero. A step of 0 panics, as integer division by 0 does.
157    #[must_use]
158    pub const fn down_to_whole(self, units_per_step: i64) -> Self {
159        Self(self.0.div_euclid(units_per_step) * units_per_step)
160    }
161
162    /// This length rounded toward zero to a whole number of steps of `units_per_step`
163    /// half-EMUs, such as [`Self::UNITS_PER_TWIP`] for whole twips: a positive length rounds
164    /// down and a negative one up. A step of 0 panics, as integer division by 0 does.
165    #[must_use]
166    pub const fn toward_zero_whole(self, units_per_step: i64) -> Self {
167        Self(self.0 / units_per_step * units_per_step)
168    }
169
170    /// This length rounded to the nearest whole number of steps of `units_per_step` half-EMUs,
171    /// such as [`Self::UNITS_PER_TWIP`] for whole twips, a half step up toward the larger value,
172    /// as [`div_round`] rounds. A step of 0 gives 0, as [`div_round`] does.
173    #[must_use]
174    pub const fn nearest_whole(self, units_per_step: i64) -> Self {
175        Self(div_round(self.0, units_per_step) * units_per_step)
176    }
177
178    /// This length divided by `divisor` to the nearest half-EMU, as [`div_round`] rounds: the
179    /// named form of the rounded division that the layout's bare half-EMU code did with
180    /// [`div_round`]. A divisor of 0 gives 0, as [`div_round`] does.
181    #[must_use]
182    pub const fn div_round(self, divisor: i64) -> Self {
183        Self(div_round(self.0, divisor))
184    }
185
186    /// This length divided by `divisor` to the nearest half-EMU, as [`checked_div_round`]
187    /// rounds, for a length that a factor from a file scaled: `None` when the terms of the
188    /// division do not fit in an `i64`, or when the divisor is 0.
189    #[must_use]
190    pub fn checked_div_round(self, divisor: i64) -> Option<Self> {
191        checked_div_round(self.0, divisor).map(Self)
192    }
193
194    const fn scaled(value: i64, units_per_value: i64) -> Option<Self> {
195        match value.checked_mul(units_per_value) {
196            Some(units) if -Self::FILE_LIMIT <= units && units <= Self::FILE_LIMIT => {
197                Some(Self(units))
198            }
199            _ => None,
200        }
201    }
202}
203
204impl Add for Length {
205    type Output = Self;
206
207    fn add(self, other: Self) -> Self {
208        Self(self.0 + other.0)
209    }
210}
211
212impl Sub for Length {
213    type Output = Self;
214
215    fn sub(self, other: Self) -> Self {
216        Self(self.0 - other.0)
217    }
218}
219
220impl AddAssign for Length {
221    fn add_assign(&mut self, other: Self) {
222        self.0 += other.0;
223    }
224}
225
226impl SubAssign for Length {
227    fn sub_assign(&mut self, other: Self) {
228        self.0 -= other.0;
229    }
230}
231
232impl Neg for Length {
233    type Output = Self;
234
235    fn neg(self) -> Self {
236        Self(-self.0)
237    }
238}
239
240/// A length times a factor that the code knows, or that a reader bounded at the border.
241impl Mul<i64> for Length {
242    type Output = Self;
243
244    fn mul(self, factor: i64) -> Self {
245        Self(self.0 * factor)
246    }
247}
248
249impl Sum for Length {
250    fn sum<I: Iterator<Item = Self>>(lengths: I) -> Self {
251        lengths.fold(Self::ZERO, Add::add)
252    }
253}
254
255/// `numerator / denominator` to the nearest whole number, with a half toward positive
256/// infinity: 5 / 2 gives 3 and -5 / 2 gives -2. A denominator of 0 gives 0.
257///
258/// The three divisions are `#[inline]`: the layout calls them in its inner loops from other
259/// crates, and the compiler does not inline a function across crates on its own when it calls
260/// another one, here `div_euclid`.
261#[must_use]
262#[inline]
263pub const fn div_round(numerator: i64, denominator: i64) -> i64 {
264    if denominator == 0 {
265        return 0;
266    }
267    (numerator * 2 + denominator).div_euclid(denominator * 2)
268}
269
270/// [`div_round`] for products that need more than 64 bits.
271#[must_use]
272#[inline]
273pub const fn div_round_i128(numerator: i128, denominator: i128) -> i128 {
274    if denominator == 0 {
275        return 0;
276    }
277    (numerator * 2 + denominator).div_euclid(denominator * 2)
278}
279
280/// `value` as an `i64`, or the end of the range of an `i64` that is nearer to it: a count that
281/// the arithmetic makes in `i128`.
282#[must_use]
283pub fn saturated(value: i128) -> i64 {
284    i64::try_from(value).unwrap_or(if value < 0 { i64::MIN } else { i64::MAX })
285}
286
287/// The fraction `numerator / denominator` in its lowest terms: both divided by the greatest
288/// common divisor of their magnitudes, so that each keeps its sign. A fraction of two zeros,
289/// and one whose divisor does not fit in an `i128` (2^127, when each part is 0 or
290/// `i128::MIN`), stays as it is.
291#[must_use]
292pub fn lowest_terms(numerator: i128, denominator: i128) -> (i128, i128) {
293    let divisor = gcd(numerator.unsigned_abs(), denominator.unsigned_abs());
294    match i128::try_from(divisor) {
295        Ok(divisor) if divisor > 0 => (numerator / divisor, denominator / divisor),
296        _ => (numerator, denominator),
297    }
298}
299
300/// The greatest common divisor of `a` and `b`, by Euclid's algorithm: 0 only when both are 0.
301const fn gcd(mut a: u128, mut b: u128) -> u128 {
302    while b != 0 {
303        (a, b) = (b, a % b);
304    }
305    a
306}
307
308/// [`div_round`] for values from a file: `None` when `2 × numerator + denominator` or
309/// `2 × denominator` does not fit in an `i64`, or when the denominator is 0.
310#[must_use]
311#[inline]
312pub fn checked_div_round(numerator: i64, denominator: i64) -> Option<i64> {
313    numerator
314        .checked_mul(2)?
315        .checked_add(denominator)?
316        .checked_div_euclid(denominator.checked_mul(2)?)
317}
318
319/// A count of things that the program holds, such as pages or the pieces of a line, as an
320/// `i64`, for a factor of a length or a term of a sum. A count of a `Vec` is at most
321/// `isize::MAX`, so it fits; the saturation at `i64::MAX` keeps the conversion total.
322#[must_use]
323#[inline]
324pub fn count_factor(count: usize) -> i64 {
325    i64::try_from(count).unwrap_or(i64::MAX)
326}
327
328#[cfg(test)]
329mod tests {
330    use super::{
331        Length, checked_div_round, count_factor, div_round, div_round_i128, gcd, lowest_terms,
332    };
333
334    #[test]
335    fn gives_a_count_as_an_i64() {
336        assert_eq!(count_factor(0), 0);
337        assert_eq!(count_factor(12), 12);
338    }
339
340    #[cfg(target_pointer_width = "64")]
341    #[test]
342    fn saturates_a_count_beyond_an_i64() {
343        let largest = usize::try_from(i64::MAX).unwrap();
344        assert_eq!(count_factor(largest), i64::MAX);
345        assert_eq!(count_factor(largest + 1), i64::MAX);
346        assert_eq!(count_factor(usize::MAX), i64::MAX);
347    }
348
349    #[test]
350    fn divides_toward_zero() {
351        let length = |units| Length::from_units(units);
352        assert_eq!(length(5).div_toward_zero(2), length(2));
353        assert_eq!(length(-5).div_toward_zero(2), length(-2));
354        assert_eq!(length(6).div_toward_zero(3), length(2));
355    }
356
357    #[test]
358    fn rounds_up_to_whole_steps() {
359        let length = |units| Length::from_units(units);
360        let twip = Length::UNITS_PER_TWIP;
361        assert_eq!(length(0).up_to_whole(twip), length(0));
362        assert_eq!(length(1).up_to_whole(twip), length(twip));
363        assert_eq!(length(twip).up_to_whole(twip), length(twip));
364        assert_eq!(length(twip + 1).up_to_whole(twip), length(2 * twip));
365        assert_eq!(length(-1).up_to_whole(twip), length(0));
366        assert_eq!(length(-twip - 1).up_to_whole(twip), length(-twip));
367    }
368
369    #[test]
370    fn rounds_down_to_whole_steps() {
371        let length = |units| Length::from_units(units);
372        let twip = Length::UNITS_PER_TWIP;
373        assert_eq!(length(0).down_to_whole(twip), length(0));
374        assert_eq!(length(twip - 1).down_to_whole(twip), length(0));
375        assert_eq!(length(twip).down_to_whole(twip), length(twip));
376        assert_eq!(length(5 * twip / 2).down_to_whole(twip), length(2 * twip));
377        assert_eq!(length(-1).down_to_whole(twip), length(-twip));
378        assert_eq!(length(-twip).down_to_whole(twip), length(-twip));
379    }
380
381    /// The roundings to whole twips that the layout spelled out, toward zero with
382    /// [`Length::div_toward_zero`] and to the nearest with [`Length::div_round`], give the values
383    /// of [`Length::toward_zero_whole`] and [`Length::nearest_whole`], for negative and positive
384    /// lengths.
385    #[test]
386    fn rounds_toward_zero_and_to_the_nearest_whole_step() {
387        let twip = Length::UNITS_PER_TWIP;
388        for units in -3 * twip..=3 * twip {
389            let length = Length::from_units(units);
390            assert_eq!(
391                length.toward_zero_whole(twip),
392                length.div_toward_zero(twip) * twip,
393                "{units}"
394            );
395            assert_eq!(
396                length.nearest_whole(twip),
397                length.div_round(twip) * twip,
398                "{units}"
399            );
400        }
401    }
402
403    #[test]
404    fn rounds_a_part_step_toward_zero_and_a_half_step_up() {
405        let length = |units| Length::from_units(units);
406        let twip = Length::UNITS_PER_TWIP;
407        assert_eq!(length(twip - 1).toward_zero_whole(twip), length(0));
408        assert_eq!(length(1 - twip).toward_zero_whole(twip), length(0));
409        assert_eq!(length(twip / 2).nearest_whole(twip), length(twip));
410        assert_eq!(length(-twip / 2).nearest_whole(twip), length(0));
411        assert_eq!(length(twip / 2 - 1).nearest_whole(twip), length(0));
412    }
413
414    /// The two roundings up that the layout spelled in half-EMUs, to whole twips in its tables
415    /// (for any length) and to whole points in the limit step of balanced columns (for a length
416    /// of 0 or more), give the values of [`Length::up_to_whole`].
417    #[test]
418    fn rounds_up_as_the_tables_and_the_balanced_columns_did() {
419        let twip = Length::UNITS_PER_TWIP;
420        let point = Length::UNITS_PER_POINT;
421        let tables = |units: i64| (units + twip - 1).div_euclid(twip) * twip;
422        let columns = |units: i64| (units + point - 1) / point * point;
423        for units in (-3 * point..=3 * point).chain([1_000_003 * point - 1, 1_000_003 * point]) {
424            let length = Length::from_units(units);
425            assert_eq!(length.up_to_whole(twip).units(), tables(units), "{units}");
426            if units >= 0 {
427                assert_eq!(length.up_to_whole(point).units(), columns(units), "{units}");
428            }
429        }
430    }
431
432    #[test]
433    fn divides_to_the_nearest_unit_when_it_fits() {
434        let length = |units| Length::from_units(units);
435        assert_eq!(length(5).div_round(2), length(3));
436        assert_eq!(length(-5).div_round(2), length(-2));
437        assert_eq!(length(5).div_round(0), Length::ZERO);
438        assert_eq!(length(5).checked_div_round(2), Some(length(3)));
439        assert_eq!(length(-5).checked_div_round(2), Some(length(-2)));
440        assert_eq!(length(5).checked_div_round(0), None);
441        assert_eq!(length(i64::MAX).checked_div_round(2), None);
442    }
443
444    #[test]
445    fn subtracts_up_to_the_bounds() {
446        let length = |units| Length::from_units(units);
447        assert_eq!(length(5).saturating_sub(length(2)), length(3));
448        assert_eq!(
449            length(i64::MAX).saturating_sub(length(-1)),
450            length(i64::MAX)
451        );
452        assert_eq!(length(i64::MIN).saturating_sub(length(1)), length(i64::MIN));
453    }
454
455    #[test]
456    fn rounds_halves_up() {
457        assert_eq!(div_round(5, 2), 3);
458        assert_eq!(div_round(4, 2), 2);
459        assert_eq!(div_round(7, 3), 2);
460        assert_eq!(div_round(-5, 2), -2);
461        assert_eq!(div_round(1, 0), 0);
462    }
463
464    #[test]
465    fn rounds_halves_up_past_64_bits() {
466        assert_eq!(div_round_i128(-5, 2), -2);
467        // 3 times the largest i64 is odd, so its half ends in .5 and goes up.
468        assert_eq!(
469            div_round_i128(i128::from(i64::MAX) * 3, 2),
470            13_835_058_055_282_163_711
471        );
472        assert_eq!(div_round_i128(1, 0), 0);
473    }
474
475    #[test]
476    fn finds_the_greatest_common_divisor() {
477        assert_eq!(gcd(12, 18), 6);
478        assert_eq!(gcd(18, 12), 6);
479        assert_eq!(gcd(17, 5), 1);
480        assert_eq!((gcd(0, 5), gcd(5, 0), gcd(0, 0)), (5, 5, 0));
481        // The magnitude of the lowest i128, 2^127, with 2^64.
482        assert_eq!(gcd(i128::MIN.unsigned_abs(), 1 << 64), 1 << 64);
483        assert_eq!(gcd(u128::MAX, u128::MAX), u128::MAX);
484    }
485
486    #[test]
487    fn puts_a_fraction_in_its_lowest_terms_with_its_signs() {
488        // The last three stay: two zeros, and two fractions whose divisor, 2^127, does not fit
489        // in an i128.
490        let fractions = [
491            ((6, 4), (3, 2)),
492            ((-6, 4), (-3, 2)),
493            ((6, -4), (3, -2)),
494            ((0, 5), (0, 1)),
495            ((7, 1), (7, 1)),
496            ((i128::MIN, 2), (i128::MIN / 2, 1)),
497            ((0, 0), (0, 0)),
498            ((i128::MIN, 0), (i128::MIN, 0)),
499            ((i128::MIN, i128::MIN), (i128::MIN, i128::MIN)),
500        ];
501        for ((numerator, denominator), lowest) in fractions {
502            assert_eq!(lowest_terms(numerator, denominator), lowest);
503        }
504    }
505
506    #[test]
507    fn checked_division_refuses_what_does_not_fit() {
508        assert_eq!(checked_div_round(5, 2), Some(3));
509        assert_eq!(checked_div_round(-5, 2), Some(-2));
510        assert_eq!(checked_div_round(1, 0), None);
511        assert_eq!(checked_div_round(i64::MAX / 2 - 1, 2), Some(i64::MAX / 4));
512        assert_eq!(checked_div_round(i64::MAX / 2, 2), None);
513        assert_eq!(checked_div_round(1, i64::MAX / 2 + 1), None);
514    }
515
516    #[test]
517    fn units_round_trip() {
518        assert_eq!(Length::from_units(-7).units(), -7);
519        assert_eq!(Length::ZERO.units(), 0);
520    }
521
522    #[test]
523    fn each_file_unit_has_its_exact_size() {
524        assert_eq!(Length::from_points(1), Some(Length::from_units(25_400)));
525        assert_eq!(Length::from_twips(1), Some(Length::from_units(1_270)));
526        assert_eq!(
527            Length::from_half_points(1),
528            Some(Length::from_units(12_700))
529        );
530        assert_eq!(
531            Length::from_eighth_points(1),
532            Some(Length::from_units(3_175))
533        );
534        assert_eq!(Length::from_emus(1), Some(Length::from_units(2)));
535    }
536
537    #[test]
538    fn file_units_agree_on_one_point_and_one_inch() {
539        let point = Length::from_points(1);
540        assert_eq!(Length::from_twips(20), point);
541        assert_eq!(Length::from_half_points(2), point);
542        assert_eq!(Length::from_eighth_points(8), point);
543        assert_eq!(Length::from_emus(12_700), point);
544        assert_eq!(Length::from_emus(914_400), Length::from_points(72));
545        assert_eq!(Length::from_twips(1_440), Length::from_points(72));
546    }
547
548    #[test]
549    fn negative_values_scale_exactly() {
550        assert_eq!(Length::from_twips(-3), Some(Length::from_units(-3_810)));
551    }
552
553    #[test]
554    fn scaling_that_overflows_returns_none() {
555        assert_eq!(Length::from_points(i64::MAX), None);
556        assert_eq!(Length::from_twips(i64::MIN), None);
557        assert_eq!(Length::from_half_points(i64::MAX / 2), None);
558        assert_eq!(Length::from_eighth_points(i64::MAX / 3), None);
559        assert_eq!(Length::from_emus(i64::MAX), None);
560    }
561
562    #[test]
563    fn file_constructors_refuse_lengths_beyond_the_limit() {
564        let limit = Length::from_units(Length::FILE_LIMIT);
565        assert_eq!(Length::from_emus(Length::FILE_LIMIT / 2), Some(limit));
566        assert_eq!(Length::from_emus(-Length::FILE_LIMIT / 2), Some(-limit));
567        assert_eq!(Length::from_emus(Length::FILE_LIMIT / 2 + 1), None);
568        assert_eq!(Length::from_emus(-Length::FILE_LIMIT / 2 - 1), None);
569        // The largest DrawingML coordinate reads.
570        assert!(Length::from_emus(27_273_042_316_900).is_some());
571        assert_eq!(Length::from_twips(i64::MIN / 1_270), None);
572    }
573
574    #[test]
575    fn operators_act_as_the_arithmetic_of_half_emus() {
576        let (a, b) = (Length::from_units(40), Length::from_units(15));
577        assert_eq!(a + b, Length::from_units(55));
578        assert_eq!(b - a, Length::from_units(-25));
579        assert_eq!(-a, Length::from_units(-40));
580        assert_eq!(a * 3, Length::from_units(120));
581        let mut c = a;
582        c += b;
583        c -= a + a;
584        assert_eq!(c, Length::from_units(-25));
585        assert_eq!(
586            [a, b, b].into_iter().sum::<Length>(),
587            Length::from_units(70)
588        );
589        assert_eq!(
590            Length::from_points(72),
591            Some(Length::from_units(Length::UNITS_PER_INCH))
592        );
593    }
594
595    #[test]
596    fn checked_mul_refuses_products_that_do_not_fit() {
597        let a = Length::from_units(40);
598        assert_eq!(a.checked_mul(-2), Some(Length::from_units(-80)));
599        assert_eq!(Length::from_units(i64::MAX / 2 + 1).checked_mul(2), None);
600        // A sum of 131,071 lengths at the limit fits.
601        let most = Length::from_units(Length::FILE_LIMIT) * 131_071;
602        assert_eq!(
603            most.checked_add(Length::from_units(Length::FILE_LIMIT)),
604            None
605        );
606    }
607
608    #[test]
609    fn checked_add_and_sub() {
610        let a = Length::from_units(40);
611        let b = Length::from_units(15);
612        assert_eq!(a.checked_add(b), Some(Length::from_units(55)));
613        assert_eq!(a.checked_sub(b), Some(Length::from_units(25)));
614        assert_eq!(b.checked_sub(a), Some(Length::from_units(-25)));
615        assert_eq!(
616            Length::from_units(i64::MAX).checked_add(Length::from_units(1)),
617            None
618        );
619        assert_eq!(
620            Length::from_units(i64::MIN).checked_sub(Length::from_units(1)),
621            None
622        );
623    }
624}