grippo 0.2.2

Parse, match and scrub data faster and more efficiently.
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
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
// Project:   grippo
// File:      src/record/nested.rs
// Purpose:   A record whose fields and bodies read as other formats, layer on layer
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! Layers named with the chain grammar, read lazily as one record.
//!
//! `ndjson > field("doc"):xml` reads the record as JSON and its field `doc`
//! as an XML document, so `doc.Event.ID` is the element `ID` in that
//! document. A field hop's layer sits at its field. A hop with no selector
//! reads the body the parser before it handed on, and sits at the key its
//! prefix names, the parser's name by default, as a parse writes it:
//! `syslog > cef` puts the CEF fields at `cef`. `ndjson` and `xml` are read
//! in place as [`Json`] and [`Xml`]. Any other name is a parser from the
//! registry, and its fields are read as [`Fields`] are.
//!
//! A layer opens the first time a path reaches into it, once a record, into
//! the [`LayerCache`] the caller holds for that record. Its bytes are
//! borrowed when the value holds no escape, and decoded once otherwise. A
//! value that isn't the layer's format reads as the plain value it is.

use std::borrow::Cow;
use std::fmt;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, OnceLock};

use thiserror::Error;

use crate::parse::{
    Chain, ChainError, FallbackConfig, Fields, FormatChoice, HopConfig, Parsed, Parser, Resolve,
    ResolveError,
};
use crate::path::keys;

use super::{FieldsAt, Json, Kind, Miss, Node, Record, Typed, Walk};
#[cfg(feature = "xml")]
use super::{Xml, XmlAt};

/// The most hops a chain of layers may have.
pub const MAX_LAYERS: usize = 8;

/// The most keys a field hop's path may have.
const MAX_MOUNT_KEYS: usize = 64;

/// A mount progress meaning the path left the next layer's mount.
const OFF: u8 = u8::MAX;

/// Why a chain can't be read as layers.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum LayerError {
    /// The chain string doesn't read.
    #[error(transparent)]
    Chain(#[from] ChainError),
    /// A parser it names can't be built.
    #[error(transparent)]
    Resolve(#[from] ResolveError),
    /// A hop a record can't be read through.
    #[error("hop {hop}: {reason}")]
    Unsupported {
        /// The hop, from 0.
        hop: usize,
        /// Why.
        reason: &'static str,
    },
}

/// The layers a chain names, compiled once and shared across records.
pub struct LayerPlan {
    layers: Vec<Layer>,
}

struct Layer {
    /// Tried in order: the first that reads the bytes opens the layer.
    formats: Vec<Format>,
    /// Keys from the layer before's root: its field, or the body's one key.
    /// Empty for a body a decoder handed on, which sits where the decoder does.
    mount: Vec<String>,
    /// Whether it reads the body the layer before handed on.
    body: bool,
    /// Whether every format it names decodes, so it writes no field and hands
    /// on bytes of its own.
    decodes: bool,
}

struct Format {
    name: String,
    read: Read,
}

enum Read {
    Json,
    #[cfg(feature = "xml")]
    Xml,
    Parser(Arc<dyn Parser>),
}

impl fmt::Debug for LayerPlan {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_list()
            .entries(self.layers.iter().map(|l| {
                let names: Vec<&str> = l.formats.iter().map(|f| f.name.as_str()).collect();
                (names, &l.mount, l.body)
            }))
            .finish()
    }
}

impl LayerPlan {
    /// The layers a chain string names, its parsers from `resolve`.
    ///
    /// # Errors
    ///
    /// [`LayerError`] when the chain doesn't read, a parser can't be built,
    /// or a hop has no one place in the record: `each`, `auto`, a fallback
    /// other than `raw`, a prefix on the first hop or a field hop, or a body
    /// hop after formats that hand none on.
    pub fn chain(text: &str, resolve: &dyn Resolve) -> Result<Self, LayerError> {
        let chain: Chain = text.parse()?;
        Self::compile(&chain.0, resolve)
    }

