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
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
// Project:   grippo
// File:      src/path.rs
// Purpose:   One field path grammar for the crate: JSON paths and the names parsers write
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! Field paths, and the field names grippo's parsers write in the same
//! grammar.
//!
//! `a.b.c` steps through three keys. A key holding `.`, `[`, `]` or `"` is
//! written as a JSON string in brackets, `labels["app.kind"]`, so the record
//! `{"a.b":1}` writes the name `["a.b"]` and `{"a":{"b":1}}` writes `a.b`.
//! Every other key is written as it is.
//!
//! ```
//! use grippo::path::Path;
//!
//! assert_eq!(Path::parse(r#"labels["app.kind"]"#)?, Path::from_keys(["labels", "app.kind"])?);
//! assert_ne!(Path::parse(r#"["a.b"]"#)?, Path::parse("a.b")?);
//! # Ok::<(), grippo::path::PathError>(())
//! ```

#[cfg(any(feature = "parse", feature = "scrub", feature = "xml"))]
use std::borrow::Cow;
use std::str::FromStr;

use memchr::{memchr, memchr2};
use thiserror::Error;

/// The most dotted parts a whole-key-first path may have: a path of `n` parts
/// has `2^(n-1)` readings.
pub const MAX_DOTTED_PARTS: usize = 8;

/// One field path.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Path {
    reading: Reading,
}

#[derive(Debug, Clone, PartialEq, Eq)]
enum Reading {
    /// One step per key or index.
    Steps(Vec<Step>),
    /// The text as one key, then each dot as a step, left to right.
    WholeKeyFirst(String),
}

/// One step down a path.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Step {
    /// A key of an object.
    Key(String),
    /// An element of an array, by position.
    Index(usize),
    /// A key of an object or an element of an array, as a JSON Pointer's
    /// numeric segment is read.
    Either(String, usize),
}

/// Why a path can't be built.
#[derive(Debug, Clone, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum PathError {
    /// A path with no keys.
    #[error("a path needs at least one key")]
    Empty,
    /// [`Path::parse`] text that isn't a path.
    #[error("{why} at byte {at}")]
    Syntax {
        /// The byte offset where reading stopped.
        at: usize,
        /// What was expected there.
        why: &'static str,
    },
    /// A whole-key-first path with more than [`MAX_DOTTED_PARTS`] parts.
    #[error("{parts} dotted parts, past the {max} a whole-key-first path takes", max = MAX_DOTTED_PARTS)]
    TooManyParts {
        /// The parts the text has.
        parts: usize,
    },
}

impl Path {
    /// A path in text: `a.b.c` steps through three keys, `["a.b"]` is one key
    /// with a dot in it, written as a JSON string, `a[0]` is the first element
    /// of the array at `a`, and `a["b.c"][2].d` mixes them.
    ///
    /// # Errors
    ///
    /// [`PathError::Empty`] for empty text, [`PathError::Syntax`] for an empty
    /// name, a bracket holding neither one JSON string nor an index, or text
    /// after a `]` that isn't `.` or `[`.
    pub fn parse(text: &str) -> Result<Self, PathError> {
        if text.is_empty() {
            return Err(PathError::Empty);
        }
        let bytes = text.as_bytes();
        let mut keys = Vec::new();
        let mut at = 0;
        let mut after_dot = false;
        loop {
            if bytes.get(at) == Some(&b'[') && !after_dot {
                let (step, next) = if bytes.get(at + 1).is_some_and(u8::is_ascii_digit) {
                    bracketed_index(bytes, at)?
                } else {
                    let (key, next) = quoted(bytes, at)?;
                    (Step::Key(key), next)
                };
                keys.push(step);
                at = next;
            } else {
                let len = bytes[at..]
                    .iter()
                    .position(|&b| b == b'.' || b == b'[')
                    .unwrap_or(bytes.len() - at);
                if len == 0 {
                    return Err(syntax(at, "a key name"));
                }
                keys.push(Step::Key(text[at..at + len].to_owned()));
                at += len;
            }
            after_dot = false;
            match bytes.get(at) {
                None => return Ok(Self::steps(keys)),
                Some(b'.') => {
                    at += 1;
                    after_dot = true;
                }
                Some(b'[') => {}
                Some(_) => return Err(syntax(at, "`.` or `[` after `]`")),
            }
        }
    }

    /// The keys as given, one step each, with no reading of dots or brackets.
    ///
    /// # Errors
    ///
    /// [`PathError::Empty`] when there are no keys.
    pub fn from_keys<I, K>(keys: I) -> Result<Self, PathError>
    where
        I: IntoIterator<Item = K>,
        K: Into<String>,
    {
        let keys: Vec<Step> = keys.into_iter().map(|k| Step::Key(k.into())).collect();
        if keys.is_empty() {
            return Err(PathError::Empty);
        }
        Ok(Self::steps(keys))
    }

