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
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
// Project:   grippo
// File:      src/record/fields.rs
// Purpose:   The fields a parser chain wrote, read as a nested record by dotted name
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! [`Fields`] as a [`Record`]. A full name splits into keys as
//! [`crate::path`] writes them, so `syslog.host` is the key `host` in the
//! object `syslog`, and `labels["app.kind"]` the key `app.kind` in `labels`.
//! A name written more than once is a list, a name with longer names below it
//! is an object, and a `Hint::Json` value is read as JSON, paths below it
//! included.

use std::borrow::Cow;
#[cfg(feature = "scrub")]
use std::ops::Range;

use crate::parse::{FieldValue, Fields, Hint};
use crate::path::{after_key, below, first_key, keys};

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

/// How deep an object built from dotted names may nest before it's refused
/// as malformed, so the build's recursion stays bounded.
const MAX_NESTING: usize = 64;

/// Where a value sits in [`Fields`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FieldsAt<'a>(Place<'a>);

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Place<'a> {
    /// The field at this position, its name written once.
    One(usize),
    /// A name written more than once, its first position: a list.
    Many(usize),
    /// The names below a prefix: the first `len` bytes of this field's name.
    Object { witness: usize, len: usize },
    /// A value inside the `Hint::Json` field at this position, its JSON text.
    Json(usize, &'a str),
}

type Pairs<'v> = [(String, FieldValue<'v>)];

impl<'a, 'v: 'a> Record<'a> for &'a Fields<'v> {
    type At = FieldsAt<'a>;

