Skip to main content

latexml_core/common/
float.rs

1use std::{fmt, sync::LazyLock};
2
3use regex::Regex;
4
5use crate::{
6  common::{error::Result, numeric_ops::NumericOps, object::Object},
7  definition::register::RegisterType,
8  mouth,
9  tokens::{TeXString, Tokens},
10};
11
12static TRAILING_ZEROS: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"0+$").unwrap());
13
14//======================================================================
15// Strictly speaking, Float isn't part of TeX, but it's handy.
16
17#[derive(Debug, Copy, Clone, PartialEq)]
18pub struct Float(pub f64);
19
20impl Default for Float {
21  fn default() -> Self { Float(0.0) }
22}
23
24impl Object for Float {
25  fn revert(&self) -> Result<Tokens> { Ok(Tokens::new(ExplodeText!(&self.to_string()))) }
26  fn stringify(&self) -> String { s!("Float[{}]", self.0) }
27  fn be_digested(self) -> Result<crate::Digested> {
28    // Float can be digested as a text box containing its string representation
29    // TODO: Perl's Float digests to itself (Common/Object.pm:156 `beDigested`),
30    // a value that is no box and measures nothing; this text box measures its
31    // digits. That needs a `RegisterValue::Float` (own batch), and would make
32    // the explicit sizers of the `{Float}` picture constructors unnecessary
33    // (latex_constructs/sect13.rs: `\lx@pic@line` and `\vector` `sizer => 0`,
34    // `\circle` `sizer => "#1"`, `\oval` `sizer => "#3"`).
35    let s = self.to_string();
36    Ok(
37      crate::Tbox::new(
38        // `pin` takes `AsRef<str>` — `&String` borrows cleanly without
39        // an extra `.to_string()` clone that `into_pin` would force.
40        crate::common::arena::pin(&s),
41        None,
42        None,
43        Tokens::new(ExplodeText!(&s)),
44        crate::common::arena::SymHashMap::default(),
45      )
46      .into(),
47    )
48  }
49}
50
51impl NumericOps for Float {
52  fn new(number: i64) -> Self { Float(number as f64) }
53  fn new_f64(number: f64) -> Self { Float(number) }
54  fn value_of(self) -> i64 { self.0 as i64 }
55  fn value_f64(self) -> f64 { self.0 }
56  fn negate(self) -> Self { Float(-self.0) }
57  fn register_type(&self) -> RegisterType { RegisterType::Number }
58  fn add<T: NumericOps>(self, other: T) -> Self { Float::new_f64(self.0 + other.value_f64()) }
59  fn subtract<T: NumericOps>(self, other: T) -> Self { Float::new_f64(self.0 - other.value_f64()) }
60  fn multiply<T: NumericOps>(self, other: T) -> Self { Float::new_f64(self.0 * other.value_f64()) }
61  fn divide<T: NumericOps>(self, other: T) -> Self { Float::new_f64(self.0 / other.value_f64()) }
62}
63
64impl From<Float> for Tokens {
65  fn from(v: Float) -> Tokens { mouth::tokenize_internal(TeXString::assembled(v.to_string())) }
66}
67
68impl From<Float> for Option<Tokens> {
69  fn from(v: Float) -> Option<Tokens> { Some(v.into()) }
70}
71
72impl fmt::Display for Float {
73  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", floatformat(self.0)) }
74}
75
76impl Float {
77  /// Tight formatting of floats, where we emit them as integers when they do not have a decimal
78  /// part used in e.g. the multido.sty binding and test
79  pub fn to_tight_string(&self) -> String { custom_float_format(self.0, true) }
80}
81
82/// Utility for formatting sane numbers.
83pub fn floatformat(n: f64) -> String { custom_float_format(n, false) }
84pub fn custom_float_format(n: f64, tight: bool) -> String {
85  let mut s = format!("{:.5}", n);
86  if s.contains('.') {
87    s = TRAILING_ZEROS.replace(&s, "").to_string();
88  }
89  if s.ends_with('.') {
90    if tight {
91      // tight format does not need the trailing dot
92      s.pop();
93    } else {
94      s.push('0'); //  Seems TeX prints .0 which in odd corner cases, people use?
95    }
96  }
97  s
98}
99
100impl From<&str> for Float {
101  /// Non-numeric input silently becomes 0.0 (Perl parity — see the
102  /// `From<String>` impl).
103  fn from(spec: &str) -> Self { Float(spec.trim().parse::<f64>().unwrap_or(0.0)) }
104}
105impl From<String> for Float {
106  /// Parse a string into a Float. Non-numeric input silently becomes 0.0
107  /// to match Perl's implicit numeric coercion — `Float("abc")` + x in
108  /// Perl yields x, not a panic.
109  fn from(spec: String) -> Self { Float(spec.trim().parse::<f64>().unwrap_or(0.0)) }
110}
111
112#[cfg(test)]
113mod tests {
114  use super::*;
115
116  #[test]
117  fn floatformat_integer_gets_dot_zero() {
118    assert_eq!(floatformat(1.0), "1.0");
119    assert_eq!(floatformat(0.0), "0.0");
120    assert_eq!(floatformat(-5.0), "-5.0");
121  }
122
123  #[test]
124  fn floatformat_trims_trailing_zeros() {
125    assert_eq!(floatformat(1.5), "1.5");
126    assert_eq!(floatformat(1.25), "1.25");
127    assert_eq!(floatformat(0.10000), "0.1");
128  }
129
130  #[test]
131  fn tight_format_drops_dot_for_integers() {
132    assert_eq!(Float(1.0).to_tight_string(), "1");
133    assert_eq!(Float(0.0).to_tight_string(), "0");
134    assert_eq!(Float(1.5).to_tight_string(), "1.5");
135  }
136
137  #[test]
138  fn custom_float_format_precision() {
139    let out = custom_float_format(0.123456789, false);
140    assert!(
141      out.starts_with("0.12346") || out.starts_with("0.12345"),
142      "got {out:?}"
143    );
144  }
145
146  #[test]
147  fn from_str_nonnumeric_is_zero() {
148    assert_eq!(Float::from("abc").0, 0.0);
149    assert_eq!(Float::from("  xyz  ").0, 0.0);
150    assert_eq!(Float::from("").0, 0.0);
151  }
152
153  #[test]
154  fn from_str_numeric_parses() {
155    assert_eq!(Float::from("1.5").0, 1.5);
156    assert_eq!(Float::from("  -3.125  ").0, -3.125);
157    assert_eq!(Float::from("42").0, 42.0);
158  }
159
160  #[test]
161  fn from_string_matches_from_str() {
162    for s in &["1", "1.5", "", "abc", "-0.0001"] {
163      let a = Float::from(*s).0;
164      let b = Float::from(s.to_string()).0;
165      assert_eq!(a, b, "divergence on {s:?}: {a} vs {b}");
166    }
167  }
168
169  #[test]
170  fn float_arithmetic_roundtrip() {
171    let a = Float::new_f64(1.5);
172    let b = Float::new_f64(2.5);
173    assert_eq!(a.add(b).value_f64(), 4.0);
174    assert_eq!(b.subtract(a).value_f64(), 1.0);
175    assert_eq!(a.multiply(b).value_f64(), 3.75);
176    assert_eq!(b.divide(a).value_f64(), 2.5 / 1.5);
177  }
178
179  #[test]
180  fn float_negate() {
181    assert_eq!(Float::new_f64(1.5).negate().value_f64(), -1.5);
182    assert_eq!(Float::new_f64(0.0).negate().value_f64(), 0.0);
183  }
184}