summaryrefslogtreecommitdiff
path: root/crates
diff options
context:
space:
mode:
authorMalo <57839069+MDLC01@users.noreply.github.com>2024-08-11 22:18:57 +0200
committerGitHub <noreply@github.com>2024-08-11 20:18:57 +0000
commit79fb2c36893140ce61765e2b437ef37c51235615 (patch)
treed2b3cbf8a5926fccf2bdb05446f65b805c104c53 /crates
parent70931ac1f6f68f013e25fe5437e23ad148ce23e1 (diff)
Fix `calc.inf`, `-calc.inf`, and `calc.nan` reprs and displays (#4724)
Diffstat (limited to 'crates')
-rw-r--r--crates/typst/src/foundations/repr.rs20
1 files changed, 15 insertions, 5 deletions
diff --git a/crates/typst/src/foundations/repr.rs b/crates/typst/src/foundations/repr.rs
index 00d9931a..68c94c56 100644
--- a/crates/typst/src/foundations/repr.rs
+++ b/crates/typst/src/foundations/repr.rs
@@ -73,12 +73,15 @@ pub fn format_int_with_base(mut n: i64, base: i64) -> EcoString {
}
/// Converts a float to a string representation with a specific precision and a
-/// suffix, all with a single allocation.
+/// unit, all with a single allocation.
+///
+/// The returned string is always valid Typst code. As such, it might not be a
+/// float literal. For example, it may return `"calc.inf"`.
pub fn format_float(
mut value: f64,
precision: Option<u8>,
force_separator: bool,
- suffix: &str,
+ unit: &str,
) -> EcoString {
if let Some(p) = precision {
let offset = 10_f64.powi(p as i32);
@@ -86,12 +89,16 @@ pub fn format_float(
}
// Debug for f64 always prints a decimal separator, while Display only does
// when necessary.
+ let unit_multiplication = if unit.is_empty() { "" } else { " * 1" };
if value.is_nan() {
- "NaN".into()
+ eco_format!("calc.nan{unit_multiplication}{unit}")
+ } else if value.is_infinite() {
+ let sign = if value < 0.0 { "-" } else { "" };
+ eco_format!("{sign}calc.inf{unit_multiplication}{unit}")
} else if force_separator {
- eco_format!("{:?}{}", value, suffix)
+ eco_format!("{value:?}{unit}")
} else {
- eco_format!("{}{}", value, suffix)
+ eco_format!("{value}{unit}")
}
}
@@ -112,6 +119,9 @@ pub fn format_float_with_unit(value: f64, unit: &str) -> EcoString {
pub fn display_float(value: f64) -> EcoString {
if value.is_nan() {
"NaN".into()
+ } else if value.is_infinite() {
+ let sign = if value < 0.0 { MINUS_SIGN } else { "" };
+ eco_format!("{sign}∞")
} else if value < 0.0 {
eco_format!("{}{}", MINUS_SIGN, value.abs())
} else {