grippo 0.2.4

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
// Project:   grippo
// File:      src/decode/tests.rs
// Purpose:   Tests for the decoding layers: each codec, chains, layered records
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

use super::{Codec, Decoder, stock};
use crate::parse::{DECODE_MAX_BYTES, ParseError, Parser};

/// What a decode should give.
#[derive(Debug)]
enum Want {
    Bytes(Vec<u8>),
    Malformed,
    Limit,
}

fn check(name: &str, decoder: &Decoder, input: &[u8], want: &Want) {
    let mut out = b"kept".to_vec();
    let got = decoder.decode(input, &mut out);
    match (want, got) {
        (Want::Bytes(bytes), Ok(())) => assert_eq!(&out[4..], bytes, "{name}"),
        (Want::Malformed, Err(ParseError::Malformed { .. }))
        | (
            Want::Limit,
            Err(ParseError::Limit {
                what: "decoded bytes",
            }),
        ) => {
            assert_eq!(out, b"kept", "{name}: a failed decode leaves out as it was");
        }
        (want, got) => panic!("{name}: want {want:?}, got {got:?}"),
    }
}

/// A plain payload, compressible as a log is.
fn plain(len: usize) -> Vec<u8> {
    br#"{"host":"web-07","level":"info","msg":"order 81723 paid"}"#
        .iter()
        .copied()
        .cycle()
        .take(len)
        .collect()
}

/// The rows every codec shares: whole, empty, cut short, over the cap and at
/// it, and bytes that aren't the format. `encode` turns plain bytes into the
/// codec's, `empty` is what decoding no bytes gives, and `cut` what decoding
/// the first half of the encoded bytes gives.
fn table(
    codec: Codec,
    encode: impl Fn(&[u8]) -> Vec<u8>,
    empty: &Want,
    cut: impl Fn(&[u8]) -> Want,
) {
    let name = codec.name();
    let decoder = Decoder::new(codec);
    let whole = plain(5000);
    let encoded = encode(&whole);
    let half = &encoded[..encoded.len() / 2];
    let rows: Vec<(&str, Decoder, Vec<u8>, Want)> = vec![
        (
            "whole",
            decoder.clone(),
            encoded.clone(),
            Want::Bytes(whole.clone()),
        ),
        ("empty", decoder.clone(), Vec::new(), clone(empty)),
        ("cut short", decoder.clone(), half.to_vec(), cut(half)),
        (
            "one byte over the cap",
            decoder.clone().with_max_bytes(whole.len() - 1),
            encoded.clone(),
            Want::Limit,
        ),
        (
            "at the cap",
            decoder.clone().with_max_bytes(whole.len()),
            encoded.clone(),
            Want::Bytes(whole),
        ),
        (
            "not the format",
            decoder,
            b"\x00\x01 not this codec's ~~~".to_vec(),
            Want::Malformed,
        ),
    ];
    for (row, decoder, input, want) in &rows {
        check(&format!("{name} {row}"), decoder, input, want);
    }
}

fn clone(want: &Want) -> Want {
    match want {
        Want::Bytes(bytes) => Want::Bytes(bytes.clone()),
        Want::Malformed => Want::Malformed,
        Want::Limit => Want::Limit,
    }
}

#[test]
fn every_stock_decoder_decodes_writes_no_field_and_has_a_valid_name() {
    for decoder in stock() {
        assert!(
            crate::parse::valid_parser_name(decoder.name()),
            "{}",
            decoder.name()
        );
        assert!(decoder.decodes());
        assert_eq!(decoder.max_bytes(), DECODE_MAX_BYTES);
    }
    assert_eq!(DECODE_MAX_BYTES, 16 << 20);
}

