latex-rust 1.0.2

Pure-Rust LaTeX math renderer. Parse to AST, TeX-faithful layout on exact rationals, emit SVG, PNG, or egui shapes. No JavaScript, no webview, no runtime.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
//! Layout dimension: exact rational (`num / den`).
//!
//! TeX layout is ratios of integers (font units, mu = 1/18 em, style scales).
//! Hardware `f32` / `f64` never appear as calculation terminals.

use core::cmp::Ordering;
use core::fmt;
use core::ops::{Add, Div, Mul, Neg, Sub};

use crate::error::Error;

/// Kept in the public API. Layout values are exact rationals, not rounded bits.
pub const DIM_PREC: usize = 256;

fn gcd_u(mut a: u128, mut b: u128) -> u128 {
    while b != 0 {
        let t = a % b;
        a = b;
        b = t;
    }
    a
}

/// TeX-style dimension: width, height, depth, italic correction, mu.
///
/// One unit is one em at the current math style unless a method says otherwise.
///
/// # Examples
///
/// ```
/// use latex_rust::Dim;
///
/// let half = Dim::ratio(1, 2);
/// assert!(half.eq_dim(&(&Dim::one() / &Dim::from_i64(2))));
/// assert!(!Dim::zero().eq_dim(&Dim::one()));
/// ```
#[derive(Clone, Debug)]
pub struct Dim {
    num: i128,
    den: i128,
    nan: bool,
}

impl Dim {
    fn raw(num: i128, den: i128) -> Self {
        if den == 0 {
            return Self::nan();
        }
        if num == 0 {
            return Self {
                num: 0,
                den: 1,
                nan: false,
            };
        }
        let g = gcd_u(num.unsigned_abs(), den.unsigned_abs());
        let g = i128::try_from(g).unwrap_or(1);
        let mut n = num / g;
        let mut d = den / g;
        if d < 0 {
            n = -n;
            d = -d;
        }
        Self {
            num: n,
            den: d,
            nan: false,
        }
    }

    fn nan() -> Self {
        Self {
            num: 0,
            den: 1,
            nan: true,
        }
    }

    fn binop(
        a: &Self,
        b: &Self,
        f: impl Fn(i128, i128, i128, i128) -> Option<(i128, i128)>,
    ) -> Self {
        if a.nan || b.nan {
            return Self::nan();
        }
        match f(a.num, a.den, b.num, b.den) {
            Some((n, d)) => Self::raw(n, d),
            None => Self::nan(),
        }
    }

    /// Zero em.
    #[must_use]
    pub fn zero() -> Self {
        Self::raw(0, 1)
    }

    /// One em.
    #[must_use]
    pub fn one() -> Self {
        Self::raw(1, 1)
    }

    /// Integer em count.
    #[must_use]
    pub fn from_i64(v: i64) -> Self {
        Self::raw(i128::from(v), 1)
    }

    /// Exact rational `num / den` em. `den == 0` yields NaN.
    #[must_use]
    pub fn ratio(num: i64, den: i64) -> Self {
        Self::raw(i128::from(num), i128::from(den))
    }

    /// Parse a decimal string (optional sign, fraction, `e` exponent).
    #[must_use]
    pub fn parse(s: &str) -> Self {
        let t = s.trim();
        if t.is_empty() || t.eq_ignore_ascii_case("nan") {
            return Self::nan();
        }
        let mut rest = t;
        let neg = if let Some(r) = rest.strip_prefix('-') {
            rest = r;
            true
        } else if let Some(r) = rest.strip_prefix('+') {
            rest = r;
            false
        } else {
            false
        };
        let (mant, exp_s) = match rest.find(['e', 'E']) {
            Some(i) => (&rest[..i], Some(&rest[i + 1..])),
            None => (rest, None),
        };
        let (ip, fp) = match mant.find('.') {
            Some(i) => (&mant[..i], &mant[i + 1..]),
            None => (mant, ""),
        };
        if ip.is_empty() && fp.is_empty() {
            return Self::nan();
        }
        if !ip.chars().all(|c| c.is_ascii_digit()) || !fp.chars().all(|c| c.is_ascii_digit()) {
            return Self::nan();
        }
        let mut num: i128 = 0;
        for c in ip.bytes().chain(fp.bytes()) {
            let d = i128::from(c - b'0');
            num = match num.checked_mul(10).and_then(|n| n.checked_add(d)) {
                Some(n) => n,
                None => return Self::nan(),
            };
        }
        let mut den = 1i128;
        for _ in 0..fp.len() {
            den = match den.checked_mul(10) {
                Some(d) => d,
                None => return Self::nan(),
            };
        }
        if let Some(es) = exp_s {
            let e: i32 = match es.parse() {
                Ok(v) => v,
                Err(_) => return Self::nan(),
            };
            if e > 0 {
                for _ in 0..e {
                    num = match num.checked_mul(10) {
                        Some(n) => n,
                        None => return Self::nan(),
                    };
                }
            } else {
                for _ in 0..(-e) {
                    den = match den.checked_mul(10) {
                        Some(d) => d,
                        None => return Self::nan(),
                    };
                }
            }
        }
        if neg {
            num = -num;
        }
        Self::raw(num, den)
    }