    /// A JSON Pointer (RFC 6901): `/data/0/message` steps through `data`, `0`
    /// and `message`, with `~1` read as `/` and `~0` as `~`. A segment that's
    /// an array index, `0` or digits with no leading zero, is read as a key
    /// in an object and a position in an array.
    ///
    /// # Errors
    ///
    /// [`PathError::Empty`] for `""`, which names the whole record, and
    /// [`PathError::Syntax`] for text that doesn't start with `/` or a `~`
    /// not followed by `0` or `1`.
    pub fn from_pointer(text: &str) -> Result<Self, PathError> {
        let Some(rest) = text.strip_prefix('/') else {
            return Err(if text.is_empty() {
                PathError::Empty
            } else {
                syntax(0, "`/` to start a pointer")
            });
        };
        let mut at = 1;
        let mut steps = Vec::new();
        for segment in rest.split('/') {
            let mut key = String::with_capacity(segment.len());
            let mut chars = segment.char_indices();
            while let Some((i, c)) = chars.next() {
                if c == '~' {
                    match chars.next() {
                        Some((_, '0')) => key.push('~'),
                        Some((_, '1')) => key.push('/'),
                        _ => return Err(syntax(at + i, "`~0` or `~1`")),
                    }
                } else {
                    key.push(c);
                }
            }
            at += segment.len() + 1;
            let is_index = !key.is_empty()
                && key.bytes().all(|b| b.is_ascii_digit())
                && (key == "0" || !key.starts_with('0'));
            let index = if is_index {
                key.parse::<usize>().ok()
            } else {
                None
            };
            steps.push(match index {
                Some(i) => Step::Either(key, i),
                None => Step::Key(key),
            });
        }
        Ok(Self::steps(steps))
    }

    /// Dotted text read whole key first: `a.b.c` is tried as the one key
    /// `a.b.c`, then with each dot from the left as a step, the rest read the
    /// same way inside that key's object. The first reading that finds a value
    /// wins, so `a`, `b.c` comes before `a`, `b`, `c`, which comes before
    /// `a.b`, `c`. That reads literal dotted keys at any depth.
    ///
    /// # Errors
    ///
    /// [`PathError::TooManyParts`] past [`MAX_DOTTED_PARTS`] parts.
    pub fn whole_key_first(text: &str) -> Result<Self, PathError> {
        let parts = text.split('.').count();
        if parts > MAX_DOTTED_PARTS {
            return Err(PathError::TooManyParts { parts });
        }
        Ok(Self {
            reading: Reading::WholeKeyFirst(text.to_owned()),
        })
    }

    pub(crate) const fn steps(steps: Vec<Step>) -> Self {
        Self {
            reading: Reading::Steps(steps),
        }
    }

    /// Each step list this path is read as, in the order tried, and the one
    /// whose miss is reported when none finds a value.
    #[cfg(feature = "json-paths")]
    pub(crate) fn readings(&self) -> (Vec<Vec<Step>>, usize) {
        match &self.reading {
            Reading::Steps(steps) => (vec![steps.clone()], 0),
            Reading::WholeKeyFirst(text) => {
                let parts: Vec<&str> = text.split('.').collect();
                let readings: Vec<Vec<Step>> = groupings(&parts)
                    .into_iter()
                    .map(|keys| keys.into_iter().map(Step::Key).collect())
                    .collect();
                let plain = readings
                    .iter()
                    .position(|keys| keys.len() == parts.len())
                    .unwrap_or(0);
                (readings, plain)
            }
        }
    }
}

/// The `[N]` at `at`, and the offset just past its `]`.
fn bracketed_index(bytes: &[u8], at: usize) -> Result<(Step, usize), PathError> {
    let digits = bytes[at + 1..]
        .iter()
        .take_while(|b| b.is_ascii_digit())
        .count();
    let text = &bytes[at + 1..at + 1 + digits];
    if text.len() > 1 && text[0] == b'0' {
        return Err(syntax(at + 1, "an index with no leading zero"));
    }
    let index = std::str::from_utf8(text)
        .ok()
        .and_then(|t| t.parse::<usize>().ok())
        .ok_or_else(|| syntax(at + 1, "an index that fits a usize"))?;
    if bytes.get(at + 1 + digits) != Some(&b']') {
        return Err(syntax(at + 1 + digits, "`]` after the index"));
    }
    Ok((Step::Index(index), at + 2 + digits))
}

impl FromStr for Path {
    type Err = PathError;

    fn from_str(text: &str) -> Result<Self, PathError> {
        Self::parse(text)
    }
}

const fn syntax(at: usize, why: &'static str) -> PathError {
    PathError::Syntax { at, why }
}

