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"]
24 #![crate_type = "rlib"]
25 #![crate_type = "dylib"]
26 #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
27 html_favicon_url = "http://www.rust-lang.org/favicon.ico",
28 html_root_url = "http://doc.rust-lang.org/nightly/")]
30 #![feature(unsafe_destructor)]
31 #![allow(missing_docs)]
35 use std::cell::{Cell, RefCell};
37 use std::intrinsics::{TyDesc, get_tydesc};
40 use std::num::{Int, UnsignedInt};
43 use std::rt::heap::{allocate, deallocate};
45 // The way arena uses arrays is really deeply awful. The arrays are
46 // allocated, and have capacities reserved, but the fill for the array
47 // will always stay at 0.
48 #[deriving(Clone, PartialEq)]
50 data: Rc<RefCell<Vec<u8>>>,
56 fn capacity(&self) -> uint {
57 self.data.borrow().capacity()
60 unsafe fn as_ptr(&self) -> *const u8 {
61 self.data.borrow().as_ptr()
65 /// A slower reflection-based arena that can allocate objects of any type.
67 /// This arena uses `Vec<u8>` as a backing store to allocate objects from. For
68 /// each allocated object, the arena stores a pointer to the type descriptor
69 /// followed by the object (potentially with alignment padding after each
70 /// element). When the arena is destroyed, it iterates through all of its
71 /// chunks, and uses the tydesc information to trace through the objects,
72 /// calling the destructors on them. One subtle point that needs to be
73 /// addressed is how to handle panics while running the user provided
74 /// initializer function. It is important to not run the destructor on
75 /// uninitialized objects, but how to detect them is somewhat subtle. Since
76 /// `alloc()` can be invoked recursively, it is not sufficient to simply exclude
77 /// the most recent object. To solve this without requiring extra space, we
78 /// use the low order bit of the tydesc pointer to encode whether the object
79 /// it describes has been fully initialized.
81 /// As an optimization, objects with destructors are stored in different chunks
82 /// than objects without destructors. This reduces overhead when initializing
83 /// plain-old-data (`Copy` types) and means we don't need to waste time running
84 /// their destructors.
86 // The head is separated out from the list as a unbenchmarked
87 // microoptimization, to avoid needing to case on the list to access the
90 copy_head: RefCell<Chunk>,
91 chunks: RefCell<Vec<Chunk>>,
95 /// Allocates a new Arena with 32 bytes preallocated.
96 pub fn new() -> Arena {
97 Arena::new_with_size(32u)
100 /// Allocates a new Arena with `initial_size` bytes preallocated.
101 pub fn new_with_size(initial_size: uint) -> Arena {
103 head: RefCell::new(chunk(initial_size, false)),
104 copy_head: RefCell::new(chunk(initial_size, true)),
105 chunks: RefCell::new(Vec::new()),
110 fn chunk(size: uint, is_copy: bool) -> Chunk {
112 data: Rc::new(RefCell::new(Vec::with_capacity(size))),
114 is_copy: Cell::new(is_copy),
119 impl Drop for Arena {
122 destroy_chunk(&*self.head.borrow());
123 for chunk in self.chunks.borrow().iter() {
124 if !chunk.is_copy.get() {
125 destroy_chunk(chunk);
133 fn round_up(base: uint, align: uint) -> uint {
134 (base.checked_add(align - 1)).unwrap() & !(align - 1)
137 // Walk down a chunk, running the destructors for any objects stored
139 unsafe fn destroy_chunk(chunk: &Chunk) {
141 let buf = chunk.as_ptr();
142 let fill = chunk.fill.get();
145 let tydesc_data: *const uint = mem::transmute(buf.offset(idx as int));
146 let (tydesc, is_done) = un_bitpack_tydesc_ptr(*tydesc_data);
147 let (size, align) = ((*tydesc).size, (*tydesc).align);
149 let after_tydesc = idx + mem::size_of::<*const TyDesc>();
151 let start = round_up(after_tydesc, align);
153 //debug!("freeing object: idx = {}, size = {}, align = {}, done = {}",
154 // start, size, align, is_done);
156 ((*tydesc).drop_glue)(buf.offset(start as int) as *const i8);
159 // Find where the next tydesc lives
160 idx = round_up(start + size, mem::align_of::<*const TyDesc>());
164 // We encode whether the object a tydesc describes has been
165 // initialized in the arena in the low bit of the tydesc pointer. This
166 // is necessary in order to properly do cleanup if a panic occurs
167 // during an initializer.
169 fn bitpack_tydesc_ptr(p: *const TyDesc, is_done: bool) -> uint {
170 p as uint | (is_done as uint)
173 fn un_bitpack_tydesc_ptr(p: uint) -> (*const TyDesc, bool) {
174 ((p & !1) as *const TyDesc, p & 1 == 1)
178 fn chunk_size(&self) -> uint {
179 self.copy_head.borrow().capacity()
182 // Functions for the POD part of the arena
183 fn alloc_copy_grow(&self, n_bytes: uint, align: uint) -> *const u8 {
184 // Allocate a new chunk.
185 let new_min_chunk_size = cmp::max(n_bytes, self.chunk_size());
186 self.chunks.borrow_mut().push(self.copy_head.borrow().clone());
188 *self.copy_head.borrow_mut() =
189 chunk((new_min_chunk_size + 1u).next_power_of_two(), true);
191 return self.alloc_copy_inner(n_bytes, align);
195 fn alloc_copy_inner(&self, n_bytes: uint, align: uint) -> *const u8 {
196 let start = round_up(self.copy_head.borrow().fill.get(), align);
198 let end = start + n_bytes;
199 if end > self.chunk_size() {
200 return self.alloc_copy_grow(n_bytes, align);
203 let copy_head = self.copy_head.borrow();
204 copy_head.fill.set(end);
207 copy_head.as_ptr().offset(start as int)
212 fn alloc_copy<T>(&self, op: || -> T) -> &mut T {
214 let ptr = self.alloc_copy_inner(mem::size_of::<T>(),
215 mem::min_align_of::<T>());
216 let ptr = ptr as *mut T;
217 ptr::write(&mut (*ptr), op());
222 // Functions for the non-POD part of the arena
223 fn alloc_noncopy_grow(&self, n_bytes: uint,
224 align: uint) -> (*const u8, *const u8) {
225 // Allocate a new chunk.
226 let new_min_chunk_size = cmp::max(n_bytes, self.chunk_size());
227 self.chunks.borrow_mut().push(self.head.borrow().clone());
229 *self.head.borrow_mut() =
230 chunk((new_min_chunk_size + 1u).next_power_of_two(), false);
232 return self.alloc_noncopy_inner(n_bytes, align);
236 fn alloc_noncopy_inner(&self, n_bytes: uint,
237 align: uint) -> (*const u8, *const u8) {
238 // Be careful to not maintain any `head` borrows active, because
239 // `alloc_noncopy_grow` borrows it mutably.
240 let (start, end, tydesc_start, head_capacity) = {
241 let head = self.head.borrow();
242 let fill = head.fill.get();
244 let tydesc_start = fill;
245 let after_tydesc = fill + mem::size_of::<*const TyDesc>();
246 let start = round_up(after_tydesc, align);
247 let end = start + n_bytes;
249 (start, end, tydesc_start, head.capacity())
252 if end > head_capacity {
253 return self.alloc_noncopy_grow(n_bytes, align);
256 let head = self.head.borrow();
257 head.fill.set(round_up(end, mem::align_of::<*const TyDesc>()));
260 let buf = head.as_ptr();
261 return (buf.offset(tydesc_start as int), buf.offset(start as int));
266 fn alloc_noncopy<T>(&self, op: || -> T) -> &mut T {
268 let tydesc = get_tydesc::<T>();
270 self.alloc_noncopy_inner(mem::size_of::<T>(),
271 mem::min_align_of::<T>());
272 let ty_ptr = ty_ptr as *mut uint;
273 let ptr = ptr as *mut T;
274 // Write in our tydesc along with a bit indicating that it
275 // has *not* been initialized yet.
276 *ty_ptr = mem::transmute(tydesc);
277 // Actually initialize it
278 ptr::write(&mut(*ptr), op());
279 // Now that we are done, update the tydesc to indicate that
280 // the object is there.
281 *ty_ptr = bitpack_tydesc_ptr(tydesc, true);
287 /// Allocates a new item in the arena, using `op` to initialize the value,
288 /// and returns a reference to it.
290 pub fn alloc<T>(&self, op: || -> T) -> &mut T {
292 if intrinsics::needs_drop::<T>() {
293 self.alloc_noncopy(op)
302 fn test_arena_destructors() {
303 let arena = Arena::new();
304 for i in range(0u, 10) {
305 // Arena allocate something with drop glue to make sure it
307 arena.alloc(|| Rc::new(i));
308 // Allocate something with funny size and alignment, to keep
309 // things interesting.
310 arena.alloc(|| [0u8, 1u8, 2u8]);
315 fn test_arena_alloc_nested() {
316 struct Inner { value: uint }
317 struct Outer<'a> { inner: &'a Inner }
319 let arena = Arena::new();
321 let result = arena.alloc(|| Outer {
322 inner: arena.alloc(|| Inner { value: 10 })
325 assert_eq!(result.inner.value, 10);
330 fn test_arena_destructors_fail() {
331 let arena = Arena::new();
332 // Put some stuff in the arena.
333 for i in range(0u, 10) {
334 // Arena allocate something with drop glue to make sure it
336 arena.alloc(|| { Rc::new(i) });
337 // Allocate something with funny size and alignment, to keep
338 // things interesting.
339 arena.alloc(|| { [0u8, 1u8, 2u8] });
341 // Now, panic while allocating
342 arena.alloc::<Rc<int>>(|| {
347 /// A faster arena that can hold objects of only one type.
349 /// Safety note: Modifying objects in the arena that have already had their
350 /// `drop` destructors run can cause leaks, because the destructor will not
351 /// run again for these objects.
352 pub struct TypedArena<T> {
353 /// A pointer to the next object to be allocated.
356 /// A pointer to the end of the allocated area. When this pointer is
357 /// reached, a new chunk is allocated.
360 /// A pointer to the first arena segment.
361 first: RefCell<*mut TypedArenaChunk<T>>,
364 struct TypedArenaChunk<T> {
365 /// Pointer to the next arena segment.
366 next: *mut TypedArenaChunk<T>,
368 /// The number of elements that this chunk can hold.
371 // Objects follow here, suitably aligned.
374 fn calculate_size<T>(capacity: uint) -> uint {
375 let mut size = mem::size_of::<TypedArenaChunk<T>>();
376 size = round_up(size, mem::min_align_of::<T>());
377 let elem_size = mem::size_of::<T>();
378 let elems_size = elem_size.checked_mul(capacity).unwrap();
379 size = size.checked_add(elems_size).unwrap();
383 impl<T> TypedArenaChunk<T> {
385 unsafe fn new(next: *mut TypedArenaChunk<T>, capacity: uint)
386 -> *mut TypedArenaChunk<T> {
387 let size = calculate_size::<T>(capacity);
388 let chunk = allocate(size, mem::min_align_of::<TypedArenaChunk<T>>())
389 as *mut TypedArenaChunk<T>;
390 if chunk.is_null() { alloc::oom() }
391 (*chunk).next = next;
392 (*chunk).capacity = capacity;
396 /// Destroys this arena chunk. If the type descriptor is supplied, the
397 /// drop glue is called; otherwise, drop glue is not called.
399 unsafe fn destroy(&mut self, len: uint) {
400 // Destroy all the allocated objects.
401 if intrinsics::needs_drop::<T>() {
402 let mut start = self.start();
403 for _ in range(0, len) {
404 ptr::read(start as *const T); // run the destructor on the pointer
405 start = start.offset(mem::size_of::<T>() as int)
409 // Destroy the next chunk.
410 let next = self.next;
411 let size = calculate_size::<T>(self.capacity);
412 deallocate(self as *mut TypedArenaChunk<T> as *mut u8, size,
413 mem::min_align_of::<TypedArenaChunk<T>>());
414 if next.is_not_null() {
415 let capacity = (*next).capacity;
416 (*next).destroy(capacity);
420 // Returns a pointer to the first allocated object.
422 fn start(&self) -> *const u8 {
423 let this: *const TypedArenaChunk<T> = self;
425 mem::transmute(round_up(this.offset(1) as uint,
426 mem::min_align_of::<T>()))
430 // Returns a pointer to the end of the allocated space.
432 fn end(&self) -> *const u8 {
434 let size = mem::size_of::<T>().checked_mul(self.capacity).unwrap();
435 self.start().offset(size as int)
440 impl<T> TypedArena<T> {
441 /// Creates a new `TypedArena` with preallocated space for eight objects.
443 pub fn new() -> TypedArena<T> {
444 TypedArena::with_capacity(8)
447 /// Creates a new `TypedArena` with preallocated space for the given number of
450 pub fn with_capacity(capacity: uint) -> TypedArena<T> {
452 let chunk = TypedArenaChunk::<T>::new(ptr::null_mut(), capacity);
454 ptr: Cell::new((*chunk).start() as *const T),
455 end: Cell::new((*chunk).end() as *const T),
456 first: RefCell::new(chunk),
461 /// Allocates an object in the `TypedArena`, returning a reference to it.
463 pub fn alloc(&self, object: T) -> &mut T {
464 if self.ptr == self.end {
468 let ptr: &mut T = unsafe {
469 let ptr: &mut T = mem::transmute(self.ptr);
470 ptr::write(ptr, object);
471 self.ptr.set(self.ptr.get().offset(1));
482 let chunk = *self.first.borrow_mut();
483 let new_capacity = (*chunk).capacity.checked_mul(2).unwrap();
484 let chunk = TypedArenaChunk::<T>::new(chunk, new_capacity);
485 self.ptr.set((*chunk).start() as *const T);
486 self.end.set((*chunk).end() as *const T);
487 *self.first.borrow_mut() = chunk
493 impl<T> Drop for TypedArena<T> {
496 // Determine how much was filled.
497 let start = self.first.borrow().as_ref().unwrap().start() as uint;
498 let end = self.ptr.get() as uint;
499 let diff = (end - start) / mem::size_of::<T>();
501 // Pass that to the `destroy` method.
502 (**self.first.borrow_mut()).destroy(diff)
510 use self::test::Bencher;
511 use super::{Arena, TypedArena};
522 let arena = TypedArena::new();
523 for _ in range(0u, 100000) {
533 pub fn bench_copy(b: &mut Bencher) {
534 let arena = TypedArena::new();
545 pub fn bench_copy_nonarena(b: &mut Bencher) {
556 pub fn bench_copy_old_arena(b: &mut Bencher) {
557 let arena = Arena::new();
576 pub fn test_noncopy() {
577 let arena = TypedArena::new();
578 for _ in range(0u, 100000) {
579 arena.alloc(Noncopy {
580 string: "hello world".to_string(),
581 array: vec!( 1, 2, 3, 4, 5 ),
587 pub fn bench_noncopy(b: &mut Bencher) {
588 let arena = TypedArena::new();
590 arena.alloc(Noncopy {
591 string: "hello world".to_string(),
592 array: vec!( 1, 2, 3, 4, 5 ),
598 pub fn bench_noncopy_nonarena(b: &mut Bencher) {
601 string: "hello world".to_string(),
602 array: vec!( 1, 2, 3, 4, 5 ),
608 pub fn bench_noncopy_old_arena(b: &mut Bencher) {
609 let arena = Arena::new();
611 arena.alloc(|| Noncopy {
612 string: "hello world".to_string(),
613 array: vec!( 1, 2, 3, 4, 5 ),