    fn find<K: AsRef<str>>(self, path: &[K]) -> Result<FieldsAt<'a>, Miss> {
        locate(self.as_slice(), None, path).map(FieldsAt)
    }

    fn find_below<K: AsRef<str>>(self, at: FieldsAt<'a>, path: &[K]) -> Result<FieldsAt<'a>, Miss> {
        if path.is_empty() {
            return Ok(at);
        }
        let fields = self.as_slice();
        let place = match at.0 {
            Place::One(i) => {
                let value = value(fields, i)?;
                if value.hint != Hint::Json {
                    return Err(Miss::WrongParentType);
                }
                Place::Json(i, json::below(utf8(value)?, path)?)
            }
            Place::Many(_) => return Err(Miss::WrongParentType),
            Place::Object { witness, len } => {
                locate(fields, Some(prefix_of(fields, witness, len)?), path)?
            }
            Place::Json(i, raw) => Place::Json(i, json::below(raw, path)?),
        };
        Ok(FieldsAt(place))
    }

    fn typed(self, at: FieldsAt<'a>) -> Result<Typed<'a>, Miss> {
        match at.0 {
            Place::One(i) => typed(value(self.as_slice(), i)?),
            Place::Many(_) => Ok(Typed::List),
            Place::Object { .. } => Ok(Typed::Map),
            Place::Json(_, raw) => json::typed(raw),
        }
    }

    fn text(self, at: FieldsAt<'a>) -> Result<Cow<'a, str>, Miss> {
        let fields = self.as_slice();
        match at.0 {
            Place::One(i) => {
                let value = value(fields, i)?;
                let raw = utf8(value)?;
                if value.hint == Hint::Json {
                    json::text(raw)
                } else {
                    Ok(Cow::Borrowed(raw))
                }
            }
            Place::Json(_, raw) => json::text(raw),
            place => {
                let mut out = String::new();
                write_json(fields, place, 0, &mut out)?;
                Ok(Cow::Owned(out))
            }
        }
    }
}

impl<'a, 'v: 'a> Walk<'a> for &'a Fields<'v> {
    /// Members come in first-written order. Every field is reached: longer
    /// names below a name that is a path follow it as an object with the same
    /// key, and any field the nesting doesn't reach comes last, whole, at
    /// depth 0.
    /// A `Hint::Json` value that doesn't parse is a string.
    fn walk<F: FnMut(Node<'a, FieldsAt<'a>>)>(self, mut visit: F) -> Result<(), Miss> {
        let fields = self.as_slice();
        if fields
            .iter()
            .any(|(name, _)| keys(name).nth(MAX_NESTING + 1).is_some())
        {
            return Err(Miss::Malformed);
        }
        let mut seen = vec![false; fields.len()];
        members(fields, None, 0, &mut seen, &mut visit)?;
        for (i, (name, _)) in fields.iter().enumerate() {
            if !seen[i] {
                one(
                    fields,
                    i,
                    0,
                    Some(Cow::Borrowed(name)),
                    &mut seen,
                    &mut visit,
                )?;
            }
        }
        Ok(())
    }

    /// A field's bytes as they are, UTF-8 or not, unless it holds JSON.
    fn bytes(self, at: FieldsAt<'a>) -> Result<Cow<'a, [u8]>, Miss> {
        if let Place::One(i) = at.0 {
            let value = value(self.as_slice(), i)?;
            let parsed = value.hint == Hint::Json
                && utf8(value).is_ok_and(|text| json::values(text, |_, _, _, _| {}).is_ok());
            if !parsed {
                return Ok(Cow::Borrowed(&value.bytes));
            }
        }
        self.text(at).map(super::text_bytes)
    }
}

/// Visits each member below `prefix`, `None` for the root, once per key.
fn members<'a, F: FnMut(Node<'a, FieldsAt<'a>>)>(
    fields: &'a Pairs<'_>,
    prefix: Option<&'a str>,
    depth: usize,
    seen: &mut [bool],
    visit: &mut F,
) -> Result<(), Miss> {
    for key in member_keys(fields, prefix) {
        let node = |kind, place| Node {
            depth,
            key: Some(key.clone()),
            kind,
            at: FieldsAt(place),
        };
        let exact: &'a str = match locate(fields, prefix, &[&*key])? {
            Place::One(i) => {
                one(fields, i, depth, Some(key.clone()), seen, visit)?;
                &fields[i].0
            }
            Place::Many(first) => {
                let name = &fields[first].0;
                visit(node(Kind::List, Place::Many(first)));
                for (i, (n, _)) in fields.iter().enumerate() {
                    if n == name {
                        one(fields, i, depth + 1, None, seen, visit)?;
                    }
                }
                name
            }
            Place::Object { witness, len } => {
                visit(node(Kind::Map, Place::Object { witness, len }));
                members(
                    fields,
                    Some(prefix_of(fields, witness, len)?),
                    depth + 1,
                    seen,
                    visit,
                )?;
                continue;
            }
            Place::Json(..) => return Err(Miss::Malformed),
        };
        if let Some(witness) = fields
            .iter()
            .position(|(n, _)| under(n, Some(exact)).is_some())
        {
            let len = exact.len();
            visit(node(Kind::Map, Place::Object { witness, len }));
            members(fields, Some(exact), depth + 1, seen, visit)?;
        }
    }
    Ok(())
}

/// The first key of each name below `prefix`, `None` for the root, once
/// each in first-written order.
fn member_keys<'a>(fields: &'a Pairs<'_>, prefix: Option<&str>) -> Vec<Cow<'a, str>> {
    let mut keys: Vec<Cow<'a, str>> = Vec::new();
    for (name, _) in fields {
        if let Some(rest) = under(name, prefix) {
            let (key, _) = first_key(rest);
            if !keys.contains(&key) {
                keys.push(key);
            }
        }
    }
    keys
}

/// Visits the field at `i`, and the values inside it when it holds JSON.
fn one<'a, F: FnMut(Node<'a, FieldsAt<'a>>)>(
    fields: &'a Pairs<'_>,
    i: usize,
    depth: usize,
    key: Option<Cow<'a, str>>,
    seen: &mut [bool],
    visit: &mut F,
) -> Result<(), Miss> {
    if let Some(s) = seen.get_mut(i) {
        *s = true;
    }
    let value = value(fields, i)?;
    if value.hint == Hint::Json
        && let Ok(text) = utf8(value)
    {
        let mut root = Some(key.clone());
        let walked = json::values(text, |level, inner, kind, raw| {
            let key = if level == 0 {
                root.take().flatten()
            } else {
                inner
            };
            visit(Node {
                depth: depth + level,
                key,
                kind,
                at: FieldsAt(Place::Json(i, raw)),
            });
        });
        if walked.is_ok() {
            return Ok(());
        }
    }
    let text = std::str::from_utf8(&value.bytes).ok();
    let kind = match (value.hint, text) {
        (Hint::Int | Hint::Float, Some(t)) if number(t).is_ok() => Kind::Number,
        (Hint::Bool, Some("true" | "false")) => Kind::Bool,
        _ => Kind::Str,
    };
    visit(Node {
        depth,
        key,
        kind,
        at: FieldsAt(Place::One(i)),
    });
    Ok(())
}