    /// The layers a list of hops names, as [`LayerPlan::chain`].
    ///
    /// # Errors
    ///
    /// As [`LayerPlan::chain`].
    pub fn compile(hops: &[HopConfig], resolve: &dyn Resolve) -> Result<Self, LayerError> {
        let unsupported = |hop, reason| Err(LayerError::Unsupported { hop, reason });
        if hops.is_empty() {
            return unsupported(0, "a chain names at least one hop");
        }
        if hops.len() > MAX_LAYERS {
            return unsupported(MAX_LAYERS, "more hops than MAX_LAYERS");
        }
        let mut layers: Vec<Layer> = Vec::with_capacity(hops.len());
        for (i, hop) in hops.iter().enumerate() {
            if hop.each {
                return unsupported(i, "`each` reads many values, so its layer has no one place");
            }
            if !matches!(hop.fallback, None | Some(FallbackConfig::Raw)) {
                return unsupported(
                    i,
                    "a layer that doesn't open reads as its value: only `raw`",
                );
            }
            let FormatChoice::Named(names) = &hop.format else {
                return unsupported(i, "`auto` picks a format per record: name the formats");
            };
            let Some(first) = names.first() else {
                return unsupported(i, "a hop names at least one format");
            };
            let formats = names
                .iter()
                .map(|name| Format::resolve(name, hop, resolve))
                .collect::<Result<Vec<Format>, ResolveError>>()?;
            let (mount, body) = match (i, &hop.field, &hop.prefix) {
                (0, Some(_), _) => return unsupported(0, "the first hop reads the record"),
                (0, None, Some(p)) if !p.is_empty() => {
                    return unsupported(0, "the first hop's layer is the record's root");
                }
                (0, None, _) => (Vec::new(), false),
                (_, Some(_), Some(_)) => {
                    return unsupported(i, "a field hop's layer sits at its field");
                }
                (_, Some(field), None) => {
                    let mount: Vec<String> = keys(field).map(Cow::into_owned).collect();
                    if mount.len() > MAX_MOUNT_KEYS {
                        return unsupported(i, "the field has too many keys");
                    }
                    (mount, false)
                }
                (_, None, prefix) => {
                    let key = prefix
                        .as_deref()
                        .map_or(first.as_str(), |p| p.strip_suffix('.').unwrap_or(p));
                    let mut mount = keys(key);
                    let (Some(key), None) = (mount.next(), mount.next()) else {
                        return unsupported(i, "a body's prefix is one key");
                    };
                    if key.is_empty() {
                        return unsupported(i, "a body's prefix is one key");
                    }
                    let before = &layers[i - 1];
                    let parser_before = before
                        .formats
                        .iter()
                        .any(|f| matches!(&f.read, Read::Parser(p) if p.hands_on_body()));
                    if !parser_before {
                        return unsupported(i, "no format of the hop before hands on a body");
                    }
                    if before.decodes {
                        (Vec::new(), true)
                    } else {
                        (vec![key.into_owned()], true)
                    }
                }
            };
            let decodes = formats
                .iter()
                .all(|f| matches!(&f.read, Read::Parser(p) if p.decodes()));
            layers.push(Layer {
                formats,
                mount,
                body,
                decodes,
            });
        }
        Ok(Self { layers })
    }

    /// The record in `record`, read through these layers. The first hop's
    /// format reads it at once, and the rest open as a path reaches them.
    ///
    /// # Errors
    ///
    /// [`Miss::Malformed`] when no format of the first hop reads `record`.
    pub fn open<'a>(
        &'a self,
        record: &'a [u8],
        cache: &'a LayerCache<'a>,
    ) -> Result<Layered<'a, Source<'a>>, Miss> {
        let slot = &cache.slots[0];
        let opened = *slot.open.get_or_init(|| {
            cache.opened.fetch_add(1, Ordering::Relaxed);
            open_bytes(&self.layers[0].formats, record, slot)
        });
        let base = opened.ok_or(Miss::Malformed)?;
        Ok(Layered {
            base: Source(base.source),
            layers: self,
            cache,
        })
    }

    /// `base`, a record the caller already holds in the first hop's format,
    /// read through these layers: a [`Json`] for `ndjson` keeps JSON's own
    /// reads for every path that stays in it. A body the first hop hands on
    /// isn't known this way, so a body hop after it reads nothing.
    #[must_use]
    pub const fn over<'a, R: Record<'a>>(
        &'a self,
        base: R,
        cache: &'a LayerCache<'a>,
    ) -> Layered<'a, R> {
        Layered {
            base,
            layers: self,
            cache,
        }
    }

    /// How many layers there are, the record's own included.
    #[must_use]
    pub const fn len(&self) -> usize {
        self.layers.len()
    }

    /// Never: a chain names at least one layer.
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.layers.is_empty()
    }
}

