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_id = "arena#0.11.0-pre"]
24 #![crate_type = "rlib"]
25 #![crate_type = "dylib"]
26 #![license = "MIT/ASL2"]
27 #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
28 html_favicon_url = "http://www.rust-lang.org/favicon.ico",
29 html_root_url = "http://doc.rust-lang.org/")]
31 #![feature(unsafe_destructor)]
32 #![allow(missing_doc)]
34 use std::cell::{Cell, RefCell};
36 use std::intrinsics::{TyDesc, get_tydesc};
42 use std::rt::heap::allocate;
44 // The way arena uses arrays is really deeply awful. The arrays are
45 // allocated, and have capacities reserved, but the fill for the array
46 // will always stay at 0.
47 #[deriving(Clone, PartialEq)]
49 data: Rc<RefCell<Vec<u8> >>,
54 fn capacity(&self) -> uint {
55 self.data.borrow().capacity()
58 unsafe fn as_ptr(&self) -> *u8 {
59 self.data.borrow().as_ptr()
63 /// A slower reflection-based arena that can allocate objects of any type.
65 /// This arena uses Vec<u8> as a backing store to allocate objects from. For
66 /// each allocated object, the arena stores a pointer to the type descriptor
67 /// followed by the object. (Potentially with alignment padding after each
68 /// element.) When the arena is destroyed, it iterates through all of its
69 /// chunks, and uses the tydesc information to trace through the objects,
70 /// calling the destructors on them. One subtle point that needs to be
71 /// addressed is how to handle failures while running the user provided
72 /// initializer function. It is important to not run the destructor on
73 /// uninitialized objects, but how to detect them is somewhat subtle. Since
74 /// alloc() can be invoked recursively, it is not sufficient to simply exclude
75 /// the most recent object. To solve this without requiring extra space, we
76 /// use the low order bit of the tydesc pointer to encode whether the object
77 /// it describes has been fully initialized.
79 /// As an optimization, objects with destructors are stored in
80 /// different chunks than objects without destructors. This reduces
81 /// overhead when initializing plain-old-data and means we don't need
82 /// to waste time running the destructors of POD.
84 // The head is separated out from the list as a unbenchmarked
85 // microoptimization, to avoid needing to case on the list to access the
88 copy_head: RefCell<Chunk>,
89 chunks: RefCell<Vec<Chunk>>,
93 /// Allocate a new Arena with 32 bytes preallocated.
94 pub fn new() -> Arena {
95 Arena::new_with_size(32u)
98 /// Allocate a new Arena with `initial_size` bytes preallocated.
99 pub fn new_with_size(initial_size: uint) -> Arena {
101 head: RefCell::new(chunk(initial_size, false)),
102 copy_head: RefCell::new(chunk(initial_size, true)),
103 chunks: RefCell::new(Vec::new()),
108 fn chunk(size: uint, is_copy: bool) -> Chunk {
110 data: Rc::new(RefCell::new(Vec::with_capacity(size))),
112 is_copy: Cell::new(is_copy),
117 impl Drop for Arena {
120 destroy_chunk(&*self.head.borrow());
121 for chunk in self.chunks.borrow().iter() {
122 if !chunk.is_copy.get() {
123 destroy_chunk(chunk);
131 fn round_up(base: uint, align: uint) -> uint {
132 (base.checked_add(&(align - 1))).unwrap() & !(&(align - 1))
135 // Walk down a chunk, running the destructors for any objects stored
137 unsafe fn destroy_chunk(chunk: &Chunk) {
139 let buf = chunk.as_ptr();
140 let fill = chunk.fill.get();
143 let tydesc_data: *uint = mem::transmute(buf.offset(idx as int));
144 let (tydesc, is_done) = un_bitpack_tydesc_ptr(*tydesc_data);
145 let (size, align) = ((*tydesc).size, (*tydesc).align);
147 let after_tydesc = idx + mem::size_of::<*TyDesc>();
149 let start = round_up(after_tydesc, align);
151 //debug!("freeing object: idx = {}, size = {}, align = {}, done = {}",
152 // start, size, align, is_done);
154 ((*tydesc).drop_glue)(buf.offset(start as int) as *i8);
157 // Find where the next tydesc lives
158 idx = round_up(start + size, mem::align_of::<*TyDesc>());
162 // We encode whether the object a tydesc describes has been
163 // initialized in the arena in the low bit of the tydesc pointer. This
164 // is necessary in order to properly do cleanup if a failure occurs
165 // during an initializer.
167 fn bitpack_tydesc_ptr(p: *TyDesc, is_done: bool) -> uint {
168 p as uint | (is_done as uint)
171 fn un_bitpack_tydesc_ptr(p: uint) -> (*TyDesc, bool) {
172 ((p & !1) as *TyDesc, p & 1 == 1)
176 fn chunk_size(&self) -> uint {
177 self.copy_head.borrow().capacity()
180 // Functions for the POD part of the arena
181 fn alloc_copy_grow(&self, n_bytes: uint, align: uint) -> *u8 {
182 // Allocate a new chunk.
183 let new_min_chunk_size = cmp::max(n_bytes, self.chunk_size());
184 self.chunks.borrow_mut().push(self.copy_head.borrow().clone());
186 *self.copy_head.borrow_mut() =
187 chunk(num::next_power_of_two(new_min_chunk_size + 1u), true);
189 return self.alloc_copy_inner(n_bytes, align);
193 fn alloc_copy_inner(&self, n_bytes: uint, align: uint) -> *u8 {
194 let start = round_up(self.copy_head.borrow().fill.get(), align);
196 let end = start + n_bytes;
197 if end > self.chunk_size() {
198 return self.alloc_copy_grow(n_bytes, align);
201 let copy_head = self.copy_head.borrow();
202 copy_head.fill.set(end);
205 copy_head.as_ptr().offset(start as int)
210 fn alloc_copy<'a, T>(&'a self, op: || -> T) -> &'a T {
212 let ptr = self.alloc_copy_inner(mem::size_of::<T>(),
213 mem::min_align_of::<T>());
214 let ptr = ptr as *mut T;
215 ptr::write(&mut (*ptr), op());
220 // Functions for the non-POD part of the arena
221 fn alloc_noncopy_grow(&self, n_bytes: uint, align: uint) -> (*u8, *u8) {
222 // Allocate a new chunk.
223 let new_min_chunk_size = cmp::max(n_bytes, self.chunk_size());
224 self.chunks.borrow_mut().push(self.head.borrow().clone());
226 *self.head.borrow_mut() =
227 chunk(num::next_power_of_two(new_min_chunk_size + 1u), false);
229 return self.alloc_noncopy_inner(n_bytes, align);
233 fn alloc_noncopy_inner(&self, n_bytes: uint, align: uint) -> (*u8, *u8) {
234 // Be careful to not maintain any `head` borrows active, because
235 // `alloc_noncopy_grow` borrows it mutably.
236 let (start, end, tydesc_start, head_capacity) = {
237 let head = self.head.borrow();
238 let fill = head.fill.get();
240 let tydesc_start = fill;
241 let after_tydesc = fill + mem::size_of::<*TyDesc>();
242 let start = round_up(after_tydesc, align);
243 let end = start + n_bytes;
245 (start, end, tydesc_start, head.capacity())
248 if end > head_capacity {
249 return self.alloc_noncopy_grow(n_bytes, align);
252 let head = self.head.borrow();
253 head.fill.set(round_up(end, mem::align_of::<*TyDesc>()));
256 let buf = head.as_ptr();
257 return (buf.offset(tydesc_start as int), buf.offset(start as int));
262 fn alloc_noncopy<'a, T>(&'a self, op: || -> T) -> &'a T {
264 let tydesc = get_tydesc::<T>();
266 self.alloc_noncopy_inner(mem::size_of::<T>(),
267 mem::min_align_of::<T>());
268 let ty_ptr = ty_ptr as *mut uint;
269 let ptr = ptr as *mut T;
270 // Write in our tydesc along with a bit indicating that it
271 // has *not* been initialized yet.
272 *ty_ptr = mem::transmute(tydesc);
273 // Actually initialize it
274 ptr::write(&mut(*ptr), op());
275 // Now that we are done, update the tydesc to indicate that
276 // the object is there.
277 *ty_ptr = bitpack_tydesc_ptr(tydesc, true);
283 /// Allocate a new item in the arena, using `op` to initialize the value
284 /// and returning a reference to it.
286 pub fn alloc<'a, T>(&'a self, op: || -> T) -> &'a T {
288 if intrinsics::needs_drop::<T>() {
289 self.alloc_noncopy(op)
298 fn test_arena_destructors() {
299 let arena = Arena::new();
300 for i in range(0u, 10) {
301 // Arena allocate something with drop glue to make sure it
303 arena.alloc(|| Rc::new(i));
304 // Allocate something with funny size and alignment, to keep
305 // things interesting.
306 arena.alloc(|| [0u8, 1u8, 2u8]);
311 fn test_arena_alloc_nested() {
312 struct Inner { value: uint }
313 struct Outer<'a> { inner: &'a Inner }
315 let arena = Arena::new();
317 let result = arena.alloc(|| Outer {
318 inner: arena.alloc(|| Inner { value: 10 })
321 assert_eq!(result.inner.value, 10);
326 fn test_arena_destructors_fail() {
327 let arena = Arena::new();
328 // Put some stuff in the arena.
329 for i in range(0u, 10) {
330 // Arena allocate something with drop glue to make sure it
332 arena.alloc(|| { Rc::new(i) });
333 // Allocate something with funny size and alignment, to keep
334 // things interesting.
335 arena.alloc(|| { [0u8, 1u8, 2u8] });
337 // Now, fail while allocating
338 arena.alloc::<Rc<int>>(|| {
344 /// A faster arena that can hold objects of only one type.
346 /// Safety note: Modifying objects in the arena that have already had their
347 /// `drop` destructors run can cause leaks, because the destructor will not
348 /// run again for these objects.
349 pub struct TypedArena<T> {
350 /// A pointer to the next object to be allocated.
353 /// A pointer to the end of the allocated area. When this pointer is
354 /// reached, a new chunk is allocated.
357 /// A pointer to the first arena segment.
358 first: RefCell<TypedArenaChunkRef<T>>,
360 type TypedArenaChunkRef<T> = Option<Box<TypedArenaChunk<T>>>;
362 struct TypedArenaChunk<T> {
363 /// Pointer to the next arena segment.
364 next: TypedArenaChunkRef<T>,
366 /// The number of elements that this chunk can hold.
369 // Objects follow here, suitably aligned.
372 impl<T> TypedArenaChunk<T> {
374 fn new(next: Option<Box<TypedArenaChunk<T>>>, capacity: uint)
375 -> Box<TypedArenaChunk<T>> {
376 let mut size = mem::size_of::<TypedArenaChunk<T>>();
377 size = round_up(size, mem::min_align_of::<T>());
378 let elem_size = mem::size_of::<T>();
379 let elems_size = elem_size.checked_mul(&capacity).unwrap();
380 size = size.checked_add(&elems_size).unwrap();
382 let mut chunk = unsafe {
383 let chunk = allocate(size, mem::min_align_of::<TypedArenaChunk<T>>());
384 let mut chunk: Box<TypedArenaChunk<T>> = mem::transmute(chunk);
385 ptr::write(&mut chunk.next, next);
389 chunk.capacity = capacity;
393 /// Destroys this arena chunk. If the type descriptor is supplied, the
394 /// drop glue is called; otherwise, drop glue is not called.
396 unsafe fn destroy(&mut self, len: uint) {
397 // Destroy all the allocated objects.
398 if intrinsics::needs_drop::<T>() {
399 let mut start = self.start();
400 for _ in range(0, len) {
401 ptr::read(start as *T); // run the destructor on the pointer
402 start = start.offset(mem::size_of::<T>() as int)
406 // Destroy the next chunk.
407 let next_opt = mem::replace(&mut self.next, None);
411 // We assume that the next chunk is completely filled.
412 let capacity = next.capacity;
413 next.destroy(capacity)
418 // Returns a pointer to the first allocated object.
420 fn start(&self) -> *u8 {
421 let this: *TypedArenaChunk<T> = self;
423 mem::transmute(round_up(this.offset(1) as uint,
424 mem::min_align_of::<T>()))
428 // Returns a pointer to the end of the allocated space.
430 fn end(&self) -> *u8 {
432 let size = mem::size_of::<T>().checked_mul(&self.capacity).unwrap();
433 self.start().offset(size as int)
438 impl<T> TypedArena<T> {
439 /// Creates a new TypedArena with preallocated space for 8 objects.
441 pub fn new() -> TypedArena<T> {
442 TypedArena::with_capacity(8)
445 /// Creates a new TypedArena with preallocated space for the given number of
448 pub fn with_capacity(capacity: uint) -> TypedArena<T> {
449 let chunk = TypedArenaChunk::<T>::new(None, capacity);
451 ptr: Cell::new(chunk.start() as *T),
452 end: Cell::new(chunk.end() as *T),
453 first: RefCell::new(Some(chunk)),
457 /// Allocates an object in the TypedArena, returning a reference to it.
459 pub fn alloc<'a>(&'a self, object: T) -> &'a T {
460 if self.ptr == self.end {
464 let ptr: &'a T = unsafe {
465 let ptr: &'a mut T = mem::transmute(self.ptr);
466 ptr::write(ptr, object);
467 self.ptr.set(self.ptr.get().offset(1));
477 let chunk = self.first.borrow_mut().take_unwrap();
478 let new_capacity = chunk.capacity.checked_mul(&2).unwrap();
479 let chunk = TypedArenaChunk::<T>::new(Some(chunk), new_capacity);
480 self.ptr.set(chunk.start() as *T);
481 self.end.set(chunk.end() as *T);
482 *self.first.borrow_mut() = Some(chunk)
487 impl<T> Drop for TypedArena<T> {
489 // Determine how much was filled.
490 let start = self.first.borrow().get_ref().start() as uint;
491 let end = self.ptr.get() as uint;
492 let diff = (end - start) / mem::size_of::<T>();
494 // Pass that to the `destroy` method.
496 self.first.borrow_mut().get_mut_ref().destroy(diff)
504 use self::test::Bencher;
505 use super::{Arena, TypedArena};
515 let arena = TypedArena::new();
516 for _ in range(0u, 100000) {
526 pub fn bench_copy(b: &mut Bencher) {
527 let arena = TypedArena::new();
538 pub fn bench_copy_nonarena(b: &mut Bencher) {
549 pub fn bench_copy_old_arena(b: &mut Bencher) {
550 let arena = Arena::new();
568 pub fn test_noncopy() {
569 let arena = TypedArena::new();
570 for _ in range(0u, 100000) {
571 arena.alloc(Noncopy {
572 string: "hello world".to_string(),
573 array: vec!( 1, 2, 3, 4, 5 ),
579 pub fn bench_noncopy(b: &mut Bencher) {
580 let arena = TypedArena::new();
582 arena.alloc(Noncopy {
583 string: "hello world".to_string(),
584 array: vec!( 1, 2, 3, 4, 5 ),
590 pub fn bench_noncopy_nonarena(b: &mut Bencher) {
593 string: "hello world".to_string(),
594 array: vec!( 1, 2, 3, 4, 5 ),
600 pub fn bench_noncopy_old_arena(b: &mut Bencher) {
601 let arena = Arena::new();
603 arena.alloc(|| Noncopy {
604 string: "hello world".to_string(),
605 array: vec!( 1, 2, 3, 4, 5 ),