/// Where a value sits in [`Fields`], by position, so the fields can be
/// changed while it's held.
#[cfg(feature = "scrub")]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Spot {
    /// One field.
    One(usize),
    /// Every field written under the name at this position.
    Many(usize),
    /// Every field below the first `len` bytes of this field's name.
    Object { witness: usize, len: usize },
    /// A span of a `Hint::Json` field's bytes.
    Inside { field: usize, span: Range<usize> },
}

/// Where `at` sits, by position.
#[cfg(feature = "scrub")]
pub fn spot(fields: &Fields<'_>, at: FieldsAt<'_>) -> Result<Spot, Miss> {
    Ok(match at.0 {
        Place::One(i) => Spot::One(i),
        Place::Many(i) => Spot::Many(i),
        Place::Object { witness, len } => Spot::Object { witness, len },
        Place::Json(field, raw) => {
            let bytes = &value(fields.as_slice(), field)?.bytes;
            let span = json::span_in(bytes, raw).ok_or(Miss::Malformed)?;
            Spot::Inside { field, span }
        }
    })
}

/// Sets each value at a [`Spot`] to a string of the bytes given for it. A
/// list or object becomes one field under its name. Spots come from one walk
/// of these fields, none inside another.
#[cfg(feature = "scrub")]
pub fn write_strings(fields: &mut Fields<'_>, mut edits: Vec<(Spot, Vec<u8>)>) -> Result<(), Miss> {
    edits.sort_by_key(|(spot, _)| match spot {
        Spot::Inside { field, span } => (*field, span.start),
        _ => (usize::MAX, 0),
    });
    let mut gone = vec![false; fields.len()];
    let slice = fields.as_mut_slice();
    let mut k = 0;
    while let Some((Spot::Inside { field, .. }, _)) = edits.get(k) {
        let field = *field;
        let (_, value) = slice.get_mut(field).ok_or(Miss::Malformed)?;
        let mut out = Vec::with_capacity(value.bytes.len());
        let mut copied = 0;
        while let Some((Spot::Inside { field: f, span }, masked)) = edits.get(k)
            && *f == field
        {
            out.extend_from_slice(value.bytes.get(copied..span.start).ok_or(Miss::Malformed)?);
            json::push_string(&mut out, masked);
            copied = span.end;
            k += 1;
        }
        out.extend_from_slice(value.bytes.get(copied..).ok_or(Miss::Malformed)?);
        *value = FieldValue::owned(out, Hint::Json);
    }
    for (spot, masked) in edits.drain(k..) {
        let text = |bytes| FieldValue::owned(bytes, Hint::Text);
        match spot {
            Spot::One(i) => slice.get_mut(i).ok_or(Miss::Malformed)?.1 = text(masked),
            Spot::Many(first) => {
                let name = slice.get(first).ok_or(Miss::Malformed)?.0.clone();
                for (i, (n, _)) in slice.iter().enumerate() {
                    gone[i] |= i != first && *n == name;
                }
                slice[first].1 = text(masked);
            }
            Spot::Object { witness, len } => {
                let prefix = prefix_of(slice, witness, len)?.to_owned();
                let mut members =
                    (0..slice.len()).filter(|&i| under(&slice[i].0, Some(&prefix)).is_some());
                let first = members.next().ok_or(Miss::Malformed)?;
                for i in members {
                    gone[i] = true;
                }
                slice[first] = (prefix, text(masked));
            }
            Spot::Inside { .. } => return Err(Miss::Malformed),
        }
    }
    let mut i = 0;
    fields.retain(|_, _| {
        i += 1;
        !gone[i - 1]
    });
    Ok(())
}