impl Format {
    fn resolve(name: &str, hop: &HopConfig, resolve: &dyn Resolve) -> Result<Self, ResolveError> {
        let read = match name {
            "ndjson" => Read::Json,
            #[cfg(feature = "xml")]
            "xml" => Read::Xml,
            _ => Read::Parser(resolve.resolve(name, hop.settings.get(name))?),
        };
        Ok(Self {
            name: name.to_owned(),
            read,
        })
    }
}

/// The layers one record opened. Hold one per record: it is filled as paths
/// reach into layers, and borrowed by everything read from them.
#[derive(Debug, Default)]
pub struct LayerCache<'a> {
    slots: [Slot<'a>; MAX_LAYERS],
    opened: AtomicUsize,
}

impl LayerCache<'_> {
    /// An empty cache.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// How many times a layer was opened, each layer at most once.
    #[must_use]
    pub fn opened(&self) -> usize {
        self.opened.load(Ordering::Relaxed)
    }
}

#[derive(Debug, Default)]
struct Slot<'a> {
    /// The layer's bytes, when its value had to be decoded.
    decoded: OnceLock<Vec<u8>>,
    /// The body its parser handed on, when it decoded one.
    body: OnceLock<Vec<u8>>,
    /// The fields its parser wrote.
    fields: OnceLock<Fields<'a>>,
    /// `None` when no format read it.
    open: OnceLock<Option<Opened<'a>>>,
}

#[derive(Debug, Clone, Copy)]
struct Opened<'a> {
    bytes: &'a [u8],
    source: Src<'a>,
    /// Which of the hop's formats read it.
    #[cfg_attr(
        not(feature = "scrub"),
        expect(dead_code, reason = "read only by scrub write-back")
    )]
    format: usize,
    /// The body its parser handed on: a span of `bytes`, or decoded bytes.
    body: Option<&'a [u8]>,
}

/// Opens `bytes` with the first of `formats` that reads them.
fn open_bytes<'a>(formats: &[Format], bytes: &'a [u8], slot: &'a Slot<'a>) -> Option<Opened<'a>> {
    let first = bytes.iter().find(|b| !b.is_ascii_whitespace()).copied();
    formats.iter().enumerate().find_map(|(format, f)| {
        let (source, body) = match &f.read {
            Read::Json => (first == Some(b'{')).then_some((Src::Json(Json::new(bytes)), None))?,
            #[cfg(feature = "xml")]
            Read::Xml => (first == Some(b'<')).then_some((Src::Xml(Xml::new(bytes)), None))?,
            Read::Parser(parser) => {
                let mut fields = Fields::new();
                let body = match parser.parse(bytes, &mut fields) {
                    Ok(Parsed::Done) => None,
                    Ok(Parsed::Body { span, .. }) => Some(bytes.get(span)?),
                    Ok(Parsed::Decoded(decoded)) => {
                        Some(slot.body.get_or_init(|| decoded.into_vec()).as_slice())
                    }
                    _ => return None,
                };
                (Src::Fields(slot.fields.get_or_init(|| fields)), body)
            }
        };
        Some(Opened {
            bytes,
            source,
            format,
            body,
        })
    })
}

/// One layer's record: JSON, XML or a parser's fields.
#[derive(Debug, Clone, Copy)]
pub struct Source<'a>(Src<'a>);

