Skip to main content

latexml_core/common/
mudimension.rs

1use std::{fmt, sync::LazyLock};
2
3use regex::Regex;
4
5use super::dimension::fixedformat;
6use crate::{
7  Object,
8  common::numeric_ops::{NumericOps, UNITY_F64, fixpoint, kround},
9  definition::register::RegisterType,
10};
11
12static MUDIM_SPEC_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^(-?\d*\.?\d*)mu$").unwrap());
13
14#[derive(Debug, Copy, Clone, PartialEq, Default, Eq)]
15pub struct MuDimension(pub i64);
16
17impl NumericOps for MuDimension {
18  fn new(number: i64) -> Self { MuDimension(number) }
19  fn new_f64(number: f64) -> Self { MuDimension(kround(number)) }
20  fn value_of(self) -> i64 { self.0 }
21  fn register_type(&self) -> RegisterType { RegisterType::MuDimension }
22  fn unit(&self) -> Option<&'static str> { Some("mu") }
23  // XML attribute output is pt-typed by convention. Convert mu→pt via
24  // Perl `MuGlue::ptValue` two-step truncation so XMHint width attrs
25  // emit `1.66663pt` not `3.0mu` (and downstream lpadding/rpadding
26  // transferred from the XMHint width keep the pt unit).
27  fn to_attribute(&self) -> String {
28    let fs = crate::state::lookup_font()
29      .and_then(|f| f.get_size())
30      .unwrap_or(10.0);
31    let muwidth = (fs * UNITY_F64 / 18.0) as i64;
32    let pt_scaled = ((self.0 as f64 * muwidth as f64 / UNITY_F64).trunc()) as i64;
33    super::dimension::attribute_format(pt_scaled, Some("pt"))
34  }
35}
36
37impl fmt::Display for MuDimension {
38  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
39    write!(f, "{}", fixedformat(self.0, self.unit()))
40  }
41}
42impl Object for MuDimension {}
43
44impl MuDimension {
45  pub fn new_spec(spec: &str) -> Self {
46    if let Some(cap) = MUDIM_SPEC_RE.captures(spec) {
47      // The numeric capture `-?\d*\.?\d*` can match empty (e.g. input
48      // "mu"); Perl's fixpoint coerces "" → 0 via numeric context, so
49      // unwrap_or(0.0) keeps parity.
50      let num: f64 = cap
51        .get(1)
52        .map_or("", |m| m.as_str())
53        .parse::<f64>()
54        .unwrap_or(0.0);
55      MuDimension(fixpoint(num, Some(UNITY_F64)))
56    } else {
57      // Perl parity: bad input coerces to 0.
58      MuDimension(kround(spec.parse::<f64>().unwrap_or(0.0)))
59    }
60  }
61}
62
63#[cfg(test)]
64mod tests {
65  use super::*;
66
67  #[test]
68  fn mudim_default_is_zero() {
69    assert_eq!(MuDimension::default().value_of(), 0);
70  }
71
72  #[test]
73  fn mudim_new_builds_value() {
74    assert_eq!(MuDimension::new(65536).value_of(), 65536);
75    assert_eq!(MuDimension::new(0).value_of(), 0);
76    assert_eq!(MuDimension::new(-100).value_of(), -100);
77  }
78
79  #[test]
80  fn mudim_new_f64_rounds_knuthian() {
81    assert_eq!(MuDimension::new_f64(0.0).value_of(), 0);
82    assert_eq!(MuDimension::new_f64(1.0).value_of(), 1);
83    assert_eq!(MuDimension::new_f64(-1.0).value_of(), -1);
84  }
85
86  #[test]
87  fn mudim_register_type_is_mudimension() {
88    assert_eq!(
89      MuDimension::default().register_type(),
90      RegisterType::MuDimension
91    );
92  }
93
94  #[test]
95  fn mudim_unit_is_mu() {
96    assert_eq!(MuDimension::default().unit(), Some("mu"));
97  }
98
99  #[test]
100  fn mudim_display_includes_mu_unit() {
101    let m = MuDimension::new(65536); // 1mu in scaled units
102    let out = format!("{m}");
103    assert!(out.ends_with("mu"), "got {out:?}");
104  }
105
106  #[test]
107  fn new_spec_parses_numeric_with_mu() {
108    // "1mu" parses as MuDimension(fixpoint(1.0, UNITY_F64)).
109    let m = MuDimension::new_spec("1mu");
110    assert_ne!(m.value_of(), 0, "1mu should not be zero");
111    // "0mu" is zero.
112    let m0 = MuDimension::new_spec("0mu");
113    assert_eq!(m0.value_of(), 0);
114  }
115
116  #[test]
117  fn new_spec_empty_numeric_part_is_zero() {
118    // "mu" (bare unit, no number) coerces to 0 via Perl-parity.
119    let m = MuDimension::new_spec("mu");
120    assert_eq!(m.value_of(), 0);
121  }
122
123  #[test]
124  fn new_spec_bad_input_is_zero() {
125    // Non-matching spec falls through to bare-number parse → 0 if that
126    // also fails.
127    let m = MuDimension::new_spec("not a number");
128    assert_eq!(m.value_of(), 0);
129  }
130
131  #[test]
132  fn mudim_equality() {
133    assert_eq!(MuDimension::new(100), MuDimension::new(100));
134    assert_ne!(MuDimension::new(100), MuDimension::new(101));
135  }
136}