#[cfg(feature = "decode-base64")]
mod base64_rows {
    use base64::Engine;
    use base64::alphabet;
    use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD};
    use base64::engine::{DecodePaddingMode, GeneralPurpose, GeneralPurposeConfig};

    use super::{Codec, Decoder, Want, check, plain, table};

    const INDIFFERENT: GeneralPurposeConfig =
        GeneralPurposeConfig::new().with_decode_padding_mode(DecodePaddingMode::Indifferent);
    const STANDARD_INDIFFERENT: GeneralPurpose =
        GeneralPurpose::new(&alphabet::STANDARD, INDIFFERENT);
    const URL_SAFE_INDIFFERENT: GeneralPurpose =
        GeneralPurpose::new(&alphabet::URL_SAFE, INDIFFERENT);

    /// What the `base64` crate makes of `text`.
    fn by_crate(engine: &GeneralPurpose, text: &[u8]) -> Want {
        engine.decode(text).map_or(Want::Malformed, Want::Bytes)
    }

    const STANDARD_CODEC: Codec = Codec::Base64 {
        url_safe: false,
        skip_whitespace: false,
    };

    #[test]
    fn base64_reads_its_table() {
        table(
            STANDARD_CODEC,
            |b| STANDARD.encode(b).into_bytes(),
            &Want::Bytes(Vec::new()),
            |half| by_crate(&STANDARD_INDIFFERENT, half),
        );
        table(
            Codec::Base64 {
                url_safe: true,
                skip_whitespace: false,
            },
            |b| URL_SAFE_NO_PAD.encode(b).into_bytes(),
            &Want::Bytes(Vec::new()),
            |half| by_crate(&URL_SAFE_INDIFFERENT, half),
        );
    }

    #[test]
    fn base64_takes_or_refuses_each_short_form() {
        let decoder = Decoder::new(STANDARD_CODEC);
        let rows: &[(&str, Option<&[u8]>)] = &[
            ("QUJD", Some(b"ABC")),
            ("QUI=", Some(b"AB")),
            ("QUI", Some(b"AB")),
            ("QQ==", Some(b"A")),
            ("QQ=", Some(b"A")),
            ("QQ", Some(b"A")),
            ("", Some(b"")),
            ("Q", None),
            ("QQ===", None),
            ("QUJD=", None),
            ("QR==", None),
            ("QUJ=", None),
            ("QQ==QQ==", None),
            ("QU JD", None),
            ("QUJD\n", None),
            ("-_-_", None),
            ("=", None),
        ];
        for (text, want) in rows {
            let want = want.map_or(Want::Malformed, |b| Want::Bytes(b.to_vec()));
            check(text, &decoder, text.as_bytes(), &want);
        }
    }

    #[test]
    fn whitespace_is_refused_unless_the_layer_skips_it() {
        let text = STANDARD.encode(plain(300));
        let lines: Vec<&str> = text
            .as_bytes()
            .chunks(76)
            .map(|l| std::str::from_utf8(l).unwrap())
            .collect();
        let wrapped = lines.join("\r\n") + "\n";
        let strict = Decoder::new(STANDARD_CODEC);
        let lenient = Decoder::new(Codec::Base64 {
            url_safe: false,
            skip_whitespace: true,
        });
        check(
            "strict, wrapped",
            &strict,
            wrapped.as_bytes(),
            &Want::Malformed,
        );
        check(
            "skip, wrapped",
            &lenient,
            wrapped.as_bytes(),
            &Want::Bytes(plain(300)),
        );
        check(
            "skip, spaced padding",
            &lenient,
            b" QQ = = ",
            &Want::Bytes(b"A".to_vec()),
        );
        check(
            "skip, only spaces",
            &lenient,
            b" \t\n",
            &Want::Bytes(Vec::new()),
        );
        check("skip, bad byte", &lenient, b"QU*D", &Want::Malformed);
        check(
            "skip, over the cap",
            &lenient.with_max_bytes(299),
            wrapped.as_bytes(),
            &Want::Limit,
        );
    }

    #[test]
    fn an_error_names_the_byte_it_found() {
        let decoder = Decoder::new(STANDARD_CODEC);
        let mut text = STANDARD.encode(plain(600)).into_bytes();
        text[517] = b'*';
        let err = decoder.decode(&text, &mut Vec::new()).unwrap_err();
        assert!(
            matches!(err, crate::parse::ParseError::Malformed { offset: 517, .. }),
            "{err:?}"
        );
    }
}

#[cfg(feature = "decode-hex")]
#[test]
fn hex_reads_its_table() {
    let hex = |b: &[u8]| -> Vec<u8> {
        b.iter()
            .flat_map(|b| format!("{b:02X}").into_bytes())
            .collect()
    };
    table(Codec::Hex, hex, &Want::Bytes(Vec::new()), |_| {
        Want::Bytes(plain(2500))
    });
    let decoder = Decoder::new(Codec::Hex);
    let rows: &[(&str, Want)] = &[
        ("00ff7Fa0", Want::Bytes(vec![0x00, 0xFF, 0x7F, 0xA0])),
        ("0", Want::Malformed),
        ("0g", Want::Malformed),
        ("0x00", Want::Malformed),
        (" 00", Want::Malformed),
    ];
    for (text, want) in rows {
        check(text, &decoder, text.as_bytes(), want);
    }
    let err = decoder.decode(
        b"00112233445566778899aabbccddeeff00112233445566778899aabbccddeeZf",
        &mut Vec::new(),
    );
    assert!(
        matches!(err, Err(ParseError::Malformed { offset: 62, .. })),
        "{err:?}"
    );
}

