rsonpath/
string_pattern.rs

1use rsonpath_syntax::str::JsonString;
2
3/// String pattern coming from a JSONPath query that can be matched against strings in a JSON.
4///
5/// Right now the only pattern is matching against a given [`JsonString`].
6#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
7#[derive(Debug, Clone)]
8pub struct StringPattern(JsonString);
9
10impl std::hash::Hash for StringPattern {
11    #[inline]
12    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
13        self.0.hash(state);
14    }
15}
16
17impl PartialOrd for StringPattern {
18    #[inline]
19    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
20        Some(self.0.unquoted().cmp(other.0.unquoted()))
21    }
22}
23
24impl Ord for StringPattern {
25    #[inline]
26    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
27        self.0.unquoted().cmp(other.0.unquoted())
28    }
29}
30
31impl PartialEq for StringPattern {
32    #[inline]
33    fn eq(&self, other: &Self) -> bool {
34        self.0 == other.0
35    }
36}
37
38impl Eq for StringPattern {}
39
40impl StringPattern {
41    /// Get the underlying [`JsonString`] as bytes, including the delimiting double quote symbols.
42    #[inline]
43    #[must_use]
44    pub fn quoted(&self) -> &[u8] {
45        self.0.quoted().as_bytes()
46    }
47
48    /// Get the underlying [`JsonString`] as bytes, without the delimiting quotes.
49    #[inline]
50    #[must_use]
51    pub fn unquoted(&self) -> &[u8] {
52        self.0.unquoted().as_bytes()
53    }
54
55    /// Create a new pattern from a given [`JsonString`].
56    #[inline]
57    #[must_use]
58    pub fn new(string: &JsonString) -> Self {
59        Self(string.clone())
60    }
61}
62
63impl From<JsonString> for StringPattern {
64    #[inline(always)]
65    fn from(value: JsonString) -> Self {
66        Self::new(&value)
67    }
68}
69
70impl From<&JsonString> for StringPattern {
71    #[inline(always)]
72    fn from(value: &JsonString) -> Self {
73        Self::new(value)
74    }
75}