While I was making my own Arena as a little side project, I wondered why the stdlib doesn't have an Arena type. It has many other common data types like Vec, VecDeque, BinaryHeap etc. So my question is do you all think that an Arena fits in the stdlib?
here is my code for anyone interested:
#![deny(unsafe_op_in_unsafe_fn)]
use std::alloc::{Layout, alloc, dealloc, handle_alloc_error};
use std::hint::cold_path;
use std::ptr::NonNull;
use std::cell::Cell;
#[derive(Debug)]
/// An "array" of many different items with the same lifetime.
///
/// Note that uppon Drop, none of the destructors will be run, you can use [`drop_in_place`](https://doc.rust-lang.org/std/ptr/fn.drop_in_place.html) for each item you want to Drop.
/// Also note that not all space is used for storing objects, some padding may be needed for proper alignment.
pub struct Arena {
ptr: Cell<NonNull<u8>>,
ptr_pos: Cell<usize>,
capacity: usize,
}
impl Arena {
/// Creates a new Arena with a given capacity.
/// # panics
/// Panics if capacity > isize::MAX or if capacity == 0.
pub fn new(capacity: usize) -> Self {
if capacity > isize::MAX as usize {
cold_path();
panic!("cannot alloc more than isize::MAX bytes");
}
if capacity == 0 {
cold_path();
panic!("capacity cannot be 0");
}
// SAFETY: we know capacity is smaller than isize::MAX bytes and that capacity isn't equal to 0
unsafe {
Self::new_unchecked(capacity)
}
}
/// Create a new Arena without runtime checks.
/// # safety
/// It is UB to allocate 0 bytes, so capacity must not be 0.
/// The capacity should also be smaller than isize::MAX.
pub unsafe fn new_unchecked(capacity: usize) -> Self {
// SAFETY: the caller checked if the capacity is smaller than isize::MAX bytes
let layout = unsafe {
Layout::array::<u8>(capacity).unwrap_unchecked()
};
// SAFETY: the caller checked if the capacity is 0
let ptr = unsafe {
alloc(layout)
};
if ptr.is_null() {
handle_alloc_error(layout);
}
// SAFETY: we checked if the ptr is null
let ptr = unsafe {
NonNull::new(ptr).unwrap_unchecked()
};
let ptr = Cell::new(ptr);
Self {
ptr,
ptr_pos: Cell::new(0),
capacity,
}
}
/// Alocates data on the Arena.
///
/// Returns None if the Arena doesn't have enough room for data + alignment padding.
pub fn alloc<T>(&self, data: T) -> Option<&mut T> {
let size = size_of::<T>();
let padding = self.ptr.get().align_offset(align_of::<T>());
self.ptr_pos.update(|pos| pos + size + padding);
if self.ptr_pos.get() >= self.capacity() {
// return None if we can't alloc data
self.ptr_pos.update(|pos| pos - size - padding);
return None;
}
// make sure the pointer is aligned before writing
self.ptr.update(|ptr| unsafe {ptr.add(padding)});
let ptr = self.ptr.get().as_ptr() as *mut T;
// SAFETY: ptr is properly aligned and valid
unsafe {
ptr.write(data);
}
self.ptr.update(|ptr| unsafe {ptr.add(size)});
// SAFETY: the pointer is valid non-null
unsafe {
Some(ptr.as_mut().expect("the pointer isn't null"))
}
}
#[inline]
/// Sets the inner pointer to its original position.
///
/// Note that the Arena isn't deallocated when clearing.
pub fn clear(&mut self) {
*self.ptr.get_mut() = unsafe {self.ptr.get().sub(self.ptr_pos.get())};
*self.ptr_pos.get_mut() = 0;
}
/// Returns the capacity of the Arena.
#[inline(always)]
pub fn capacity(&self) -> usize {
self.capacity
}
/// Returns the remeaning space in the Arena.
#[inline(always)]
pub fn remaining_space(&self) -> usize {
self.capacity - self.ptr_pos.get()
}
#[inline(always)]
/// Checks if the Arena is empty.
pub fn is_empty(&self) -> bool {
self.ptr_pos.get() == 0
}
}
impl Drop for Arena {
fn drop(&mut self) {
self.clear();
let layout = Layout::array::<u8>(self.capacity).expect("capacity isn't 0");
// SAFETY: is from same allocator and same layout
unsafe {
dealloc(self.ptr.get().as_ptr(), layout);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::assert_matches;
#[test]
fn no_space() {
let arena = Arena::new(1);
assert_matches!(arena.alloc([0; 3]), None);
}
#[test]
#[should_panic]
fn zero_alloc() {
let _ = Arena::new(0);
}
}
I think the biggest reason is that it is, at least to me, unclear what the benefit of the arena being in the stdlib is, as opposed to a 3rd party crate that you can import if you want. Especially now that the allocator trait is on track to stabilize, crates exposing data structures can be generic over the allocator, and then you as the user can give them your arena allocator.
The reason why Vec and the like are in the stdlib is that it's useful to pass them as arguments to functions explicitly, instead of being generic over trait bounds, so they become a common language between crates, and placing them in the standard library helps ensure interoperability.
Rust has a fairly good method for sharing libraries via cargo, so the bar for inclusion in std can be pretty high. What should go in std though?
Things implemented via compiler "magic", and library elements of language syntax (like Iterator and Try).
Things that lots of libraries need to talk to each other, like &[T].
Simple "batteries" with only one really obvious implementation. Binary search, many simple collections. More complicated things or things with no real consensus can get hashed out in a crate.
Operating system abstraction. It might be best to be able to print a string without knowing what platform I'm on.
So I would say Arena would be a good fit for inclusion in std if there were some special aspect of arenas that made them unwieldy without special compiler support, or if there were some third party arena implementation that was widely used and largely "done". With regard to that first point though, it's sometimes better for the compiler to implement more general features that make it convenient to write that third party library. Better support for all custom allocators, and not just arenas, might allow arenas to exist as their own library in a natural way. Most programs don't require an arena more complicated than Vec,
I think the core point is that if getting a &'a mut Tout of the arena is good enough, then it doesn't need to be centralized into allochow the backing store for such things is made for everyone.
If one needed some form of ArenaHandle<'a, T> that everyone spoke as a vocabulary type, then that might be a good thing for core, but letting different libraries pick whatever kind of arena works well for them sounds fine.
(And it's also need to be something that isn't handled fine with Box<T, ArenaAllocator<'a>> or whatever, now that custom allocators are stabilizing.)
Arenas can be done easily in user code, except of Drop of elements inside the arena, because elements containing references to other elements in the same arena could end up observing dangling pointers.
It could be interesting if Rust added some new flavor of Drop that leaves still-valid objects behind or maybe a lifetime that prevents use of references (like an opposite of 'static to cast Item<'a> to Item<'gone>).
That is possible to work around by having the data-structure be built from std types (which have #[may_dangle] so it can drop types where the lifetimes already expired) so you don't need a custom Drop impl -- this is how typed-arena works:
This is good idea, it would make the allocator API more complete. Since this is also rarely change. Another benefit is it hass less supply chain risk. There is also some joke Rust doesn't has complete STD, everything needs 3rd party libraries :v
It is strong addition to STD because it could become the backbone of memory reuse technique that is not limited to a single type, since you could use it to allocate Vector, then just reset the index to 0 and reuse to allocate a coompletely different type. Or preallocated static global arena :v
Then I also propose to add debug allocator for catching memory leak, use after free, and double free that works with Rust collections for making the experience in using Rust pointer better. Miri has serious limitation, it couldn't check FFI code. A debug allocator won't has this limitation
Idk if this really is te solution, but for my Arena I have a custom type which does Drop its contents upon Drop, it is basically just a wrapper around a mut reference:
/// Data stored in an Arena which does Drop its contents.
#[repr(transparent)]
#[derive(Debug)]
pub struct ArenaBox<'a, T> {
data: &'a mut T,
}
impl<'a, T> ArenaBox<'a, T> {
/// Consumes and leaks the ArenaBox, returning the inner mutable refrence.
#[inline]
pub fn leak(self) -> &'a mut T {
// SAFETY: ArenaBox has #[repr(transparent)], so it is safe to transmute to the inner value as they should have the exact same representation
unsafe { transmute(self) }
}
}
impl<T: Clone> ArenaBox<'_, T> {
/// Creates a copy of the ArenaBox in an (different) Arena.
///
/// Returns None if the Arena doesn't have enough room for data + alignment padding.
#[inline]
pub fn copy<'a>(&self, arena: &'a Arena) -> Option<ArenaBox<'a, T>> {
arena.alloc_boxed(self.data.clone())
}
/// Get an owned version of the data.
#[inline]
pub fn get_owned(&self) -> T {
self.data.clone()
}
}
impl<T> Deref for ArenaBox<'_, T> {
type Target = T;
fn deref(&self) -> &Self::Target {
self.data
}
}
impl<T> DerefMut for ArenaBox<'_, T> {
fn deref_mut(&mut self) -> &mut Self::Target {
self.data
}
}
impl<T> Drop for ArenaBox<'_, T> {
fn drop(&mut self) {
// SAFETY: a refrence is always valid (and value can't be used after Drop call)
unsafe {
drop_in_place(self.data);
}
}
}
Could you elaborate why did you say that happen? Because arena does not deallocate individual memory, and that is by design. If it deallocates individual then it would become general purpose allocator, aka it doesn't get the fast speed bump, because the speed comes from doing less thing in the allocation and deallocation process of the collections stored in the arena. So because it never deallocate individual memory, it is impossible to cause dangling. All memory inside the arena has the same lifetime, deallocated at the same time at once. The method .reset() that reset the index to 0 takes &mut self that already prevents resetting the arena while there are still active users because can't call &mut if there are & and other &mut. The impl deallocate in the allocator trait is left blank just { }. The collections's impl drop does nothing, because it call that allocator api impl drop under the hood. The real impl drop is done in the struct of the arena allocator itself that free all the heap at once
In a hypothetical arena which drops elements - not just deallocates their backing memory - there's the problem with drop order.
Say, you store BTreeSet<u32, Global> in your arena. You need to drop it so that the non-arena allocation is freed; otherwise, it will be leaked as the arena will only free the control structure's bytes.
That doesn't seem like elements containing references to other elements in the same arena, but containing refetence to other element that are not owned by the arena
That would not become arena allocator anymore, because now it has the same complexity of general purpose allocator that means it pays the same cost. That should be a dedicated allocator, so pure arena usage doesn't pay this cost
Secondly, the allocator that dealloc a heap must be the one that allocate it. So the global allocator is the one that can deallocate the real heap. That means it would need to call the global allocator, but what if it comes from other custom allocator not the global? So it won't become hard code, but generic callback where C: Allocator, then you have to track the heap => which allocator callback that allocated it. Now it becomes complex process that practically remove the arena speed
error[E0713]: borrow may still be in use when destructor runs
--> src/lib.rs:18:9
|
14 | impl<'a, T> ArenaBox<'a, T> {
| -- lifetime `'a` defined here
...
18 | self.data
| ^^^^^^^^^ returning this value requires that `*self.data` is borrowed for `'a`
19 | }
| - here, drop of `self` needs exclusive access to `*self.data`, because the type `ArenaBox<'_, T>` implements the `Drop` trait
For more information about this error, try `rustc --explain E0713`.
The transmute basically makes sure that the ArenaBox doesn't get dropped, so we can just return the reference. (transmuting here is fine anyway because of #[repr(transparent)]).
There's no such thing as dropping all items at once. You can de-allocate the arena's storage without dropping its items, but that risks leaking the data they own.
You can either leak all of the Strings when you dealloc Item memory without dropping, or some of the other.str references will have use-after-free if you support Drop in items.
That is not arena usage, if it is, the string would be owned by the arena not the global allocator, because the point of arena is grouping, variables that has same lifetime or almost same lifetime are allocated inside 1 arena to improve spatial cache locality
The String is there to demonstrate the unsafety that you can't prevent if you support both Drop and non-'static items.
This problem comes up in the real world, e.g. you may want to manipulate a graph of nodes (without Rc) that own the data they represent. You may have a fixed or append-only set of Items, but need to mutate variable length (not append-only) data per item.
And even if items were stored entirely within arena's storage, you can still have types with significant Drop and deinitialized state even if that drop doesn't manage heap memory.
That still seems not the correct use case of arena. The single purpose of arena is, contigous it should not contain memory that is owned by other allocator, does not deallocate single element
If your data structure contains pointer to memory that is not owned by the arena, it is the use case of typed pool memory, there is no impl allocator api needed here. Eg
That is already contigous except the String since in your usage the String is also intented not contigous to the main buffer. Arena would provide zero benefit if in the end of the day you insert pointer of memory that is owned by other allocator
In real arena usage the whole Node would be owned by the arena, the String is also allocated in the arena, if it grows it would copy to bigger block inside the arena but the old block is stall there doing nothing, arena is a tradeoff between memory usage and speed, if you start adding complexity that eg reusing the middle block, then it is becoming general purpose allocator because it needs to search the free block. Arena only support reusing and grow memory if it is the last allocation to maintain the speed