Skip to main content

Crate datalogic_rs

Crate datalogic_rs 

Source
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::Bump arena and can borrow directly into caller input for zero-copy paths
  • Extensible: Add custom operators via the CustomOperator trait
  • 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:

  1. Compilation: JSON logic is parsed into Logic with OpCode dispatch
  2. Evaluation: Compiled logic is evaluated through arena dispatch — results are &'a DataValue<'a> allocated in a bumpalo::Bump for 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§

pub use bumpalo;
pub use datavalue;

Modules§

operator
Public scaffolding for user-supplied operators.

Structs§

CompileError
A rule Engine::compile_checked refused: every diagnostic the check found, errors and warnings, in rule order.
CustomOperatorInfo
What the engine may assume about a CustomOperator, returned by CustomOperator::info.
DataPath
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.
EngineBuilder
Builder for Engine. Construct via Engine::builder.
Error
Error returned by every crate::Engine operation.
EvaluationConfig
Knobs that change how an Engine treats 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.
ExecutionSteptrace
Captures state at each evaluation step.
ExpressionNodetrace
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.
Meteredbudget
An evaluation’s result paired with what it cost.
NumericCoercionConfig
Knobs for the implicit value→number coercions arithmetic and comparison perform on non-numeric arguments.
OperatorInfo
One built-in operator, as its operator-table row declares it.
ParsedData
A parsed JSON document that owns its backing storage.
PathStep
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.
RootValue
One value a Roots holds. Built from a reference to any accepted input type through From; 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.
TracedRuntrace
Result of a traced evaluation produced by TracedSession. Always includes the trace data; the value-or-error split lives on Self::result.
TracedSessiontrace
Trace-enabled view over a crate::Engine engine. Constructed via crate::Engine::trace. Every eval* returns a TracedRun<R> carrying the trace alongside the result, where R is the same shape the corresponding Session::eval* would return. The inputs differ from crate::Session, though: Self::eval and Self::eval_borrowed take compiled crate::Logic, while Self::eval_str and Self::eval_into take a rule source (crate::IntoLogic) and compile it with the optimizer disabled so every operator surfaces a step. The trace path allocates a fresh bumpalo::Bump per call (nothing is retained between runs) to keep the borrowed-result lifetime tied to the run.
UnknownErrorCode
The name is not one of ErrorCode::ALL’s as_str.

Enums§

CheckMode
Which mode a rule is checked in. See Engine::check.
DataValue
Arena-allocated JSON value tree. Mirrors serde_json::Value in shape and access surface, but every composite payload lives in a Bump.
DiagnosticCode
What a Diagnostic is about. Serialised as the variant name.
DivisionByZeroHandling
Defines how to handle division by zero
ErrorCode
What kind of error an Error is, without the details: one variant per ErrorKind variant, Copy, comparable and hashable. Read it with Error::code.
ErrorKind
Discriminant for crate::Error. Stable variant tags are exposed via crate::Error::tag for 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_compiled says whether this build has it. See EngineBuilder::with_families.
MissingVar
What a var / val read that finds nothing evaluates to. See EvaluationConfig::missing_var.
NanHandling
Defines how to handle NaN (Not a Number) scenarios in arithmetic operations
ScopedArg
An argument position that runs under a pushed context frame, where val paths resolve against the current element (or the caught error) rather than the enclosing data.
Severity
How serious a Diagnostic is.
TruthyEvaluator
Defines how to evaluate truthiness of values

Traits§

ArenaExt
Allocate borrowed DataValues in a Bump without typing arena.alloc(DataValue::...) at every return.
CustomOperator
Custom operator hook for the Engine.
EvalInput
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.
FromDataValue
Convert a borrowed arena DataValue into a concrete result type.
IntoLogic
Convert self into an OwnedDataValue suitable for compilation.
OwnedInput
Adapter trait for crate::Engine::eval / crate::Engine::eval_str / crate::Engine::eval_into and the module-level datalogic_rs::eval* helpers, where the engine creates and owns the arena per call.
TruthyInput
A value Engine::truthy_of can judge. Sealed: the supported shapes are &DataValue, &OwnedDataValue, &ParsedData and, with the serde_json feature, &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_intoserde_json
One-shot evaluation deserialised into a typed T: DeserializeOwned.
eval_str
One-shot evaluation returning a JSON String.

Type Aliases§

CustomErrorSource
Trait-object alias for the source carried by ErrorKind::Custom. Reference-counted so ErrorKind stays cheap to clone, and bounded so a single crate::Error value can be sent across threads.
Result
Result type for Engine operations
SharedSession
A Session that holds its engine by Arc: 'static + Send, with no lifetime to thread through the caller’s types. Build one with SharedSession::new or SharedSession::from(arc).