    /// Convert integer font units to em: `units / units_per_em`.
    #[must_use]
    pub fn from_font_units(units: i64, units_per_em: u16) -> Self {
        Self::raw(i128::from(units), i128::from(units_per_em))
    }

    /// One math unit (mu). TeX: `18 mu = 1 em`.
    #[must_use]
    pub fn mu() -> Self {
        Self::ratio(1, 18)
    }

    /// Convert this em value to mu (`* 18`).
    #[must_use]
    pub fn to_mu(&self) -> Self {
        self.clone() * Self::from_i64(18)
    }

    /// Convert a mu value to em (`/ 18`).
    #[must_use]
    pub fn from_mu(mu: &Self) -> Self {
        mu.clone() / Self::from_i64(18)
    }

    /// Absolute value.
    #[must_use]
    pub fn abs(&self) -> Self {
        if self.nan {
            return Self::nan();
        }
        if self.num == i128::MIN {
            return Self::nan();
        }
        Self::raw(self.num.abs(), self.den)
    }

    /// Maximum of two dimensions.
    #[must_use]
    pub fn max(&self, other: &Self) -> Self {
        match self.cmp(other) {
            Some(Ordering::Less) => other.clone(),
            _ => self.clone(),
        }
    }

    /// Minimum of two dimensions.
    #[must_use]
    pub fn min(&self, other: &Self) -> Self {
        match self.cmp(other) {
            Some(Ordering::Greater) => other.clone(),
            _ => self.clone(),
        }
    }

    /// `max(self, 0)`.
    #[must_use]
    pub fn clamp_nonneg(&self) -> Self {
        self.max(&Self::zero())
    }

    /// True when the value is NaN.
    #[must_use]
    pub fn is_nan(&self) -> bool {
        self.nan
    }

    /// True when the value compares equal to zero.
    #[must_use]
    pub fn is_zero(&self) -> bool {
        !self.nan && self.num == 0
    }

    /// Decimal string (exact terminating expansion, or scientific).
    #[must_use]
    pub fn to_dec_string(&self) -> String {
        if self.nan {
            return "NaN".into();
        }
        format_rational(self.num, self.den)
    }

    /// Compact decimal for SVG attributes.
    #[must_use]
    pub fn to_svg_string(&self) -> String {
        self.to_dec_string()
    }

    /// Layout dimension from an IEEE-754 binary32 bit pattern (outline boundary).
    #[must_use]
    pub fn from_ieee32_bits(bits: u32) -> Self {
        let sign = (bits >> 31) != 0;
        let exp = (bits >> 23) & 0xff;
        let frac = bits & 0x7f_ffff;
        if exp == 255 {
            return Self::nan();
        }
        let (num, den, sh) = if exp == 0 {
            if frac == 0 {
                return Self::zero();
            }
            (i128::from(frac), 1i128, 149i32)
        } else {
            (i128::from(frac) + (1i128 << 23), 1i128, 150i32 - exp as i32)
        };
        let mut n = num;
        let mut d = den;
        if sh >= 0 {
            for _ in 0..sh {
                d = match d.checked_mul(2) {
                    Some(v) => v,
                    None => return Self::nan(),
                };
            }
        } else {
            for _ in 0..(-sh) {
                n = match n.checked_mul(2) {
                    Some(v) => v,
                    None => return Self::nan(),
                };
            }
        }
        if sign {
            n = -n;
        }
        Self::raw(n, d)
    }

