From c7db709da53e0559adabc99d483a374224ef5ce8 Mon Sep 17 00:00:00 2001 From: Eric Biedert Date: Tue, 11 Apr 2023 14:13:01 +0200 Subject: [PATCH] Allow treating ratios as floats (#681) --- library/src/compute/construct.rs | 3 +++ src/eval/ops.rs | 3 +++ src/geom/ratio.rs | 8 ++++++++ tests/typ/compute/calc.typ | 3 ++- 4 files changed, 16 insertions(+), 1 deletion(-) diff --git a/library/src/compute/construct.rs b/library/src/compute/construct.rs index e7e05eeea..4ba73a739 100644 --- a/library/src/compute/construct.rs +++ b/library/src/compute/construct.rs @@ -45,6 +45,7 @@ cast_from_value! { /// /// - Booleans are converted to `0.0` or `1.0`. /// - Integers are converted to the closest 64-bit float. +/// - Ratios are divided by 100%. /// - Strings are parsed in base 10 to the closest 64-bit float. /// Exponential notation is supported. /// @@ -53,6 +54,7 @@ cast_from_value! { /// #float(false) \ /// #float(true) \ /// #float(4) \ +/// #float(40%) \ /// #float("2.7") \ /// #float("1e5") /// ``` @@ -76,6 +78,7 @@ cast_from_value! { v: bool => Self(v as i64 as f64), v: i64 => Self(v as f64), v: f64 => Self(v), + v: Ratio => Self(v.get()), v: EcoString => Self(v.parse().map_err(|_| "not a valid float")?), } diff --git a/src/eval/ops.rs b/src/eval/ops.rs index 5efb68c37..91160c0de 100644 --- a/src/eval/ops.rs +++ b/src/eval/ops.rs @@ -179,6 +179,7 @@ pub fn mul(lhs: Value, rhs: Value) -> StrResult { (Int(a), Angle(b)) => Angle(a as f64 * b), (Float(a), Angle(b)) => Angle(a * b), + (Ratio(a), Ratio(b)) => Ratio(a * b), (Ratio(a), Int(b)) => Ratio(a * b as f64), (Ratio(a), Float(b)) => Ratio(a * b), (Float(a), Ratio(b)) => Ratio(a * b), @@ -214,8 +215,10 @@ pub fn div(lhs: Value, rhs: Value) -> StrResult { Ok(match (lhs, rhs) { (Int(a), Int(b)) => Float(a as f64 / b as f64), (Int(a), Float(b)) => Float(a as f64 / b), + (Int(a), Ratio(b)) => Float(a as f64 / b), (Float(a), Int(b)) => Float(a / b as f64), (Float(a), Float(b)) => Float(a / b), + (Float(a), Ratio(b)) => Float(a / b), (Length(a), Int(b)) => Length(a / b as f64), (Length(a), Float(b)) => Length(a / b), diff --git a/src/geom/ratio.rs b/src/geom/ratio.rs index 5490bcba6..fe87dd6cd 100644 --- a/src/geom/ratio.rs +++ b/src/geom/ratio.rs @@ -110,6 +110,14 @@ impl Div for Ratio { } } +impl Div for f64 { + type Output = Self; + + fn div(self, other: Ratio) -> Self { + self / other.get() + } +} + impl Div for Ratio { type Output = f64; diff --git a/tests/typ/compute/calc.typ b/tests/typ/compute/calc.typ index 31c5c967a..18c2e2c96 100644 --- a/tests/typ/compute/calc.typ +++ b/tests/typ/compute/calc.typ @@ -9,6 +9,7 @@ #test(int("150"), 150) #test(int(10 / 3), 3) #test(float(10), 10.0) +#test(float(50% * 30%), 0.15) #test(float("31.4e-1"), 3.14) #test(type(float(10)), "float") @@ -21,7 +22,7 @@ #int(10pt) --- -// Error: 8-13 expected boolean, integer, float, or string, found function +// Error: 8-13 expected boolean, integer, float, ratio, or string, found function #float(float) ---