json-eval-rs 0.0.87

High-performance JSON Logic evaluator with schema validation and dependency tracking. Built on blazing-fast Rust engine.
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
use serde_json::Value;
use std::borrow::Cow;

/// Normalize path to JSON pointer format for efficient native access
///
/// Handles various input formats:
/// - JSON Schema refs: #/$params/constants/DEATH_SA -> /$params/constants/DEATH_SA
/// - Dotted paths: user.name -> /user/name
/// - Already normalized paths (no-op)
/// - Simple field names: field -> /field
///
/// Returns `Cow::Borrowed` for already-normalized paths to avoid heap allocation.
#[inline]
pub fn normalize_to_json_pointer(path: &str) -> Cow<'_, str> {
    if path.is_empty() {
        return Cow::Borrowed("");
    }

    if path.starts_with("#/") {
        let stripped = &path[1..];
        if !stripped.contains("//") {
            return Cow::Borrowed(stripped);
        }
    }

    if path.starts_with('/') && !path.contains("//") {
        return if path == "/" {
            Cow::Borrowed("")
        } else {
            Cow::Borrowed(path)
        };
    }

    let mut normalized = String::with_capacity(path.len() + 1);
    let source = if path.starts_with("#/") {
        &path[1..]
    } else if !path.starts_with('/') {
        normalized.push('/');
        path
    } else {
        path
    };

    let mut prev_slash = normalized.ends_with('/');
    for ch in source.chars() {
        let c = if ch == '.' && !path.starts_with('/') && !path.starts_with('#') {
            '/'
        } else {
            ch
        };
        if c == '/' {
            if !prev_slash {
                normalized.push('/');
            }
            prev_slash = true;
        } else {
            normalized.push(c);
            prev_slash = false;
        }
    }

    if normalized == "/" {
        Cow::Borrowed("")
    } else {
        Cow::Owned(normalized)
    }
}

/// Fast conversion from schema path (e.g. `#/foo/properties/bar`)
/// to data JSON pointer (e.g. `/foo/bar`).
/// Strips leading `#`, removes `properties` segments, and ensures a leading `/`.
#[inline]
pub fn schema_path_to_data_pointer(path: &str) -> Cow<'_, str> {
    if path.is_empty() {
        return Cow::Borrowed("");
    }

    let no_hash = if path.starts_with('#') {
        &path[1..]
    } else {
        path
    };

    let clean_path = if no_hash.starts_with('/') {
        &no_hash[1..]
    } else {
        no_hash
    };

    if !clean_path.contains("properties/") && clean_path != "properties" {
        if path.starts_with('/') && path.len() == clean_path.len() + 1 {
            return Cow::Borrowed(path);
        }
        let mut s = String::with_capacity(clean_path.len() + 1);
        s.push('/');
        s.push_str(clean_path);
        return Cow::Owned(s);
    }

    let parts = clean_path.split('/');
    let mut s = String::with_capacity(clean_path.len() + 1);
    for part in parts {
        if part.is_empty() || part == "properties" {
            continue;
        }
        s.push('/');
        s.push_str(part);
    }
    
    if s.is_empty() {
        Cow::Borrowed("")
    } else {
        Cow::Owned(s)
    }
}

/// Convert dotted path to JSON Schema pointer format
///
/// This is used for schema paths where properties are nested under `/properties/`
///
/// Examples:
/// - "illustration.insured.name" -> "#/illustration/properties/insured/properties/name"
/// - "header.form_number" -> "#/header/properties/form_number"
/// - "#/already/formatted" -> "#/already/formatted" (no change)
#[inline]
pub fn dot_notation_to_schema_pointer(path: &str) -> String {
    // If already a JSON pointer (starts with # or /), return as-is
    if path.starts_with('#') || path.starts_with('/') {
        return path.to_string();
    }

    // Check if it's explicitly a dotted schema pointer
    if path.starts_with("properties.") || path.contains(".properties.") {
        return format!("#/{}", path.replace('.', "/"));
    }

    // Split by dots and join with /properties/
    let parts: Vec<&str> = path.split('.').collect();
    if parts.is_empty() {
        return "#/".to_string();
    }

    // Build schema path: #/part1/properties/part2/properties/part3
    // First part is root-level field, rest are under /properties/
    // Don't add /properties/ if path starts with $ (direct JSON pointer)
    let mut result = String::from("#");
    for (i, part) in parts.iter().enumerate() {
        if part.eq(&"properties") {
            continue;
        }

        if i > 0 && !path.starts_with('$') {
            result.push_str("/properties");
        }
        result.push_str("/");
        result.push_str(part);
    }

    result
}