#[cfg(any(feature = "decode-gzip", feature = "decode-zlib"))]
mod flate_rows {
    use std::io::Write;

    use super::{Codec, Want, table};

    #[cfg(feature = "decode-gzip")]
    pub(super) fn gzip(bytes: &[u8]) -> Vec<u8> {
        let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
        encoder.write_all(bytes).unwrap();
        encoder.finish().unwrap()
    }

    #[cfg(feature = "decode-gzip")]
    #[test]
    fn gzip_reads_its_table_and_members_back_to_back() {
        table(Codec::Gzip, gzip, &Want::Malformed, |_| Want::Malformed);
        let mut two = gzip(b"first ");
        two.extend(gzip(b"second"));
        super::check(
            "two members",
            &super::Decoder::new(Codec::Gzip),
            &two,
            &Want::Bytes(b"first second".to_vec()),
        );
    }

    #[cfg(feature = "decode-zlib")]
    #[test]
    fn zlib_reads_its_table() {
        let zlib = |bytes: &[u8]| {
            let mut encoder =
                flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default());
            encoder.write_all(bytes).unwrap();
            encoder.finish().unwrap()
        };
        table(Codec::Zlib, zlib, &Want::Malformed, |_| Want::Malformed);
    }
}

#[cfg(feature = "decode-zstd")]
#[test]
fn zstd_reads_its_table_and_frames_back_to_back() {
    let zstd = |bytes: &[u8]| zstd::encode_all(bytes, 3).unwrap();
    table(Codec::Zstd, zstd, &Want::Malformed, |_| Want::Malformed);
    let mut two = zstd(b"first ");
    two.extend(zstd(b"second"));
    check(
        "two frames",
        &Decoder::new(Codec::Zstd),
        &two,
        &Want::Bytes(b"first second".to_vec()),
    );
    // A frame whose window is larger than the cap allows is refused before
    // its window is allocated.
    let mut encoder = zstd::stream::Encoder::new(Vec::new(), 3).unwrap();
    encoder.window_log(20).unwrap();
    encoder.long_distance_matching(true).unwrap();
    std::io::Write::write_all(&mut encoder, &plain(1 << 20)).unwrap();
    let wide = encoder.finish().unwrap();
    check(
        "a window past the cap",
        &Decoder::new(Codec::Zstd).with_max_bytes(1 << 12),
        &wide,
        &Want::Malformed,
    );
}

#[cfg(feature = "decode-snappy")]
#[test]
fn snappy_reads_its_table_framed_and_raw() {
    let framed = |bytes: &[u8]| {
        let mut encoder = snap::write::FrameEncoder::new(Vec::new());
        std::io::Write::write_all(&mut encoder, bytes).unwrap();
        encoder.into_inner().unwrap()
    };
    table(Codec::Snappy, framed, &Want::Malformed, |_| Want::Malformed);
    let raw = |bytes: &[u8]| snap::raw::Encoder::new().compress_vec(bytes).unwrap();
    table(Codec::SnappyRaw, raw, &Want::Malformed, |_| Want::Malformed);
}

#[cfg(feature = "decode-gzip")]
#[test]
fn a_decoder_with_magic_leaves_other_input_alone() {
    use crate::parse::{Decoded, Fields, Parsed};

    let decoder = Decoder::new(Codec::Gzip);
    let stream = flate_rows::gzip(b"x");
    let mut out = Fields::new();
    let other = decoder.parse(b"{\"a\":1}", &mut out).ok();
    assert_eq!(other, Some(Parsed::NoMatch));
    assert!(decoder.signature().may_match(&stream));
    assert!(!decoder.signature().may_match(b"{\"a\":1}"));
    let got = decoder.parse(&stream, &mut out).unwrap();
    assert_eq!(got, Parsed::Decoded(Decoded::new(b"x".to_vec())));
    assert_eq!(out.as_slice().len(), 0);
}

#[cfg(all(
    feature = "decode-base64",
    feature = "decode-gzip",
    feature = "parse-ndjson"
))]
mod chains {
    use std::sync::Arc;

    use base64::Engine;
    use base64::engine::general_purpose::STANDARD;

    use super::flate_rows::gzip;
    use super::{Codec, Decoder};
    use crate::format;
    use crate::parse::{Fields, ParsePlan, Parsers, Status};

    fn registry() -> Parsers {
        let mut registry = Parsers::new();
        format::register_stock(&mut registry).unwrap();
        registry
            .register(Arc::new(
                Decoder::new(Codec::Base64 {
                    url_safe: false,
                    skip_whitespace: true,
                })
                .named("base64:wrapped"),
            ))
            .unwrap();
        registry
    }

