grippo 0.3.1

Grok, regex, CEL and scrubbing on typed primitives. Up to 9 times faster than the stock Rust regex.
Documentation
// Project:   grippo
// File:      src/decode/rsyslog.rs
// Purpose:   rsyslog's escaped control characters put back
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! rsyslog's `escapeControlCharactersOnReceive` replaces each byte below 0x20
//! with its prefix and three octal digits: a tab is `#011`, a line feed `#012`,
//! a carriage return `#015`. `escape8BitCharactersOnReceive` does the same
//! for each byte from 0x80. A byte from 0x20 to 0x7F is never escaped, so
//! `#064` is the text it looks like.

/// Which of rsyslog's escapes a decoder reads back.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Escaped {
    /// Bytes below 0x20, which rsyslog escapes unless told not to.
    Controls,
    /// Those and bytes from 0x80, which rsyslog escapes when
    /// `escape8BitCharactersOnReceive` is on: an e acute is `#303#251`.
    ControlsAndHigh,
}

/// Appends `input` to `out` with each escape written as its byte, and
/// returns `true`. When that is more than `cap` bytes `out` is left as it was
/// and the result is `false`.
pub(super) fn decode(
    prefix: u8,
    escaped: Escaped,
    input: &[u8],
    out: &mut Vec<u8>,
    cap: usize,
) -> bool {
    let start = out.len();
    out.reserve(input.len().min(cap.saturating_add(1)));
    let mut from = 0;
    for at in memchr::memchr_iter(prefix, input) {
        if at < from {
            continue;
        }
        let Some(byte) = escape_at(input, at, escaped) else {
            continue;
        };
        out.extend_from_slice(&input[from..at]);
        out.push(byte);
        from = at + 4;
    }
    out.extend_from_slice(&input[from..]);
    if out.len() - start > cap {
        out.truncate(start);
        return false;
    }
    true
}

/// The byte the escape at `input[at]` stands for, when three octal digits
/// follow and they name a byte rsyslog escapes.
fn escape_at(input: &[u8], at: usize, escaped: Escaped) -> Option<u8> {
    let digits = input.get(at + 1..at + 4)?;
    let mut value = 0_u16;
    for &digit in digits {
        if !(b'0'..=b'7').contains(&digit) {
            return None;
        }
        value = value * 8 + u16::from(digit - b'0');
    }
    let byte = u8::try_from(value).ok()?;
    match (byte, escaped) {
        (..0x20, _) | (0x80.., Escaped::ControlsAndHigh) => Some(byte),
        _ => None,
    }
}