grippo 0.1.1

Parse, match and scrub data at scale.
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
582
583
584
585
586
587
588
// Project:   grippo
// File:      src/record/json.rs
// Purpose:   Raw JSON bytes as a record, read lazily with no value tree
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! A JSON object's bytes as a [`Record`]. On x86-64 and aarch64 each read is
//! a sonic-rs lookup on the bytes, with UTF-8 checked only up to the value
//! read. sonic-rs builds nowhere else, so there each object on a path is read
//! with `serde_json`, and a fault anywhere in that object is `Malformed`.
//! A walk reads the whole record in two passes of its own on every target:
//! one checks it and finds where each container ends, one visits.

use std::borrow::Cow;
use std::ops::Range;

use super::{Kind, Miss, Node, Record, Typed, Walk, number};

/// Raw JSON bytes, read as a record. A record with duplicate keys is outside
/// what's defined.
#[derive(Debug, Clone, Copy)]
pub struct Json<'a> {
    bytes: &'a [u8],
}

impl<'a> Json<'a> {
    /// The record in `bytes`.
    #[must_use]
    pub const fn new(bytes: &'a [u8]) -> Self {
        Self { bytes }
    }
}

impl<'a> Record<'a> for Json<'a> {
    /// The value's JSON text.
    type At = &'a str;

    fn find<K: AsRef<str>>(self, path: &[K]) -> Result<&'a str, Miss> {
        let Some((first, rest)) = path.split_first() else {
            return Err(Miss::MissingRoot);
        };
        if let Some(raw) = backend::lookup(self.bytes, path) {
            return Ok(raw);
        }
        walk(root(self.bytes, first.as_ref())?, rest)
    }

    fn find_below<K: AsRef<str>>(self, at: &'a str, path: &[K]) -> Result<&'a str, Miss> {
        below(at, path)
    }

    fn typed(self, at: &'a str) -> Result<Typed<'a>, Miss> {
        typed(at)
    }

    fn text(self, at: &'a str) -> Result<Cow<'a, str>, Miss> {
        text(at)
    }
}

impl<'a> Walk<'a> for Json<'a> {
    fn walk<F: FnMut(Node<'a, &'a str>)>(self, mut visit: F) -> Result<(), Miss> {
        let text = std::str::from_utf8(self.bytes).map_err(|_| Miss::Malformed)?;
        let object = text.as_bytes().get(space(text.as_bytes(), 0)) == Some(&b'{');
        values(text, |level, key, kind, at| {
            // An object root is the record itself, so its members are at depth 0.
            let depth = if object {
                level.checked_sub(1)
            } else {
                Some(level)
            };
            if let Some(depth) = depth {
                visit(Node {
                    depth,
                    key,
                    kind,
                    at,
                });
            }
        })
    }
}

impl<'a> Json<'a> {
    /// Writes the record to `out` with each value in `strings` replaced by a
    /// JSON string of the bytes given for it, invalid UTF-8 as U+FFFD.
    ///
    /// Each value is an `At` from this record, in document order, none
    /// inside another, as [`Walk::walk`] gives them.
    ///
    /// # Errors
    ///
    /// [`Miss::Malformed`] when an `At` isn't from this record or comes
    /// before the end of the last one, with `out` left as it was.
    pub fn splice_strings<B: AsRef<[u8]>>(
        self,
        strings: &[(&'a str, B)],
        out: &mut Vec<u8>,
    ) -> Result<(), Miss> {
        let mark = out.len();
        let mut copied = 0;
        for (at, value) in strings {
            let Some(span) = span_in(self.bytes, at).filter(|s| s.start >= copied) else {
                out.truncate(mark);
                return Err(Miss::Malformed);
            };
            out.extend_from_slice(&self.bytes[copied..span.start]);
            push_string(out, value.as_ref());
            copied = span.end;
        }
        out.extend_from_slice(&self.bytes[copied..]);
        Ok(())
    }
}

/// Where `at` sits in `bytes`, `None` when it isn't inside them.
pub(super) fn span_in(bytes: &[u8], at: &str) -> Option<Range<usize>> {
    let start = at.as_ptr().addr().checked_sub(bytes.as_ptr().addr())?;
    let end = start.checked_add(at.len())?;
    (end <= bytes.len()).then_some(start..end)
}

/// Appends `value` as a JSON string, invalid UTF-8 as U+FFFD.
pub(super) fn push_string(out: &mut Vec<u8>, value: &[u8]) {
    // Writing to a Vec can't fail.
    let _ = serde_json::to_writer(&mut *out, &*String::from_utf8_lossy(value));
}

/// JSON whitespace from `at` on, skipped.
fn space(bytes: &[u8], mut at: usize) -> usize {
    while matches!(bytes.get(at), Some(b' ' | b'\t' | b'\n' | b'\r')) {
        at += 1;
    }
    at
}

/// Calls `visit` with each value in the JSON text `text`: its nesting level,
/// 0 for the root, its key in an object, its kind and its raw text, in
/// document order. The whole text is checked before the first call.
pub(super) fn values<'a>(
    text: &'a str,
    mut visit: impl FnMut(usize, Option<Cow<'a, str>>, Kind, &'a str),
) -> Result<(), Miss> {
    let mut ends = Vec::new();
    scan(text, &mut ends, false, &mut visit)?;
    scan(text, &mut ends, true, &mut visit)
}

/// One pass over `text`. The first, with `emit` off, checks the grammar and
/// records where each container ends, in the order they open. The second
/// calls `visit`, a container's raw text known when it opens.
fn scan<'a, F: FnMut(usize, Option<Cow<'a, str>>, Kind, &'a str)>(
    text: &'a str,
    ends: &mut Vec<usize>,
    emit: bool,
    visit: &mut F,
) -> Result<(), Miss> {
    let b = text.as_bytes();
    // Each open container: whether it is an object, and its slot in `ends`.
    let mut open: Vec<(bool, usize)> = Vec::new();
    let mut opened = 0;
    let mut key: Option<Cow<'a, str>> = None;
    let mut at = space(b, 0);
    loop {
        let start = at;
        let kind = match b.get(at) {
            Some(b'{') => Kind::Map,
            Some(b'[') => Kind::List,
            Some(b'"') => Kind::Str,
            Some(b't' | b'f') => Kind::Bool,
            Some(b'n') => Kind::Null,
            Some(b'-' | b'0'..=b'9') => Kind::Number,
            _ => return Err(Miss::Malformed),
        };
        if let Kind::Map | Kind::List = kind {
            let slot = opened;
            opened += 1;
            if emit {
                let end = *ends.get(slot).ok_or(Miss::Malformed)?;
                visit(
                    open.len(),
                    key.take(),
                    kind,
                    text.get(start..end).ok_or(Miss::Malformed)?,
                );
            } else {
                ends.push(0);
            }
            let object = kind == Kind::Map;
            open.push((object, slot));
            at = space(b, at + 1);
            let close = if object { b'}' } else { b']' };
            if b.get(at) != Some(&close) {
                if object {
                    key = Some(member_key(text, &mut at, emit)?);
                }
                continue;
            }
        } else {
            let end = match kind {
                Kind::Str => string_end(b, at)?,
                Kind::Number => number_end(b, at)?,
                _ => {
                    let word: &[u8] = match b[at] {
                        b't' => b"true",
                        b'f' => b"false",
                        _ => b"null",
                    };
                    if !b[at..].starts_with(word) {
                        return Err(Miss::Malformed);
                    }
                    at + word.len()
                }
            };
            let raw = &text[start..end];
            if emit {
                visit(open.len(), key.take(), kind, raw);
            } else if kind == Kind::Str && memchr::memchr(b'\\', raw.as_bytes()).is_some() {
                string(raw)?;
            }
            at = space(b, end);
        }
        // After a value: a comma before the next, or the closes that follow.
        loop {
            let Some(&(object, slot)) = open.last() else {
                return if at == b.len() {
                    Ok(())
                } else {
                    Err(Miss::Malformed)
                };
            };
            match b.get(at) {
                Some(b',') => {
                    at = space(b, at + 1);
                    if object {
                        key = Some(member_key(text, &mut at, emit)?);
                    }
                    break;
                }
                Some(b'}') if object => {}
                Some(b']') if !object => {}
                _ => return Err(Miss::Malformed),
            }
            if !emit {
                ends[slot] = at + 1;
            }
            open.pop();
            at = space(b, at + 1);
        }
    }
}

/// The member key at `at`, decoded when `emit` is on and checked either way,
/// with `at` moved past its colon.
fn member_key<'a>(text: &'a str, at: &mut usize, emit: bool) -> Result<Cow<'a, str>, Miss> {
    let b = text.as_bytes();
    if b.get(*at) != Some(&b'"') {
        return Err(Miss::Malformed);
    }
    let end = string_end(b, *at)?;
    let raw = &text[*at..end];
    let key = if emit || memchr::memchr(b'\\', raw.as_bytes()).is_some() {
        string(raw)?
    } else {
        Cow::Borrowed("")
    };
    *at = space(b, end);
    if b.get(*at) != Some(&b':') {
        return Err(Miss::Malformed);
    }
    *at = space(b, *at + 1);
    Ok(key)
}