/// Convert JSON pointer or schema pointer to dotted notation
///
/// This converts various pointer formats back to dotted notation:
///
/// Examples:
/// - "#/illustration/properties/insured/properties/ins_corrname" -> "illustration.properties.insured.properties.ins_corrname"
/// - "/user/name" -> "user.name"
/// - "person.name" -> "person.name" (already dotted, no change)
#[inline]
pub fn pointer_to_dot_notation(path: &str) -> String {
    if path.is_empty() {
        return String::new();
    }

    // If already dotted notation (no # or / prefix), return as-is
    if !path.starts_with('#') && !path.starts_with('/') {
        return path.to_string();
    }

    // Remove leading # or /
    let clean_path = if path.starts_with("#/") {
        &path[2..]
    } else if path.starts_with('/') {
        &path[1..]
    } else if path.starts_with('#') {
        &path[1..]
    } else {
        path
    };

    // Convert slashes to dots
    clean_path.replace('/', ".")
}

/// Canonicalize a path for schema lookups.
///
/// This performs a single-pass conversion that:
/// 1. Normalizes the path to a JSON pointer (starts with /).
/// 2. Injects `/properties/` segments for data paths (e.g., `a.b.c` -> `/a/properties/b/properties/c`).
/// 3. Preserves system paths starting with `$` (e.g., `/$params` -> `/$params`).
/// 4. Handles existing JSON pointers/schema refs by re-canonicalizing them.
///
/// Returns `Cow::Borrowed` if the path is already canonical.
pub fn canonicalize_schema_path(path: &str) -> Cow<'_, str> {
    if path.is_empty() {
        return Cow::Borrowed("");
    }

    // Fast check for already normalized system paths
    if path.starts_with("/$") && !path.contains('.') && !path.contains("//") {
        return Cow::Borrowed(path);
    }

    // Identify system paths early
    let is_system = path.starts_with('$') || path.starts_with("/$") || path.starts_with("#/$");

    // Clean prefix and detect if we need to do work
    let clean_path = if path.starts_with("#/") {
        &path[2..]
    } else if path.starts_with('/') {
        &path[1..]
    } else if path.starts_with('#') {
        &path[1..]
    } else {
        path
    };

    // If it's a simple top-level field with no dots/slashes, and not system,
    // we can just prepend / and return borrowed if it was already /field
    if !is_system
        && !clean_path.contains('.')
        && !clean_path.contains('/')
        && !clean_path.is_empty()
    {
        if path.starts_with('/') && path.len() == clean_path.len() + 1 {
            return Cow::Borrowed(path);
        }
        let mut s = String::with_capacity(clean_path.len() + 1);
        s.push('/');
        s.push_str(clean_path);
        return Cow::Owned(s);
    }

    // If the path explicitly uses schema pointer semantics, just normalize delimiters
    if clean_path.starts_with("properties/") || clean_path.starts_with("properties.")
        || clean_path.contains("/properties/") || clean_path.contains(".properties.") {
        
        let mut s = String::with_capacity(clean_path.len() + 1);
        s.push('/');
        for c in clean_path.chars() {
            if c == '.' {
                s.push('/');
            } else {
                s.push(c);
            }
        }
        if s == path {
            return Cow::Borrowed(path);
        } else {
            return Cow::Owned(s);
        }
    }

    // Full decomposition and reconstruction
    let mut result = String::with_capacity(path.len() * 2);
    result.push('/');

    let parts = clean_path.split(|c| c == '/' || c == '.');
    let mut first = true;

    for part in parts {
        if part.is_empty() || part == "properties" {
            continue;
        }

        if !first && !is_system {
            result.push_str("properties/");
        }
        result.push_str(part);
        result.push('/');
        first = false;
    }

    if result.len() > 1 {
        result.pop(); // Remove trailing slash
    }

    // If result matches original exactly, return borrowed
    if result == path {
        Cow::Borrowed(path)
    } else {
        Cow::Owned(result)
    }
}

