yason 0.0.2

Encoding and decoding support for YASON in Rust
Documentation
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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
//! Query by path expression.

use crate::path::parse::{ArrayStep, FuncStep, ObjectStep, SingleIndex, SingleStep, Step};
use crate::path::push_value;
use crate::yason::{LazyValue, YasonResult};
use crate::{DataType, Number, Value, Yason, YasonError};

pub struct Selector<'a, 'b> {
    steps: &'b [Step],
    with_wrapper: bool,
    query_buf: &'b mut Vec<Value<'a>>,
    for_exists: bool,
}

impl<'a, 'b> Selector<'a, 'b> {
    #[inline]
    pub fn new(steps: &'b [Step], with_wrapper: bool, query_buf: &'b mut Vec<Value<'a>>, for_exists: bool) -> Self {
        Self {
            steps,
            with_wrapper,
            query_buf,
            for_exists,
        }
    }

    #[inline]
    pub fn query(&mut self, value: &'a Yason, step_index: usize) -> YasonResult<bool> {
        let lazy_value = LazyValue::try_from(value)?;
        self.query_internal(lazy_value, step_index)
    }

    #[inline]
    fn query_internal<const IN_ARRAY: bool>(
        &mut self,
        value: LazyValue<'a, IN_ARRAY>,
        step_index: usize,
    ) -> YasonResult<bool> {
        debug_assert!(step_index <= self.steps.len());

        if step_index == self.steps.len() {
            if !self.for_exists {
                if !self.with_wrapper && !self.query_buf.is_empty() {
                    return Err(YasonError::MultiValuesWithoutWrapper);
                }

                push_value(self.query_buf, value.value()?)?;
            }
            return Ok(true);
        }

        let cur_step = &self.steps[step_index];
        match cur_step {
            Step::Root => unreachable!(),
            Step::Object(obj_step) => match obj_step {
                ObjectStep::Key(key) => self.object_key_match(value, step_index, key.as_str()),
                ObjectStep::Wildcard => self.object_wildcard_match(value, step_index),
            },
            Step::Array(arr_step) => match arr_step {
                ArrayStep::Index(index) => self.array_index_match(value, step_index, *index),
                ArrayStep::Last(minus) => self.array_last_match(value, step_index, *minus),
                ArrayStep::Range(begin, end) => self.array_range_match(value, step_index, begin, end),
                ArrayStep::Multiple(arr_steps) => self.array_multi_steps_match(value, step_index, arr_steps),
                ArrayStep::Wildcard => self.array_wildcard_match(value, step_index),
            },
            Step::Descendent(key) => self.descendent_step_match(value, step_index, key.as_str()),
            Step::Func(func) => self.func_step_match(value, step_index, func),
        }
    }

    #[inline]
    fn object_key_match<const IN_ARRAY: bool>(
        &mut self,
        value: LazyValue<'a, IN_ARRAY>,
        step_index: usize,
        key: &'b str,
    ) -> YasonResult<bool> {
        match value.data_type() {
            DataType::Object => {
                let object = unsafe { value.object()? };
                let val = object.lazy_get(key)?;
                if let Some(v) = val {
                    return self.query_internal(v, step_index + 1);
                }
            }
            DataType::Array => {
                let array = unsafe { value.array()? };
                for val in array.lazy_iter()? {
                    let found = self.query_internal(val?, step_index)?;
                    if self.for_exists && found {
                        return Ok(true);
                    }
                }
            }
            _ => {}
        }
        Ok(false)
    }

