]> git.lizzy.rs Git - rust.git/blob - src/libarena/lib.rs
aacf9936cce3681a544c9b35092220589d7236dd
[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_id = "arena#0.11.0-pre"]
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/")]
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;
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 impl Chunk {
54     fn capacity(&self) -> uint {
55         self.data.borrow().capacity()
56     }
57
58     unsafe fn as_ptr(&self) -> *u8 {
59         self.data.borrow().as_ptr()
60     }
61 }
62
63 /// A slower reflection-based arena that can allocate objects of any type.
64 ///
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.
78 ///
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.
83 pub struct Arena {
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
86     // head.
87     head: RefCell<Chunk>,
88     copy_head: RefCell<Chunk>,
89     chunks: RefCell<Vec<Chunk>>,
90 }
91
92 impl Arena {
93     /// Allocate a new Arena with 32 bytes preallocated.
94     pub fn new() -> Arena {
95         Arena::new_with_size(32u)
96     }
97
98     /// Allocate a new Arena with `initial_size` bytes preallocated.
99     pub fn new_with_size(initial_size: uint) -> Arena {
100         Arena {
101             head: RefCell::new(chunk(initial_size, false)),
102             copy_head: RefCell::new(chunk(initial_size, true)),
103             chunks: RefCell::new(Vec::new()),
104         }
105     }
106 }
107
108 fn chunk(size: uint, is_copy: bool) -> Chunk {
109     Chunk {
110         data: Rc::new(RefCell::new(Vec::with_capacity(size))),
111         fill: Cell::new(0u),
112         is_copy: Cell::new(is_copy),
113     }
114 }
115
116 #[unsafe_destructor]
117 impl Drop for Arena {
118     fn drop(&mut self) {
119         unsafe {
120             destroy_chunk(&*self.head.borrow());
121             for chunk in self.chunks.borrow().iter() {
122                 if !chunk.is_copy.get() {
123                     destroy_chunk(chunk);
124                 }
125             }
126         }
127     }
128 }
129
130 #[inline]
131 fn round_up(base: uint, align: uint) -> uint {
132     (base.checked_add(&(align - 1))).unwrap() & !(&(align - 1))
133 }
134
135 // Walk down a chunk, running the destructors for any objects stored
136 // in it.
137 unsafe fn destroy_chunk(chunk: &Chunk) {
138     let mut idx = 0;
139     let buf = chunk.as_ptr();
140     let fill = chunk.fill.get();
141
142     while idx < fill {
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);
146
147         let after_tydesc = idx + mem::size_of::<*TyDesc>();
148
149         let start = round_up(after_tydesc, align);
150
151         //debug!("freeing object: idx = {}, size = {}, align = {}, done = {}",
152         //       start, size, align, is_done);
153         if is_done {
154             ((*tydesc).drop_glue)(buf.offset(start as int) as *i8);
155         }
156
157         // Find where the next tydesc lives
158         idx = round_up(start + size, mem::align_of::<*TyDesc>());
159     }
160 }
161
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.
166 #[inline]
167 fn bitpack_tydesc_ptr(p: *TyDesc, is_done: bool) -> uint {
168     p as uint | (is_done as uint)
169 }
170 #[inline]
171 fn un_bitpack_tydesc_ptr(p: uint) -> (*TyDesc, bool) {
172     ((p & !1) as *TyDesc, p & 1 == 1)
173 }
174
175 impl Arena {
176     fn chunk_size(&self) -> uint {
177         self.copy_head.borrow().capacity()
178     }
179
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());
185
186         *self.copy_head.borrow_mut() =
187             chunk(num::next_power_of_two(new_min_chunk_size + 1u), true);
188
189         return self.alloc_copy_inner(n_bytes, align);
190     }
191
192     #[inline]
193     fn alloc_copy_inner(&self, n_bytes: uint, align: uint) -> *u8 {
194         let start = round_up(self.copy_head.borrow().fill.get(), align);
195
196         let end = start + n_bytes;
197         if end > self.chunk_size() {
198             return self.alloc_copy_grow(n_bytes, align);
199         }
200
201         let copy_head = self.copy_head.borrow();
202         copy_head.fill.set(end);
203
204         unsafe {
205             copy_head.as_ptr().offset(start as int)
206         }
207     }
208
209     #[inline]
210     fn alloc_copy<'a, T>(&'a self, op: || -> T) -> &'a T {
211         unsafe {
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());
216             return &*ptr;
217         }
218     }
219
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());
225
226         *self.head.borrow_mut() =
227             chunk(num::next_power_of_two(new_min_chunk_size + 1u), false);
228
229         return self.alloc_noncopy_inner(n_bytes, align);
230     }
231
232     #[inline]
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();
239
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;
244
245             (start, end, tydesc_start, head.capacity())
246         };
247
248         if end > head_capacity {
249             return self.alloc_noncopy_grow(n_bytes, align);
250         }
251
252         let head = self.head.borrow();
253         head.fill.set(round_up(end, mem::align_of::<*TyDesc>()));
254
255         unsafe {
256             let buf = head.as_ptr();
257             return (buf.offset(tydesc_start as int), buf.offset(start as int));
258         }
259     }
260
261     #[inline]
262     fn alloc_noncopy<'a, T>(&'a self, op: || -> T) -> &'a T {
263         unsafe {
264             let tydesc = get_tydesc::<T>();
265             let (ty_ptr, ptr) =
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);
278
279             return &*ptr;
280         }
281     }
282
283     /// Allocate a new item in the arena, using `op` to initialize the value
284     /// and returning a reference to it.
285     #[inline]
286     pub fn alloc<'a, T>(&'a self, op: || -> T) -> &'a T {
287         unsafe {
288             if intrinsics::needs_drop::<T>() {
289                 self.alloc_noncopy(op)
290             } else {
291                 self.alloc_copy(op)
292             }
293         }
294     }
295 }
296
297 #[test]
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
302         // doesn't leak.
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]);
307     }
308 }
309
310 #[test]
311 fn test_arena_alloc_nested() {
312     struct Inner { value: uint }
313     struct Outer<'a> { inner: &'a Inner }
314
315     let arena = Arena::new();
316
317     let result = arena.alloc(|| Outer {
318         inner: arena.alloc(|| Inner { value: 10 })
319     });
320
321     assert_eq!(result.inner.value, 10);
322 }
323
324 #[test]
325 #[should_fail]
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
331         // doesn't leak.
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] });
336     }
337     // Now, fail while allocating
338     arena.alloc::<Rc<int>>(|| {
339         // Now fail.
340         fail!();
341     });
342 }
343
344 /// A faster arena that can hold objects of only one type.
345 ///
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.
351     ptr: Cell<*T>,
352
353     /// A pointer to the end of the allocated area. When this pointer is
354     /// reached, a new chunk is allocated.
355     end: Cell<*T>,
356
357     /// A pointer to the first arena segment.
358     first: RefCell<TypedArenaChunkRef<T>>,
359 }
360 type TypedArenaChunkRef<T> = Option<Box<TypedArenaChunk<T>>>;
361
362 struct TypedArenaChunk<T> {
363     /// Pointer to the next arena segment.
364     next: TypedArenaChunkRef<T>,
365
366     /// The number of elements that this chunk can hold.
367     capacity: uint,
368
369     // Objects follow here, suitably aligned.
370 }
371
372 impl<T> TypedArenaChunk<T> {
373     #[inline]
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();
381
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);
386             chunk
387         };
388
389         chunk.capacity = capacity;
390         chunk
391     }
392
393     /// Destroys this arena chunk. If the type descriptor is supplied, the
394     /// drop glue is called; otherwise, drop glue is not called.
395     #[inline]
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)
403             }
404         }
405
406         // Destroy the next chunk.
407         let next_opt = mem::replace(&mut self.next, None);
408         match next_opt {
409             None => {}
410             Some(mut next) => {
411                 // We assume that the next chunk is completely filled.
412                 let capacity = next.capacity;
413                 next.destroy(capacity)
414             }
415         }
416     }
417
418     // Returns a pointer to the first allocated object.
419     #[inline]
420     fn start(&self) -> *u8 {
421         let this: *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) -> *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 8 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         let chunk = TypedArenaChunk::<T>::new(None, capacity);
450         TypedArena {
451             ptr: Cell::new(chunk.start() as *T),
452             end: Cell::new(chunk.end() as *T),
453             first: RefCell::new(Some(chunk)),
454         }
455     }
456
457     /// Allocates an object in the TypedArena, returning a reference to it.
458     #[inline]
459     pub fn alloc<'a>(&'a self, object: T) -> &'a T {
460         if self.ptr == self.end {
461             self.grow()
462         }
463
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));
468             ptr
469         };
470
471         ptr
472     }
473
474     /// Grows the arena.
475     #[inline(never)]
476     fn grow(&self) {
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)
483     }
484 }
485
486 #[unsafe_destructor]
487 impl<T> Drop for TypedArena<T> {
488     fn drop(&mut self) {
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>();
493
494         // Pass that to the `destroy` method.
495         unsafe {
496             self.first.borrow_mut().get_mut_ref().destroy(diff)
497         }
498     }
499 }
500
501 #[cfg(test)]
502 mod tests {
503     extern crate test;
504     use self::test::Bencher;
505     use super::{Arena, TypedArena};
506
507     struct Point {
508         x: int,
509         y: int,
510         z: int,
511     }
512
513     #[test]
514     pub fn test_copy() {
515         let arena = TypedArena::new();
516         for _ in range(0u, 100000) {
517             arena.alloc(Point {
518                 x: 1,
519                 y: 2,
520                 z: 3,
521             });
522         }
523     }
524
525     #[bench]
526     pub fn bench_copy(b: &mut Bencher) {
527         let arena = TypedArena::new();
528         b.iter(|| {
529             arena.alloc(Point {
530                 x: 1,
531                 y: 2,
532                 z: 3,
533             })
534         })
535     }
536
537     #[bench]
538     pub fn bench_copy_nonarena(b: &mut Bencher) {
539         b.iter(|| {
540             box Point {
541                 x: 1,
542                 y: 2,
543                 z: 3,
544             }
545         })
546     }
547
548     #[bench]
549     pub fn bench_copy_old_arena(b: &mut Bencher) {
550         let arena = Arena::new();
551         b.iter(|| {
552             arena.alloc(|| {
553                 Point {
554                     x: 1,
555                     y: 2,
556                     z: 3,
557                 }
558             })
559         })
560     }
561
562     struct Noncopy {
563         string: String,
564         array: Vec<int> ,
565     }
566
567     #[test]
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 ),
574             });
575         }
576     }
577
578     #[bench]
579     pub fn bench_noncopy(b: &mut Bencher) {
580         let arena = TypedArena::new();
581         b.iter(|| {
582             arena.alloc(Noncopy {
583                 string: "hello world".to_string(),
584                 array: vec!( 1, 2, 3, 4, 5 ),
585             })
586         })
587     }
588
589     #[bench]
590     pub fn bench_noncopy_nonarena(b: &mut Bencher) {
591         b.iter(|| {
592             box Noncopy {
593                 string: "hello world".to_string(),
594                 array: vec!( 1, 2, 3, 4, 5 ),
595             }
596         })
597     }
598
599     #[bench]
600     pub fn bench_noncopy_old_arena(b: &mut Bencher) {
601         let arena = Arena::new();
602         b.iter(|| {
603             arena.alloc(|| Noncopy {
604                 string: "hello world".to_string(),
605                 array: vec!( 1, 2, 3, 4, 5 ),
606             })
607         })
608     }
609 }