Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add features: decimal_support/empty_is_null #140

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ description = "A powerful arithmetic and boolean expression evaluator"
keywords = ["expression", "evaluate", "evaluator", "arithmetic", "boolean"]
categories = ["parsing", "game-engines"]
authors = ["isibboi <[email protected]>"]
repository = "https://github.com/ISibboI/evalexpr.git"
repository = "https://github.com/ISibboI/evalexpr"
homepage = "https://github.com/ISibboI/evalexpr"
documentation = "https://docs.rs/evalexpr"
readme = "README.md"
Expand All @@ -27,10 +27,13 @@ regex = { version = "1.5.5", optional = true}
serde = { version = "1.0.133", optional = true}
serde_derive = { version = "1.0.133", optional = true}
rand = { version = "0.8.5", optional = true}
rust_decimal = { version = "1.30.0", features = ["maths"], optional = true }

[features]
serde_support = ["serde", "serde_derive"]
regex_support = ["regex"]
decimal_support = ["rust_decimal"]
empty_is_null = []

[dev-dependencies]
ron = "0.7.0"
Expand Down
7 changes: 7 additions & 0 deletions src/context/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,13 @@ impl Context for HashMapContext {
impl ContextWithMutableVariables for HashMapContext {
fn set_value(&mut self, identifier: String, value: Value) -> EvalexprResult<()> {
if let Some(existing_value) = self.variables.get_mut(&identifier) {
#[cfg(feature = "empty_is_null")]
{
if value.is_empty() {
*existing_value = value;
return Ok(());
}
}
if ValueType::from(&existing_value) == ValueType::from(&value) {
*existing_value = value;
return Ok(());
Expand Down
113 changes: 100 additions & 13 deletions src/function/builtin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ macro_rules! simple_math {
};
}

#[allow(unused)]
fn float_is(func: fn(FloatType) -> bool) -> Option<Function> {
Some(Function::new(move |argument| {
Ok(func(argument.as_number()?).into())
Expand All @@ -46,46 +47,89 @@ macro_rules! int_function {
}

pub fn builtin_function(identifier: &str) -> Option<Function> {
#[cfg(feature = "decimal_support")]
use rust_decimal::prelude::*;
match identifier {
// Log
"math::ln" => simple_math!(ln),
#[cfg(not(feature = "decimal_support"))]
"math::log" => simple_math!(log, 2),
#[cfg(not(feature = "decimal_support"))]
"math::log2" => simple_math!(log2),
"math::log10" => simple_math!(log10),
// Exp
"math::exp" => simple_math!(exp),
#[cfg(not(feature = "decimal_support"))]
"math::exp2" => simple_math!(exp2),
// Pow
#[cfg(feature = "decimal_support")]
"math::pow" => Some(Function::new(|argument| {
let tuple = argument.as_fixed_len_tuple(2)?;
let (a, b) = (tuple[0].as_number()?, tuple[1].as_number()?);
Ok(Value::Float(a.powf(b.to_f64().unwrap())))
})),
#[cfg(not(feature = "decimal_support"))]
"math::pow" => simple_math!(powf, 2),
// Cos
"math::cos" => simple_math!(cos),
#[cfg(not(feature = "decimal_support"))]
"math::acos" => simple_math!(acos),
#[cfg(not(feature = "decimal_support"))]
"math::cosh" => simple_math!(cosh),
#[cfg(not(feature = "decimal_support"))]
"math::acosh" => simple_math!(acosh),
// Sin
"math::sin" => simple_math!(sin),
#[cfg(not(feature = "decimal_support"))]
"math::asin" => simple_math!(asin),
#[cfg(not(feature = "decimal_support"))]
"math::sinh" => simple_math!(sinh),
#[cfg(not(feature = "decimal_support"))]
"math::asinh" => simple_math!(asinh),
// Tan
"math::tan" => simple_math!(tan),
#[cfg(not(feature = "decimal_support"))]
"math::atan" => simple_math!(atan),
#[cfg(not(feature = "decimal_support"))]
"math::tanh" => simple_math!(tanh),
#[cfg(not(feature = "decimal_support"))]
"math::atanh" => simple_math!(atanh),
#[cfg(not(feature = "decimal_support"))]
"math::atan2" => simple_math!(atan2, 2),
// Root
#[cfg(feature = "decimal_support")]
"math::sqrt" => Some(Function::new(|argument| {
let num = argument.as_number()?;
Ok(Value::Float(num.sqrt().unwrap()))
})),
#[cfg(not(feature = "decimal_support"))]
"math::sqrt" => simple_math!(sqrt),
#[cfg(not(feature = "decimal_support"))]
"math::cbrt" => simple_math!(cbrt),
// Hypotenuse
#[cfg(not(feature = "decimal_support"))]
"math::hypot" => simple_math!(hypot, 2),
// Rounding
"floor" => simple_math!(floor),
#[cfg(feature = "decimal_support")]
"round" => Some(Function::new(|argument| {
let num = argument.as_number()?;
Ok(Value::Float(num.round_dp_with_strategy(
0,
RoundingStrategy::MidpointAwayFromZero,
)))
})),
#[cfg(not(feature = "decimal_support"))]
"round" => simple_math!(round),
"ceil" => simple_math!(ceil),
// Float special values
#[cfg(not(feature = "decimal_support"))]
"math::is_nan" => float_is(FloatType::is_nan),
#[cfg(not(feature = "decimal_support"))]
"math::is_finite" => float_is(FloatType::is_finite),
#[cfg(not(feature = "decimal_support"))]
"math::is_infinite" => float_is(FloatType::is_infinite),
#[cfg(not(feature = "decimal_support"))]
"math::is_normal" => float_is(FloatType::is_normal),
// Absolute
"math::abs" => Some(Function::new(|argument| match argument {
Expand All @@ -108,45 +152,79 @@ pub fn builtin_function(identifier: &str) -> Option<Function> {
"min" => Some(Function::new(|argument| {
let arguments = argument.as_tuple()?;
let mut min_int = IntType::max_value();
let mut min_float: FloatType = 1.0 / 0.0;
debug_assert!(min_float.is_infinite());
let mut min_float = Option::<FloatType>::None;

for argument in arguments {
if let Value::Float(float) = argument {
min_float = min_float.min(float);
if let Some(min) = min_float {
min_float = Some(min.max(float));
} else {
min_float = Some(float);
}
} else if let Value::Int(int) = argument {
min_int = min_int.min(int);
} else {
return Err(EvalexprError::expected_number(argument));
}
}

if (min_int as FloatType) < min_float {
Ok(Value::Int(min_int))
if let Some(min_float) = min_float {
if ({
#[cfg(feature = "decimal_support")]
{
FloatType::from_i64(min_int).unwrap()
}
#[cfg(not(feature = "decimal_support"))]
{
min_int as FloatType
}
}) < min_float
{
Ok(Value::Int(min_int))
} else {
Ok(Value::Float(min_float))
}
} else {
Ok(Value::Float(min_float))
Ok(Value::Int(min_int))
}
})),
"max" => Some(Function::new(|argument| {
let arguments = argument.as_tuple()?;
let mut max_int = IntType::min_value();
let mut max_float: FloatType = -1.0 / 0.0;
debug_assert!(max_float.is_infinite());
let mut max_float = Option::<FloatType>::None;

for argument in arguments {
if let Value::Float(float) = argument {
max_float = max_float.max(float);
if let Some(max) = max_float {
max_float = Some(max.max(float));
} else {
max_float = Some(float);
}
} else if let Value::Int(int) = argument {
max_int = max_int.max(int);
} else {
return Err(EvalexprError::expected_number(argument));
}
}

if (max_int as FloatType) > max_float {
Ok(Value::Int(max_int))
if let Some(max_float) = max_float {
if ({
#[cfg(feature = "decimal_support")]
{
FloatType::from_i64(max_int).unwrap()
}
#[cfg(not(feature = "decimal_support"))]
{
max_int as FloatType
}
}) > max_float
{
Ok(Value::Int(max_int))
} else {
Ok(Value::Float(max_float))
}
} else {
Ok(Value::Float(max_float))
Ok(Value::Int(max_int))
}
})),
"if" => Some(Function::new(|argument| {
Expand Down Expand Up @@ -270,7 +348,16 @@ pub fn builtin_function(identifier: &str) -> Option<Function> {
#[cfg(feature = "rand")]
"random" => Some(Function::new(|argument| {
argument.as_empty()?;
Ok(Value::Float(rand::random()))
Ok(Value::Float({
#[cfg(feature = "decimal_support")]
{
FloatType::from_f64(rand::random()).unwrap()
}
#[cfg(not(feature = "decimal_support"))]
{
rand::random()
}
}))
})),
// Bitwise operators
"bitand" => int_function!(bitand, 2),
Expand Down
6 changes: 6 additions & 0 deletions src/interface/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,9 @@ pub fn eval_number_with_context<C: Context>(
) -> EvalexprResult<FloatType> {
match eval_with_context(string, context) {
Ok(Value::Float(float)) => Ok(float),
#[cfg(feature = "decimal_support")]
Ok(Value::Int(int)) => Ok(int.into()),
#[cfg(not(feature = "decimal_support"))]
Ok(Value::Int(int)) => Ok(int as FloatType),
Ok(value) => Err(EvalexprError::expected_number(value)),
Err(error) => Err(error),
Expand Down Expand Up @@ -271,6 +274,9 @@ pub fn eval_number_with_context_mut<C: ContextWithMutableVariables>(
) -> EvalexprResult<FloatType> {
match eval_with_context_mut(string, context) {
Ok(Value::Float(float)) => Ok(float),
#[cfg(feature = "decimal_support")]
Ok(Value::Int(int)) => Ok(int.into()),
#[cfg(not(feature = "decimal_support"))]
Ok(Value::Int(int)) => Ok(int as FloatType),
Ok(value) => Err(EvalexprError::expected_number(value)),
Err(error) => Err(error),
Expand Down
Loading