    #[inline]
    fn object_wildcard_match<const IN_ARRAY: bool>(
        &mut self,
        value: LazyValue<'a, IN_ARRAY>,
        step_index: usize,
    ) -> YasonResult<bool> {
        match value.data_type() {
            DataType::Object => {
                let object = unsafe { value.object()? };
                for val in object.lazy_value_iter()? {
                    let found = self.query_internal(val?, step_index + 1)?;
                    if self.for_exists && found {
                        return Ok(true);
                    }
                }
            }
            DataType::Array => {
                let array = unsafe { value.array()? };
                for val in array.lazy_iter()? {
                    let found = self.query_internal(val?, step_index)?;
                    if self.for_exists && found {
                        return Ok(true);
                    }
                }
            }
            _ => {}
        }

        Ok(false)
    }

    #[inline]
    fn array_index_match<const IN_ARRAY: bool>(
        &mut self,
        value: LazyValue<'a, IN_ARRAY>,
        step_index: usize,
        index: usize,
    ) -> YasonResult<bool> {
        match value.data_type() {
            DataType::Array => {
                let array = unsafe { value.array()? };
                if index < array.len()? {
                    let val = unsafe { array.lazy_get_unchecked(index)? };
                    return self.query_internal(val, step_index + 1);
                }
            }
            _ => {
                if index == 0 {
                    return self.non_array_relax_match(value, step_index + 1);
                }
            }
        }
        Ok(false)
    }

    #[inline]
    fn array_last_match<const IN_ARRAY: bool>(
        &mut self,
        value: LazyValue<'a, IN_ARRAY>,
        step_index: usize,
        minus: usize,
    ) -> YasonResult<bool> {
        match value.data_type() {
            DataType::Array => {
                let array = unsafe { value.array()? };
                let len = array.len()?;
                if len > minus {
                    let val = unsafe { array.lazy_get_unchecked(len - 1 - minus)? };
                    return self.query_internal(val, step_index + 1);
                }
            }
            _ => {
                if minus == 0 {
                    return self.non_array_relax_match(value, step_index + 1);
                }
            }
        }

        Ok(false)
    }

    #[inline]
    fn array_range_match<const IN_ARRAY: bool>(
        &mut self,
        value: LazyValue<'a, IN_ARRAY>,
        step_index: usize,
        begin: &'b SingleIndex,
        end: &'b SingleIndex,
    ) -> YasonResult<bool> {
        match value.data_type() {
            DataType::Array => {
                let array = unsafe { value.array()? };
                let len = array.len()?;
                if len == 0 {
                    return Ok(false);
                }

                let last = len - 1;
                if let Some((b, e)) = find_range(begin, end, last) {
                    for i in b..e + 1 {
                        let val = unsafe { array.lazy_get_unchecked(i)? };
                        let found = self.query_internal(val, step_index + 1)?;
                        if self.for_exists && found {
                            return Ok(true);
                        }
                    }
                }
            }
            _ => {
                if non_array_range_step_relaxed_match(begin, end) {
                    return self.non_array_relax_match(value, step_index + 1);
                }
            }
        }
        Ok(false)
    }

    #[inline]
    fn array_multi_steps_match<const IN_ARRAY: bool>(
        &mut self,
        value: LazyValue<'a, IN_ARRAY>,
        step_index: usize,
        arr_steps: &'b [SingleStep],
    ) -> YasonResult<bool> {
        match value.data_type() {
            DataType::Array => {
                let array = unsafe { value.array()? };
                let len = array.len()?;
                if len == 0 {
                    return Ok(false);
                }

                let mut arr_steps_index = 0;
                while arr_steps_index < arr_steps.len() {
                    let cur_step = &arr_steps[arr_steps_index];

                    match cur_step {
                        SingleStep::Single(single_index) => match single_index {
                            SingleIndex::Index(index) => {
                                if *index < len {
                                    let val = unsafe { array.lazy_get_unchecked(*index)? };
                                    let found = self.query_internal(val, step_index + 1)?;
                                    if self.for_exists && found {
                                        return Ok(true);
                                    }
                                }
                            }
                            SingleIndex::Last(minus) => {
                                if len > *minus {
                                    let val = unsafe { array.lazy_get_unchecked(len - 1 - minus)? };
                                    let found = self.query_internal(val, step_index + 1)?;
                                    if self.for_exists && found {
                                        return Ok(true);
                                    }
                                }
                            }
                        },
                        SingleStep::Range(begin, end) => {
                            let last = len - 1;
                            if let Some((b, e)) = find_range(begin, end, last) {
                                for i in b..e + 1 {
                                    let val = unsafe { array.lazy_get_unchecked(i)? };
                                    let found = self.query_internal(val, step_index + 1)?;
                                    if self.for_exists && found {
                                        return Ok(true);
                                    }
                                }
                            }
                        }
                    }
                    arr_steps_index += 1;
                }
            }
            _ => {
                if non_array_multi_steps_relaxed_match(arr_steps) {
                    return self.non_array_relax_match(value, step_index + 1);
                }
            }
        }
        Ok(false)
    }

