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
15pub 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 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
34pub 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
47pub 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
61pub 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
82pub const MAX_DIMEN: i64 = 0x3FFF_FFFF;
89
90pub 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
98pub 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
108pub 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 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
123pub const MAX_INTEGER: i64 = 0x7FFF_FFFF;
126
127pub 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 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 fn arith_ceiling() -> i64 { MAX_DIMEN }
217 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; }
224 Self::new((self.value_of() as f64 / other_value).trunc() as i64)
225 }
226
227 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 fn into_glue_type(self) -> Glue
276 where Self: Sized {
277 Glue::new(0) }
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 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 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 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 let out = fixpoint(1.0, Some(1.0));
344 assert!(out >= 0 || out < 0, "defined integer output: {out}");
347 }
348
349 #[test]
350 fn constants_unity_matches_f64() {
351 assert_eq!(UNITY as f64, UNITY_F64);
353 }
354
355 #[test]
356 fn fixpoint_unit_matches_pdftex() {
357 let cases: &[(f64, i64, i64, i64)] = &[
362 (1.0, 7227, 100, 4736286), (1.0, 7227, 254, 1864679), (1.0, 7227, 2540, 186467), (1.0, 7227, 7200, 65781), (1.0, 1238, 1157, 70124), (1.0, 14856, 1157, 841489), (76.24341, 7227, 254, 142169544), (400.43946, 7227, 7200, 26341612), (188.33008, 7227, 7200, 12388684), (75.77057, 7227, 2540, 14128785), (76.40832, 14856, 1157, 64296768), ];
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 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; 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}