Skip to main content

latex_rust/
dim.rs

1//! Layout dimension: exact rational (`num / den`).
2//!
3//! TeX layout is ratios of integers (font units, mu = 1/18 em, style scales).
4//! Hardware `f32` / `f64` never appear as calculation terminals.
5
6use core::cmp::Ordering;
7use core::fmt;
8use core::ops::{Add, Div, Mul, Neg, Sub};
9
10use crate::error::Error;
11
12/// Kept in the public API. Layout values are exact rationals, not rounded bits.
13pub 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
24/// The dimension units the reader accepts and the printer writes, with how
25/// many of each make one em (`pt` is a tenth of an em here, `mu` is 1/18).
26/// `bp` reads as `pt` and no unit as `em`, see [`Dim::in_em`].
27const UNITS: [(&str, i128); 3] = [("em", 1), ("mu", 18), ("pt", 10)];
28
29/// TeX-style dimension: width, height, depth, italic correction, mu.
30///
31/// One unit is one em at the current math style unless a method says otherwise.
32///
33/// # Examples
34///
35/// ```
36/// use latex_rust::Dim;
37///
38/// let half = Dim::ratio(1, 2);
39/// assert!(half.eq_dim(&(&Dim::one() / &Dim::from_i64(2))));
40/// assert!(!Dim::zero().eq_dim(&Dim::one()));
41/// ```
42#[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    /// Zero em.
99    #[must_use]
100    pub fn zero() -> Self {
101        Self::raw(0, 1)
102    }
103
104    /// One em.
105    #[must_use]
106    pub fn one() -> Self {
107        Self::raw(1, 1)
108    }
109
110    /// Integer em count.
111    #[must_use]
112    pub fn from_i64(v: i64) -> Self {
113        Self::raw(i128::from(v), 1)
114    }
115
116    /// Exact rational `num / den` em. `den == 0` yields NaN.
117    #[must_use]
118    pub fn ratio(num: i64, den: i64) -> Self {
119        Self::raw(i128::from(num), i128::from(den))
120    }
121
122    /// Parse a decimal string (optional sign, fraction, `e` exponent).
123    #[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    /// Convert integer font units to em: `units / units_per_em`.
196    #[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    /// One math unit (mu). TeX: `18 mu = 1 em`.
202    #[must_use]
203    pub fn mu() -> Self {
204        Self::ratio(1, 18)
205    }
206
207    /// Convert this em value to mu (`* 18`).
208    #[must_use]
209    pub fn to_mu(&self) -> Self {
210        self.clone() * Self::from_i64(18)
211    }
212
213    /// Convert a mu value to em (`/ 18`).
214    #[must_use]
215    pub fn from_mu(mu: &Self) -> Self {
216        mu.clone() / Self::from_i64(18)
217    }
218
219    /// Absolute value.
220    #[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    /// Maximum of two dimensions.
232    #[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    /// Minimum of two dimensions.
241    #[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    /// `max(self, 0)`.
250    #[must_use]
251    pub fn clamp_nonneg(&self) -> Self {
252        self.max(&Self::zero())
253    }
254
255    /// True when the value is NaN.
256    #[must_use]
257    pub fn is_nan(&self) -> bool {
258        self.nan
259    }
260
261    /// True when the value compares equal to zero.
262    #[must_use]
263    pub fn is_zero(&self) -> bool {
264        !self.nan && self.num == 0
265    }
266
267    /// The exact rational value in em, as `(numerator, denominator)`, or
268    /// `None` if this dimension is NaN.
269    ///
270    /// The denominator is positive and the fraction is in lowest terms. This is
271    /// the only accessor that does not round: [`Self::to_dec_string`] formats a
272    /// decimal expansion and [`Self::to_ieee32_bits`] rounds to binary32. An
273    /// external renderer that wants to convert at its own pixel boundary,
274    /// rather than take the crate's rounding, should start here.
275    ///
276    /// # Examples
277    ///
278    /// ```
279    /// use latex_rust::Dim;
280    ///
281    /// assert_eq!(Dim::ratio(2, 6).as_ratio(), Some((1, 3)));
282    /// assert_eq!(Dim::ratio(1, -2).as_ratio(), Some((-1, 2)));
283    /// assert_eq!(Dim::zero().as_ratio(), Some((0, 1)));
284    /// assert_eq!(Dim::ratio(1, 0).as_ratio(), None);
285    /// ```
286    #[must_use]
287    pub fn as_ratio(&self) -> Option<(i128, i128)> {
288        (!self.nan).then_some((self.num, self.den))
289    }
290
291    /// Decimal string (exact terminating expansion, or scientific).
292    #[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    /// The number `self`, read in `unit`, as em: the one definition of the
301    /// dimension units, used by the reader and by the printer's check of what it
302    /// writes. `""` is `em`, `bp` is `pt`; `None` for any other unit.
303    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    /// The number and unit the printer writes in `\hspace{..}` and `\rule{..}{..}`
314    /// (`0.25em`, `1.5mu`), so that the text reads back as this exact `Dim`.
315    ///
316    /// Every value a parse can make is exact in the unit it was read in: a
317    /// finite decimal in em, in mu (1/18 em) when em would never end, or in pt
318    /// when em has more digits than the reader holds. Each candidate is checked
319    /// against the reader before it is used (`X.0` of a 38-digit whole number
320    /// overflows the reader, `X` does not). A value that no text reaches (1/3,
321    /// say) falls back to the 24-digit text of [`Self::to_dec_string`], which
322    /// is lossy.
323    #[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        // No parse makes this value; the text is the lossy decimal.
343        format!("{}em", self.to_dec_string())
344    }
345
346    /// True when the reader turns `text`, in `unit`, into exactly `self`.
347    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    /// Compact decimal for SVG attributes.
354    #[must_use]
355    pub fn to_svg_string(&self) -> String {
356        self.to_dec_string()
357    }
358
359    /// Layout dimension from an IEEE-754 binary32 bit pattern (outline boundary).
360    #[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    /// Round to IEEE-754 binary32 bits for PNG / raster emission only.
400    #[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        // Find e such that 2^e <= n/d < 2^{e+1}.
412        let mut e: i32 = 0;
413        // Compare n/d vs 1: n ? d
414        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        // mantissa: floor((n/d) / 2^(e-23)) = floor(n * 2^(23-e) / d)
440        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        // round to nearest even
457        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            // subnormal
469            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    /// Largest `u32` that is not greater than `self`. Negative and NaN fail.
483    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    /// Smallest `u32` that is not less than `self`.
508    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    /// Compare two dimensions. `None` if either is NaN.
520    #[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        // Exact for every value: no cross products, so nothing overflows.
527        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    /// True when `self` and `other` compare equal.
541    #[must_use]
542    pub fn eq_dim(&self, other: &Self) -> bool {
543        matches!(self.cmp(other), Some(Ordering::Equal))
544    }
545}
546
547/// Compares `n1/d1` with `n2/d2` (denominators positive) without multiplying:
548/// the integer parts first, then the fractional parts by their reciprocals
549/// (the Euclidean algorithm, so it ends in at most about 190 steps).
550fn 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    // Long division, cap at `cap` digits.
584    for _ in 0..cap {
585        if n == 0 {
586            break;
587        }
588        let mut digit = 0u8;
589        let mut next = 0u128;
590        // Preserve long division without forming n * 10, which can overflow.
591        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    // Trim trailing zeros but keep one fractional digit.
602    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
612/// The decimal expansion of `per_em * num / den` (the value in a unit that is
613/// `per_em` to the em), and whether it is complete; `None` on overflow. The
614/// fraction is reduced by `gcd(per_em, den)` first, so only a numerator that
615/// really needs more than 127 bits overflows.
616fn 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}