    #[inline]
    fn array_wildcard_match<const IN_ARRAY: bool>(
        &mut self,
        value: LazyValue<'a, IN_ARRAY>,
        step_index: usize,
    ) -> YasonResult<bool> {
        match value.data_type() {
            DataType::Array => {
                let array = unsafe { value.array()? };
                for val in array.lazy_iter()? {
                    let found = self.query_internal(val?, step_index + 1)?;
                    if self.for_exists && found {
                        return Ok(true);
                    }
                }
            }
            _ => return self.non_array_relax_match(value, step_index + 1),
        }

        Ok(false)
    }

    #[inline]
    fn non_array_relax_match<const IN_ARRAY: bool>(
        &mut self,
        value: LazyValue<'a, IN_ARRAY>,
        step_index: usize,
    ) -> YasonResult<bool> {
        let mut cur_step_index = step_index;

        while cur_step_index < self.steps.len() {
            let step = &self.steps[cur_step_index];
            match step {
                Step::Array(array_step) => match array_step {
                    ArrayStep::Index(index) => {
                        if *index == 0 {
                            cur_step_index += 1;
                        } else {
                            return Ok(false);
                        }
                    }
                    ArrayStep::Last(minus) => {
                        if *minus == 0 {
                            cur_step_index += 1;
                        } else {
                            return Ok(false);
                        }
                    }
                    ArrayStep::Range(begin, end) => {
                        if non_array_range_step_relaxed_match(begin, end) {
                            cur_step_index += 1;
                        } else {
                            return Ok(false);
                        }
                    }
                    ArrayStep::Multiple(steps) => {
                        if non_array_multi_steps_relaxed_match(steps) {
                            cur_step_index += 1;
                        } else {
                            return Ok(false);
                        }
                    }
                    ArrayStep::Wildcard => {
                        cur_step_index += 1;
                    }
                },
                _ => return self.query_internal(value, cur_step_index),
            }
        }

        self.query_internal(value, cur_step_index)
    }

    #[inline]
    fn descendent_step_match<const IN_ARRAY: bool>(
        &mut self,
        value: LazyValue<'a, IN_ARRAY>,
        step_index: usize,
        key: &'b str,
    ) -> YasonResult<bool> {
        match value.data_type() {
            DataType::Object => {
                let object = unsafe { value.object()? };
                if let Some(val) = object.lazy_get(key)? {
                    let found = self.query_internal(val, step_index + 1)?;
                    if self.for_exists && found {
                        return Ok(true);
                    }
                }

                for val in object.lazy_value_iter()? {
                    let found = self.query_internal(val?, step_index)?;
                    if self.for_exists && found {
                        return Ok(true);
                    }
                }
            }
            DataType::Array => {
                let array = unsafe { value.array()? };
                for val in array.lazy_iter()? {
                    let found = self.query_internal(val?, step_index)?;
                    if self.for_exists && found {
                        return Ok(true);
                    }
                }
            }
            _ => {}
        }

        Ok(false)
    }

