1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! The arena, a fast but limited type of allocator.
13 //! Arenas are a type of allocator that destroy the objects within, all at
14 //! once, once the arena itself is destroyed. They do not support deallocation
15 //! of individual objects while the arena itself is still alive. The benefit
16 //! of an arena is very fast allocation; just a pointer bump.
18 //! This crate implements `TypedArena`, a simple arena that can only hold
19 //! objects of a single type.
21 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
22 html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
23 html_root_url = "https://doc.rust-lang.org/nightly/",
24 test(no_crate_inject, attr(deny(warnings))))]
27 #![feature(core_intrinsics)]
28 #![feature(dropck_eyepatch)]
30 #![feature(raw_vec_internals)]
31 #![cfg_attr(test, feature(test))]
36 extern crate rustc_data_structures;
38 use rustc_data_structures::sync::MTLock;
40 use std::cell::{Cell, RefCell};
43 use std::marker::{PhantomData, Send};
48 use alloc::raw_vec::RawVec;
50 /// An arena that can hold objects of only one type.
51 pub struct TypedArena<T> {
52 /// A pointer to the next object to be allocated.
55 /// A pointer to the end of the allocated area. When this pointer is
56 /// reached, a new chunk is allocated.
59 /// A vector of arena chunks.
60 chunks: RefCell<Vec<TypedArenaChunk<T>>>,
62 /// Marker indicating that dropping the arena causes its owned
63 /// instances of `T` to be dropped.
67 struct TypedArenaChunk<T> {
68 /// The raw storage for the arena chunk.
72 impl<T> TypedArenaChunk<T> {
74 unsafe fn new(capacity: usize) -> TypedArenaChunk<T> {
76 storage: RawVec::with_capacity(capacity),
80 /// Destroys this arena chunk.
82 unsafe fn destroy(&mut self, len: usize) {
83 // The branch on needs_drop() is an -O1 performance optimization.
84 // Without the branch, dropping TypedArena<u8> takes linear time.
85 if mem::needs_drop::<T>() {
86 let mut start = self.start();
87 // Destroy all allocated objects.
89 ptr::drop_in_place(start);
90 start = start.offset(1);
95 // Returns a pointer to the first allocated object.
97 fn start(&self) -> *mut T {
101 // Returns a pointer to the end of the allocated space.
103 fn end(&self) -> *mut T {
105 if mem::size_of::<T>() == 0 {
106 // A pointer as large as possible for zero-sized elements.
109 self.start().add(self.storage.cap())
115 const PAGE: usize = 4096;
117 impl<T> Default for TypedArena<T> {
118 /// Creates a new `TypedArena`.
119 fn default() -> TypedArena<T> {
121 // We set both `ptr` and `end` to 0 so that the first call to
122 // alloc() will trigger a grow().
123 ptr: Cell::new(0 as *mut T),
124 end: Cell::new(0 as *mut T),
125 chunks: RefCell::new(vec![]),
131 impl<T> TypedArena<T> {
132 /// Allocates an object in the `TypedArena`, returning a reference to it.
134 pub fn alloc(&self, object: T) -> &mut T {
135 if self.ptr == self.end {
140 if mem::size_of::<T>() == 0 {
142 .set(intrinsics::arith_offset(self.ptr.get() as *mut u8, 1)
144 let ptr = mem::align_of::<T>() as *mut T;
145 // Don't drop the object. This `write` is equivalent to `forget`.
146 ptr::write(ptr, object);
149 let ptr = self.ptr.get();
150 // Advance the pointer.
151 self.ptr.set(self.ptr.get().offset(1));
152 // Write into uninitialized memory.
153 ptr::write(ptr, object);
159 /// Allocates a slice of objects that are copied into the `TypedArena`, returning a mutable
160 /// reference to it. Will panic if passed a zero-sized types.
164 /// - Zero-sized types
165 /// - Zero-length slices
167 pub fn alloc_slice(&self, slice: &[T]) -> &mut [T]
171 assert!(mem::size_of::<T>() != 0);
172 assert!(slice.len() != 0);
174 let available_capacity_bytes = self.end.get() as usize - self.ptr.get() as usize;
175 let at_least_bytes = slice.len() * mem::size_of::<T>();
176 if available_capacity_bytes < at_least_bytes {
177 self.grow(slice.len());
181 let start_ptr = self.ptr.get();
182 let arena_slice = slice::from_raw_parts_mut(start_ptr, slice.len());
183 self.ptr.set(start_ptr.add(arena_slice.len()));
184 arena_slice.copy_from_slice(slice);
192 fn grow(&self, n: usize) {
194 let mut chunks = self.chunks.borrow_mut();
195 let (chunk, mut new_capacity);
196 if let Some(last_chunk) = chunks.last_mut() {
197 let used_bytes = self.ptr.get() as usize - last_chunk.start() as usize;
198 let currently_used_cap = used_bytes / mem::size_of::<T>();
199 if last_chunk.storage.reserve_in_place(currently_used_cap, n) {
200 self.end.set(last_chunk.end());
203 new_capacity = last_chunk.storage.cap();
205 new_capacity = new_capacity.checked_mul(2).unwrap();
206 if new_capacity >= currently_used_cap + n {
212 let elem_size = cmp::max(1, mem::size_of::<T>());
213 new_capacity = cmp::max(n, PAGE / elem_size);
215 chunk = TypedArenaChunk::<T>::new(new_capacity);
216 self.ptr.set(chunk.start());
217 self.end.set(chunk.end());
222 /// Clears the arena. Deallocates all but the longest chunk which may be reused.
223 pub fn clear(&mut self) {
225 // Clear the last chunk, which is partially filled.
226 let mut chunks_borrow = self.chunks.borrow_mut();
227 if let Some(mut last_chunk) = chunks_borrow.pop() {
228 self.clear_last_chunk(&mut last_chunk);
229 // If `T` is ZST, code below has no effect.
230 for mut chunk in chunks_borrow.drain(..) {
231 let cap = chunk.storage.cap();
234 chunks_borrow.push(last_chunk);
239 // Drops the contents of the last chunk. The last chunk is partially empty, unlike all other
241 fn clear_last_chunk(&self, last_chunk: &mut TypedArenaChunk<T>) {
242 // Determine how much was filled.
243 let start = last_chunk.start() as usize;
244 // We obtain the value of the pointer to the first uninitialized element.
245 let end = self.ptr.get() as usize;
246 // We then calculate the number of elements to be dropped in the last chunk,
247 // which is the filled area's length.
248 let diff = if mem::size_of::<T>() == 0 {
249 // `T` is ZST. It can't have a drop flag, so the value here doesn't matter. We get
250 // the number of zero-sized values in the last and only chunk, just out of caution.
251 // Recall that `end` was incremented for each allocated value.
254 (end - start) / mem::size_of::<T>()
256 // Pass that to the `destroy` method.
258 last_chunk.destroy(diff);
261 self.ptr.set(last_chunk.start());
265 unsafe impl<#[may_dangle] T> Drop for TypedArena<T> {
268 // Determine how much was filled.
269 let mut chunks_borrow = self.chunks.borrow_mut();
270 if let Some(mut last_chunk) = chunks_borrow.pop() {
271 // Drop the contents of the last chunk.
272 self.clear_last_chunk(&mut last_chunk);
273 // The last chunk will be dropped. Destroy all other chunks.
274 for chunk in chunks_borrow.iter_mut() {
275 let cap = chunk.storage.cap();
279 // RawVec handles deallocation of `last_chunk` and `self.chunks`.
284 unsafe impl<T: Send> Send for TypedArena<T> {}
286 pub struct DroplessArena {
287 /// A pointer to the next object to be allocated.
290 /// A pointer to the end of the allocated area. When this pointer is
291 /// reached, a new chunk is allocated.
294 /// A vector of arena chunks.
295 chunks: RefCell<Vec<TypedArenaChunk<u8>>>,
298 unsafe impl Send for DroplessArena {}
300 impl Default for DroplessArena {
302 fn default() -> DroplessArena {
304 ptr: Cell::new(0 as *mut u8),
305 end: Cell::new(0 as *mut u8),
306 chunks: Default::default(),
312 pub fn in_arena<T: ?Sized>(&self, ptr: *const T) -> bool {
313 let ptr = ptr as *const u8 as *mut u8;
314 for chunk in &*self.chunks.borrow() {
315 if chunk.start() <= ptr && ptr < chunk.end() {
324 fn align(&self, align: usize) {
325 let final_address = ((self.ptr.get() as usize) + align - 1) & !(align - 1);
326 self.ptr.set(final_address as *mut u8);
327 assert!(self.ptr <= self.end);
332 fn grow(&self, needed_bytes: usize) {
334 let mut chunks = self.chunks.borrow_mut();
335 let (chunk, mut new_capacity);
336 if let Some(last_chunk) = chunks.last_mut() {
337 let used_bytes = self.ptr.get() as usize - last_chunk.start() as usize;
340 .reserve_in_place(used_bytes, needed_bytes)
342 self.end.set(last_chunk.end());
345 new_capacity = last_chunk.storage.cap();
347 new_capacity = new_capacity.checked_mul(2).unwrap();
348 if new_capacity >= used_bytes + needed_bytes {
354 new_capacity = cmp::max(needed_bytes, PAGE);
356 chunk = TypedArenaChunk::<u8>::new(new_capacity);
357 self.ptr.set(chunk.start());
358 self.end.set(chunk.end());
364 pub fn alloc_raw(&self, bytes: usize, align: usize) -> &mut [u8] {
370 let future_end = intrinsics::arith_offset(self.ptr.get(), bytes as isize);
371 if (future_end as *mut u8) >= self.end.get() {
375 let ptr = self.ptr.get();
376 // Set the pointer past ourselves
378 intrinsics::arith_offset(self.ptr.get(), bytes as isize) as *mut u8,
380 slice::from_raw_parts_mut(ptr, bytes)
385 pub fn alloc<T>(&self, object: T) -> &mut T {
386 assert!(!mem::needs_drop::<T>());
388 let mem = self.alloc_raw(
390 mem::align_of::<T>()) as *mut _ as *mut T;
393 // Write into uninitialized memory.
394 ptr::write(mem, object);
399 /// Allocates a slice of objects that are copied into the `DroplessArena`, returning a mutable
400 /// reference to it. Will panic if passed a zero-sized type.
404 /// - Zero-sized types
405 /// - Zero-length slices
407 pub fn alloc_slice<T>(&self, slice: &[T]) -> &mut [T]
411 assert!(!mem::needs_drop::<T>());
412 assert!(mem::size_of::<T>() != 0);
413 assert!(slice.len() != 0);
415 let mem = self.alloc_raw(
416 slice.len() * mem::size_of::<T>(),
417 mem::align_of::<T>()) as *mut _ as *mut T;
420 let arena_slice = slice::from_raw_parts_mut(mem, slice.len());
421 arena_slice.copy_from_slice(slice);
428 // FIXME(@Zoxc): this type is entirely unused in rustc
429 pub struct SyncTypedArena<T> {
430 lock: MTLock<TypedArena<T>>,
433 impl<T> SyncTypedArena<T> {
435 pub fn alloc(&self, object: T) -> &mut T {
436 // Extend the lifetime of the result since it's limited to the lock guard
437 unsafe { &mut *(self.lock.lock().alloc(object) as *mut T) }
441 pub fn alloc_slice(&self, slice: &[T]) -> &mut [T]
445 // Extend the lifetime of the result since it's limited to the lock guard
446 unsafe { &mut *(self.lock.lock().alloc_slice(slice) as *mut [T]) }
450 pub fn clear(&mut self) {
451 self.lock.get_mut().clear();
456 pub struct SyncDroplessArena {
457 lock: MTLock<DroplessArena>,
460 impl SyncDroplessArena {
462 pub fn in_arena<T: ?Sized>(&self, ptr: *const T) -> bool {
463 self.lock.lock().in_arena(ptr)
467 pub fn alloc_raw(&self, bytes: usize, align: usize) -> &mut [u8] {
468 // Extend the lifetime of the result since it's limited to the lock guard
469 unsafe { &mut *(self.lock.lock().alloc_raw(bytes, align) as *mut [u8]) }
473 pub fn alloc<T>(&self, object: T) -> &mut T {
474 // Extend the lifetime of the result since it's limited to the lock guard
475 unsafe { &mut *(self.lock.lock().alloc(object) as *mut T) }
479 pub fn alloc_slice<T>(&self, slice: &[T]) -> &mut [T]
483 // Extend the lifetime of the result since it's limited to the lock guard
484 unsafe { &mut *(self.lock.lock().alloc_slice(slice) as *mut [T]) }
491 use self::test::Bencher;
492 use super::TypedArena;
496 #[derive(Debug, Eq, PartialEq)]
504 pub fn test_unused() {
505 let arena: TypedArena<Point> = TypedArena::default();
506 assert!(arena.chunks.borrow().is_empty());
510 fn test_arena_alloc_nested() {
522 struct Wrap<'a>(TypedArena<EI<'a>>);
525 fn alloc_inner<F: Fn() -> Inner>(&self, f: F) -> &Inner {
526 let r: &EI = self.0.alloc(EI::I(f()));
527 if let &EI::I(ref i) = r {
533 fn alloc_outer<F: Fn() -> Outer<'a>>(&self, f: F) -> &Outer {
534 let r: &EI = self.0.alloc(EI::O(f()));
535 if let &EI::O(ref o) = r {
543 let arena = Wrap(TypedArena::default());
545 let result = arena.alloc_outer(|| Outer {
546 inner: arena.alloc_inner(|| Inner { value: 10 }),
549 assert_eq!(result.inner.value, 10);
554 let arena = TypedArena::default();
556 arena.alloc(Point { x: 1, y: 2, z: 3 });
561 pub fn bench_copy(b: &mut Bencher) {
562 let arena = TypedArena::default();
563 b.iter(|| arena.alloc(Point { x: 1, y: 2, z: 3 }))
567 pub fn bench_copy_nonarena(b: &mut Bencher) {
569 let _: Box<_> = Box::new(Point { x: 1, y: 2, z: 3 });
580 pub fn test_noncopy() {
581 let arena = TypedArena::default();
583 arena.alloc(Noncopy {
584 string: "hello world".to_string(),
585 array: vec![1, 2, 3, 4, 5],
591 pub fn test_typed_arena_zero_sized() {
592 let arena = TypedArena::default();
599 pub fn test_typed_arena_clear() {
600 let mut arena = TypedArena::default();
604 arena.alloc(Point { x: 1, y: 2, z: 3 });
611 struct DropCounter<'a> {
612 count: &'a Cell<u32>,
615 impl<'a> Drop for DropCounter<'a> {
617 self.count.set(self.count.get() + 1);
622 fn test_typed_arena_drop_count() {
623 let counter = Cell::new(0);
625 let arena: TypedArena<DropCounter> = TypedArena::default();
627 // Allocate something with drop glue to make sure it doesn't leak.
628 arena.alloc(DropCounter { count: &counter });
631 assert_eq!(counter.get(), 100);
635 fn test_typed_arena_drop_on_clear() {
636 let counter = Cell::new(0);
637 let mut arena: TypedArena<DropCounter> = TypedArena::default();
640 // Allocate something with drop glue to make sure it doesn't leak.
641 arena.alloc(DropCounter { count: &counter });
644 assert_eq!(counter.get(), i * 100 + 100);
649 static DROP_COUNTER: Cell<u32> = Cell::new(0)
652 struct SmallDroppable;
654 impl Drop for SmallDroppable {
656 DROP_COUNTER.with(|c| c.set(c.get() + 1));
661 fn test_typed_arena_drop_small_count() {
662 DROP_COUNTER.with(|c| c.set(0));
664 let arena: TypedArena<SmallDroppable> = TypedArena::default();
666 // Allocate something with drop glue to make sure it doesn't leak.
667 arena.alloc(SmallDroppable);
671 assert_eq!(DROP_COUNTER.with(|c| c.get()), 100);
675 pub fn bench_noncopy(b: &mut Bencher) {
676 let arena = TypedArena::default();
678 arena.alloc(Noncopy {
679 string: "hello world".to_string(),
680 array: vec![1, 2, 3, 4, 5],
686 pub fn bench_noncopy_nonarena(b: &mut Bencher) {
688 let _: Box<_> = Box::new(Noncopy {
689 string: "hello world".to_string(),
690 array: vec![1, 2, 3, 4, 5],