    fn texts(out: &Fields<'_>) -> Vec<(String, String)> {
        out.as_slice()
            .iter()
            .map(|(n, v)| (n.clone(), String::from_utf8(v.bytes.to_vec()).unwrap()))
            .collect()
    }

    fn record(payload: &str) -> String {
        format!(r#"{{"src":"s3","payload":"{payload}"}}"#)
    }

    #[test]
    fn a_chain_decodes_base64_then_gzip_then_reads_the_json() {
        let inner = br#"{"user":"kay","n":7}"#;
        let line = record(&STANDARD.encode(gzip(inner)));
        let rows: &[(&str, &str, Status, usize, &[(&str, &str)])] = &[
            (
                r#"ndjson > field("payload"):base64 > gzip > ndjson"#,
                &line,
                Status::Parsed,
                4,
                &[("ndjson.user", "kay"), ("ndjson.n", "7")],
            ),
            (
                r#"ndjson > field("payload"):base64 > auto*"#,
                &line,
                Status::Parsed,
                4,
                &[("ndjson.user", "kay"), ("ndjson.n", "7")],
            ),
            (
                r#"ndjson > field("payload"):base64 > gzip > ndjson"#,
                &record("not*base64"),
                Status::Fallback,
                1,
                &[],
            ),
            (
                r#"ndjson > field("payload"):base64 > gzip > ndjson"#,
                &record(&STANDARD.encode(b"plain text, not gzip")),
                Status::Fallback,
                2,
                &[],
            ),
            (
                r#"ndjson > field("payload"):base64:wrapped > gzip > ndjson"#,
                &record(&{
                    let text = STANDARD.encode(gzip(inner));
                    let (a, b) = text.split_at(10);
                    format!("{a}\\n{b}")
                }),
                Status::Parsed,
                4,
                &[("ndjson.user", "kay"), ("ndjson.n", "7")],
            ),
        ];
        let registry = registry();
        for (chain, line, status, layers, want) in rows {
            let plan = ParsePlan::chain(chain, &registry).unwrap();
            let mut out = Fields::new();
            let outcome = plan.parse_stateless(line.as_bytes(), &mut out);
            assert_eq!(
                (outcome.status, outcome.layers),
                (*status, *layers),
                "{chain} {line}"
            );
            let got = texts(&out);
            for (name, value) in *want {
                assert!(
                    got.contains(&((*name).to_owned(), (*value).to_owned())),
                    "{chain}: {name} in {got:?}"
                );
            }
            assert!(
                got.contains(&("src".to_owned(), "s3".to_owned())),
                "{chain}"
            );
        }
    }

    #[test]
    fn decoded_bytes_get_their_own_budget() {
        // About 400 KiB of JSON that gzips to a few KiB: far past the budget
        // the line alone earns, 32 times its length or 64 KiB.
        let padding = "x".repeat(400 << 10);
        let inner = format!(r#"{{"user":"kay","pad":"{padding}"}}"#);
        let line = record(&STANDARD.encode(gzip(inner.as_bytes())));
        assert!(
            inner.len() > (32 * line.len()).max(64 << 10),
            "{}",
            line.len()
        );
        let plan = ParsePlan::chain(
            r#"ndjson > field("payload"):base64 > gzip > ndjson"#,
            &registry(),
        )
        .unwrap();
        let mut out = Fields::new();
        let outcome = plan.parse_stateless(line.as_bytes(), &mut out);
        assert_eq!((outcome.status, outcome.layers), (Status::Parsed, 4));
        assert_eq!(
            out.get("ndjson.pad").map(|v| v.bytes.len()),
            Some(400 << 10)
        );
    }

    #[test]
    fn a_decode_over_its_cap_falls_back() {
        let mut registry = registry();
        registry
            .register(Arc::new(Decoder::new(Codec::Gzip).with_max_bytes(8)))
            .unwrap();
        let line = record(&STANDARD.encode(gzip(br#"{"user":"kay"}"#)));
        let plan = ParsePlan::chain(
            r#"ndjson > field("payload"):base64 > gzip > ndjson"#,
            &registry,
        )
        .unwrap();
        let mut out = Fields::new();
        let outcome = plan.parse_stateless(line.as_bytes(), &mut out);
        assert_eq!(outcome.status, Status::Fallback);
        assert!(
            matches!(
                outcome.error,
                Some(crate::parse::ParseError::Limit {
                    what: "decoded bytes"
                })
            ),
            "{:?}",
            outcome.error
        );
    }
}

#[cfg(all(
    feature = "decode-base64",
    feature = "decode-gzip",
    feature = "parse-ndjson",
    feature = "record"
))]
mod layered {
    use std::borrow::Cow;

    use base64::Engine;
    use base64::engine::general_purpose::STANDARD;

    use super::flate_rows::gzip;
    use crate::format;
    use crate::parse::Parsers;
    use crate::record::{LayerCache, LayerPlan, Miss, Record, Typed, Walk};

    const CHAIN: &str = r#"ndjson > field("payload"):base64 > gzip > ndjson"#;

    fn line() -> String {
        let inner = br#"{"user":"kay","tags":{"team":"ui"}}"#;
        format!(
            r#"{{"src":"s3","payload":"{}"}}"#,
            STANDARD.encode(gzip(inner))
        )
    }

    fn registry() -> Parsers {
        let mut registry = Parsers::new();
        format::register_stock(&mut registry).unwrap();
        registry
    }

    #[test]
    fn a_decoded_body_sits_at_the_decoders_place_with_no_key() {
        let layers = LayerPlan::chain(CHAIN, &registry()).unwrap();
        let line = line();
        let cache = LayerCache::new();
        let layered = layers.open(line.as_bytes(), &cache).unwrap();
        let rows: &[(&[&str], Result<&str, Miss>)] = &[
            (&["payload", "user"], Ok("kay")),
            (&["payload", "tags", "team"], Ok("ui")),
            (&["src"], Ok("s3")),
            (
                &["payload", "gzip", "ndjson", "user"],
                Err(Miss::MissingField),
            ),
            (&["payload", "nope"], Err(Miss::MissingField)),
        ];
        for (path, want) in rows {
            let got = layered.find(path).and_then(|at| layered.typed(at));
            match (want, got) {
                (Ok(text), Ok(Typed::Str(got))) => assert_eq!(got, *text, "{path:?}"),
                (Err(miss), Err(got)) => assert_eq!(got, *miss, "{path:?}"),
                (want, got) => panic!("{path:?}: want {want:?}, got {got:?}"),
            }
        }
    }

    #[test]
    fn a_walk_puts_the_decoded_values_under_the_field() {
        let layers = LayerPlan::chain(CHAIN, &registry()).unwrap();
        let line = line();
        let cache = LayerCache::new();
        let layered = layers.open(line.as_bytes(), &cache).unwrap();
        let mut stack: Vec<String> = Vec::new();
        let mut paths = Vec::new();
        layered
            .walk(|node| {
                stack.truncate(node.depth);
                stack.push(node.key.map_or_else(String::new, Cow::into_owned));
                paths.push(stack.join("."));
            })
            .unwrap();
        assert_eq!(
            paths,
            [
                "src",
                "payload",
                "payload.user",
                "payload.tags",
                "payload.tags.team"
            ],
        );
    }

    #[test]
    fn a_record_that_is_all_gzip_reads_from_its_root() {
        let layers = LayerPlan::chain("gzip > ndjson", &registry()).unwrap();
        let record = gzip(br#"{"user":"kay"}"#);
        let cache = LayerCache::new();
        let layered = layers.open(&record, &cache).unwrap();
        let got = layered.find(&["user"]).and_then(|at| layered.typed(at));
        assert!(
            matches!(got, Ok(Typed::Str(ref t)) if t == "kay"),
            "{got:?}"
        );
    }

    #[test]
    fn a_payload_that_doesnt_decode_reads_as_its_text() {
        let layers = LayerPlan::chain(CHAIN, &registry()).unwrap();
        let line = r#"{"payload":"not*base64"}"#;
        let cache = LayerCache::new();
        let layered = layers.open(line.as_bytes(), &cache).unwrap();
        let got = layered.find(&["payload"]).and_then(|at| layered.typed(at));
        assert!(
            matches!(got, Ok(Typed::Str(ref t)) if t == "not*base64"),
            "{got:?}"
        );
    }

    #[cfg(feature = "scrub")]
    #[test]
    fn a_write_back_through_a_decoder_is_refused() {
        let layers = LayerPlan::chain(CHAIN, &registry()).unwrap();
        let line = line();
        let cache = LayerCache::new();
        let layered = layers.open(line.as_bytes(), &cache).unwrap();
        let at = layered.find(&["payload", "user"]).unwrap();
        let mut out = b"kept".to_vec();
        assert_eq!(
            layered.splice(&[(at, "ray")], &mut out),
            Err(Miss::Malformed)
        );
        assert_eq!(out, b"kept");
    }
}