Skip to main content

latexml_core/common/
numeric_ops.rs

1use std::fmt::Display;
2
3use crate::{
4  common::glue::Glue,
5  definition::register::RegisterType,
6  token::{Catcode, Token},
7};
8
9pub const UNITY: i64 = 65536;
10pub const UNITY_F64: f64 = 65536.0;
11pub const EPSILON: f64 = 0.000_000_119_209_29;
12pub const ROUNDING_HALF: f64 = 0.49999994;
13pub const SCALES: &[i32] = &[1, 10, 100, 1000, 10000, 100_000];
14
15/// Round $number to $prec decimals (0...6) attempting to do so portably.
16pub fn round_to(number: f64, prec_opt: Option<u8>) -> f64 {
17  let mut prec = prec_opt.unwrap_or(2);
18  if prec > 5 {
19    prec = 5;
20  }
21  let scale = SCALES[prec as usize];
22  // scale to integer, w/some slop in case arbitrarily close to an integer...
23  let n = number * scale as f64 * (1.0 + 100.0 * EPSILON);
24  let adjusted: f64 = if n < -EPSILON {
25    n - 0.5
26  } else if n > EPSILON {
27    n + 0.5
28  } else {
29    0.0
30  };
31  adjusted.trunc() / scale as f64
32}
33
34/// An attempt at rounding floats to integers (like scaled points),
35/// in a (hopefully) Knuthian manner (like round_decimals \S102 in Tex The Program)
36// DG: Note that we have to go to the largest `i64` type to contain the truncation
37// of large SP values multiplied up by UNITY
38pub fn kround(number: f64) -> i64 {
39  let rounded = if number < 0.0 {
40    number - ROUNDING_HALF
41  } else {
42    number + ROUNDING_HALF
43  };
44  rounded.trunc() as i64
45}
46
47/// Convert `float` to a fixed-point number
48///
49/// If `unit` is given, it is number of units PER SCALED-POINT! (hence, extra division)
50/// AND, note that the float is rounded and THEN truncated after multiplying by units!
51/// to mimic TeX's behavior.
52pub fn fixpoint(float: f64, unit_opt: Option<f64>) -> i64 {
53  let fix = kround(float * UNITY_F64);
54  if let Some(unit) = unit_opt {
55    (fix as f64 * unit / UNITY_F64).trunc() as i64
56  } else {
57    fix
58  }
59}
60
61/// Exact TeX fixed-point unit conversion: `floor(round(float·65536)·num/den)`,
62/// computed in integer (i128) arithmetic.
63///
64/// This is tex.web §458 `scan_dimen` — `cur_val := xn_over_d(cur_val,num,denom);
65/// f := (num*f + 65536*remainder) div denom; cur_val += f div 65536` — which
66/// algebraically collapses to `floor(fix·num/den)` for `fix = cur_val·65536 + f`
67/// (proof: `xn_over_d(x,n,d) = floor(x·n/d)` with `remainder = x·n mod d`, so the
68/// integer-part and fraction-carry terms recombine to `num·fix/den`). The
69/// per-unit `(num,den)` come from [`crate::state::convert_unit_ratio`] (physical
70/// units use TeX's `set_conversion` fractions, tex.web 9020-9032; font-relative
71/// units use `(metric_sp, 65536)`, the `nx_plus_y`/`xn_over_d` path of §8983).
72///
73/// The legacy float [`fixpoint`] computes `trunc(fix·(65536·num/den)/65536)` and
74/// drifts ±1 sp on rounding boundaries (verified against pdftex on `cm`/`bp`/`mm`/
75/// `cc`; issue #127). Integer math is bit-faithful to TeX/pdfTeX. Sign matches
76/// TeX: it tracks sign separately and floors the magnitude, i.e. truncation
77/// toward zero — exactly Rust's integer `/`.
78pub fn fixpoint_unit(float: f64, num: i64, den: i64) -> i64 {
79  fixpoint_unit_checked(float, num, den).unwrap_or_else(|sign| sign * MAX_DIMEN)
80}
81
82/// TeX's `max_dimen` (tex.web §421: 2^30 − 1 sp = 16383.99998pt), the bound
83/// `arith_error` clamps a scanned dimension to ("Dimension too large", §460).
84/// LaTeXML keeps i64 headroom above it for pgf/tikz intermediates, so the
85/// clamp fires only where the value would not even fit an i64 — the
86/// pathology that wrapped to garbage (chinesechess.sty:2016-2020's
87/// `\coffin_scale:cnn{\dim_ratio:nn{…}{0}}`, batch 56bq).
88pub const MAX_DIMEN: i64 = 0x3FFF_FFFF;
89
90/// [`fixpoint_unit`] that reports an i64 overflow as `Err(sign)` instead of
91/// wrapping the `i128` product (the caller raises TeX's arith_error).
92pub fn fixpoint_unit_checked(float: f64, num: i64, den: i64) -> Result<i64, i64> {
93  let fix = kround(float * UNITY_F64) as i128;
94  let v = fix * num as i128 / den as i128;
95  i64::try_from(v).map_err(|_| if v < 0 { -1 } else { 1 })
96}
97
98/// TeX's `round_decimals` (tex.web §102): the fraction `.d₁d₂…` of the decimal digits `digits` (the first 17 count),
99/// in scaled points, rounded half up.
100pub fn round_decimals(digits: &[u8]) -> i64 {
101  let mut a = 0;
102  for &digit in digits.iter().take(17).rev() {
103    a = (a + i64::from(digit - b'0') * 0x20000) / 10;
104  }
105  (a + 1) / 2
106}
107
108/// `<factor><dimen>` as TeX's `scan_dimen` multiplies them (tex.web §455): `nx_plus_y(n, x, xn_over_d(x, f, 2^16))`
109/// for the factor `n + f/2^16` (`factor` in scaled points), its sign attached after (§448). Not clamped: an overflow
110/// past `max_dimen` is the caller's to report (§461).
111pub fn scale_by_factor(x: i64, factor: i64) -> i64 {
112  let (whole, fraction) = (
113    i128::from(factor.abs() / UNITY),
114    i128::from(factor.abs() % UNITY),
115  );
116  let x = i128::from(x);
117  // xn_over_d (§107) truncates the magnitude, its sign kept.
118  let product = whole * x + (x.abs() * fraction / i128::from(UNITY)) * x.signum();
119  let product = if factor < 0 { -product } else { product };
120  product.clamp(i128::from(i64::MIN), i128::from(i64::MAX)) as i64
121}
122
123/// TeX's `infinity` for integers (tex.web §445: 2^31 − 1), the `\numexpr`/
124/// `\multiply` counterpart of [`MAX_DIMEN`].
125pub const MAX_INTEGER: i64 = 0x7FFF_FFFF;
126
127/// A product that left the i64 range (an infinite or saturated `f64→i64`
128/// cast): TeX's arith_error ("Arithmetic overflow", tex.web §105-108) clamps
129/// to ±`ceiling` — `MAX_DIMEN` for a dimension, `MAX_INTEGER` for a count —
130/// never a wrapped value. An Error, as TeX's (OXIDIZED_DESIGN #519); no `Err`
131/// channel here, so the cap latches as [`emit_error`](crate::common::error::emit_error) does.
132/// A Warning in a box measured by our approximation ([`approximated_measure`](crate::common::error::approximated_measure)).
133pub fn clamp_arith_overflow(product: f64, ceiling: i64) -> i64 {
134  if product.is_finite() && product.abs() < i64::MAX as f64 {
135    product as i64
136  } else {
137    let detail = "clamped (tex.web §105-108)";
138    use crate::common::error::{approximated_measure, emit_error, emit_info, emit_warn};
139    match approximated_measure() {
140      Some((ours, first)) => {
141        let message = crate::generate_message!("Arithmetic overflow.", detail, ours);
142        (if first { emit_warn } else { emit_info })("expected", "<number>", &message);
143      },
144      None => {
145        emit_error(
146          "expected",
147          "<number>",
148          &crate::generate_message!("Arithmetic overflow.", detail),
149        );
150      },
151    }
152    if product < 0.0 { -ceiling } else { ceiling }
153  }
154}
155
156pub trait NumericOps {
157  fn new(num: i64) -> Self
158  where Self: Sized;
159  fn new_f64(num: f64) -> Self
160  where Self: Sized;
161  fn unit(&self) -> Option<&'static str> { None }
162  fn value_of(self) -> i64;
163  fn value_f64(self) -> f64
164  where Self: Sized {
165    self.value_of() as f64
166  }
167  fn pt_value(self, prec: Option<u8>) -> f64
168  where Self: Sized {
169    round_to(self.value_of() as f64 / UNITY_F64, prec)
170  }
171  fn px_value(self, prec: Option<u8>) -> f64
172  where Self: Sized {
173    let dpi = crate::state::lookup_int("DPI");
174    let dpi = if dpi > 0 { dpi as f64 } else { 100.0 };
175    round_to((self.value_f64() / UNITY_F64) * (dpi / 72.27), prec)
176  }
177
178  fn absolute(self) -> Self
179  where Self: Sized {
180    Self::new(self.value_of().abs())
181  }
182
183  fn sign(self) -> i8
184  where Self: Sized {
185    use std::cmp::Ordering::*;
186    match self.value_of().cmp(&0) {
187      Less => -1,
188      Equal => 0,
189      Greater => 1,
190    }
191  }
192
193  fn negate(self) -> Self
194  where Self: Sized {
195    Self::new(-self.value_of())
196  }
197  fn add<T: NumericOps>(self, other: T) -> Self
198  where Self: Sized {
199    Self::new(self.value_of() + other.value_of())
200  }
201  fn subtract<T: NumericOps>(self, other: T) -> Self
202  where Self: Sized {
203    Self::new(self.value_of() - other.value_of())
204  }
205  // Perl: int($self->valueOf * $other->valueOf) — uses float arithmetic to
206  // handle Float multipliers correctly, then truncates.
207  fn multiply<T: NumericOps>(self, other: T) -> Self
208  where Self: Sized {
209    Self::new(clamp_arith_overflow(
210      self.value_of() as f64 * other.value_f64(),
211      Self::arith_ceiling(),
212    ))
213  }
214  /// The arith_error clamp bound: `max_dimen` for dimensions and glue,
215  /// TeX's integer `infinity` for counts (overridden by `Number`).
216  fn arith_ceiling() -> i64 { MAX_DIMEN }
217  /// Truncating division
218  fn divide<T: NumericOps>(self, other: T) -> Self
219  where Self: Sized {
220    let mut other_value: f64 = other.value_of() as f64;
221    if other_value == 0.0 {
222      other_value = EPSILON; // avoid dividing by zero
223    }
224    Self::new((self.value_of() as f64 / other_value).trunc() as i64)
225  }
226
227  /// Rounding division — eTeX's `quotient(n,d)` (etex.ch "Declare
228  /// subprocedures for scan_expr"): work on magnitudes and round half AWAY
229  /// from zero, so `\numexpr -1/2` = -1 and `-7/2` = -4 (pdflatex-probed).
230  /// Perl Number.pm `int(0.5 + n/d)` truncates toward zero and yields 0 / -3
231  /// (KNOWN_PERL_ERRORS #124); l3fp's `\__fp_mul_cases_o:NnNnww` case index
232  /// `(#5 #2 #8) / 2 * 2 + 7` (expl3-code.tex:18724-18760) relies on the TeX
233  /// rounding, so `0 * x` inside a `+`/`-` expression collapsed the whole
234  /// `\fp_eval:n` to 0 (wheelchart's tikz transform determinant,
235  /// wheelchart.sty:2423). A zero divisor is TeX's arith_error → 0.
236  fn divideround<T: NumericOps>(self, other: T) -> Self
237  where Self: Sized {
238    let mut n = self.value_of();
239    let mut d = other.value_of();
240    if d == 0 {
241      return Self::new(0);
242    }
243    let mut negative = false;
244    if d < 0 {
245      d = -d;
246      negative = !negative;
247    }
248    if n < 0 {
249      n = -n;
250      negative = !negative;
251    }
252    let mut a = n / d;
253    let r = n - a * d;
254    if r - d + r >= 0 {
255      a += 1;
256    }
257    Self::new(if negative { -a } else { a })
258  }
259
260  fn smaller<T: NumericOps>(self, other: T) -> Self
261  where Self: Sized {
262    Self::new(self.value_of().min(other.value_of()))
263  }
264
265  fn larger<T: NumericOps>(self, other: T) -> Self
266  where Self: Sized {
267    Self::new(self.value_of().max(other.value_of()))
268  }
269
270  fn to_token(self) -> Token
271  where Self: Sized {
272    T_OTHER!(self.value_of().to_string())
273  }
274  // dancing around meta-programming in the Glue case... is there a better way?
275  fn into_glue_type(self) -> Glue
276  where Self: Sized {
277    Glue::new(0) // default: zero glue
278  }
279  fn register_type(&self) -> RegisterType;
280  fn to_attribute(&self) -> String
281  where Self: Display {
282    self.to_string()
283  }
284}
285
286#[cfg(test)]
287mod tests {
288  use super::*;
289
290  #[test]
291  fn round_to_default_precision_is_two() {
292    assert_eq!(round_to(1.2345, None), 1.23);
293    assert_eq!(round_to(1.2355, None), 1.24);
294    assert_eq!(round_to(0.0, None), 0.0);
295  }
296
297  #[test]
298  fn round_to_respects_precision() {
299    assert_eq!(round_to(1.23456, Some(3)), 1.235);
300    assert_eq!(round_to(1.23456, Some(0)), 1.0);
301    assert_eq!(round_to(1.5, Some(0)), 2.0);
302  }
303
304  #[test]
305  fn round_to_caps_precision_at_five() {
306    // The doc-comment says 0..=5 is the intended range; precisions
307    // above 5 are clamped to 5.
308    let a = round_to(1.12345, Some(5));
309    let b = round_to(1.12345, Some(10));
310    assert_eq!(a, b, "precision > 5 clamps to 5 (got {a} vs {b})");
311  }
312
313  #[test]
314  fn round_to_negative_numbers() {
315    assert_eq!(round_to(-1.235, None), -1.24);
316    assert_eq!(round_to(-0.005, None), -0.01);
317  }
318
319  #[test]
320  fn kround_basic() {
321    assert_eq!(kround(0.0), 0);
322    assert_eq!(kround(0.49), 0);
323    // 0.5 + ROUNDING_HALF (0.49999994) = 0.99999994 → trunc = 0
324    // Knuthian rounding below is actually a bit different from banker's.
325    assert_eq!(kround(1.49), 1);
326    assert_eq!(kround(1.5), 1);
327    assert_eq!(kround(-0.49), 0);
328    assert_eq!(kround(-1.49), -1);
329  }
330
331  #[test]
332  fn fixpoint_without_unit() {
333    // fixpoint(x, None) returns kround(x * 65536).
334    assert_eq!(fixpoint(1.0, None), UNITY);
335    assert_eq!(fixpoint(0.0, None), 0);
336    assert_eq!(fixpoint(0.5, None), UNITY / 2);
337  }
338
339  #[test]
340  fn fixpoint_with_unit_scales() {
341    // unit=1.0 means 1 unit per scaled-point, so:
342    //   fix(1.0, Some(1.0)) = kround(65536.0) * 1.0 / 65536.0 = 1 (truncated)
343    let out = fixpoint(1.0, Some(1.0));
344    // Result depends on the unit semantics ("units PER SCALED-POINT").
345    // Just sanity-check that non-zero input produces a defined result.
346    assert!(out >= 0 || out < 0, "defined integer output: {out}");
347  }
348
349  #[test]
350  fn constants_unity_matches_f64() {
351    // The integer UNITY and f64 UNITY_F64 must agree numerically.
352    assert_eq!(UNITY as f64, UNITY_F64);
353  }
354
355  #[test]
356  fn fixpoint_unit_matches_pdftex() {
357    // Ground-truth scaled-point values captured from pdftex (TeX Live 2025):
358    //   `\dimen0=<value><unit> \showthe\dimen0`. These are the cases where the
359    //   legacy float multiply drifts ±1 sp; the integer path is bit-exact.
360    //   See issue #127. (num, den) are tex.web §458 set_conversion fractions.
361    let cases: &[(f64, i64, i64, i64)] = &[
362      // value, num, den, expected sp
363      (1.0, 7227, 100, 4736286),         // 1in   = 72.26999pt
364      (1.0, 7227, 254, 1864679),         // 1cm   = 28.45274pt
365      (1.0, 7227, 2540, 186467),         // 1mm   = 2.84526pt
366      (1.0, 7227, 7200, 65781),          // 1bp   = 1.00374pt
367      (1.0, 1238, 1157, 70124),          // 1dd   = 1.07pt
368      (1.0, 14856, 1157, 841489),        // 1cc   = 12.8401pt
369      (76.24341, 7227, 254, 142169544),  // cm: float gave 142169543 (off by 1)
370      (400.43946, 7227, 7200, 26341612), // bp: float gave 26341611
371      (188.33008, 7227, 7200, 12388684), // bp: float gave 12388683
372      (75.77057, 7227, 2540, 14128785),  // mm: float gave 14128784
373      (76.40832, 14856, 1157, 64296768), // cc: float gave 64296767
374    ];
375    for &(value, num, den, expected) in cases {
376      assert_eq!(
377        fixpoint_unit(value, num, den),
378        expected,
379        "fixpoint_unit({value}, {num}, {den}) should match pdftex"
380      );
381    }
382  }
383
384  #[test]
385  fn fixpoint_unit_is_exact_floor() {
386    // fixpoint_unit must equal floor(fix·num/den), the integer collapse of
387    // tex.web scan_dimen — no float drift. Cross-check against an independent
388    // i128 floor over a deterministic sweep.
389    let units: &[(i64, i64)] = &[(7227, 100), (7227, 254), (7227, 2540), (7227, 7200)];
390    for &(num, den) in units {
391      for k in 0..2000 {
392        let value = k as f64 * 0.13759 + 0.0007; // varied non-round decimals
393        let fix = kround(value * UNITY_F64) as i128;
394        let expected = (fix * num as i128 / den as i128) as i64;
395        assert_eq!(fixpoint_unit(value, num, den), expected);
396      }
397    }
398  }
399}