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 #![deny(rust_2018_idioms)]
15 #![deny(unused_lifetimes)]
17 #![feature(core_intrinsics)]
18 #![feature(dropck_eyepatch)]
19 #![feature(raw_vec_internals)]
20 #![cfg_attr(test, feature(test))]
26 use rustc_data_structures::cold_path;
27 use rustc_data_structures::sync::MTLock;
28 use smallvec::SmallVec;
30 use std::cell::{Cell, RefCell};
33 use std::marker::{PhantomData, Send};
38 use alloc::raw_vec::RawVec;
40 /// An arena that can hold objects of only one type.
41 pub struct TypedArena<T> {
42 /// A pointer to the next object to be allocated.
45 /// A pointer to the end of the allocated area. When this pointer is
46 /// reached, a new chunk is allocated.
49 /// A vector of arena chunks.
50 chunks: RefCell<Vec<TypedArenaChunk<T>>>,
52 /// Marker indicating that dropping the arena causes its owned
53 /// instances of `T` to be dropped.
57 struct TypedArenaChunk<T> {
58 /// The raw storage for the arena chunk.
60 /// The number of valid entries in the chunk.
64 impl<T> TypedArenaChunk<T> {
66 unsafe fn new(capacity: usize) -> TypedArenaChunk<T> {
68 storage: RawVec::with_capacity(capacity),
73 /// Destroys this arena chunk.
75 unsafe fn destroy(&mut self, len: usize) {
76 // The branch on needs_drop() is an -O1 performance optimization.
77 // Without the branch, dropping TypedArena<u8> takes linear time.
78 if mem::needs_drop::<T>() {
79 let mut start = self.start();
80 // Destroy all allocated objects.
82 ptr::drop_in_place(start);
83 start = start.offset(1);
88 // Returns a pointer to the first allocated object.
90 fn start(&self) -> *mut T {
94 // Returns a pointer to the end of the allocated space.
96 fn end(&self) -> *mut T {
98 if mem::size_of::<T>() == 0 {
99 // A pointer as large as possible for zero-sized elements.
102 self.start().add(self.storage.capacity())
108 const PAGE: usize = 4096;
110 impl<T> Default for TypedArena<T> {
111 /// Creates a new `TypedArena`.
112 fn default() -> TypedArena<T> {
114 // We set both `ptr` and `end` to 0 so that the first call to
115 // alloc() will trigger a grow().
116 ptr: Cell::new(ptr::null_mut()),
117 end: Cell::new(ptr::null_mut()),
118 chunks: RefCell::new(vec![]),
124 impl<T> TypedArena<T> {
125 pub fn in_arena(&self, ptr: *const T) -> bool {
126 let ptr = ptr as *const T as *mut T;
128 self.chunks.borrow().iter().any(|chunk| chunk.start() <= ptr && ptr < chunk.end())
130 /// Allocates an object in the `TypedArena`, returning a reference to it.
132 pub fn alloc(&self, object: T) -> &mut T {
133 if self.ptr == self.end {
138 if mem::size_of::<T>() == 0 {
140 .set(intrinsics::arith_offset(self.ptr.get() as *mut u8, 1)
142 let ptr = mem::align_of::<T>() as *mut T;
143 // Don't drop the object. This `write` is equivalent to `forget`.
144 ptr::write(ptr, object);
147 let ptr = self.ptr.get();
148 // Advance the pointer.
149 self.ptr.set(self.ptr.get().offset(1));
150 // Write into uninitialized memory.
151 ptr::write(ptr, object);
158 fn can_allocate(&self, len: usize) -> bool {
159 let available_capacity_bytes = self.end.get() as usize - self.ptr.get() as usize;
160 let at_least_bytes = len.checked_mul(mem::size_of::<T>()).unwrap();
161 available_capacity_bytes >= at_least_bytes
164 /// Ensures there's enough space in the current chunk to fit `len` objects.
166 fn ensure_capacity(&self, len: usize) {
167 if !self.can_allocate(len) {
169 debug_assert!(self.can_allocate(len));
174 unsafe fn alloc_raw_slice(&self, len: usize) -> *mut T {
175 assert!(mem::size_of::<T>() != 0);
178 self.ensure_capacity(len);
180 let start_ptr = self.ptr.get();
181 self.ptr.set(start_ptr.add(len));
185 /// Allocates a slice of objects that are copied into the `TypedArena`, returning a mutable
186 /// reference to it. Will panic if passed a zero-sized types.
190 /// - Zero-sized types
191 /// - Zero-length slices
193 pub fn alloc_slice(&self, slice: &[T]) -> &mut [T]
198 let len = slice.len();
199 let start_ptr = self.alloc_raw_slice(len);
200 slice.as_ptr().copy_to_nonoverlapping(start_ptr, len);
201 slice::from_raw_parts_mut(start_ptr, len)
206 pub fn alloc_from_iter<I: IntoIterator<Item = T>>(&self, iter: I) -> &mut [T] {
207 assert!(mem::size_of::<T>() != 0);
208 let mut iter = iter.into_iter();
209 let size_hint = iter.size_hint();
212 (min, Some(max)) if min == max => {
213 // We know the exact number of elements the iterator will produce here
220 self.ensure_capacity(len);
222 let slice = self.ptr.get();
225 let mut ptr = self.ptr.get();
227 // Write into uninitialized memory.
228 ptr::write(ptr, iter.next().unwrap());
229 // Advance the pointer.
231 // Update the pointer per iteration so if `iter.next()` panics
232 // we destroy the correct amount
235 slice::from_raw_parts_mut(slice, len)
239 cold_path(move || -> &mut [T] {
240 let mut vec: SmallVec<[_; 8]> = iter.collect();
244 // Move the content to the arena by copying it and then forgetting
245 // the content of the SmallVec
248 let start_ptr = self.alloc_raw_slice(len);
249 vec.as_ptr().copy_to_nonoverlapping(start_ptr, len);
251 slice::from_raw_parts_mut(start_ptr, len)
261 fn grow(&self, n: usize) {
263 let mut chunks = self.chunks.borrow_mut();
264 let (chunk, mut new_capacity);
265 if let Some(last_chunk) = chunks.last_mut() {
266 let used_bytes = self.ptr.get() as usize - last_chunk.start() as usize;
267 let currently_used_cap = used_bytes / mem::size_of::<T>();
268 last_chunk.entries = currently_used_cap;
269 if last_chunk.storage.reserve_in_place(currently_used_cap, n) {
270 self.end.set(last_chunk.end());
273 new_capacity = last_chunk.storage.capacity();
275 new_capacity = new_capacity.checked_mul(2).unwrap();
276 if new_capacity >= currently_used_cap + n {
282 let elem_size = cmp::max(1, mem::size_of::<T>());
283 new_capacity = cmp::max(n, PAGE / elem_size);
285 chunk = TypedArenaChunk::<T>::new(new_capacity);
286 self.ptr.set(chunk.start());
287 self.end.set(chunk.end());
292 /// Clears the arena. Deallocates all but the longest chunk which may be reused.
293 pub fn clear(&mut self) {
295 // Clear the last chunk, which is partially filled.
296 let mut chunks_borrow = self.chunks.borrow_mut();
297 if let Some(mut last_chunk) = chunks_borrow.last_mut() {
298 self.clear_last_chunk(&mut last_chunk);
299 let len = chunks_borrow.len();
300 // If `T` is ZST, code below has no effect.
301 for mut chunk in chunks_borrow.drain(..len-1) {
302 chunk.destroy(chunk.entries);
308 // Drops the contents of the last chunk. The last chunk is partially empty, unlike all other
310 fn clear_last_chunk(&self, last_chunk: &mut TypedArenaChunk<T>) {
311 // Determine how much was filled.
312 let start = last_chunk.start() as usize;
313 // We obtain the value of the pointer to the first uninitialized element.
314 let end = self.ptr.get() as usize;
315 // We then calculate the number of elements to be dropped in the last chunk,
316 // which is the filled area's length.
317 let diff = if mem::size_of::<T>() == 0 {
318 // `T` is ZST. It can't have a drop flag, so the value here doesn't matter. We get
319 // the number of zero-sized values in the last and only chunk, just out of caution.
320 // Recall that `end` was incremented for each allocated value.
323 (end - start) / mem::size_of::<T>()
325 // Pass that to the `destroy` method.
327 last_chunk.destroy(diff);
330 self.ptr.set(last_chunk.start());
334 unsafe impl<#[may_dangle] T> Drop for TypedArena<T> {
337 // Determine how much was filled.
338 let mut chunks_borrow = self.chunks.borrow_mut();
339 if let Some(mut last_chunk) = chunks_borrow.pop() {
340 // Drop the contents of the last chunk.
341 self.clear_last_chunk(&mut last_chunk);
342 // The last chunk will be dropped. Destroy all other chunks.
343 for chunk in chunks_borrow.iter_mut() {
344 chunk.destroy(chunk.entries);
347 // RawVec handles deallocation of `last_chunk` and `self.chunks`.
352 unsafe impl<T: Send> Send for TypedArena<T> {}
354 pub struct DroplessArena {
355 /// A pointer to the next object to be allocated.
358 /// A pointer to the end of the allocated area. When this pointer is
359 /// reached, a new chunk is allocated.
362 /// A vector of arena chunks.
363 chunks: RefCell<Vec<TypedArenaChunk<u8>>>,
366 unsafe impl Send for DroplessArena {}
368 impl Default for DroplessArena {
370 fn default() -> DroplessArena {
372 ptr: Cell::new(ptr::null_mut()),
373 end: Cell::new(ptr::null_mut()),
374 chunks: Default::default(),
380 pub fn in_arena<T: ?Sized>(&self, ptr: *const T) -> bool {
381 let ptr = ptr as *const u8 as *mut u8;
383 self.chunks.borrow().iter().any(|chunk| chunk.start() <= ptr && ptr < chunk.end())
387 fn align(&self, align: usize) {
388 let final_address = ((self.ptr.get() as usize) + align - 1) & !(align - 1);
389 self.ptr.set(final_address as *mut u8);
390 assert!(self.ptr <= self.end);
395 fn grow(&self, needed_bytes: usize) {
397 let mut chunks = self.chunks.borrow_mut();
398 let (chunk, mut new_capacity);
399 if let Some(last_chunk) = chunks.last_mut() {
400 let used_bytes = self.ptr.get() as usize - last_chunk.start() as usize;
403 .reserve_in_place(used_bytes, needed_bytes)
405 self.end.set(last_chunk.end());
408 new_capacity = last_chunk.storage.capacity();
410 new_capacity = new_capacity.checked_mul(2).unwrap();
411 if new_capacity >= used_bytes + needed_bytes {
417 new_capacity = cmp::max(needed_bytes, PAGE);
419 chunk = TypedArenaChunk::<u8>::new(new_capacity);
420 self.ptr.set(chunk.start());
421 self.end.set(chunk.end());
427 pub fn alloc_raw(&self, bytes: usize, align: usize) -> &mut [u8] {
433 let future_end = intrinsics::arith_offset(self.ptr.get(), bytes as isize);
434 if (future_end as *mut u8) >= self.end.get() {
438 let ptr = self.ptr.get();
439 // Set the pointer past ourselves
441 intrinsics::arith_offset(self.ptr.get(), bytes as isize) as *mut u8,
443 slice::from_raw_parts_mut(ptr, bytes)
448 pub fn alloc<T>(&self, object: T) -> &mut T {
449 assert!(!mem::needs_drop::<T>());
451 let mem = self.alloc_raw(
453 mem::align_of::<T>()) as *mut _ as *mut T;
456 // Write into uninitialized memory.
457 ptr::write(mem, object);
462 /// Allocates a slice of objects that are copied into the `DroplessArena`, returning a mutable
463 /// reference to it. Will panic if passed a zero-sized type.
467 /// - Zero-sized types
468 /// - Zero-length slices
470 pub fn alloc_slice<T>(&self, slice: &[T]) -> &mut [T]
474 assert!(!mem::needs_drop::<T>());
475 assert!(mem::size_of::<T>() != 0);
476 assert!(!slice.is_empty());
478 let mem = self.alloc_raw(
479 slice.len() * mem::size_of::<T>(),
480 mem::align_of::<T>()) as *mut _ as *mut T;
483 let arena_slice = slice::from_raw_parts_mut(mem, slice.len());
484 arena_slice.copy_from_slice(slice);
490 unsafe fn write_from_iter<T, I: Iterator<Item = T>>(
497 // Use a manual loop since LLVM manages to optimize it better for
500 let value = iter.next();
501 if i >= len || value.is_none() {
502 // We only return as many items as the iterator gave us, even
503 // though it was supposed to give us `len`
504 return slice::from_raw_parts_mut(mem, i);
506 ptr::write(mem.offset(i as isize), value.unwrap());
512 pub fn alloc_from_iter<T, I: IntoIterator<Item = T>>(&self, iter: I) -> &mut [T] {
513 let iter = iter.into_iter();
514 assert!(mem::size_of::<T>() != 0);
515 assert!(!mem::needs_drop::<T>());
517 let size_hint = iter.size_hint();
520 (min, Some(max)) if min == max => {
521 // We know the exact number of elements the iterator will produce here
527 let size = len.checked_mul(mem::size_of::<T>()).unwrap();
528 let mem = self.alloc_raw(size, mem::align_of::<T>()) as *mut _ as *mut T;
530 self.write_from_iter(iter, len, mem)
534 cold_path(move || -> &mut [T] {
535 let mut vec: SmallVec<[_; 8]> = iter.collect();
539 // Move the content to the arena by copying it and then forgetting
540 // the content of the SmallVec
543 let start_ptr = self.alloc_raw(
544 len * mem::size_of::<T>(),
546 ) as *mut _ as *mut T;
547 vec.as_ptr().copy_to_nonoverlapping(start_ptr, len);
549 slice::from_raw_parts_mut(start_ptr, len)
558 // FIXME(@Zoxc): this type is entirely unused in rustc
559 pub struct SyncTypedArena<T> {
560 lock: MTLock<TypedArena<T>>,
563 impl<T> SyncTypedArena<T> {
565 pub fn alloc(&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(&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]) }
580 pub fn clear(&mut self) {
581 self.lock.get_mut().clear();
586 pub struct SyncDroplessArena {
587 lock: MTLock<DroplessArena>,
590 impl SyncDroplessArena {
592 pub fn in_arena<T: ?Sized>(&self, ptr: *const T) -> bool {
593 self.lock.lock().in_arena(ptr)
597 pub fn alloc_raw(&self, bytes: usize, align: usize) -> &mut [u8] {
598 // Extend the lifetime of the result since it's limited to the lock guard
599 unsafe { &mut *(self.lock.lock().alloc_raw(bytes, align) as *mut [u8]) }
603 pub fn alloc<T>(&self, object: T) -> &mut T {
604 // Extend the lifetime of the result since it's limited to the lock guard
605 unsafe { &mut *(self.lock.lock().alloc(object) as *mut T) }
609 pub fn alloc_slice<T>(&self, slice: &[T]) -> &mut [T]
613 // Extend the lifetime of the result since it's limited to the lock guard
614 unsafe { &mut *(self.lock.lock().alloc_slice(slice) as *mut [T]) }