datalogic-rs 4.0.21

A fast, type-safe Rust implementation of JSONLogic for evaluating logical rules as JSON. Perfect for business rules engines and dynamic filtering in Rust applications.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
//! Comparison operators for value comparisons.
//!
//! This module provides equality and ordering comparison operators with support for
//! type coercion, datetime/duration handling, and chained comparisons.
//!
//! # Operators
//!
//! | Operator | Description | Example |
//! |----------|-------------|---------|
//! | `==` | Loose equality (with coercion) | `{"==": [1, "1"]}` → `true` |
//! | `===` | Strict equality (no coercion) | `{"===": [1, "1"]}` → `false` |
//! | `!=` | Loose inequality | `{"!=": [1, 2]}` → `true` |
//! | `!==` | Strict inequality | `{"!==": [1, "1"]}` → `true` |
//! | `>` | Greater than | `{">": [5, 3]}` → `true` |
//! | `>=` | Greater than or equal | `{">=": [5, 5]}` → `true` |
//! | `<` | Less than | `{"<": [3, 5]}` → `true` |
//! | `<=` | Less than or equal | `{"<=": [5, 5]}` → `true` |
//!
//! # Comparison Precedence
//!
//! When comparing values, the following precedence is used:
//!
//! 1. **DateTime**: If both values are parseable as ISO 8601 datetimes, compare chronologically
//! 2. **Duration**: If both values are parseable as durations, compare by total duration
//! 3. **String**: If both are strings (and not datetime/duration), compare lexicographically
//! 4. **Number**: Coerce to numbers and compare numerically
//!
//! # Chained Comparisons
//!
//! All comparison operators support chained comparisons with 3+ arguments:
//!
//! ```json
//! {"<": [1, 2, 3]}  // Equivalent to: 1 < 2 && 2 < 3, returns true
//! {"<": [1, 5, 3]}  // Equivalent to: 1 < 5 && 5 < 3, returns false
//! ```
//!
//! Chained comparisons use short-circuit evaluation - they stop at the first `false` result.
//!
//! # Error Handling
//!
//! Comparison throws a NaN error when:
//! - Comparing arrays or objects (except datetime/duration objects)
//! - Comparing a number with a non-numeric string

use serde_json::Value;

use super::helpers::{extract_datetime_value, extract_duration_value};
use crate::constants::INVALID_ARGS;
use crate::value_helpers::{coerce_to_number, loose_equals, strict_equals};
use crate::{CompiledNode, ContextStack, DataLogic, Result};

/// Equals operator function (== for loose equality)
#[inline]
pub fn evaluate_equals(
    args: &[CompiledNode],
    context: &mut ContextStack,
    engine: &DataLogic,
) -> Result<Value> {
    if args.len() < 2 {
        return Err(crate::Error::InvalidArguments(INVALID_ARGS.into()));
    }

    // For chained equality (3+ arguments), check if all are equal
    let first = engine.evaluate_node_cow(&args[0], context)?;

    for item in args.iter().skip(1) {
        let current = engine.evaluate_node_cow(item, context)?;

        // Compare first == current (loose equality)
        let result = compare_equals(&first, &current, false, engine)?;

        if !result {
            // Short-circuit on first inequality
            return Ok(Value::Bool(false));
        }
    }

    Ok(Value::Bool(true))
}

/// Strict equals operator function (=== for strict equality)
#[inline]
pub fn evaluate_strict_equals(
    args: &[CompiledNode],
    context: &mut ContextStack,
    engine: &DataLogic,
) -> Result<Value> {
    if args.len() < 2 {
        return Err(crate::Error::InvalidArguments(INVALID_ARGS.into()));
    }

    // For chained equality (3+ arguments), check if all are equal
    let first = engine.evaluate_node_cow(&args[0], context)?;

    for item in args.iter().skip(1) {
        let current = engine.evaluate_node_cow(item, context)?;

        // Compare first === current (strict equality)
        let result = compare_equals(&first, &current, true, engine)?;

        if !result {
            // Short-circuit on first inequality
            return Ok(Value::Bool(false));
        }
    }

    Ok(Value::Bool(true))
}

/// Returns true if a string could plausibly be a datetime or duration.
/// Filters out pure numeric strings and short strings that can't be either format.
#[inline]
fn could_be_datetime_or_duration(s: &str) -> bool {
    let b = s.as_bytes();
    if b.len() < 2 || !b[0].is_ascii_digit() {
        return false;
    }
    // Datetime: "YYYY-MM-DD..." requires '-' at position 4
    if b.len() >= 10 && b[4] == b'-' {
        return true;
    }
    // Duration: must contain a time-unit letter suffix (d/h/m/s)
    b.iter().any(|&c| matches!(c, b'd' | b'h' | b'm' | b's'))
}