/// The end of the JSON string opening at `at`, its escapes checked.
fn string_end(b: &[u8], at: usize) -> Result<usize, Miss> {
    let mut i = at + 1;
    loop {
        match b.get(i) {
            Some(b'"') => return Ok(i + 1),
            Some(b'\\') => {
                i += match b.get(i + 1) {
                    Some(b'"' | b'\\' | b'/' | b'b' | b'f' | b'n' | b'r' | b't') => 2,
                    Some(b'u')
                        if b.get(i + 2..i + 6)
                            .is_some_and(|h| h.iter().all(u8::is_ascii_hexdigit)) =>
                    {
                        6
                    }
                    _ => return Err(Miss::Malformed),
                };
            }
            Some(0x00..=0x1f) | None => return Err(Miss::Malformed),
            Some(_) => i += 1,
        }
    }
}

/// The end of the JSON number starting at `at`, held to JSON's grammar.
fn number_end(b: &[u8], at: usize) -> Result<usize, Miss> {
    let digits = |mut i: usize| {
        while b.get(i).is_some_and(u8::is_ascii_digit) {
            i += 1;
        }
        i
    };
    let mut i = at + usize::from(b.get(at) == Some(&b'-'));
    i = match b.get(i) {
        Some(b'0') => i + 1,
        Some(b'1'..=b'9') => digits(i + 1),
        _ => return Err(Miss::Malformed),
    };
    if b.get(i) == Some(&b'.') {
        let after = digits(i + 1);
        if after == i + 1 {
            return Err(Miss::Malformed);
        }
        i = after;
    }
    if matches!(b.get(i), Some(b'e' | b'E')) {
        i += 1 + usize::from(matches!(b.get(i + 1), Some(b'+' | b'-')));
        let after = digits(i);
        if after == i {
            return Err(Miss::Malformed);
        }
        i = after;
    }
    Ok(i)
}

