Skip to main content

jsonpath_rust/query/
context.rs

1use regex::Regex;
2use std::borrow::Cow;
3
4/// What an evaluation can reuse from one node, document or query to the next.
5///
6/// The library keeps no state of its own. Whatever is worth reusing lives in a context that
7/// the caller creates, passes to [`JpQuery::execute_with_context`] and drops when it is no
8/// longer needed. The default context reuses nothing.
9///
10/// ```
11/// use jsonpath_rust::parser::parse_json_path;
12/// use jsonpath_rust::query::JsonPathEvalContext;
13/// use serde_json::json;
14///
15/// let query = parse_json_path("$[?search(@.title, 'of')]")?;
16/// let mut ctx = JsonPathEvalContext::with_regex_cache();
17///
18/// let first = json!([{"title": "Sayings of the Century"}, {"title": "Moby Dick"}]);
19/// let second = json!([{"title": "Sword of Honour"}]);
20///
21/// // The pattern is compiled once for the three titles.
22/// assert_eq!(query.execute_with_context(&first, &mut ctx)?.len(), 1);
23/// assert_eq!(query.execute_with_context(&second, &mut ctx)?.len(), 1);
24/// # Ok::<(), jsonpath_rust::parser::errors::JsonPathError>(())
25/// ```
26///
27/// [`JpQuery::execute_with_context`]: crate::parser::model::JpQuery::execute_with_context
28#[derive(Debug, Clone, Default)]
29pub struct JsonPathEvalContext {
30    regex_cache: Option<RegexCache>,
31}
32
33impl JsonPathEvalContext {
34    /// A context that keeps the patterns `match()` and `search()` compile, so that a pattern
35    /// is compiled once instead of once per node.
36    ///
37    /// It keeps the 8 patterns used last, whichever queries and documents they come from.
38    pub fn with_regex_cache() -> Self {
39        JsonPathEvalContext {
40            regex_cache: Some(RegexCache::default()),
41        }
42    }
43
44    /// Returns the compiled `pattern`, from the cache if the context has one.
45    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/// The compiled patterns, the most recently used first.
54#[derive(Debug, Clone, Default)]
55struct RegexCache(Vec<Regex>);
56
57impl RegexCache {
58    /// A pattern can come from the document, so the cache must not grow with the data.
59    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        // p0 is used again, which leaves p1 as the one to give up for the next pattern
91        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    // match() and search() have to get the context wherever they are in the query.
118    #[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}