ParsedSchemaCache

Struct ParsedSchemaCache 

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

Thread-safe cache for storing and reusing ParsedSchema instances

Β§Example

use json_eval_rs::{ParsedSchemaCache, ParsedSchema};
use std::sync::Arc;
 
let cache = ParsedSchemaCache::new();
 
// Parse and cache a schema
let schema_json = r#"{"type": "object"}"#;
let schema = ParsedSchema::parse(schema_json).unwrap();
cache.insert("my-schema".to_string(), Arc::new(schema));
 
// Retrieve from cache
if let Some(cached) = cache.get("my-schema") {
    // Use cached schema for evaluation
}
 
// Remove specific entry
cache.remove("my-schema");
 
// Clear all entries
cache.clear();

ImplementationsΒ§

SourceΒ§

impl ParsedSchemaCache

Source

pub fn new() -> Self

Create a new empty cache

Examples found in repository?
examples/cache_demo.rs (line 42)
38fn demo_local_cache() -> Result<(), Box<dyn std::error::Error>> {
39    println!("πŸ“¦ Example 1: Local Cache Instance");
40    println!("Creating a dedicated cache for this application...\n");
41    
42    let cache = ParsedSchemaCache::new();
43    
44    // Simple schema
45    let schema_json = r#"{
46        "$params": {
47            "rate": { "type": "number" }
48        },
49        "result": {
50            "type": "number",
51            "title": "Calculated Result",
52            "$evaluation": {
53                "logic": { "*": [{"var": "$rate"}, 100] }
54            }
55        }
56    }"#;
57    
58    // Parse and cache with a custom key
59    println!("πŸ“ Parsing schema and caching with key 'calculation-v1'...");
60    let parsed = ParsedSchema::parse(schema_json)?;
61    cache.insert("calculation-v1".to_string(), Arc::new(parsed));
62    
63    println!("βœ… Schema cached successfully");
64    println!("   Cache size: {} entries", cache.len());
65    println!("   Keys: {:?}\n", cache.keys());
66    
67    // Retrieve and use cached schema
68    println!("πŸ” Retrieving cached schema...");
69    if let Some(cached_schema) = cache.get("calculation-v1") {
70        println!("βœ… Retrieved from cache");
71        
72        // Create JSONEval from cached ParsedSchema
73        let mut eval = JSONEval::with_parsed_schema(cached_schema, Some(r#"{"rate": 1.5}"#), None)?;
74        eval.evaluate("{}", None)?;
75        
76        let evaluated = eval.get_evaluated_schema(false);
77        let result = evaluated.pointer("/result")
78            .and_then(|v| v.as_f64())
79            .unwrap_or(0.0);
80        println!("   Evaluation result: {}\n", result);
81    }
82    
83    // Check cache stats
84    let stats = cache.stats();
85    println!("πŸ“Š Cache Statistics: {}", stats);
86    
87    // Remove entry
88    println!("\nπŸ—‘οΈ  Removing 'calculation-v1' from cache...");
89    cache.remove("calculation-v1");
90    println!("   Cache size after removal: {}", cache.len());
91    
92    Ok(())
93}
94
95fn demo_global_cache() -> Result<(), Box<dyn std::error::Error>> {
96    println!("🌍 Example 2: Global Cache Instance");
97    println!("Using the built-in PARSED_SCHEMA_CACHE...\n");
98    
99    let schema_json = r#"{
100        "$params": {
101            "x": { "type": "number" },
102            "y": { "type": "number" }
103        },
104        "sum": {
105            "type": "number",
106            "$evaluation": { "+": [{"var": "$x"}, {"var": "$y"}] }
107        }
108    }"#;
109    
110    // Use global cache
111    println!("πŸ“ Caching schema globally with key 'math-operations'...");
112    let parsed = ParsedSchema::parse(schema_json)?;
113    PARSED_SCHEMA_CACHE.insert("math-operations".to_string(), Arc::new(parsed));
114    
115    println!("βœ… Schema cached globally");
116    println!("   Global cache size: {}\n", PARSED_SCHEMA_CACHE.len());
117    
118    // Access from anywhere in the application
119    simulate_another_function()?;
120    
121    // Clean up
122    println!("\n🧹 Clearing global cache...");
123    PARSED_SCHEMA_CACHE.clear();
124    println!("   Global cache size: {}", PARSED_SCHEMA_CACHE.len());
125    
126    Ok(())
127}
128
129fn simulate_another_function() -> Result<(), Box<dyn std::error::Error>> {
130    println!("πŸ”„ In another function, accessing global cache...");
131    
132    if let Some(cached) = PARSED_SCHEMA_CACHE.get("math-operations") {
133        println!("βœ… Retrieved schema from global cache");
134        
135        let mut eval = JSONEval::with_parsed_schema(cached, Some(r#"{"x": 10, "y": 20}"#), None)?;
136        eval.evaluate("{}", None)?;
137        
138        let evaluated = eval.get_evaluated_schema(false);
139        let sum = evaluated.pointer("/sum")
140            .and_then(|v| v.as_f64())
141            .unwrap_or(0.0);
142        println!("   Result: {}", sum);
143    }
144    
145    Ok(())
146}
147
148fn demo_performance_comparison() -> Result<(), Box<dyn std::error::Error>> {
149    println!("⚑ Example 3: Performance Comparison");
150    println!("Comparing cached vs non-cached schema usage...\n");
151    
152    let schema_json = r#"{
153        "$params": {
154            "value": { "type": "number" }
155        },
156        "doubled": {
157            "type": "number",
158            "$evaluation": { "*": [{"var": "$value"}, 2] }
159        },
160        "tripled": {
161            "type": "number",
162            "$evaluation": { "*": [{"var": "$value"}, 3] }
163        }
164    }"#;
165    
166    let iterations = 100;
167    
168    // WITHOUT CACHE: Parse schema every time
169    println!("🐌 Without cache (parse + evaluate each time):");
170    let start = Instant::now();
171    for i in 0..iterations {
172        let context = format!(r#"{{"value": {}}}"#, i);
173        let mut eval = JSONEval::new(schema_json, Some(&context), None)?;
174        eval.evaluate("{}", None)?;
175    }
176    let without_cache = start.elapsed();
177    println!("   Time: {:?}", without_cache);
178    println!("   Avg per iteration: {:?}\n", without_cache / iterations);
179    
180    // WITH CACHE: Parse once, evaluate many times
181    println!("πŸš€ With cache (parse once, reuse for all evaluations):");
182    let cache = ParsedSchemaCache::new();
183    
184    // Parse once
185    let parse_start = Instant::now();
186    let parsed = ParsedSchema::parse(schema_json)?;
187    cache.insert("perf-test".to_string(), Arc::new(parsed));
188    let parse_time = parse_start.elapsed();
189    
190    // Evaluate many times
191    let eval_start = Instant::now();
192    for i in 0..iterations {
193        if let Some(cached) = cache.get("perf-test") {
194            let context = format!(r#"{{"value": {}}}"#, i);
195            let mut eval = JSONEval::with_parsed_schema(cached.clone(), Some(&context), None)?;
196            eval.evaluate("{}", None)?;
197        }
198    }
199    let eval_time = eval_start.elapsed();
200    let with_cache = parse_time + eval_time;
201    
202    println!("   Parse time: {:?}", parse_time);
203    println!("   Eval time: {:?}", eval_time);
204    println!("   Total time: {:?}", with_cache);
205    println!("   Avg per iteration: {:?}\n", eval_time / iterations);
206    
207    let speedup = without_cache.as_secs_f64() / with_cache.as_secs_f64();
208    println!("πŸ“ˆ Speedup: {:.2}x faster", speedup);
209    
210    Ok(())
211}
212
213fn demo_lazy_insertion() -> Result<(), Box<dyn std::error::Error>> {
214    println!("πŸ”„ Example 4: Lazy Insertion with get_or_insert_with");
215    println!("Parse only if not already cached...\n");
216    
217    let cache = ParsedSchemaCache::new();
218    
219    let schema_json = r#"{
220        "$params": {
221            "name": { "type": "string" }
222        },
223        "greeting": {
224            "type": "string",
225            "$evaluation": {
226                "cat": ["Hello, ", {"var": "$name"}, "!"]
227            }
228        }
229    }"#;
230    
231    // First access: will parse
232    println!("πŸ“ First access (will parse)...");
233    let start = Instant::now();
234    let schema1 = cache.get_or_insert_with("greeting-schema", || {
235        println!("   βš™οΈ  Parsing schema...");
236        Arc::new(ParsedSchema::parse(schema_json).unwrap())
237    });
238    println!("   Time: {:?}\n", start.elapsed());
239    
240    // Second access: will use cached
241    println!("πŸ” Second access (will use cache)...");
242    let start = Instant::now();
243    let schema2 = cache.get_or_insert_with("greeting-schema", || {
244        println!("   βš™οΈ  Parsing schema...");
245        Arc::new(ParsedSchema::parse(schema_json).unwrap())
246    });
247    println!("   Time: {:?}", start.elapsed());
248    
249    // Verify they're the same Arc (pointer equality)
250    println!("\nβœ… Both accesses returned the same cached instance");
251    println!("   Same pointer: {}", Arc::ptr_eq(&schema1, &schema2));
252    
253    Ok(())
254}
Source

pub fn insert( &self, key: String, schema: Arc<ParsedSchema>, ) -> Option<Arc<ParsedSchema>>

Insert or update a parsed schema with the given key

Returns the previous value if the key already existed

Examples found in repository?
examples/cache_demo.rs (line 61)
38fn demo_local_cache() -> Result<(), Box<dyn std::error::Error>> {
39    println!("πŸ“¦ Example 1: Local Cache Instance");
40    println!("Creating a dedicated cache for this application...\n");
41    
42    let cache = ParsedSchemaCache::new();
43    
44    // Simple schema
45    let schema_json = r#"{
46        "$params": {
47            "rate": { "type": "number" }
48        },
49        "result": {
50            "type": "number",
51            "title": "Calculated Result",
52            "$evaluation": {
53                "logic": { "*": [{"var": "$rate"}, 100] }
54            }
55        }
56    }"#;
57    
58    // Parse and cache with a custom key
59    println!("πŸ“ Parsing schema and caching with key 'calculation-v1'...");
60    let parsed = ParsedSchema::parse(schema_json)?;
61    cache.insert("calculation-v1".to_string(), Arc::new(parsed));
62    
63    println!("βœ… Schema cached successfully");
64    println!("   Cache size: {} entries", cache.len());
65    println!("   Keys: {:?}\n", cache.keys());
66    
67    // Retrieve and use cached schema
68    println!("πŸ” Retrieving cached schema...");
69    if let Some(cached_schema) = cache.get("calculation-v1") {
70        println!("βœ… Retrieved from cache");
71        
72        // Create JSONEval from cached ParsedSchema
73        let mut eval = JSONEval::with_parsed_schema(cached_schema, Some(r#"{"rate": 1.5}"#), None)?;
74        eval.evaluate("{}", None)?;
75        
76        let evaluated = eval.get_evaluated_schema(false);
77        let result = evaluated.pointer("/result")
78            .and_then(|v| v.as_f64())
79            .unwrap_or(0.0);
80        println!("   Evaluation result: {}\n", result);
81    }
82    
83    // Check cache stats
84    let stats = cache.stats();
85    println!("πŸ“Š Cache Statistics: {}", stats);
86    
87    // Remove entry
88    println!("\nπŸ—‘οΈ  Removing 'calculation-v1' from cache...");
89    cache.remove("calculation-v1");
90    println!("   Cache size after removal: {}", cache.len());
91    
92    Ok(())
93}
94
95fn demo_global_cache() -> Result<(), Box<dyn std::error::Error>> {
96    println!("🌍 Example 2: Global Cache Instance");
97    println!("Using the built-in PARSED_SCHEMA_CACHE...\n");
98    
99    let schema_json = r#"{
100        "$params": {
101            "x": { "type": "number" },
102            "y": { "type": "number" }
103        },
104        "sum": {
105            "type": "number",
106            "$evaluation": { "+": [{"var": "$x"}, {"var": "$y"}] }
107        }
108    }"#;
109    
110    // Use global cache
111    println!("πŸ“ Caching schema globally with key 'math-operations'...");
112    let parsed = ParsedSchema::parse(schema_json)?;
113    PARSED_SCHEMA_CACHE.insert("math-operations".to_string(), Arc::new(parsed));
114    
115    println!("βœ… Schema cached globally");
116    println!("   Global cache size: {}\n", PARSED_SCHEMA_CACHE.len());
117    
118    // Access from anywhere in the application
119    simulate_another_function()?;
120    
121    // Clean up
122    println!("\n🧹 Clearing global cache...");
123    PARSED_SCHEMA_CACHE.clear();
124    println!("   Global cache size: {}", PARSED_SCHEMA_CACHE.len());
125    
126    Ok(())
127}
128
129fn simulate_another_function() -> Result<(), Box<dyn std::error::Error>> {
130    println!("πŸ”„ In another function, accessing global cache...");
131    
132    if let Some(cached) = PARSED_SCHEMA_CACHE.get("math-operations") {
133        println!("βœ… Retrieved schema from global cache");
134        
135        let mut eval = JSONEval::with_parsed_schema(cached, Some(r#"{"x": 10, "y": 20}"#), None)?;
136        eval.evaluate("{}", None)?;
137        
138        let evaluated = eval.get_evaluated_schema(false);
139        let sum = evaluated.pointer("/sum")
140            .and_then(|v| v.as_f64())
141            .unwrap_or(0.0);
142        println!("   Result: {}", sum);
143    }
144    
145    Ok(())
146}
147
148fn demo_performance_comparison() -> Result<(), Box<dyn std::error::Error>> {
149    println!("⚑ Example 3: Performance Comparison");
150    println!("Comparing cached vs non-cached schema usage...\n");
151    
152    let schema_json = r#"{
153        "$params": {
154            "value": { "type": "number" }
155        },
156        "doubled": {
157            "type": "number",
158            "$evaluation": { "*": [{"var": "$value"}, 2] }
159        },
160        "tripled": {
161            "type": "number",
162            "$evaluation": { "*": [{"var": "$value"}, 3] }
163        }
164    }"#;
165    
166    let iterations = 100;
167    
168    // WITHOUT CACHE: Parse schema every time
169    println!("🐌 Without cache (parse + evaluate each time):");
170    let start = Instant::now();
171    for i in 0..iterations {
172        let context = format!(r#"{{"value": {}}}"#, i);
173        let mut eval = JSONEval::new(schema_json, Some(&context), None)?;
174        eval.evaluate("{}", None)?;
175    }
176    let without_cache = start.elapsed();
177    println!("   Time: {:?}", without_cache);
178    println!("   Avg per iteration: {:?}\n", without_cache / iterations);
179    
180    // WITH CACHE: Parse once, evaluate many times
181    println!("πŸš€ With cache (parse once, reuse for all evaluations):");
182    let cache = ParsedSchemaCache::new();
183    
184    // Parse once
185    let parse_start = Instant::now();
186    let parsed = ParsedSchema::parse(schema_json)?;
187    cache.insert("perf-test".to_string(), Arc::new(parsed));
188    let parse_time = parse_start.elapsed();
189    
190    // Evaluate many times
191    let eval_start = Instant::now();
192    for i in 0..iterations {
193        if let Some(cached) = cache.get("perf-test") {
194            let context = format!(r#"{{"value": {}}}"#, i);
195            let mut eval = JSONEval::with_parsed_schema(cached.clone(), Some(&context), None)?;
196            eval.evaluate("{}", None)?;
197        }
198    }
199    let eval_time = eval_start.elapsed();
200    let with_cache = parse_time + eval_time;
201    
202    println!("   Parse time: {:?}", parse_time);
203    println!("   Eval time: {:?}", eval_time);
204    println!("   Total time: {:?}", with_cache);
205    println!("   Avg per iteration: {:?}\n", eval_time / iterations);
206    
207    let speedup = without_cache.as_secs_f64() / with_cache.as_secs_f64();
208    println!("πŸ“ˆ Speedup: {:.2}x faster", speedup);
209    
210    Ok(())
211}
Source

pub fn get(&self, key: &str) -> Option<Arc<ParsedSchema>>

Get a cloned Arc reference to the cached schema

Returns None if the key doesn’t exist

Examples found in repository?
examples/cache_demo.rs (line 69)
38fn demo_local_cache() -> Result<(), Box<dyn std::error::Error>> {
39    println!("πŸ“¦ Example 1: Local Cache Instance");
40    println!("Creating a dedicated cache for this application...\n");
41    
42    let cache = ParsedSchemaCache::new();
43    
44    // Simple schema
45    let schema_json = r#"{
46        "$params": {
47            "rate": { "type": "number" }
48        },
49        "result": {
50            "type": "number",
51            "title": "Calculated Result",
52            "$evaluation": {
53                "logic": { "*": [{"var": "$rate"}, 100] }
54            }
55        }
56    }"#;
57    
58    // Parse and cache with a custom key
59    println!("πŸ“ Parsing schema and caching with key 'calculation-v1'...");
60    let parsed = ParsedSchema::parse(schema_json)?;
61    cache.insert("calculation-v1".to_string(), Arc::new(parsed));
62    
63    println!("βœ… Schema cached successfully");
64    println!("   Cache size: {} entries", cache.len());
65    println!("   Keys: {:?}\n", cache.keys());
66    
67    // Retrieve and use cached schema
68    println!("πŸ” Retrieving cached schema...");
69    if let Some(cached_schema) = cache.get("calculation-v1") {
70        println!("βœ… Retrieved from cache");
71        
72        // Create JSONEval from cached ParsedSchema
73        let mut eval = JSONEval::with_parsed_schema(cached_schema, Some(r#"{"rate": 1.5}"#), None)?;
74        eval.evaluate("{}", None)?;
75        
76        let evaluated = eval.get_evaluated_schema(false);
77        let result = evaluated.pointer("/result")
78            .and_then(|v| v.as_f64())
79            .unwrap_or(0.0);
80        println!("   Evaluation result: {}\n", result);
81    }
82    
83    // Check cache stats
84    let stats = cache.stats();
85    println!("πŸ“Š Cache Statistics: {}", stats);
86    
87    // Remove entry
88    println!("\nπŸ—‘οΈ  Removing 'calculation-v1' from cache...");
89    cache.remove("calculation-v1");
90    println!("   Cache size after removal: {}", cache.len());
91    
92    Ok(())
93}
94
95fn demo_global_cache() -> Result<(), Box<dyn std::error::Error>> {
96    println!("🌍 Example 2: Global Cache Instance");
97    println!("Using the built-in PARSED_SCHEMA_CACHE...\n");
98    
99    let schema_json = r#"{
100        "$params": {
101            "x": { "type": "number" },
102            "y": { "type": "number" }
103        },
104        "sum": {
105            "type": "number",
106            "$evaluation": { "+": [{"var": "$x"}, {"var": "$y"}] }
107        }
108    }"#;
109    
110    // Use global cache
111    println!("πŸ“ Caching schema globally with key 'math-operations'...");
112    let parsed = ParsedSchema::parse(schema_json)?;
113    PARSED_SCHEMA_CACHE.insert("math-operations".to_string(), Arc::new(parsed));
114    
115    println!("βœ… Schema cached globally");
116    println!("   Global cache size: {}\n", PARSED_SCHEMA_CACHE.len());
117    
118    // Access from anywhere in the application
119    simulate_another_function()?;
120    
121    // Clean up
122    println!("\n🧹 Clearing global cache...");
123    PARSED_SCHEMA_CACHE.clear();
124    println!("   Global cache size: {}", PARSED_SCHEMA_CACHE.len());
125    
126    Ok(())
127}
128
129fn simulate_another_function() -> Result<(), Box<dyn std::error::Error>> {
130    println!("πŸ”„ In another function, accessing global cache...");
131    
132    if let Some(cached) = PARSED_SCHEMA_CACHE.get("math-operations") {
133        println!("βœ… Retrieved schema from global cache");
134        
135        let mut eval = JSONEval::with_parsed_schema(cached, Some(r#"{"x": 10, "y": 20}"#), None)?;
136        eval.evaluate("{}", None)?;
137        
138        let evaluated = eval.get_evaluated_schema(false);
139        let sum = evaluated.pointer("/sum")
140            .and_then(|v| v.as_f64())
141            .unwrap_or(0.0);
142        println!("   Result: {}", sum);
143    }
144    
145    Ok(())
146}
147
148fn demo_performance_comparison() -> Result<(), Box<dyn std::error::Error>> {
149    println!("⚑ Example 3: Performance Comparison");
150    println!("Comparing cached vs non-cached schema usage...\n");
151    
152    let schema_json = r#"{
153        "$params": {
154            "value": { "type": "number" }
155        },
156        "doubled": {
157            "type": "number",
158            "$evaluation": { "*": [{"var": "$value"}, 2] }
159        },
160        "tripled": {
161            "type": "number",
162            "$evaluation": { "*": [{"var": "$value"}, 3] }
163        }
164    }"#;
165    
166    let iterations = 100;
167    
168    // WITHOUT CACHE: Parse schema every time
169    println!("🐌 Without cache (parse + evaluate each time):");
170    let start = Instant::now();
171    for i in 0..iterations {
172        let context = format!(r#"{{"value": {}}}"#, i);
173        let mut eval = JSONEval::new(schema_json, Some(&context), None)?;
174        eval.evaluate("{}", None)?;
175    }
176    let without_cache = start.elapsed();
177    println!("   Time: {:?}", without_cache);
178    println!("   Avg per iteration: {:?}\n", without_cache / iterations);
179    
180    // WITH CACHE: Parse once, evaluate many times
181    println!("πŸš€ With cache (parse once, reuse for all evaluations):");
182    let cache = ParsedSchemaCache::new();
183    
184    // Parse once
185    let parse_start = Instant::now();
186    let parsed = ParsedSchema::parse(schema_json)?;
187    cache.insert("perf-test".to_string(), Arc::new(parsed));
188    let parse_time = parse_start.elapsed();
189    
190    // Evaluate many times
191    let eval_start = Instant::now();
192    for i in 0..iterations {
193        if let Some(cached) = cache.get("perf-test") {
194            let context = format!(r#"{{"value": {}}}"#, i);
195            let mut eval = JSONEval::with_parsed_schema(cached.clone(), Some(&context), None)?;
196            eval.evaluate("{}", None)?;
197        }
198    }
199    let eval_time = eval_start.elapsed();
200    let with_cache = parse_time + eval_time;
201    
202    println!("   Parse time: {:?}", parse_time);
203    println!("   Eval time: {:?}", eval_time);
204    println!("   Total time: {:?}", with_cache);
205    println!("   Avg per iteration: {:?}\n", eval_time / iterations);
206    
207    let speedup = without_cache.as_secs_f64() / with_cache.as_secs_f64();
208    println!("πŸ“ˆ Speedup: {:.2}x faster", speedup);
209    
210    Ok(())
211}
Source

pub fn remove(&self, key: &str) -> Option<Arc<ParsedSchema>>

Remove and return the schema for the given key

Returns None if the key doesn’t exist

Examples found in repository?
examples/cache_demo.rs (line 89)
38fn demo_local_cache() -> Result<(), Box<dyn std::error::Error>> {
39    println!("πŸ“¦ Example 1: Local Cache Instance");
40    println!("Creating a dedicated cache for this application...\n");
41    
42    let cache = ParsedSchemaCache::new();
43    
44    // Simple schema
45    let schema_json = r#"{
46        "$params": {
47            "rate": { "type": "number" }
48        },
49        "result": {
50            "type": "number",
51            "title": "Calculated Result",
52            "$evaluation": {
53                "logic": { "*": [{"var": "$rate"}, 100] }
54            }
55        }
56    }"#;
57    
58    // Parse and cache with a custom key
59    println!("πŸ“ Parsing schema and caching with key 'calculation-v1'...");
60    let parsed = ParsedSchema::parse(schema_json)?;
61    cache.insert("calculation-v1".to_string(), Arc::new(parsed));
62    
63    println!("βœ… Schema cached successfully");
64    println!("   Cache size: {} entries", cache.len());
65    println!("   Keys: {:?}\n", cache.keys());
66    
67    // Retrieve and use cached schema
68    println!("πŸ” Retrieving cached schema...");
69    if let Some(cached_schema) = cache.get("calculation-v1") {
70        println!("βœ… Retrieved from cache");
71        
72        // Create JSONEval from cached ParsedSchema
73        let mut eval = JSONEval::with_parsed_schema(cached_schema, Some(r#"{"rate": 1.5}"#), None)?;
74        eval.evaluate("{}", None)?;
75        
76        let evaluated = eval.get_evaluated_schema(false);
77        let result = evaluated.pointer("/result")
78            .and_then(|v| v.as_f64())
79            .unwrap_or(0.0);
80        println!("   Evaluation result: {}\n", result);
81    }
82    
83    // Check cache stats
84    let stats = cache.stats();
85    println!("πŸ“Š Cache Statistics: {}", stats);
86    
87    // Remove entry
88    println!("\nπŸ—‘οΈ  Removing 'calculation-v1' from cache...");
89    cache.remove("calculation-v1");
90    println!("   Cache size after removal: {}", cache.len());
91    
92    Ok(())
93}
Source

pub fn clear(&self)

Clear all cached schemas

Examples found in repository?
examples/cache_demo.rs (line 123)
95fn demo_global_cache() -> Result<(), Box<dyn std::error::Error>> {
96    println!("🌍 Example 2: Global Cache Instance");
97    println!("Using the built-in PARSED_SCHEMA_CACHE...\n");
98    
99    let schema_json = r#"{
100        "$params": {
101            "x": { "type": "number" },
102            "y": { "type": "number" }
103        },
104        "sum": {
105            "type": "number",
106            "$evaluation": { "+": [{"var": "$x"}, {"var": "$y"}] }
107        }
108    }"#;
109    
110    // Use global cache
111    println!("πŸ“ Caching schema globally with key 'math-operations'...");
112    let parsed = ParsedSchema::parse(schema_json)?;
113    PARSED_SCHEMA_CACHE.insert("math-operations".to_string(), Arc::new(parsed));
114    
115    println!("βœ… Schema cached globally");
116    println!("   Global cache size: {}\n", PARSED_SCHEMA_CACHE.len());
117    
118    // Access from anywhere in the application
119    simulate_another_function()?;
120    
121    // Clean up
122    println!("\n🧹 Clearing global cache...");
123    PARSED_SCHEMA_CACHE.clear();
124    println!("   Global cache size: {}", PARSED_SCHEMA_CACHE.len());
125    
126    Ok(())
127}
Source

pub fn contains_key(&self, key: &str) -> bool

Check if a key exists in the cache

Source

pub fn len(&self) -> usize

Get the number of cached schemas

Examples found in repository?
examples/cache_demo.rs (line 64)
38fn demo_local_cache() -> Result<(), Box<dyn std::error::Error>> {
39    println!("πŸ“¦ Example 1: Local Cache Instance");
40    println!("Creating a dedicated cache for this application...\n");
41    
42    let cache = ParsedSchemaCache::new();
43    
44    // Simple schema
45    let schema_json = r#"{
46        "$params": {
47            "rate": { "type": "number" }
48        },
49        "result": {
50            "type": "number",
51            "title": "Calculated Result",
52            "$evaluation": {
53                "logic": { "*": [{"var": "$rate"}, 100] }
54            }
55        }
56    }"#;
57    
58    // Parse and cache with a custom key
59    println!("πŸ“ Parsing schema and caching with key 'calculation-v1'...");
60    let parsed = ParsedSchema::parse(schema_json)?;
61    cache.insert("calculation-v1".to_string(), Arc::new(parsed));
62    
63    println!("βœ… Schema cached successfully");
64    println!("   Cache size: {} entries", cache.len());
65    println!("   Keys: {:?}\n", cache.keys());
66    
67    // Retrieve and use cached schema
68    println!("πŸ” Retrieving cached schema...");
69    if let Some(cached_schema) = cache.get("calculation-v1") {
70        println!("βœ… Retrieved from cache");
71        
72        // Create JSONEval from cached ParsedSchema
73        let mut eval = JSONEval::with_parsed_schema(cached_schema, Some(r#"{"rate": 1.5}"#), None)?;
74        eval.evaluate("{}", None)?;
75        
76        let evaluated = eval.get_evaluated_schema(false);
77        let result = evaluated.pointer("/result")
78            .and_then(|v| v.as_f64())
79            .unwrap_or(0.0);
80        println!("   Evaluation result: {}\n", result);
81    }
82    
83    // Check cache stats
84    let stats = cache.stats();
85    println!("πŸ“Š Cache Statistics: {}", stats);
86    
87    // Remove entry
88    println!("\nπŸ—‘οΈ  Removing 'calculation-v1' from cache...");
89    cache.remove("calculation-v1");
90    println!("   Cache size after removal: {}", cache.len());
91    
92    Ok(())
93}
94
95fn demo_global_cache() -> Result<(), Box<dyn std::error::Error>> {
96    println!("🌍 Example 2: Global Cache Instance");
97    println!("Using the built-in PARSED_SCHEMA_CACHE...\n");
98    
99    let schema_json = r#"{
100        "$params": {
101            "x": { "type": "number" },
102            "y": { "type": "number" }
103        },
104        "sum": {
105            "type": "number",
106            "$evaluation": { "+": [{"var": "$x"}, {"var": "$y"}] }
107        }
108    }"#;
109    
110    // Use global cache
111    println!("πŸ“ Caching schema globally with key 'math-operations'...");
112    let parsed = ParsedSchema::parse(schema_json)?;
113    PARSED_SCHEMA_CACHE.insert("math-operations".to_string(), Arc::new(parsed));
114    
115    println!("βœ… Schema cached globally");
116    println!("   Global cache size: {}\n", PARSED_SCHEMA_CACHE.len());
117    
118    // Access from anywhere in the application
119    simulate_another_function()?;
120    
121    // Clean up
122    println!("\n🧹 Clearing global cache...");
123    PARSED_SCHEMA_CACHE.clear();
124    println!("   Global cache size: {}", PARSED_SCHEMA_CACHE.len());
125    
126    Ok(())
127}
Source

pub fn is_empty(&self) -> bool

Check if the cache is empty

Source

pub fn keys(&self) -> Vec<String>

Get all keys currently in the cache

Examples found in repository?
examples/cache_demo.rs (line 65)
38fn demo_local_cache() -> Result<(), Box<dyn std::error::Error>> {
39    println!("πŸ“¦ Example 1: Local Cache Instance");
40    println!("Creating a dedicated cache for this application...\n");
41    
42    let cache = ParsedSchemaCache::new();
43    
44    // Simple schema
45    let schema_json = r#"{
46        "$params": {
47            "rate": { "type": "number" }
48        },
49        "result": {
50            "type": "number",
51            "title": "Calculated Result",
52            "$evaluation": {
53                "logic": { "*": [{"var": "$rate"}, 100] }
54            }
55        }
56    }"#;
57    
58    // Parse and cache with a custom key
59    println!("πŸ“ Parsing schema and caching with key 'calculation-v1'...");
60    let parsed = ParsedSchema::parse(schema_json)?;
61    cache.insert("calculation-v1".to_string(), Arc::new(parsed));
62    
63    println!("βœ… Schema cached successfully");
64    println!("   Cache size: {} entries", cache.len());
65    println!("   Keys: {:?}\n", cache.keys());
66    
67    // Retrieve and use cached schema
68    println!("πŸ” Retrieving cached schema...");
69    if let Some(cached_schema) = cache.get("calculation-v1") {
70        println!("βœ… Retrieved from cache");
71        
72        // Create JSONEval from cached ParsedSchema
73        let mut eval = JSONEval::with_parsed_schema(cached_schema, Some(r#"{"rate": 1.5}"#), None)?;
74        eval.evaluate("{}", None)?;
75        
76        let evaluated = eval.get_evaluated_schema(false);
77        let result = evaluated.pointer("/result")
78            .and_then(|v| v.as_f64())
79            .unwrap_or(0.0);
80        println!("   Evaluation result: {}\n", result);
81    }
82    
83    // Check cache stats
84    let stats = cache.stats();
85    println!("πŸ“Š Cache Statistics: {}", stats);
86    
87    // Remove entry
88    println!("\nπŸ—‘οΈ  Removing 'calculation-v1' from cache...");
89    cache.remove("calculation-v1");
90    println!("   Cache size after removal: {}", cache.len());
91    
92    Ok(())
93}
Source

pub fn stats(&self) -> ParsedSchemaCacheStats

Get cache statistics

Examples found in repository?
examples/cache_demo.rs (line 84)
38fn demo_local_cache() -> Result<(), Box<dyn std::error::Error>> {
39    println!("πŸ“¦ Example 1: Local Cache Instance");
40    println!("Creating a dedicated cache for this application...\n");
41    
42    let cache = ParsedSchemaCache::new();
43    
44    // Simple schema
45    let schema_json = r#"{
46        "$params": {
47            "rate": { "type": "number" }
48        },
49        "result": {
50            "type": "number",
51            "title": "Calculated Result",
52            "$evaluation": {
53                "logic": { "*": [{"var": "$rate"}, 100] }
54            }
55        }
56    }"#;
57    
58    // Parse and cache with a custom key
59    println!("πŸ“ Parsing schema and caching with key 'calculation-v1'...");
60    let parsed = ParsedSchema::parse(schema_json)?;
61    cache.insert("calculation-v1".to_string(), Arc::new(parsed));
62    
63    println!("βœ… Schema cached successfully");
64    println!("   Cache size: {} entries", cache.len());
65    println!("   Keys: {:?}\n", cache.keys());
66    
67    // Retrieve and use cached schema
68    println!("πŸ” Retrieving cached schema...");
69    if let Some(cached_schema) = cache.get("calculation-v1") {
70        println!("βœ… Retrieved from cache");
71        
72        // Create JSONEval from cached ParsedSchema
73        let mut eval = JSONEval::with_parsed_schema(cached_schema, Some(r#"{"rate": 1.5}"#), None)?;
74        eval.evaluate("{}", None)?;
75        
76        let evaluated = eval.get_evaluated_schema(false);
77        let result = evaluated.pointer("/result")
78            .and_then(|v| v.as_f64())
79            .unwrap_or(0.0);
80        println!("   Evaluation result: {}\n", result);
81    }
82    
83    // Check cache stats
84    let stats = cache.stats();
85    println!("πŸ“Š Cache Statistics: {}", stats);
86    
87    // Remove entry
88    println!("\nπŸ—‘οΈ  Removing 'calculation-v1' from cache...");
89    cache.remove("calculation-v1");
90    println!("   Cache size after removal: {}", cache.len());
91    
92    Ok(())
93}
Source

pub fn get_or_insert_with<F>(&self, key: &str, factory: F) -> Arc<ParsedSchema>
where F: FnOnce() -> Arc<ParsedSchema>,

Get or insert a schema using a factory function

If the key exists, returns the cached value. Otherwise, calls the factory function to create a new value, inserts it, and returns it.

Β§Example
use json_eval_rs::{ParsedSchemaCache, ParsedSchema};
use std::sync::Arc;
 
let cache = ParsedSchemaCache::new();
let json = r#"{"type": "object"}"#;
let schema = cache.get_or_insert_with("my-schema", || {
    Arc::new(ParsedSchema::parse(json).unwrap())
});
Examples found in repository?
examples/cache_demo.rs (lines 234-237)
213fn demo_lazy_insertion() -> Result<(), Box<dyn std::error::Error>> {
214    println!("πŸ”„ Example 4: Lazy Insertion with get_or_insert_with");
215    println!("Parse only if not already cached...\n");
216    
217    let cache = ParsedSchemaCache::new();
218    
219    let schema_json = r#"{
220        "$params": {
221            "name": { "type": "string" }
222        },
223        "greeting": {
224            "type": "string",
225            "$evaluation": {
226                "cat": ["Hello, ", {"var": "$name"}, "!"]
227            }
228        }
229    }"#;
230    
231    // First access: will parse
232    println!("πŸ“ First access (will parse)...");
233    let start = Instant::now();
234    let schema1 = cache.get_or_insert_with("greeting-schema", || {
235        println!("   βš™οΈ  Parsing schema...");
236        Arc::new(ParsedSchema::parse(schema_json).unwrap())
237    });
238    println!("   Time: {:?}\n", start.elapsed());
239    
240    // Second access: will use cached
241    println!("πŸ” Second access (will use cache)...");
242    let start = Instant::now();
243    let schema2 = cache.get_or_insert_with("greeting-schema", || {
244        println!("   βš™οΈ  Parsing schema...");
245        Arc::new(ParsedSchema::parse(schema_json).unwrap())
246    });
247    println!("   Time: {:?}", start.elapsed());
248    
249    // Verify they're the same Arc (pointer equality)
250    println!("\nβœ… Both accesses returned the same cached instance");
251    println!("   Same pointer: {}", Arc::ptr_eq(&schema1, &schema2));
252    
253    Ok(())
254}
Source

pub fn insert_batch(&self, entries: Vec<(String, Arc<ParsedSchema>)>)

Batch insert multiple schemas at once

Source

pub fn remove_batch(&self, keys: &[String]) -> Vec<(String, Arc<ParsedSchema>)>

Remove multiple keys at once

Trait ImplementationsΒ§

SourceΒ§

impl Clone for ParsedSchemaCache

SourceΒ§

fn clone(&self) -> ParsedSchemaCache

Returns a duplicate of the value. Read more
1.0.0 Β· SourceΒ§

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

Performs copy-assignment from source. Read more
SourceΒ§

impl Default for ParsedSchemaCache

SourceΒ§

fn default() -> Self

Returns the β€œdefault value” for a type. Read more

Auto Trait ImplementationsΒ§

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, 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.