grippo 0.3.1

Grok, regex, CEL and scrubbing on typed primitives. Up to 9 times faster than the stock Rust regex.
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
// Project:   grippo
// File:      src/decode/mod.rs
// Purpose:   Decoding layers: base64, hex, compression, UTF-16, code pages and rsyslog escapes
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! Parsers that decode their input and hand on the bytes, so a chain reads
//! `field("payload"):base64 > gzip > ndjson`.
//!
//! A [`Decoder`] writes no field. It returns [`Parsed::Decoded`], and the next
//! hop reads those bytes. Each one stops at its cap, [`DECODE_MAX_BYTES`]
//! unless built with another, and an input that would decode past it is
//! [`ParseError::Limit`] with nothing held past the cap.
//!
//! base64 and hex are grippo's own, with vector steps in the kernel module.
//! gzip and zlib run on flate2 with the zlib-rs backend, zstd on the C
//! libzstd, snappy on snap, and text in UTF-16 or a code page on `encoding_rs`.
//! The rsyslog layer puts back the control characters rsyslog escaped. Each
//! sits behind its own `decode-*` feature, off by default. `auto` finds gzip,
//! zstd and framed snappy by their magic bytes. The rest run only when named.

use crate::parse::{DECODE_MAX_BYTES, Decoded, FieldSink, ParseError, Parsed, Parser};
use crate::strmatch::Signature;
use crate::tier::MatcherTier;

#[cfg(feature = "decode-text")]
use crate::charset::{Charset, Malformed, Transcoder};
#[cfg(feature = "decode-rsyslog")]
mod rsyslog;
#[cfg(feature = "decode-rsyslog")]
pub use rsyslog::Escaped;

#[cfg(any(
    feature = "decode-gzip",
    feature = "decode-zlib",
    feature = "decode-zstd",
    feature = "decode-snappy"
))]
use std::io::Read;

/// What a decoder reads.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Codec {
    /// Base64 text, RFC 4648. Padding is optional and bits left over in the
    /// last symbol must be zero.
    #[cfg(feature = "decode-base64")]
    Base64 {
        /// The `-` and `_` alphabet in place of `+` and `/`.
        url_safe: bool,
        /// Pass over ASCII whitespace, as in line-wrapped text. It decodes
        /// a byte at a time, where text with none goes 16 to 64 symbols a step.
        skip_whitespace: bool,
    },
    /// Hex digits, upper or lower case, two to a byte.
    #[cfg(feature = "decode-hex")]
    Hex,
    /// A gzip stream, RFC 1952. Members back to back decode as one.
    #[cfg(feature = "decode-gzip")]
    Gzip,
    /// A zlib stream, RFC 1950.
    #[cfg(feature = "decode-zlib")]
    Zlib,
    /// zstd frames, RFC 8878. Frames back to back decode as one.
    #[cfg(feature = "decode-zstd")]
    Zstd,
    /// The snappy framing format, opening with its stream identifier.
    #[cfg(feature = "decode-snappy")]
    Snappy,
    /// One raw snappy block, with no framing.
    #[cfg(feature = "decode-snappy")]
    SnappyRaw,
    /// Text in a [`Charset`], read to UTF-8. A byte order mark that names the
    /// charset is dropped, and bytes that don't decode become U+FFFD, so
    /// text with a lone UTF-16 surrogate still decodes around it. Nothing
    /// here is `Malformed`.
    #[cfg(feature = "decode-text")]
    Text(Charset),
    /// The control characters rsyslog escaped on receive, put back. Where
    /// the escape was a literal in the original text it reads as the
    /// control character, as rsyslog's own output can't tell them apart.
    #[cfg(feature = "decode-rsyslog")]
    Rsyslog {
        /// rsyslog's `parser.controlCharacterEscapePrefix`: `#` unless set
        /// otherwise.
        prefix: u8,
        /// Which escapes to read back.
        escaped: Escaped,
    },
}

/// The name a decoder of `charset` is registered under: `utf8`, `utf16le`
/// and `utf16be`, else `charset`, which [`Decoder::new`] extends with the
/// charset's name, `charset:windows-1252`.
#[cfg(feature = "decode-text")]
fn text_name(charset: Charset) -> &'static str {
    if charset == Charset::UTF_8 {
        "utf8"
    } else if charset == Charset::UTF_16LE {
        "utf16le"
    } else if charset == Charset::UTF_16BE {
        "utf16be"
    } else {
        "charset"
    }
}