/// The key in the `["..."]` at `at`, and the offset just past its `]`.
fn quoted(bytes: &[u8], at: usize) -> Result<(String, usize), PathError> {
    if bytes.get(at + 1) != Some(&b'"') {
        return Err(syntax(at + 1, "a JSON string after `[`"));
    }
    let (end, _) = string_end(bytes, at + 2).map_err(|_| syntax(at + 1, "a closing quote"))?;
    let mut key = Vec::new();
    unescape(&bytes[at + 2..end], |part| key.extend_from_slice(part))
        .map_err(|_| syntax(at + 1, "a JSON string"))?;
    let key = String::from_utf8(key).map_err(|_| syntax(at + 1, "a JSON string"))?;
    if bytes.get(end + 1) != Some(&b']') {
        return Err(syntax(end + 1, "`]` after the key"));
    }
    Ok((key, end + 2))
}

/// Every grouping of `parts` into dotted keys, in the whole-key-first order.
#[cfg(feature = "json-paths")]
fn groupings(parts: &[&str]) -> Vec<Vec<String>> {
    let mut out = vec![vec![parts.join(".")]];
    for cut in 1..parts.len() {
        let head = parts[..cut].join(".");
        for rest in groupings(&parts[cut..]) {
            let mut keys = Vec::with_capacity(rest.len() + 1);
            keys.push(head.clone());
            keys.extend(rest);
            out.push(keys);
        }
    }
    out
}

/// Whether `key` is written quoted in a field name.
#[cfg(feature = "parse")]
#[inline]
pub(crate) fn needs_quotes(key: &str) -> bool {
    key.bytes().any(|b| matches!(b, b'.' | b'[' | b']' | b'"'))
}

/// `key` as one part of a field name: as it is, or `["..."]` when it holds
/// `.`, `[`, `]` or `"`.
#[cfg(any(
    feature = "parse-ndjson",
    feature = "parse-xml",
    feature = "parse-kv",
    feature = "parse-csv",
    feature = "parse-cef",
    feature = "parse-leef",
    feature = "parse-w3c",
    feature = "parse-syslog",
))]
pub(crate) fn key_part(key: Cow<'_, str>) -> Cow<'_, str> {
    if needs_quotes(&key) {
        let mut part = String::with_capacity(key.len() + 4);
        push_quoted(&mut part, &key);
        Cow::Owned(part)
    } else {
        key
    }
}

/// Appends `key` to the field name `name`: after a `.`, or quoted.
#[cfg(feature = "parse")]
pub(crate) fn push_key(name: &mut String, key: &str) {
    if needs_quotes(key) {
        push_quoted(name, key);
    } else {
        if !name.is_empty() {
            name.push('.');
        }
        name.push_str(key);
    }
}

/// Appends `["key"]`, the key escaped as a JSON string.
#[cfg(feature = "parse")]
fn push_quoted(out: &mut String, key: &str) {
    out.push_str("[\"");
    for c in key.chars() {
        match c {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            c if u32::from(c) < 0x20 => {
                out.push_str("\\u00");
                let code = u32::from(c);
                for digit in [code >> 4, code & 0xF] {
                    out.push(char::from_digit(digit, 16).unwrap_or('0'));
                }
            }
            c => out.push(c),
        }
    }
    out.push_str("\"]");
}

/// The name with every quoted key that needs no quotes written plain, so two
/// spellings of one name compare equal. Text with no `["` is returned as it is.
#[cfg(feature = "parse")]
pub(crate) fn canonical(name: &str) -> Cow<'_, str> {
    if !name.contains("[\"") {
        return Cow::Borrowed(name);
    }
    let mut out = String::with_capacity(name.len());
    for key in keys(name) {
        push_key(&mut out, &key);
    }
    Cow::Owned(out)
}

/// The key a quoted part at the start of `text` spells, and its length, when
/// `text` opens with a whole `["..."]` followed by its end, `.` or `[`.
#[cfg(any(feature = "parse", feature = "scrub", feature = "xml"))]
fn quoted_part(text: &str) -> Option<(String, usize)> {
    if !text.starts_with("[\"") {
        return None;
    }
    let (key, end) = quoted(text.as_bytes(), 0).ok()?;
    matches!(text.as_bytes().get(end), None | Some(b'.' | b'[')).then_some((key, end))
}

/// The first key of a field name, decoded, and what follows it: nothing, or
/// text from a `.` or a quoted part. A name is read leniently: a `[` that
/// opens no quoted part is part of its key, as a parser that doesn't quote
/// writes it.
#[cfg(any(feature = "parse", feature = "scrub", feature = "xml"))]
pub(crate) fn first_key(name: &str) -> (Cow<'_, str>, &str) {
    if let Some((key, end)) = quoted_part(name) {
        return (Cow::Owned(key), &name[end..]);
    }
    let bytes = name.as_bytes();
    let mut at = usize::from(name.starts_with('['));
    let end = loop {
        let Some(i) = bytes.get(at..).and_then(|rest| memchr2(b'.', b'[', rest)) else {
            break bytes.len();
        };
        let j = at + i;
        if bytes[j] == b'.' || quoted_part(&name[j..]).is_some() {
            break j;
        }
        at = j + 1;
    };
    (Cow::Borrowed(&name[..end]), &name[end..])
}

