1use core::cmp::Ordering;
7use core::fmt;
8use core::ops::{Add, Div, Mul, Neg, Sub};
9
10use crate::error::Error;
11
12pub const DIM_PREC: usize = 256;
14
15fn gcd_u(mut a: u128, mut b: u128) -> u128 {
16 while b != 0 {
17 let t = a % b;
18 a = b;
19 b = t;
20 }
21 a
22}
23
24const UNITS: [(&str, i128); 3] = [("em", 1), ("mu", 18), ("pt", 10)];
28
29#[derive(Clone, Debug)]
43pub struct Dim {
44 num: i128,
45 den: i128,
46 nan: bool,
47}
48
49impl Dim {
50 fn raw(num: i128, den: i128) -> Self {
51 if den == 0 {
52 return Self::nan();
53 }
54 if num == 0 {
55 return Self {
56 num: 0,
57 den: 1,
58 nan: false,
59 };
60 }
61 let g = gcd_u(num.unsigned_abs(), den.unsigned_abs());
62 let g = i128::try_from(g).unwrap_or(1);
63 let mut n = num / g;
64 let mut d = den / g;
65 if d < 0 {
66 n = -n;
67 d = -d;
68 }
69 Self {
70 num: n,
71 den: d,
72 nan: false,
73 }
74 }
75
76 fn nan() -> Self {
77 Self {
78 num: 0,
79 den: 1,
80 nan: true,
81 }
82 }
83
84 fn binop(
85 a: &Self,
86 b: &Self,
87 f: impl Fn(i128, i128, i128, i128) -> Option<(i128, i128)>,
88 ) -> Self {
89 if a.nan || b.nan {
90 return Self::nan();
91 }
92 match f(a.num, a.den, b.num, b.den) {
93 Some((n, d)) => Self::raw(n, d),
94 None => Self::nan(),
95 }
96 }
97
98 #[must_use]
100 pub fn zero() -> Self {
101 Self::raw(0, 1)
102 }
103
104 #[must_use]
106 pub fn one() -> Self {
107 Self::raw(1, 1)
108 }
109
110 #[must_use]
112 pub fn from_i64(v: i64) -> Self {
113 Self::raw(i128::from(v), 1)
114 }
115
116 #[must_use]
118 pub fn ratio(num: i64, den: i64) -> Self {
119 Self::raw(i128::from(num), i128::from(den))
120 }
121
122 #[must_use]
124 pub fn parse(s: &str) -> Self {
125 let t = s.trim();
126 if t.is_empty() || t.eq_ignore_ascii_case("nan") {
127 return Self::nan();
128 }
129 let mut rest = t;
130 let neg = if let Some(r) = rest.strip_prefix('-') {
131 rest = r;
132 true
133 } else if let Some(r) = rest.strip_prefix('+') {
134 rest = r;
135 false
136 } else {
137 false
138 };
139 let (mant, exp_s) = match rest.find(['e', 'E']) {
140 Some(i) => (&rest[..i], Some(&rest[i + 1..])),
141 None => (rest, None),
142 };
143 let (ip, fp) = match mant.find('.') {
144 Some(i) => (&mant[..i], &mant[i + 1..]),
145 None => (mant, ""),
146 };
147 if ip.is_empty() && fp.is_empty() {
148 return Self::nan();
149 }
150 if !ip.chars().all(|c| c.is_ascii_digit()) || !fp.chars().all(|c| c.is_ascii_digit()) {
151 return Self::nan();
152 }
153 let mut num: i128 = 0;
154 for c in ip.bytes().chain(fp.bytes()) {
155 let d = i128::from(c - b'0');
156 num = match num.checked_mul(10).and_then(|n| n.checked_add(d)) {
157 Some(n) => n,
158 None => return Self::nan(),
159 };
160 }
161 let mut den = 1i128;
162 for _ in 0..fp.len() {
163 den = match den.checked_mul(10) {
164 Some(d) => d,
165 None => return Self::nan(),
166 };
167 }
168 if let Some(es) = exp_s {
169 let e: i32 = match es.parse() {
170 Ok(v) => v,
171 Err(_) => return Self::nan(),
172 };
173 if e > 0 {
174 for _ in 0..e {
175 num = match num.checked_mul(10) {
176 Some(n) => n,
177 None => return Self::nan(),
178 };
179 }
180 } else {
181 for _ in 0..(-e) {
182 den = match den.checked_mul(10) {
183 Some(d) => d,
184 None => return Self::nan(),
185 };
186 }
187 }
188 }
189 if neg {
190 num = -num;
191 }
192 Self::raw(num, den)
193 }
194
195 #[must_use]
197 pub fn from_font_units(units: i64, units_per_em: u16) -> Self {
198 Self::raw(i128::from(units), i128::from(units_per_em))
199 }
200
201 #[must_use]
203 pub fn mu() -> Self {
204 Self::ratio(1, 18)
205 }
206
207 #[must_use]
209 pub fn to_mu(&self) -> Self {
210 self.clone() * Self::from_i64(18)
211 }
212
213 #[must_use]
215 pub fn from_mu(mu: &Self) -> Self {
216 mu.clone() / Self::from_i64(18)
217 }
218
219 #[must_use]
221 pub fn abs(&self) -> Self {
222 if self.nan {
223 return Self::nan();
224 }
225 if self.num == i128::MIN {
226 return Self::nan();
227 }
228 Self::raw(self.num.abs(), self.den)
229 }
230
231 #[must_use]
233 pub fn max(&self, other: &Self) -> Self {
234 match self.cmp(other) {
235 Some(Ordering::Less) => other.clone(),
236 _ => self.clone(),
237 }
238 }
239
240 #[must_use]
242 pub fn min(&self, other: &Self) -> Self {
243 match self.cmp(other) {
244 Some(Ordering::Greater) => other.clone(),
245 _ => self.clone(),
246 }
247 }
248
249 #[must_use]
251 pub fn clamp_nonneg(&self) -> Self {
252 self.max(&Self::zero())
253 }
254
255 #[must_use]
257 pub fn is_nan(&self) -> bool {
258 self.nan
259 }
260
261 #[must_use]
263 pub fn is_zero(&self) -> bool {
264 !self.nan && self.num == 0
265 }
266
267 #[must_use]
287 pub fn as_ratio(&self) -> Option<(i128, i128)> {
288 (!self.nan).then_some((self.num, self.den))
289 }
290
291 #[must_use]
293 pub fn to_dec_string(&self) -> String {
294 if self.nan {
295 return "NaN".into();
296 }
297 format_rational(self.num, self.den)
298 }
299
300 pub(crate) fn in_em(self, unit: &str) -> Option<Self> {
304 let unit = match unit {
305 "" => "em",
306 "bp" => "pt",
307 other => other,
308 };
309 let (_, per_em) = UNITS.iter().find(|(name, _)| *name == unit)?;
310 Some(self / Self::from_i64(i64::try_from(*per_em).ok()?))
311 }
312
313 #[must_use]
324 pub(crate) fn to_tex_string(&self) -> String {
325 if self.nan {
326 return "NaNem".to_string();
327 }
328 for (unit, per_em) in UNITS {
329 let Some((text, done)) = scaled_decimal(self.num, self.den, per_em) else {
330 continue;
331 };
332 if !done {
333 continue;
334 }
335 let bare = text.strip_suffix(".0").unwrap_or(&text);
336 for text in [text.as_str(), bare] {
337 if self.reads_back(text, unit) {
338 return format!("{text}{unit}");
339 }
340 }
341 }
342 format!("{}em", self.to_dec_string())
344 }
345
346 fn reads_back(&self, text: &str, unit: &str) -> bool {
348 Self::parse(text)
349 .in_em(unit)
350 .is_some_and(|read| read.eq_dim(self))
351 }
352
353 #[must_use]
355 pub fn to_svg_string(&self) -> String {
356 self.to_dec_string()
357 }
358
359 #[must_use]
361 pub fn from_ieee32_bits(bits: u32) -> Self {
362 let sign = (bits >> 31) != 0;
363 let exp = (bits >> 23) & 0xff;
364 let frac = bits & 0x7f_ffff;
365 if exp == 255 {
366 return Self::nan();
367 }
368 let (num, den, sh) = if exp == 0 {
369 if frac == 0 {
370 return Self::zero();
371 }
372 (i128::from(frac), 1i128, 149i32)
373 } else {
374 (i128::from(frac) + (1i128 << 23), 1i128, 150i32 - exp as i32)
375 };
376 let mut n = num;
377 let mut d = den;
378 if sh >= 0 {
379 for _ in 0..sh {
380 d = match d.checked_mul(2) {
381 Some(v) => v,
382 None => return Self::nan(),
383 };
384 }
385 } else {
386 for _ in 0..(-sh) {
387 n = match n.checked_mul(2) {
388 Some(v) => v,
389 None => return Self::nan(),
390 };
391 }
392 }
393 if sign {
394 n = -n;
395 }
396 Self::raw(n, d)
397 }
398
399 #[must_use]
401 pub fn to_ieee32_bits(&self) -> u32 {
402 if self.nan {
403 return 0x7fc0_0000;
404 }
405 if self.num == 0 {
406 return 0;
407 }
408 let sign = if self.num < 0 { 1u32 << 31 } else { 0 };
409 let n = self.num.unsigned_abs();
410 let d = self.den.unsigned_abs();
411 let mut e: i32 = 0;
413 if n < d {
415 let mut t = n;
416 while t < d {
417 t = match t.checked_mul(2) {
418 Some(v) => v,
419 None => break,
420 };
421 e -= 1;
422 if e < -149 {
423 return sign;
424 }
425 }
426 } else {
427 let mut t = d;
428 while t <= n / 2 {
429 t = match t.checked_mul(2) {
430 Some(v) => v,
431 None => break,
432 };
433 e += 1;
434 if e > 127 {
435 return sign | 0x7f80_0000;
436 }
437 }
438 }
439 let mut shift = 23i32 - e;
441 let mut num = n;
442 let den = d;
443 while shift > 0 {
444 num = match num.checked_mul(2) {
445 Some(v) => v,
446 None => return sign | 0x7f80_0000,
447 };
448 shift -= 1;
449 }
450 while shift < 0 {
451 num /= 2;
452 shift += 1;
453 }
454 let mut mant = num / den;
455 let rem = num % den;
456 if rem * 2 > den || (rem * 2 == den && mant & 1 == 1) {
458 mant += 1;
459 }
460 if mant >= (1u128 << 24) {
461 mant >>= 1;
462 e += 1;
463 }
464 if e > 127 {
465 return sign | 0x7f80_0000;
466 }
467 if e < -126 {
468 let sub_shift = -126 - e;
470 if sub_shift >= 24 {
471 return sign;
472 }
473 mant >>= sub_shift as u32;
474 let frac = (mant as u32) & 0x7f_ffff;
475 return sign | frac;
476 }
477 let biased = (e + 127) as u32;
478 let frac = (mant as u32) & 0x7f_ffff;
479 sign | (biased << 23) | frac
480 }
481
482 pub fn floor_to_u32(&self) -> Result<u32, Error> {
484 if self.is_nan() {
485 return Err(Error::InvalidOption {
486 what: "dimension is NaN".into(),
487 });
488 }
489 if matches!(self.cmp(&Self::zero()), Some(Ordering::Less)) {
490 return Err(Error::InvalidOption {
491 what: "negative dimension".into(),
492 });
493 }
494 const MAX: u32 = 1 << 20;
495 if matches!(
496 self.cmp(&Self::from_i64(i64::from(MAX))),
497 Some(Ordering::Greater) | Some(Ordering::Equal)
498 ) {
499 return Err(Error::InvalidOption {
500 what: "dimension exceeds raster limit".into(),
501 });
502 }
503 let q = (self.num / self.den) as u32;
504 Ok(q)
505 }
506
507 pub fn ceil_to_u32(&self) -> Result<u32, Error> {
509 let floor = self.floor_to_u32()?;
510 if self.eq_dim(&Self::from_i64(i64::from(floor))) {
511 Ok(floor)
512 } else {
513 floor.checked_add(1).ok_or_else(|| Error::InvalidOption {
514 what: "dimension overflow".into(),
515 })
516 }
517 }
518
519 #[must_use]
521 #[allow(clippy::should_implement_trait)]
522 pub fn cmp(&self, other: &Self) -> Option<Ordering> {
523 if self.nan || other.nan {
524 return None;
525 }
526 let signs = self.num.signum().cmp(&other.num.signum());
528 if signs != Ordering::Equal || self.num == 0 {
529 return Some(signs);
530 }
531 let (n1, d1) = (self.num.unsigned_abs(), self.den.unsigned_abs());
532 let (n2, d2) = (other.num.unsigned_abs(), other.den.unsigned_abs());
533 Some(if self.num < 0 {
534 cmp_ratio(n2, d2, n1, d1)
535 } else {
536 cmp_ratio(n1, d1, n2, d2)
537 })
538 }
539
540 #[must_use]
542 pub fn eq_dim(&self, other: &Self) -> bool {
543 matches!(self.cmp(other), Some(Ordering::Equal))
544 }
545}
546
547fn cmp_ratio(n1: u128, d1: u128, n2: u128, d2: u128) -> Ordering {
551 let (q1, q2) = (n1 / d1, n2 / d2);
552 if q1 != q2 {
553 return q1.cmp(&q2);
554 }
555 match (n1 % d1, n2 % d2) {
556 (0, 0) => Ordering::Equal,
557 (0, _) => Ordering::Less,
558 (_, 0) => Ordering::Greater,
559 (r1, r2) => cmp_ratio(d2, r2, d1, r1),
560 }
561}
562
563fn expand_decimal(num: i128, den: i128, cap: usize) -> (String, bool) {
564 if num == 0 {
565 return ("0.0".into(), true);
566 }
567 let neg = num < 0;
568 let mut n = num.unsigned_abs();
569 let d = den.unsigned_abs();
570 let ip = n / d;
571 n %= d;
572 let mut s = String::new();
573 if neg {
574 s.push('-');
575 }
576 if n == 0 {
577 s.push_str(&ip.to_string());
578 s.push_str(".0");
579 return (s, true);
580 }
581 s.push_str(&ip.to_string());
582 s.push('.');
583 for _ in 0..cap {
585 if n == 0 {
586 break;
587 }
588 let mut digit = 0u8;
589 let mut next = 0u128;
590 for _ in 0..10 {
592 next += n;
593 if next >= d {
594 next -= d;
595 digit += 1;
596 }
597 }
598 s.push(char::from(b'0' + digit));
599 n = next;
600 }
601 while s.ends_with('0') && !s.ends_with(".0") {
603 s.pop();
604 }
605 (s, n == 0)
606}
607
608fn format_rational(num: i128, den: i128) -> String {
609 expand_decimal(num, den, 24).0
610}
611
612fn scaled_decimal(num: i128, den: i128, per_em: i128) -> Option<(String, bool)> {
617 let g = gcd_u(per_em.unsigned_abs(), den.unsigned_abs());
618 let g = i128::try_from(g).ok()?;
619 let n = num.checked_mul(per_em / g)?;
620 let d = den / g;
621 Some(expand_decimal(n, d, 130))
622}
623
624impl PartialEq for Dim {
625 fn eq(&self, other: &Self) -> bool {
626 self.eq_dim(other)
627 }
628}
629
630impl Eq for Dim {}
631
632impl PartialOrd for Dim {
633 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
634 self.cmp(other)
635 }
636}
637
638impl fmt::Display for Dim {
639 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
640 f.write_str(&self.to_dec_string())
641 }
642}
643
644impl Neg for Dim {
645 type Output = Self;
646
647 fn neg(self) -> Self {
648 if self.nan {
649 return Self::nan();
650 }
651 Self::raw(-self.num, self.den)
652 }
653}
654
655fn add_r(a: i128, b: i128, c: i128, d: i128) -> Option<(i128, i128)> {
656 let ad = a.checked_mul(d)?;
657 let cb = c.checked_mul(b)?;
658 let n = ad.checked_add(cb)?;
659 let den = b.checked_mul(d)?;
660 Some((n, den))
661}
662
663fn sub_r(a: i128, b: i128, c: i128, d: i128) -> Option<(i128, i128)> {
664 let ad = a.checked_mul(d)?;
665 let cb = c.checked_mul(b)?;
666 let n = ad.checked_sub(cb)?;
667 let den = b.checked_mul(d)?;
668 Some((n, den))
669}
670
671fn mul_r(a: i128, b: i128, c: i128, d: i128) -> Option<(i128, i128)> {
672 let n = a.checked_mul(c)?;
673 let den = b.checked_mul(d)?;
674 Some((n, den))
675}
676
677fn div_r(a: i128, b: i128, c: i128, d: i128) -> Option<(i128, i128)> {
678 if c == 0 {
679 return None;
680 }
681 let n = a.checked_mul(d)?;
682 let den = b.checked_mul(c)?;
683 Some((n, den))
684}
685
686macro_rules! impl_dim_op {
687 ($Trait:ident, $method:ident, $helper:ident) => {
688 impl $Trait for Dim {
689 type Output = Dim;
690 fn $method(self, rhs: Dim) -> Dim {
691 Dim::binop(&self, &rhs, $helper)
692 }
693 }
694 impl $Trait<&Dim> for Dim {
695 type Output = Dim;
696 fn $method(self, rhs: &Dim) -> Dim {
697 Dim::binop(&self, rhs, $helper)
698 }
699 }
700 impl $Trait<Dim> for &Dim {
701 type Output = Dim;
702 fn $method(self, rhs: Dim) -> Dim {
703 Dim::binop(self, &rhs, $helper)
704 }
705 }
706 impl $Trait for &Dim {
707 type Output = Dim;
708 fn $method(self, rhs: &Dim) -> Dim {
709 Dim::binop(self, rhs, $helper)
710 }
711 }
712 };
713}
714
715impl_dim_op!(Add, add, add_r);
716impl_dim_op!(Sub, sub, sub_r);
717impl_dim_op!(Mul, mul, mul_r);
718impl_dim_op!(Div, div, div_r);
719
720#[cfg(test)]
721mod tests {
722 use super::Dim;
723
724 #[test]
725 fn half_and_font_units() {
726 assert!(Dim::ratio(1, 2).eq_dim(&(&Dim::one() / &Dim::from_i64(2))));
727 let w = Dim::from_font_units(479, 1000);
728 assert_eq!(w.to_dec_string(), "0.479");
729 assert_eq!((Dim::from_i64(12) * w).to_dec_string(), "5.748");
730 }
731
732 #[test]
733 fn ieee32_one() {
734 let one = Dim::from_ieee32_bits(0x3f80_0000);
735 assert!(one.eq_dim(&Dim::one()));
736 assert_eq!(Dim::one().to_ieee32_bits(), 0x3f80_0000);
737 }
738
739 #[test]
740 fn decimal_format_avoids_large_remainder_overflow() {
741 let near_one = Dim::ratio(i64::MAX - 1, i64::MAX);
742 let squared = &near_one * &near_one;
743
744 assert_eq!(squared.to_dec_string(), "0.999999999999999999783159");
745 }
746}