grippo 0.2.0

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
// Project:   grippo
// File:      src/kernel/tests.rs
// Purpose:   Tests for the kernel: every tier against the byte loop, and base64 and hex
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

use proptest::prelude::*;

use super::ByteClass;

/// The run by every path this host can take: the dispatching one, and each
/// vector tier called directly with the byte loop after it.
fn runs(class: &ByteClass, h: &[u8]) -> Vec<(&'static str, usize)> {
    let mut all = vec![("dispatch", class.run(h))];
    #[cfg(target_arch = "x86_64")]
    let tiers = super::x86::tiers();
    #[cfg(all(
        target_arch = "aarch64",
        target_endian = "little",
        target_feature = "neon"
    ))]
    let tiers = super::neon::tiers();
    #[cfg(not(any(
        target_arch = "x86_64",
        all(
            target_arch = "aarch64",
            target_endian = "little",
            target_feature = "neon"
        )
    )))]
    let tiers: Vec<(&'static str, fn(&[u8; 16], &[u8]) -> usize)> = Vec::new();
    for (name, tier) in tiers {
        let at = tier(&class.low, h);
        // A tier stops at a non-member or where the last whole step ends.
        assert!(at <= h.len(), "{name} went past the slice");
        assert!(
            at == h.len() - h.len() % 16 || !class.has(h[at]),
            "{name} stopped at a member before its last whole step"
        );
        all.push((name, at + class.run_by_table(&h[at..])));
    }
    all
}

/// The reference: a bit test a byte, written apart from the kernel's own.
fn reference(ascii: u128, h: &[u8]) -> usize {
    h.iter()
        .take_while(|&&b| b < 0x80 && ascii >> b & 1 == 1)
        .count()
}

fn agrees(ascii: u128, h: &[u8]) {
    let class = ByteClass::new(ascii);
    let want = reference(ascii, h);
    assert_eq!(class.run_by_table(h), want, "table on {h:?}");
    for (name, got) in runs(&class, h) {
        assert_eq!(got, want, "{name} on {h:?} with set {ascii:#x}");
    }
}

#[cfg(target_arch = "x86_64")]
#[test]
fn a_cpu_with_a_tier_takes_whole_steps_by_vector() {
    // Every run test passes on the table alone, so this is the one that
    // fails if the dispatcher stops handing whole steps to a tier.
    let class = ByteClass::new(u128::MAX);
    let members = [b'a'; 80];
    let by_vector = super::x86::whole_steps(&class.low, &members);
    if std::arch::is_x86_feature_detected!("ssse3") {
        assert_eq!(by_vector, 80);
    } else {
        assert_eq!(by_vector, 0);
    }
    // A non-member inside a step stops the steps there.
    let mut broken = members;
    broken[41] = b' ';
    let class = ByteClass::new(!(1 << b' '));
    let stopped = super::x86::whole_steps(&class.low, &broken);
    assert!(stopped == 41 || stopped == 0, "{stopped}");
}

#[cfg(all(
    target_arch = "aarch64",
    target_endian = "little",
    target_feature = "neon"
))]
#[test]
fn an_aarch64_cpu_takes_whole_steps_by_vector() {
    // Every run test passes on the table alone, so this is the one that
    // fails if the run stops handing whole steps to the tier.
    let class = ByteClass::new(u128::MAX);
    let members = [b'a'; 80];
    assert_eq!(super::neon::run_steps(&class.low, &members), 80);
    let mut broken = members;
    broken[41] = b' ';
    let class = ByteClass::new(!(1 << b' '));
    assert_eq!(super::neon::run_steps(&class.low, &broken), 41);
}

