1 //! The arena, a fast but limited type of allocator.
3 //! Arenas are a type of allocator that destroy the objects within, all at
4 //! once, once the arena itself is destroyed. They do not support deallocation
5 //! of individual objects while the arena itself is still alive. The benefit
6 //! of an arena is very fast allocation; just a pointer bump.
8 //! This crate implements `TypedArena`, a simple arena that can only hold
9 //! objects of a single type.
11 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/",
12 test(no_crate_inject, attr(deny(warnings))))]
14 #![feature(core_intrinsics)]
15 #![feature(dropck_eyepatch)]
16 #![feature(raw_vec_internals)]
17 #![cfg_attr(test, feature(test))]
23 use rustc_data_structures::cold_path;
24 use rustc_data_structures::sync::MTLock;
25 use smallvec::SmallVec;
27 use std::cell::{Cell, RefCell};
30 use std::marker::{PhantomData, Send};
35 use alloc::raw_vec::RawVec;
37 /// An arena that can hold objects of only one type.
38 pub struct TypedArena<T> {
39 /// A pointer to the next object to be allocated.
42 /// A pointer to the end of the allocated area. When this pointer is
43 /// reached, a new chunk is allocated.
46 /// A vector of arena chunks.
47 chunks: RefCell<Vec<TypedArenaChunk<T>>>,
49 /// Marker indicating that dropping the arena causes its owned
50 /// instances of `T` to be dropped.
54 struct TypedArenaChunk<T> {
55 /// The raw storage for the arena chunk.
57 /// The number of valid entries in the chunk.
61 impl<T> TypedArenaChunk<T> {
63 unsafe fn new(capacity: usize) -> TypedArenaChunk<T> {
65 storage: RawVec::with_capacity(capacity),
70 /// Destroys this arena chunk.
72 unsafe fn destroy(&mut self, len: usize) {
73 // The branch on needs_drop() is an -O1 performance optimization.
74 // Without the branch, dropping TypedArena<u8> takes linear time.
75 if mem::needs_drop::<T>() {
76 let mut start = self.start();
77 // Destroy all allocated objects.
79 ptr::drop_in_place(start);
80 start = start.offset(1);
85 // Returns a pointer to the first allocated object.
87 fn start(&self) -> *mut T {
91 // Returns a pointer to the end of the allocated space.
93 fn end(&self) -> *mut T {
95 if mem::size_of::<T>() == 0 {
96 // A pointer as large as possible for zero-sized elements.
99 self.start().add(self.storage.capacity())
105 const PAGE: usize = 4096;
107 impl<T> Default for TypedArena<T> {
108 /// Creates a new `TypedArena`.
109 fn default() -> TypedArena<T> {
111 // We set both `ptr` and `end` to 0 so that the first call to
112 // alloc() will trigger a grow().
113 ptr: Cell::new(ptr::null_mut()),
114 end: Cell::new(ptr::null_mut()),
115 chunks: RefCell::new(vec![]),
121 impl<T> TypedArena<T> {
122 pub fn in_arena(&self, ptr: *const T) -> bool {
123 let ptr = ptr as *const T as *mut T;
125 self.chunks.borrow().iter().any(|chunk| chunk.start() <= ptr && ptr < chunk.end())
127 /// Allocates an object in the `TypedArena`, returning a reference to it.
129 pub fn alloc(&self, object: T) -> &mut T {
130 if self.ptr == self.end {
135 if mem::size_of::<T>() == 0 {
137 .set(intrinsics::arith_offset(self.ptr.get() as *mut u8, 1)
139 let ptr = mem::align_of::<T>() as *mut T;
140 // Don't drop the object. This `write` is equivalent to `forget`.
141 ptr::write(ptr, object);
144 let ptr = self.ptr.get();
145 // Advance the pointer.
146 self.ptr.set(self.ptr.get().offset(1));
147 // Write into uninitialized memory.
148 ptr::write(ptr, object);
155 fn can_allocate(&self, len: usize) -> bool {
156 let available_capacity_bytes = self.end.get() as usize - self.ptr.get() as usize;
157 let at_least_bytes = len.checked_mul(mem::size_of::<T>()).unwrap();
158 available_capacity_bytes >= at_least_bytes
161 /// Ensures there's enough space in the current chunk to fit `len` objects.
163 fn ensure_capacity(&self, len: usize) {
164 if !self.can_allocate(len) {
166 debug_assert!(self.can_allocate(len));
171 unsafe fn alloc_raw_slice(&self, len: usize) -> *mut T {
172 assert!(mem::size_of::<T>() != 0);
175 self.ensure_capacity(len);
177 let start_ptr = self.ptr.get();
178 self.ptr.set(start_ptr.add(len));
182 /// Allocates a slice of objects that are copied into the `TypedArena`, returning a mutable
183 /// reference to it. Will panic if passed a zero-sized types.
187 /// - Zero-sized types
188 /// - Zero-length slices
190 pub fn alloc_slice(&self, slice: &[T]) -> &mut [T]
195 let len = slice.len();
196 let start_ptr = self.alloc_raw_slice(len);
197 slice.as_ptr().copy_to_nonoverlapping(start_ptr, len);
198 slice::from_raw_parts_mut(start_ptr, len)
203 pub fn alloc_from_iter<I: IntoIterator<Item = T>>(&self, iter: I) -> &mut [T] {
204 assert!(mem::size_of::<T>() != 0);
205 let mut vec: SmallVec<[_; 8]> = iter.into_iter().collect();
209 // Move the content to the arena by copying it and then forgetting
210 // the content of the SmallVec
213 let start_ptr = self.alloc_raw_slice(len);
214 vec.as_ptr().copy_to_nonoverlapping(start_ptr, len);
216 slice::from_raw_parts_mut(start_ptr, len)
223 fn grow(&self, n: usize) {
225 let mut chunks = self.chunks.borrow_mut();
226 let (chunk, mut new_capacity);
227 if let Some(last_chunk) = chunks.last_mut() {
228 let used_bytes = self.ptr.get() as usize - last_chunk.start() as usize;
229 let currently_used_cap = used_bytes / mem::size_of::<T>();
230 last_chunk.entries = currently_used_cap;
231 if last_chunk.storage.reserve_in_place(currently_used_cap, n) {
232 self.end.set(last_chunk.end());
235 new_capacity = last_chunk.storage.capacity();
237 new_capacity = new_capacity.checked_mul(2).unwrap();
238 if new_capacity >= currently_used_cap + n {
244 let elem_size = cmp::max(1, mem::size_of::<T>());
245 new_capacity = cmp::max(n, PAGE / elem_size);
247 chunk = TypedArenaChunk::<T>::new(new_capacity);
248 self.ptr.set(chunk.start());
249 self.end.set(chunk.end());
254 /// Clears the arena. Deallocates all but the longest chunk which may be reused.
255 pub fn clear(&mut self) {
257 // Clear the last chunk, which is partially filled.
258 let mut chunks_borrow = self.chunks.borrow_mut();
259 if let Some(mut last_chunk) = chunks_borrow.last_mut() {
260 self.clear_last_chunk(&mut last_chunk);
261 let len = chunks_borrow.len();
262 // If `T` is ZST, code below has no effect.
263 for mut chunk in chunks_borrow.drain(..len-1) {
264 chunk.destroy(chunk.entries);
270 // Drops the contents of the last chunk. The last chunk is partially empty, unlike all other
272 fn clear_last_chunk(&self, last_chunk: &mut TypedArenaChunk<T>) {
273 // Determine how much was filled.
274 let start = last_chunk.start() as usize;
275 // We obtain the value of the pointer to the first uninitialized element.
276 let end = self.ptr.get() as usize;
277 // We then calculate the number of elements to be dropped in the last chunk,
278 // which is the filled area's length.
279 let diff = if mem::size_of::<T>() == 0 {
280 // `T` is ZST. It can't have a drop flag, so the value here doesn't matter. We get
281 // the number of zero-sized values in the last and only chunk, just out of caution.
282 // Recall that `end` was incremented for each allocated value.
285 (end - start) / mem::size_of::<T>()
287 // Pass that to the `destroy` method.
289 last_chunk.destroy(diff);
292 self.ptr.set(last_chunk.start());
296 unsafe impl<#[may_dangle] T> Drop for TypedArena<T> {
299 // Determine how much was filled.
300 let mut chunks_borrow = self.chunks.borrow_mut();
301 if let Some(mut last_chunk) = chunks_borrow.pop() {
302 // Drop the contents of the last chunk.
303 self.clear_last_chunk(&mut last_chunk);
304 // The last chunk will be dropped. Destroy all other chunks.
305 for chunk in chunks_borrow.iter_mut() {
306 chunk.destroy(chunk.entries);
309 // RawVec handles deallocation of `last_chunk` and `self.chunks`.
314 unsafe impl<T: Send> Send for TypedArena<T> {}
316 pub struct DroplessArena {
317 /// A pointer to the next object to be allocated.
320 /// A pointer to the end of the allocated area. When this pointer is
321 /// reached, a new chunk is allocated.
324 /// A vector of arena chunks.
325 chunks: RefCell<Vec<TypedArenaChunk<u8>>>,
328 unsafe impl Send for DroplessArena {}
330 impl Default for DroplessArena {
332 fn default() -> DroplessArena {
334 ptr: Cell::new(ptr::null_mut()),
335 end: Cell::new(ptr::null_mut()),
336 chunks: Default::default(),
342 pub fn in_arena<T: ?Sized>(&self, ptr: *const T) -> bool {
343 let ptr = ptr as *const u8 as *mut u8;
345 self.chunks.borrow().iter().any(|chunk| chunk.start() <= ptr && ptr < chunk.end())
349 fn align(&self, align: usize) {
350 let final_address = ((self.ptr.get() as usize) + align - 1) & !(align - 1);
351 self.ptr.set(final_address as *mut u8);
352 assert!(self.ptr <= self.end);
357 fn grow(&self, needed_bytes: usize) {
359 let mut chunks = self.chunks.borrow_mut();
360 let (chunk, mut new_capacity);
361 if let Some(last_chunk) = chunks.last_mut() {
362 let used_bytes = self.ptr.get() as usize - last_chunk.start() as usize;
365 .reserve_in_place(used_bytes, needed_bytes)
367 self.end.set(last_chunk.end());
370 new_capacity = last_chunk.storage.capacity();
372 new_capacity = new_capacity.checked_mul(2).unwrap();
373 if new_capacity >= used_bytes + needed_bytes {
379 new_capacity = cmp::max(needed_bytes, PAGE);
381 chunk = TypedArenaChunk::<u8>::new(new_capacity);
382 self.ptr.set(chunk.start());
383 self.end.set(chunk.end());
389 pub fn alloc_raw(&self, bytes: usize, align: usize) -> &mut [u8] {
395 let future_end = intrinsics::arith_offset(self.ptr.get(), bytes as isize);
396 if (future_end as *mut u8) >= self.end.get() {
400 let ptr = self.ptr.get();
401 // Set the pointer past ourselves
403 intrinsics::arith_offset(self.ptr.get(), bytes as isize) as *mut u8,
405 slice::from_raw_parts_mut(ptr, bytes)
410 pub fn alloc<T>(&self, object: T) -> &mut T {
411 assert!(!mem::needs_drop::<T>());
413 let mem = self.alloc_raw(
415 mem::align_of::<T>()) as *mut _ as *mut T;
418 // Write into uninitialized memory.
419 ptr::write(mem, object);
424 /// Allocates a slice of objects that are copied into the `DroplessArena`, returning a mutable
425 /// reference to it. Will panic if passed a zero-sized type.
429 /// - Zero-sized types
430 /// - Zero-length slices
432 pub fn alloc_slice<T>(&self, slice: &[T]) -> &mut [T]
436 assert!(!mem::needs_drop::<T>());
437 assert!(mem::size_of::<T>() != 0);
438 assert!(!slice.is_empty());
440 let mem = self.alloc_raw(
441 slice.len() * mem::size_of::<T>(),
442 mem::align_of::<T>()) as *mut _ as *mut T;
445 let arena_slice = slice::from_raw_parts_mut(mem, slice.len());
446 arena_slice.copy_from_slice(slice);
452 unsafe fn write_from_iter<T, I: Iterator<Item = T>>(
459 // Use a manual loop since LLVM manages to optimize it better for
462 let value = iter.next();
463 if i >= len || value.is_none() {
464 // We only return as many items as the iterator gave us, even
465 // though it was supposed to give us `len`
466 return slice::from_raw_parts_mut(mem, i);
468 ptr::write(mem.add(i), value.unwrap());
474 pub fn alloc_from_iter<T, I: IntoIterator<Item = T>>(&self, iter: I) -> &mut [T] {
475 let iter = iter.into_iter();
476 assert!(mem::size_of::<T>() != 0);
477 assert!(!mem::needs_drop::<T>());
479 let size_hint = iter.size_hint();
482 (min, Some(max)) if min == max => {
483 // We know the exact number of elements the iterator will produce here
489 let size = len.checked_mul(mem::size_of::<T>()).unwrap();
490 let mem = self.alloc_raw(size, mem::align_of::<T>()) as *mut _ as *mut T;
492 self.write_from_iter(iter, len, mem)
496 cold_path(move || -> &mut [T] {
497 let mut vec: SmallVec<[_; 8]> = iter.collect();
501 // Move the content to the arena by copying it and then forgetting
502 // the content of the SmallVec
505 let start_ptr = self.alloc_raw(
506 len * mem::size_of::<T>(),
508 ) as *mut _ as *mut T;
509 vec.as_ptr().copy_to_nonoverlapping(start_ptr, len);
511 slice::from_raw_parts_mut(start_ptr, len)
520 // FIXME(@Zoxc): this type is entirely unused in rustc
521 pub struct SyncTypedArena<T> {
522 lock: MTLock<TypedArena<T>>,
525 impl<T> SyncTypedArena<T> {
527 pub fn alloc(&self, object: T) -> &mut T {
528 // Extend the lifetime of the result since it's limited to the lock guard
529 unsafe { &mut *(self.lock.lock().alloc(object) as *mut T) }
533 pub fn alloc_slice(&self, slice: &[T]) -> &mut [T]
537 // Extend the lifetime of the result since it's limited to the lock guard
538 unsafe { &mut *(self.lock.lock().alloc_slice(slice) as *mut [T]) }
542 pub fn clear(&mut self) {
543 self.lock.get_mut().clear();
548 pub struct SyncDroplessArena {
549 lock: MTLock<DroplessArena>,
552 impl SyncDroplessArena {
554 pub fn in_arena<T: ?Sized>(&self, ptr: *const T) -> bool {
555 self.lock.lock().in_arena(ptr)
559 pub fn alloc_raw(&self, bytes: usize, align: usize) -> &mut [u8] {
560 // Extend the lifetime of the result since it's limited to the lock guard
561 unsafe { &mut *(self.lock.lock().alloc_raw(bytes, align) as *mut [u8]) }
565 pub fn alloc<T>(&self, object: T) -> &mut T {
566 // Extend the lifetime of the result since it's limited to the lock guard
567 unsafe { &mut *(self.lock.lock().alloc(object) as *mut T) }
571 pub fn alloc_slice<T>(&self, slice: &[T]) -> &mut [T]
575 // Extend the lifetime of the result since it's limited to the lock guard
576 unsafe { &mut *(self.lock.lock().alloc_slice(slice) as *mut [T]) }