]> git.lizzy.rs Git - rust.git/blob - src/libarena/lib.rs
Move tests around
[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 #![unstable(feature = "rustc_private", issue = "27812")]
24 #![crate_type = "rlib"]
25 #![crate_type = "dylib"]
26 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
27        html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
28        html_root_url = "https://doc.rust-lang.org/nightly/",
29        test(no_crate_inject, attr(deny(warnings))))]
30
31 #![feature(alloc)]
32 #![feature(core_intrinsics)]
33 #![feature(drop_in_place)]
34 #![feature(heap_api)]
35 #![feature(raw)]
36 #![feature(heap_api)]
37 #![feature(staged_api)]
38 #![feature(dropck_parametricity)]
39 #![cfg_attr(test, feature(test))]
40
41 extern crate alloc;
42
43 use std::cell::{Cell, RefCell};
44 use std::cmp;
45 use std::intrinsics;
46 use std::marker::{PhantomData, Send};
47 use std::mem;
48 use std::ptr;
49 use std::slice;
50
51 use alloc::heap;
52 use alloc::raw_vec::RawVec;
53
54 struct Chunk {
55     data: RawVec<u8>,
56     /// Index of the first unused byte.
57     fill: Cell<usize>,
58     /// Indicates whether objects with destructors are stored in this chunk.
59     is_copy: Cell<bool>,
60 }
61
62 impl Chunk {
63     fn new(size: usize, is_copy: bool) -> Chunk {
64         Chunk {
65             data: RawVec::with_capacity(size),
66             fill: Cell::new(0),
67             is_copy: Cell::new(is_copy),
68         }
69     }
70
71     fn capacity(&self) -> usize {
72         self.data.cap()
73     }
74
75     unsafe fn as_ptr(&self) -> *const u8 {
76         self.data.ptr()
77     }
78
79     // Walk down a chunk, running the destructors for any objects stored
80     // in it.
81     unsafe fn destroy(&self) {
82         let mut idx = 0;
83         let buf = self.as_ptr();
84         let fill = self.fill.get();
85
86         while idx < fill {
87             let tydesc_data = buf.offset(idx as isize) as *const usize;
88             let (tydesc, is_done) = un_bitpack_tydesc_ptr(*tydesc_data);
89             let (size, align) = ((*tydesc).size, (*tydesc).align);
90
91             let after_tydesc = idx + mem::size_of::<*const TyDesc>();
92
93             let start = round_up(after_tydesc, align);
94
95             if is_done {
96                 ((*tydesc).drop_glue)(buf.offset(start as isize) as *const i8);
97             }
98
99             // Find where the next tydesc lives
100             idx = round_up(start + size, mem::align_of::<*const TyDesc>());
101         }
102     }
103 }
104
105 /// A slower reflection-based arena that can allocate objects of any type.
106 ///
107 /// This arena uses `RawVec<u8>` as a backing store to allocate objects from.
108 /// For each allocated object, the arena stores a pointer to the type descriptor
109 /// followed by the object (potentially with alignment padding after each
110 /// element). When the arena is destroyed, it iterates through all of its
111 /// chunks, and uses the tydesc information to trace through the objects,
112 /// calling the destructors on them. One subtle point that needs to be
113 /// addressed is how to handle panics while running the user provided
114 /// initializer function. It is important to not run the destructor on
115 /// uninitialized objects, but how to detect them is somewhat subtle. Since
116 /// `alloc()` can be invoked recursively, it is not sufficient to simply exclude
117 /// the most recent object. To solve this without requiring extra space, we
118 /// use the low order bit of the tydesc pointer to encode whether the object
119 /// it describes has been fully initialized.
120 ///
121 /// As an optimization, objects with destructors are stored in different chunks
122 /// than objects without destructors. This reduces overhead when initializing
123 /// plain-old-data (`Copy` types) and means we don't need to waste time running
124 /// their destructors.
125 pub struct Arena<'longer_than_self> {
126     // The heads are separated out from the list as a unbenchmarked
127     // microoptimization, to avoid needing to case on the list to access a head.
128     head: RefCell<Chunk>,
129     copy_head: RefCell<Chunk>,
130     chunks: RefCell<Vec<Chunk>>,
131     _marker: PhantomData<*mut &'longer_than_self ()>,
132 }
133
134 impl<'a> Arena<'a> {
135     /// Allocates a new Arena with 32 bytes preallocated.
136     pub fn new() -> Arena<'a> {
137         Arena::new_with_size(32)
138     }
139
140     /// Allocates a new Arena with `initial_size` bytes preallocated.
141     pub fn new_with_size(initial_size: usize) -> Arena<'a> {
142         Arena {
143             head: RefCell::new(Chunk::new(initial_size, false)),
144             copy_head: RefCell::new(Chunk::new(initial_size, true)),
145             chunks: RefCell::new(Vec::new()),
146             _marker: PhantomData,
147         }
148     }
149 }
150
151 impl<'longer_than_self> Drop for Arena<'longer_than_self> {
152     fn drop(&mut self) {
153         unsafe {
154             self.head.borrow().destroy();
155             for chunk in self.chunks.borrow().iter() {
156                 if !chunk.is_copy.get() {
157                     chunk.destroy();
158                 }
159             }
160         }
161     }
162 }
163
164 #[inline]
165 fn round_up(base: usize, align: usize) -> usize {
166     (base.checked_add(align - 1)).unwrap() & !(align - 1)
167 }
168
169 // We encode whether the object a tydesc describes has been
170 // initialized in the arena in the low bit of the tydesc pointer. This
171 // is necessary in order to properly do cleanup if a panic occurs
172 // during an initializer.
173 #[inline]
174 fn bitpack_tydesc_ptr(p: *const TyDesc, is_done: bool) -> usize {
175     p as usize | (is_done as usize)
176 }
177 #[inline]
178 fn un_bitpack_tydesc_ptr(p: usize) -> (*const TyDesc, bool) {
179     ((p & !1) as *const TyDesc, p & 1 == 1)
180 }
181
182 // HACK(eddyb) TyDesc replacement using a trait object vtable.
183 // This could be replaced in the future with a custom DST layout,
184 // or `&'static (drop_glue, size, align)` created by a `const fn`.
185 // Requirements:
186 // * rvalue promotion (issue #1056)
187 // * mem::{size_of, align_of} must be const fns
188 struct TyDesc {
189     drop_glue: fn(*const i8),
190     size: usize,
191     align: usize,
192 }
193
194 trait AllTypes {
195     fn dummy(&self) {}
196 }
197
198 impl<T: ?Sized> AllTypes for T {}
199
200 unsafe fn get_tydesc<T>() -> *const TyDesc {
201     use std::raw::TraitObject;
202
203     let ptr = &*(heap::EMPTY as *const T);
204
205     // Can use any trait that is implemented for all types.
206     let obj = mem::transmute::<&AllTypes, TraitObject>(ptr);
207     obj.vtable as *const TyDesc
208 }
209
210 impl<'longer_than_self> Arena<'longer_than_self> {
211     // Grows a given chunk and returns `false`, or replaces it with a bigger
212     // chunk and returns `true`.
213     // This method is shared by both parts of the arena.
214     #[cold]
215     fn alloc_grow(&self, head: &mut Chunk, used_cap: usize, n_bytes: usize) -> bool {
216         if head.data.reserve_in_place(used_cap, n_bytes) {
217             // In-place reallocation succeeded.
218             false
219         } else {
220             // Allocate a new chunk.
221             let new_min_chunk_size = cmp::max(n_bytes, head.capacity());
222             let new_chunk = Chunk::new((new_min_chunk_size + 1).next_power_of_two(), false);
223             let old_chunk = mem::replace(head, new_chunk);
224             if old_chunk.fill.get() != 0 {
225                 self.chunks.borrow_mut().push(old_chunk);
226             }
227             true
228         }
229     }
230
231     // Functions for the copyable part of the arena.
232
233     #[inline]
234     fn alloc_copy_inner(&self, n_bytes: usize, align: usize) -> *const u8 {
235         let mut copy_head = self.copy_head.borrow_mut();
236         let fill = copy_head.fill.get();
237         let mut start = round_up(fill, align);
238         let mut end = start + n_bytes;
239
240         if end > copy_head.capacity() {
241             if self.alloc_grow(&mut *copy_head, fill, end - fill) {
242                 // Continuing with a newly allocated chunk
243                 start = 0;
244                 end = n_bytes;
245                 copy_head.is_copy.set(true);
246             }
247         }
248
249         copy_head.fill.set(end);
250
251         unsafe { copy_head.as_ptr().offset(start as isize) }
252     }
253
254     #[inline]
255     fn alloc_copy<T, F>(&self, op: F) -> &mut T
256         where F: FnOnce() -> T
257     {
258         unsafe {
259             let ptr = self.alloc_copy_inner(mem::size_of::<T>(), mem::align_of::<T>());
260             let ptr = ptr as *mut T;
261             ptr::write(&mut (*ptr), op());
262             &mut *ptr
263         }
264     }
265
266     // Functions for the non-copyable part of the arena.
267
268     #[inline]
269     fn alloc_noncopy_inner(&self, n_bytes: usize, align: usize) -> (*const u8, *const u8) {
270         let mut head = self.head.borrow_mut();
271         let fill = head.fill.get();
272
273         let mut tydesc_start = fill;
274         let after_tydesc = fill + mem::size_of::<*const TyDesc>();
275         let mut start = round_up(after_tydesc, align);
276         let mut end = round_up(start + n_bytes, mem::align_of::<*const TyDesc>());
277
278         if end > head.capacity() {
279             if self.alloc_grow(&mut *head, tydesc_start, end - tydesc_start) {
280                 // Continuing with a newly allocated chunk
281                 tydesc_start = 0;
282                 start = round_up(mem::size_of::<*const TyDesc>(), align);
283                 end = round_up(start + n_bytes, mem::align_of::<*const TyDesc>());
284             }
285         }
286
287         head.fill.set(end);
288
289         unsafe {
290             let buf = head.as_ptr();
291             (buf.offset(tydesc_start as isize),
292              buf.offset(start as isize))
293         }
294     }
295
296     #[inline]
297     fn alloc_noncopy<T, F>(&self, op: F) -> &mut T
298         where F: FnOnce() -> T
299     {
300         unsafe {
301             let tydesc = get_tydesc::<T>();
302             let (ty_ptr, ptr) = self.alloc_noncopy_inner(mem::size_of::<T>(), mem::align_of::<T>());
303             let ty_ptr = ty_ptr as *mut usize;
304             let ptr = ptr as *mut T;
305             // Write in our tydesc along with a bit indicating that it
306             // has *not* been initialized yet.
307             *ty_ptr = bitpack_tydesc_ptr(tydesc, false);
308             // Actually initialize it
309             ptr::write(&mut (*ptr), op());
310             // Now that we are done, update the tydesc to indicate that
311             // the object is there.
312             *ty_ptr = bitpack_tydesc_ptr(tydesc, true);
313
314             &mut *ptr
315         }
316     }
317
318     /// Allocates a new item in the arena, using `op` to initialize the value,
319     /// and returns a reference to it.
320     #[inline]
321     pub fn alloc<T: 'longer_than_self, F>(&self, op: F) -> &mut T
322         where F: FnOnce() -> T
323     {
324         unsafe {
325             if intrinsics::needs_drop::<T>() {
326                 self.alloc_noncopy(op)
327             } else {
328                 self.alloc_copy(op)
329             }
330         }
331     }
332
333     /// Allocates a slice of bytes of requested length. The bytes are not guaranteed to be zero
334     /// if the arena has previously been cleared.
335     ///
336     /// # Panics
337     ///
338     /// Panics if the requested length is too large and causes overflow.
339     pub fn alloc_bytes(&self, len: usize) -> &mut [u8] {
340         unsafe {
341             // Check for overflow.
342             self.copy_head.borrow().fill.get().checked_add(len).expect("length overflow");
343             let ptr = self.alloc_copy_inner(len, 1);
344             intrinsics::assume(!ptr.is_null());
345             slice::from_raw_parts_mut(ptr as *mut _, len)
346         }
347     }
348
349     /// Clears the arena. Deallocates all but the longest chunk which may be reused.
350     pub fn clear(&mut self) {
351         unsafe {
352             self.head.borrow().destroy();
353             self.head.borrow().fill.set(0);
354             self.copy_head.borrow().fill.set(0);
355             for chunk in self.chunks.borrow().iter() {
356                 if !chunk.is_copy.get() {
357                     chunk.destroy();
358                 }
359             }
360             self.chunks.borrow_mut().clear();
361         }
362     }
363 }
364
365 /// A faster arena that can hold objects of only one type.
366 pub struct TypedArena<T> {
367     /// A pointer to the next object to be allocated.
368     ptr: Cell<*mut T>,
369
370     /// A pointer to the end of the allocated area. When this pointer is
371     /// reached, a new chunk is allocated.
372     end: Cell<*mut T>,
373
374     /// A vector arena segments.
375     chunks: RefCell<Vec<TypedArenaChunk<T>>>,
376
377     /// Marker indicating that dropping the arena causes its owned
378     /// instances of `T` to be dropped.
379     _own: PhantomData<T>,
380 }
381
382 struct TypedArenaChunk<T> {
383     /// Pointer to the next arena segment.
384     storage: RawVec<T>,
385 }
386
387 impl<T> TypedArenaChunk<T> {
388     #[inline]
389     unsafe fn new(capacity: usize) -> TypedArenaChunk<T> {
390         TypedArenaChunk { storage: RawVec::with_capacity(capacity) }
391     }
392
393     /// Destroys this arena chunk.
394     #[inline]
395     unsafe fn destroy(&mut self, len: usize) {
396         // The branch on needs_drop() is an -O1 performance optimization.
397         // Without the branch, dropping TypedArena<u8> takes linear time.
398         if intrinsics::needs_drop::<T>() {
399             let mut start = self.start();
400             // Destroy all allocated objects.
401             for _ in 0..len {
402                 ptr::drop_in_place(start);
403                 start = start.offset(1);
404             }
405         }
406     }
407
408     // Returns a pointer to the first allocated object.
409     #[inline]
410     fn start(&self) -> *mut T {
411         self.storage.ptr()
412     }
413
414     // Returns a pointer to the end of the allocated space.
415     #[inline]
416     fn end(&self) -> *mut T {
417         unsafe {
418             if mem::size_of::<T>() == 0 {
419                 // A pointer as large as possible for zero-sized elements.
420                 !0 as *mut T
421             } else {
422                 self.start().offset(self.storage.cap() as isize)
423             }
424         }
425     }
426 }
427
428 const PAGE: usize = 4096;
429
430 impl<T> TypedArena<T> {
431     /// Creates a new `TypedArena` with preallocated space for many objects.
432     #[inline]
433     pub fn new() -> TypedArena<T> {
434         // Reserve at least one page.
435         let elem_size = cmp::max(1, mem::size_of::<T>());
436         TypedArena::with_capacity(PAGE / elem_size)
437     }
438
439     /// Creates a new `TypedArena` with preallocated space for the given number of
440     /// objects.
441     #[inline]
442     pub fn with_capacity(capacity: usize) -> TypedArena<T> {
443         unsafe {
444             let chunk = TypedArenaChunk::<T>::new(cmp::max(1, capacity));
445             TypedArena {
446                 ptr: Cell::new(chunk.start()),
447                 end: Cell::new(chunk.end()),
448                 chunks: RefCell::new(vec![chunk]),
449                 _own: PhantomData,
450             }
451         }
452     }
453
454     /// Allocates an object in the `TypedArena`, returning a reference to it.
455     #[inline]
456     pub fn alloc(&self, object: T) -> &mut T {
457         if self.ptr == self.end {
458             self.grow()
459         }
460
461         unsafe {
462             if mem::size_of::<T>() == 0 {
463                 self.ptr.set(intrinsics::arith_offset(self.ptr.get() as *mut u8, 1) as *mut T);
464                 let ptr = heap::EMPTY as *mut T;
465                 // Don't drop the object. This `write` is equivalent to `forget`.
466                 ptr::write(ptr, object);
467                 &mut *ptr
468             } else {
469                 let ptr = self.ptr.get();
470                 // Advance the pointer.
471                 self.ptr.set(self.ptr.get().offset(1));
472                 // Write into uninitialized memory.
473                 ptr::write(ptr, object);
474                 &mut *ptr
475             }
476         }
477     }
478
479     /// Grows the arena.
480     #[inline(never)]
481     #[cold]
482     fn grow(&self) {
483         unsafe {
484             let mut chunks = self.chunks.borrow_mut();
485             let prev_capacity = chunks.last().unwrap().storage.cap();
486             let new_capacity = prev_capacity.checked_mul(2).unwrap();
487             if chunks.last_mut().unwrap().storage.double_in_place() {
488                 self.end.set(chunks.last().unwrap().end());
489             } else {
490                 let chunk = TypedArenaChunk::<T>::new(new_capacity);
491                 self.ptr.set(chunk.start());
492                 self.end.set(chunk.end());
493                 chunks.push(chunk);
494             }
495         }
496     }
497     /// Clears the arena. Deallocates all but the longest chunk which may be reused.
498     pub fn clear(&mut self) {
499         unsafe {
500             // Clear the last chunk, which is partially filled.
501             let mut chunks_borrow = self.chunks.borrow_mut();
502             let last_idx = chunks_borrow.len() - 1;
503             self.clear_last_chunk(&mut chunks_borrow[last_idx]);
504             // If `T` is ZST, code below has no effect.
505             for mut chunk in chunks_borrow.drain(..last_idx) {
506                 let cap = chunk.storage.cap();
507                 chunk.destroy(cap);
508             }
509         }
510     }
511
512     // Drops the contents of the last chunk. The last chunk is partially empty, unlike all other
513     // chunks.
514     fn clear_last_chunk(&self, last_chunk: &mut TypedArenaChunk<T>) {
515         // Determine how much was filled.
516         let start = last_chunk.start() as usize;
517         // We obtain the value of the pointer to the first uninitialized element.
518         let end = self.ptr.get() as usize;
519         // We then calculate the number of elements to be dropped in the last chunk,
520         // which is the filled area's length.
521         let diff = if mem::size_of::<T>() == 0 {
522             // `T` is ZST. It can't have a drop flag, so the value here doesn't matter. We get
523             // the number of zero-sized values in the last and only chunk, just out of caution.
524             // Recall that `end` was incremented for each allocated value.
525             end - start
526         } else {
527             (end - start) / mem::size_of::<T>()
528         };
529         // Pass that to the `destroy` method.
530         unsafe {
531             last_chunk.destroy(diff);
532         }
533         // Reset the chunk.
534         self.ptr.set(last_chunk.start());
535     }
536 }
537
538 impl<T> Drop for TypedArena<T> {
539     #[unsafe_destructor_blind_to_params]
540     fn drop(&mut self) {
541         unsafe {
542             // Determine how much was filled.
543             let mut chunks_borrow = self.chunks.borrow_mut();
544             let mut last_chunk = chunks_borrow.pop().unwrap();
545             // Drop the contents of the last chunk.
546             self.clear_last_chunk(&mut last_chunk);
547             // The last chunk will be dropped. Destroy all other chunks.
548             for chunk in chunks_borrow.iter_mut() {
549                 let cap = chunk.storage.cap();
550                 chunk.destroy(cap);
551             }
552             // RawVec handles deallocation of `last_chunk` and `self.chunks`.
553         }
554     }
555 }
556
557 unsafe impl<T: Send> Send for TypedArena<T> {}
558
559 #[cfg(test)]
560 mod tests {
561     extern crate test;
562     use self::test::Bencher;
563     use super::{Arena, TypedArena};
564     use std::rc::Rc;
565
566     #[allow(dead_code)]
567     struct Point {
568         x: i32,
569         y: i32,
570         z: i32,
571     }
572
573     #[test]
574     fn test_arena_alloc_nested() {
575         struct Inner {
576             value: u8,
577         }
578         struct Outer<'a> {
579             inner: &'a Inner,
580         }
581         enum EI<'e> {
582             I(Inner),
583             O(Outer<'e>),
584         }
585
586         struct Wrap<'a>(TypedArena<EI<'a>>);
587
588         impl<'a> Wrap<'a> {
589             fn alloc_inner<F: Fn() -> Inner>(&self, f: F) -> &Inner {
590                 let r: &EI = self.0.alloc(EI::I(f()));
591                 if let &EI::I(ref i) = r {
592                     i
593                 } else {
594                     panic!("mismatch");
595                 }
596             }
597             fn alloc_outer<F: Fn() -> Outer<'a>>(&self, f: F) -> &Outer {
598                 let r: &EI = self.0.alloc(EI::O(f()));
599                 if let &EI::O(ref o) = r {
600                     o
601                 } else {
602                     panic!("mismatch");
603                 }
604             }
605         }
606
607         let arena = Wrap(TypedArena::new());
608
609         let result = arena.alloc_outer(|| {
610             Outer { inner: arena.alloc_inner(|| Inner { value: 10 }) }
611         });
612
613         assert_eq!(result.inner.value, 10);
614     }
615
616     #[test]
617     pub fn test_copy() {
618         let arena = TypedArena::new();
619         for _ in 0..100000 {
620             arena.alloc(Point { x: 1, y: 2, z: 3 });
621         }
622     }
623
624     #[bench]
625     pub fn bench_copy(b: &mut Bencher) {
626         let arena = TypedArena::new();
627         b.iter(|| arena.alloc(Point { x: 1, y: 2, z: 3 }))
628     }
629
630     #[bench]
631     pub fn bench_copy_nonarena(b: &mut Bencher) {
632         b.iter(|| {
633             let _: Box<_> = Box::new(Point {
634                 x: 1,
635                 y: 2,
636                 z: 3
637             });
638         })
639     }
640
641     #[bench]
642     pub fn bench_copy_old_arena(b: &mut Bencher) {
643         let arena = Arena::new();
644         b.iter(|| arena.alloc(|| Point { x: 1, y: 2, z: 3 }))
645     }
646
647     #[allow(dead_code)]
648     struct Noncopy {
649         string: String,
650         array: Vec<i32>,
651     }
652
653     #[test]
654     pub fn test_noncopy() {
655         let arena = TypedArena::new();
656         for _ in 0..100000 {
657             arena.alloc(Noncopy {
658                 string: "hello world".to_string(),
659                 array: vec![1, 2, 3, 4, 5],
660             });
661         }
662     }
663
664     #[test]
665     pub fn test_typed_arena_zero_sized() {
666         let arena = TypedArena::new();
667         for _ in 0..100000 {
668             arena.alloc(());
669         }
670     }
671
672     #[test]
673     pub fn test_arena_zero_sized() {
674         let arena = Arena::new();
675         for _ in 0..1000 {
676             for _ in 0..100 {
677                 arena.alloc(|| ());
678             }
679             arena.alloc(|| Point {
680                 x: 1,
681                 y: 2,
682                 z: 3,
683             });
684         }
685     }
686
687     #[test]
688     pub fn test_typed_arena_clear() {
689         let mut arena = TypedArena::new();
690         for _ in 0..10 {
691             arena.clear();
692             for _ in 0..10000 {
693                 arena.alloc(Point {
694                     x: 1,
695                     y: 2,
696                     z: 3,
697                 });
698             }
699         }
700     }
701
702     #[test]
703     pub fn test_arena_clear() {
704         let mut arena = Arena::new();
705         for _ in 0..10 {
706             arena.clear();
707             for _ in 0..10000 {
708                 arena.alloc(|| Point {
709                     x: 1,
710                     y: 2,
711                     z: 3,
712                 });
713                 arena.alloc(|| Noncopy {
714                     string: "hello world".to_string(),
715                     array: vec![],
716                 });
717             }
718         }
719     }
720
721     #[test]
722     pub fn test_arena_alloc_bytes() {
723         let arena = Arena::new();
724         for i in 0..10000 {
725             arena.alloc(|| Point {
726                 x: 1,
727                 y: 2,
728                 z: 3,
729             });
730             for byte in arena.alloc_bytes(i % 42).iter_mut() {
731                 *byte = i as u8;
732             }
733         }
734     }
735
736     #[test]
737     fn test_arena_destructors() {
738         let arena = Arena::new();
739         for i in 0..10 {
740             // Arena allocate something with drop glue to make sure it
741             // doesn't leak.
742             arena.alloc(|| Rc::new(i));
743             // Allocate something with funny size and alignment, to keep
744             // things interesting.
745             arena.alloc(|| [0u8, 1u8, 2u8]);
746         }
747     }
748
749     #[test]
750     #[should_panic]
751     fn test_arena_destructors_fail() {
752         let arena = Arena::new();
753         // Put some stuff in the arena.
754         for i in 0..10 {
755             // Arena allocate something with drop glue to make sure it
756             // doesn't leak.
757             arena.alloc(|| { Rc::new(i) });
758             // Allocate something with funny size and alignment, to keep
759             // things interesting.
760             arena.alloc(|| { [0u8, 1, 2] });
761         }
762         // Now, panic while allocating
763         arena.alloc::<Rc<i32>, _>(|| {
764             panic!();
765         });
766     }
767
768     #[bench]
769     pub fn bench_noncopy(b: &mut Bencher) {
770         let arena = TypedArena::new();
771         b.iter(|| {
772             arena.alloc(Noncopy {
773                 string: "hello world".to_string(),
774                 array: vec!( 1, 2, 3, 4, 5 ),
775             })
776         })
777     }
778
779     #[bench]
780     pub fn bench_noncopy_nonarena(b: &mut Bencher) {
781         b.iter(|| {
782             let _: Box<_> = Box::new(Noncopy {
783                 string: "hello world".to_string(),
784                 array: vec!( 1, 2, 3, 4, 5 ),
785             });
786         })
787     }
788
789     #[bench]
790     pub fn bench_noncopy_old_arena(b: &mut Bencher) {
791         let arena = Arena::new();
792         b.iter(|| {
793             arena.alloc(|| Noncopy {
794                 string: "hello world".to_string(),
795                 array: vec!( 1, 2, 3, 4, 5 ),
796             })
797         })
798     }
799 }