grippo 0.1.2

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
// Project:   grippo
// File:      src/parse/frame/json.rs
// Purpose:   JSON values found by their brackets and quotes, and the records at a pointer
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! Where a JSON value ends, found by its brackets and quotes with no parse,
//! and the records at an RFC 6901 pointer in one document.
//!
//! Structure only: `[1,nul]` frames as two records, and the parser that runs
//! next refuses the second. Bracket pairs aren't matched by type.

use std::fmt;
use std::ops::Range;
use std::str::FromStr;

use memchr::{memchr2, memchr3};
use serde::{Deserialize, Serialize};

use super::Frame;
use crate::parse::ParseError;

/// The byte RFC 7464 puts before each text of a sequence.
pub(super) const RS: u8 = 0x1e;

/// Bytes a scan inside a container stops at.
const STRUCTURAL: [bool; 256] = {
    let mut table = [false; 256];
    table[b'"' as usize] = true;
    table[b'{' as usize] = true;
    table[b'[' as usize] = true;
    table[b'}' as usize] = true;
    table[b']' as usize] = true;
    table[RS as usize] = true;
    table
};

/// An RFC 6901 JSON Pointer, such as `/data/items`. Each `/` steps into an
/// object's member by name or an array's element by position, `~1` reads as
/// `/` and `~0` as `~`, and `""`, the default, names the whole document.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(try_from = "String", into = "String")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[cfg_attr(feature = "schemars", schemars(with = "String"))]
pub struct JsonPointer {
    text: String,
    tokens: Vec<String>,
}

/// Why text isn't a JSON Pointer.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum PointerError {
    /// It's neither empty nor starts with `/`.
    #[error("a JSON pointer is empty or starts with `/`: {0:?}")]
    NoSlash(String),
    /// A `~` not followed by `0` or `1`.
    #[error("a `~` at byte {at} of a JSON pointer is followed by neither `0` nor `1`")]
    Tilde {
        /// Its byte offset in the pointer.
        at: usize,
    },
}

impl JsonPointer {
    /// The pointer as written.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.text
    }

    #[cfg(test)]
    pub(super) fn tokens(&self) -> &[String] {
        &self.tokens
    }
}

impl FromStr for JsonPointer {
    type Err = PointerError;

    fn from_str(text: &str) -> Result<Self, PointerError> {
        let mut tokens = Vec::new();
        if !text.is_empty() {
            let Some(rest) = text.strip_prefix('/') else {
                return Err(PointerError::NoSlash(text.to_owned()));
            };
            let mut at = 1;
            for segment in rest.split('/') {
                tokens.push(unescape(segment, at)?);
                at += segment.len() + 1;
            }
        }
        Ok(Self {
            text: text.to_owned(),
            tokens,
        })
    }
}

/// A reference token with `~0` read as `~` and `~1` as `/`. `offset` is
/// where the segment starts in the pointer, for the error.
fn unescape(segment: &str, offset: usize) -> Result<String, PointerError> {
    let mut token = String::with_capacity(segment.len());
    let mut rest = segment;
    while let Some(i) = rest.find('~') {
        token.push_str(&rest[..i]);
        match rest.as_bytes().get(i + 1) {
            Some(b'0') => token.push('~'),
            Some(b'1') => token.push('/'),
            _ => {
                let at = offset + segment.len() - rest.len() + i;
                return Err(PointerError::Tilde { at });
            }
        }
        rest = &rest[i + 2..];
    }
    token.push_str(rest);
    Ok(token)
}

impl TryFrom<String> for JsonPointer {
    type Error = PointerError;

    fn try_from(text: String) -> Result<Self, PointerError> {
        text.parse()
    }
}

impl From<JsonPointer> for String {
    fn from(pointer: JsonPointer) -> Self {
        pointer.text
    }
}

impl fmt::Display for JsonPointer {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.text)
    }
}

/// Settings for [`FramingConfig::JsonPointer`](super::FramingConfig::JsonPointer).
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(default, deny_unknown_fields)]
#[non_exhaustive]
pub struct JsonPointerConfig {
    /// Where the records sit in each document.
    pub pointer: JsonPointer,
}

/// Where a scan stands inside one value, so a value cut across inputs is
/// scanned on from where the last input ended.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) struct Scan {
    depth: u32,
    string: bool,
    escape: bool,
    scalar: bool,
}

/// What a scan came to.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum Step {
    /// The value ends just before this offset.
    End(usize),
    /// The input ended first.
    More,
    /// An RS at this offset cut a sequence text short.
    Cut(usize),
}

impl Scan {
    /// The scan of a value that starts with `first`, or `None` when no
    /// value starts with it.
    pub(super) const fn open(first: u8) -> Option<Self> {
        let mut scan = Self {
            depth: 0,
            string: false,
            escape: false,
            scalar: false,
        };
        match first {
            b'{' | b'[' => scan.depth = 1,
            b'"' => scan.string = true,
            b'-' | b'0'..=b'9' | b't' | b'f' | b'n' => scan.scalar = true,
            _ => return None,
        }
        Some(scan)
    }