/// How a field's name stands to a path below the same prefix.
enum Relation {
    /// Unrelated.
    None,
    /// The first key matches and nothing more.
    Root,
    /// The name is the path.
    Exact,
    /// The name runs on below the path, which takes this many of its bytes.
    Below(usize),
    /// The name is the path's first this many keys.
    Into(usize),
}

/// How `rest`, a name with the prefix taken off, stands to `path`, key by
/// key: a key holding a dot matches only the quoted key it was written as.
fn relate<K: AsRef<str>>(rest: &str, path: &[K]) -> Relation {
    let mut left = rest;
    for (i, key) in path.iter().enumerate() {
        let (first, after) = first_key(left);
        if first != key.as_ref() {
            return if i == 0 {
                Relation::None
            } else {
                Relation::Root
            };
        }
        let Some(next) = after_key(after) else {
            return if i + 1 == path.len() {
                Relation::Exact
            } else {
                Relation::Into(i + 1)
            };
        };
        if i + 1 == path.len() {
            return Relation::Below(rest.len() - after.len());
        }
        left = next;
    }
    Relation::None
}

/// The name with `prefix` and the `.` after it taken off, or `None` outside
/// it. A quoted key below the prefix follows it with no `.`.
fn under<'n>(name: &'n str, prefix: Option<&str>) -> Option<&'n str> {
    match prefix {
        None => Some(name),
        Some(p) => below(name.strip_prefix(p)?),
    }
}

/// The place `path` names below `prefix`, `None` for the record's root. A
/// name that is the path wins over longer names below it.
fn locate<'a, K: AsRef<str>>(
    fields: &'a Pairs<'_>,
    prefix: Option<&str>,
    path: &[K],
) -> Result<Place<'a>, Miss> {
    if path.is_empty() {
        return Err(Miss::MissingRoot);
    }
    let mut exact: Option<(usize, bool)> = None;
    let mut below: Option<(usize, usize)> = None;
    let mut into: Option<(usize, usize)> = None;
    let mut root = false;
    for (i, (name, _)) in fields.iter().enumerate() {
        let Some(rest) = under(name, prefix) else {
            continue;
        };
        match relate(rest, path) {
            Relation::None => {}
            Relation::Root => root = true,
            Relation::Exact => match &mut exact {
                Some((_, many)) => *many = true,
                None => exact = Some((i, false)),
            },
            Relation::Below(taken) => {
                below.get_or_insert((i, name.len() - rest.len() + taken));
            }
            Relation::Into(keys) => {
                if into.is_none_or(|(_, k)| keys < k) {
                    into = Some((i, keys));
                }
            }
        }
    }
    if let Some((i, many)) = exact {
        return Ok(if many { Place::Many(i) } else { Place::One(i) });
    }
    if let Some((witness, len)) = below {
        return Ok(Place::Object { witness, len });
    }
    if let Some((i, keys)) = into {
        let (name, value) = &fields[i];
        let repeated = fields.iter().filter(|(n, _)| n == name).nth(1).is_some();
        if repeated || value.hint != Hint::Json {
            return Err(Miss::WrongParentType);
        }
        return json::below(utf8(value)?, &path[keys..]).map(|raw| Place::Json(i, raw));
    }
    Err(if prefix.is_none() && !root {
        Miss::MissingRoot
    } else {
        Miss::MissingField
    })
}