/// Whether raw JSON text is an object.
fn is_object(raw: &str) -> bool {
    raw.as_bytes().first() == Some(&b'{')
}

/// The raw text of the root field `key` in the record `json`. A record that
/// isn't a JSON object has no root fields.
fn root<'a>(json: &'a [u8], key: &str) -> Result<&'a str, Miss> {
    let start = json.iter().position(|b| !b.is_ascii_whitespace());
    if start.map(|i| json[i]) != Some(b'{') {
        return Err(Miss::MissingRoot);
    }
    backend::root(json, key)?.ok_or(Miss::MissingRoot)
}

/// The raw text at `path` below the JSON value `obj`, one lookup when it's
/// there.
pub(super) fn below<'a, K: AsRef<str>>(obj: &'a str, path: &[K]) -> Result<&'a str, Miss> {
    if path.is_empty() {
        return Ok(obj);
    }
    if !is_object(obj) {
        return Err(Miss::WrongParentType);
    }
    if let Some(raw) = backend::lookup_str(obj, path) {
        return Ok(raw);
    }
    walk(obj, path)
}

/// Each key of `path` read in turn from `at`, naming the first miss.
fn walk<'a, K: AsRef<str>>(mut at: &'a str, path: &[K]) -> Result<&'a str, Miss> {
    for key in path {
        if !is_object(at) {
            return Err(Miss::WrongParentType);
        }
        at = backend::member(at, key.as_ref())?.ok_or(Miss::MissingField)?;
    }
    Ok(at)
}