#[test]
fn every_byte_at_every_place_of_a_step_and_its_tail() {
    let sets = [
        0_u128,
        u128::MAX,
        1 << b'a',
        !(1 << b' '),
        (1 << 0x7F) | 1,
        0x5555_5555_5555_5555_5555_5555_5555_5555,
    ];
    for ascii in sets {
        for len in [0, 1, 15, 16, 17, 31, 32, 33, 47, 48, 63, 64, 65] {
            // A member everywhere, then each byte value at each place.
            let member = (0..128_u8).find(|&b| ascii >> b & 1 == 1);
            let fill = member.unwrap_or(b'x');
            agrees(ascii, &vec![fill; len]);
            for at in 0..len {
                for byte in 0..=255_u8 {
                    let mut h = vec![fill; len];
                    h[at] = byte;
                    agrees(ascii, &h);
                }
            }
        }
    }
}

#[test]
fn a_class_holds_the_bytes_its_bits_name() {
    let class = ByteClass::new((1 << b'0') | (1 << b'z') | (1 << 0x7F));
    for byte in 0..=255_u8 {
        let want = matches!(byte, b'0' | b'z' | 0x7F);
        assert_eq!(class.has(byte), want, "{byte:#x}");
    }
}

proptest! {
    #![proptest_config(ProptestConfig::with_cases(2000))]

    #[test]
    fn a_run_is_the_byte_loops_run(
        halves in any::<(u64, u64)>(),
        before in proptest::collection::vec(any::<u8>(), 0..40),
        body in proptest::collection::vec(any::<u8>(), 0..300),
        dense in any::<bool>(),
    ) {
        let ascii = u128::from(halves.0) << 64 | u128::from(halves.1);
        // A dense body is mostly members, so runs cross step ends.
        let member = (0..128_u8).find(|&b| ascii >> b & 1 == 1).unwrap_or(0);
        let body: Vec<u8> = body
            .iter()
            .enumerate()
            .map(|(i, &b)| if dense && i % 37 != 36 { member } else { b })
            .collect();
        agrees(ascii, &body);
        // The same bytes at another offset of a longer buffer.
        let mut longer = before.clone();
        longer.extend_from_slice(&body);
        agrees(ascii, &longer[before.len()..]);
    }
}

#[cfg(feature = "decode-base64")]
mod base64_steps {
    //! Every base64 tier against the table loop and the `base64` crate.

    use base64::Engine;
    use base64::alphabet;
    use base64::engine::{DecodePaddingMode, GeneralPurpose, GeneralPurposeConfig};
    use proptest::prelude::*;

    use crate::kernel::base64::{Alphabet, Failure, STANDARD, URL_SAFE, by_table, decode};

    /// The crate's decoder with the kernel's rules: padding optional, no
    /// bits left over.
    fn engine(url_safe: bool) -> GeneralPurpose {
        let config = GeneralPurposeConfig::new()
            .with_encode_padding(true)
            .with_decode_padding_mode(DecodePaddingMode::Indifferent);
        let alphabet = if url_safe {
            &alphabet::URL_SAFE
        } else {
            &alphabet::STANDARD
        };
        GeneralPurpose::new(alphabet, config)
    }