/// Fast JSON pointer-based value access using serde's native implementation
///
/// This is significantly faster than manual path traversal for deeply nested objects
#[inline]
pub fn get_value_by_pointer<'a>(data: &'a Value, pointer: &str) -> Option<&'a Value> {
    if pointer.is_empty() {
        Some(data)
    } else {
        data.pointer(pointer)
    }
}

#[inline]
pub fn get_value_by_pointer_without_properties<'a>(
    data: &'a Value,
    pointer: &str,
) -> Option<&'a Value> {
    if pointer.is_empty() {
        Some(data)
    } else {
        data.pointer(&pointer.replace("properties/", ""))
    }
}

/// Batch pointer resolution for multiple paths
pub fn get_values_by_pointers<'a>(data: &'a Value, pointers: &[String]) -> Vec<Option<&'a Value>> {
    pointers
        .iter()
        .map(|pointer| get_value_by_pointer(data, pointer))
        .collect()
}

/// Fast array indexing helper for JSON arrays
///
/// Returns None if not an array or index out of bounds
#[inline]
pub fn get_array_element<'a>(data: &'a Value, index: usize) -> Option<&'a Value> {
    data.as_array()?.get(index)
}

/// Fast array indexing with JSON pointer path
///
/// Example: get_array_element_by_pointer(data, "/$params/tables", 0)
#[inline]
pub fn get_array_element_by_pointer<'a>(
    data: &'a Value,
    pointer: &str,
    index: usize,
) -> Option<&'a Value> {
    get_value_by_pointer(data, pointer)?.as_array()?.get(index)
}

/// Extract table metadata for fast array operations during schema parsing
#[derive(Debug, Clone)]
pub struct ArrayMetadata {
    /// Pointer to the array location
    pub pointer: String,
    /// Array length (cached for fast bounds checking)
    pub length: usize,
    /// Column names for object arrays (cached for fast field access)
    pub column_names: Vec<String>,
    /// Whether this is a uniform object array (all elements have same structure)
    pub is_uniform: bool,
}

impl ArrayMetadata {
    /// Build metadata for an array at the given pointer
    pub fn build(data: &Value, pointer: &str) -> Option<Self> {
        let array = get_value_by_pointer(data, pointer)?.as_array()?;

        let length = array.len();
        if length == 0 {
            return Some(ArrayMetadata {
                pointer: pointer.to_string(),
                length: 0,
                column_names: Vec::new(),
                is_uniform: true,
            });
        }

        // Analyze first element to determine structure
        let first_element = &array[0];
        let column_names = if let Value::Object(obj) = first_element {
            obj.keys().cloned().collect()
        } else {
            Vec::new()
        };

        // Check if all elements have the same structure (uniform array)
        let is_uniform = if !column_names.is_empty() {
            array.iter().all(|elem| {
                if let Value::Object(obj) = elem {
                    obj.keys().len() == column_names.len()
                        && column_names.iter().all(|col| obj.contains_key(col))
                } else {
                    false
                }
            })
        } else {
            // Non-object arrays are considered uniform if all elements have same type
            let first_type = std::mem::discriminant(first_element);
            array
                .iter()
                .all(|elem| std::mem::discriminant(elem) == first_type)
        };

        Some(ArrayMetadata {
            pointer: pointer.to_string(),
            length,
            column_names,
            is_uniform,
        })
    }

    /// Fast column access for uniform object arrays
    #[inline]
    pub fn get_column_value<'a>(
        &self,
        data: &'a Value,
        row_index: usize,
        column: &str,
    ) -> Option<&'a Value> {
        if !self.is_uniform || row_index >= self.length {
            return None;
        }

        get_array_element_by_pointer(data, &self.pointer, row_index)?
            .as_object()?
            .get(column)
    }

    /// Fast bounds checking
    #[inline]
    pub fn is_valid_index(&self, index: usize) -> bool {
        index < self.length
    }
}