pjson-rs 0.5.2

Priority JSON Streaming Protocol - high-performance priority-based JSON streaming (requires nightly 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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
//! Lazy JSON value types for zero-copy parsing

use crate::parser::scanner::{Range, ScanResult};
use crate::{Error, Result};
use smallvec::SmallVec;

/// Zero-copy JSON value representation
#[derive(Debug, Clone)]
pub enum JsonValue<'a> {
    /// Raw bytes slice (not parsed yet)
    Raw(&'a [u8]),
    /// Parsed string (zero-copy)
    String(&'a str),
    /// Number stored as bytes for lazy parsing
    Number(&'a [u8]),
    /// Boolean value
    Bool(bool),
    /// Null value
    Null,
    /// Array with lazy evaluation
    Array(LazyArray<'a>),
    /// Object with lazy evaluation
    Object(LazyObject<'a>),
}

/// Lazy array that parses elements on-demand
#[derive(Debug, Clone)]
pub struct LazyArray<'a> {
    /// Raw JSON bytes
    raw: &'a [u8],
    /// Pre-computed element boundaries using SIMD scanning
    boundaries: SmallVec<[Range; 32]>,
}

/// Lazy object that parses fields on-demand
#[derive(Debug, Clone)]
pub struct LazyObject<'a> {
    /// Raw JSON bytes
    raw: &'a [u8],
    /// Pre-computed key-value boundaries
    fields: SmallVec<[FieldRange; 16]>,
}

/// Field boundary information
#[derive(Debug, Clone)]
pub struct FieldRange {
    /// Key range (without quotes)
    key: Range,
    /// Value range
    value: Range,
}

impl<'a> JsonValue<'a> {
    /// Get value as string if it's a string type
    pub fn as_str(&self) -> Option<&str> {
        match self {
            JsonValue::String(s) => Some(s),
            _ => None,
        }
    }

    /// Get value as f64 if it's a number
    pub fn as_f64(&self) -> Option<f64> {
        match self {
            JsonValue::Number(bytes) => std::str::from_utf8(bytes).ok()?.parse().ok(),
            _ => None,
        }
    }

    /// Get value as i64 if it's an integer number
    pub fn as_i64(&self) -> Option<i64> {
        match self {
            JsonValue::Number(bytes) => std::str::from_utf8(bytes).ok()?.parse().ok(),
            _ => None,
        }
    }

    /// Get value as bool if it's a boolean
    pub fn as_bool(&self) -> Option<bool> {
        match self {
            JsonValue::Bool(b) => Some(*b),
            _ => None,
        }
    }

    /// Check if value is null
    pub fn is_null(&self) -> bool {
        matches!(self, JsonValue::Null)
    }

    /// Get value as array
    pub fn as_array(&self) -> Option<&LazyArray<'a>> {
        match self {
            JsonValue::Array(arr) => Some(arr),
            _ => None,
        }
    }

    /// Get value as object
    pub fn as_object(&self) -> Option<&LazyObject<'a>> {
        match self {
            JsonValue::Object(obj) => Some(obj),
            _ => None,
        }
    }

    /// Force parse raw bytes into structured value
    pub fn parse_raw(&mut self) -> Result<()> {
        match self {
            JsonValue::Raw(_bytes) => {
                // This would use the main parser to parse the raw bytes
                // For now, we'll leave this as a placeholder
                *self = JsonValue::Null; // Simplified
                Ok(())
            }
            _ => Ok(()),
        }
    }
}

impl<'a> LazyArray<'a> {
    /// Create new lazy array from scan result
    pub fn from_scan(raw: &'a [u8], scan_result: ScanResult) -> Self {
        // Extract array element boundaries from scan result
        let boundaries = Self::extract_element_boundaries(raw, &scan_result);

        Self { raw, boundaries }
    }

    /// Get array length
    pub fn len(&self) -> usize {
        self.boundaries.len()
    }

    /// Check if array is empty
    pub fn is_empty(&self) -> bool {
        self.boundaries.is_empty()
    }

    /// Get element at index (simplified - returns raw bytes)
    pub fn get(&self, index: usize) -> Option<&'a [u8]> {
        if index >= self.boundaries.len() {
            return None;
        }

        let range = self.boundaries[index];
        Some(&self.raw[range.start..range.end])
    }

    /// Get element at index, parsing if necessary (simplified)
    pub fn get_parsed(&self, index: usize) -> Option<JsonValue<'a>> {
        self.get(index).map(JsonValue::Raw)
    }

    /// Iterator over array elements (lazy)
    pub fn iter(&'a self) -> LazyArrayIter<'a> {
        LazyArrayIter {
            array: self,
            index: 0,
        }
    }

    /// Extract top-level element boundaries from a JSON array.
    ///
    /// Parses `raw` bytes assuming it is a JSON array (`[...]`) and returns
    /// a `Range` for each top-level element, trimmed of surrounding whitespace.
    /// Nested arrays/objects and strings (including escaped quotes) are treated
    /// opaquely — only depth-0 commas and the closing `]` act as delimiters.
    ///
    /// # Invariant
    ///
    /// Assumes well-formed JSON. Mismatched brackets in nested content (e.g. `[{]}`) may
    /// produce incorrect ranges without signalling an error.
    fn extract_element_boundaries(raw: &[u8], _scan_result: &ScanResult) -> SmallVec<[Range; 32]> {
        let mut result = SmallVec::new();
        let len = raw.len();

        // Find the opening '['.
        let mut pos = 0;
        while pos < len && raw[pos] != b'[' {
            pos += 1;
        }
        if pos == len {
            return result;
        }
        pos += 1; // skip '['

        let mut depth: usize = 1;
        let mut in_string = false;
        let mut elem_start: Option<usize> = None;

        while pos < len {
            let b = raw[pos];

            if in_string {
                if b == b'\\' {
                    // Skip the escaped character.
                    pos += 1;
                } else if b == b'"' {
                    in_string = false;
                }
                pos += 1;
                continue;
            }

            match b {
                b'"' => {
                    in_string = true;
                    if elem_start.is_none() {
                        elem_start = Some(pos);
                    }
                }
                b'[' | b'{' => {
                    depth += 1;
                    if elem_start.is_none() {
                        elem_start = Some(pos);
                    }
                }
                b']' | b'}' => {
                    depth -= 1;
                    if depth == 0 {
                        // Closing bracket of the top-level array — emit last element.
                        if let Some(start) = elem_start {
                            let end = trim_end(raw, start, pos);
                            if end > start {
                                result.push(Range::new(start, end));
                            }
                        }
                        break;
                    }
                }
                b',' if depth == 1 => {
                    // Top-level separator — emit the current element.
                    if let Some(start) = elem_start {
                        let end = trim_end(raw, start, pos);
                        if end > start {
                            result.push(Range::new(start, end));
                        }
                    }
                    elem_start = None;
                }
                b' ' | b'\t' | b'\n' | b'\r' => {
                    // Whitespace before first non-space character of an element.
                    pos += 1;
                    continue;
                }
                _ => {
                    if elem_start.is_none() {
                        elem_start = Some(pos);
                    }
                }
            }
            pos += 1;
        }

        result
    }

    /// Check if this appears to be a numeric array for SIMD optimization
    pub fn is_numeric(&self) -> bool {
        // Heuristic: check first few elements
        self.boundaries.len() > 4
            && self.boundaries.iter().take(3).all(|range| {
                let slice = &self.raw[range.start..range.end];
                self.looks_like_number(slice)
            })
    }

    fn looks_like_number(&self, bytes: &[u8]) -> bool {
        if bytes.is_empty() {
            return false;
        }

        bytes.iter().all(|&b| {
            b.is_ascii_digit() || b == b'.' || b == b'-' || b == b'+' || b == b'e' || b == b'E'
        })
    }
}