    fn kernel(url_safe: bool) -> &'static Alphabet {
        if url_safe { &URL_SAFE } else { &STANDARD }
    }

    #[cfg(target_arch = "x86_64")]
    fn tiers() -> Vec<(&'static str, crate::kernel::base64::x86::Tier)> {
        crate::kernel::base64::x86::tiers()
    }

    #[cfg(all(
        target_arch = "aarch64",
        target_endian = "little",
        target_feature = "neon"
    ))]
    fn tiers() -> Vec<(&'static str, crate::kernel::base64::neon::Tier)> {
        crate::kernel::base64::neon::tiers()
    }

    #[cfg(not(any(
        target_arch = "x86_64",
        all(
            target_arch = "aarch64",
            target_endian = "little",
            target_feature = "neon"
        )
    )))]
    fn tiers() -> Vec<(&'static str, fn(&Alphabet, &[u8], &mut Vec<u8>) -> usize)> {
        Vec::new()
    }

    /// `text` decoded every way this host can: by the dispatcher, by the
    /// table loop alone, and by each vector tier with the table loop after it.
    fn every_way(
        alphabet: &Alphabet,
        text: &[u8],
    ) -> Vec<(&'static str, Result<Vec<u8>, Failure>)> {
        let mut out = Vec::new();
        let dispatch = decode(alphabet, text, false, &mut out, usize::MAX).map(|()| out);
        let mut out = Vec::new();
        let table = by_table(alphabet, text, false, 0, &mut out, usize::MAX).map(|()| out);
        let mut all = vec![("dispatch", dispatch), ("table", table)];
        let padding = text
            .iter()
            .rev()
            .take(2)
            .take_while(|&&b| b == b'=')
            .count();
        let symbols = &text[..text.len() - padding];
        for (name, tier) in tiers() {
            let mut out = Vec::new();
            let taken = tier(alphabet, symbols, &mut out);
            assert!(
                taken <= symbols.len() && taken % 16 == 0,
                "{name} took {taken}"
            );
            assert_eq!(out.len(), taken / 4 * 3, "{name} wrote past what it took");
            let rest = by_table(alphabet, &text[taken..], false, taken, &mut out, usize::MAX);
            all.push((name, rest.map(|()| out)));
        }
        all
    }

    /// Every way agrees with the table loop exactly, and with the crate on
    /// whether `text` decodes and to what.
    fn agrees(url_safe: bool, text: &[u8]) {
        let ways = every_way(kernel(url_safe), text);
        let table = ways[1].1.clone();
        for (name, got) in &ways {
            assert_eq!(got, &table, "{name} on {text:?}");
        }
        let want = engine(url_safe).decode(text);
        assert_eq!(
            table.as_ref().ok(),
            want.as_ref().ok(),
            "the crate on {text:?}: {want:?}"
        );
    }

    #[test]
    fn every_symbol_of_each_alphabet_decodes_in_every_lane() {
        // 0, 4, 8 .. 252 encode to every symbol at least once, in each place
        // of a group of four.
        let bytes: Vec<u8> = (0..=255_u8).step_by(4).chain((0..=255_u8).rev()).collect();
        for url_safe in [false, true] {
            let text = engine(url_safe).encode(&bytes);
            let alphabet = if url_safe {
                b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
            } else {
                b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
            };
            assert!(alphabet.iter().all(|s| text.as_bytes().contains(s)));
            for (name, got) in every_way(kernel(url_safe), text.as_bytes()) {
                assert_eq!(got.as_deref().ok(), Some(bytes.as_slice()), "{name}");
            }
        }
    }

    #[cfg(target_arch = "x86_64")]
    #[test]
    fn a_cpu_with_a_tier_takes_whole_steps_by_vector() {
        // Every agreement test passes on the table loop alone, so this is the
        // one that fails if the dispatcher stops handing steps to a tier.
        let text = engine(false).encode([7_u8; 96]);
        let mut out = Vec::new();
        let taken = crate::kernel::base64::x86::steps(&STANDARD, text.as_bytes(), &mut out);
        if std::arch::is_x86_feature_detected!("ssse3") {
            assert_eq!(taken, 128);
            assert_eq!(out, [7_u8; 96]);
        } else {
            assert_eq!(taken, 0);
        }
    }

    /// Mostly symbols of the standard alphabet, now and then a byte that
    /// breaks the text, or belongs to the other alphabet.
    fn text() -> impl Strategy<Value = Vec<u8>> {
        let byte = prop_oneof![
            40 => proptest::sample::select(
                b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".to_vec()
            ),
            1 => proptest::sample::select(b"=-_ \n*\x80\xff\x00".to_vec()),
        ];
        proptest::collection::vec(byte, 0..300)
    }

    proptest! {
        #![proptest_config(ProptestConfig::with_cases(3000))]

        #[test]
        fn encoded_bytes_decode_back(
            bytes in proptest::collection::vec(any::<u8>(), 0..400),
            url_safe in any::<bool>(),
            padded in any::<bool>(),
        ) {
            let mut text = engine(url_safe).encode(&bytes).into_bytes();
            if !padded {
                text.retain(|&b| b != b'=');
            }
            for (name, got) in every_way(kernel(url_safe), &text) {
                prop_assert_eq!(got.as_deref().ok(), Some(bytes.as_slice()), "{}", name);
            }
        }

        #[test]
        fn any_text_agrees_with_the_table_loop_and_the_crate(
            text in text(),
            url_safe in any::<bool>(),
        ) {
            agrees(url_safe, &text);
        }

        #[test]
        fn one_bad_byte_in_long_text_is_found_where_it_is(
            bytes in proptest::collection::vec(any::<u8>(), 48..400),
            at in any::<proptest::sample::Index>(),
            bad in proptest::sample::select(b"=*\x80\xff\n".to_vec()),
        ) {
            let mut text = engine(false).encode(&bytes).into_bytes();
            let at = at.index(text.len() - 2);
            text[at] = bad;
            agrees(false, &text);
            let mut out = Vec::new();
            prop_assert!(decode(&STANDARD, &text, false, &mut out, usize::MAX).is_err());
        }

        #[test]
        fn whitespace_anywhere_is_skipped_when_asked(
            bytes in proptest::collection::vec(any::<u8>(), 0..300),
            spaces in proptest::collection::vec(
                (any::<proptest::sample::Index>(), proptest::sample::select(b" \t\r\n\x0c".to_vec())),
                0..20,
            ),
        ) {
            let mut text = engine(false).encode(&bytes).into_bytes();
            for (at, space) in spaces {
                let at = at.index(text.len() + 1);
                text.insert(at, space);
            }
            let mut out = Vec::new();
            prop_assert_eq!(decode(&STANDARD, &text, true, &mut out, usize::MAX), Ok(()));
            prop_assert_eq!(out, bytes);
        }

        #[test]
        fn a_cap_stops_at_its_byte(
            bytes in proptest::collection::vec(any::<u8>(), 0..300),
            cap in 0_usize..320,
            skip in any::<bool>(),
        ) {
            let text = engine(false).encode(&bytes);
            let mut out = b"kept".to_vec();
            let got = decode(&STANDARD, text.as_bytes(), skip, &mut out, cap);
            if bytes.len() > cap {
                prop_assert_eq!(got, Err(Failure::Limit));
                prop_assert_eq!(out, b"kept");
            } else {
                prop_assert_eq!(got, Ok(()));
                prop_assert_eq!(&out[4..], bytes.as_slice());
            }
        }
    }
}