    /// Whether the value is a number or a literal, which only the byte
    /// after it ends.
    pub(super) const fn scalar(self) -> bool {
        self.scalar
    }

    /// Scan `buf` from `at` for the value's end. Under `seq` an RS outside a
    /// string's escape cuts the value short.
    pub(super) fn run(&mut self, buf: &[u8], mut at: usize, seq: bool) -> Step {
        loop {
            if self.escape {
                if at >= buf.len() {
                    return Step::More;
                }
                self.escape = false;
                at += 1;
            }
            let rest = buf.get(at..).unwrap_or_default();
            if self.string {
                let hit = if seq {
                    memchr3(b'"', b'\\', RS, rest)
                } else {
                    memchr2(b'"', b'\\', rest)
                };
                let Some(i) = hit else {
                    return Step::More;
                };
                at += i;
                match buf[at] {
                    b'\\' => self.escape = true,
                    b'"' => {
                        self.string = false;
                        if self.depth == 0 {
                            return Step::End(at + 1);
                        }
                    }
                    _ => return Step::Cut(at),
                }
                at += 1;
                continue;
            }
            if self.scalar {
                let Some(i) = rest.iter().position(|&b| !scalar_byte(b)) else {
                    return Step::More;
                };
                self.scalar = false;
                return Step::End(at + i);
            }
            let Some(i) = rest.iter().position(|&b| STRUCTURAL[usize::from(b)]) else {
                return Step::More;
            };
            at += i;
            match buf[at] {
                b'"' => self.string = true,
                b'{' | b'[' => self.depth = self.depth.saturating_add(1),
                b'}' | b']' => {
                    self.depth = self.depth.saturating_sub(1);
                    if self.depth == 0 {
                        return Step::End(at + 1);
                    }
                }
                _ if seq => return Step::Cut(at),
                _ => {}
            }
            at += 1;
        }
    }
}

/// A byte that can go on a number or a literal.
const fn scalar_byte(b: u8) -> bool {
    b.is_ascii_alphanumeric() || matches!(b, b'+' | b'-' | b'.')
}

/// JSON whitespace.
pub(super) const fn space(b: u8) -> bool {
    matches!(b, b' ' | b'\t' | b'\n' | b'\r')
}

/// The offset of the first byte at or after `at` that isn't JSON whitespace.
pub(super) fn skip_space(buf: &[u8], at: usize) -> usize {
    buf.get(at..)
        .and_then(|rest| rest.iter().position(|&b| !space(b)))
        .map_or(buf.len(), |i| at + i)
}

/// The offset past the value that starts at `at`, in a buffer that holds it
/// whole: the end of the buffer ends a number or a literal.
pub(super) fn value_end(buf: &[u8], at: usize) -> Option<usize> {
    let mut scan = Scan::open(*buf.get(at)?)?;
    match scan.run(buf, at + 1, false) {
        Step::End(end) => Some(end),
        Step::More if scan.scalar() => Some(buf.len()),
        Step::More | Step::Cut(_) => None,
    }
}

/// Whether a member's key, quotes included, is `name` once decoded.
pub(super) fn key_is(quoted: &[u8], name: &str) -> bool {
    let inner = quoted
        .get(1..quoted.len().saturating_sub(1))
        .unwrap_or_default();
    if memchr::memchr(b'\\', inner).is_none() {
        return inner == name.as_bytes();
    }
    serde_json::from_slice::<String>(quoted).is_ok_and(|key| key == name)
}

/// The members of the object whose `{` is at `open`: each key's range,
/// quotes included, and its value's range. An item is `Err` where the
/// object isn't well formed, and nothing follows it.
pub(super) const fn members(buf: &[u8], open: usize) -> Entries<'_> {
    Entries {
        buf,
        at: open + 1,
        object: true,
        done: false,
        failed: false,
    }
}

/// The elements of the array whose `[` is at `open`, as [`members`] gives
/// an object's, each with an empty key.
pub(super) const fn elements(buf: &[u8], open: usize) -> Entries<'_> {
    Entries {
        buf,
        at: open + 1,
        object: false,
        done: false,
        failed: false,
    }
}

/// An object's members or an array's elements, from [`members`] or
/// [`elements`].
pub(super) struct Entries<'b> {
    buf: &'b [u8],
    /// Where the next entry starts, and once `done`, the closing bracket.
    at: usize,
    object: bool,
    done: bool,
    failed: bool,
}

/// One entry: its key's range, empty in an array, and its value's range.
type Entry = (Range<usize>, Range<usize>);

impl Iterator for Entries<'_> {
    type Item = Result<Entry, ()>;

    fn next(&mut self) -> Option<Self::Item> {
        let Ok((key, value)) = self.start()? else {
            return Some(Err(()));
        };
        let Some(end) = value_end(self.buf, value) else {
            return Some(self.fail());
        };
        Some(self.after(end).map(|()| (key, value..end)))
    }
}

