Skip to main content

Logic

Struct Logic 

Source
pub struct Logic { /* private fields */ }
Expand description

Compiled logic that can be evaluated multiple times across different data.

Logic represents a pre-processed JSONLogic expression that has been optimized for repeated evaluation. It’s thread-safe and can be shared across threads using Arc.

§Performance Benefits

  • Parse once, evaluate many: Avoid repeated JSON parsing
  • Static evaluation: Constant expressions are pre-computed
  • OpCode dispatch: Built-in operators use fast enum dispatch
  • Thread-safe sharing: Use Arc to share across threads

§Example

use std::sync::Arc;
use datalogic_rs::Engine;

let engine = Engine::new();
let compiled = Arc::new(engine.compile(r#"{">": [{"var": "score"}, 90]}"#).unwrap());

// Compiled logic can be cloned cheaply (atomic refcount) and sent across threads.
let compiled_clone = Arc::clone(&compiled);
std::thread::spawn(move || {
    let engine = Engine::new();
    let _result = engine
        .session()
        .eval_str(&compiled_clone, r#"{"score": 95}"#)
        .unwrap();
});

Logic is Clone (deep-clones the compiled tree). Cloning is the right choice when a caller needs an independently mutable copy or wants to store the rule by value; for sharing the same compiled rule across threads or evaluations, prefer Arc<Logic> — the Arc::clone is a single atomic refcount bump rather than a tree walk.

Implementations§

Source§

impl Logic

Source

pub fn is_static(&self) -> bool

Check if this compiled logic is static (can be evaluated without context)

Source

pub fn to_json(&self) -> String

Reconstruct a JSONLogic string from this compiled tree.

Reflects the compiled shape — constant-folded sub-expressions appear as literals, since the original operator is gone by then. Re-parsing the output through crate::Engine::compile yields a Logic that evaluates identically. Useful for caching keys, identity checks across compiled rules, debug logging, and tooling.

Var nodes serialise to {"var": "..."} for scope_level == 0 and to {"val": [[<level>], ...]} for scope_level > 0 — that’s the shape the compiler accepts on round-trip.

§Example
use datalogic_rs::Engine;

let engine = Engine::new();
let compiled = engine.compile(r#"{">": [{"var": "score"}, 90]}"#).unwrap();
let json = compiled.to_json();
assert!(json.contains(r#""var": "score""#));

// Round-trip: re-compiling the output produces an equivalent rule.
let recompiled = engine.compile(&json).unwrap();
assert_eq!(
    engine.eval_str(&json, r#"{"score": 95}"#).unwrap(),
    "true",
);
Source§

impl Logic

Source

pub fn resolve_node_ids(&self, ids: &[u32]) -> Vec<PathStep>

Translate a breadcrumb of compiled-node ids into structured PathSteps, root-to-leaf.

Input is the leaf-to-root breadcrumb stored on crate::Error::node_ids. Walks the compiled tree once to build an id → location index, then resolves each input id; ids absent from the tree are skipped (defensive against synthetic nodes from operator fast paths).

Trait Implementations§

Source§

impl Clone for Logic

Source§

fn clone(&self) -> Logic

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Logic

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for Logic

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl Freeze for Logic

§

impl RefUnwindSafe for Logic

§

impl Send for Logic

§

impl Sync for Logic

§

impl Unpin for Logic

§

impl UnsafeUnpin for Logic

§

impl UnwindSafe for Logic

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.