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 has two arenas implemented: `TypedArena`, which is a simpler
19 //! arena but can only hold objects of a single type, and `Arena`, which is a
20 //! more complex, slower arena which can hold objects of any type.
22 #![crate_name = "arena"]
23 #![unstable(feature = "rustc_private", issue = "27812")]
24 #![crate_type = "rlib"]
25 #![crate_type = "dylib"]
26 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
27 html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
28 html_root_url = "https://doc.rust-lang.org/nightly/",
29 test(no_crate_inject, attr(deny(warnings))))]
32 #![feature(core_intrinsics)]
33 #![feature(drop_in_place)]
37 #![feature(staged_api)]
38 #![feature(dropck_parametricity)]
39 #![cfg_attr(test, feature(test))]
43 use std::cell::{Cell, RefCell};
46 use std::marker::{PhantomData, Send};
52 use alloc::raw_vec::RawVec;
56 /// Index of the first unused byte.
58 /// Indicates whether objects with destructors are stored in this chunk.
63 fn new(size: usize, is_copy: bool) -> Chunk {
65 data: RawVec::with_capacity(size),
67 is_copy: Cell::new(is_copy),
71 fn capacity(&self) -> usize {
75 unsafe fn as_ptr(&self) -> *const u8 {
79 // Walk down a chunk, running the destructors for any objects stored
81 unsafe fn destroy(&self) {
83 let buf = self.as_ptr();
84 let fill = self.fill.get();
87 let tydesc_data = buf.offset(idx as isize) as *const usize;
88 let (tydesc, is_done) = un_bitpack_tydesc_ptr(*tydesc_data);
89 let (size, align) = ((*tydesc).size, (*tydesc).align);
91 let after_tydesc = idx + mem::size_of::<*const TyDesc>();
93 let start = round_up(after_tydesc, align);
96 ((*tydesc).drop_glue)(buf.offset(start as isize) as *const i8);
99 // Find where the next tydesc lives
100 idx = round_up(start + size, mem::align_of::<*const TyDesc>());
105 /// A slower reflection-based arena that can allocate objects of any type.
107 /// This arena uses `RawVec<u8>` as a backing store to allocate objects from.
108 /// For each allocated object, the arena stores a pointer to the type descriptor
109 /// followed by the object (potentially with alignment padding after each
110 /// element). When the arena is destroyed, it iterates through all of its
111 /// chunks, and uses the tydesc information to trace through the objects,
112 /// calling the destructors on them. One subtle point that needs to be
113 /// addressed is how to handle panics while running the user provided
114 /// initializer function. It is important to not run the destructor on
115 /// uninitialized objects, but how to detect them is somewhat subtle. Since
116 /// `alloc()` can be invoked recursively, it is not sufficient to simply exclude
117 /// the most recent object. To solve this without requiring extra space, we
118 /// use the low order bit of the tydesc pointer to encode whether the object
119 /// it describes has been fully initialized.
121 /// As an optimization, objects with destructors are stored in different chunks
122 /// than objects without destructors. This reduces overhead when initializing
123 /// plain-old-data (`Copy` types) and means we don't need to waste time running
124 /// their destructors.
125 pub struct Arena<'longer_than_self> {
126 // The heads are separated out from the list as a unbenchmarked
127 // microoptimization, to avoid needing to case on the list to access a head.
128 head: RefCell<Chunk>,
129 copy_head: RefCell<Chunk>,
130 chunks: RefCell<Vec<Chunk>>,
131 _marker: PhantomData<*mut &'longer_than_self ()>,
135 /// Allocates a new Arena with 32 bytes preallocated.
136 pub fn new() -> Arena<'a> {
137 Arena::new_with_size(32)
140 /// Allocates a new Arena with `initial_size` bytes preallocated.
141 pub fn new_with_size(initial_size: usize) -> Arena<'a> {
143 head: RefCell::new(Chunk::new(initial_size, false)),
144 copy_head: RefCell::new(Chunk::new(initial_size, true)),
145 chunks: RefCell::new(Vec::new()),
146 _marker: PhantomData,
151 impl<'longer_than_self> Drop for Arena<'longer_than_self> {
154 self.head.borrow().destroy();
155 for chunk in self.chunks.borrow().iter() {
156 if !chunk.is_copy.get() {
165 fn round_up(base: usize, align: usize) -> usize {
166 (base.checked_add(align - 1)).unwrap() & !(align - 1)
169 // We encode whether the object a tydesc describes has been
170 // initialized in the arena in the low bit of the tydesc pointer. This
171 // is necessary in order to properly do cleanup if a panic occurs
172 // during an initializer.
174 fn bitpack_tydesc_ptr(p: *const TyDesc, is_done: bool) -> usize {
175 p as usize | (is_done as usize)
178 fn un_bitpack_tydesc_ptr(p: usize) -> (*const TyDesc, bool) {
179 ((p & !1) as *const TyDesc, p & 1 == 1)
182 // HACK(eddyb) TyDesc replacement using a trait object vtable.
183 // This could be replaced in the future with a custom DST layout,
184 // or `&'static (drop_glue, size, align)` created by a `const fn`.
186 // * rvalue promotion (issue #1056)
187 // * mem::{size_of, align_of} must be const fns
189 drop_glue: fn(*const i8),
198 impl<T: ?Sized> AllTypes for T {}
200 unsafe fn get_tydesc<T>() -> *const TyDesc {
201 use std::raw::TraitObject;
203 let ptr = &*(heap::EMPTY as *const T);
205 // Can use any trait that is implemented for all types.
206 let obj = mem::transmute::<&AllTypes, TraitObject>(ptr);
207 obj.vtable as *const TyDesc
210 impl<'longer_than_self> Arena<'longer_than_self> {
211 // Grows a given chunk and returns `false`, or replaces it with a bigger
212 // chunk and returns `true`.
213 // This method is shared by both parts of the arena.
215 fn alloc_grow(&self, head: &mut Chunk, used_cap: usize, n_bytes: usize) -> bool {
216 if head.data.reserve_in_place(used_cap, n_bytes) {
217 // In-place reallocation succeeded.
220 // Allocate a new chunk.
221 let new_min_chunk_size = cmp::max(n_bytes, head.capacity());
222 let new_chunk = Chunk::new((new_min_chunk_size + 1).next_power_of_two(), false);
223 let old_chunk = mem::replace(head, new_chunk);
224 if old_chunk.fill.get() != 0 {
225 self.chunks.borrow_mut().push(old_chunk);
231 // Functions for the copyable part of the arena.
234 fn alloc_copy_inner(&self, n_bytes: usize, align: usize) -> *const u8 {
235 let mut copy_head = self.copy_head.borrow_mut();
236 let fill = copy_head.fill.get();
237 let mut start = round_up(fill, align);
238 let mut end = start + n_bytes;
240 if end > copy_head.capacity() {
241 if self.alloc_grow(&mut *copy_head, fill, end - fill) {
242 // Continuing with a newly allocated chunk
245 copy_head.is_copy.set(true);
249 copy_head.fill.set(end);
251 unsafe { copy_head.as_ptr().offset(start as isize) }
255 fn alloc_copy<T, F>(&self, op: F) -> &mut T
256 where F: FnOnce() -> T
259 let ptr = self.alloc_copy_inner(mem::size_of::<T>(), mem::align_of::<T>());
260 let ptr = ptr as *mut T;
261 ptr::write(&mut (*ptr), op());
266 // Functions for the non-copyable part of the arena.
269 fn alloc_noncopy_inner(&self, n_bytes: usize, align: usize) -> (*const u8, *const u8) {
270 let mut head = self.head.borrow_mut();
271 let fill = head.fill.get();
273 let mut tydesc_start = fill;
274 let after_tydesc = fill + mem::size_of::<*const TyDesc>();
275 let mut start = round_up(after_tydesc, align);
276 let mut end = round_up(start + n_bytes, mem::align_of::<*const TyDesc>());
278 if end > head.capacity() {
279 if self.alloc_grow(&mut *head, tydesc_start, end - tydesc_start) {
280 // Continuing with a newly allocated chunk
282 start = round_up(mem::size_of::<*const TyDesc>(), align);
283 end = round_up(start + n_bytes, mem::align_of::<*const TyDesc>());
290 let buf = head.as_ptr();
291 (buf.offset(tydesc_start as isize),
292 buf.offset(start as isize))
297 fn alloc_noncopy<T, F>(&self, op: F) -> &mut T
298 where F: FnOnce() -> T
301 let tydesc = get_tydesc::<T>();
302 let (ty_ptr, ptr) = self.alloc_noncopy_inner(mem::size_of::<T>(), mem::align_of::<T>());
303 let ty_ptr = ty_ptr as *mut usize;
304 let ptr = ptr as *mut T;
305 // Write in our tydesc along with a bit indicating that it
306 // has *not* been initialized yet.
307 *ty_ptr = bitpack_tydesc_ptr(tydesc, false);
308 // Actually initialize it
309 ptr::write(&mut (*ptr), op());
310 // Now that we are done, update the tydesc to indicate that
311 // the object is there.
312 *ty_ptr = bitpack_tydesc_ptr(tydesc, true);
318 /// Allocates a new item in the arena, using `op` to initialize the value,
319 /// and returns a reference to it.
321 pub fn alloc<T: 'longer_than_self, F>(&self, op: F) -> &mut T
322 where F: FnOnce() -> T
325 if intrinsics::needs_drop::<T>() {
326 self.alloc_noncopy(op)
333 /// Allocates a slice of bytes of requested length. The bytes are not guaranteed to be zero
334 /// if the arena has previously been cleared.
338 /// Panics if the requested length is too large and causes overflow.
339 pub fn alloc_bytes(&self, len: usize) -> &mut [u8] {
341 // Check for overflow.
342 self.copy_head.borrow().fill.get().checked_add(len).expect("length overflow");
343 let ptr = self.alloc_copy_inner(len, 1);
344 intrinsics::assume(!ptr.is_null());
345 slice::from_raw_parts_mut(ptr as *mut _, len)
349 /// Clears the arena. Deallocates all but the longest chunk which may be reused.
350 pub fn clear(&mut self) {
352 self.head.borrow().destroy();
353 self.head.borrow().fill.set(0);
354 self.copy_head.borrow().fill.set(0);
355 for chunk in self.chunks.borrow().iter() {
356 if !chunk.is_copy.get() {
360 self.chunks.borrow_mut().clear();
365 /// A faster arena that can hold objects of only one type.
366 pub struct TypedArena<T> {
367 /// A pointer to the next object to be allocated.
370 /// A pointer to the end of the allocated area. When this pointer is
371 /// reached, a new chunk is allocated.
374 /// A vector arena segments.
375 chunks: RefCell<Vec<TypedArenaChunk<T>>>,
377 /// Marker indicating that dropping the arena causes its owned
378 /// instances of `T` to be dropped.
379 _own: PhantomData<T>,
382 struct TypedArenaChunk<T> {
383 /// Pointer to the next arena segment.
387 impl<T> TypedArenaChunk<T> {
389 unsafe fn new(capacity: usize) -> TypedArenaChunk<T> {
390 TypedArenaChunk { storage: RawVec::with_capacity(capacity) }
393 /// Destroys this arena chunk.
395 unsafe fn destroy(&mut self, len: usize) {
396 // The branch on needs_drop() is an -O1 performance optimization.
397 // Without the branch, dropping TypedArena<u8> takes linear time.
398 if intrinsics::needs_drop::<T>() {
399 let mut start = self.start();
400 // Destroy all allocated objects.
402 ptr::drop_in_place(start);
403 start = start.offset(1);
408 // Returns a pointer to the first allocated object.
410 fn start(&self) -> *mut T {
414 // Returns a pointer to the end of the allocated space.
416 fn end(&self) -> *mut T {
418 if mem::size_of::<T>() == 0 {
419 // A pointer as large as possible for zero-sized elements.
422 self.start().offset(self.storage.cap() as isize)
428 const PAGE: usize = 4096;
430 impl<T> TypedArena<T> {
431 /// Creates a new `TypedArena` with preallocated space for many objects.
433 pub fn new() -> TypedArena<T> {
434 // Reserve at least one page.
435 let elem_size = cmp::max(1, mem::size_of::<T>());
436 TypedArena::with_capacity(PAGE / elem_size)
439 /// Creates a new `TypedArena` with preallocated space for the given number of
442 pub fn with_capacity(capacity: usize) -> TypedArena<T> {
444 let chunk = TypedArenaChunk::<T>::new(cmp::max(1, capacity));
446 ptr: Cell::new(chunk.start()),
447 end: Cell::new(chunk.end()),
448 chunks: RefCell::new(vec![chunk]),
454 /// Allocates an object in the `TypedArena`, returning a reference to it.
456 pub fn alloc(&self, object: T) -> &mut T {
457 if self.ptr == self.end {
462 if mem::size_of::<T>() == 0 {
463 self.ptr.set(intrinsics::arith_offset(self.ptr.get() as *mut u8, 1) as *mut T);
464 let ptr = heap::EMPTY as *mut T;
465 // Don't drop the object. This `write` is equivalent to `forget`.
466 ptr::write(ptr, object);
469 let ptr = self.ptr.get();
470 // Advance the pointer.
471 self.ptr.set(self.ptr.get().offset(1));
472 // Write into uninitialized memory.
473 ptr::write(ptr, object);
484 let mut chunks = self.chunks.borrow_mut();
485 let prev_capacity = chunks.last().unwrap().storage.cap();
486 let new_capacity = prev_capacity.checked_mul(2).unwrap();
487 if chunks.last_mut().unwrap().storage.double_in_place() {
488 self.end.set(chunks.last().unwrap().end());
490 let chunk = TypedArenaChunk::<T>::new(new_capacity);
491 self.ptr.set(chunk.start());
492 self.end.set(chunk.end());
497 /// Clears the arena. Deallocates all but the longest chunk which may be reused.
498 pub fn clear(&mut self) {
500 // Clear the last chunk, which is partially filled.
501 let mut chunks_borrow = self.chunks.borrow_mut();
502 let last_idx = chunks_borrow.len() - 1;
503 self.clear_last_chunk(&mut chunks_borrow[last_idx]);
504 // If `T` is ZST, code below has no effect.
505 for mut chunk in chunks_borrow.drain(..last_idx) {
506 let cap = chunk.storage.cap();
512 // Drops the contents of the last chunk. The last chunk is partially empty, unlike all other
514 fn clear_last_chunk(&self, last_chunk: &mut TypedArenaChunk<T>) {
515 // Determine how much was filled.
516 let start = last_chunk.start() as usize;
517 // We obtain the value of the pointer to the first uninitialized element.
518 let end = self.ptr.get() as usize;
519 // We then calculate the number of elements to be dropped in the last chunk,
520 // which is the filled area's length.
521 let diff = if mem::size_of::<T>() == 0 {
522 // `T` is ZST. It can't have a drop flag, so the value here doesn't matter. We get
523 // the number of zero-sized values in the last and only chunk, just out of caution.
524 // Recall that `end` was incremented for each allocated value.
527 (end - start) / mem::size_of::<T>()
529 // Pass that to the `destroy` method.
531 last_chunk.destroy(diff);
534 self.ptr.set(last_chunk.start());
538 impl<T> Drop for TypedArena<T> {
539 #[unsafe_destructor_blind_to_params]
542 // Determine how much was filled.
543 let mut chunks_borrow = self.chunks.borrow_mut();
544 let mut last_chunk = chunks_borrow.pop().unwrap();
545 // Drop the contents of the last chunk.
546 self.clear_last_chunk(&mut last_chunk);
547 // The last chunk will be dropped. Destroy all other chunks.
548 for chunk in chunks_borrow.iter_mut() {
549 let cap = chunk.storage.cap();
552 // RawVec handles deallocation of `last_chunk` and `self.chunks`.
557 unsafe impl<T: Send> Send for TypedArena<T> {}
562 use self::test::Bencher;
563 use super::{Arena, TypedArena};
574 fn test_arena_alloc_nested() {
586 struct Wrap<'a>(TypedArena<EI<'a>>);
589 fn alloc_inner<F: Fn() -> Inner>(&self, f: F) -> &Inner {
590 let r: &EI = self.0.alloc(EI::I(f()));
591 if let &EI::I(ref i) = r {
597 fn alloc_outer<F: Fn() -> Outer<'a>>(&self, f: F) -> &Outer {
598 let r: &EI = self.0.alloc(EI::O(f()));
599 if let &EI::O(ref o) = r {
607 let arena = Wrap(TypedArena::new());
609 let result = arena.alloc_outer(|| {
610 Outer { inner: arena.alloc_inner(|| Inner { value: 10 }) }
613 assert_eq!(result.inner.value, 10);
618 let arena = TypedArena::new();
620 arena.alloc(Point { x: 1, y: 2, z: 3 });
625 pub fn bench_copy(b: &mut Bencher) {
626 let arena = TypedArena::new();
627 b.iter(|| arena.alloc(Point { x: 1, y: 2, z: 3 }))
631 pub fn bench_copy_nonarena(b: &mut Bencher) {
633 let _: Box<_> = Box::new(Point {
642 pub fn bench_copy_old_arena(b: &mut Bencher) {
643 let arena = Arena::new();
644 b.iter(|| arena.alloc(|| Point { x: 1, y: 2, z: 3 }))
654 pub fn test_noncopy() {
655 let arena = TypedArena::new();
657 arena.alloc(Noncopy {
658 string: "hello world".to_string(),
659 array: vec![1, 2, 3, 4, 5],
665 pub fn test_typed_arena_zero_sized() {
666 let arena = TypedArena::new();
673 pub fn test_arena_zero_sized() {
674 let arena = Arena::new();
679 arena.alloc(|| Point {
688 pub fn test_typed_arena_clear() {
689 let mut arena = TypedArena::new();
703 pub fn test_arena_clear() {
704 let mut arena = Arena::new();
708 arena.alloc(|| Point {
713 arena.alloc(|| Noncopy {
714 string: "hello world".to_string(),
722 pub fn test_arena_alloc_bytes() {
723 let arena = Arena::new();
725 arena.alloc(|| Point {
730 for byte in arena.alloc_bytes(i % 42).iter_mut() {
737 fn test_arena_destructors() {
738 let arena = Arena::new();
740 // Arena allocate something with drop glue to make sure it
742 arena.alloc(|| Rc::new(i));
743 // Allocate something with funny size and alignment, to keep
744 // things interesting.
745 arena.alloc(|| [0u8, 1u8, 2u8]);
751 fn test_arena_destructors_fail() {
752 let arena = Arena::new();
753 // Put some stuff in the arena.
755 // Arena allocate something with drop glue to make sure it
757 arena.alloc(|| { Rc::new(i) });
758 // Allocate something with funny size and alignment, to keep
759 // things interesting.
760 arena.alloc(|| { [0u8, 1, 2] });
762 // Now, panic while allocating
763 arena.alloc::<Rc<i32>, _>(|| {
769 pub fn bench_noncopy(b: &mut Bencher) {
770 let arena = TypedArena::new();
772 arena.alloc(Noncopy {
773 string: "hello world".to_string(),
774 array: vec!( 1, 2, 3, 4, 5 ),
780 pub fn bench_noncopy_nonarena(b: &mut Bencher) {
782 let _: Box<_> = Box::new(Noncopy {
783 string: "hello world".to_string(),
784 array: vec!( 1, 2, 3, 4, 5 ),
790 pub fn bench_noncopy_old_arena(b: &mut Bencher) {
791 let arena = Arena::new();
793 arena.alloc(|| Noncopy {
794 string: "hello world".to_string(),
795 array: vec!( 1, 2, 3, 4, 5 ),