impl Entries<'_> {
    const fn close(&self) -> u8 {
        if self.object { b'}' } else { b']' }
    }

    const fn fail<T>(&mut self) -> Result<T, ()> {
        self.done = true;
        self.failed = true;
        Err(())
    }

    /// The next entry's key and where its value starts, or `None` at the
    /// closing bracket.
    fn start(&mut self) -> Option<Result<(Range<usize>, usize), ()>> {
        if self.done {
            return None;
        }
        let buf = self.buf;
        let at = skip_space(buf, self.at);
        if buf.get(at) == Some(&self.close()) {
            self.at = at;
            self.done = true;
            return None;
        }
        if !self.object {
            return Some(Ok((at..at, at)));
        }
        let key_end = (buf.get(at) == Some(&b'"'))
            .then(|| value_end(buf, at))
            .flatten();
        let colon = key_end
            .map(|end| skip_space(buf, end))
            .filter(|&colon| buf.get(colon) == Some(&b':'));
        match (key_end, colon) {
            (Some(end), Some(colon)) => Some(Ok((at..end, skip_space(buf, colon + 1)))),
            _ => Some(self.fail()),
        }
    }

    /// Step past the value that ends at `end`, to the next entry or the
    /// closing bracket.
    fn after(&mut self, end: usize) -> Result<(), ()> {
        let next = skip_space(self.buf, end);
        match self.buf.get(next) {
            Some(b',') => self.at = next + 1,
            Some(&b) if b == self.close() => self.at = next,
            _ => return self.fail(),
        }
        Ok(())
    }

    /// The offset past the closing bracket, once the entries left are read.
    fn close_end(&mut self) -> Result<usize, ()> {
        for entry in self.by_ref() {
            entry?;
        }
        if self.failed {
            return Err(());
        }
        Ok(self.at + 1)
    }
}

/// An RFC 6901 reference token read as an array index: `0`, or digits with
/// no leading zero.
fn index(token: &str) -> Option<usize> {
    let digits = !token.is_empty() && token.bytes().all(|b| b.is_ascii_digit());
    if !digits || (token.len() > 1 && token.starts_with('0')) {
        return None;
    }
    token.parse().ok()
}

/// The records at `pointer` in the document `input`: each element of an
/// array, or the value alone. A pointer that reaches nothing, or `null`,
/// gives no records. On an error `out` is as it was.
pub(super) fn at_pointer<'a>(
    pointer: &JsonPointer,
    input: &'a [u8],
    out: &mut Vec<Frame<'a>>,
) -> Result<(), ParseError> {
    let mark = out.len();
    let read = walk(pointer, input, out);
    if read.is_err() {
        out.truncate(mark);
    }
    read
}

/// Step down `pointer` without reading past the value it reaches, frame
/// that value, then read the rest of the document to check it's whole: one
/// pass over the bytes.
fn walk<'a>(
    pointer: &JsonPointer,
    input: &'a [u8],
    out: &mut Vec<Frame<'a>>,
) -> Result<(), ParseError> {
    let broken = |offset| ParseError::Malformed {
        offset,
        reason: "a JSON object or array that isn't well formed",
    };
    let root = skip_space(input, 0);
    let mut parents = Vec::with_capacity(pointer.tokens.len());
    let mut at = root;
    for token in &pointer.tokens {
        let mut entries = match input.get(at) {
            Some(b'{') => members(input, at),
            Some(b'[') => elements(input, at),
            _ => return whole(input, root),
        };
        let want = index(token);
        let mut n = 0;
        let found = loop {
            let Some(entry) = entries.start() else {
                break None;
            };
            let (key, value) = entry.map_err(|()| broken(at))?;
            let hit = if entries.object {
                key_is(&input[key], token)
            } else {
                Some(n) == want
            };
            if hit {
                break Some(value);
            }
            let end = value_end(input, value).ok_or_else(|| broken(value))?;
            entries.after(end).map_err(|()| broken(at))?;
            n += 1;
        };
        let Some(value) = found else {
            return whole(input, root);
        };
        parents.push((at, entries));
        at = value;
    }
    let mut end = if input.get(at) == Some(&b'[') {
        let mut entries = elements(input, at);
        for entry in entries.by_ref() {
            let (_, value) = entry.map_err(|()| broken(at))?;
            out.push(Frame::new(&input[value]));
        }
        entries.close_end().map_err(|()| broken(at))?
    } else {
        let end = value_end(input, at).ok_or_else(|| broken(at))?;
        if &input[at..end] != b"null" {
            out.push(Frame::new(&input[at..end]));
        }
        end
    };
    while let Some((open, mut entries)) = parents.pop() {
        entries.after(end).map_err(|()| broken(open))?;
        end = entries.close_end().map_err(|()| broken(open))?;
    }
    trailing(input, end)
}

/// Check the document at `root` is whole, for a pointer that reached nothing.
fn whole(input: &[u8], root: usize) -> Result<(), ParseError> {
    let end = value_end(input, root).ok_or(ParseError::Malformed {
        offset: root,
        reason: "no whole JSON document",
    })?;
    trailing(input, end)
}

/// Nothing but whitespace after the document, which ends at `end`.
fn trailing(input: &[u8], end: usize) -> Result<(), ParseError> {
    if skip_space(input, end) == input.len() {
        Ok(())
    } else {
        Err(ParseError::Malformed {
            offset: end,
            reason: "text after the JSON document",
        })
    }
}