Expand description
§datalogic-rs
A high-performance, thread-safe Rust implementation of JSONLogic.
§Overview
datalogic-rs provides a powerful rule evaluation engine that compiles JSONLogic
expressions into optimized, reusable structures that can be evaluated across
multiple threads with zero overhead.
§Key Features
- Compilation-based optimization: Parse once, evaluate many times
- Thread-safe by design: Share compiled logic across threads with
Arc - 84 built-in operators: Complete JSONLogic compatibility plus extensions
- Arena-allocated evaluation: Results live in a
bumpalo::Bumparena and can borrow directly into caller input for zero-copy paths - Extensible: Add custom operators via the
CustomOperatortrait - Structured templates: Preserve object structure for dynamic outputs
§Quick Start (one-shot)
use datalogic_rs::Engine;
let engine = Engine::new();
let result = engine.eval_str(
r#"{"==": [{"var": "status"}, "active"]}"#,
r#"{"status": "active"}"#,
).unwrap();
assert_eq!(result, "true");§Reusing the arena across many evaluations
For high-throughput callers, open a Session handle. It owns a
bumpalo::Bump, resets it between calls, and returns owned results so
you don’t have to juggle arena lifetimes:
use datalogic_rs::Engine;
let engine = Engine::new();
let compiled = engine.compile(r#"{"+": [{"var": "x"}, 1]}"#).unwrap();
let mut session = engine.session();
for x in 0..3 {
let payload = format!(r#"{{"x": {}}}"#, x);
let result = session.eval_str(&compiled, &payload).unwrap();
assert_eq!(result, (x + 1).to_string());
// The session does not auto-reset; bound peak memory by
// resetting between iterations (constant-time, reuses chunks).
session.reset();
}§Power-user (compile once, evaluate many, zero-copy results)
When the result borrow can stay scoped to a caller-managed
bumpalo::Bump, skip the deep-clone and use Engine::evaluate
directly. evaluate accepts any input shape via EvalInput:
&str, &OwnedDataValue, &serde_json::Value, an owned DataValue<'a>,
or an existing &'a DataValue<'a>.
use bumpalo::Bump;
use datalogic_rs::Engine;
let engine = Engine::new();
let compiled = engine.compile(r#"{"==": [{"var": "status"}, "active"]}"#).unwrap();
let arena = Bump::new();
let result = engine.evaluate(&compiled, r#"{"status": "active"}"#, &arena).unwrap();
assert_eq!(result.as_bool(), Some(true));§Architecture
The library uses a two-phase approach:
- Compilation: JSON logic is parsed into
Logicwith OpCode dispatch - Evaluation: Compiled logic is evaluated through arena dispatch — results
are
&'a DataValue<'a>allocated in abumpalo::Bumpfor the duration of one evaluate call.
This design enables sharing compiled logic across threads, eliminates
repeated parsing overhead, and lets read-through operations like var
return zero-copy borrows into the caller’s input data.
Re-exports§
Modules§
- operator
- Public scaffolding for user-supplied operators.
Structs§
- Compile
Error - A rule
Engine::compile_checkedrefused: every diagnostic the check found, errors and warnings, in rule order. - Custom
Operator Info - What the engine may assume about a
CustomOperator, returned byCustomOperator::info. - Data
Path - A path into the data a rule is evaluated against, one segment per object key or array index, from the root.
- Diagnostic
- One problem in a rule, located by an RFC 6901 JSON Pointer into it.
- Engine
- JSONLogic compile/evaluate engine.
- Engine
Builder - Builder for
Engine. Construct viaEngine::builder. - Error
- Error returned by every
crate::Engineoperation. - Evaluation
Config - Knobs that change how an
Enginetreats edge cases during evaluation — non-numeric arguments to arithmetic, division by zero, loose equality across types, truthiness rules, numeric coercion, and a recursion-depth cap. - Execution
Step trace - Captures state at each evaluation step.
- Expression
Node trace - Represents a node in the expression tree for flow diagram rendering.
- Facts
- What a compiled rule reads, which operators it uses, and whether its
result is a function of its data. Returned by
crate::Logic::facts. - Logic
- Compiled logic that can be evaluated multiple times across different data.
- Metered
budget - An evaluation’s result paired with what it cost.
- Numeric
Coercion Config - Knobs for the implicit value→number coercions arithmetic and comparison perform on non-numeric arguments.
- Operator
Info - One built-in operator, as its operator-table row declares it.
- Parsed
Data - A parsed JSON document that owns its backing storage.
- Path
Step - One node along the path from the root of a compiled rule down to the
failing sub-expression. Returned root-to-leaf by
crate::Logic::resolve_node_ids/crate::Error::resolve_path. - Root
Value - One value a
Rootsholds. Built from a reference to any accepted input type throughFrom; there is nothing else to do with it. - Roots
- Several values evaluated as the fields of one top-level object, each under its own name, without building that object.
- Session
- Reusable evaluation handle. Construct via
Engine::session. - Traced
Run trace - Result of a traced evaluation produced by
TracedSession. Always includes the trace data; the value-or-error split lives onSelf::result. - Traced
Session trace - Trace-enabled view over a
crate::Engineengine. Constructed viacrate::Engine::trace. Everyeval*returns aTracedRun<R>carrying the trace alongside the result, whereRis the same shape the correspondingSession::eval*would return. The inputs differ fromcrate::Session, though:Self::evalandSelf::eval_borrowedtake compiledcrate::Logic, whileSelf::eval_strandSelf::eval_intotake a rule source (crate::IntoLogic) and compile it with the optimizer disabled so every operator surfaces a step. The trace path allocates a freshbumpalo::Bumpper call (nothing is retained between runs) to keep the borrowed-result lifetime tied to the run. - Unknown
Error Code - The name is not one of
ErrorCode::ALL’sas_str.
Enums§
- Check
Mode - Which mode a rule is checked in. See
Engine::check. - Data
Value - Arena-allocated JSON value tree. Mirrors
serde_json::Valuein shape and access surface, but every composite payload lives in aBump. - Diagnostic
Code - What a
Diagnosticis about. Serialised as the variant name. - Division
ByZero Handling - Defines how to handle division by zero
- Error
Code - What kind of error an
Erroris, without the details: one variant perErrorKindvariant,Copy, comparable and hashable. Read it withError::code. - Error
Kind - Discriminant for
crate::Error. Stable variant tags are exposed viacrate::Error::tagfor matching across releases. - Family
- A family of built-in operators: the JSONLogic core, or one of the
extension families a Cargo feature compiles in. Every family is
named in every build;
Family::is_compiledsays whether this build has it. SeeEngineBuilder::with_families. - Missing
Var - What a
var/valread that finds nothing evaluates to. SeeEvaluationConfig::missing_var. - NanHandling
- Defines how to handle NaN (Not a Number) scenarios in arithmetic operations
- Scoped
Arg - An argument position that runs under a pushed context frame, where
valpaths resolve against the current element (or the caught error) rather than the enclosing data. - Severity
- How serious a
Diagnosticis. - Truthy
Evaluator - Defines how to evaluate truthiness of values
Traits§
- Arena
Ext - Allocate borrowed
DataValues in aBumpwithout typingarena.alloc(DataValue::...)at every return. - Custom
Operator - Custom operator hook for the
Engine. - Eval
Input - Adapter trait that converts a value into a
&'a DataValue<'a>borrowed from the caller-supplied arena. Sealed — the supported input shapes are listed in this file; external crates cannot add new ones. - From
Data Value - Convert a borrowed arena
DataValueinto a concrete result type. - Into
Logic - Convert
selfinto anOwnedDataValuesuitable for compilation. - Owned
Input - Adapter trait for
crate::Engine::eval/crate::Engine::eval_str/crate::Engine::eval_intoand the module-leveldatalogic_rs::eval*helpers, where the engine creates and owns the arena per call. - Truthy
Input - A value
Engine::truthy_ofcan judge. Sealed: the supported shapes are&DataValue,&OwnedDataValue,&ParsedDataand, with theserde_jsonfeature,&serde_json::Value.
Functions§
- compile
- Compile a rule using the default engine. Equivalent to
Engine::default().compile(rule). - eval
- One-shot evaluation returning
datavalue::OwnedDataValue. - eval_
into serde_json - One-shot evaluation deserialised into a typed
T: DeserializeOwned. - eval_
str - One-shot evaluation returning a JSON
String.
Type Aliases§
- Custom
Error Source - Trait-object alias for the source carried by
ErrorKind::Custom. Reference-counted soErrorKindstays cheap to clone, and bounded so a singlecrate::Errorvalue can be sent across threads. - Result
- Result type for Engine operations
- Shared
Session - A
Sessionthat holds its engine byArc:'static + Send, with no lifetime to thread through the caller’s types. Build one withSharedSession::neworSharedSession::from(arc).