// Helper function for == and === comparison
#[inline]
fn compare_equals(left: &Value, right: &Value, strict: bool, engine: &DataLogic) -> Result<bool> {
    // Fast path: same-type simple comparisons — skip datetime/duration entirely
    match (left, right) {
        (Value::Number(_), Value::Number(_))
        | (Value::Bool(_), Value::Bool(_))
        | (Value::Null, Value::Null) => {
            return if strict {
                Ok(strict_equals(left, right))
            } else {
                loose_equals(left, right, engine)
            };
        }
        // Two strings that can't be datetimes — skip extraction
        (Value::String(l), Value::String(r))
            if !could_be_datetime_or_duration(l) || !could_be_datetime_or_duration(r) =>
        {
            return if strict {
                Ok(strict_equals(left, right))
            } else {
                loose_equals(left, right, engine)
            };
        }
        // Non-string primitives vs anything (except objects) — skip datetime extraction
        (Value::Number(_), _)
        | (_, Value::Number(_))
        | (Value::Bool(_), _)
        | (_, Value::Bool(_))
        | (Value::Null, _)
        | (_, Value::Null)
            if !matches!(left, Value::Object(_)) && !matches!(right, Value::Object(_)) =>
        {
            return if strict {
                Ok(strict_equals(left, right))
            } else {
                loose_equals(left, right, engine)
            };
        }
        _ => {}
    }

    // Handle datetime comparisons - both objects and strings
    let left_dt = extract_datetime_value(left);
    let right_dt = extract_datetime_value(right);

    if let (Some(dt1), Some(dt2)) = (left_dt, right_dt) {
        return Ok(dt1 == dt2);
    }

    // Handle duration comparisons - both objects and strings
    let left_dur = extract_duration_value(left);
    let right_dur = extract_duration_value(right);

    if let (Some(dur1), Some(dur2)) = (left_dur, right_dur) {
        return Ok(dur1 == dur2);
    }

    if strict {
        Ok(strict_equals(left, right))
    } else {
        loose_equals(left, right, engine)
    }
}

/// Not equals operator function (!= for loose inequality)
#[inline]
pub fn evaluate_not_equals(
    args: &[CompiledNode],
    context: &mut ContextStack,
    engine: &DataLogic,
) -> Result<Value> {
    if args.len() < 2 {
        return Err(crate::Error::InvalidArguments(INVALID_ARGS.into()));
    }

    // != returns true if arguments are not all equal
    // It's the logical negation of ==
    // But we need to handle lazy evaluation differently

    // Evaluate first two arguments
    let first = engine.evaluate_node_cow(&args[0], context)?;
    let second = engine.evaluate_node_cow(&args[1], context)?;

    // Compare them (loose equality)
    let equals = compare_equals(&first, &second, false, engine)?;

    if !equals {
        // Found inequality, return true immediately (lazy)
        return Ok(Value::Bool(true));
    }

    // If we only have 2 args and they're equal, return false
    if args.len() == 2 {
        return Ok(Value::Bool(false));
    }

    // For 3+ args, since first two are equal, the result depends on whether
    // all remaining args also equal the first. But JSONLogic != seems to only
    // check the first two operands when they're equal (based on test case)
    // This achieves lazy evaluation.
    Ok(Value::Bool(false))
}
/// Strict not equals operator function (!== for strict inequality)
#[inline]
pub fn evaluate_strict_not_equals(
    args: &[CompiledNode],
    context: &mut ContextStack,
    engine: &DataLogic,
) -> Result<Value> {
    if args.len() < 2 {
        return Err(crate::Error::InvalidArguments(INVALID_ARGS.into()));
    }

    // !== returns true if arguments are not all equal
    // It's the logical negation of ===
    // But we need to handle lazy evaluation differently

    // Evaluate first two arguments
    let first = engine.evaluate_node_cow(&args[0], context)?;
    let second = engine.evaluate_node_cow(&args[1], context)?;

    // Compare them (strict equality)
    let equals = compare_equals(&first, &second, true, engine)?;

    if !equals {
        // Found inequality, return true immediately (lazy)
        return Ok(Value::Bool(true));
    }

    // If we only have 2 args and they're equal, return false
    if args.len() == 2 {
        return Ok(Value::Bool(false));
    }

    // For 3+ args, since first two are equal, the result depends on whether
    // all remaining args also equal the first. But JSONLogic !== seems to only
    // check the first two operands when they're equal (based on test case)
    // This achieves lazy evaluation.
    Ok(Value::Bool(false))
}

/// Ordering comparison operation type
#[derive(Clone, Copy)]
enum OrdOp {
    Gt,
    Gte,
    Lt,
    Lte,
}

impl OrdOp {
    #[inline]
    fn apply_f64(self, l: f64, r: f64) -> bool {
        match self {
            OrdOp::Gt => l > r,
            OrdOp::Gte => l >= r,
            OrdOp::Lt => l < r,
            OrdOp::Lte => l <= r,
        }
    }

    #[inline]
    fn apply_str(self, l: &str, r: &str) -> bool {
        match self {
            OrdOp::Gt => l > r,
            OrdOp::Gte => l >= r,
            OrdOp::Lt => l < r,
            OrdOp::Lte => l <= r,
        }
    }

    #[inline]
    fn apply_datetime(
        self,
        l: &crate::datetime::DataDateTime,
        r: &crate::datetime::DataDateTime,
    ) -> bool {
        match self {
            OrdOp::Gt => l > r,
            OrdOp::Gte => l >= r,
            OrdOp::Lt => l < r,
            OrdOp::Lte => l <= r,
        }
    }

