latexml_core/common/
dimension.rs1use 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 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) };
58 round_to(self.0 as f64 / em_width, prec)
59 }
60
61 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 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 Ok(kround(spec.parse::<f64>().unwrap_or(0.0)) as f64)
88 }
89 }
90}
91
92impl Dimension {
93 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
107pub fn fixedformat(mut s: i64, unit_opt: Option<&str>) -> String {
112 use std::fmt::Write as _;
113 let mut string = String::new();
117 if s < 0 {
118 string.push('-');
119 s = s.saturating_neg(); }
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 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 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 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 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 let out = Dimension::spec_to_f64("65536").unwrap();
207 assert_eq!(out, 65536.0);
208 }
209}