#[derive(Debug, Clone, Copy)]
enum Src<'a> {
    Json(Json<'a>),
    #[cfg(feature = "xml")]
    Xml(Xml<'a>),
    Fields(&'a Fields<'a>),
}

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

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SrcAt<'a> {
    Json(&'a str),
    #[cfg(feature = "xml")]
    Xml(XmlAt),
    Fields(FieldsAt<'a>),
}

impl<'a> Record<'a> for Source<'a> {
    type At = SourceAt<'a>;

    fn find<K: AsRef<str>>(self, path: &[K]) -> Result<SourceAt<'a>, Miss> {
        Ok(SourceAt(match self.0 {
            Src::Json(r) => SrcAt::Json(r.find(path)?),
            #[cfg(feature = "xml")]
            Src::Xml(r) => SrcAt::Xml(r.find(path)?),
            Src::Fields(r) => SrcAt::Fields(r.find(path)?),
        }))
    }

    fn find_below<K: AsRef<str>>(self, at: SourceAt<'a>, path: &[K]) -> Result<SourceAt<'a>, Miss> {
        Ok(SourceAt(match (self.0, at.0) {
            (Src::Json(r), SrcAt::Json(at)) => SrcAt::Json(r.find_below(at, path)?),
            #[cfg(feature = "xml")]
            (Src::Xml(r), SrcAt::Xml(at)) => SrcAt::Xml(r.find_below(at, path)?),
            (Src::Fields(r), SrcAt::Fields(at)) => SrcAt::Fields(r.find_below(at, path)?),
            _ => return Err(Miss::Malformed),
        }))
    }

    fn typed(self, at: SourceAt<'a>) -> Result<Typed<'a>, Miss> {
        match (self.0, at.0) {
            (Src::Json(r), SrcAt::Json(at)) => r.typed(at),
            #[cfg(feature = "xml")]
            (Src::Xml(r), SrcAt::Xml(at)) => r.typed(at),
            (Src::Fields(r), SrcAt::Fields(at)) => r.typed(at),
            _ => Err(Miss::Malformed),
        }
    }

    fn text(self, at: SourceAt<'a>) -> Result<Cow<'a, str>, Miss> {
        match (self.0, at.0) {
            (Src::Json(r), SrcAt::Json(at)) => r.text(at),
            #[cfg(feature = "xml")]
            (Src::Xml(r), SrcAt::Xml(at)) => r.text(at),
            (Src::Fields(r), SrcAt::Fields(at)) => r.text(at),
            _ => Err(Miss::Malformed),
        }
    }
}

impl<'a> Walk<'a> for Source<'a> {
    fn walk<F: FnMut(Node<'a, SourceAt<'a>>)>(self, mut visit: F) -> Result<(), Miss> {
        match self.0 {
            Src::Json(r) => r.walk(|n| visit(retag(n, |at| SourceAt(SrcAt::Json(at))))),
            #[cfg(feature = "xml")]
            Src::Xml(r) => r.walk(|n| visit(retag(n, |at| SourceAt(SrcAt::Xml(at))))),
            Src::Fields(r) => r.walk(|n| visit(retag(n, |at| SourceAt(SrcAt::Fields(at))))),
        }
    }

    fn bytes(self, at: SourceAt<'a>) -> Result<Cow<'a, [u8]>, Miss> {
        match (self.0, at.0) {
            (Src::Json(r), SrcAt::Json(at)) => r.bytes(at),
            #[cfg(feature = "xml")]
            (Src::Xml(r), SrcAt::Xml(at)) => r.bytes(at),
            (Src::Fields(r), SrcAt::Fields(at)) => r.bytes(at),
            _ => Err(Miss::Malformed),
        }
    }
}

/// A node with its place in another type.
fn retag<A, B>(n: Node<'_, A>, place: impl FnOnce(A) -> B) -> Node<'_, B> {
    Node {
        depth: n.depth,
        key: n.key,
        kind: n.kind,
        at: place(n.at),
    }
}

/// A record read through a [`LayerPlan`]: `R` is the first layer, read with its
/// own reads, and the rest are [`Source`]s, dispatched at the layer's edge.
#[derive(Debug, Clone, Copy)]
pub struct Layered<'a, R> {
    base: R,
    layers: &'a LayerPlan,
    cache: &'a LayerCache<'a>,
}

/// Where a value sits in a [`Layered`] record.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct LayeredAt<'a, A> {
    place: Place<'a, A>,
    /// How many keys of the next layer's mount the path to here matched, or
    /// [`OFF`] once it left it.
    toward: u8,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Place<'a, A> {
    Base(A),
    /// A layer's whole record, at its mount.
    Root(u8),
    Inner(u8, SourceAt<'a>),
}

/// Where a read starts.
#[derive(Clone, Copy)]
enum Start<'a, A> {
    BaseRoot,
    At(Place<'a, A>),
}

impl<A> Start<'_, A> {
    const fn layer(&self) -> usize {
        match self {
            Self::BaseRoot | Self::At(Place::Base(_)) => 0,
            Self::At(Place::Root(k) | Place::Inner(k, _)) => *k as usize,
        }
    }
}

/// `k` as a layer index. Every index is below [`MAX_LAYERS`].
#[allow(
    clippy::cast_possible_truncation,
    reason = "a layer index is below MAX_LAYERS"
)]
const fn index(k: usize) -> u8 {
    k as u8
}