/// The value at position `i`. An `At` from another record may point past
/// this one's end.
fn value<'f, 'v>(fields: &'f Pairs<'v>, i: usize) -> Result<&'f FieldValue<'v>, Miss> {
    fields.get(i).map(|(_, v)| v).ok_or(Miss::Malformed)
}

/// The first `len` bytes of the name at position `witness`.
fn prefix_of<'f>(fields: &'f Pairs<'_>, witness: usize, len: usize) -> Result<&'f str, Miss> {
    fields
        .get(witness)
        .and_then(|(name, _)| name.get(..len))
        .ok_or(Miss::Malformed)
}

/// A field's bytes as text.
fn utf8<'a>(value: &'a FieldValue<'_>) -> Result<&'a str, Miss> {
    std::str::from_utf8(&value.bytes).map_err(|_| Miss::Malformed)
}

/// A field's value typed by its hint. A number or bool hint whose text isn't
/// one is a string, as the parser wrote it.
fn typed<'a>(value: &'a FieldValue<'_>) -> Result<Typed<'a>, Miss> {
    let text = utf8(value)?;
    Ok(match value.hint {
        Hint::Json => return json::typed(text),
        Hint::Int | Hint::Float => number(text).unwrap_or(Typed::Str(Cow::Borrowed(text))),
        Hint::Bool => match text {
            "true" => Typed::Bool(true),
            "false" => Typed::Bool(false),
            _ => Typed::Str(Cow::Borrowed(text)),
        },
        _ => Typed::Str(Cow::Borrowed(text)),
    })
}

/// Appends the JSON for `place`.
fn write_json(
    fields: &Pairs<'_>,
    place: Place<'_>,
    depth: usize,
    out: &mut String,
) -> Result<(), Miss> {
    if depth > MAX_NESTING {
        return Err(Miss::Malformed);
    }
    match place {
        Place::One(i) => write_value(value(fields, i)?, out),
        Place::Json(_, raw) => {
            out.push_str(raw);
            Ok(())
        }
        Place::Many(first) => {
            let name = &fields.get(first).ok_or(Miss::Malformed)?.0;
            out.push('[');
            for (k, (_, value)) in fields.iter().filter(|(n, _)| n == name).enumerate() {
                if k > 0 {
                    out.push(',');
                }
                write_value(value, out)?;
            }
            out.push(']');
            Ok(())
        }
        Place::Object { witness, len } => {
            let prefix = prefix_of(fields, witness, len)?;
            out.push('{');
            for (k, key) in member_keys(fields, Some(prefix)).iter().enumerate() {
                if k > 0 {
                    out.push(',');
                }
                write_string(key, out)?;
                out.push(':');
                let child = locate(fields, Some(prefix), &[&**key])?;
                write_json(fields, child, depth + 1, out)?;
            }
            out.push('}');
            Ok(())
        }
    }
}

/// Appends one field's value as JSON, typed as [`Record::typed`] types it.
fn write_value(value: &FieldValue<'_>, out: &mut String) -> Result<(), Miss> {
    if value.hint == Hint::Json {
        out.push_str(utf8(value)?);
        return Ok(());
    }
    match typed(value)? {
        Typed::Str(s) => write_string(&s, out),
        Typed::Int(n) => {
            out.push_str(&n.to_string());
            Ok(())
        }
        Typed::Uint(n) => {
            out.push_str(&n.to_string());
            Ok(())
        }
        Typed::Double(n) => {
            out.push_str(&serde_json::to_string(&n).map_err(|_| Miss::Malformed)?);
            Ok(())
        }
        Typed::Bool(b) => {
            out.push_str(if b { "true" } else { "false" });
            Ok(())
        }
        Typed::Null => {
            out.push_str("null");
            Ok(())
        }
        Typed::List | Typed::Map => Err(Miss::Malformed),
    }
}

/// Appends `s` as a JSON string.
fn write_string(s: &str, out: &mut String) -> Result<(), Miss> {
    out.push_str(&serde_json::to_string(s).map_err(|_| Miss::Malformed)?);
    Ok(())
}