impl<'a> LazyObject<'a> {
    /// Create new lazy object from scan result
    pub fn from_scan(raw: &'a [u8], scan_result: ScanResult) -> Self {
        let fields = Self::extract_field_boundaries(raw, &scan_result);

        Self { raw, fields }
    }

    /// Get number of fields
    pub fn len(&self) -> usize {
        self.fields.len()
    }

    /// Check if object is empty
    pub fn is_empty(&self) -> bool {
        self.fields.is_empty()
    }

    /// Get field value by key (simplified)
    pub fn get(&self, key: &str) -> Option<&'a [u8]> {
        // Find field by key
        let field_range = self.fields.iter().find(|field| {
            let key_bytes = &self.raw[field.key.start..field.key.end];
            std::str::from_utf8(key_bytes) == Ok(key)
        })?;

        // Return value bytes
        Some(&self.raw[field_range.value.start..field_range.value.end])
    }

    /// Get all field keys
    pub fn keys(&self) -> Result<Vec<&str>> {
        self.fields
            .iter()
            .map(|field| {
                let key_bytes = &self.raw[field.key.start..field.key.end];
                std::str::from_utf8(key_bytes).map_err(Error::from)
            })
            .collect()
    }

    /// Extract top-level field boundaries from a JSON object.
    ///
    /// Parses `raw` bytes assuming it is a JSON object (`{...}`) and returns a
    /// `FieldRange` for each top-level field.  The `key` range covers the string
    /// content **without** surrounding quotes; the `value` range covers the full
    /// value representation (including quotes when the value is a string).
    ///
    /// # Invariant
    ///
    /// Assumes well-formed JSON. Malformed input (e.g. duplicate commas, mismatched
    /// brackets) may produce incomplete results without signalling an error.
    fn extract_field_boundaries(
        raw: &[u8],
        _scan_result: &ScanResult,
    ) -> SmallVec<[FieldRange; 16]> {
        let mut result = SmallVec::new();
        let len = raw.len();

        // Find the opening '{'.
        let mut pos = 0;
        while pos < len && raw[pos] != b'{' {
            pos += 1;
        }
        if pos == len {
            return result;
        }
        pos += 1; // skip '{'

        loop {
            // --- skip whitespace before key ---
            while pos < len && raw[pos].is_ascii_whitespace() {
                pos += 1;
            }
            if pos >= len || raw[pos] == b'}' {
                break;
            }
            if raw[pos] != b'"' {
                // Malformed input; stop.
                break;
            }
            pos += 1; // skip opening '"'
            let key_start = pos;
            // Scan to closing '"', honouring backslash escapes.
            while pos < len && raw[pos] != b'"' {
                if raw[pos] == b'\\' {
                    pos += 1; // skip escaped char
                }
                pos += 1;
            }
            let key_end = pos;
            if pos < len {
                pos += 1; // skip closing '"'
            }

            // --- skip whitespace and ':' ---
            while pos < len && (raw[pos].is_ascii_whitespace() || raw[pos] == b':') {
                pos += 1;
            }
            if pos >= len {
                break;
            }

            // --- parse value with depth tracking ---
            let value_start = pos;
            let mut depth: usize = 0;
            let mut in_str = false;

            while pos < len {
                let b = raw[pos];
                if in_str {
                    if b == b'\\' {
                        pos += 1; // skip escaped char
                    } else if b == b'"' {
                        in_str = false;
                        if depth == 0 {
                            pos += 1;
                            break;
                        }
                    }
                    pos += 1;
                    continue;
                }
                match b {
                    b'"' => {
                        in_str = true;
                    }
                    b'[' | b'{' => depth += 1,
                    b']' | b'}' => {
                        if depth == 0 {
                            // Closing brace of the parent object — do not consume.
                            break;
                        }
                        depth -= 1;
                        if depth == 0 {
                            pos += 1;
                            break;
                        }
                    }
                    b',' if depth == 0 => {
                        // Separator between fields — do not consume.
                        break;
                    }
                    _ => {}
                }
                pos += 1;
            }

            let value_end = trim_end(raw, value_start, pos);
            if value_end > value_start {
                result.push(FieldRange::new(
                    Range::new(key_start, key_end),
                    Range::new(value_start, value_end),
                ));
            }

            // Skip ',' between fields (or '}' will exit on the next iteration).
            while pos < len && (raw[pos].is_ascii_whitespace() || raw[pos] == b',') {
                pos += 1;
            }
        }

        result
    }
}