/// Types the raw JSON text of a value.
pub(super) fn typed(raw: &str) -> Result<Typed<'_>, Miss> {
    match raw.as_bytes().first() {
        Some(b'"') => string(raw).map(Typed::Str),
        Some(b't') => Ok(Typed::Bool(true)),
        Some(b'f') => Ok(Typed::Bool(false)),
        Some(b'n') => Ok(Typed::Null),
        Some(b'[') => Ok(Typed::List),
        Some(b'{') => Ok(Typed::Map),
        Some(b'-' | b'0'..=b'9') => number(raw),
        _ => Err(Miss::Malformed),
    }
}

/// The raw JSON text of a value as text: a string decoded, anything else as
/// written.
pub(super) fn text(raw: &str) -> Result<Cow<'_, str>, Miss> {
    if raw.as_bytes().first() == Some(&b'"') {
        string(raw)
    } else {
        Ok(Cow::Borrowed(raw))
    }
}

/// A JSON string's text decoded, borrowed when it holds no escape.
fn string(raw: &str) -> Result<Cow<'_, str>, Miss> {
    let inner = raw
        .get(1..raw.len().saturating_sub(1))
        .ok_or(Miss::Malformed)?;
    if memchr::memchr(b'\\', inner.as_bytes()).is_none() {
        Ok(Cow::Borrowed(inner))
    } else {
        backend::decode(raw).map(Cow::Owned)
    }
}

/// A JSON object's keys, decoded, in document order where sonic-rs builds
/// and in key order elsewhere.
#[cfg(feature = "expr")]
pub(super) fn object_keys(obj: &str) -> Result<Vec<String>, Miss> {
    backend::object_keys(obj)
}

#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]
use simd as backend;

#[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))]
use portable as backend;

/// The reads on sonic-rs, which builds only for x86-64 and aarch64.
#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]
mod simd {
    use std::borrow::Cow;

    use super::Miss;

    /// The raw text at `path` in `json`, when one lookup finds it in place.
    pub(super) fn lookup<'a, K: AsRef<str>>(json: &'a [u8], path: &[K]) -> Option<&'a str> {
        sonic_rs::get_from_slice(json, path.iter().map(AsRef::as_ref))
            .ok()
            .and_then(|v| borrowed(&v))
    }

    /// As [`lookup`] on text, with no UTF-8 check.
    pub(super) fn lookup_str<'a, K: AsRef<str>>(obj: &'a str, path: &[K]) -> Option<&'a str> {
        sonic_rs::get_from_str(obj, path.iter().map(AsRef::as_ref))
            .ok()
            .and_then(|v| borrowed(&v))
    }

    /// The value's raw text, when sonic-rs could hand it back in place.
    fn borrowed<'a>(v: &sonic_rs::LazyValue<'a>) -> Option<&'a str> {
        match v.as_raw_cow() {
            Cow::Borrowed(raw) => Some(raw),
            Cow::Owned(_) => None,
        }
    }

    /// The raw text of the root field `key`, `None` when it's absent.
    pub(super) fn root<'a>(json: &'a [u8], key: &str) -> Result<Option<&'a str>, Miss> {
        found(sonic_rs::get_from_slice(json, [key]))
    }

    /// The raw text of the value at `key` in the object `obj`.
    pub(super) fn member<'a>(obj: &'a str, key: &str) -> Result<Option<&'a str>, Miss> {
        found(sonic_rs::get_from_str(obj, [key]))
    }

    fn found(got: sonic_rs::Result<sonic_rs::LazyValue<'_>>) -> Result<Option<&str>, Miss> {
        match got {
            Ok(v) => match v.as_raw_cow() {
                Cow::Borrowed(raw) => Ok(Some(raw)),
                Cow::Owned(_) => Err(Miss::Malformed),
            },
            Err(e) if e.is_not_found() => Ok(None),
            Err(_) => Err(Miss::Malformed),
        }
    }

    /// A JSON string with an escape, decoded.
    pub(super) fn decode(raw: &str) -> Result<String, Miss> {
        sonic_rs::from_str(raw).map_err(|_| Miss::Malformed)
    }

    #[cfg(any(test, feature = "expr"))]
    pub(super) fn object_keys(obj: &str) -> Result<Vec<String>, Miss> {
        sonic_rs::to_object_iter(obj)
            .map(|pair| {
                pair.map(|(key, _)| key.into_owned())
                    .map_err(|_| Miss::Malformed)
            })
            .collect()
    }
}