impl<'a, R: Record<'a>> Layered<'a, R> {
    /// Layer `k`, when it opened.
    fn opened(self, k: usize) -> Option<Opened<'a>> {
        self.cache.slots.get(k)?.open.get().copied().flatten()
    }

    fn source(self, k: u8) -> Result<Source<'a>, Miss> {
        self.opened(usize::from(k))
            .map(|o| Source(o.source))
            .ok_or(Miss::Malformed)
    }

    /// Layer `j`, opened over the value at `anchor` in the layer before, or
    /// over the body that layer handed on.
    fn open(self, j: usize, anchor: Option<LayeredAt<'a, R::At>>) -> Option<Opened<'a>> {
        let slot = self.cache.slots.get(j)?;
        let layer = self.layers.layers.get(j)?;
        *slot.open.get_or_init(|| {
            self.cache.opened.fetch_add(1, Ordering::Relaxed);
            let bytes: &'a [u8] = match anchor {
                None => self.opened(j.checked_sub(1)?)?.body?,
                Some(at) => match self.text(at).ok()? {
                    Cow::Borrowed(text) => text.as_bytes(),
                    Cow::Owned(text) => slot.decoded.get_or_init(|| text.into_bytes()).as_slice(),
                },
            };
            open_bytes(&layer.formats, bytes, slot)
        })
    }

    /// The value at `path` from `from` in its layer, which matched `toward`
    /// keys of the next layer's mount, stepping into that layer where the
    /// path reaches it.
    fn descend<K: AsRef<str>>(
        self,
        from: Start<'a, R::At>,
        toward: u8,
        path: &[K],
    ) -> Result<LayeredAt<'a, R::At>, Miss> {
        let k = from.layer();
        let Some(next) = self.layers.layers.get(k + 1).filter(|_| toward != OFF) else {
            return self.read(from, OFF, path);
        };
        let matched = usize::from(toward);
        let rest = next.mount.get(matched..).unwrap_or_default();
        let n = rest
            .iter()
            .zip(path)
            .take_while(|(m, key)| m.as_str() == key.as_ref())
            .count();
        if n < rest.len() {
            let toward = if n == path.len() {
                index(matched + n)
            } else {
                OFF
            };
            return self.read(from, toward, path);
        }
        let opened = if next.body {
            self.open(k + 1, None)
        } else {
            let anchor = self.read(from, OFF, &path[..n])?;
            self.open(k + 1, Some(anchor))
        };
        if opened.is_none() {
            return self.read(from, OFF, path);
        }
        self.descend(Start::At(Place::Root(index(k + 1))), 0, &path[n..])
    }

    /// The value at `path` from `from`, within its layer.
    fn read<K: AsRef<str>>(
        self,
        from: Start<'a, R::At>,
        toward: u8,
        path: &[K],
    ) -> Result<LayeredAt<'a, R::At>, Miss> {
        let place = match from {
            Start::BaseRoot => Place::Base(self.base.find(path)?),
            Start::At(Place::Base(at)) => Place::Base(self.base.find_below(at, path)?),
            Start::At(Place::Root(k)) if path.is_empty() => Place::Root(k),
            // A layer's root sits below the record's, so a key it lacks is a missing field.
            Start::At(Place::Root(k)) => match self.source(k)?.find(path) {
                Ok(at) => Place::Inner(k, at),
                Err(Miss::MissingRoot) => return Err(Miss::MissingField),
                Err(miss) => return Err(miss),
            },
            Start::At(Place::Inner(k, at)) => {
                Place::Inner(k, self.source(k)?.find_below(at, path)?)
            }
        };
        Ok(LayeredAt { place, toward })
    }
}

