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();
366 fn test_arena_destructors() {
367 let arena = Arena::new();
369 // Arena allocate something with drop glue to make sure it
371 arena.alloc(|| Rc::new(i));
372 // Allocate something with funny size and alignment, to keep
373 // things interesting.
374 arena.alloc(|| [0u8, 1u8, 2u8]);
380 fn test_arena_destructors_fail() {
381 let arena = Arena::new();
382 // Put some stuff in the arena.
384 // Arena allocate something with drop glue to make sure it
386 arena.alloc(|| Rc::new(i));
387 // Allocate something with funny size and alignment, to keep
388 // things interesting.
389 arena.alloc(|| [0u8, 1, 2]);
391 // Now, panic while allocating
392 arena.alloc::<Rc<i32>, _>(|| {
397 /// A faster arena that can hold objects of only one type.
398 pub struct TypedArena<T> {
399 /// A pointer to the next object to be allocated.
402 /// A pointer to the end of the allocated area. When this pointer is
403 /// reached, a new chunk is allocated.
406 /// A vector arena segments.
407 chunks: RefCell<Vec<TypedArenaChunk<T>>>,
409 /// Marker indicating that dropping the arena causes its owned
410 /// instances of `T` to be dropped.
411 _own: PhantomData<T>,
414 struct TypedArenaChunk<T> {
415 /// Pointer to the next arena segment.
419 impl<T> TypedArenaChunk<T> {
421 unsafe fn new(capacity: usize) -> TypedArenaChunk<T> {
422 TypedArenaChunk { storage: RawVec::with_capacity(capacity) }
425 /// Destroys this arena chunk.
427 unsafe fn destroy(&mut self, len: usize) {
428 // The branch on needs_drop() is an -O1 performance optimization.
429 // Without the branch, dropping TypedArena<u8> takes linear time.
430 if intrinsics::needs_drop::<T>() {
431 let mut start = self.start();
432 // Destroy all allocated objects.
434 ptr::drop_in_place(start);
435 start = start.offset(1);
440 // Returns a pointer to the first allocated object.
442 fn start(&self) -> *mut T {
446 // Returns a pointer to the end of the allocated space.
448 fn end(&self) -> *mut T {
450 if mem::size_of::<T>() == 0 {
451 // A pointer as large as possible for zero-sized elements.
454 self.start().offset(self.storage.cap() as isize)
460 const PAGE: usize = 4096;
462 impl<T> TypedArena<T> {
463 /// Creates a new `TypedArena` with preallocated space for many objects.
465 pub fn new() -> TypedArena<T> {
466 // Reserve at least one page.
467 let elem_size = cmp::max(1, mem::size_of::<T>());
468 TypedArena::with_capacity(PAGE / elem_size)
471 /// Creates a new `TypedArena` with preallocated space for the given number of
474 pub fn with_capacity(capacity: usize) -> TypedArena<T> {
476 let chunk = TypedArenaChunk::<T>::new(cmp::max(1, capacity));
478 ptr: Cell::new(chunk.start()),
479 end: Cell::new(chunk.end()),
480 chunks: RefCell::new(vec![chunk]),
486 /// Allocates an object in the `TypedArena`, returning a reference to it.
488 pub fn alloc(&self, object: T) -> &mut T {
489 if self.ptr == self.end {
494 if mem::size_of::<T>() == 0 {
495 self.ptr.set(intrinsics::arith_offset(self.ptr.get() as *mut u8, 1) as *mut T);
496 let ptr = heap::EMPTY as *mut T;
497 // Don't drop the object. This `write` is equivalent to `forget`.
498 ptr::write(ptr, object);
501 let ptr = self.ptr.get();
502 // Advance the pointer.
503 self.ptr.set(self.ptr.get().offset(1));
504 // Write into uninitialized memory.
505 ptr::write(ptr, object);
516 let mut chunks = self.chunks.borrow_mut();
517 let prev_capacity = chunks.last().unwrap().storage.cap();
518 let new_capacity = prev_capacity.checked_mul(2).unwrap();
519 if chunks.last_mut().unwrap().storage.double_in_place() {
520 self.end.set(chunks.last().unwrap().end());
522 let chunk = TypedArenaChunk::<T>::new(new_capacity);
523 self.ptr.set(chunk.start());
524 self.end.set(chunk.end());
529 /// Clears the arena. Deallocates all but the longest chunk which may be reused.
530 pub fn clear(&mut self) {
532 // Clear the last chunk, which is partially filled.
533 let mut chunks_borrow = self.chunks.borrow_mut();
534 let last_idx = chunks_borrow.len() - 1;
535 self.clear_last_chunk(&mut chunks_borrow[last_idx]);
536 // If `T` is ZST, code below has no effect.
537 for mut chunk in chunks_borrow.drain(..last_idx) {
538 let cap = chunk.storage.cap();
544 // Drops the contents of the last chunk. The last chunk is partially empty, unlike all other
546 fn clear_last_chunk(&self, last_chunk: &mut TypedArenaChunk<T>) {
547 // Determine how much was filled.
548 let start = last_chunk.start() as usize;
549 // We obtain the value of the pointer to the first uninitialized element.
550 let end = self.ptr.get() as usize;
551 // We then calculate the number of elements to be dropped in the last chunk,
552 // which is the filled area's length.
553 let diff = if mem::size_of::<T>() == 0 {
554 // `T` is ZST. It can't have a drop flag, so the value here doesn't matter. We get
555 // the number of zero-sized values in the last and only chunk, just out of caution.
556 // Recall that `end` was incremented for each allocated value.
559 (end - start) / mem::size_of::<T>()
561 // Pass that to the `destroy` method.
563 last_chunk.destroy(diff);
566 self.ptr.set(last_chunk.start());
570 impl<T> Drop for TypedArena<T> {
571 #[unsafe_destructor_blind_to_params]
574 // Determine how much was filled.
575 let mut chunks_borrow = self.chunks.borrow_mut();
576 let mut last_chunk = chunks_borrow.pop().unwrap();
577 // Drop the contents of the last chunk.
578 self.clear_last_chunk(&mut last_chunk);
579 // The last chunk will be dropped. Destroy all other chunks.
580 for chunk in chunks_borrow.iter_mut() {
581 let cap = chunk.storage.cap();
584 // RawVec handles deallocation of `last_chunk` and `self.chunks`.
589 unsafe impl<T: Send> Send for TypedArena<T> {}
594 use self::test::Bencher;
595 use super::{Arena, TypedArena};
606 fn test_arena_alloc_nested() {
618 struct Wrap<'a>(TypedArena<EI<'a>>);
621 fn alloc_inner<F: Fn() -> Inner>(&self, f: F) -> &Inner {
622 let r: &EI = self.0.alloc(EI::I(f()));
623 if let &EI::I(ref i) = r {
629 fn alloc_outer<F: Fn() -> Outer<'a>>(&self, f: F) -> &Outer {
630 let r: &EI = self.0.alloc(EI::O(f()));
631 if let &EI::O(ref o) = r {
639 let arena = Wrap(TypedArena::new());
641 let result = arena.alloc_outer(|| {
642 Outer { inner: arena.alloc_inner(|| Inner { value: 10 }) }
645 assert_eq!(result.inner.value, 10);
650 let arena = TypedArena::new();
652 arena.alloc(Point { x: 1, y: 2, z: 3 });
657 pub fn bench_copy(b: &mut Bencher) {
658 let arena = TypedArena::new();
659 b.iter(|| arena.alloc(Point { x: 1, y: 2, z: 3 }))
663 pub fn bench_copy_nonarena(b: &mut Bencher) {
665 let _: Box<_> = Box::new(Point {
674 pub fn bench_copy_old_arena(b: &mut Bencher) {
675 let arena = Arena::new();
676 b.iter(|| arena.alloc(|| Point { x: 1, y: 2, z: 3 }))
686 pub fn test_noncopy() {
687 let arena = TypedArena::new();
689 arena.alloc(Noncopy {
690 string: "hello world".to_string(),
691 array: vec![1, 2, 3, 4, 5],
697 pub fn bench_noncopy(b: &mut Bencher) {
698 let arena = TypedArena::new();
700 arena.alloc(Noncopy {
701 string: "hello world".to_string(),
702 array: vec![1, 2, 3, 4, 5],
708 pub fn bench_noncopy_nonarena(b: &mut Bencher) {
710 let _: Box<_> = Box::new(Noncopy {
711 string: "hello world".to_string(),
712 array: vec![1, 2, 3, 4, 5],
718 pub fn bench_noncopy_old_arena(b: &mut Bencher) {
719 let arena = Arena::new();
723 string: "hello world".to_string(),
724 array: vec![1, 2, 3, 4, 5],
731 pub fn test_typed_arena_zero_sized() {
732 let arena = TypedArena::new();
739 pub fn test_arena_zero_sized() {
740 let arena = Arena::new();
745 arena.alloc(|| Point {
754 pub fn test_typed_arena_clear() {
755 let mut arena = TypedArena::new();
769 pub fn test_arena_clear() {
770 let mut arena = Arena::new();
774 arena.alloc(|| Point {
779 arena.alloc(|| Noncopy {
780 string: "hello world".to_string(),
788 pub fn test_arena_alloc_bytes() {
789 let arena = Arena::new();
791 arena.alloc(|| Point {
796 for byte in arena.alloc_bytes(i % 42).iter_mut() {