    #[inline]
    fn apply_duration(
        self,
        l: &crate::datetime::DataDuration,
        r: &crate::datetime::DataDuration,
    ) -> bool {
        match self {
            OrdOp::Gt => l > r,
            OrdOp::Gte => l >= r,
            OrdOp::Lt => l < r,
            OrdOp::Lte => l <= r,
        }
    }
}

/// Generic chained comparison for ordering operators (>, >=, <, <=).
/// Evaluates args pairwise with short-circuit on first false.
#[inline]
fn evaluate_chained_comparison(
    args: &[CompiledNode],
    context: &mut ContextStack,
    engine: &DataLogic,
    op: OrdOp,
) -> Result<Value> {
    if args.len() < 2 {
        return Err(crate::Error::InvalidArguments(INVALID_ARGS.into()));
    }

    let mut prev = engine.evaluate_node_cow(&args[0], context)?;

    for item in args.iter().skip(1) {
        let curr = engine.evaluate_node_cow(item, context)?;

        if !compare_ordered(&prev, &curr, op, engine)? {
            return Ok(Value::Bool(false));
        }

        prev = curr;
    }

    Ok(Value::Bool(true))
}

/// Generic ordered comparison helper handling numbers, strings, datetimes, and durations.
#[inline]
fn compare_ordered(left: &Value, right: &Value, op: OrdOp, engine: &DataLogic) -> Result<bool> {
    // Fast path: both numbers — most common case
    if let (Value::Number(l), Value::Number(r)) = (left, right) {
        return Ok(op.apply_f64(
            l.as_f64().unwrap_or(f64::NAN),
            r.as_f64().unwrap_or(f64::NAN),
        ));
    }

    // Fast path: both strings that can't be datetimes — skip datetime parsing
    if let (Value::String(l), Value::String(r)) = (left, right)
        && (!could_be_datetime_or_duration(l) || !could_be_datetime_or_duration(r))
    {
        return Ok(op.apply_str(l, r));
    }

    // Handle datetime comparisons first - both objects and strings
    let left_dt = extract_datetime_value(left);
    let right_dt = extract_datetime_value(right);

    if let (Some(dt1), Some(dt2)) = (&left_dt, &right_dt) {
        return Ok(op.apply_datetime(dt1, dt2));
    }

    // Handle duration comparisons - skip if already parsed as datetime (mutually exclusive)
    let left_dur = if left_dt.is_none() {
        extract_duration_value(left)
    } else {
        None
    };
    let right_dur = if right_dt.is_none() {
        extract_duration_value(right)
    } else {
        None
    };

    if let (Some(dur1), Some(dur2)) = (&left_dur, &right_dur) {
        return Ok(op.apply_duration(dur1, dur2));
    }

    // Arrays and objects cannot be compared (after checking for special objects)
    if matches!(left, Value::Array(_) | Value::Object(_))
        || matches!(right, Value::Array(_) | Value::Object(_))
    {
        return Err(crate::constants::nan_error());
    }

    // If both are strings, do string comparison
    if let (Value::String(l), Value::String(r)) = (left, right) {
        return Ok(op.apply_str(l, r));
    }

    // Check if both can be coerced to numbers
    let left_num = coerce_to_number(left, engine);
    let right_num = coerce_to_number(right, engine);

    if let (Some(l), Some(r)) = (left_num, right_num) {
        return Ok(op.apply_f64(l, r));
    }

    // If one is a number and the other is a string that can't be coerced, throw NaN
    if (matches!(left, Value::Number(_)) && matches!(right, Value::String(_)))
        || (matches!(right, Value::Number(_)) && matches!(left, Value::String(_)))
    {
        return Err(crate::constants::nan_error());
    }

    Ok(false)
}

/// Greater than operator function (>)
#[inline]
pub fn evaluate_greater_than(
    args: &[CompiledNode],
    context: &mut ContextStack,
    engine: &DataLogic,
) -> Result<Value> {
    evaluate_chained_comparison(args, context, engine, OrdOp::Gt)
}

/// Greater than or equal operator function (>=)
#[inline]
pub fn evaluate_greater_than_equal(
    args: &[CompiledNode],
    context: &mut ContextStack,
    engine: &DataLogic,
) -> Result<Value> {
    evaluate_chained_comparison(args, context, engine, OrdOp::Gte)
}

/// Less than operator function (<) - supports variadic arguments
#[inline]
pub fn evaluate_less_than(
    args: &[CompiledNode],
    context: &mut ContextStack,
    engine: &DataLogic,
) -> Result<Value> {
    evaluate_chained_comparison(args, context, engine, OrdOp::Lt)
}

/// Less than or equal operator function (<=) - supports variadic arguments
#[inline]
pub fn evaluate_less_than_equal(
    args: &[CompiledNode],
    context: &mut ContextStack,
    engine: &DataLogic,
) -> Result<Value> {
    evaluate_chained_comparison(args, context, engine, OrdOp::Lte)
}