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