impl Codec {
    /// The name the stock decoder is registered under. A code page with no
    /// stock name is `charset` here, and `charset:` and its lower-case label
    /// on the [`Decoder`].
    #[must_use]
    #[allow(
        clippy::missing_const_for_fn,
        reason = "a charset's name reads from a table at run time"
    )]
    pub fn name(self) -> &'static str {
        match self {
            #[cfg(feature = "decode-text")]
            Self::Text(charset) => text_name(charset),
            #[cfg(feature = "decode-rsyslog")]
            Self::Rsyslog { .. } => "rsyslog",
            #[cfg(feature = "decode-base64")]
            Self::Base64 {
                url_safe: false, ..
            } => "base64",
            #[cfg(feature = "decode-base64")]
            Self::Base64 { url_safe: true, .. } => "base64url",
            #[cfg(feature = "decode-hex")]
            Self::Hex => "hex",
            #[cfg(feature = "decode-gzip")]
            Self::Gzip => "gzip",
            #[cfg(feature = "decode-zlib")]
            Self::Zlib => "zlib",
            #[cfg(feature = "decode-zstd")]
            Self::Zstd => "zstd",
            #[cfg(feature = "decode-snappy")]
            Self::Snappy => "snappy",
            #[cfg(feature = "decode-snappy")]
            Self::SnappyRaw => "snappy_raw",
        }
    }

    /// Why an input didn't decode, for a codec that can't say where.
    const fn broken(self) -> &'static str {
        match self {
            #[cfg(feature = "decode-base64")]
            Self::Base64 { .. } => "not base64",
            #[cfg(feature = "decode-hex")]
            Self::Hex => "not hex",
            #[cfg(feature = "decode-gzip")]
            Self::Gzip => "not a whole gzip stream",
            #[cfg(feature = "decode-zlib")]
            Self::Zlib => "not a whole zlib stream",
            #[cfg(feature = "decode-zstd")]
            Self::Zstd => "not whole zstd frames, or a window over the cap",
            #[cfg(feature = "decode-snappy")]
            Self::Snappy => "not a whole snappy stream",
            #[cfg(feature = "decode-snappy")]
            Self::SnappyRaw => "not a whole snappy block",
            #[cfg(feature = "decode-text")]
            Self::Text(_) => "not text this charset reads",
            #[cfg(feature = "decode-rsyslog")]
            Self::Rsyslog { .. } => "not text rsyslog wrote",
        }
    }

    /// The bytes every input opens with, for a format that has them.
    const fn magic(self) -> Option<&'static [u8]> {
        match self {
            #[cfg(feature = "decode-gzip")]
            Self::Gzip => Some(b"\x1f\x8b\x08"),
            #[cfg(feature = "decode-zstd")]
            Self::Zstd => Some(b"\x28\xb5\x2f\xfd"),
            #[cfg(feature = "decode-snappy")]
            Self::Snappy => Some(b"\xff\x06\x00\x00sNaPpY"),
            #[allow(unreachable_patterns, reason = "every arm may be compiled out")]
            _ => None,
        }
    }
}

/// A decoding layer, registered under its codec's name unless renamed.
#[derive(Debug, Clone)]
pub struct Decoder {
    codec: Codec,
    name: String,
    max_bytes: usize,
    signature: Signature,
}

impl Decoder {
    /// A decoder for `codec`, named as [`Codec::name`] says, with the cap
    /// [`DECODE_MAX_BYTES`].
    ///
    /// # Panics
    ///
    /// Never: a signature of fixed literals, or of none, always builds.
    #[must_use]
    pub fn new(codec: Codec) -> Self {
        let builder = Signature::builder();
        let builder = match codec.magic() {
            Some(magic) => builder.anchored([magic]),
            None => builder,
        };
        let signature = builder
            .build()
            .unwrap_or_else(|_| unreachable!("invariant: a fixed signature builds"));
        Self {
            codec,
            name: registered_name(codec),
            max_bytes: DECODE_MAX_BYTES,
            signature,
        }
    }

    /// The same decoder under `name`, such as `base64:wrapped`, to register
    /// beside the stock one.
    #[must_use]
    pub fn named(mut self, name: impl Into<String>) -> Self {
        self.name = name.into();
        self
    }

    /// The same decoder with `max_bytes` as its cap.
    #[must_use]
    pub const fn with_max_bytes(mut self, max_bytes: usize) -> Self {
        self.max_bytes = max_bytes;
        self
    }

    /// What it reads.
    #[must_use]
    pub const fn codec(&self) -> Codec {
        self.codec
    }

    /// The most bytes it writes for one input.
    #[must_use]
    pub const fn max_bytes(&self) -> usize {
        self.max_bytes
    }

