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 iter = iter.into_iter();
206 let size_hint = iter.size_hint();
209 (min, Some(max)) if min == max => {
210 // We know the exact number of elements the iterator will produce here
217 self.ensure_capacity(len);
219 let slice = self.ptr.get();
222 let mut ptr = self.ptr.get();
224 // Write into uninitialized memory.
225 ptr::write(ptr, iter.next().unwrap());
226 // Advance the pointer.
228 // Update the pointer per iteration so if `iter.next()` panics
229 // we destroy the correct amount
232 slice::from_raw_parts_mut(slice, len)
236 cold_path(move || -> &mut [T] {
237 let mut vec: SmallVec<[_; 8]> = iter.collect();
241 // Move the content to the arena by copying it and then forgetting
242 // the content of the SmallVec
245 let start_ptr = self.alloc_raw_slice(len);
246 vec.as_ptr().copy_to_nonoverlapping(start_ptr, len);
248 slice::from_raw_parts_mut(start_ptr, len)
258 fn grow(&self, n: usize) {
260 let mut chunks = self.chunks.borrow_mut();
261 let (chunk, mut new_capacity);
262 if let Some(last_chunk) = chunks.last_mut() {
263 let used_bytes = self.ptr.get() as usize - last_chunk.start() as usize;
264 let currently_used_cap = used_bytes / mem::size_of::<T>();
265 last_chunk.entries = currently_used_cap;
266 if last_chunk.storage.reserve_in_place(currently_used_cap, n) {
267 self.end.set(last_chunk.end());
270 new_capacity = last_chunk.storage.capacity();
272 new_capacity = new_capacity.checked_mul(2).unwrap();
273 if new_capacity >= currently_used_cap + n {
279 let elem_size = cmp::max(1, mem::size_of::<T>());
280 new_capacity = cmp::max(n, PAGE / elem_size);
282 chunk = TypedArenaChunk::<T>::new(new_capacity);
283 self.ptr.set(chunk.start());
284 self.end.set(chunk.end());
289 /// Clears the arena. Deallocates all but the longest chunk which may be reused.
290 pub fn clear(&mut self) {
292 // Clear the last chunk, which is partially filled.
293 let mut chunks_borrow = self.chunks.borrow_mut();
294 if let Some(mut last_chunk) = chunks_borrow.last_mut() {
295 self.clear_last_chunk(&mut last_chunk);
296 let len = chunks_borrow.len();
297 // If `T` is ZST, code below has no effect.
298 for mut chunk in chunks_borrow.drain(..len-1) {
299 chunk.destroy(chunk.entries);
305 // Drops the contents of the last chunk. The last chunk is partially empty, unlike all other
307 fn clear_last_chunk(&self, last_chunk: &mut TypedArenaChunk<T>) {
308 // Determine how much was filled.
309 let start = last_chunk.start() as usize;
310 // We obtain the value of the pointer to the first uninitialized element.
311 let end = self.ptr.get() as usize;
312 // We then calculate the number of elements to be dropped in the last chunk,
313 // which is the filled area's length.
314 let diff = if mem::size_of::<T>() == 0 {
315 // `T` is ZST. It can't have a drop flag, so the value here doesn't matter. We get
316 // the number of zero-sized values in the last and only chunk, just out of caution.
317 // Recall that `end` was incremented for each allocated value.
320 (end - start) / mem::size_of::<T>()
322 // Pass that to the `destroy` method.
324 last_chunk.destroy(diff);
327 self.ptr.set(last_chunk.start());
331 unsafe impl<#[may_dangle] T> Drop for TypedArena<T> {
334 // Determine how much was filled.
335 let mut chunks_borrow = self.chunks.borrow_mut();
336 if let Some(mut last_chunk) = chunks_borrow.pop() {
337 // Drop the contents of the last chunk.
338 self.clear_last_chunk(&mut last_chunk);
339 // The last chunk will be dropped. Destroy all other chunks.
340 for chunk in chunks_borrow.iter_mut() {
341 chunk.destroy(chunk.entries);
344 // RawVec handles deallocation of `last_chunk` and `self.chunks`.
349 unsafe impl<T: Send> Send for TypedArena<T> {}
351 pub struct DroplessArena {
352 /// A pointer to the next object to be allocated.
355 /// A pointer to the end of the allocated area. When this pointer is
356 /// reached, a new chunk is allocated.
359 /// A vector of arena chunks.
360 chunks: RefCell<Vec<TypedArenaChunk<u8>>>,
363 unsafe impl Send for DroplessArena {}
365 impl Default for DroplessArena {
367 fn default() -> DroplessArena {
369 ptr: Cell::new(ptr::null_mut()),
370 end: Cell::new(ptr::null_mut()),
371 chunks: Default::default(),
377 pub fn in_arena<T: ?Sized>(&self, ptr: *const T) -> bool {
378 let ptr = ptr as *const u8 as *mut u8;
380 self.chunks.borrow().iter().any(|chunk| chunk.start() <= ptr && ptr < chunk.end())
384 fn align(&self, align: usize) {
385 let final_address = ((self.ptr.get() as usize) + align - 1) & !(align - 1);
386 self.ptr.set(final_address as *mut u8);
387 assert!(self.ptr <= self.end);
392 fn grow(&self, needed_bytes: usize) {
394 let mut chunks = self.chunks.borrow_mut();
395 let (chunk, mut new_capacity);
396 if let Some(last_chunk) = chunks.last_mut() {
397 let used_bytes = self.ptr.get() as usize - last_chunk.start() as usize;
400 .reserve_in_place(used_bytes, needed_bytes)
402 self.end.set(last_chunk.end());
405 new_capacity = last_chunk.storage.capacity();
407 new_capacity = new_capacity.checked_mul(2).unwrap();
408 if new_capacity >= used_bytes + needed_bytes {
414 new_capacity = cmp::max(needed_bytes, PAGE);
416 chunk = TypedArenaChunk::<u8>::new(new_capacity);
417 self.ptr.set(chunk.start());
418 self.end.set(chunk.end());
424 pub fn alloc_raw(&self, bytes: usize, align: usize) -> &mut [u8] {
430 let future_end = intrinsics::arith_offset(self.ptr.get(), bytes as isize);
431 if (future_end as *mut u8) >= self.end.get() {
435 let ptr = self.ptr.get();
436 // Set the pointer past ourselves
438 intrinsics::arith_offset(self.ptr.get(), bytes as isize) as *mut u8,
440 slice::from_raw_parts_mut(ptr, bytes)
445 pub fn alloc<T>(&self, object: T) -> &mut T {
446 assert!(!mem::needs_drop::<T>());
448 let mem = self.alloc_raw(
450 mem::align_of::<T>()) as *mut _ as *mut T;
453 // Write into uninitialized memory.
454 ptr::write(mem, object);
459 /// Allocates a slice of objects that are copied into the `DroplessArena`, returning a mutable
460 /// reference to it. Will panic if passed a zero-sized type.
464 /// - Zero-sized types
465 /// - Zero-length slices
467 pub fn alloc_slice<T>(&self, slice: &[T]) -> &mut [T]
471 assert!(!mem::needs_drop::<T>());
472 assert!(mem::size_of::<T>() != 0);
473 assert!(!slice.is_empty());
475 let mem = self.alloc_raw(
476 slice.len() * mem::size_of::<T>(),
477 mem::align_of::<T>()) as *mut _ as *mut T;
480 let arena_slice = slice::from_raw_parts_mut(mem, slice.len());
481 arena_slice.copy_from_slice(slice);
487 unsafe fn write_from_iter<T, I: Iterator<Item = T>>(
494 // Use a manual loop since LLVM manages to optimize it better for
497 let value = iter.next();
498 if i >= len || value.is_none() {
499 // We only return as many items as the iterator gave us, even
500 // though it was supposed to give us `len`
501 return slice::from_raw_parts_mut(mem, i);
503 ptr::write(mem.add(i), value.unwrap());
509 pub fn alloc_from_iter<T, I: IntoIterator<Item = T>>(&self, iter: I) -> &mut [T] {
510 let iter = iter.into_iter();
511 assert!(mem::size_of::<T>() != 0);
512 assert!(!mem::needs_drop::<T>());
514 let size_hint = iter.size_hint();
517 (min, Some(max)) if min == max => {
518 // We know the exact number of elements the iterator will produce here
524 let size = len.checked_mul(mem::size_of::<T>()).unwrap();
525 let mem = self.alloc_raw(size, mem::align_of::<T>()) as *mut _ as *mut T;
527 self.write_from_iter(iter, len, mem)
531 cold_path(move || -> &mut [T] {
532 let mut vec: SmallVec<[_; 8]> = iter.collect();
536 // Move the content to the arena by copying it and then forgetting
537 // the content of the SmallVec
540 let start_ptr = self.alloc_raw(
541 len * mem::size_of::<T>(),
543 ) as *mut _ as *mut T;
544 vec.as_ptr().copy_to_nonoverlapping(start_ptr, len);
546 slice::from_raw_parts_mut(start_ptr, len)
555 // FIXME(@Zoxc): this type is entirely unused in rustc
556 pub struct SyncTypedArena<T> {
557 lock: MTLock<TypedArena<T>>,
560 impl<T> SyncTypedArena<T> {
562 pub fn alloc(&self, object: T) -> &mut T {
563 // Extend the lifetime of the result since it's limited to the lock guard
564 unsafe { &mut *(self.lock.lock().alloc(object) as *mut T) }
568 pub fn alloc_slice(&self, slice: &[T]) -> &mut [T]
572 // Extend the lifetime of the result since it's limited to the lock guard
573 unsafe { &mut *(self.lock.lock().alloc_slice(slice) as *mut [T]) }
577 pub fn clear(&mut self) {
578 self.lock.get_mut().clear();
583 pub struct SyncDroplessArena {
584 lock: MTLock<DroplessArena>,
587 impl SyncDroplessArena {
589 pub fn in_arena<T: ?Sized>(&self, ptr: *const T) -> bool {
590 self.lock.lock().in_arena(ptr)
594 pub fn alloc_raw(&self, bytes: usize, align: usize) -> &mut [u8] {
595 // Extend the lifetime of the result since it's limited to the lock guard
596 unsafe { &mut *(self.lock.lock().alloc_raw(bytes, align) as *mut [u8]) }
600 pub fn alloc<T>(&self, object: T) -> &mut T {
601 // Extend the lifetime of the result since it's limited to the lock guard
602 unsafe { &mut *(self.lock.lock().alloc(object) as *mut T) }
606 pub fn alloc_slice<T>(&self, slice: &[T]) -> &mut [T]
610 // Extend the lifetime of the result since it's limited to the lock guard
611 unsafe { &mut *(self.lock.lock().alloc_slice(slice) as *mut [T]) }