1 // Copyright 2012-2013 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.10-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)];
26 #[feature(managed_boxes)];
27 #[allow(deprecated_owned_vector)]; // NOTE: remove after stage0
29 extern crate collections;
31 use collections::list::{List, Cons, Nil};
33 use std::cast::{transmute, transmute_mut, transmute_mut_region};
35 use std::cell::{Cell, RefCell};
40 use std::kinds::marker;
42 use std::rt::global_heap;
43 use std::intrinsics::{TyDesc, get_tydesc};
46 // The way arena uses arrays is really deeply awful. The arrays are
47 // allocated, and have capacities reserved, but the fill for the array
48 // will always stay at 0.
49 #[deriving(Clone, Eq)]
51 data: Rc<RefCell<Vec<u8> >>,
56 fn capacity(&self) -> uint {
57 self.data.deref().borrow().get().capacity()
60 unsafe fn as_ptr(&self) -> *u8 {
61 self.data.deref().borrow().get().as_ptr()
65 // Arenas are used to quickly allocate objects that share a
66 // lifetime. The arena uses ~[u8] vectors as a backing store to
67 // allocate objects from. For each allocated object, the arena stores
68 // a pointer to the type descriptor followed by the
69 // object. (Potentially with alignment padding after each of them.)
70 // When the arena is destroyed, it iterates through all of its chunks,
71 // and uses the tydesc information to trace through the objects,
72 // calling the destructors on them.
73 // One subtle point that needs to be addressed is how to handle
74 // failures while running the user provided initializer function. It
75 // is important to not run the destructor on uninitialized objects, but
76 // how to detect them is somewhat subtle. Since alloc() can be invoked
77 // recursively, it is not sufficient to simply exclude the most recent
78 // object. To solve this without requiring extra space, we use the low
79 // order bit of the tydesc pointer to encode whether the object it
80 // describes has been fully initialized.
82 // As an optimization, objects with destructors are stored in
83 // different chunks than objects without destructors. This reduces
84 // overhead when initializing plain-old-data and means we don't need
85 // to waste time running the destructors of POD.
87 // The head is separated out from the list as a unbenchmarked
88 // microoptimization, to avoid needing to case on the list to
92 priv chunks: RefCell<@List<Chunk>>,
93 priv no_freeze: marker::NoFreeze,
97 pub fn new() -> Arena {
98 Arena::new_with_size(32u)
101 pub fn new_with_size(initial_size: uint) -> Arena {
103 head: chunk(initial_size, false),
104 pod_head: chunk(initial_size, true),
105 chunks: RefCell::new(@Nil),
106 no_freeze: marker::NoFreeze,
111 fn chunk(size: uint, is_pod: bool) -> Chunk {
113 data: Rc::new(RefCell::new(Vec::with_capacity(size))),
115 is_pod: Cell::new(is_pod),
120 impl Drop for Arena {
123 destroy_chunk(&self.head);
124 for chunk in self.chunks.get().iter() {
125 if !chunk.is_pod.get() {
126 destroy_chunk(chunk);
134 fn round_up(base: uint, align: uint) -> uint {
135 (base.checked_add(&(align - 1))).unwrap() & !(&(align - 1))
138 // Walk down a chunk, running the destructors for any objects stored
140 unsafe fn destroy_chunk(chunk: &Chunk) {
142 let buf = chunk.as_ptr();
143 let fill = chunk.fill.get();
146 let tydesc_data: *uint = transmute(buf.offset(idx as int));
147 let (tydesc, is_done) = un_bitpack_tydesc_ptr(*tydesc_data);
148 let (size, align) = ((*tydesc).size, (*tydesc).align);
150 let after_tydesc = idx + mem::size_of::<*TyDesc>();
152 let start = round_up(after_tydesc, align);
154 //debug!("freeing object: idx = {}, size = {}, align = {}, done = {}",
155 // start, size, align, is_done);
157 ((*tydesc).drop_glue)(buf.offset(start as int) as *i8);
160 // Find where the next tydesc lives
161 idx = round_up(start + size, mem::pref_align_of::<*TyDesc>());
165 // We encode whether the object a tydesc describes has been
166 // initialized in the arena in the low bit of the tydesc pointer. This
167 // is necessary in order to properly do cleanup if a failure occurs
168 // during an initializer.
170 fn bitpack_tydesc_ptr(p: *TyDesc, is_done: bool) -> uint {
171 p as uint | (is_done as uint)
174 fn un_bitpack_tydesc_ptr(p: uint) -> (*TyDesc, bool) {
175 ((p & !1) as *TyDesc, p & 1 == 1)
179 fn chunk_size(&self) -> uint {
180 self.pod_head.capacity()
182 // Functions for the POD part of the arena
183 fn alloc_pod_grow(&mut self, n_bytes: uint, align: uint) -> *u8 {
184 // Allocate a new chunk.
185 let new_min_chunk_size = cmp::max(n_bytes, self.chunk_size());
186 self.chunks.set(@Cons(self.pod_head.clone(), self.chunks.get()));
188 chunk(num::next_power_of_two(new_min_chunk_size + 1u), true);
190 return self.alloc_pod_inner(n_bytes, align);
194 fn alloc_pod_inner(&mut self, n_bytes: uint, align: uint) -> *u8 {
196 let this = transmute_mut_region(self);
197 let start = round_up(this.pod_head.fill.get(), align);
198 let end = start + n_bytes;
199 if end > self.chunk_size() {
200 return this.alloc_pod_grow(n_bytes, align);
202 this.pod_head.fill.set(end);
204 //debug!("idx = {}, size = {}, align = {}, fill = {}",
205 // start, n_bytes, align, head.fill.get());
207 this.pod_head.as_ptr().offset(start as int)
212 fn alloc_pod<'a, T>(&'a mut self, op: || -> T) -> &'a T {
214 let ptr = self.alloc_pod_inner(mem::size_of::<T>(), mem::min_align_of::<T>());
215 let ptr: *mut T = transmute(ptr);
216 mem::move_val_init(&mut (*ptr), op());
217 return transmute(ptr);
221 // Functions for the non-POD part of the arena
222 fn alloc_nonpod_grow(&mut self, n_bytes: uint, align: uint)
224 // Allocate a new chunk.
225 let new_min_chunk_size = cmp::max(n_bytes, self.chunk_size());
226 self.chunks.set(@Cons(self.head.clone(), self.chunks.get()));
228 chunk(num::next_power_of_two(new_min_chunk_size + 1u), false);
230 return self.alloc_nonpod_inner(n_bytes, align);
234 fn alloc_nonpod_inner(&mut self, n_bytes: uint, align: uint)
243 let head = transmute_mut_region(&mut self.head);
245 tydesc_start = head.fill.get();
246 after_tydesc = head.fill.get() + mem::size_of::<*TyDesc>();
247 start = round_up(after_tydesc, align);
248 end = start + n_bytes;
251 if end > self.head.capacity() {
252 return self.alloc_nonpod_grow(n_bytes, align);
255 let head = transmute_mut_region(&mut self.head);
256 head.fill.set(round_up(end, mem::pref_align_of::<*TyDesc>()));
258 //debug!("idx = {}, size = {}, align = {}, fill = {}",
259 // start, n_bytes, align, head.fill);
261 let buf = self.head.as_ptr();
262 return (buf.offset(tydesc_start as int), buf.offset(start as int));
267 fn alloc_nonpod<'a, T>(&'a mut self, op: || -> T) -> &'a T {
269 let tydesc = get_tydesc::<T>();
271 self.alloc_nonpod_inner(mem::size_of::<T>(), mem::min_align_of::<T>());
272 let ty_ptr: *mut uint = transmute(ty_ptr);
273 let ptr: *mut T = transmute(ptr);
274 // Write in our tydesc along with a bit indicating that it
275 // has *not* been initialized yet.
276 *ty_ptr = transmute(tydesc);
277 // Actually initialize it
278 mem::move_val_init(&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);
283 return transmute(ptr);
287 // The external interface
289 pub fn alloc<'a, T>(&'a self, op: || -> T) -> &'a T {
291 // FIXME: Borrow check
292 let this = transmute_mut(self);
293 if intrinsics::needs_drop::<T>() {
294 this.alloc_nonpod(op)
303 fn test_arena_destructors() {
304 let arena = Arena::new();
305 for i in range(0u, 10) {
306 // Arena allocate something with drop glue to make sure it
309 // Allocate something with funny size and alignment, to keep
310 // things interesting.
311 arena.alloc(|| [0u8, 1u8, 2u8]);
317 fn test_arena_destructors_fail() {
318 let arena = Arena::new();
319 // Put some stuff in the arena.
320 for i in range(0u, 10) {
321 // Arena allocate something with drop glue to make sure it
323 arena.alloc(|| { @i });
324 // Allocate something with funny size and alignment, to keep
325 // things interesting.
326 arena.alloc(|| { [0u8, 1u8, 2u8] });
328 // Now, fail while allocating
329 arena.alloc::<@int>(|| {
335 /// An arena that can hold objects of only one type.
337 /// Safety note: Modifying objects in the arena that have already had their
338 /// `drop` destructors run can cause leaks, because the destructor will not
339 /// run again for these objects.
340 pub struct TypedArena<T> {
341 /// A pointer to the next object to be allocated.
344 /// A pointer to the end of the allocated area. When this pointer is
345 /// reached, a new chunk is allocated.
348 /// A pointer to the first arena segment.
349 priv first: Option<~TypedArenaChunk<T>>,
352 struct TypedArenaChunk<T> {
353 /// Pointer to the next arena segment.
354 next: Option<~TypedArenaChunk<T>>,
356 /// The number of elements that this chunk can hold.
359 // Objects follow here, suitably aligned.
362 impl<T> TypedArenaChunk<T> {
364 fn new(next: Option<~TypedArenaChunk<T>>, capacity: uint) -> ~TypedArenaChunk<T> {
365 let mut size = mem::size_of::<TypedArenaChunk<T>>();
366 size = round_up(size, mem::min_align_of::<T>());
367 let elem_size = mem::size_of::<T>();
368 let elems_size = elem_size.checked_mul(&capacity).unwrap();
369 size = size.checked_add(&elems_size).unwrap();
371 let mut chunk = unsafe {
372 let chunk = global_heap::exchange_malloc(size);
373 let mut chunk: ~TypedArenaChunk<T> = cast::transmute(chunk);
374 mem::move_val_init(&mut chunk.next, next);
378 chunk.capacity = capacity;
382 /// Destroys this arena chunk. If the type descriptor is supplied, the
383 /// drop glue is called; otherwise, drop glue is not called.
385 unsafe fn destroy(&mut self, len: uint) {
386 // Destroy all the allocated objects.
387 if intrinsics::needs_drop::<T>() {
388 let mut start = self.start();
389 for _ in range(0, len) {
390 read(start as *T); // run the destructor on the pointer
391 start = start.offset(mem::size_of::<T>() as int)
395 // Destroy the next chunk.
396 let next_opt = mem::replace(&mut self.next, None);
400 // We assume that the next chunk is completely filled.
401 next.destroy(next.capacity)
406 // Returns a pointer to the first allocated object.
408 fn start(&self) -> *u8 {
409 let this: *TypedArenaChunk<T> = self;
411 cast::transmute(round_up(this.offset(1) as uint, mem::min_align_of::<T>()))
415 // Returns a pointer to the end of the allocated space.
417 fn end(&self) -> *u8 {
419 let size = mem::size_of::<T>().checked_mul(&self.capacity).unwrap();
420 self.start().offset(size as int)
425 impl<T> TypedArena<T> {
426 /// Creates a new arena with preallocated space for 8 objects.
428 pub fn new() -> TypedArena<T> {
429 TypedArena::with_capacity(8)
432 /// Creates a new arena with preallocated space for the given number of
435 pub fn with_capacity(capacity: uint) -> TypedArena<T> {
436 let chunk = TypedArenaChunk::<T>::new(None, capacity);
438 ptr: chunk.start() as *T,
439 end: chunk.end() as *T,
444 /// Allocates an object into this arena.
446 pub fn alloc<'a>(&'a self, object: T) -> &'a T {
448 let this = cast::transmute_mut(self);
449 if this.ptr == this.end {
453 let ptr: &'a mut T = cast::transmute(this.ptr);
454 mem::move_val_init(ptr, object);
455 this.ptr = this.ptr.offset(1);
456 let ptr: &'a T = ptr;
464 let chunk = self.first.take_unwrap();
465 let new_capacity = chunk.capacity.checked_mul(&2).unwrap();
466 let chunk = TypedArenaChunk::<T>::new(Some(chunk), new_capacity);
467 self.ptr = chunk.start() as *T;
468 self.end = chunk.end() as *T;
469 self.first = Some(chunk)
474 impl<T> Drop for TypedArena<T> {
476 // Determine how much was filled.
477 let start = self.first.get_ref().start() as uint;
478 let end = self.ptr as uint;
479 let diff = (end - start) / mem::size_of::<T>();
481 // Pass that to the `destroy` method.
483 self.first.get_mut_ref().destroy(diff)
493 use self::test::BenchHarness;
494 use super::{Arena, TypedArena};
504 let arena = TypedArena::new();
505 for _ in range(0, 100000) {
515 pub fn bench_pod(bh: &mut BenchHarness) {
516 let arena = TypedArena::new();
527 pub fn bench_pod_nonarena(bh: &mut BenchHarness) {
538 pub fn bench_pod_old_arena(bh: &mut BenchHarness) {
539 let arena = Arena::new();
557 pub fn test_nonpod() {
558 let arena = TypedArena::new();
559 for _ in range(0, 100000) {
561 string: ~"hello world",
562 array: vec!( 1, 2, 3, 4, 5 ),
568 pub fn bench_nonpod(bh: &mut BenchHarness) {
569 let arena = TypedArena::new();
572 string: ~"hello world",
573 array: vec!( 1, 2, 3, 4, 5 ),
579 pub fn bench_nonpod_nonarena(bh: &mut BenchHarness) {
582 string: ~"hello world",
583 array: vec!( 1, 2, 3, 4, 5 ),
589 pub fn bench_nonpod_old_arena(bh: &mut BenchHarness) {
590 let arena = Arena::new();
592 arena.alloc(|| Nonpod {
593 string: ~"hello world",
594 array: vec!( 1, 2, 3, 4, 5 ),