Skip to main content

latexml_core/common/
dimension.rs

1use std::{fmt, sync::LazyLock};
2
3use regex::Regex;
4
5use crate::{
6  Digested, RegisterValue,
7  common::{
8    error::*,
9    numeric_ops::{NumericOps, UNITY, UNITY_F64, fixpoint_unit, kround, round_to},
10    object::Object,
11  },
12  definition::register::RegisterType,
13  state::*,
14  tokens::Tokens,
15};
16
17static SPEC_RE: LazyLock<Regex> =
18  LazyLock::new(|| Regex::new(r"^(-?\d*\.?\d*)([a-zA-Z][a-zA-Z])$").unwrap());
19
20#[derive(Debug, Copy, Clone, Default, PartialEq, Eq)]
21pub struct Dimension(pub i64);
22
23impl Object for Dimension {
24  fn revert(&self) -> Result<Tokens> { Ok(Tokens::new(ExplodeText!(&self.to_string()))) }
25  fn be_digested(self) -> Result<Digested>
26  where
27    Self: Sized,
28    Self: fmt::Debug,
29  {
30    Ok(Digested::from(RegisterValue::Dimension(self)))
31  }
32}
33impl NumericOps for Dimension {
34  fn new(number: i64) -> Self { Dimension(number) }
35  fn new_f64(number: f64) -> Self { Dimension(kround(number)) }
36  fn value_of(self) -> i64 { self.0 }
37  fn register_type(&self) -> RegisterType { RegisterType::Dimension }
38  fn unit(&self) -> Option<&'static str> { Some("pt") }
39  fn to_attribute(&self) -> String { attribute_format(self.value_of(), self.unit()) }
40}
41
42impl fmt::Display for Dimension {
43  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
44    write!(f, "{}", fixedformat(self.0, self.unit()))
45  }
46}
47
48impl Dimension {
49  /// Convert dimension to em units, using the given font's EM width (or current font if None).
50  pub fn em_value(&self, prec: Option<u8>, font: Option<&crate::common::font::Font>) -> f64 {
51    let em_width: f64 = if let Some(f) = font {
52      f.get_em_width() as f64
53    } else {
54      lookup_font()
55        .map(|f| f.get_em_width() as f64)
56        .unwrap_or(UNITY_F64 * 10.0) // fallback: 10pt
57    };
58    round_to(self.0 as f64 / em_width, prec)
59  }
60
61  /// Whether [`Self::spec_to_f64`] reads `spec` as written: empty, a dimension (`SPEC_RE`), or a number of sp.
62  pub fn spec_is_readable(spec: &str) -> bool {
63    spec.is_empty() || SPEC_RE.is_match(spec) || spec.parse::<f64>().is_ok()
64  }
65
66  pub fn spec_to_f64(spec: &str) -> Result<f64> {
67    if spec.is_empty() {
68      Ok(0.0)
69    } else if let Some(cap) = SPEC_RE.captures(spec) {
70      // Dimensions given. SPEC_RE's numeric part is `-?\d*\.?\d*` which
71      // can match empty (e.g. input "pt"); Perl's `fixpoint($1, ...)`
72      // coerces "" → 0 via numeric context, so unwrap_or(0.0) keeps parity.
73      let num_str = cap.get(1).map_or("", |m| m.as_str());
74      let num: f64 = num_str.parse::<f64>().unwrap_or(0.0);
75      let unit = cap.get(2).map_or("", |m| m.as_str());
76      let (conv_num, conv_den) = convert_unit_ratio(unit);
77      Ok(fixpoint_unit(num, conv_num, conv_den) as f64)
78    } else {
79      // When scaled points passed in (typically the result of Perl calculations on other
80      // Dimensions), you might think truncation (int) is more TeX-like.
81      // Recall that TeX arithmatic truncates, whereas reading by Gullet tends to round.
82      // The Perl arithmetic is replacing an unknown combination of those truncates & rounds.
83      // As it turns out, using int() here results in non-terminating loops in pgf/tikz.
84      // So, we use round (Knuth style)
85      // Note that divide and such explicitly use int(), however!
86      // Perl parity: `kround($spec || 0)` — non-numeric input coerces to 0.
87      Ok(kround(spec.parse::<f64>().unwrap_or(0.0)) as f64)
88    }
89  }
90}
91
92impl Dimension {
93  /// Whether `spec` is a form Perl's `Dimension($spec)` reads (Dimension.pm `new`): a number with a two-letter
94  /// unit, or a bare number of sp; any other string Perl reads as a number, silently (`"1pt plus 2pt"` is 1sp).
95  pub fn is_spec(spec: &str) -> bool {
96    spec.is_empty() || SPEC_RE.is_match(spec) || spec.parse::<f64>().is_ok()
97  }
98}
99
100impl std::str::FromStr for Dimension {
101  type Err = Error;
102  fn from_str(spec: &str) -> Result<Dimension> {
103    Ok(Dimension::new_f64(Dimension::spec_to_f64(spec)?))
104  }
105}
106
107// Dimension!() macro is in setup.rs, since it binds state
108
109// This is Knuth's print_scaled (See TeX the Program, \S 103)
110// It (should) round-trip with kround.
111pub fn fixedformat(mut s: i64, unit_opt: Option<&str>) -> String {
112  use std::fmt::Write as _;
113  // Format directly into `string`; `write!` into a String is infallible.
114  // Avoids the per-iteration `i64::to_string()` temporaries the Perl-faithful
115  // algorithm would otherwise leak on a very hot path (≈1M calls/doc).
116  let mut string = String::new();
117  if s < 0 {
118    string.push('-');
119    s = s.saturating_neg(); // i64::MIN (an overflowed product) cannot be negated
120  }
121  write!(string, "{}", s / UNITY).unwrap();
122  string.push('.');
123  s = 10 * (s % UNITY) + 5;
124  let mut delta = 10;
125  loop {
126    if delta > UNITY {
127      s += 0x8000 - 50000;
128    }
129    write!(string, "{}", s / UNITY).unwrap();
130    s = 10 * (s % UNITY);
131    delta *= 10;
132    if s <= delta {
133      break;
134    }
135  }
136  if let Some(unit) = unit_opt {
137    string.push_str(unit);
138  }
139  string
140}
141
142pub fn attribute_format(sp: i64, unit_opt: Option<&str>) -> String {
143  let unit = unit_opt.unwrap_or("pt");
144  s!("{:.1}{unit}", round_to(sp as f64 / UNITY_F64, Some(1)))
145}
146
147#[cfg(test)]
148mod tests {
149  use super::*;
150
151  #[test]
152  fn fixedformat_zero() {
153    // Knuth's print_scaled of 0 with a unit.
154    assert_eq!(fixedformat(0, Some("pt")), "0.0pt");
155    assert_eq!(fixedformat(0, None), "0.0");
156  }
157
158  #[test]
159  fn fixedformat_one_sp_unit() {
160    // UNITY = 65536 scaled-points = 1pt.
161    assert_eq!(fixedformat(UNITY, Some("pt")), "1.0pt");
162    assert_eq!(fixedformat(2 * UNITY, Some("pt")), "2.0pt");
163  }
164
165  #[test]
166  fn fixedformat_negative() {
167    assert_eq!(fixedformat(-UNITY, Some("pt")), "-1.0pt");
168    assert_eq!(fixedformat(-2 * UNITY, Some("pt")), "-2.0pt");
169  }
170
171  #[test]
172  fn fixedformat_half_pt() {
173    // 0.5 pt = UNITY/2 = 32768 sp.
174    let out = fixedformat(UNITY / 2, Some("pt"));
175    assert_eq!(out, "0.5pt");
176  }
177
178  #[test]
179  fn attribute_format_defaults_to_pt() {
180    assert_eq!(attribute_format(UNITY, None), "1.0pt");
181    assert_eq!(attribute_format(UNITY, Some("pt")), "1.0pt");
182  }
183
184  #[test]
185  fn attribute_format_other_unit() {
186    assert_eq!(attribute_format(UNITY, Some("in")), "1.0in");
187  }
188
189  #[test]
190  fn attribute_format_rounds_to_one_decimal() {
191    // sp = UNITY * 1.25 → 1.3pt (round to 1 decimal, half-up).
192    let sp = (UNITY_F64 * 1.25) as i64;
193    let out = attribute_format(sp, None);
194    assert_eq!(out, "1.3pt", "got {out:?}");
195  }
196
197  #[test]
198  fn spec_to_f64_empty_is_zero() {
199    assert_eq!(Dimension::spec_to_f64("").unwrap(), 0.0);
200  }
201
202  #[test]
203  fn spec_to_f64_bare_number_is_scaled() {
204    // No unit → treated as scaled-points directly; the value is
205    // kround()-ed through, so "65536" stays 65536.
206    let out = Dimension::spec_to_f64("65536").unwrap();
207    assert_eq!(out, 65536.0);
208  }
209}