#[cfg(feature = "decode-hex")]
mod hex_steps {
    //! Every hex tier against the table loop and a per-pair reference.

    use proptest::prelude::*;

    use crate::kernel::hex::{Failure, by_table, decode};

    #[cfg(target_arch = "x86_64")]
    fn tiers() -> Vec<(&'static str, crate::kernel::hex::x86::Tier)> {
        crate::kernel::hex::x86::tiers()
    }

    #[cfg(all(
        target_arch = "aarch64",
        target_endian = "little",
        target_feature = "neon"
    ))]
    fn tiers() -> Vec<(&'static str, crate::kernel::hex::neon::Tier)> {
        crate::kernel::hex::neon::tiers()
    }

    #[cfg(not(any(
        target_arch = "x86_64",
        all(
            target_arch = "aarch64",
            target_endian = "little",
            target_feature = "neon"
        )
    )))]
    fn tiers() -> Vec<(&'static str, fn(&[u8], &mut [u8]) -> usize)> {
        Vec::new()
    }

    /// The bytes, or the offset of the first byte that isn't a digit, read a
    /// pair at a time apart from the kernel. `from_str_radix` takes a leading
    /// `+`, so each byte is checked first.
    fn reference(text: &[u8]) -> Result<Vec<u8>, usize> {
        if !text.len().is_multiple_of(2) {
            return Err(text.len());
        }
        let mut out = Vec::new();
        for (i, pair) in text.chunks(2).enumerate() {
            if let Some(j) = pair.iter().position(|b| !b.is_ascii_hexdigit()) {
                return Err(2 * i + j);
            }
            let pair = std::str::from_utf8(pair).unwrap();
            out.push(u8::from_str_radix(pair, 16).unwrap());
        }
        Ok(out)
    }

    fn agrees(text: &[u8]) {
        let want = reference(text);
        let mut out = Vec::new();
        let got = decode(text, &mut out, usize::MAX).map(|()| out);
        let mut ways = vec![("dispatch", got)];
        if text.len().is_multiple_of(2) {
            for (name, tier) in tiers() {
                let mut out = vec![0; text.len() / 2];
                let taken = tier(text, &mut out);
                assert!(
                    taken <= text.len() && taken % 32 == 0,
                    "{name} took {taken}"
                );
                let rest = by_table(&text[taken..], &mut out[taken / 2..], taken);
                ways.push((name, rest.map(|()| out)));
            }
        }
        for (name, got) in ways {
            match (&want, got) {
                (Ok(bytes), Ok(got)) => assert_eq!(&got, bytes, "{name} on {text:?}"),
                (Err(offset), Err(Failure::Malformed { offset: got, .. })) => {
                    assert_eq!(got, *offset, "{name} on {text:?}");
                }
                (want, got) => panic!("{name} on {text:?}: want {want:?}, got {got:?}"),
            }
        }
    }

    #[cfg(target_arch = "x86_64")]
    #[test]
    fn a_cpu_with_a_tier_takes_whole_steps_by_vector() {
        let text = b"0123456789abcdefABCDEF".repeat(6);
        let mut out = vec![0; 64];
        let taken = crate::kernel::hex::x86::steps(&text[..128], &mut out);
        if std::arch::is_x86_feature_detected!("ssse3") {
            assert_eq!(taken, 128);
            assert_eq!(Ok(out), reference(&text[..128]));
        } else {
            assert_eq!(taken, 0);
        }
    }

    fn hex_text(bytes: &[u8], upper: bool) -> String {
        use std::fmt::Write;
        bytes.iter().fold(String::new(), |mut text, b| {
            let _ = if upper {
                write!(text, "{b:02X}")
            } else {
                write!(text, "{b:02x}")
            };
            text
        })
    }

    fn text() -> impl Strategy<Value = Vec<u8>> {
        let byte = prop_oneof![
            40 => proptest::sample::select(b"0123456789abcdefABCDEF".to_vec()),
            1 => proptest::sample::select(b"gG+ /:@`\x80\xff\x00".to_vec()),
        ];
        proptest::collection::vec(byte, 0..300)
    }

    proptest! {
        #![proptest_config(ProptestConfig::with_cases(3000))]

        #[test]
        fn any_text_agrees_with_the_reference(text in text()) {
            agrees(&text);
        }

        #[test]
        fn encoded_bytes_decode_back(
            bytes in proptest::collection::vec(any::<u8>(), 0..300),
            upper in any::<bool>(),
        ) {
            let text = hex_text(&bytes, upper);
            agrees(text.as_bytes());
            let mut out = Vec::new();
            prop_assert_eq!(decode(text.as_bytes(), &mut out, bytes.len()), Ok(()));
            prop_assert_eq!(out, bytes);
        }

        #[test]
        fn a_cap_stops_at_its_byte(
            bytes in proptest::collection::vec(any::<u8>(), 0..200),
            cap in 0_usize..220,
        ) {
            let text = hex_text(&bytes, false);
            let mut out = b"kept".to_vec();
            let got = decode(text.as_bytes(), &mut out, cap);
            if bytes.len() > cap {
                prop_assert_eq!(got, Err(Failure::Limit));
                prop_assert_eq!(out, b"kept");
            } else {
                prop_assert_eq!(got, Ok(()));
                prop_assert_eq!(&out[4..], bytes.as_slice());
            }
        }
    }
}