]> git.lizzy.rs Git - rust.git/blob - src/libarena/lib.rs
test: Make manual changes to deal with the fallout from removal of
[rust.git] / src / libarena / lib.rs
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.
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 #[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
28
29 extern crate collections;
30
31 use collections::list::{List, Cons, Nil};
32
33 use std::cast::{transmute, transmute_mut, transmute_mut_region};
34 use std::cast;
35 use std::cell::{Cell, RefCell};
36 use std::mem;
37 use std::ptr::read;
38 use std::cmp;
39 use std::num;
40 use std::kinds::marker;
41 use std::rc::Rc;
42 use std::rt::global_heap;
43 use std::intrinsics::{TyDesc, get_tydesc};
44 use std::intrinsics;
45
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)]
50 struct Chunk {
51     data: Rc<RefCell<Vec<u8> >>,
52     fill: Cell<uint>,
53     is_pod: Cell<bool>,
54 }
55 impl Chunk {
56     fn capacity(&self) -> uint {
57         self.data.deref().borrow().get().capacity()
58     }
59
60     unsafe fn as_ptr(&self) -> *u8 {
61         self.data.deref().borrow().get().as_ptr()
62     }
63 }
64
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.
81
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.
86 pub struct Arena {
87     // The head is separated out from the list as a unbenchmarked
88     // microoptimization, to avoid needing to case on the list to
89     // access the head.
90     priv head: Chunk,
91     priv pod_head: Chunk,
92     priv chunks: RefCell<@List<Chunk>>,
93     priv no_freeze: marker::NoFreeze,
94 }
95
96 impl Arena {
97     pub fn new() -> Arena {
98         Arena::new_with_size(32u)
99     }
100
101     pub fn new_with_size(initial_size: uint) -> Arena {
102         Arena {
103             head: chunk(initial_size, false),
104             pod_head: chunk(initial_size, true),
105             chunks: RefCell::new(@Nil),
106             no_freeze: marker::NoFreeze,
107         }
108     }
109 }
110
111 fn chunk(size: uint, is_pod: bool) -> Chunk {
112     Chunk {
113         data: Rc::new(RefCell::new(Vec::with_capacity(size))),
114         fill: Cell::new(0u),
115         is_pod: Cell::new(is_pod),
116     }
117 }
118
119 #[unsafe_destructor]
120 impl Drop for Arena {
121     fn drop(&mut self) {
122         unsafe {
123             destroy_chunk(&self.head);
124             for chunk in self.chunks.get().iter() {
125                 if !chunk.is_pod.get() {
126                     destroy_chunk(chunk);
127                 }
128             }
129         }
130     }
131 }
132
133 #[inline]
134 fn round_up(base: uint, align: uint) -> uint {
135     (base.checked_add(&(align - 1))).unwrap() & !(&(align - 1))
136 }
137
138 // Walk down a chunk, running the destructors for any objects stored
139 // in it.
140 unsafe fn destroy_chunk(chunk: &Chunk) {
141     let mut idx = 0;
142     let buf = chunk.as_ptr();
143     let fill = chunk.fill.get();
144
145     while idx < fill {
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);
149
150         let after_tydesc = idx + mem::size_of::<*TyDesc>();
151
152         let start = round_up(after_tydesc, align);
153
154         //debug!("freeing object: idx = {}, size = {}, align = {}, done = {}",
155         //       start, size, align, is_done);
156         if is_done {
157             ((*tydesc).drop_glue)(buf.offset(start as int) as *i8);
158         }
159
160         // Find where the next tydesc lives
161         idx = round_up(start + size, mem::pref_align_of::<*TyDesc>());
162     }
163 }
164
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.
169 #[inline]
170 fn bitpack_tydesc_ptr(p: *TyDesc, is_done: bool) -> uint {
171     p as uint | (is_done as uint)
172 }
173 #[inline]
174 fn un_bitpack_tydesc_ptr(p: uint) -> (*TyDesc, bool) {
175     ((p & !1) as *TyDesc, p & 1 == 1)
176 }
177
178 impl Arena {
179     fn chunk_size(&self) -> uint {
180         self.pod_head.capacity()
181     }
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()));
187         self.pod_head =
188             chunk(num::next_power_of_two(new_min_chunk_size + 1u), true);
189
190         return self.alloc_pod_inner(n_bytes, align);
191     }
192
193     #[inline]
194     fn alloc_pod_inner(&mut self, n_bytes: uint, align: uint) -> *u8 {
195         unsafe {
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);
201             }
202             this.pod_head.fill.set(end);
203
204             //debug!("idx = {}, size = {}, align = {}, fill = {}",
205             //       start, n_bytes, align, head.fill.get());
206
207             this.pod_head.as_ptr().offset(start as int)
208         }
209     }
210
211     #[inline]
212     fn alloc_pod<'a, T>(&'a mut self, op: || -> T) -> &'a T {
213         unsafe {
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);
218         }
219     }
220
221     // Functions for the non-POD part of the arena
222     fn alloc_nonpod_grow(&mut self, n_bytes: uint, align: uint)
223                          -> (*u8, *u8) {
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()));
227         self.head =
228             chunk(num::next_power_of_two(new_min_chunk_size + 1u), false);
229
230         return self.alloc_nonpod_inner(n_bytes, align);
231     }
232
233     #[inline]
234     fn alloc_nonpod_inner(&mut self, n_bytes: uint, align: uint)
235                           -> (*u8, *u8) {
236         unsafe {
237             let start;
238             let end;
239             let tydesc_start;
240             let after_tydesc;
241
242             {
243                 let head = transmute_mut_region(&mut self.head);
244
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;
249             }
250
251             if end > self.head.capacity() {
252                 return self.alloc_nonpod_grow(n_bytes, align);
253             }
254
255             let head = transmute_mut_region(&mut self.head);
256             head.fill.set(round_up(end, mem::pref_align_of::<*TyDesc>()));
257
258             //debug!("idx = {}, size = {}, align = {}, fill = {}",
259             //       start, n_bytes, align, head.fill);
260
261             let buf = self.head.as_ptr();
262             return (buf.offset(tydesc_start as int), buf.offset(start as int));
263         }
264     }
265
266     #[inline]
267     fn alloc_nonpod<'a, T>(&'a mut self, op: || -> T) -> &'a T {
268         unsafe {
269             let tydesc = get_tydesc::<T>();
270             let (ty_ptr, ptr) =
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);
282
283             return transmute(ptr);
284         }
285     }
286
287     // The external interface
288     #[inline]
289     pub fn alloc<'a, T>(&'a self, op: || -> T) -> &'a T {
290         unsafe {
291             // FIXME: Borrow check
292             let this = transmute_mut(self);
293             if intrinsics::needs_drop::<T>() {
294                 this.alloc_nonpod(op)
295             } else {
296                 this.alloc_pod(op)
297             }
298         }
299     }
300 }
301
302 #[test]
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
307         // doesn't leak.
308         arena.alloc(|| @i);
309         // Allocate something with funny size and alignment, to keep
310         // things interesting.
311         arena.alloc(|| [0u8, 1u8, 2u8]);
312     }
313 }
314
315 #[test]
316 #[should_fail]
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
322         // doesn't leak.
323         arena.alloc(|| { @i });
324         // Allocate something with funny size and alignment, to keep
325         // things interesting.
326         arena.alloc(|| { [0u8, 1u8, 2u8] });
327     }
328     // Now, fail while allocating
329     arena.alloc::<@int>(|| {
330         // Now fail.
331         fail!();
332     });
333 }
334
335 /// An arena that can hold objects of only one type.
336 ///
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.
342     priv ptr: *T,
343
344     /// A pointer to the end of the allocated area. When this pointer is
345     /// reached, a new chunk is allocated.
346     priv end: *T,
347
348     /// A pointer to the first arena segment.
349     priv first: Option<~TypedArenaChunk<T>>,
350 }
351
352 struct TypedArenaChunk<T> {
353     /// Pointer to the next arena segment.
354     next: Option<~TypedArenaChunk<T>>,
355
356     /// The number of elements that this chunk can hold.
357     capacity: uint,
358
359     // Objects follow here, suitably aligned.
360 }
361
362 impl<T> TypedArenaChunk<T> {
363     #[inline]
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();
370
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);
375             chunk
376         };
377
378         chunk.capacity = capacity;
379         chunk
380     }
381
382     /// Destroys this arena chunk. If the type descriptor is supplied, the
383     /// drop glue is called; otherwise, drop glue is not called.
384     #[inline]
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)
392             }
393         }
394
395         // Destroy the next chunk.
396         let next_opt = mem::replace(&mut self.next, None);
397         match next_opt {
398             None => {}
399             Some(mut next) => {
400                 // We assume that the next chunk is completely filled.
401                 next.destroy(next.capacity)
402             }
403         }
404     }
405
406     // Returns a pointer to the first allocated object.
407     #[inline]
408     fn start(&self) -> *u8 {
409         let this: *TypedArenaChunk<T> = self;
410         unsafe {
411             cast::transmute(round_up(this.offset(1) as uint, mem::min_align_of::<T>()))
412         }
413     }
414
415     // Returns a pointer to the end of the allocated space.
416     #[inline]
417     fn end(&self) -> *u8 {
418         unsafe {
419             let size = mem::size_of::<T>().checked_mul(&self.capacity).unwrap();
420             self.start().offset(size as int)
421         }
422     }
423 }
424
425 impl<T> TypedArena<T> {
426     /// Creates a new arena with preallocated space for 8 objects.
427     #[inline]
428     pub fn new() -> TypedArena<T> {
429         TypedArena::with_capacity(8)
430     }
431
432     /// Creates a new arena with preallocated space for the given number of
433     /// objects.
434     #[inline]
435     pub fn with_capacity(capacity: uint) -> TypedArena<T> {
436         let chunk = TypedArenaChunk::<T>::new(None, capacity);
437         TypedArena {
438             ptr: chunk.start() as *T,
439             end: chunk.end() as *T,
440             first: Some(chunk),
441         }
442     }
443
444     /// Allocates an object into this arena.
445     #[inline]
446     pub fn alloc<'a>(&'a self, object: T) -> &'a T {
447         unsafe {
448             let this = cast::transmute_mut(self);
449             if this.ptr == this.end {
450                 this.grow()
451             }
452
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;
457             ptr
458         }
459     }
460
461     /// Grows the arena.
462     #[inline(never)]
463     fn grow(&mut self) {
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)
470     }
471 }
472
473 #[unsafe_destructor]
474 impl<T> Drop for TypedArena<T> {
475     fn drop(&mut self) {
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>();
480
481         // Pass that to the `destroy` method.
482         unsafe {
483             self.first.get_mut_ref().destroy(diff)
484         }
485     }
486 }
487
488 #[cfg(test)]
489 mod tests {
490     extern crate test;
491
492     use std::vec_ng::Vec;
493
494     use self::test::BenchHarness;
495     use super::{Arena, TypedArena};
496
497     struct Point {
498         x: int,
499         y: int,
500         z: int,
501     }
502
503     #[test]
504     pub fn test_pod() {
505         let arena = TypedArena::new();
506         for _ in range(0, 100000) {
507             arena.alloc(Point {
508                 x: 1,
509                 y: 2,
510                 z: 3,
511             });
512         }
513     }
514
515     #[bench]
516     pub fn bench_pod(bh: &mut BenchHarness) {
517         let arena = TypedArena::new();
518         bh.iter(|| {
519             arena.alloc(Point {
520                 x: 1,
521                 y: 2,
522                 z: 3,
523             })
524         })
525     }
526
527     #[bench]
528     pub fn bench_pod_nonarena(bh: &mut BenchHarness) {
529         bh.iter(|| {
530             ~Point {
531                 x: 1,
532                 y: 2,
533                 z: 3,
534             }
535         })
536     }
537
538     #[bench]
539     pub fn bench_pod_old_arena(bh: &mut BenchHarness) {
540         let arena = Arena::new();
541         bh.iter(|| {
542             arena.alloc(|| {
543                 Point {
544                     x: 1,
545                     y: 2,
546                     z: 3,
547                 }
548             })
549         })
550     }
551
552     struct Nonpod {
553         string: ~str,
554         array: Vec<int> ,
555     }
556
557     #[test]
558     pub fn test_nonpod() {
559         let arena = TypedArena::new();
560         for _ in range(0, 100000) {
561             arena.alloc(Nonpod {
562                 string: ~"hello world",
563                 array: vec!( 1, 2, 3, 4, 5 ),
564             });
565         }
566     }
567
568     #[bench]
569     pub fn bench_nonpod(bh: &mut BenchHarness) {
570         let arena = TypedArena::new();
571         bh.iter(|| {
572             arena.alloc(Nonpod {
573                 string: ~"hello world",
574                 array: vec!( 1, 2, 3, 4, 5 ),
575             })
576         })
577     }
578
579     #[bench]
580     pub fn bench_nonpod_nonarena(bh: &mut BenchHarness) {
581         bh.iter(|| {
582             ~Nonpod {
583                 string: ~"hello world",
584                 array: vec!( 1, 2, 3, 4, 5 ),
585             }
586         })
587     }
588
589     #[bench]
590     pub fn bench_nonpod_old_arena(bh: &mut BenchHarness) {
591         let arena = Arena::new();
592         bh.iter(|| {
593             arena.alloc(|| Nonpod {
594                 string: ~"hello world",
595                 array: vec!( 1, 2, 3, 4, 5 ),
596             })
597         })
598     }
599 }