use std::cell::Cell;
use std::ops::{Deref, DerefMut, Range};
use std::thread::LocalKey;
use regex_automata::util::primitives::NonMaxUsize;
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()) };
}
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);
let _ = self.home.try_with(|kept| {
let theirs = kept.take();
kept.set(if theirs.capacity() >= mine.capacity() {
theirs
} else {
mine
});
});
}
}
pub(super) fn steps() -> Lease<(usize, Range<usize>)> {
Lease::take(&STEPS)
}
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();
}
}