]> git.lizzy.rs Git - rust.git/blob - src/libarena/lib.rs
rollup merge of #18407 : thestinger/arena
[rust.git] / src / libarena / lib.rs
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.
4 //
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.
10
11 //! The arena, a fast but limited type of allocator.
12 //!
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.
17 //!
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.
21
22 #![crate_name = "arena"]
23 #![experimental]
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/nightly/")]
30
31 #![feature(unsafe_destructor)]
32 #![allow(missing_doc)]
33
34 use std::cell::{Cell, RefCell};
35 use std::cmp;
36 use std::intrinsics::{TyDesc, get_tydesc};
37 use std::intrinsics;
38 use std::mem;
39 use std::num;
40 use std::ptr;
41 use std::rc::Rc;
42 use std::rt::heap::{allocate, deallocate};
43
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)]
48 struct Chunk {
49     data: Rc<RefCell<Vec<u8>>>,
50     fill: Cell<uint>,
51     is_copy: Cell<bool>,
52 }
53
54 impl Chunk {
55     fn capacity(&self) -> uint {
56         self.data.borrow().capacity()
57     }
58
59     unsafe fn as_ptr(&self) -> *const u8 {
60         self.data.borrow().as_ptr()
61     }
62 }
63
64 /// A slower reflection-based arena that can allocate objects of any type.
65 ///
66 /// This arena uses `Vec<u8>` as a backing store to allocate objects from. For
67 /// each allocated object, the arena stores a pointer to the type descriptor
68 /// followed by the object (potentially with alignment padding after each
69 /// element). When the arena is destroyed, it iterates through all of its
70 /// chunks, and uses the tydesc information to trace through the objects,
71 /// calling the destructors on them. One subtle point that needs to be
72 /// addressed is how to handle panics while running the user provided
73 /// initializer function. It is important to not run the destructor on
74 /// uninitialized objects, but how to detect them is somewhat subtle. Since
75 /// `alloc()` can be invoked recursively, it is not sufficient to simply exclude
76 /// the most recent object. To solve this without requiring extra space, we
77 /// use the low order bit of the tydesc pointer to encode whether the object
78 /// it describes has been fully initialized.
79 ///
80 /// As an optimization, objects with destructors are stored in different chunks
81 /// than objects without destructors. This reduces overhead when initializing
82 /// plain-old-data (`Copy` types) and means we don't need to waste time running
83 /// their destructors.
84 pub struct Arena {
85     // The head is separated out from the list as a unbenchmarked
86     // microoptimization, to avoid needing to case on the list to access the
87     // head.
88     head: RefCell<Chunk>,
89     copy_head: RefCell<Chunk>,
90     chunks: RefCell<Vec<Chunk>>,
91 }
92
93 impl Arena {
94     /// Allocates a new Arena with 32 bytes preallocated.
95     pub fn new() -> Arena {
96         Arena::new_with_size(32u)
97     }
98
99     /// Allocates a new Arena with `initial_size` bytes preallocated.
100     pub fn new_with_size(initial_size: uint) -> Arena {
101         Arena {
102             head: RefCell::new(chunk(initial_size, false)),
103             copy_head: RefCell::new(chunk(initial_size, true)),
104             chunks: RefCell::new(Vec::new()),
105         }
106     }
107 }
108
109 fn chunk(size: uint, is_copy: bool) -> Chunk {
110     Chunk {
111         data: Rc::new(RefCell::new(Vec::with_capacity(size))),
112         fill: Cell::new(0u),
113         is_copy: Cell::new(is_copy),
114     }
115 }
116
117 #[unsafe_destructor]
118 impl Drop for Arena {
119     fn drop(&mut self) {
120         unsafe {
121             destroy_chunk(&*self.head.borrow());
122             for chunk in self.chunks.borrow().iter() {
123                 if !chunk.is_copy.get() {
124                     destroy_chunk(chunk);
125                 }
126             }
127         }
128     }
129 }
130
131 #[inline]
132 fn round_up(base: uint, align: uint) -> uint {
133     (base.checked_add(&(align - 1))).unwrap() & !(&(align - 1))
134 }
135
136 // Walk down a chunk, running the destructors for any objects stored
137 // in it.
138 unsafe fn destroy_chunk(chunk: &Chunk) {
139     let mut idx = 0;
140     let buf = chunk.as_ptr();
141     let fill = chunk.fill.get();
142
143     while idx < fill {
144         let tydesc_data: *const uint = mem::transmute(buf.offset(idx as int));
145         let (tydesc, is_done) = un_bitpack_tydesc_ptr(*tydesc_data);
146         let (size, align) = ((*tydesc).size, (*tydesc).align);
147
148         let after_tydesc = idx + mem::size_of::<*const TyDesc>();
149
150         let start = round_up(after_tydesc, align);
151
152         //debug!("freeing object: idx = {}, size = {}, align = {}, done = {}",
153         //       start, size, align, is_done);
154         if is_done {
155             ((*tydesc).drop_glue)(buf.offset(start as int) as *const i8);
156         }
157
158         // Find where the next tydesc lives
159         idx = round_up(start + size, mem::align_of::<*const TyDesc>());
160     }
161 }
162
163 // We encode whether the object a tydesc describes has been
164 // initialized in the arena in the low bit of the tydesc pointer. This
165 // is necessary in order to properly do cleanup if a panic occurs
166 // during an initializer.
167 #[inline]
168 fn bitpack_tydesc_ptr(p: *const TyDesc, is_done: bool) -> uint {
169     p as uint | (is_done as uint)
170 }
171 #[inline]
172 fn un_bitpack_tydesc_ptr(p: uint) -> (*const TyDesc, bool) {
173     ((p & !1) as *const TyDesc, p & 1 == 1)
174 }
175
176 impl Arena {
177     fn chunk_size(&self) -> uint {
178         self.copy_head.borrow().capacity()
179     }
180
181     // Functions for the POD part of the arena
182     fn alloc_copy_grow(&self, n_bytes: uint, align: uint) -> *const u8 {
183         // Allocate a new chunk.
184         let new_min_chunk_size = cmp::max(n_bytes, self.chunk_size());
185         self.chunks.borrow_mut().push(self.copy_head.borrow().clone());
186
187         *self.copy_head.borrow_mut() =
188             chunk(num::next_power_of_two(new_min_chunk_size + 1u), true);
189
190         return self.alloc_copy_inner(n_bytes, align);
191     }
192
193     #[inline]
194     fn alloc_copy_inner(&self, n_bytes: uint, align: uint) -> *const u8 {
195         let start = round_up(self.copy_head.borrow().fill.get(), align);
196
197         let end = start + n_bytes;
198         if end > self.chunk_size() {
199             return self.alloc_copy_grow(n_bytes, align);
200         }
201
202         let copy_head = self.copy_head.borrow();
203         copy_head.fill.set(end);
204
205         unsafe {
206             copy_head.as_ptr().offset(start as int)
207         }
208     }
209
210     #[inline]
211     fn alloc_copy<T>(&self, op: || -> T) -> &mut T {
212         unsafe {
213             let ptr = self.alloc_copy_inner(mem::size_of::<T>(),
214                                             mem::min_align_of::<T>());
215             let ptr = ptr as *mut T;
216             ptr::write(&mut (*ptr), op());
217             return &mut *ptr;
218         }
219     }
220
221     // Functions for the non-POD part of the arena
222     fn alloc_noncopy_grow(&self, n_bytes: uint,
223                           align: uint) -> (*const u8, *const u8) {
224         // Allocate a new chunk.
225         let new_min_chunk_size = cmp::max(n_bytes, self.chunk_size());
226         self.chunks.borrow_mut().push(self.head.borrow().clone());
227
228         *self.head.borrow_mut() =
229             chunk(num::next_power_of_two(new_min_chunk_size + 1u), false);
230
231         return self.alloc_noncopy_inner(n_bytes, align);
232     }
233
234     #[inline]
235     fn alloc_noncopy_inner(&self, n_bytes: uint,
236                            align: uint) -> (*const u8, *const u8) {
237         // Be careful to not maintain any `head` borrows active, because
238         // `alloc_noncopy_grow` borrows it mutably.
239         let (start, end, tydesc_start, head_capacity) = {
240             let head = self.head.borrow();
241             let fill = head.fill.get();
242
243             let tydesc_start = fill;
244             let after_tydesc = fill + mem::size_of::<*const TyDesc>();
245             let start = round_up(after_tydesc, align);
246             let end = start + n_bytes;
247
248             (start, end, tydesc_start, head.capacity())
249         };
250
251         if end > head_capacity {
252             return self.alloc_noncopy_grow(n_bytes, align);
253         }
254
255         let head = self.head.borrow();
256         head.fill.set(round_up(end, mem::align_of::<*const TyDesc>()));
257
258         unsafe {
259             let buf = head.as_ptr();
260             return (buf.offset(tydesc_start as int), buf.offset(start as int));
261         }
262     }
263
264     #[inline]
265     fn alloc_noncopy<T>(&self, op: || -> T) -> &mut T {
266         unsafe {
267             let tydesc = get_tydesc::<T>();
268             let (ty_ptr, ptr) =
269                 self.alloc_noncopy_inner(mem::size_of::<T>(),
270                                          mem::min_align_of::<T>());
271             let ty_ptr = ty_ptr as *mut uint;
272             let ptr = ptr as *mut T;
273             // Write in our tydesc along with a bit indicating that it
274             // has *not* been initialized yet.
275             *ty_ptr = mem::transmute(tydesc);
276             // Actually initialize it
277             ptr::write(&mut(*ptr), op());
278             // Now that we are done, update the tydesc to indicate that
279             // the object is there.
280             *ty_ptr = bitpack_tydesc_ptr(tydesc, true);
281
282             return &mut *ptr;
283         }
284     }
285
286     /// Allocates a new item in the arena, using `op` to initialize the value,
287     /// and returns a reference to it.
288     #[inline]
289     pub fn alloc<T>(&self, op: || -> T) -> &mut T {
290         unsafe {
291             if intrinsics::needs_drop::<T>() {
292                 self.alloc_noncopy(op)
293             } else {
294                 self.alloc_copy(op)
295             }
296         }
297     }
298 }
299
300 #[test]
301 fn test_arena_destructors() {
302     let arena = Arena::new();
303     for i in range(0u, 10) {
304         // Arena allocate something with drop glue to make sure it
305         // doesn't leak.
306         arena.alloc(|| Rc::new(i));
307         // Allocate something with funny size and alignment, to keep
308         // things interesting.
309         arena.alloc(|| [0u8, 1u8, 2u8]);
310     }
311 }
312
313 #[test]
314 fn test_arena_alloc_nested() {
315     struct Inner { value: uint }
316     struct Outer<'a> { inner: &'a Inner }
317
318     let arena = Arena::new();
319
320     let result = arena.alloc(|| Outer {
321         inner: arena.alloc(|| Inner { value: 10 })
322     });
323
324     assert_eq!(result.inner.value, 10);
325 }
326
327 #[test]
328 #[should_fail]
329 fn test_arena_destructors_fail() {
330     let arena = Arena::new();
331     // Put some stuff in the arena.
332     for i in range(0u, 10) {
333         // Arena allocate something with drop glue to make sure it
334         // doesn't leak.
335         arena.alloc(|| { Rc::new(i) });
336         // Allocate something with funny size and alignment, to keep
337         // things interesting.
338         arena.alloc(|| { [0u8, 1u8, 2u8] });
339     }
340     // Now, panic while allocating
341     arena.alloc::<Rc<int>>(|| {
342         panic!();
343     });
344 }
345
346 /// A faster arena that can hold objects of only one type.
347 ///
348 /// Safety note: Modifying objects in the arena that have already had their
349 /// `drop` destructors run can cause leaks, because the destructor will not
350 /// run again for these objects.
351 pub struct TypedArena<T> {
352     /// A pointer to the next object to be allocated.
353     ptr: Cell<*const T>,
354
355     /// A pointer to the end of the allocated area. When this pointer is
356     /// reached, a new chunk is allocated.
357     end: Cell<*const T>,
358
359     /// A pointer to the first arena segment.
360     first: RefCell<*mut TypedArenaChunk<T>>,
361 }
362
363 struct TypedArenaChunk<T> {
364     /// Pointer to the next arena segment.
365     next: *mut TypedArenaChunk<T>,
366
367     /// The number of elements that this chunk can hold.
368     capacity: uint,
369
370     // Objects follow here, suitably aligned.
371 }
372
373 fn calculate_size<T>(capacity: uint) -> uint {
374     let mut size = mem::size_of::<TypedArenaChunk<T>>();
375     size = round_up(size, mem::min_align_of::<T>());
376     let elem_size = mem::size_of::<T>();
377     let elems_size = elem_size.checked_mul(&capacity).unwrap();
378     size = size.checked_add(&elems_size).unwrap();
379     size
380 }
381
382 impl<T> TypedArenaChunk<T> {
383     #[inline]
384     unsafe fn new(next: *mut TypedArenaChunk<T>, capacity: uint)
385            -> *mut TypedArenaChunk<T> {
386         let size = calculate_size::<T>(capacity);
387         let chunk = allocate(size, mem::min_align_of::<TypedArenaChunk<T>>())
388                     as *mut TypedArenaChunk<T>;
389         (*chunk).next = next;
390         (*chunk).capacity = capacity;
391         chunk
392     }
393
394     /// Destroys this arena chunk. If the type descriptor is supplied, the
395     /// drop glue is called; otherwise, drop glue is not called.
396     #[inline]
397     unsafe fn destroy(&mut self, len: uint) {
398         // Destroy all the allocated objects.
399         if intrinsics::needs_drop::<T>() {
400             let mut start = self.start();
401             for _ in range(0, len) {
402                 ptr::read(start as *const T); // run the destructor on the pointer
403                 start = start.offset(mem::size_of::<T>() as int)
404             }
405         }
406
407         // Destroy the next chunk.
408         let next = self.next;
409         let size = calculate_size::<T>(self.capacity);
410         deallocate(self as *mut TypedArenaChunk<T> as *mut u8, size,
411                    mem::min_align_of::<TypedArenaChunk<T>>());
412         if next.is_not_null() {
413             let capacity = (*next).capacity;
414             (*next).destroy(capacity);
415         }
416     }
417
418     // Returns a pointer to the first allocated object.
419     #[inline]
420     fn start(&self) -> *const u8 {
421         let this: *const TypedArenaChunk<T> = self;
422         unsafe {
423             mem::transmute(round_up(this.offset(1) as uint,
424                                     mem::min_align_of::<T>()))
425         }
426     }
427
428     // Returns a pointer to the end of the allocated space.
429     #[inline]
430     fn end(&self) -> *const u8 {
431         unsafe {
432             let size = mem::size_of::<T>().checked_mul(&self.capacity).unwrap();
433             self.start().offset(size as int)
434         }
435     }
436 }
437
438 impl<T> TypedArena<T> {
439     /// Creates a new `TypedArena` with preallocated space for eight objects.
440     #[inline]
441     pub fn new() -> TypedArena<T> {
442         TypedArena::with_capacity(8)
443     }
444
445     /// Creates a new `TypedArena` with preallocated space for the given number of
446     /// objects.
447     #[inline]
448     pub fn with_capacity(capacity: uint) -> TypedArena<T> {
449         unsafe {
450             let chunk = TypedArenaChunk::<T>::new(ptr::null_mut(), capacity);
451             TypedArena {
452                 ptr: Cell::new((*chunk).start() as *const T),
453                 end: Cell::new((*chunk).end() as *const T),
454                 first: RefCell::new(chunk),
455             }
456         }
457     }
458
459     /// Allocates an object in the `TypedArena`, returning a reference to it.
460     #[inline]
461     pub fn alloc(&self, object: T) -> &mut T {
462         if self.ptr == self.end {
463             self.grow()
464         }
465
466         let ptr: &mut T = unsafe {
467             let ptr: &mut T = mem::transmute(self.ptr);
468             ptr::write(ptr, object);
469             self.ptr.set(self.ptr.get().offset(1));
470             ptr
471         };
472
473         ptr
474     }
475
476     /// Grows the arena.
477     #[inline(never)]
478     fn grow(&self) {
479         unsafe {
480             let chunk = *self.first.borrow_mut();
481             let new_capacity = (*chunk).capacity.checked_mul(&2).unwrap();
482             let chunk = TypedArenaChunk::<T>::new(chunk, new_capacity);
483             self.ptr.set((*chunk).start() as *const T);
484             self.end.set((*chunk).end() as *const T);
485             *self.first.borrow_mut() = chunk
486         }
487     }
488 }
489
490 #[unsafe_destructor]
491 impl<T> Drop for TypedArena<T> {
492     fn drop(&mut self) {
493         unsafe {
494             // Determine how much was filled.
495             let start = self.first.borrow().as_ref().unwrap().start() as uint;
496             let end = self.ptr.get() as uint;
497             let diff = (end - start) / mem::size_of::<T>();
498
499             // Pass that to the `destroy` method.
500             (**self.first.borrow_mut()).destroy(diff)
501         }
502     }
503 }
504
505 #[cfg(test)]
506 mod tests {
507     extern crate test;
508     use self::test::Bencher;
509     use super::{Arena, TypedArena};
510
511     #[allow(dead_code)]
512     struct Point {
513         x: int,
514         y: int,
515         z: int,
516     }
517
518     #[test]
519     pub fn test_copy() {
520         let arena = TypedArena::new();
521         for _ in range(0u, 100000) {
522             arena.alloc(Point {
523                 x: 1,
524                 y: 2,
525                 z: 3,
526             });
527         }
528     }
529
530     #[bench]
531     pub fn bench_copy(b: &mut Bencher) {
532         let arena = TypedArena::new();
533         b.iter(|| {
534             arena.alloc(Point {
535                 x: 1,
536                 y: 2,
537                 z: 3,
538             })
539         })
540     }
541
542     #[bench]
543     pub fn bench_copy_nonarena(b: &mut Bencher) {
544         b.iter(|| {
545             box Point {
546                 x: 1,
547                 y: 2,
548                 z: 3,
549             }
550         })
551     }
552
553     #[bench]
554     pub fn bench_copy_old_arena(b: &mut Bencher) {
555         let arena = Arena::new();
556         b.iter(|| {
557             arena.alloc(|| {
558                 Point {
559                     x: 1,
560                     y: 2,
561                     z: 3,
562                 }
563             })
564         })
565     }
566
567     #[allow(dead_code)]
568     struct Noncopy {
569         string: String,
570         array: Vec<int>,
571     }
572
573     #[test]
574     pub fn test_noncopy() {
575         let arena = TypedArena::new();
576         for _ in range(0u, 100000) {
577             arena.alloc(Noncopy {
578                 string: "hello world".to_string(),
579                 array: vec!( 1, 2, 3, 4, 5 ),
580             });
581         }
582     }
583
584     #[bench]
585     pub fn bench_noncopy(b: &mut Bencher) {
586         let arena = TypedArena::new();
587         b.iter(|| {
588             arena.alloc(Noncopy {
589                 string: "hello world".to_string(),
590                 array: vec!( 1, 2, 3, 4, 5 ),
591             })
592         })
593     }
594
595     #[bench]
596     pub fn bench_noncopy_nonarena(b: &mut Bencher) {
597         b.iter(|| {
598             box Noncopy {
599                 string: "hello world".to_string(),
600                 array: vec!( 1, 2, 3, 4, 5 ),
601             }
602         })
603     }
604
605     #[bench]
606     pub fn bench_noncopy_old_arena(b: &mut Bencher) {
607         let arena = Arena::new();
608         b.iter(|| {
609             arena.alloc(|| Noncopy {
610                 string: "hello world".to_string(),
611                 array: vec!( 1, 2, 3, 4, 5 ),
612             })
613         })
614     }
615 }