use std::alloc::{Layout, alloc_zeroed, dealloc, handle_alloc_error};
use std::ptr::NonNull;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
pub const BLOCK_BYTES: usize = 256 * 1024;
const FIRST_BLOCK_BYTES: usize = 8 * 1024;
const BLOCK_ALIGN: usize = 64;
struct Block {
ptr: NonNull<u8>,
bytes: usize,
}
unsafe impl Send for Block {}
impl Block {
fn new(bytes: usize) -> Self {
let layout = Layout::from_size_align(bytes, BLOCK_ALIGN).expect("block layout");
let raw = unsafe { alloc_zeroed(layout) };
let Some(ptr) = NonNull::new(raw) else {
handle_alloc_error(layout)
};
Self { ptr, bytes }
}
}
impl Drop for Block {
fn drop(&mut self) {
let layout = unsafe { Layout::from_size_align_unchecked(self.bytes, BLOCK_ALIGN) };
unsafe { dealloc(self.ptr.as_ptr(), layout) };
}
}
pub struct MorselArena {
blocks: Vec<Block>,
cur: usize,
off: usize,
generation: Arc<AtomicU64>,
}
impl Default for MorselArena {
fn default() -> Self {
Self::new()
}
}
impl MorselArena {
pub fn new() -> Self {
Self {
blocks: Vec::new(),
cur: 0,
off: 0,
generation: Arc::new(AtomicU64::new(0)),
}
}
pub fn alloc(&mut self, bytes: usize, align: usize) -> RawBuf {
assert!(
align.is_power_of_two() && align <= BLOCK_ALIGN,
"align {align}"
);
if bytes == 0 {
return RawBuf::empty();
}
if bytes > BLOCK_BYTES {
let block = Block::new(bytes);
let ptr = block.ptr;
let at = self.cur.min(self.blocks.len());
self.blocks.insert(at, block);
self.cur += 1;
return self.tag(RawBuf {
ptr,
len: bytes,
#[cfg(debug_assertions)]
tag: None,
#[cfg(debug_assertions)]
borrowed: false,
});
}
let cap = self.blocks.get(self.cur).map_or(0, |b| b.bytes);
let off = self.off.next_multiple_of(align);
if self.cur >= self.blocks.len() || off + bytes > cap {
if self.cur < self.blocks.len() && off + bytes > cap {
self.cur += 1;
}
if self.cur >= self.blocks.len() {
let want = self.next_block_bytes().max(bytes);
self.blocks.push(Block::new(want));
self.cur = self.blocks.len() - 1;
}
self.off = 0;
return self.alloc(bytes, align);
}
self.off = off + bytes;
let ptr = unsafe { NonNull::new_unchecked(self.blocks[self.cur].ptr.as_ptr().add(off)) };
self.tag(RawBuf {
ptr,
len: bytes,
#[cfg(debug_assertions)]
tag: None,
#[cfg(debug_assertions)]
borrowed: false,
})
}
fn next_block_bytes(&self) -> usize {
let last = self.blocks.last().map_or(0, |b| b.bytes);
(last * 2).clamp(FIRST_BLOCK_BYTES, BLOCK_BYTES)
}
pub fn alloc_of<T: Pod>(&mut self, count: usize) -> RawBuf {
self.alloc(count * size_of::<T>(), align_of::<T>())
}
pub fn reset(&mut self) {
self.cur = 0;
self.off = 0;
self.generation.fetch_add(1, Ordering::Release);
}
pub fn capacity(&self) -> usize {
self.blocks.iter().map(|b| b.bytes).sum()
}
pub fn pooled() -> PooledArena {
let arena = POOL.with(|p| p.borrow_mut().pop()).map(|mut a| {
a.reset();
a
});
PooledArena {
arena: arena.or_else(|| Some(MorselArena::new())),
}
}
fn shrink(&mut self) {
self.blocks.truncate(1);
self.cur = 0;
self.off = 0;
}
}
const POOL_ARENAS: usize = 4;
const POOL_KEEP_BYTES: usize = BLOCK_BYTES;
thread_local! {
static POOL: std::cell::RefCell<Vec<MorselArena>> =
const { std::cell::RefCell::new(Vec::new()) };
}
pub struct PooledArena {
arena: Option<MorselArena>,
}
impl std::ops::Deref for PooledArena {
type Target = MorselArena;
fn deref(&self) -> &MorselArena {
self.arena.as_ref().expect("arena is taken only on drop")
}
}
impl std::ops::DerefMut for PooledArena {
fn deref_mut(&mut self) -> &mut MorselArena {
self.arena.as_mut().expect("arena is taken only on drop")
}
}
impl Drop for PooledArena {
fn drop(&mut self) {
let Some(mut arena) = self.arena.take() else {
return;
};
if arena.capacity() > POOL_KEEP_BYTES {
arena.shrink();
}
let _ = POOL.try_with(|p| {
let mut pool = p.borrow_mut();
if pool.len() < POOL_ARENAS {
pool.push(arena);
}
});
}
}
impl MorselArena {
#[cfg(debug_assertions)]
fn tag(&self, mut buf: RawBuf) -> RawBuf {
buf.tag = Some((
Arc::clone(&self.generation),
self.generation.load(Ordering::Acquire),
));
buf
}
#[cfg(not(debug_assertions))]
fn tag(&self, buf: RawBuf) -> RawBuf {
buf
}
}
pub struct RawBuf {
ptr: NonNull<u8>,
len: usize,
#[cfg(debug_assertions)]
tag: Option<(Arc<AtomicU64>, u64)>,
#[cfg(debug_assertions)]
borrowed: bool,
}
unsafe impl Send for RawBuf {}
unsafe impl Sync for RawBuf {}
impl RawBuf {
pub fn empty() -> Self {
Self {
ptr: NonNull::dangling(),
len: 0,
#[cfg(debug_assertions)]
tag: None,
#[cfg(debug_assertions)]
borrowed: false,
}
}
pub unsafe fn borrowed(ptr: NonNull<u8>, len: usize) -> Self {
Self {
ptr,
len,
#[cfg(debug_assertions)]
tag: None,
#[cfg(debug_assertions)]
borrowed: true,
}
}
pub fn len(&self) -> usize {
self.len
}
pub fn is_empty(&self) -> bool {
self.len == 0
}
#[inline]
fn check(&self) {
#[cfg(debug_assertions)]
if let Some((cell, born)) = &self.tag {
assert_eq!(
cell.load(Ordering::Acquire),
*born,
"vector buffer used after its arena was reset"
);
}
}
#[inline]
pub fn as_slice<T: Pod>(&self) -> &[T] {
self.check();
debug_assert_eq!(self.ptr.as_ptr() as usize % align_of::<T>(), 0);
unsafe { std::slice::from_raw_parts(self.ptr.as_ptr().cast(), self.len / size_of::<T>()) }
}
#[inline]
pub fn as_mut_slice<T: Pod>(&mut self) -> &mut [T] {
self.check();
#[cfg(debug_assertions)]
assert!(!self.borrowed, "a borrowed buffer was written to");
debug_assert_eq!(self.ptr.as_ptr() as usize % align_of::<T>(), 0);
unsafe {
std::slice::from_raw_parts_mut(self.ptr.as_ptr().cast(), self.len / size_of::<T>())
}
}
}
pub unsafe trait Pod: Copy {}
unsafe impl Pod for u8 {}
unsafe impl Pod for u16 {}
unsafe impl Pod for u32 {}
unsafe impl Pod for u64 {}
unsafe impl Pod for i64 {}
unsafe impl Pod for f64 {}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn bump_and_reuse() {
let mut arena = MorselArena::new();
let mut a = arena.alloc_of::<u64>(1024);
a.as_mut_slice::<u64>().fill(7);
let b = arena.alloc_of::<u64>(1024);
assert_eq!(a.as_slice::<u64>()[1023], 7);
assert_eq!(b.as_slice::<u64>()[0], 0, "fresh block memory is zeroed");
let held = arena.capacity();
arena.reset();
let _c = arena.alloc_of::<u64>(1024);
assert_eq!(arena.capacity(), held, "reset keeps blocks");
}
#[test]
fn a_small_run_pays_a_small_block() {
let mut arena = MorselArena::new();
let _one_vector = arena.alloc(64, 64);
assert_eq!(
arena.capacity(),
FIRST_BLOCK_BYTES,
"a run that wants 64 bytes does not take 256 KiB"
);
let _spill = arena.alloc(FIRST_BLOCK_BYTES, 64);
assert_eq!(arena.capacity(), FIRST_BLOCK_BYTES * 3);
for _ in 0..8 {
arena.alloc(BLOCK_BYTES, 64);
}
assert!(
arena.blocks.iter().all(|b| b.bytes <= BLOCK_BYTES),
"no block grows past the cap"
);
assert!(
arena.blocks.iter().any(|b| b.bytes == BLOCK_BYTES),
"a run that keeps asking reaches the cap"
);
}
#[test]
fn oversize_gets_own_block() {
let mut arena = MorselArena::new();
let small = arena.alloc_of::<u64>(4);
let big = arena.alloc(BLOCK_BYTES * 2, 64);
let small2 = arena.alloc_of::<u64>(4);
assert_eq!(big.len(), BLOCK_BYTES * 2);
assert_eq!(small.as_slice::<u64>().len(), 4);
assert_eq!(small2.as_slice::<u64>().len(), 4);
}
#[test]
fn alignment_honored() {
let mut arena = MorselArena::new();
let _odd = arena.alloc(3, 1);
let aligned = arena.alloc_of::<u64>(1);
assert_eq!(aligned.as_slice::<u64>().len(), 1);
}
#[test]
fn borrowed_reads_the_memory_it_was_given() {
let outside = [7u64, 8, 9];
let buf = unsafe {
RawBuf::borrowed(
NonNull::new(outside.as_ptr() as *mut u8).expect("a real pointer"),
size_of_val(&outside[..]),
)
};
assert_eq!(buf.as_slice::<u64>(), &outside[..]);
let mut arena = MorselArena::new();
arena.reset();
assert_eq!(buf.as_slice::<u64>()[2], 9);
}
#[test]
#[should_panic(expected = "borrowed buffer was written")]
#[cfg(debug_assertions)]
fn writing_a_borrowed_buffer_asserts() {
let outside = [7u64];
let mut buf = unsafe {
RawBuf::borrowed(
NonNull::new(outside.as_ptr() as *mut u8).expect("a real pointer"),
8,
)
};
buf.as_mut_slice::<u64>()[0] = 1;
}
#[test]
fn a_pooled_arena_comes_back_with_the_block_the_last_run_left() {
std::thread::spawn(|| {
let first = {
let mut arena = MorselArena::pooled();
let _ = arena.alloc_of::<u64>(64);
arena.blocks[0].ptr
};
let mut arena = MorselArena::pooled();
assert_eq!(arena.capacity(), FIRST_BLOCK_BYTES, "the block is kept");
assert_eq!(arena.blocks[0].ptr, first, "and it is the same block");
assert_eq!(arena.alloc_of::<u64>(64).as_slice::<u64>().len(), 64);
assert_eq!(arena.capacity(), FIRST_BLOCK_BYTES, "nothing new is taken");
})
.join()
.expect("thread");
}
#[test]
fn an_arena_that_grew_for_one_run_does_not_charge_the_next() {
std::thread::spawn(|| {
{
let mut arena = MorselArena::pooled();
let _ = arena.alloc(64, 64);
for _ in 0..8 {
arena.alloc(BLOCK_BYTES, 64);
}
assert!(arena.capacity() > POOL_KEEP_BYTES, "this run went wide");
}
let arena = MorselArena::pooled();
assert_eq!(
arena.capacity(),
FIRST_BLOCK_BYTES,
"a wide run hands back its first block and no more"
);
})
.join()
.expect("thread");
}
#[test]
#[should_panic(expected = "arena was reset")]
#[cfg(debug_assertions)]
fn a_buffer_that_outlived_its_run_fails_on_the_next_one() {
let buf = {
let mut arena = MorselArena::pooled();
arena.alloc_of::<u64>(8)
};
let _next = MorselArena::pooled();
let _ = buf.as_slice::<u64>();
}
#[test]
#[should_panic(expected = "arena was reset")]
#[cfg(debug_assertions)]
fn use_after_reset_asserts() {
let mut arena = MorselArena::new();
let buf = arena.alloc_of::<u64>(8);
arena.reset();
let _ = buf.as_slice::<u64>();
}
}