1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
pub mod automaton;
pub mod builder;
pub mod error;
mod parser;
use aligners::{alignment, AlignedBytes, AlignedSlice};
use cfg_if::cfg_if;
use log::*;
use std::fmt::{self, Display};
cfg_if! {
if #[cfg(feature = "simd")] {
pub type LabelAlignment = alignment::SimdBlock;
}
else {
pub type LabelAlignment = alignment::One;
}
}
pub struct Label {
label: AlignedBytes<LabelAlignment>,
label_with_quotes: AlignedBytes<LabelAlignment>,
}
impl std::fmt::Debug for Label {
#[inline]
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
write!(
f,
r#"{}"#,
std::str::from_utf8(&self.label_with_quotes).unwrap_or("[invalid utf8]")
)
}
}
impl Clone for Label {
#[inline]
fn clone(&self) -> Self {
let label_clone = AlignedBytes::from(self.label.as_ref());
let quoted_clone = AlignedBytes::from(self.label_with_quotes.as_ref());
Self {
label: label_clone,
label_with_quotes: quoted_clone,
}
}
}
impl Label {
#[must_use]
#[inline]
pub fn new(label: &str) -> Self {
let bytes = label.as_bytes();
let without_quotes = AlignedBytes::<LabelAlignment>::from(bytes);
let mut with_quotes = AlignedBytes::<LabelAlignment>::new_zeroed(bytes.len() + 2);
with_quotes[0] = b'"';
with_quotes[1..bytes.len() + 1].copy_from_slice(bytes);
with_quotes[bytes.len() + 1] = b'"';
Self {
label: without_quotes,
label_with_quotes: with_quotes,
}
}
#[must_use]
#[inline(always)]
pub fn bytes(&self) -> &AlignedSlice<LabelAlignment> {
&self.label
}
#[must_use]
#[inline(always)]
pub fn bytes_with_quotes(&self) -> &AlignedSlice<LabelAlignment> {
&self.label_with_quotes
}
#[must_use]
#[inline(always)]
pub fn display(&self) -> impl Display + '_ {
std::str::from_utf8(&self.label).unwrap_or("[invalid utf8]")
}
}
impl std::ops::Deref for Label {
type Target = AlignedSlice<LabelAlignment>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
self.bytes()
}
}
impl PartialEq<Self> for Label {
#[inline(always)]
fn eq(&self, other: &Self) -> bool {
self.label == other.label
}
}
impl Eq for Label {}
impl PartialEq<Label> for [u8] {
#[inline(always)]
fn eq(&self, other: &Label) -> bool {
self == &other.label
}
}
impl PartialEq<Label> for &[u8] {
#[inline(always)]
fn eq(&self, other: &Label) -> bool {
*self == &other.label
}
}
impl PartialEq<[u8]> for Label {
#[inline(always)]
fn eq(&self, other: &[u8]) -> bool {
&self.label == other
}
}
impl PartialEq<&[u8]> for Label {
#[inline(always)]
fn eq(&self, other: &&[u8]) -> bool {
&self.label == *other
}
}
impl std::hash::Hash for Label {
#[inline(always)]
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
let slice: &[u8] = &self.label;
slice.hash(state);
}
}
#[derive(Debug, PartialEq, Eq)]
pub enum JsonPathQueryNode {
Root(Option<Box<JsonPathQueryNode>>),
Child(Label, Option<Box<JsonPathQueryNode>>),
AnyChild(Option<Box<JsonPathQueryNode>>),
Descendant(Label, Option<Box<JsonPathQueryNode>>),
}
use JsonPathQueryNode::*;
use self::error::ParserError;
impl JsonPathQueryNode {
#[must_use]
#[inline(always)]
pub fn child(&self) -> Option<&Self> {
match self {
Root(node) | Child(_, node) | AnyChild(node) | Descendant(_, node) => node.as_deref(),
}
}
#[must_use]
#[inline(always)]
pub fn iter(&self) -> JsonPathQueryIterator {
JsonPathQueryIterator { node: Some(self) }
}
}
#[derive(Debug, PartialEq, Eq)]
pub struct JsonPathQuery {
root: Box<JsonPathQueryNode>,
}
pub struct JsonPathQueryIterator<'a> {
node: Option<&'a JsonPathQueryNode>,
}
impl<'a> Iterator for JsonPathQueryIterator<'a> {
type Item = &'a JsonPathQueryNode;
#[inline]
fn next(&mut self) -> Option<Self::Item> {
let result = self.node;
if let Some(node) = result {
self.node = node.child()
}
result
}
}
impl JsonPathQuery {
#[must_use]
#[inline(always)]
pub fn root(&self) -> &JsonPathQueryNode {
self.root.as_ref()
}
#[inline(always)]
pub fn parse(query_string: &str) -> Result<Self, ParserError> {
self::parser::parse_json_path_query(query_string)
}
#[inline]
#[must_use]
pub fn new(node: Box<JsonPathQueryNode>) -> Self {
let root = if node.is_root() {
node
} else {
info!("Implicitly using the Root expression (`$`) at the start of the query.");
Box::new(Root(Some(node)))
};
Self { root }
}
}
impl Display for JsonPathQuery {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.root.as_ref())
}
}
impl Display for JsonPathQueryNode {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Root(_) => write!(f, "$"),
Child(label, _) => write!(f, "['{}']", label.display()),
AnyChild(_) => write!(f, "[*]"),
Descendant(label, _) => write!(f, "..['{}']", label.display()),
}?;
if let Some(child) = self.child() {
write!(f, "{child}")
} else {
Ok(())
}
}
}
pub trait JsonPathQueryNodeType {
fn is_root(&self) -> bool;
fn is_descendant(&self) -> bool;
fn is_child(&self) -> bool;
fn label(&self) -> Option<&Label>;
}
impl JsonPathQueryNodeType for JsonPathQueryNode {
#[inline(always)]
fn is_root(&self) -> bool {
matches!(self, Root(_))
}
#[inline(always)]
fn is_descendant(&self) -> bool {
matches!(self, Descendant(_, _))
}
#[inline(always)]
fn is_child(&self) -> bool {
matches!(self, Child(_, _))
}
#[inline(always)]
fn label(&self) -> Option<&Label> {
match self {
Child(label, _) | Descendant(label, _) => Some(label),
Root(_) | AnyChild(_) => None,
}
}
}
impl<T: std::ops::Deref<Target = JsonPathQueryNode>> JsonPathQueryNodeType for Option<T> {
#[inline(always)]
fn is_root(&self) -> bool {
self.as_ref().map_or(false, |x| x.is_root())
}
#[inline(always)]
fn is_descendant(&self) -> bool {
self.as_ref().map_or(false, |x| x.is_descendant())
}
#[inline(always)]
fn is_child(&self) -> bool {
self.as_ref().map_or(false, |x| x.is_child())
}
#[inline(always)]
fn label(&self) -> Option<&Label> {
self.as_ref().and_then(|x| x.label())
}
}
#[cfg(test)]
mod tests {
use std::{
collections::hash_map::DefaultHasher,
hash::{Hash, Hasher},
};
use super::*;
#[test]
fn label_equality() {
let label1 = Label::new("dog");
let label2 = Label::new("dog");
assert_eq!(label1, label2);
}
#[test]
fn label_inequality() {
let label1 = Label::new("dog");
let label2 = Label::new("doc");
assert_ne!(label1, label2);
}
#[test]
fn label_hash() {
let label1 = Label::new("dog");
let label2 = Label::new("dog");
let mut s1 = DefaultHasher::new();
label1.hash(&mut s1);
let h1 = s1.finish();
let mut s2 = DefaultHasher::new();
label2.hash(&mut s2);
let h2 = s2.finish();
assert_eq!(h1, h2);
}
}