/// The text after a key's separator, `None` when the name ends there.
#[cfg(any(feature = "parse", feature = "scrub", feature = "xml"))]
pub(crate) fn after_key(rest: &str) -> Option<&str> {
    if rest.is_empty() {
        None
    } else {
        Some(rest.strip_prefix('.').unwrap_or(rest))
    }
}

/// Whether `rest`, what follows a name's prefix, starts a key below it: the
/// text after its `.`, or the quoted part it opens with.
#[cfg(feature = "parse")]
pub(crate) fn below(rest: &str) -> Option<&str> {
    rest.strip_prefix('.')
        .or_else(|| quoted_part(rest).map(|_| rest))
}

/// Every key of a field name, decoded, as [`first_key`] reads them. A name
/// with no quoted part splits at every `.`.
#[cfg(any(feature = "parse", feature = "scrub", feature = "xml"))]
pub(crate) fn keys(name: &str) -> impl Iterator<Item = Cow<'_, str>> {
    let mut rest = Some(name);
    std::iter::from_fn(move || {
        let (key, after) = first_key(rest?);
        rest = after_key(after);
        Some(key)
    })
}

/// The record ends, or holds something that isn't JSON, where a read needs more.
#[derive(Debug)]
pub(crate) struct Malformed;

/// The offset of the quote closing the string whose contents start at `from`,
/// and whether the string holds a backslash.
#[inline]
pub(crate) fn string_end(json: &[u8], from: usize) -> Result<(usize, bool), Malformed> {
    let mut at = from;
    let mut escaped = false;
    loop {
        let rest = json.get(at..).ok_or(Malformed)?;
        let i = memchr2(b'"', b'\\', rest).ok_or(Malformed)?;
        if rest[i] == b'"' {
            return Ok((at + i, escaped));
        }
        escaped = true;
        at += i + 2;
    }
}

/// Decodes a JSON string's contents, between its quotes, handing each piece
/// to `out`. A raw control character, a bad escape or a lone surrogate is
/// malformed.
pub(crate) fn unescape(mut raw: &[u8], mut out: impl FnMut(&[u8])) -> Result<(), Malformed> {
    loop {
        let run = memchr(b'\\', raw).unwrap_or(raw.len());
        let (text, rest) = raw.split_at(run);
        if text.iter().any(|&b| b < 0x20) {
            return Err(Malformed);
        }
        out(text);
        let Some((_, rest)) = rest.split_first() else {
            return Ok(());
        };
        let (&escape, rest) = rest.split_first().ok_or(Malformed)?;
        raw = rest;
        let byte = match escape {
            b'"' => b'"',
            b'\\' => b'\\',
            b'/' => b'/',
            b'b' => 0x08,
            b'f' => 0x0c,
            b'n' => b'\n',
            b'r' => b'\r',
            b't' => b'\t',
            b'u' => {
                let (c, rest) = code_point(raw)?;
                raw = rest;
                out(c.encode_utf8(&mut [0; 4]).as_bytes());
                continue;
            }
            _ => return Err(Malformed),
        };
        out(&[byte]);
    }
}

/// The character a `\u` escape spells, from its first hex digit, and what
/// follows it. A high surrogate takes the `\u` low surrogate after it.
fn code_point(raw: &[u8]) -> Result<(char, &[u8]), Malformed> {
    let high = hex4(raw)?;
    let mut rest = &raw[4..];
    let code = match high {
        0xD800..=0xDBFF => {
            let low = hex4(rest.strip_prefix(b"\\u").ok_or(Malformed)?)?;
            if !(0xDC00..=0xDFFF).contains(&low) {
                return Err(Malformed);
            }
            rest = &rest[6..];
            0x1_0000 + ((high - 0xD800) << 10) + (low - 0xDC00)
        }
        0xDC00..=0xDFFF => return Err(Malformed),
        code => code,
    };
    Ok((char::from_u32(code).ok_or(Malformed)?, rest))
}

/// Four hex digits at the start of `raw`.
fn hex4(raw: &[u8]) -> Result<u32, Malformed> {
    raw.get(..4)
        .ok_or(Malformed)?
        .iter()
        .try_fold(0, |code, &b| {
            let digit = char::from(b).to_digit(16).ok_or(Malformed)?;
            Ok((code << 4) | digit)
        })
}

#[cfg(all(test, feature = "parse"))]
mod tests;