1use regex::Regex;
2use std::borrow::Cow;
3
4#[derive(Debug, Clone, Default)]
29pub struct JsonPathEvalContext {
30 regex_cache: Option<RegexCache>,
31}
32
33impl JsonPathEvalContext {
34 pub fn with_regex_cache() -> Self {
39 JsonPathEvalContext {
40 regex_cache: Some(RegexCache::default()),
41 }
42 }
43
44 pub(crate) fn regex(&mut self, pattern: &str) -> Result<Cow<'_, Regex>, regex::Error> {
46 match &mut self.regex_cache {
47 Some(cache) => cache.get_or_compile(pattern).map(Cow::Borrowed),
48 None => Regex::new(pattern).map(Cow::Owned),
49 }
50 }
51}
52
53#[derive(Debug, Clone, Default)]
55struct RegexCache(Vec<Regex>);
56
57impl RegexCache {
58 const CAPACITY: usize = 8;
60
61 fn get_or_compile(&mut self, pattern: &str) -> Result<&Regex, regex::Error> {
62 match self.0.iter().position(|regex| regex.as_str() == pattern) {
63 Some(hit) => self.0[..=hit].rotate_right(1),
64 None => {
65 let regex = Regex::new(pattern)?;
66 self.0.truncate(Self::CAPACITY - 1);
67 self.0.insert(0, regex);
68 }
69 }
70 Ok(&self.0[0])
71 }
72}
73
74#[cfg(test)]
75mod tests {
76 use super::*;
77 use crate::parser::parse_json_path;
78 use serde_json::json;
79
80 fn patterns(cache: &RegexCache) -> Vec<&str> {
81 cache.0.iter().map(Regex::as_str).collect()
82 }
83
84 #[test]
85 fn cache_keeps_the_patterns_used_last() {
86 let mut cache = RegexCache::default();
87 for i in 0..RegexCache::CAPACITY {
88 cache.get_or_compile(&format!("p{i}")).unwrap();
89 }
90 cache.get_or_compile("p0").unwrap();
92 cache.get_or_compile("next").unwrap();
93
94 assert_eq!(
95 patterns(&cache),
96 ["next", "p0", "p7", "p6", "p5", "p4", "p3", "p2"]
97 );
98 }
99
100 #[test]
101 fn cache_skips_an_invalid_pattern() {
102 let mut cache = RegexCache::default();
103 cache.get_or_compile("a").unwrap();
104
105 assert!(cache.get_or_compile("a[").is_err());
106 assert_eq!(patterns(&cache), ["a"]);
107 }
108
109 #[test]
110 fn default_context_keeps_nothing() {
111 let mut ctx = JsonPathEvalContext::default();
112
113 assert!(ctx.regex("a").is_ok());
114 assert!(ctx.regex_cache.is_none());
115 }
116
117 #[test]
119 fn context_reaches_every_function_call() {
120 let json = json!({
121 "a": [{"b": "x1", "c": {"b": "x1"}}, {"b": "x2", "c": {"b": "x2"}}],
122 "p": "x."
123 });
124
125 for (path, compiled) in [
126 ("$.a[?match(@.b, 'x.')]", 1),
127 ("$.a[?!search(@.b, 'x.')]", 1),
128 ("$.a[?match(@.b, $.p)]", 1),
129 ("$.a[?@.b == 'y' || match(@.b, 'x.')]", 1),
130 ("$.a[?@.b && (match(@.b, 'x.'))]", 1),
131 ("$..[?match(@.b, 'x.')]", 1),
132 ("$.a[?match(@.b, 'x1'), ?match(@.b, 'x2')]", 2),
133 ("$.a[?@[?match(@.b, 'x.')]]", 1),
134 ("$[?$.a[?match(@.b, 'x.')]]", 1),
135 ("$.a[?count(@[?match(@.b, 'x.')]) == 1]", 1),
136 ("$.a[?1 == count(@[?match(@.b, 'x.')])]", 1),
137 ("$.a[?value(@[?match(@.b, 'x.')]) == 'x1']", 1),
138 ("$.a[?length(@[?match(@.b, 'x.')]) == 1]", 1),
139 ("$.a[?match(@[?match(@.b, 'x.')], 'y')]", 1),
140 ("$.a[?match(@.b, @[?match(@.b, 'x.')])]", 1),
141 ("$.a[?search(@[?search(@.b, 'x.')], 'y')]", 1),
142 ("$.a[?search(@.b, @[?search(@.b, 'x.')])]", 1),
143 ("$.a[?in(@.b, $.a[?match(@.b, 'x.')])]", 1),
144 ("$.a[?in(!match(@.b, 'x.'), $.p)]", 1),
145 ] {
146 let mut ctx = JsonPathEvalContext::with_regex_cache();
147 parse_json_path(path)
148 .and_then(|query| query.execute_with_context(&json, &mut ctx))
149 .expect(path);
150
151 assert_eq!(ctx.regex_cache.unwrap().0.len(), compiled, "{path}");
152 }
153 }
154}