difftreelog
feat implement builtins for trivial numeric functions
in: master
3 files changed
crates/jrsonnet-stdlib/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/lib.rs
+++ b/crates/jrsonnet-stdlib/src/lib.rs
@@ -77,6 +77,11 @@
("member", builtin_member::INST),
("count", builtin_count::INST),
// Math
+ ("abs", builtin_abs::INST),
+ ("sign", builtin_sign::INST),
+ ("max", builtin_max::INST),
+ ("min", builtin_min::INST),
+ ("clamp", builtin_clamp::INST),
("modulo", builtin_modulo::INST),
("floor", builtin_floor::INST),
("ceil", builtin_ceil::INST),
crates/jrsonnet-stdlib/src/math.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/math.rs
+++ b/crates/jrsonnet-stdlib/src/math.rs
@@ -1,6 +1,42 @@
use jrsonnet_evaluator::{error::Result, function::builtin, typed::PositiveF64};
#[builtin]
+pub fn builtin_abs(x: f64) -> Result<f64> {
+ Ok(x.abs())
+}
+
+#[builtin]
+pub fn builtin_sign(x: f64) -> Result<f64> {
+ Ok(if x == 0. { 0. } else { x.signum() })
+}
+
+#[builtin]
+pub fn builtin_max(x: f64, y: f64) -> Result<f64> {
+ Ok(x.max(y))
+}
+
+#[builtin]
+pub fn builtin_min(x: f64, y: f64) -> Result<f64> {
+ Ok(x.min(y))
+}
+
+#[builtin]
+pub fn builtin_clamp(x: f64, min_val: f64, max_val: f64) -> Result<f64> {
+ debug_assert!(x.is_finite(), "jsonnet number are always finite");
+ debug_assert!(min_val.is_finite(), "jsonnet number are always finite");
+ debug_assert!(max_val.is_finite(), "jsonnet number are always finite");
+
+ // `f64::clamp` should noe be used here since it requires extra checks to guarantee NaN-safety
+ Ok(if x < min_val {
+ min_val
+ } else if x > max_val {
+ max_val
+ } else {
+ x
+ })
+}
+
+#[builtin]
pub fn builtin_modulo(a: f64, b: f64) -> Result<f64> {
Ok(a % b)
}
crates/jrsonnet-stdlib/src/std.jsonnetdiffbeforeafterboth77 else77 else78 error 'Assertion failed. ' + a + ' != ' + b,78 error 'Assertion failed. ' + a + ' != ' + b,797980 abs(n)::81 if !std.isNumber(n) then82 error 'std.abs expected number, got ' + std.type(n)83 else84 if n > 0 then n else -n,8586 sign(n)::87 if !std.isNumber(n) then88 error 'std.sign expected number, got ' + std.type(n)89 else90 if n > 0 then91 192 else if n < 0 then93 -194 else 0,9596 max(a, b)::97 if !std.isNumber(a) then98 error 'std.max first param expected number, got ' + std.type(a)99 else if !std.isNumber(b) then100 error 'std.max second param expected number, got ' + std.type(b)101 else102 if a > b then a else b,103104 min(a, b)::105 if !std.isNumber(a) then106 error 'std.min first param expected number, got ' + std.type(a)107 else if !std.isNumber(b) then108 error 'std.min second param expected number, got ' + std.type(b)109 else110 if a < b then a else b,111112 clamp(x, minVal, maxVal)::80 clamp(x, minVal, maxVal)::113 if x < minVal then minVal81 if x < minVal then minVal114 else if x > maxVal then maxVal82 else if x > maxVal then maxVal