    #[inline]
    fn func_step_match<const IN_ARRAY: bool>(
        &mut self,
        value: LazyValue<'a, IN_ARRAY>,
        step_index: usize,
        func: &'b FuncStep,
    ) -> YasonResult<bool> {
        debug_assert!(step_index + 1 == self.steps.len());
        debug_assert!(self.with_wrapper);
        let val = match func {
            FuncStep::Count => Value::Null,
            FuncStep::Size => {
                let size = match value.data_type() {
                    DataType::Array => {
                        let array = unsafe { value.array()? };
                        array.len()?
                    }
                    _ => 1,
                };

                Value::Number(Number::from(size))
            }
            FuncStep::Type => {
                let data_type = value.data_type();
                Value::String(data_type.name())
            }
        };
        push_value(self.query_buf, val)?;
        Ok(false)
    }
}

#[inline]
fn non_array_multi_steps_relaxed_match(steps: &[SingleStep]) -> bool {
    for step in steps {
        match step {
            SingleStep::Single(single_index) => match single_index {
                SingleIndex::Index(index) => {
                    if *index == 0 {
                        return true;
                    }
                }
                SingleIndex::Last(minus) => {
                    if *minus == 0 {
                        return true;
                    }
                }
            },

            SingleStep::Range(left_field, right_field) => {
                if non_array_range_step_relaxed_match(left_field, right_field) {
                    return true;
                }
            }
        }
    }

    false
}

#[inline]
fn non_array_range_step_relaxed_match(begin: &SingleIndex, end: &SingleIndex) -> bool {
    // For non-array types, an array of size 1 is automatically encapsulated for relaxed matching
    // and only index 0 can be matched.
    if let Some((b, _)) = find_range(begin, end, 0) {
        if b == 0 {
            return true;
        }
    }

    false
}

// Find the index range to traverse based on the two SingleIndexes, both sides of this range are closed.
// For example, if the return value is Some((1, 3)), the indexes that need to be traversed are 1, 2, 3.
// The argument `last` is equal to the last index of the array (last = array.len() - 1).
#[inline]
fn find_range(begin: &SingleIndex, end: &SingleIndex, last: usize) -> Option<(usize, usize)> {
    #[inline]
    fn find_range_by_index(begin_index: usize, end_index: usize, last: usize) -> Option<(usize, usize)> {
        debug_assert!(begin_index <= end_index);
        let end_index = end_index.min(last);
        if begin_index <= end_index {
            Some((begin_index, end_index))
        } else {
            None
        }
    }

    #[inline]
    fn find_range_by_last(minus1: usize, minus2: usize, last: usize) -> Option<(usize, usize)> {
        debug_assert!(minus1 <= minus2);
        let begin_index = last.saturating_sub(minus2);

        if minus1 <= last {
            Some((begin_index, last - minus1))
        } else {
            None
        }
    }

    #[inline]
    fn order(l: usize, r: usize) -> (usize, usize) {
        if l <= r {
            (l, r)
        } else {
            (r, l)
        }
    }

    match (begin, end) {
        (SingleIndex::Index(i1), SingleIndex::Index(i2)) => {
            let (begin_index, end_index) = order(*i1, *i2);
            find_range_by_index(begin_index, end_index, last)
        }
        (SingleIndex::Index(i1), SingleIndex::Last(minus)) => {
            let i2 = last.saturating_sub(*minus);
            let (begin_index, end_index) = order(*i1, i2);
            find_range_by_index(begin_index, end_index, last)
        }
        (SingleIndex::Last(minus), SingleIndex::Index(i2)) => {
            let i1 = last.saturating_sub(*minus);
            let (begin_index, end_index) = order(i1, *i2);
            find_range_by_index(begin_index, end_index, last)
        }
        (SingleIndex::Last(m1), SingleIndex::Last(m2)) => {
            let (minus1, minus2) = order(*m1, *m2);
            find_range_by_last(minus1, minus2, last)
        }
    }
}