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 #![crate_id = "arena#0.11-pre"]
19 #![crate_type = "rlib"]
20 #![crate_type = "dylib"]
21 #![license = "MIT/ASL2"]
22 #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
23 html_favicon_url = "http://www.rust-lang.org/favicon.ico",
24 html_root_url = "http://static.rust-lang.org/doc/master")]
25 #![allow(missing_doc)]
27 extern crate collections;
29 use std::cast::{transmute, transmute_mut, transmute_mut_lifetime};
31 use std::cell::{Cell, RefCell};
37 use std::rt::global_heap;
38 use std::intrinsics::{TyDesc, get_tydesc};
41 // The way arena uses arrays is really deeply awful. The arrays are
42 // allocated, and have capacities reserved, but the fill for the array
43 // will always stay at 0.
44 #[deriving(Clone, Eq)]
46 data: Rc<RefCell<Vec<u8> >>,
51 fn capacity(&self) -> uint {
52 self.data.borrow().capacity()
55 unsafe fn as_ptr(&self) -> *u8 {
56 self.data.borrow().as_ptr()
60 // Arenas are used to quickly allocate objects that share a
61 // lifetime. The arena uses ~[u8] vectors as a backing store to
62 // allocate objects from. For each allocated object, the arena stores
63 // a pointer to the type descriptor followed by the
64 // object. (Potentially with alignment padding after each of them.)
65 // When the arena is destroyed, it iterates through all of its chunks,
66 // and uses the tydesc information to trace through the objects,
67 // calling the destructors on them.
68 // One subtle point that needs to be addressed is how to handle
69 // failures while running the user provided initializer function. It
70 // is important to not run the destructor on uninitialized objects, but
71 // how to detect them is somewhat subtle. Since alloc() can be invoked
72 // recursively, it is not sufficient to simply exclude the most recent
73 // object. To solve this without requiring extra space, we use the low
74 // order bit of the tydesc pointer to encode whether the object it
75 // describes has been fully initialized.
77 // As an optimization, objects with destructors are stored in
78 // different chunks than objects without destructors. This reduces
79 // overhead when initializing plain-old-data and means we don't need
80 // to waste time running the destructors of POD.
82 // The head is separated out from the list as a unbenchmarked
83 // microoptimization, to avoid needing to case on the list to
87 chunks: RefCell<Vec<Chunk>>,
91 pub fn new() -> Arena {
92 Arena::new_with_size(32u)
95 pub fn new_with_size(initial_size: uint) -> Arena {
97 head: chunk(initial_size, false),
98 copy_head: chunk(initial_size, true),
99 chunks: RefCell::new(Vec::new()),
104 fn chunk(size: uint, is_copy: bool) -> Chunk {
106 data: Rc::new(RefCell::new(Vec::with_capacity(size))),
108 is_copy: Cell::new(is_copy),
113 impl Drop for Arena {
116 destroy_chunk(&self.head);
117 for chunk in self.chunks.borrow().iter() {
118 if !chunk.is_copy.get() {
119 destroy_chunk(chunk);
127 fn round_up(base: uint, align: uint) -> uint {
128 (base.checked_add(&(align - 1))).unwrap() & !(&(align - 1))
131 // Walk down a chunk, running the destructors for any objects stored
133 unsafe fn destroy_chunk(chunk: &Chunk) {
135 let buf = chunk.as_ptr();
136 let fill = chunk.fill.get();
139 let tydesc_data: *uint = transmute(buf.offset(idx as int));
140 let (tydesc, is_done) = un_bitpack_tydesc_ptr(*tydesc_data);
141 let (size, align) = ((*tydesc).size, (*tydesc).align);
143 let after_tydesc = idx + mem::size_of::<*TyDesc>();
145 let start = round_up(after_tydesc, align);
147 //debug!("freeing object: idx = {}, size = {}, align = {}, done = {}",
148 // start, size, align, is_done);
150 ((*tydesc).drop_glue)(buf.offset(start as int) as *i8);
153 // Find where the next tydesc lives
154 idx = round_up(start + size, mem::pref_align_of::<*TyDesc>());
158 // We encode whether the object a tydesc describes has been
159 // initialized in the arena in the low bit of the tydesc pointer. This
160 // is necessary in order to properly do cleanup if a failure occurs
161 // during an initializer.
163 fn bitpack_tydesc_ptr(p: *TyDesc, is_done: bool) -> uint {
164 p as uint | (is_done as uint)
167 fn un_bitpack_tydesc_ptr(p: uint) -> (*TyDesc, bool) {
168 ((p & !1) as *TyDesc, p & 1 == 1)
172 fn chunk_size(&self) -> uint {
173 self.copy_head.capacity()
175 // Functions for the POD part of the arena
176 fn alloc_copy_grow(&mut self, n_bytes: uint, align: uint) -> *u8 {
177 // Allocate a new chunk.
178 let new_min_chunk_size = cmp::max(n_bytes, self.chunk_size());
179 self.chunks.borrow_mut().push(self.copy_head.clone());
181 chunk(num::next_power_of_two(new_min_chunk_size + 1u), true);
183 return self.alloc_copy_inner(n_bytes, align);
187 fn alloc_copy_inner(&mut self, n_bytes: uint, align: uint) -> *u8 {
189 let this = transmute_mut_lifetime(self);
190 let start = round_up(this.copy_head.fill.get(), align);
191 let end = start + n_bytes;
192 if end > self.chunk_size() {
193 return this.alloc_copy_grow(n_bytes, align);
195 this.copy_head.fill.set(end);
197 //debug!("idx = {}, size = {}, align = {}, fill = {}",
198 // start, n_bytes, align, head.fill.get());
200 this.copy_head.as_ptr().offset(start as int)
205 fn alloc_copy<'a, T>(&'a mut self, op: || -> T) -> &'a T {
207 let ptr = self.alloc_copy_inner(mem::size_of::<T>(), mem::min_align_of::<T>());
208 let ptr: *mut T = transmute(ptr);
209 mem::move_val_init(&mut (*ptr), op());
210 return transmute(ptr);
214 // Functions for the non-POD part of the arena
215 fn alloc_noncopy_grow(&mut self, n_bytes: uint, align: uint)
217 // Allocate a new chunk.
218 let new_min_chunk_size = cmp::max(n_bytes, self.chunk_size());
219 self.chunks.borrow_mut().push(self.head.clone());
221 chunk(num::next_power_of_two(new_min_chunk_size + 1u), false);
223 return self.alloc_noncopy_inner(n_bytes, align);
227 fn alloc_noncopy_inner(&mut self, n_bytes: uint, align: uint)
236 let head = transmute_mut_lifetime(&mut self.head);
238 tydesc_start = head.fill.get();
239 after_tydesc = head.fill.get() + mem::size_of::<*TyDesc>();
240 start = round_up(after_tydesc, align);
241 end = start + n_bytes;
244 if end > self.head.capacity() {
245 return self.alloc_noncopy_grow(n_bytes, align);
248 let head = transmute_mut_lifetime(&mut self.head);
249 head.fill.set(round_up(end, mem::pref_align_of::<*TyDesc>()));
251 //debug!("idx = {}, size = {}, align = {}, fill = {}",
252 // start, n_bytes, align, head.fill);
254 let buf = self.head.as_ptr();
255 return (buf.offset(tydesc_start as int), buf.offset(start as int));
260 fn alloc_noncopy<'a, T>(&'a mut self, op: || -> T) -> &'a T {
262 let tydesc = get_tydesc::<T>();
264 self.alloc_noncopy_inner(mem::size_of::<T>(), mem::min_align_of::<T>());
265 let ty_ptr: *mut uint = transmute(ty_ptr);
266 let ptr: *mut T = transmute(ptr);
267 // Write in our tydesc along with a bit indicating that it
268 // has *not* been initialized yet.
269 *ty_ptr = transmute(tydesc);
270 // Actually initialize it
271 mem::move_val_init(&mut(*ptr), op());
272 // Now that we are done, update the tydesc to indicate that
273 // the object is there.
274 *ty_ptr = bitpack_tydesc_ptr(tydesc, true);
276 return transmute(ptr);
280 // The external interface
282 pub fn alloc<'a, T>(&'a self, op: || -> T) -> &'a T {
284 // FIXME: Borrow check
285 let this = transmute_mut(self);
286 if intrinsics::needs_drop::<T>() {
287 this.alloc_noncopy(op)
296 fn test_arena_destructors() {
297 let arena = Arena::new();
298 for i in range(0u, 10) {
299 // Arena allocate something with drop glue to make sure it
301 arena.alloc(|| Rc::new(i));
302 // Allocate something with funny size and alignment, to keep
303 // things interesting.
304 arena.alloc(|| [0u8, 1u8, 2u8]);
310 fn test_arena_destructors_fail() {
311 let arena = Arena::new();
312 // Put some stuff in the arena.
313 for i in range(0u, 10) {
314 // Arena allocate something with drop glue to make sure it
316 arena.alloc(|| { Rc::new(i) });
317 // Allocate something with funny size and alignment, to keep
318 // things interesting.
319 arena.alloc(|| { [0u8, 1u8, 2u8] });
321 // Now, fail while allocating
322 arena.alloc::<Rc<int>>(|| {
328 /// An arena that can hold objects of only one type.
330 /// Safety note: Modifying objects in the arena that have already had their
331 /// `drop` destructors run can cause leaks, because the destructor will not
332 /// run again for these objects.
333 pub struct TypedArena<T> {
334 /// A pointer to the next object to be allocated.
337 /// A pointer to the end of the allocated area. When this pointer is
338 /// reached, a new chunk is allocated.
341 /// A pointer to the first arena segment.
342 first: Option<~TypedArenaChunk<T>>,
345 struct TypedArenaChunk<T> {
346 /// Pointer to the next arena segment.
347 next: Option<~TypedArenaChunk<T>>,
349 /// The number of elements that this chunk can hold.
352 // Objects follow here, suitably aligned.
355 impl<T> TypedArenaChunk<T> {
357 fn new(next: Option<~TypedArenaChunk<T>>, capacity: uint) -> ~TypedArenaChunk<T> {
358 let mut size = mem::size_of::<TypedArenaChunk<T>>();
359 size = round_up(size, mem::min_align_of::<T>());
360 let elem_size = mem::size_of::<T>();
361 let elems_size = elem_size.checked_mul(&capacity).unwrap();
362 size = size.checked_add(&elems_size).unwrap();
364 let mut chunk = unsafe {
365 let chunk = global_heap::exchange_malloc(size);
366 let mut chunk: ~TypedArenaChunk<T> = cast::transmute(chunk);
367 mem::move_val_init(&mut chunk.next, next);
371 chunk.capacity = capacity;
375 /// Destroys this arena chunk. If the type descriptor is supplied, the
376 /// drop glue is called; otherwise, drop glue is not called.
378 unsafe fn destroy(&mut self, len: uint) {
379 // Destroy all the allocated objects.
380 if intrinsics::needs_drop::<T>() {
381 let mut start = self.start();
382 for _ in range(0, len) {
383 read(start as *T); // run the destructor on the pointer
384 start = start.offset(mem::size_of::<T>() as int)
388 // Destroy the next chunk.
389 let next_opt = mem::replace(&mut self.next, None);
393 // We assume that the next chunk is completely filled.
394 next.destroy(next.capacity)
399 // Returns a pointer to the first allocated object.
401 fn start(&self) -> *u8 {
402 let this: *TypedArenaChunk<T> = self;
404 cast::transmute(round_up(this.offset(1) as uint, mem::min_align_of::<T>()))
408 // Returns a pointer to the end of the allocated space.
410 fn end(&self) -> *u8 {
412 let size = mem::size_of::<T>().checked_mul(&self.capacity).unwrap();
413 self.start().offset(size as int)
418 impl<T> TypedArena<T> {
419 /// Creates a new arena with preallocated space for 8 objects.
421 pub fn new() -> TypedArena<T> {
422 TypedArena::with_capacity(8)
425 /// Creates a new arena with preallocated space for the given number of
428 pub fn with_capacity(capacity: uint) -> TypedArena<T> {
429 let chunk = TypedArenaChunk::<T>::new(None, capacity);
431 ptr: chunk.start() as *T,
432 end: chunk.end() as *T,
437 /// Allocates an object into this arena.
439 pub fn alloc<'a>(&'a self, object: T) -> &'a T {
441 let this = cast::transmute_mut(self);
442 if this.ptr == this.end {
446 let ptr: &'a mut T = cast::transmute(this.ptr);
447 mem::move_val_init(ptr, object);
448 this.ptr = this.ptr.offset(1);
449 let ptr: &'a T = ptr;
457 let chunk = self.first.take_unwrap();
458 let new_capacity = chunk.capacity.checked_mul(&2).unwrap();
459 let chunk = TypedArenaChunk::<T>::new(Some(chunk), new_capacity);
460 self.ptr = chunk.start() as *T;
461 self.end = chunk.end() as *T;
462 self.first = Some(chunk)
467 impl<T> Drop for TypedArena<T> {
469 // Determine how much was filled.
470 let start = self.first.get_ref().start() as uint;
471 let end = self.ptr as uint;
472 let diff = (end - start) / mem::size_of::<T>();
474 // Pass that to the `destroy` method.
476 self.first.get_mut_ref().destroy(diff)
484 use self::test::Bencher;
485 use super::{Arena, TypedArena};
495 let arena = TypedArena::new();
496 for _ in range(0, 100000) {
506 pub fn bench_copy(b: &mut Bencher) {
507 let arena = TypedArena::new();
518 pub fn bench_copy_nonarena(b: &mut Bencher) {
529 pub fn bench_copy_old_arena(b: &mut Bencher) {
530 let arena = Arena::new();
548 pub fn test_noncopy() {
549 let arena = TypedArena::new();
550 for _ in range(0, 100000) {
551 arena.alloc(Noncopy {
552 string: ~"hello world",
553 array: vec!( 1, 2, 3, 4, 5 ),
559 pub fn bench_noncopy(b: &mut Bencher) {
560 let arena = TypedArena::new();
562 arena.alloc(Noncopy {
563 string: ~"hello world",
564 array: vec!( 1, 2, 3, 4, 5 ),
570 pub fn bench_noncopy_nonarena(b: &mut Bencher) {
573 string: ~"hello world",
574 array: vec!( 1, 2, 3, 4, 5 ),
580 pub fn bench_noncopy_old_arena(b: &mut Bencher) {
581 let arena = Arena::new();
583 arena.alloc(|| Noncopy {
584 string: ~"hello world",
585 array: vec!( 1, 2, 3, 4, 5 ),