#![forbid(unsafe_code)]
use bumpalo::Bump;
pub type BumpVec<'a, T> = bumpalo::collections::Vec<'a, T>;
pub type BumpString<'a> = bumpalo::collections::String<'a>;
pub const DEFAULT_ARENA_CAPACITY: usize = 256 * 1024;
#[derive(Debug)]
pub struct FrameArena {
bump: Bump,
}
impl FrameArena {
pub fn new(capacity: usize) -> Self {
Self {
bump: Bump::with_capacity(capacity),
}
}
pub fn with_default_capacity() -> Self {
Self::new(DEFAULT_ARENA_CAPACITY)
}
pub fn reset(&mut self) {
self.bump.reset();
}
pub fn alloc_str(&self, s: &str) -> &str {
self.bump.alloc_str(s)
}
pub fn alloc_fmt(&self, args: std::fmt::Arguments<'_>) -> &str {
use core::fmt::Write;
let mut s = bumpalo::collections::String::new_in(&self.bump);
s.write_fmt(args).expect("formatting into arena string");
s.into_bump_str()
}
pub fn alloc_slice<T: Copy>(&self, slice: &[T]) -> &[T] {
self.bump.alloc_slice_copy(slice)
}
pub fn alloc_with<T, F: FnOnce() -> T>(&self, f: F) -> &mut T {
self.bump.alloc_with(f)
}
pub fn alloc<T>(&self, val: T) -> &mut T {
self.bump.alloc(val)
}
pub fn alloc_iter<T, I>(&self, iter: I) -> &mut [T]
where
I: IntoIterator<Item = T>,
{
let mut vec = bumpalo::collections::Vec::new_in(&self.bump);
vec.extend(iter);
vec.into_bump_slice_mut()
}
pub fn new_vec<T>(&self) -> BumpVec<'_, T> {
bumpalo::collections::Vec::new_in(&self.bump)
}
pub fn new_vec_with_capacity<T>(&self, capacity: usize) -> BumpVec<'_, T> {
bumpalo::collections::Vec::with_capacity_in(capacity, &self.bump)
}
pub fn new_string(&self) -> BumpString<'_> {
bumpalo::collections::String::new_in(&self.bump)
}
pub fn new_string_with_capacity(&self, capacity: usize) -> BumpString<'_> {
bumpalo::collections::String::with_capacity_in(capacity, &self.bump)
}
pub fn allocated_bytes(&self) -> usize {
self.bump.allocated_bytes()
}
pub fn allocated_bytes_including_metadata(&self) -> usize {
self.bump.allocated_bytes_including_metadata()
}
pub fn as_bump(&self) -> &Bump {
&self.bump
}
}
impl Default for FrameArena {
fn default() -> Self {
Self::with_default_capacity()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn core_arena_alloc_and_reset() {
let mut arena = FrameArena::new(4096);
let s = arena.alloc_str("ftui-core arena");
assert_eq!(s, "ftui-core arena");
let v = arena.alloc_slice(&[10u32, 20, 30]);
assert_eq!(v, &[10, 20, 30]);
arena.reset();
let s2 = arena.alloc_str("reused");
assert_eq!(s2, "reused");
}
}