grippo 0.2.1

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
// Project:   grippo
// File:      src/decode/mod.rs
// Purpose:   Decoding layers: base64, hex, gzip, zlib, zstd and snappy as parsers
// 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. 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(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,
}

impl Codec {
    /// The name the stock decoder is registered under.
    #[must_use]
    pub const fn name(self) -> &'static str {
        match self {
            #[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",
        }
    }

    /// 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: codec.name().to_owned(),
            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))
            }
        }
    }
}

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));
    }
    all
}

#[cfg(test)]
mod tests;