    /// Appends `input` decoded to `out`, which is left as it was on an error.
    ///
    /// # Errors
    ///
    /// [`ParseError::Malformed`] when `input` isn't this codec's, and
    /// [`ParseError::Limit`] when it decodes to more than the cap.
    pub fn decode(&self, input: &[u8], out: &mut Vec<u8>) -> Result<(), ParseError> {
        let cap = self.max_bytes;
        if let Some(magic) = self.codec.magic()
            && !input.starts_with(magic)
        {
            return Err(malformed(self.codec));
        }
        match self.codec {
            #[cfg(feature = "decode-base64")]
            Codec::Base64 {
                url_safe,
                skip_whitespace,
            } => {
                use crate::kernel::base64::{Failure, STANDARD, URL_SAFE, decode};
                let alphabet = if url_safe { &URL_SAFE } else { &STANDARD };
                decode(alphabet, input, skip_whitespace, out, cap).map_err(|f| match f {
                    Failure::Malformed { offset, reason } => {
                        ParseError::Malformed { offset, reason }
                    }
                    Failure::Limit => limit(),
                })
            }
            #[cfg(feature = "decode-hex")]
            Codec::Hex => {
                use crate::kernel::hex::{Failure, decode};
                decode(input, out, cap).map_err(|f| match f {
                    Failure::Malformed { offset, reason } => {
                        ParseError::Malformed { offset, reason }
                    }
                    Failure::Limit => limit(),
                })
            }
            #[cfg(feature = "decode-gzip")]
            Codec::Gzip => read_capped(
                flate2::bufread::MultiGzDecoder::new(input),
                input.len(),
                out,
                cap,
                self.codec,
            ),
            #[cfg(feature = "decode-zlib")]
            Codec::Zlib => read_capped(
                flate2::bufread::ZlibDecoder::new(input),
                input.len(),
                out,
                cap,
                self.codec,
            ),
            #[cfg(feature = "decode-zstd")]
            Codec::Zstd => {
                let mut reader = zstd::stream::read::Decoder::with_buffer(input)
                    .map_err(|_| malformed(self.codec))?;
                reader
                    .window_log_max(window_log(cap))
                    .map_err(|_| malformed(self.codec))?;
                read_capped(reader, input.len(), out, cap, self.codec)
            }
            #[cfg(feature = "decode-snappy")]
            Codec::Snappy => read_capped(
                snap::read::FrameDecoder::new(input),
                input.len(),
                out,
                cap,
                self.codec,
            ),
            #[cfg(feature = "decode-snappy")]
            Codec::SnappyRaw => {
                let len = snap::raw::decompress_len(input).map_err(|_| malformed(self.codec))?;
                if len > cap {
                    return Err(limit());
                }
                let start = out.len();
                out.resize(start + len, 0);
                let wrote = snap::raw::Decoder::new().decompress(input, &mut out[start..]);
                out.truncate(start + wrote.as_ref().map_or(0, |n| *n));
                wrote.map(|_| ()).map_err(|_| malformed(self.codec))
            }
            #[cfg(feature = "decode-text")]
            Codec::Text(charset) => decode_text(charset, input, out, cap, self.codec),
            #[cfg(feature = "decode-rsyslog")]
            Codec::Rsyslog { prefix, escaped } => {
                if rsyslog::decode(prefix, escaped, input, out, cap) {
                    Ok(())
                } else {
                    Err(limit())
                }
            }
        }
    }
}

/// The name `codec`'s decoder is registered under.
fn registered_name(codec: Codec) -> String {
    #[cfg(feature = "decode-text")]
    if let Codec::Text(charset) = codec
        && codec.name() == "charset"
    {
        return format!("charset:{}", charset.name().to_ascii_lowercase());
    }
    codec.name().to_owned()
}

/// Input bytes a text decode takes a step, so the cap is checked after at most
/// three times that in output.
#[cfg(feature = "decode-text")]
const TEXT_STEP: usize = 8192;

/// `input` read in `charset` and appended to `out`, with U+FFFD for what
/// doesn't decode.
#[cfg(feature = "decode-text")]
fn decode_text(
    charset: Charset,
    input: &[u8],
    out: &mut Vec<u8>,
    cap: usize,
    codec: Codec,
) -> Result<(), ParseError> {
    let start = out.len();
    let mut transcoder = Transcoder::new(charset, Malformed::Replace);
    let mut steps = input.chunks(TEXT_STEP);
    let mut next = steps.next();
    loop {
        let step = next.unwrap_or_default();
        next = steps.next();
        let last = next.is_none();
        if transcoder.push(step, last, out).is_err() {
            out.truncate(start);
            return Err(malformed(codec));
        }
        if out.len() - start > cap {
            out.truncate(start);
            return Err(limit());
        }
        if last {
            return Ok(());
        }
    }
}

const fn limit() -> ParseError {
    ParseError::Limit {
        what: "decoded bytes",
    }
}

const fn malformed(codec: Codec) -> ParseError {
    ParseError::Malformed {
        offset: 0,
        reason: codec.broken(),
    }
}

