json_eval_rs/
path_utils.rs

1//! Path utilities for JSON pointer operations
2//! 
3//! This module provides JSON pointer normalization and access functions
4//! for efficient native serde_json operations.
5
6use serde_json::Value;
7
8/// Normalize path to JSON pointer format for efficient native access
9/// 
10/// Handles various input formats:
11/// - JSON Schema refs: #/$params/constants/DEATH_SA -> /$params/constants/DEATH_SA
12/// - Dotted paths: user.name -> /user/name
13/// - Already normalized paths (no-op)
14/// - Simple field names: field -> /field
15#[inline]
16pub fn normalize_to_json_pointer(path: &str) -> String {
17    if path.is_empty() {
18        return "".to_string();
19    }
20    
21    let mut normalized = path.to_string();
22    
23    // Handle JSON Schema reference format
24    if normalized.starts_with("#/") {
25        normalized = normalized[1..].to_string(); // Keep leading /
26    } else if !normalized.starts_with('/') {
27        // Handle dotted notation: user.name -> /user/name
28        if normalized.contains('.') {
29            normalized = format!("/{}", normalized.replace('.', "/"));
30        } else {
31            // Simple field name: field -> /field
32            normalized = format!("/{}", normalized);
33        }
34    }
35    
36    // Clean up double slashes
37    while normalized.contains("//") {
38        normalized = normalized.replace("//", "/");
39    }
40    
41    // Return valid JSON pointer
42    if normalized == "/" {
43        "".to_string() // Root reference
44    } else {
45        normalized
46    }
47}
48
49/// Convert dotted path to JSON Schema pointer format
50/// 
51/// This is used for schema paths where properties are nested under `/properties/`
52/// 
53/// Examples:
54/// - "illustration.insured.name" -> "#/illustration/properties/insured/properties/name"
55/// - "header.form_number" -> "#/header/properties/form_number"
56/// - "#/already/formatted" -> "#/already/formatted" (no change)
57#[inline]
58pub fn dot_notation_to_schema_pointer(path: &str) -> String {
59    // If already a JSON pointer (starts with # or /), return as-is
60    if path.starts_with('#') || path.starts_with('/') {
61        return path.to_string();
62    }
63    
64    // Split by dots and join with /properties/
65    let parts: Vec<&str> = path.split('.').collect();
66    if parts.is_empty() {
67        return "#/".to_string();
68    }
69    
70    // Build schema path: #/part1/properties/part2/properties/part3
71    // First part is root-level field, rest are under /properties/
72    let mut result = String::from("#/");
73    for (i, part) in parts.iter().enumerate() {
74        if part.eq(&"properties") {
75            continue;
76        }
77
78        if i > 0 {
79            result.push_str("/properties/");
80        }
81        result.push_str(part);
82    }
83    
84    result
85}
86
87/// Convert JSON pointer or schema pointer to dotted notation
88/// 
89/// This converts various pointer formats back to dotted notation:
90/// 
91/// Examples:
92/// - "#/illustration/properties/insured/properties/ins_corrname" -> "illustration.properties.insured.properties.ins_corrname"
93/// - "/user/name" -> "user.name"
94/// - "person.name" -> "person.name" (already dotted, no change)
95#[inline]
96pub fn pointer_to_dot_notation(path: &str) -> String {
97    if path.is_empty() {
98        return String::new();
99    }
100    
101    // If already dotted notation (no # or / prefix), return as-is
102    if !path.starts_with('#') && !path.starts_with('/') {
103        return path.to_string();
104    }
105    
106    // Remove leading # or /
107    let clean_path = if path.starts_with("#/") {
108        &path[2..]
109    } else if path.starts_with('/') {
110        &path[1..]
111    } else if path.starts_with('#') {
112        &path[1..]
113    } else {
114        path
115    };
116    
117    // Convert slashes to dots
118    clean_path.replace('/', ".")
119}
120
121/// Fast JSON pointer-based value access using serde's native implementation
122/// 
123/// This is significantly faster than manual path traversal for deeply nested objects
124#[inline]
125pub fn get_value_by_pointer<'a>(data: &'a Value, pointer: &str) -> Option<&'a Value> {
126    if pointer.is_empty() {
127        Some(data)
128    } else {
129        data.pointer(pointer)
130    }
131}
132
133#[inline]
134pub fn get_value_by_pointer_without_properties<'a>(data: &'a Value, pointer: &str) -> Option<&'a Value> {
135    if pointer.is_empty() {
136        Some(data)
137    } else {
138        data.pointer(&pointer.replace("properties/", ""))
139    }
140}
141
142/// Batch pointer resolution for multiple paths
143pub fn get_values_by_pointers<'a>(data: &'a Value, pointers: &[String]) -> Vec<Option<&'a Value>> {
144    pointers.iter()
145        .map(|pointer| get_value_by_pointer(data, pointer))
146        .collect()
147}
148
149/// Fast array indexing helper for JSON arrays
150/// 
151/// Returns None if not an array or index out of bounds
152#[inline]
153pub fn get_array_element<'a>(data: &'a Value, index: usize) -> Option<&'a Value> {
154    data.as_array()?.get(index)
155}
156
157/// Fast array indexing with JSON pointer path
158/// 
159/// Example: get_array_element_by_pointer(data, "/$params/tables", 0)
160#[inline]
161pub fn get_array_element_by_pointer<'a>(data: &'a Value, pointer: &str, index: usize) -> Option<&'a Value> {
162    get_value_by_pointer(data, pointer)?
163        .as_array()?
164        .get(index)
165}
166
167/// Extract table metadata for fast array operations during schema parsing
168#[derive(Debug, Clone)]
169pub struct ArrayMetadata {
170    /// Pointer to the array location
171    pub pointer: String,
172    /// Array length (cached for fast bounds checking)
173    pub length: usize,
174    /// Column names for object arrays (cached for fast field access)
175    pub column_names: Vec<String>,
176    /// Whether this is a uniform object array (all elements have same structure)
177    pub is_uniform: bool,
178}
179
180impl ArrayMetadata {
181    /// Build metadata for an array at the given pointer
182    pub fn build(data: &Value, pointer: &str) -> Option<Self> {
183        let array = get_value_by_pointer(data, pointer)?.as_array()?;
184        
185        let length = array.len();
186        if length == 0 {
187            return Some(ArrayMetadata {
188                pointer: pointer.to_string(),
189                length: 0,
190                column_names: Vec::new(),
191                is_uniform: true,
192            });
193        }
194        
195        // Analyze first element to determine structure
196        let first_element = &array[0];
197        let column_names = if let Value::Object(obj) = first_element {
198            obj.keys().cloned().collect()
199        } else {
200            Vec::new()
201        };
202        
203        // Check if all elements have the same structure (uniform array)
204        let is_uniform = if !column_names.is_empty() {
205            array.iter().all(|elem| {
206                if let Value::Object(obj) = elem {
207                    obj.keys().len() == column_names.len() &&
208                    column_names.iter().all(|col| obj.contains_key(col))
209                } else {
210                    false
211                }
212            })
213        } else {
214            // Non-object arrays are considered uniform if all elements have same type
215            let first_type = std::mem::discriminant(first_element);
216            array.iter().all(|elem| std::mem::discriminant(elem) == first_type)
217        };
218        
219        Some(ArrayMetadata {
220            pointer: pointer.to_string(),
221            length,
222            column_names,
223            is_uniform,
224        })
225    }
226    
227    /// Fast column access for uniform object arrays
228    #[inline]
229    pub fn get_column_value<'a>(&self, data: &'a Value, row_index: usize, column: &str) -> Option<&'a Value> {
230        if !self.is_uniform || row_index >= self.length {
231            return None;
232        }
233        
234        get_array_element_by_pointer(data, &self.pointer, row_index)?
235            .as_object()?
236            .get(column)
237    }
238    
239    /// Fast bounds checking
240    #[inline]
241    pub fn is_valid_index(&self, index: usize) -> bool {
242        index < self.length
243    }
244}
245
246