impl<'a, R: Record<'a>> Record<'a> for Layered<'a, R> {
    /// A value in the first layer, a layer's whole record, or a value in it.
    type At = LayeredAt<'a, R::At>;

    fn find<K: AsRef<str>>(self, path: &[K]) -> Result<Self::At, Miss> {
        if path.is_empty() {
            return Err(Miss::MissingRoot);
        }
        self.descend(Start::BaseRoot, 0, path)
    }

    fn find_below<K: AsRef<str>>(self, at: Self::At, path: &[K]) -> Result<Self::At, Miss> {
        if path.is_empty() {
            return Ok(at);
        }
        self.descend(Start::At(at.place), at.toward, path)
    }

    /// A layer's whole record is an object.
    fn typed(self, at: Self::At) -> Result<Typed<'a>, Miss> {
        match at.place {
            Place::Base(at) => self.base.typed(at),
            Place::Root(_) => Ok(Typed::Map),
            Place::Inner(k, at) => self.source(k)?.typed(at),
        }
    }

    /// A layer's whole record is its text as written.
    fn text(self, at: Self::At) -> Result<Cow<'a, str>, Miss> {
        match at.place {
            Place::Base(at) => self.base.text(at),
            Place::Root(k) => {
                let bytes = self.opened(usize::from(k)).ok_or(Miss::Malformed)?.bytes;
                std::str::from_utf8(bytes)
                    .map(Cow::Borrowed)
                    .map_err(|_| Miss::Malformed)
            }
            Place::Inner(k, at) => self.source(k)?.text(at),
        }
    }
}

/// A walk's visit over a [`Layered`] record's places.
type Visit<'v, 'a, A> = dyn FnMut(Node<'a, LayeredAt<'a, A>>) + 'v;

impl<'a, R: Walk<'a>> Walk<'a> for Layered<'a, R> {
    /// The first layer's values, with a layer that opens at a field visited
    /// as an object in the field's place and its values below it. A body's
    /// layer comes after the values of the layer that handed it on, under
    /// its key, and the field that copied the body is left out. A value its
    /// layer's format doesn't read is visited as the value it is.
    fn walk<F: FnMut(Node<'a, Self::At>)>(self, mut visit: F) -> Result<(), Miss> {
        self.walk_layer(self.base, 0, 0, Place::Base, &mut visit)
    }

    fn bytes(self, at: Self::At) -> Result<Cow<'a, [u8]>, Miss> {
        match at.place {
            Place::Base(at) => self.base.bytes(at),
            Place::Root(k) => self
                .opened(usize::from(k))
                .map(|o| Cow::Borrowed(o.bytes))
                .ok_or(Miss::Malformed),
            Place::Inner(k, at) => self.source(k)?.bytes(at),
        }
    }
}