/// zstd's window bound for `cap`: the power of two at or above it, from
/// zstd's least window of 1 KiB to its greatest of 2 GiB.
#[cfg(feature = "decode-zstd")]
fn window_log(cap: usize) -> u32 {
    cap.next_power_of_two().trailing_zeros().clamp(10, 31)
}

/// The first room a stream decoder gets, as a multiple of its input.
#[cfg(any(
    feature = "decode-gzip",
    feature = "decode-zlib",
    feature = "decode-zstd",
    feature = "decode-snappy"
))]
const FIRST_ROOM_PER_INPUT_BYTE: usize = 4;

/// Reads `reader` to its end onto `out`, growing `out` by doubling, never
/// past `cap` bytes and one more to see an overrun.
#[cfg(any(
    feature = "decode-gzip",
    feature = "decode-zlib",
    feature = "decode-zstd",
    feature = "decode-snappy"
))]
fn read_capped(
    mut reader: impl Read,
    input_len: usize,
    out: &mut Vec<u8>,
    cap: usize,
    codec: Codec,
) -> Result<(), ParseError> {
    let start = out.len();
    let end = start.saturating_add(cap).saturating_add(1);
    let mut len = start;
    loop {
        if len == out.len() {
            let room = (len - start)
                .max(input_len.saturating_mul(FIRST_ROOM_PER_INPUT_BYTE))
                .max(4096);
            let grown = len.saturating_add(room).min(end);
            if grown == len {
                break;
            }
            out.reserve_exact(grown - len);
            out.resize(grown, 0);
        }
        match reader.read(&mut out[len..]) {
            Ok(0) => break,
            Ok(n) => len += n,
            Err(_) => {
                out.truncate(start);
                return Err(malformed(codec));
            }
        }
    }
    out.truncate(len);
    if len - start > cap {
        out.truncate(start);
        return Err(limit());
    }
    Ok(())
}

impl Parser for Decoder {
    fn name(&self) -> &str {
        &self.name
    }

    fn tier(&self) -> MatcherTier {
        MatcherTier::Fixed
    }

    fn signature(&self) -> &Signature {
        &self.signature
    }

    fn decodes(&self) -> bool {
        true
    }

    fn parse<'a>(
        &self,
        input: &'a [u8],
        out: &mut dyn FieldSink<'a>,
    ) -> Result<Parsed, ParseError> {
        let _ = out;
        if self.codec.magic().is_some_and(|m| !input.starts_with(m)) {
            return Ok(Parsed::NoMatch);
        }
        let mut bytes = Vec::new();
        self.decode(input, &mut bytes)?;
        Ok(Parsed::Decoded(Decoded::new(bytes)))
    }
}

/// A stock decoder for every codec this build enables.
#[must_use]
#[allow(
    unused_mut,
    clippy::vec_init_then_push,
    reason = "each push sits behind its own feature"
)]
pub fn stock() -> Vec<Decoder> {
    let mut all = Vec::new();
    #[cfg(feature = "decode-base64")]
    {
        all.push(Decoder::new(Codec::Base64 {
            url_safe: false,
            skip_whitespace: false,
        }));
        all.push(Decoder::new(Codec::Base64 {
            url_safe: true,
            skip_whitespace: false,
        }));
    }
    #[cfg(feature = "decode-hex")]
    all.push(Decoder::new(Codec::Hex));
    #[cfg(feature = "decode-gzip")]
    all.push(Decoder::new(Codec::Gzip));
    #[cfg(feature = "decode-zlib")]
    all.push(Decoder::new(Codec::Zlib));
    #[cfg(feature = "decode-zstd")]
    all.push(Decoder::new(Codec::Zstd));
    #[cfg(feature = "decode-snappy")]
    {
        all.push(Decoder::new(Codec::Snappy));
        all.push(Decoder::new(Codec::SnappyRaw));
    }
    #[cfg(feature = "decode-text")]
    {
        for charset in [Charset::UTF_8, Charset::UTF_16LE, Charset::UTF_16BE] {
            all.push(Decoder::new(Codec::Text(charset)));
        }
        if let Some(charset) = Charset::for_label("windows-1252") {
            all.push(Decoder::new(Codec::Text(charset)));
        }
    }
    #[cfg(feature = "decode-rsyslog")]
    all.push(Decoder::new(Codec::Rsyslog {
        prefix: b'#',
        escaped: Escaped::Controls,
    }));
    all
}

// Clippy reads a bare `cfg(test)` as test code, so the feature gates sit apart.
#[cfg(test)]
#[cfg(any(
    feature = "decode-base64",
    feature = "decode-hex",
    feature = "decode-gzip",
    feature = "decode-zlib",
    feature = "decode-zstd",
    feature = "decode-snappy"
))]
mod tests;

#[cfg(test)]
#[cfg(any(feature = "decode-text", feature = "decode-rsyslog"))]
mod text_tests;