use std::alloc::{alloc, dealloc, Layout};
use std::ptr::NonNull;
pub const DEFAULT_ARENA_CAPACITY: usize = 1024 * 1024; pub const SIMD_SENTRY_BYTES: usize = 32;
type DropFn = unsafe fn(*mut u8);
pub struct BumpArena {
memory: NonNull<u8>,
capacity: usize,
offset: usize,
drop_chain: Vec<(*mut u8, DropFn)>,
}
unsafe impl Send for BumpArena {}
impl BumpArena {
pub fn new(capacity: usize) -> Self {
let total_size = capacity + SIMD_SENTRY_BYTES;
let layout = Layout::from_size_align(total_size, 64).expect("Invalid arena layout");
let ptr = unsafe { alloc(layout) };
assert!(!ptr.is_null(), "OOM: Failed to allocate BumpArena memory");
unsafe {
std::ptr::write_bytes(ptr.add(capacity), 0, SIMD_SENTRY_BYTES);
}
Self {
memory: NonNull::new(ptr).unwrap(),
capacity,
offset: 0,
drop_chain: Vec::new(),
}
}
#[inline(always)]
pub fn alloc<T>(&mut self, value: T) -> &mut T {
let layout = Layout::new::<T>();
let current_offset = self.offset;
let aligned_offset = (current_offset + (layout.align() - 1)) & !(layout.align() - 1);
let next_offset = aligned_offset + layout.size();
assert!(
next_offset <= self.capacity,
"BumpArena Overflow! Allocated {} bytes exceeds capacity {}",
next_offset,
self.capacity
);
self.offset = next_offset;
unsafe {
let dest = self.memory.as_ptr().add(aligned_offset) as *mut T;
std::ptr::write(dest, value);
if std::mem::needs_drop::<T>() {
unsafe fn drop_glue<T>(ptr: *mut u8) {
std::ptr::drop_in_place(ptr as *mut T);
}
self.drop_chain.push((dest as *mut u8, drop_glue::<T>));
}
&mut *dest
}
}
#[inline(always)]
pub fn alloc_slice<'a, T: Copy>(&'a mut self, items: &[T]) -> &'a mut [T] {
if items.is_empty() {
return &mut [];
}
let layout = Layout::array::<T>(items.len()).expect("Array layout error");
let current_offset = self.offset;
let aligned_offset = (current_offset + (layout.align() - 1)) & !(layout.align() - 1);
let next_offset = aligned_offset + layout.size();
assert!(next_offset <= self.capacity, "BumpArena slice overflow!");
self.offset = next_offset;
unsafe {
let dest = self.memory.as_ptr().add(aligned_offset) as *mut T;
std::ptr::copy_nonoverlapping(items.as_ptr(), dest, items.len());
std::slice::from_raw_parts_mut(dest, items.len())
}
}
#[inline(always)]
pub fn alloc_str<'a>(&'a mut self, text: &str) -> &'a str {
let bytes = self.alloc_slice(text.as_bytes());
unsafe { std::str::from_utf8_unchecked(bytes) }
}
#[inline(always)]
pub fn reset(&mut self) {
for (ptr, drop_fn) in self.drop_chain.drain(..).rev() {
unsafe {
drop_fn(ptr);
}
}
self.offset = 0;
}
#[inline(always)]
pub fn allocated_bytes(&self) -> usize {
self.offset
}
#[inline(always)]
pub fn capacity(&self) -> usize {
self.capacity
}
}
impl Drop for BumpArena {
fn drop(&mut self) {
for (ptr, drop_fn) in self.drop_chain.drain(..).rev() {
unsafe {
drop_fn(ptr);
}
}
let total_size = self.capacity + SIMD_SENTRY_BYTES;
let layout = Layout::from_size_align(total_size, 64).unwrap();
unsafe {
dealloc(self.memory.as_ptr(), layout);
}
}
}
pub struct FrameArenaManager {
arenas: [BumpArena; 2],
current_index: usize,
frame_epoch: u64,
}
impl FrameArenaManager {
pub fn new(capacity_per_frame: usize) -> Self {
Self {
arenas: [
BumpArena::new(capacity_per_frame),
BumpArena::new(capacity_per_frame),
],
current_index: 0,
frame_epoch: 0,
}
}
#[inline(always)]
pub fn active_arena(&self) -> &BumpArena {
&self.arenas[self.current_index]
}
#[inline(always)]
pub fn active_arena_mut(&mut self) -> &mut BumpArena {
&mut self.arenas[self.current_index]
}
#[inline(always)]
pub fn previous_arena(&self) -> &BumpArena {
&self.arenas[1 - self.current_index]
}
#[inline(always)]
pub fn previous_arena_mut(&mut self) -> &mut BumpArena {
&mut self.arenas[1 - self.current_index]
}
#[inline(always)]
pub fn frame_epoch(&self) -> u64 {
self.frame_epoch
}
#[inline(always)]
pub fn swap_and_reset(&mut self) {
self.current_index = 1 - self.current_index;
self.frame_epoch += 1;
self.arenas[self.current_index].reset();
}
}
type DropEntry = (*mut u8, unsafe fn(*mut u8));
#[repr(align(64))]
pub struct ThreadLocalArena {
start: *mut u8,
ptr: *mut u8,
end: *mut u8,
capacity: usize,
drop_chain: Vec<DropEntry>,
}
impl ThreadLocalArena {
pub fn new(capacity: usize) -> Self {
let layout =
Layout::from_size_align(capacity, 64).expect("Invalid layout for ThreadLocalArena");
let start = unsafe { alloc(layout) };
assert!(!start.is_null(), "OOM: Failed to allocate ThreadLocalArena");
Self {
start,
ptr: start,
end: unsafe { start.add(capacity) },
capacity,
drop_chain: Vec::new(),
}
}
#[inline(always)]
pub fn alloc<T>(&mut self, value: T) -> &mut T {
let layout = Layout::new::<T>();
let current = self.ptr as usize;
let aligned = (current + layout.align() - 1) & !(layout.align() - 1);
let next = aligned + layout.size();
assert!(next <= self.end as usize, "ThreadLocalArena overflow!");
self.ptr = next as *mut u8;
unsafe {
let target = aligned as *mut T;
target.write(value);
if std::mem::needs_drop::<T>() {
unsafe fn drop_glue<T>(ptr: *mut u8) {
std::ptr::drop_in_place(ptr as *mut T);
}
self.drop_chain.push((target as *mut u8, drop_glue::<T>));
}
&mut *target
}
}
#[inline(always)]
pub fn alloc_copy<T: Copy>(&mut self, value: T) -> &mut T {
let layout = Layout::new::<T>();
let current = self.ptr as usize;
let aligned = (current + layout.align() - 1) & !(layout.align() - 1);
let next = aligned + layout.size();
assert!(next <= self.end as usize, "ThreadLocalArena overflow!");
self.ptr = next as *mut u8;
unsafe {
let target = aligned as *mut T;
target.write(value);
&mut *target
}
}
#[inline(always)]
pub fn alloc_slice<'a, T: Copy>(&'a mut self, items: &[T]) -> &'a mut [T] {
if items.is_empty() {
return &mut [];
}
let layout = Layout::array::<T>(items.len()).expect("Array layout error");
let current = self.ptr as usize;
let aligned = (current + layout.align() - 1) & !(layout.align() - 1);
let next = aligned + layout.size();
assert!(
next <= self.end as usize,
"ThreadLocalArena slice overflow!"
);
self.ptr = next as *mut u8;
unsafe {
let target = aligned as *mut T;
std::ptr::copy_nonoverlapping(items.as_ptr(), target, items.len());
std::slice::from_raw_parts_mut(target, items.len())
}
}
#[inline(always)]
pub fn reset(&mut self) {
for (ptr, drop_fn) in self.drop_chain.drain(..).rev() {
unsafe {
drop_fn(ptr);
}
}
self.ptr = self.start;
}
#[inline(always)]
pub fn bytes_allocated(&self) -> usize {
(self.ptr as usize).saturating_sub(self.start as usize)
}
#[inline(always)]
pub fn capacity(&self) -> usize {
self.capacity
}
}
impl Drop for ThreadLocalArena {
fn drop(&mut self) {
for (ptr, drop_fn) in self.drop_chain.drain(..).rev() {
unsafe {
drop_fn(ptr);
}
}
let layout = Layout::from_size_align(self.capacity, 64).unwrap();
unsafe {
dealloc(self.start, layout);
}
}
}