]> git.lizzy.rs Git - rust.git/blob - src/libarena/lib.rs
rollup merge of #17292 : thestinger/tasks
[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/master/")]
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 failures 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 failure 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) -> &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 &*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) -> &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 &*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) -> &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, fail while allocating
341     arena.alloc::<Rc<int>>(|| {
342         // Now fail.
343         fail!();
344     });
345 }
346
347 /// A faster arena that can hold objects of only one type.
348 ///
349 /// Safety note: Modifying objects in the arena that have already had their
350 /// `drop` destructors run can cause leaks, because the destructor will not
351 /// run again for these objects.
352 pub struct TypedArena<T> {
353     /// A pointer to the next object to be allocated.
354     ptr: Cell<*const T>,
355
356     /// A pointer to the end of the allocated area. When this pointer is
357     /// reached, a new chunk is allocated.
358     end: Cell<*const T>,
359
360     /// A pointer to the first arena segment.
361     first: RefCell<*mut TypedArenaChunk<T>>,
362 }
363
364 struct TypedArenaChunk<T> {
365     /// Pointer to the next arena segment.
366     next: *mut TypedArenaChunk<T>,
367
368     /// The number of elements that this chunk can hold.
369     capacity: uint,
370
371     // Objects follow here, suitably aligned.
372 }
373
374 fn calculate_size<T>(capacity: uint) -> uint {
375     let mut size = mem::size_of::<TypedArenaChunk<T>>();
376     size = round_up(size, mem::min_align_of::<T>());
377     let elem_size = mem::size_of::<T>();
378     let elems_size = elem_size.checked_mul(&capacity).unwrap();
379     size = size.checked_add(&elems_size).unwrap();
380     size
381 }
382
383 impl<T> TypedArenaChunk<T> {
384     #[inline]
385     unsafe fn new(next: *mut TypedArenaChunk<T>, capacity: uint)
386            -> *mut TypedArenaChunk<T> {
387         let size = calculate_size::<T>(capacity);
388         let chunk = allocate(size, mem::min_align_of::<TypedArenaChunk<T>>())
389                     as *mut TypedArenaChunk<T>;
390         (*chunk).next = next;
391         (*chunk).capacity = capacity;
392         chunk
393     }
394
395     /// Destroys this arena chunk. If the type descriptor is supplied, the
396     /// drop glue is called; otherwise, drop glue is not called.
397     #[inline]
398     unsafe fn destroy(&mut self, len: uint) {
399         // Destroy all the allocated objects.
400         if intrinsics::needs_drop::<T>() {
401             let mut start = self.start();
402             for _ in range(0, len) {
403                 ptr::read(start as *const T); // run the destructor on the pointer
404                 start = start.offset(mem::size_of::<T>() as int)
405             }
406         }
407
408         // Destroy the next chunk.
409         let next = self.next;
410         let size = calculate_size::<T>(self.capacity);
411         deallocate(self as *mut TypedArenaChunk<T> as *mut u8, size,
412                    mem::min_align_of::<TypedArenaChunk<T>>());
413         if next.is_not_null() {
414             let capacity = (*next).capacity;
415             (*next).destroy(capacity);
416         }
417     }
418
419     // Returns a pointer to the first allocated object.
420     #[inline]
421     fn start(&self) -> *const u8 {
422         let this: *const TypedArenaChunk<T> = self;
423         unsafe {
424             mem::transmute(round_up(this.offset(1) as uint,
425                                     mem::min_align_of::<T>()))
426         }
427     }
428
429     // Returns a pointer to the end of the allocated space.
430     #[inline]
431     fn end(&self) -> *const u8 {
432         unsafe {
433             let size = mem::size_of::<T>().checked_mul(&self.capacity).unwrap();
434             self.start().offset(size as int)
435         }
436     }
437 }
438
439 impl<T> TypedArena<T> {
440     /// Creates a new `TypedArena` with preallocated space for eight objects.
441     #[inline]
442     pub fn new() -> TypedArena<T> {
443         TypedArena::with_capacity(8)
444     }
445
446     /// Creates a new `TypedArena` with preallocated space for the given number of
447     /// objects.
448     #[inline]
449     pub fn with_capacity(capacity: uint) -> TypedArena<T> {
450         unsafe {
451             let chunk = TypedArenaChunk::<T>::new(ptr::null_mut(), capacity);
452             TypedArena {
453                 ptr: Cell::new((*chunk).start() as *const T),
454                 end: Cell::new((*chunk).end() as *const T),
455                 first: RefCell::new(chunk),
456             }
457         }
458     }
459
460     /// Allocates an object in the `TypedArena`, returning a reference to it.
461     #[inline]
462     pub fn alloc(&self, object: T) -> &T {
463         if self.ptr == self.end {
464             self.grow()
465         }
466
467         let ptr: &T = unsafe {
468             let ptr: &mut T = mem::transmute(self.ptr);
469             ptr::write(ptr, object);
470             self.ptr.set(self.ptr.get().offset(1));
471             ptr
472         };
473
474         ptr
475     }
476
477     /// Grows the arena.
478     #[inline(never)]
479     fn grow(&self) {
480         unsafe {
481             let chunk = *self.first.borrow_mut();
482             let new_capacity = (*chunk).capacity.checked_mul(&2).unwrap();
483             let chunk = TypedArenaChunk::<T>::new(chunk, new_capacity);
484             self.ptr.set((*chunk).start() as *const T);
485             self.end.set((*chunk).end() as *const T);
486             *self.first.borrow_mut() = chunk
487         }
488     }
489 }
490
491 #[unsafe_destructor]
492 impl<T> Drop for TypedArena<T> {
493     fn drop(&mut self) {
494         unsafe {
495             // Determine how much was filled.
496             let start = self.first.borrow().as_ref().unwrap().start() as uint;
497             let end = self.ptr.get() as uint;
498             let diff = (end - start) / mem::size_of::<T>();
499
500             // Pass that to the `destroy` method.
501             (**self.first.borrow_mut()).destroy(diff)
502         }
503     }
504 }
505
506 #[cfg(test)]
507 mod tests {
508     extern crate test;
509     use self::test::Bencher;
510     use super::{Arena, TypedArena};
511
512     #[allow(dead_code)]
513     struct Point {
514         x: int,
515         y: int,
516         z: int,
517     }
518
519     #[test]
520     pub fn test_copy() {
521         let arena = TypedArena::new();
522         for _ in range(0u, 100000) {
523             arena.alloc(Point {
524                 x: 1,
525                 y: 2,
526                 z: 3,
527             });
528         }
529     }
530
531     #[bench]
532     pub fn bench_copy(b: &mut Bencher) {
533         let arena = TypedArena::new();
534         b.iter(|| {
535             arena.alloc(Point {
536                 x: 1,
537                 y: 2,
538                 z: 3,
539             })
540         })
541     }
542
543     #[bench]
544     pub fn bench_copy_nonarena(b: &mut Bencher) {
545         b.iter(|| {
546             box Point {
547                 x: 1,
548                 y: 2,
549                 z: 3,
550             }
551         })
552     }
553
554     #[bench]
555     pub fn bench_copy_old_arena(b: &mut Bencher) {
556         let arena = Arena::new();
557         b.iter(|| {
558             arena.alloc(|| {
559                 Point {
560                     x: 1,
561                     y: 2,
562                     z: 3,
563                 }
564             })
565         })
566     }
567
568     #[allow(dead_code)]
569     struct Noncopy {
570         string: String,
571         array: Vec<int>,
572     }
573
574     #[test]
575     pub fn test_noncopy() {
576         let arena = TypedArena::new();
577         for _ in range(0u, 100000) {
578             arena.alloc(Noncopy {
579                 string: "hello world".to_string(),
580                 array: vec!( 1, 2, 3, 4, 5 ),
581             });
582         }
583     }
584
585     #[bench]
586     pub fn bench_noncopy(b: &mut Bencher) {
587         let arena = TypedArena::new();
588         b.iter(|| {
589             arena.alloc(Noncopy {
590                 string: "hello world".to_string(),
591                 array: vec!( 1, 2, 3, 4, 5 ),
592             })
593         })
594     }
595
596     #[bench]
597     pub fn bench_noncopy_nonarena(b: &mut Bencher) {
598         b.iter(|| {
599             box Noncopy {
600                 string: "hello world".to_string(),
601                 array: vec!( 1, 2, 3, 4, 5 ),
602             }
603         })
604     }
605
606     #[bench]
607     pub fn bench_noncopy_old_arena(b: &mut Bencher) {
608         let arena = Arena::new();
609         b.iter(|| {
610             arena.alloc(|| Noncopy {
611                 string: "hello world".to_string(),
612                 array: vec!( 1, 2, 3, 4, 5 ),
613             })
614         })
615     }
616 }