    /// Round to IEEE-754 binary32 bits for PNG / raster emission only.
    #[must_use]
    pub fn to_ieee32_bits(&self) -> u32 {
        if self.nan {
            return 0x7fc0_0000;
        }
        if self.num == 0 {
            return 0;
        }
        let sign = if self.num < 0 { 1u32 << 31 } else { 0 };
        let n = self.num.unsigned_abs();
        let d = self.den.unsigned_abs();
        // Find e such that 2^e <= n/d < 2^{e+1}.
        let mut e: i32 = 0;
        // Compare n/d vs 1: n ? d
        if n < d {
            let mut t = n;
            while t < d {
                t = match t.checked_mul(2) {
                    Some(v) => v,
                    None => break,
                };
                e -= 1;
                if e < -149 {
                    return sign;
                }
            }
        } else {
            let mut t = d;
            while t <= n / 2 {
                t = match t.checked_mul(2) {
                    Some(v) => v,
                    None => break,
                };
                e += 1;
                if e > 127 {
                    return sign | 0x7f80_0000;
                }
            }
        }
        // mantissa: floor((n/d) / 2^(e-23)) = floor(n * 2^(23-e) / d)
        let mut shift = 23i32 - e;
        let mut num = n;
        let den = d;
        while shift > 0 {
            num = match num.checked_mul(2) {
                Some(v) => v,
                None => return sign | 0x7f80_0000,
            };
            shift -= 1;
        }
        while shift < 0 {
            num /= 2;
            shift += 1;
        }
        let mut mant = num / den;
        let rem = num % den;
        // round to nearest even
        if rem * 2 > den || (rem * 2 == den && mant & 1 == 1) {
            mant += 1;
        }
        if mant >= (1u128 << 24) {
            mant >>= 1;
            e += 1;
        }
        if e > 127 {
            return sign | 0x7f80_0000;
        }
        if e < -126 {
            // subnormal
            let sub_shift = -126 - e;
            if sub_shift >= 24 {
                return sign;
            }
            mant >>= sub_shift as u32;
            let frac = (mant as u32) & 0x7f_ffff;
            return sign | frac;
        }
        let biased = (e + 127) as u32;
        let frac = (mant as u32) & 0x7f_ffff;
        sign | (biased << 23) | frac
    }

    /// Largest `u32` that is not greater than `self`. Negative and NaN fail.
    pub fn floor_to_u32(&self) -> Result<u32, Error> {
        if self.is_nan() {
            return Err(Error::InvalidOption {
                what: "dimension is NaN".into(),
            });
        }
        if matches!(self.cmp(&Self::zero()), Some(Ordering::Less)) {
            return Err(Error::InvalidOption {
                what: "negative dimension".into(),
            });
        }
        const MAX: u32 = 1 << 20;
        if matches!(
            self.cmp(&Self::from_i64(i64::from(MAX))),
            Some(Ordering::Greater) | Some(Ordering::Equal)
        ) {
            return Err(Error::InvalidOption {
                what: "dimension exceeds raster limit".into(),
            });
        }
        let q = (self.num / self.den) as u32;
        Ok(q)
    }

    /// Smallest `u32` that is not less than `self`.
    pub fn ceil_to_u32(&self) -> Result<u32, Error> {
        let floor = self.floor_to_u32()?;
        if self.eq_dim(&Self::from_i64(i64::from(floor))) {
            Ok(floor)
        } else {
            floor.checked_add(1).ok_or_else(|| Error::InvalidOption {
                what: "dimension overflow".into(),
            })
        }
    }

    /// Compare two dimensions. `None` if either is NaN.
    #[must_use]
    #[allow(clippy::should_implement_trait)]
    pub fn cmp(&self, other: &Self) -> Option<Ordering> {
        if self.nan || other.nan {
            return None;
        }
        // n1/d1 vs n2/d2 => n1*d2 vs n2*d1
        let left = self.num.checked_mul(other.den)?;
        let right = other.num.checked_mul(self.den)?;
        Some(left.cmp(&right))
    }

    /// True when `self` and `other` compare equal.
    #[must_use]
    pub fn eq_dim(&self, other: &Self) -> bool {
        matches!(self.cmp(other), Some(Ordering::Equal))
    }
}

