datalogic-rs
A lightweight, high-performance Rust implementation of JSONLogic, optimized for rule-based decision-making and dynamic expressions.
✨ Why datalogic-rs?
- 🏆 Fully JSONLogic-compliant (100% test coverage)
- 🚀 Fast & lightweight: Zero-copy JSON parsing, minimal allocations
- 🔒 Thread-safe: Designed for parallel execution
- ⚡ Optimized for production: Static dispatch and rule optimization
- 🔌 Extensible: Support for custom operators
Overview
datalogic-rs provides a robust implementation of JSONLogic rules with arena-based memory management for optimal performance. The library features comprehensive operator support, optimizations for static rule components, and high test coverage.
Features
- Arena-based memory management for optimal performance
- Comprehensive JSONLogic operator support
- Optimizations for static rule components
- Zero copy rule creation and evaluation
- High test coverage and compatibility with standard JSONLogic
- Intuitive API for creating, parsing, and evaluating rules
Installation
Add datalogic-rs to your Cargo.toml:
[]
= "3.0.12"
Core API Methods
datalogic-rs provides three primary API methods for evaluating rules, each suited for different use cases:
1. evaluate - For reusing parsed rules and data
Best for scenarios where the same rule will be evaluated against different data contexts, or vice versa.
use DataLogic;
let dl = new;
// Parse rule and data once
let rule = dl.parse_logic.unwrap;
let data = dl.parse_data.unwrap;
// Evaluate the rule against the data
let result = dl.evaluate.unwrap;
assert!;
2. evaluate_str - One-step parsing and evaluation
Ideal for one-time evaluations or when rules are dynamically generated.
use DataLogic;
let dl = new;
// Parse and evaluate in one step
let result = dl.evaluate_str.unwrap;
assert_eq!;
3. evaluate_json - Work directly with JSON values
Perfect when your application already has the rule and data as serde_json Values.
use DataLogic;
use json;
let dl = new;
// Use serde_json values directly
let logic = json!;
let data = json!;
let result = dl.evaluate_json.unwrap;
assert_eq!;
Real-World Examples
1. Complex Logical Rules (AND/OR)
use DataLogic;
let dl = new;
let result = dl.evaluate_str.unwrap;
assert!;
2. Array Operations
use DataLogic;
let dl = new;
let result = dl.evaluate_str.unwrap;
// Returns ["Alice", "Charlie"]
assert_eq!;
3. DateTime Operations
use DataLogic;
let dl = new;
let result = dl.evaluate_str.unwrap;
assert!;
Custom Operators
Create domain-specific operators to extend the system:
use ;
// Define a custom operator that calculates the power of numbers
;
let mut dl = new;
dl.register_operator;
let result = dl.evaluate_str.unwrap;
assert_eq!;
Custom operators can be combined with built-in operators for complex logic:
let complex_rule = r#"{
"*": [
2,
{"pow": [{"var": "base"}, 2]},
3
]
}"#;
// With data: {"base": 3}, evaluates to 2 * 3² * 3 = 2 * 9 * 3 = 54
Use Cases
datalogic-rs excels in scenarios requiring runtime rule evaluation:
Feature Flagging
Control feature access based on user attributes or context:
let rule = r#"{
"and": [
{"==": [{"var": "user.country"}, "US"]},
{"or": [
{"==": [{"var": "user.role"}, "beta_tester"]},
{">=": [{"var": "user.account_age_days"}, 30]}
]}
]
}"#;
// Feature is available only to US users who are either beta testers or have accounts older than 30 days
let feature_enabled = dl.evaluate_str.unwrap.as_bool.unwrap;
Dynamic Pricing
Apply complex discount rules:
let pricing_rule = r#"{
"if": [
{">=": [{"var": "cart.total"}, 100]},
{"-": [{"var": "cart.total"}, {"*": [{"var": "cart.total"}, 0.1]}]},
{"var": "cart.total"}
]
}"#;
// 10% discount for orders over $100
let final_price = dl.evaluate_str.unwrap.as_f64.unwrap;
Fraud Detection
Evaluate transaction risk:
let fraud_check = r#"{
"or": [
{"and": [
{"!=": [{"var": "transaction.billing_country"}, {"var": "user.country"}]},
{">=": [{"var": "transaction.amount"}, 1000]}
]},
{"and": [
{">=": [{"var": "transaction.attempts_last_hour"}, 5]},
{">": [{"var": "transaction.amount"}, 500]}
]}
]
}"#;
let is_suspicious = dl.evaluate_str.unwrap.as_bool.unwrap;
Authorization Rules
Implement complex access control:
let access_rule = r#"{
"or": [
{"==": [{"var": "user.role"}, "admin"]},
{"and": [
{"==": [{"var": "user.role"}, "editor"]},
{"in": [{"var": "resource.project_id"}, {"var": "user.projects"}]}
]}
]
}"#;
let has_access = dl.evaluate_str.unwrap.as_bool.unwrap;
Form Validation
Check field dependencies dynamically:
let validation_rule = r#"{
"if": [
{"==": [{"var": "shipping_method"}, "international"]},
{"and": [
{"!": {"missing": "postal_code"}},
{"!": {"missing": "country"}}
]},
true
]
}"#;
let is_valid = dl.evaluate_str.unwrap.as_bool.unwrap;
Supported Operations
| Category | Operators |
|---|---|
| Comparison | == (equal), === (strict equal), != (not equal), !== (strict not equal), > (greater than), >= (greater than or equal), < (less than), <= (less than or equal) |
| Logic | and, or, ! (not), !! (double negation) |
| Arithmetic | + (addition), - (subtraction), * (multiplication), / (division), % (modulo), min, max, abs (absolute value), ceil (round up), floor (round down) |
| Control Flow | if (conditional), ?: (ternary), ?? (nullish coalescing) |
| Arrays | map, filter, reduce, all, some, none, merge, in (contains), length, slice, sort |
| Strings | cat (concatenate), substr, starts_with, ends_with, upper, lower, trim |
| Data Access | var (variable access), val (value access), exists, missing, missing_some |
| DateTime | datetime, timestamp, now, parse_date, format_date, date_diff |
| Error Handling | throw, try |
| Custom | Support for user-defined operators |
Performance
Benchmark results show datalogic-rs is 30% faster than the next fastest JSONLogic implementations, thanks to:
- Arena-based memory management
- Static operator dispatch
- Zero-copy deserialization
- Optimized rule compilation
Benchmark Metrics (Apple M2 Pro)
| Implementation | Execution Time | Relative Performance |
|---|---|---|
| datalogic-rs | 380ms | 1.0x (baseline) |
| json-logic-engine (pre-compiled) | 417ms | 1.1x slower |
| json-logic-engine (interpreted) | 986.064ms | 2.6x slower |
| json-logic-js | 5,755ms | 15.1x slower |
These benchmarks represent execution time for the same standard suite of JSONLogic tests, demonstrating datalogic-rs's superior performance profile across common expression patterns.
Contributing
We welcome contributions! See the CONTRIBUTING.md for details.
License
Licensed under Apache License, Version 2.0
Next Steps
✅ Try out datalogic-rs today!
📖 Check out the API documentation for detailed usage instructions
📚 See the docs.rs documentation for comprehensive reference
⭐ Star the GitHub repository if you find it useful!