1#![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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
28pub struct Length(i64);
29
30impl Length {
31 pub const ZERO: Self = Self(0);
33
34 pub const UNITS_PER_POINT: i64 = 25_400;
36
37 pub const UNITS_PER_TWIP: i64 = 1_270;
39
40 pub const UNITS_PER_HALF_POINT: i64 = 12_700;
42
43 pub const UNITS_PER_EIGHTH_POINT: i64 = 3_175;
45
46 pub const UNITS_PER_EMU: i64 = 2;
48
49 pub const UNITS_PER_DOT: i64 = 6_096;
51
52 pub const UNITS_PER_INCH: i64 = Self::UNITS_PER_POINT * scale::POINTS_PER_INCH;
54
55 pub const FILE_LIMIT: i64 = 1 << 46;
60
61 #[must_use]
63 pub const fn from_units(units: i64) -> Self {
64 Self(units)
65 }
66
67 #[must_use]
69 pub const fn units(self) -> i64 {
70 self.0
71 }
72
73 #[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 #[must_use]
87 pub const fn from_points(points: i64) -> Option<Self> {
88 Self::scaled(points, Self::UNITS_PER_POINT)
89 }
90
91 #[must_use]
93 pub const fn from_twips(twips: i64) -> Option<Self> {
94 Self::scaled(twips, Self::UNITS_PER_TWIP)
95 }
96
97 #[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 #[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 #[must_use]
111 pub const fn from_emus(emus: i64) -> Option<Self> {
112 Self::scaled(emus, Self::UNITS_PER_EMU)
113 }
114
115 #[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 #[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 #[must_use]
136 pub const fn saturating_sub(self, other: Self) -> Self {
137 Self(self.0.saturating_sub(other.0))
138 }
139
140 #[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 #[must_use]
154 pub const fn div_toward_zero(self, divisor: i64) -> Self {
155 Self(self.0 / divisor)
156 }
157
158 #[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 #[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 #[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 #[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 #[must_use]
194 pub const fn div_round(self, divisor: i64) -> Self {
195 Self(div_round(self.0, divisor))
196 }
197
198 #[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
252impl 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#[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#[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#[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#[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
312const 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#[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#[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 #[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 #[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 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 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 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 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 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}