use serde_json::Value;
use std::sync::Arc;
#[derive(Clone)]
pub struct EvaluationConfig {
pub arithmetic_nan_handling: NanHandling,
pub division_by_zero: DivisionByZeroHandling,
pub loose_equality_errors: bool,
pub truthy_evaluator: TruthyEvaluator,
pub numeric_coercion: NumericCoercionConfig,
}
#[derive(Clone, Debug, PartialEq)]
pub enum NanHandling {
ThrowError,
IgnoreValue,
CoerceToZero,
ReturnNull,
}
#[derive(Clone, Debug, PartialEq)]
pub enum DivisionByZeroHandling {
ReturnBounds,
ThrowError,
ReturnNull,
ReturnInfinity,
}
#[derive(Clone)]
pub enum TruthyEvaluator {
JavaScript,
Python,
StrictBoolean,
Custom(Arc<dyn Fn(&Value) -> bool + Send + Sync>),
}
#[derive(Clone, Debug)]
pub struct NumericCoercionConfig {
pub empty_string_to_zero: bool,
pub null_to_zero: bool,
pub bool_to_number: bool,
pub strict_numeric: bool,
pub undefined_to_zero: bool,
}
impl Default for EvaluationConfig {
fn default() -> Self {
Self {
arithmetic_nan_handling: NanHandling::ThrowError,
division_by_zero: DivisionByZeroHandling::ReturnBounds,
loose_equality_errors: true,
truthy_evaluator: TruthyEvaluator::JavaScript,
numeric_coercion: NumericCoercionConfig::default(),
}
}
}
impl Default for NumericCoercionConfig {
fn default() -> Self {
Self {
empty_string_to_zero: true,
null_to_zero: true,
bool_to_number: true,
strict_numeric: false,
undefined_to_zero: false,
}
}
}
impl EvaluationConfig {
pub fn new() -> Self {
Self::default()
}
pub fn safe_arithmetic() -> Self {
Self {
arithmetic_nan_handling: NanHandling::IgnoreValue,
division_by_zero: DivisionByZeroHandling::ReturnNull,
loose_equality_errors: false,
..Default::default()
}
}
pub fn strict() -> Self {
Self {
arithmetic_nan_handling: NanHandling::ThrowError,
division_by_zero: DivisionByZeroHandling::ThrowError,
loose_equality_errors: true,
numeric_coercion: NumericCoercionConfig {
empty_string_to_zero: false,
null_to_zero: false,
bool_to_number: false,
strict_numeric: true,
undefined_to_zero: false,
},
..Default::default()
}
}
pub fn with_nan_handling(mut self, handling: NanHandling) -> Self {
self.arithmetic_nan_handling = handling;
self
}
pub fn with_division_by_zero(mut self, handling: DivisionByZeroHandling) -> Self {
self.division_by_zero = handling;
self
}
pub fn with_loose_equality_errors(mut self, throw_errors: bool) -> Self {
self.loose_equality_errors = throw_errors;
self
}
pub fn with_truthy_evaluator(mut self, evaluator: TruthyEvaluator) -> Self {
self.truthy_evaluator = evaluator;
self
}
pub fn with_numeric_coercion(mut self, config: NumericCoercionConfig) -> Self {
self.numeric_coercion = config;
self
}
}