/// The reads on `serde_json`, for every target sonic-rs doesn't build on.
#[cfg(any(test, not(any(target_arch = "x86_64", target_arch = "aarch64"))))]
mod portable {
    use std::borrow::Cow;
    use std::collections::BTreeMap;

    use serde_json::value::RawValue;

    use super::Miss;

    /// Members by key, each value's raw text borrowed.
    type Members<'a> = BTreeMap<Cow<'a, str>, &'a RawValue>;

    /// No single lookup here: the caller reads the path key by key.
    pub(super) const fn lookup<'a, K: AsRef<str>>(_json: &'a [u8], _path: &[K]) -> Option<&'a str> {
        None
    }

    /// No single lookup here: the caller reads the path key by key.
    pub(super) const fn lookup_str<'a, K: AsRef<str>>(
        _obj: &'a str,
        _path: &[K],
    ) -> Option<&'a str> {
        None
    }

    /// The raw text of the root field `key`, `None` when it's absent.
    pub(super) fn root<'a>(json: &'a [u8], key: &str) -> Result<Option<&'a str>, Miss> {
        member(std::str::from_utf8(json).map_err(|_| Miss::Malformed)?, key)
    }

    /// The raw text of the value at `key` in the object `obj`.
    pub(super) fn member<'a>(obj: &'a str, key: &str) -> Result<Option<&'a str>, Miss> {
        let members: Members<'a> = serde_json::from_str(obj).map_err(|_| Miss::Malformed)?;
        Ok(members.get(key).map(|v| v.get()))
    }

    /// A JSON string with an escape, decoded.
    pub(super) fn decode(raw: &str) -> Result<String, Miss> {
        serde_json::from_str(raw).map_err(|_| Miss::Malformed)
    }

    #[cfg(any(test, feature = "expr"))]
    pub(super) fn object_keys(obj: &str) -> Result<Vec<String>, Miss> {
        let members: Members<'_> = serde_json::from_str(obj).map_err(|_| Miss::Malformed)?;
        Ok(members.into_keys().map(Cow::into_owned).collect())
    }
}

#[cfg(all(test, any(target_arch = "x86_64", target_arch = "aarch64")))]
mod tests {
    use super::{Miss, portable, simd};

    /// The `serde_json` reads give what the sonic-rs reads give, misses included.
    #[test]
    fn the_portable_reads_agree_with_sonic() {
        let objects = [
            r#"{"a":1,"b":{"c":"x"},"d":[1,2],"e":null}"#,
            r#" { "a" : "q\"r" , "b" : true } "#,
            "{}",
            r#"{"a":}"#,
            r#"{"a":1"#,
            "[1]",
        ];
        for obj in objects {
            for key in ["a", "b", "d", "e", "z"] {
                let want = simd::member(obj, key);
                let got = portable::member(obj, key);
                let malformed = Err(Miss::Malformed);
                // sonic-rs reads lazily, so a fault past the key it found is never seen.
                assert!(
                    got == want || got == malformed,
                    "{obj} {key}: {got:?} {want:?}"
                );
                if obj.starts_with('{') {
                    let root = (
                        simd::root(obj.as_bytes(), key),
                        portable::root(obj.as_bytes(), key),
                    );
                    assert!(
                        root.1 == root.0 || root.1 == malformed,
                        "{obj} {key}: {root:?}"
                    );
                }
            }
            if simd::object_keys(obj).is_ok() {
                let mut want = simd::object_keys(obj);
                if let Ok(keys) = want.as_mut() {
                    keys.sort();
                }
                assert_eq!(portable::object_keys(obj), want, "{obj}");
            }
        }
        for raw in [r#""a\nb""#, r#""\u00e9""#, r#""\q""#] {
            assert_eq!(portable::decode(raw), simd::decode(raw), "{raw}");
        }
        assert_eq!(portable::lookup(b"{}", &["a"]), None);
        assert_eq!(portable::lookup_str("{}", &["a"]), None);
    }
}