/// Iterator for lazy array elements
pub struct LazyArrayIter<'a> {
    array: &'a LazyArray<'a>,
    index: usize,
}

impl<'a> Iterator for LazyArrayIter<'a> {
    type Item = &'a [u8]; // Raw element bytes

    fn next(&mut self) -> Option<Self::Item> {
        if self.index >= self.array.boundaries.len() {
            return None;
        }

        let range = self.array.boundaries[self.index];
        self.index += 1;

        Some(&self.array.raw[range.start..range.end])
    }
}

impl FieldRange {
    /// Create new field range
    pub fn new(key: Range, value: Range) -> Self {
        Self { key, value }
    }
}

/// Return the index past the last non-whitespace byte in `raw[start..end]`.
///
/// Used to strip trailing whitespace from element and value ranges.
fn trim_end(raw: &[u8], start: usize, end: usize) -> usize {
    let mut e = end;
    while e > start && raw[e - 1].is_ascii_whitespace() {
        e -= 1;
    }
    e
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_json_value_types() {
        let val = JsonValue::String("hello");
        assert_eq!(val.as_str(), Some("hello"));
        assert!(val.as_f64().is_none());
    }

    #[test]
    fn test_lazy_array_creation() {
        let raw = b"[1, 2, 3]";
        let scan_result = ScanResult::new();
        let array = LazyArray::from_scan(raw, scan_result);

        assert_eq!(array.len(), 3);
        assert_eq!(array.get(0), Some(b"1".as_ref()));
        assert_eq!(array.get(1), Some(b"2".as_ref()));
        assert_eq!(array.get(2), Some(b"3".as_ref()));
    }

    #[test]
    fn test_lazy_array_empty() {
        let array = LazyArray::from_scan(b"[]", ScanResult::new());
        assert_eq!(array.len(), 0);
        assert!(array.is_empty());
    }

    #[test]
    fn test_lazy_array_strings() {
        let raw = b"[\"hello\", \"world\"]";
        let array = LazyArray::from_scan(raw, ScanResult::new());
        assert_eq!(array.len(), 2);
        assert_eq!(array.get(0), Some(b"\"hello\"".as_ref()));
    }

    #[test]
    fn test_lazy_array_nested() {
        let raw = b"[1, [2, 3], {\"a\": 4}]";
        let array = LazyArray::from_scan(raw, ScanResult::new());
        assert_eq!(array.len(), 3);
        assert_eq!(array.get(0), Some(b"1".as_ref()));
        assert_eq!(array.get(1), Some(b"[2, 3]".as_ref()));
        assert_eq!(array.get(2), Some(b"{\"a\": 4}".as_ref()));
    }

    #[test]
    fn test_lazy_array_escaped_string() {
        let raw = br#"["say \"hi\"", "bye"]"#;
        let array = LazyArray::from_scan(raw, ScanResult::new());
        assert_eq!(array.len(), 2);
    }

    #[test]
    fn test_lazy_object_creation() {
        let obj = LazyObject::from_scan(b"{\"a\": 1, \"b\": 2}", ScanResult::new());
        assert_eq!(obj.len(), 2);
        assert_eq!(obj.get("a"), Some(b"1".as_ref()));
        assert_eq!(obj.get("b"), Some(b"2".as_ref()));
    }

    #[test]
    fn test_lazy_object_empty() {
        let obj = LazyObject::from_scan(b"{}", ScanResult::new());
        assert_eq!(obj.len(), 0);
        assert!(obj.is_empty());
    }

    #[test]
    fn test_lazy_object_string_value() {
        let raw = b"{\"name\": \"alice\"}";
        let obj = LazyObject::from_scan(raw, ScanResult::new());
        assert_eq!(obj.len(), 1);
        assert_eq!(obj.get("name"), Some(b"\"alice\"".as_ref()));
    }

    #[test]
    fn test_lazy_object_nested_value() {
        let raw = b"{\"arr\": [1, 2], \"n\": 42}";
        let obj = LazyObject::from_scan(raw, ScanResult::new());
        assert_eq!(obj.len(), 2);
        assert_eq!(obj.get("arr"), Some(b"[1, 2]".as_ref()));
        assert_eq!(obj.get("n"), Some(b"42".as_ref()));
    }

    #[test]
    fn test_number_detection() {
        let raw = b"[1.0, 2.5, 3.14]";
        let scan_result = ScanResult::new();
        let array = LazyArray::from_scan(raw, scan_result);

        assert!(array.looks_like_number(b"123.45"));
        assert!(!array.looks_like_number(b"\"string\""));
    }
}