impl<'a, R: Walk<'a>> Layered<'a, R> {
    /// Walks `record`, layer `k`, its root members at depth `offset`.
    fn walk_layer<S: Walk<'a>>(
        self,
        record: S,
        k: usize,
        offset: usize,
        wrap: impl Fn(S::At) -> Place<'a, R::At>,
        visit: &mut Visit<'_, 'a, R::At>,
    ) -> Result<(), Miss> {
        let next = self.layers.layers.get(k + 1);
        let mount = next.filter(|l| !l.body).map(|l| l.mount.as_slice());
        // A body layer is walked first, so a body that doesn't walk keeps its copy.
        let mut body_nodes = Vec::new();
        let body = match next
            .filter(|l| l.body)
            .and_then(|l| Some((l, self.open(k + 1, None)?)))
        {
            Some((layer, opened)) => {
                let walked = if layer.mount.is_empty() {
                    // A decoded body's values sit beside this layer's, with no key.
                    let mut nodes = Vec::new();
                    let walked = self.walk_beside(k + 1, offset, opened, &mut |n| nodes.push(n));
                    if walked {
                        body_nodes = nodes;
                    }
                    walked
                } else {
                    let key = layer.mount.first().cloned().map(Cow::Owned);
                    let root = root_node(k + 1, offset, key);
                    self.walk_inner(k + 1, offset + 1, root, &mut |n| body_nodes.push(n))
                };
                self.opened(k).and_then(|o| o.body).filter(|_| walked)
            }
            None => None,
        };
        let mut path: Vec<Option<Cow<'a, str>>> = Vec::new();
        let mut skip: Option<usize> = None;
        record.walk(|node| {
            if let Some(depth) = skip {
                if node.depth > depth {
                    return;
                }
                skip = None;
            }
            if let Some(body) = body
                && node.kind == Kind::Str
                && record
                    .bytes(node.at)
                    .is_ok_and(|b| matches!(b, Cow::Borrowed(b) if overlaps(b, body)))
            {
                return;
            }
            path.truncate(node.depth);
            path.push(node.key.clone());
            let at = LayeredAt {
                place: wrap(node.at),
                toward: OFF,
            };
            let mounted = mount.is_some_and(|m| {
                m.len() == path.len()
                    && path
                        .iter()
                        .zip(m)
                        .all(|(key, m)| key.as_deref() == Some(m.as_str()))
            });
            if mounted && self.open(k + 1, Some(at)).is_some() {
                let root = root_node(k + 1, offset + node.depth, node.key.clone());
                if self.walk_inner(k + 1, offset + node.depth + 1, root, visit) {
                    skip = Some(node.depth);
                    return;
                }
            }
            visit(Node {
                depth: offset + node.depth,
                key: node.key,
                kind: node.kind,
                at,
            });
        })?;
        for n in body_nodes {
            visit(n);
        }
        Ok(())
    }

    /// Visits layer `j`'s values at `offset`, beside the layer before's.
    /// `false` when the layer doesn't walk.
    fn walk_beside(
        self,
        j: usize,
        offset: usize,
        opened: Opened<'a>,
        visit: &mut Visit<'_, 'a, R::At>,
    ) -> bool {
        let place = move |at| Place::Inner(index(j), at);
        self.walk_layer(Source(opened.source), j, offset, place, visit)
            .is_ok()
    }

    /// Visits `root`, then layer `j`'s values below it. `false`, with
    /// nothing visited, when the layer doesn't walk.
    fn walk_inner(
        self,
        j: usize,
        offset: usize,
        root: Node<'a, LayeredAt<'a, R::At>>,
        visit: &mut Visit<'_, 'a, R::At>,
    ) -> bool {
        let Some(opened) = self.opened(j) else {
            return false;
        };
        let mut root = Some(root);
        let mut first = |n: Node<'a, LayeredAt<'a, R::At>>| {
            if let Some(root) = root.take() {
                visit(root);
            }
            visit(n);
        };
        let place = move |at| Place::Inner(index(j), at);
        let walked = self.walk_layer(Source(opened.source), j, offset, place, &mut first);
        match (walked, root) {
            (Ok(()), Some(root)) => {
                visit(root);
                true
            }
            (Ok(()) | Err(_), None) => true,
            (Err(_), Some(_)) => false,
        }
    }
}

/// The node for layer `j`'s whole record.
const fn root_node<A>(
    j: usize,
    depth: usize,
    key: Option<Cow<'_, str>>,
) -> Node<'_, LayeredAt<'_, A>> {
    Node {
        depth,
        key,
        kind: Kind::Map,
        at: LayeredAt {
            place: Place::Root(index(j)),
            toward: 0,
        },
    }
}

/// Whether `a` shares any byte in memory with `b`.
fn overlaps(a: &[u8], b: &[u8]) -> bool {
    let (a, b) = (a.as_ptr_range(), b.as_ptr_range());
    a.start.addr() < b.end.addr() && b.start.addr() < a.end.addr()
}

#[cfg(feature = "scrub")]
mod write;

#[cfg(test)]
mod tests;