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/grok/scratch.rs
// Purpose:   A thread's own buffers for a grok parse, lent for one call
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! One steps buffer and one capture-slot buffer a thread, shared by every
//! `Grok`. A pool inside each parser would make every thread but its first
//! user take a lock for each record. These hold offsets only, nothing of a
//! parser.

use std::cell::Cell;
use std::ops::{Deref, DerefMut, Range};
use std::thread::LocalKey;

use regex_automata::util::primitives::NonMaxUsize;

/// A buffer whose allocation has grown past this isn't kept for the thread.
const KEEP_BYTES: usize = 64 * 1024;

thread_local! {
    static STEPS: Cell<Vec<(usize, Range<usize>)>> = const { Cell::new(Vec::new()) };
    static SLOTS: Cell<Vec<Option<NonMaxUsize>>> = const { Cell::new(Vec::new()) };
}

/// A thread's buffer, taken out for one call and put back when this drops.
///
/// A sink that parses again while one is out gets an empty buffer of its
/// own, and a thread that is ending gets one too. The thread keeps the
/// larger of the two that come back.
pub(super) struct Lease<T: 'static> {
    buf: Vec<T>,
    home: &'static LocalKey<Cell<Vec<T>>>,
}

impl<T> Lease<T> {
    fn take(home: &'static LocalKey<Cell<Vec<T>>>) -> Self {
        let buf = home.try_with(Cell::take).unwrap_or_default();
        Self { buf, home }
    }
}

impl<T> Deref for Lease<T> {
    type Target = Vec<T>;

    fn deref(&self) -> &Vec<T> {
        &self.buf
    }
}

impl<T> DerefMut for Lease<T> {
    fn deref_mut(&mut self) -> &mut Vec<T> {
        &mut self.buf
    }
}

impl<T> Drop for Lease<T> {
    fn drop(&mut self) {
        self.buf.clear();
        if self.buf.capacity() * size_of::<T>() > KEEP_BYTES {
            return;
        }
        let mine = std::mem::take(&mut self.buf);
        // A thread that is ending has no home left: the buffer is dropped.
        let _ = self.home.try_with(|kept| {
            let theirs = kept.take();
            kept.set(if theirs.capacity() >= mine.capacity() {
                theirs
            } else {
                mine
            });
        });
    }
}

/// The thread's steps buffer, empty.
pub(super) fn steps() -> Lease<(usize, Range<usize>)> {
    Lease::take(&STEPS)
}

/// The thread's slot buffer, as `len` empty slots.
pub(super) fn slots(len: usize) -> Lease<Option<NonMaxUsize>> {
    let mut lease = Lease::take(&SLOTS);
    lease.resize(len, None);
    lease
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_buffer_comes_back_empty_with_its_allocation() {
        {
            let mut first = steps();
            first.extend((0..40).map(|i| (i, i..i + 1)));
        }
        let again = steps();
        assert_eq!(again.len(), 0);
        assert!(again.capacity() >= 40);
    }

    #[test]
    fn a_second_lease_while_one_is_out_is_its_own() {
        let mut outer = slots(8);
        let inner = slots(4);
        assert_eq!((outer.len(), inner.len()), (8, 4));
        outer[0] = NonMaxUsize::new(7);
        assert!(inner.iter().all(Option::is_none));
        drop(inner);
        assert_eq!(outer[0], NonMaxUsize::new(7));
    }

    #[test]
    fn an_oversized_buffer_is_not_kept() {
        {
            let mut big = slots(0);
            big.reserve(KEEP_BYTES);
        }
        assert!(slots(0).capacity() * size_of::<Option<NonMaxUsize>>() <= KEEP_BYTES);
    }

    #[test]
    fn a_lease_dropped_on_an_ending_thread_does_not_panic() {
        struct Late;
        impl Drop for Late {
            fn drop(&mut self) {
                drop(steps());
                drop(slots(3));
            }
        }
        thread_local! {
            static LATE: Late = const { Late };
        }
        std::thread::spawn(|| {
            drop(steps());
            LATE.with(|_| {});
        })
        .join()
        .unwrap();
    }
}