use bumpalo::Bump;
use std::cell::RefCell;
thread_local! {
static THREAD_ARENA: RefCell<Bump> = RefCell::new(Bump::new());
}
#[must_use]
pub fn with_arena<R>(f: impl FnOnce(&mut Bump) -> R) -> R {
THREAD_ARENA.with(|cell| {
let mut arena = cell.borrow_mut();
arena.reset();
let r = f(&mut arena);
arena.reset();
r
})
}
pub fn alloc_vec<T>(arena: &Bump, len: usize, val: T) -> Vec<T>
where
T: Clone,
{
let _ = arena;
vec![val; len]
}
pub struct BumpArena {
bump: Bump,
}
impl BumpArena {
#[must_use]
pub fn new() -> Self {
Self { bump: Bump::new() }
}
#[must_use]
pub fn with_capacity(cap: usize) -> Self {
Self {
bump: Bump::with_capacity(cap),
}
}
#[must_use]
pub fn bump(&self) -> &Bump {
&self.bump
}
pub fn bump_mut(&mut self) -> &mut Bump {
&mut self.bump
}
pub fn reset(&mut self) {
self.bump.reset();
}
pub fn alloc_value_buffer(&self, len: usize, val: crate::Value) -> Vec<crate::Value> {
vec![val; len]
}
pub fn alloc_str<'a>(&'a self, s: &str) -> &'a str {
self.bump.alloc_str(s)
}
pub fn with_bump<R>(&mut self, f: impl FnOnce(&mut Bump) -> R) -> R {
self.bump.reset();
let r = f(&mut self.bump);
self.bump.reset();
r
}
}
impl Default for BumpArena {
fn default() -> Self {
Self::new()
}
}
unsafe impl Send for BumpArena {}
#[cfg(test)]
#[allow(clippy::pedantic)]
#[allow(unused_must_use)]
mod tests {
use super::*;
#[test]
fn arena_resets() {
with_arena(|arena| {
let _v = arena.alloc_str("hello");
assert_eq!(_v, "hello");
});
with_arena(|arena| {
let _w = arena.alloc_str("world");
assert_eq!(_w, "world");
});
}
#[test]
fn bump_arena_per_chunk() {
let mut arena = BumpArena::new();
let v = arena.alloc_value_buffer(16, crate::Value::Missing);
assert_eq!(v.len(), 16);
arena.reset();
let v2 = arena.alloc_value_buffer(8, crate::Value::Continuous(1.0));
assert_eq!(v2.len(), 8);
}
#[test]
fn bump_arena_threaded() {
use rayon::prelude::*;
let data: Vec<usize> = (0..100).collect();
let results: Vec<usize> = data
.par_iter()
.map(|i| {
let arena = BumpArena::new();
let buf = arena.alloc_value_buffer(4, crate::Value::Continuous(*i as f64));
buf.len()
})
.collect();
assert_eq!(results.len(), 100);
assert!(results.iter().all(|&l| l == 4));
}
}