fn format_rational(num: i128, den: i128) -> String {
    if num == 0 {
        return "0.0".into();
    }
    let neg = num < 0;
    let mut n = num.unsigned_abs();
    let d = den.unsigned_abs();
    let ip = n / d;
    n %= d;
    let mut s = String::new();
    if neg {
        s.push('-');
    }
    if n == 0 {
        s.push_str(&ip.to_string());
        s.push_str(".0");
        return s;
    }
    s.push_str(&ip.to_string());
    s.push('.');
    // Long division, cap 24 digits (plenty for font-unit rationals).
    for _ in 0..24 {
        if n == 0 {
            break;
        }
        n *= 10;
        let digit = n / d;
        s.push(char::from(b'0' + digit as u8));
        n %= d;
    }
    // Trim trailing zeros but keep one fractional digit.
    while s.ends_with('0') && !s.ends_with(".0") {
        s.pop();
    }
    s
}

impl PartialEq for Dim {
    fn eq(&self, other: &Self) -> bool {
        self.eq_dim(other)
    }
}

impl Eq for Dim {}

impl PartialOrd for Dim {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        self.cmp(other)
    }
}

impl fmt::Display for Dim {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.to_dec_string())
    }
}

impl Neg for Dim {
    type Output = Self;

    fn neg(self) -> Self {
        if self.nan {
            return Self::nan();
        }
        Self::raw(-self.num, self.den)
    }
}

fn add_r(a: i128, b: i128, c: i128, d: i128) -> Option<(i128, i128)> {
    let ad = a.checked_mul(d)?;
    let cb = c.checked_mul(b)?;
    let n = ad.checked_add(cb)?;
    let den = b.checked_mul(d)?;
    Some((n, den))
}

fn sub_r(a: i128, b: i128, c: i128, d: i128) -> Option<(i128, i128)> {
    let ad = a.checked_mul(d)?;
    let cb = c.checked_mul(b)?;
    let n = ad.checked_sub(cb)?;
    let den = b.checked_mul(d)?;
    Some((n, den))
}

fn mul_r(a: i128, b: i128, c: i128, d: i128) -> Option<(i128, i128)> {
    let n = a.checked_mul(c)?;
    let den = b.checked_mul(d)?;
    Some((n, den))
}

fn div_r(a: i128, b: i128, c: i128, d: i128) -> Option<(i128, i128)> {
    if c == 0 {
        return None;
    }
    let n = a.checked_mul(d)?;
    let den = b.checked_mul(c)?;
    Some((n, den))
}

macro_rules! impl_dim_op {
    ($Trait:ident, $method:ident, $helper:ident) => {
        impl $Trait for Dim {
            type Output = Dim;
            fn $method(self, rhs: Dim) -> Dim {
                Dim::binop(&self, &rhs, $helper)
            }
        }
        impl $Trait<&Dim> for Dim {
            type Output = Dim;
            fn $method(self, rhs: &Dim) -> Dim {
                Dim::binop(&self, rhs, $helper)
            }
        }
        impl $Trait<Dim> for &Dim {
            type Output = Dim;
            fn $method(self, rhs: Dim) -> Dim {
                Dim::binop(self, &rhs, $helper)
            }
        }
        impl $Trait for &Dim {
            type Output = Dim;
            fn $method(self, rhs: &Dim) -> Dim {
                Dim::binop(self, rhs, $helper)
            }
        }
    };
}

impl_dim_op!(Add, add, add_r);
impl_dim_op!(Sub, sub, sub_r);
impl_dim_op!(Mul, mul, mul_r);
impl_dim_op!(Div, div, div_r);

#[cfg(test)]
mod tests {
    use super::Dim;

    #[test]
    fn half_and_font_units() {
        assert!(Dim::ratio(1, 2).eq_dim(&(&Dim::one() / &Dim::from_i64(2))));
        let w = Dim::from_font_units(479, 1000);
        assert_eq!(w.to_dec_string(), "0.479");
        assert_eq!((Dim::from_i64(12) * w).to_dec_string(), "5.748");
    }

    #[test]
    fn ieee32_one() {
        let one = Dim::from_ieee32_bits(0x3f80_0000);
        assert!(one.eq_dim(&Dim::one()));
        assert_eq!(Dim::one().to_ieee32_bits(), 0x3f80_0000);
    }
}