]> git.lizzy.rs Git - rust.git/blob - src/libarena/lib.rs
Rollup merge of #59890 - GuillaumeGomez:empty-json-variables, r=QuietMisdreavus
[rust.git] / src / libarena / lib.rs
1 //! The arena, a fast but limited type of allocator.
2 //!
3 //! Arenas are a type of allocator that destroy the objects within, all at
4 //! once, once the arena itself is destroyed. They do not support deallocation
5 //! of individual objects while the arena itself is still alive. The benefit
6 //! of an arena is very fast allocation; just a pointer bump.
7 //!
8 //! This crate implements `TypedArena`, a simple arena that can only hold
9 //! objects of a single type.
10
11 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/",
12        test(no_crate_inject, attr(deny(warnings))))]
13
14 #![deny(rust_2018_idioms)]
15 #![cfg_attr(not(stage0), deny(internal))]
16
17 #![feature(alloc)]
18 #![feature(core_intrinsics)]
19 #![feature(dropck_eyepatch)]
20 #![feature(raw_vec_internals)]
21 #![cfg_attr(test, feature(test))]
22
23 #![allow(deprecated)]
24
25 extern crate alloc;
26
27 use rustc_data_structures::cold_path;
28 use rustc_data_structures::sync::MTLock;
29 use smallvec::SmallVec;
30
31 use std::cell::{Cell, RefCell};
32 use std::cmp;
33 use std::intrinsics;
34 use std::marker::{PhantomData, Send};
35 use std::mem;
36 use std::ptr;
37 use std::slice;
38
39 use alloc::raw_vec::RawVec;
40
41 /// An arena that can hold objects of only one type.
42 pub struct TypedArena<T> {
43     /// A pointer to the next object to be allocated.
44     ptr: Cell<*mut T>,
45
46     /// A pointer to the end of the allocated area. When this pointer is
47     /// reached, a new chunk is allocated.
48     end: Cell<*mut T>,
49
50     /// A vector of arena chunks.
51     chunks: RefCell<Vec<TypedArenaChunk<T>>>,
52
53     /// Marker indicating that dropping the arena causes its owned
54     /// instances of `T` to be dropped.
55     _own: PhantomData<T>,
56 }
57
58 struct TypedArenaChunk<T> {
59     /// The raw storage for the arena chunk.
60     storage: RawVec<T>,
61     /// The number of valid entries in the chunk.
62     entries: usize,
63 }
64
65 impl<T> TypedArenaChunk<T> {
66     #[inline]
67     unsafe fn new(capacity: usize) -> TypedArenaChunk<T> {
68         TypedArenaChunk {
69             storage: RawVec::with_capacity(capacity),
70             entries: 0,
71         }
72     }
73
74     /// Destroys this arena chunk.
75     #[inline]
76     unsafe fn destroy(&mut self, len: usize) {
77         // The branch on needs_drop() is an -O1 performance optimization.
78         // Without the branch, dropping TypedArena<u8> takes linear time.
79         if mem::needs_drop::<T>() {
80             let mut start = self.start();
81             // Destroy all allocated objects.
82             for _ in 0..len {
83                 ptr::drop_in_place(start);
84                 start = start.offset(1);
85             }
86         }
87     }
88
89     // Returns a pointer to the first allocated object.
90     #[inline]
91     fn start(&self) -> *mut T {
92         self.storage.ptr()
93     }
94
95     // Returns a pointer to the end of the allocated space.
96     #[inline]
97     fn end(&self) -> *mut T {
98         unsafe {
99             if mem::size_of::<T>() == 0 {
100                 // A pointer as large as possible for zero-sized elements.
101                 !0 as *mut T
102             } else {
103                 self.start().add(self.storage.cap())
104             }
105         }
106     }
107 }
108
109 const PAGE: usize = 4096;
110
111 impl<T> Default for TypedArena<T> {
112     /// Creates a new `TypedArena`.
113     fn default() -> TypedArena<T> {
114         TypedArena {
115             // We set both `ptr` and `end` to 0 so that the first call to
116             // alloc() will trigger a grow().
117             ptr: Cell::new(0 as *mut T),
118             end: Cell::new(0 as *mut T),
119             chunks: RefCell::new(vec![]),
120             _own: PhantomData,
121         }
122     }
123 }
124
125 impl<T> TypedArena<T> {
126     pub fn in_arena(&self, ptr: *const T) -> bool {
127         let ptr = ptr as *const T as *mut T;
128
129         self.chunks.borrow().iter().any(|chunk| chunk.start() <= ptr && ptr < chunk.end())
130     }
131     /// Allocates an object in the `TypedArena`, returning a reference to it.
132     #[inline]
133     pub fn alloc(&self, object: T) -> &mut T {
134         if self.ptr == self.end {
135             self.grow(1)
136         }
137
138         unsafe {
139             if mem::size_of::<T>() == 0 {
140                 self.ptr
141                     .set(intrinsics::arith_offset(self.ptr.get() as *mut u8, 1)
142                         as *mut T);
143                 let ptr = mem::align_of::<T>() as *mut T;
144                 // Don't drop the object. This `write` is equivalent to `forget`.
145                 ptr::write(ptr, object);
146                 &mut *ptr
147             } else {
148                 let ptr = self.ptr.get();
149                 // Advance the pointer.
150                 self.ptr.set(self.ptr.get().offset(1));
151                 // Write into uninitialized memory.
152                 ptr::write(ptr, object);
153                 &mut *ptr
154             }
155         }
156     }
157
158     #[inline]
159     fn can_allocate(&self, len: usize) -> bool {
160         let available_capacity_bytes = self.end.get() as usize - self.ptr.get() as usize;
161         let at_least_bytes = len.checked_mul(mem::size_of::<T>()).unwrap();
162         available_capacity_bytes >= at_least_bytes
163     }
164
165     /// Ensures there's enough space in the current chunk to fit `len` objects.
166     #[inline]
167     fn ensure_capacity(&self, len: usize) {
168         if !self.can_allocate(len) {
169             self.grow(len);
170             debug_assert!(self.can_allocate(len));
171         }
172     }
173
174     #[inline]
175     unsafe fn alloc_raw_slice(&self, len: usize) -> *mut T {
176         assert!(mem::size_of::<T>() != 0);
177         assert!(len != 0);
178
179         self.ensure_capacity(len);
180
181         let start_ptr = self.ptr.get();
182         self.ptr.set(start_ptr.add(len));
183         start_ptr
184     }
185
186     /// Allocates a slice of objects that are copied into the `TypedArena`, returning a mutable
187     /// reference to it. Will panic if passed a zero-sized types.
188     ///
189     /// Panics:
190     ///
191     ///  - Zero-sized types
192     ///  - Zero-length slices
193     #[inline]
194     pub fn alloc_slice(&self, slice: &[T]) -> &mut [T]
195     where
196         T: Copy,
197     {
198         unsafe {
199             let len = slice.len();
200             let start_ptr = self.alloc_raw_slice(len);
201             slice.as_ptr().copy_to_nonoverlapping(start_ptr, len);
202             slice::from_raw_parts_mut(start_ptr, len)
203         }
204     }
205
206     #[inline]
207     pub fn alloc_from_iter<I: IntoIterator<Item = T>>(&self, iter: I) -> &mut [T] {
208         assert!(mem::size_of::<T>() != 0);
209         let mut iter = iter.into_iter();
210         let size_hint = iter.size_hint();
211
212         match size_hint {
213             (min, Some(max)) if min == max => {
214                 // We know the exact number of elements the iterator will produce here
215                 let len = min;
216
217                 if len == 0 {
218                     return &mut [];
219                 }
220
221                 self.ensure_capacity(len);
222
223                 let slice = self.ptr.get();
224
225                 unsafe {
226                     let mut ptr = self.ptr.get();
227                     for _ in 0..len {
228                         // Write into uninitialized memory.
229                         ptr::write(ptr, iter.next().unwrap());
230                         // Advance the pointer.
231                         ptr = ptr.offset(1);
232                         // Update the pointer per iteration so if `iter.next()` panics
233                         // we destroy the correct amount
234                         self.ptr.set(ptr);
235                     }
236                     slice::from_raw_parts_mut(slice, len)
237                 }
238             }
239             _ => {
240                 cold_path(move || -> &mut [T] {
241                     let mut vec: SmallVec<[_; 8]> = iter.collect();
242                     if vec.is_empty() {
243                         return &mut [];
244                     }
245                     // Move the content to the arena by copying it and then forgetting
246                     // the content of the SmallVec
247                     unsafe {
248                         let len = vec.len();
249                         let start_ptr = self.alloc_raw_slice(len);
250                         vec.as_ptr().copy_to_nonoverlapping(start_ptr, len);
251                         vec.set_len(0);
252                         slice::from_raw_parts_mut(start_ptr, len)
253                     }
254                 })
255             }
256         }
257     }
258
259     /// Grows the arena.
260     #[inline(never)]
261     #[cold]
262     fn grow(&self, n: usize) {
263         unsafe {
264             let mut chunks = self.chunks.borrow_mut();
265             let (chunk, mut new_capacity);
266             if let Some(last_chunk) = chunks.last_mut() {
267                 let used_bytes = self.ptr.get() as usize - last_chunk.start() as usize;
268                 let currently_used_cap = used_bytes / mem::size_of::<T>();
269                 last_chunk.entries = currently_used_cap;
270                 if last_chunk.storage.reserve_in_place(currently_used_cap, n) {
271                     self.end.set(last_chunk.end());
272                     return;
273                 } else {
274                     new_capacity = last_chunk.storage.cap();
275                     loop {
276                         new_capacity = new_capacity.checked_mul(2).unwrap();
277                         if new_capacity >= currently_used_cap + n {
278                             break;
279                         }
280                     }
281                 }
282             } else {
283                 let elem_size = cmp::max(1, mem::size_of::<T>());
284                 new_capacity = cmp::max(n, PAGE / elem_size);
285             }
286             chunk = TypedArenaChunk::<T>::new(new_capacity);
287             self.ptr.set(chunk.start());
288             self.end.set(chunk.end());
289             chunks.push(chunk);
290         }
291     }
292
293     /// Clears the arena. Deallocates all but the longest chunk which may be reused.
294     pub fn clear(&mut self) {
295         unsafe {
296             // Clear the last chunk, which is partially filled.
297             let mut chunks_borrow = self.chunks.borrow_mut();
298             if let Some(mut last_chunk) = chunks_borrow.last_mut() {
299                 self.clear_last_chunk(&mut last_chunk);
300                 let len = chunks_borrow.len();
301                 // If `T` is ZST, code below has no effect.
302                 for mut chunk in chunks_borrow.drain(..len-1) {
303                     chunk.destroy(chunk.entries);
304                 }
305             }
306         }
307     }
308
309     // Drops the contents of the last chunk. The last chunk is partially empty, unlike all other
310     // chunks.
311     fn clear_last_chunk(&self, last_chunk: &mut TypedArenaChunk<T>) {
312         // Determine how much was filled.
313         let start = last_chunk.start() as usize;
314         // We obtain the value of the pointer to the first uninitialized element.
315         let end = self.ptr.get() as usize;
316         // We then calculate the number of elements to be dropped in the last chunk,
317         // which is the filled area's length.
318         let diff = if mem::size_of::<T>() == 0 {
319             // `T` is ZST. It can't have a drop flag, so the value here doesn't matter. We get
320             // the number of zero-sized values in the last and only chunk, just out of caution.
321             // Recall that `end` was incremented for each allocated value.
322             end - start
323         } else {
324             (end - start) / mem::size_of::<T>()
325         };
326         // Pass that to the `destroy` method.
327         unsafe {
328             last_chunk.destroy(diff);
329         }
330         // Reset the chunk.
331         self.ptr.set(last_chunk.start());
332     }
333 }
334
335 unsafe impl<#[may_dangle] T> Drop for TypedArena<T> {
336     fn drop(&mut self) {
337         unsafe {
338             // Determine how much was filled.
339             let mut chunks_borrow = self.chunks.borrow_mut();
340             if let Some(mut last_chunk) = chunks_borrow.pop() {
341                 // Drop the contents of the last chunk.
342                 self.clear_last_chunk(&mut last_chunk);
343                 // The last chunk will be dropped. Destroy all other chunks.
344                 for chunk in chunks_borrow.iter_mut() {
345                     chunk.destroy(chunk.entries);
346                 }
347             }
348             // RawVec handles deallocation of `last_chunk` and `self.chunks`.
349         }
350     }
351 }
352
353 unsafe impl<T: Send> Send for TypedArena<T> {}
354
355 pub struct DroplessArena {
356     /// A pointer to the next object to be allocated.
357     ptr: Cell<*mut u8>,
358
359     /// A pointer to the end of the allocated area. When this pointer is
360     /// reached, a new chunk is allocated.
361     end: Cell<*mut u8>,
362
363     /// A vector of arena chunks.
364     chunks: RefCell<Vec<TypedArenaChunk<u8>>>,
365 }
366
367 unsafe impl Send for DroplessArena {}
368
369 impl Default for DroplessArena {
370     #[inline]
371     fn default() -> DroplessArena {
372         DroplessArena {
373             ptr: Cell::new(0 as *mut u8),
374             end: Cell::new(0 as *mut u8),
375             chunks: Default::default(),
376         }
377     }
378 }
379
380 impl DroplessArena {
381     pub fn in_arena<T: ?Sized>(&self, ptr: *const T) -> bool {
382         let ptr = ptr as *const u8 as *mut u8;
383
384         self.chunks.borrow().iter().any(|chunk| chunk.start() <= ptr && ptr < chunk.end())
385     }
386
387     #[inline]
388     fn align(&self, align: usize) {
389         let final_address = ((self.ptr.get() as usize) + align - 1) & !(align - 1);
390         self.ptr.set(final_address as *mut u8);
391         assert!(self.ptr <= self.end);
392     }
393
394     #[inline(never)]
395     #[cold]
396     fn grow(&self, needed_bytes: usize) {
397         unsafe {
398             let mut chunks = self.chunks.borrow_mut();
399             let (chunk, mut new_capacity);
400             if let Some(last_chunk) = chunks.last_mut() {
401                 let used_bytes = self.ptr.get() as usize - last_chunk.start() as usize;
402                 if last_chunk
403                     .storage
404                     .reserve_in_place(used_bytes, needed_bytes)
405                 {
406                     self.end.set(last_chunk.end());
407                     return;
408                 } else {
409                     new_capacity = last_chunk.storage.cap();
410                     loop {
411                         new_capacity = new_capacity.checked_mul(2).unwrap();
412                         if new_capacity >= used_bytes + needed_bytes {
413                             break;
414                         }
415                     }
416                 }
417             } else {
418                 new_capacity = cmp::max(needed_bytes, PAGE);
419             }
420             chunk = TypedArenaChunk::<u8>::new(new_capacity);
421             self.ptr.set(chunk.start());
422             self.end.set(chunk.end());
423             chunks.push(chunk);
424         }
425     }
426
427     #[inline]
428     pub fn alloc_raw(&self, bytes: usize, align: usize) -> &mut [u8] {
429         unsafe {
430             assert!(bytes != 0);
431
432             self.align(align);
433
434             let future_end = intrinsics::arith_offset(self.ptr.get(), bytes as isize);
435             if (future_end as *mut u8) >= self.end.get() {
436                 self.grow(bytes);
437             }
438
439             let ptr = self.ptr.get();
440             // Set the pointer past ourselves
441             self.ptr.set(
442                 intrinsics::arith_offset(self.ptr.get(), bytes as isize) as *mut u8,
443             );
444             slice::from_raw_parts_mut(ptr, bytes)
445         }
446     }
447
448     #[inline]
449     pub fn alloc<T>(&self, object: T) -> &mut T {
450         assert!(!mem::needs_drop::<T>());
451
452         let mem = self.alloc_raw(
453             mem::size_of::<T>(),
454             mem::align_of::<T>()) as *mut _ as *mut T;
455
456         unsafe {
457             // Write into uninitialized memory.
458             ptr::write(mem, object);
459             &mut *mem
460         }
461     }
462
463     /// Allocates a slice of objects that are copied into the `DroplessArena`, returning a mutable
464     /// reference to it. Will panic if passed a zero-sized type.
465     ///
466     /// Panics:
467     ///
468     ///  - Zero-sized types
469     ///  - Zero-length slices
470     #[inline]
471     pub fn alloc_slice<T>(&self, slice: &[T]) -> &mut [T]
472     where
473         T: Copy,
474     {
475         assert!(!mem::needs_drop::<T>());
476         assert!(mem::size_of::<T>() != 0);
477         assert!(!slice.is_empty());
478
479         let mem = self.alloc_raw(
480             slice.len() * mem::size_of::<T>(),
481             mem::align_of::<T>()) as *mut _ as *mut T;
482
483         unsafe {
484             let arena_slice = slice::from_raw_parts_mut(mem, slice.len());
485             arena_slice.copy_from_slice(slice);
486             arena_slice
487         }
488     }
489
490     #[inline]
491     pub fn alloc_from_iter<T, I: IntoIterator<Item = T>>(&self, iter: I) -> &mut [T] {
492         let mut iter = iter.into_iter();
493         assert!(mem::size_of::<T>() != 0);
494         assert!(!mem::needs_drop::<T>());
495
496         let size_hint = iter.size_hint();
497
498         match size_hint {
499             (min, Some(max)) if min == max => {
500                 // We know the exact number of elements the iterator will produce here
501                 let len = min;
502
503                 if len == 0 {
504                     return &mut []
505                 }
506                 let size = len.checked_mul(mem::size_of::<T>()).unwrap();
507                 let mem = self.alloc_raw(size, mem::align_of::<T>()) as *mut _ as *mut T;
508                 unsafe {
509                     for i in 0..len {
510                         ptr::write(mem.offset(i as isize), iter.next().unwrap())
511                     }
512                     slice::from_raw_parts_mut(mem, len)
513                 }
514             }
515             (_, _) => {
516                 cold_path(move || -> &mut [T] {
517                     let mut vec: SmallVec<[_; 8]> = iter.collect();
518                     if vec.is_empty() {
519                         return &mut [];
520                     }
521                     // Move the content to the arena by copying it and then forgetting
522                     // the content of the SmallVec
523                     unsafe {
524                         let len = vec.len();
525                         let start_ptr = self.alloc_raw(
526                             len * mem::size_of::<T>(),
527                             mem::align_of::<T>()
528                         ) as *mut _ as *mut T;
529                         vec.as_ptr().copy_to_nonoverlapping(start_ptr, len);
530                         vec.set_len(0);
531                         slice::from_raw_parts_mut(start_ptr, len)
532                     }
533                 })
534             }
535         }
536     }
537 }
538
539 #[derive(Default)]
540 // FIXME(@Zoxc): this type is entirely unused in rustc
541 pub struct SyncTypedArena<T> {
542     lock: MTLock<TypedArena<T>>,
543 }
544
545 impl<T> SyncTypedArena<T> {
546     #[inline(always)]
547     pub fn alloc(&self, object: T) -> &mut T {
548         // Extend the lifetime of the result since it's limited to the lock guard
549         unsafe { &mut *(self.lock.lock().alloc(object) as *mut T) }
550     }
551
552     #[inline(always)]
553     pub fn alloc_slice(&self, slice: &[T]) -> &mut [T]
554     where
555         T: Copy,
556     {
557         // Extend the lifetime of the result since it's limited to the lock guard
558         unsafe { &mut *(self.lock.lock().alloc_slice(slice) as *mut [T]) }
559     }
560
561     #[inline(always)]
562     pub fn clear(&mut self) {
563         self.lock.get_mut().clear();
564     }
565 }
566
567 #[derive(Default)]
568 pub struct SyncDroplessArena {
569     lock: MTLock<DroplessArena>,
570 }
571
572 impl SyncDroplessArena {
573     #[inline(always)]
574     pub fn in_arena<T: ?Sized>(&self, ptr: *const T) -> bool {
575         self.lock.lock().in_arena(ptr)
576     }
577
578     #[inline(always)]
579     pub fn alloc_raw(&self, bytes: usize, align: usize) -> &mut [u8] {
580         // Extend the lifetime of the result since it's limited to the lock guard
581         unsafe { &mut *(self.lock.lock().alloc_raw(bytes, align) as *mut [u8]) }
582     }
583
584     #[inline(always)]
585     pub fn alloc<T>(&self, object: T) -> &mut T {
586         // Extend the lifetime of the result since it's limited to the lock guard
587         unsafe { &mut *(self.lock.lock().alloc(object) as *mut T) }
588     }
589
590     #[inline(always)]
591     pub fn alloc_slice<T>(&self, slice: &[T]) -> &mut [T]
592     where
593         T: Copy,
594     {
595         // Extend the lifetime of the result since it's limited to the lock guard
596         unsafe { &mut *(self.lock.lock().alloc_slice(slice) as *mut [T]) }
597     }
598 }
599
600 #[cfg(test)]
601 mod tests {
602     extern crate test;
603     use test::Bencher;
604     use super::TypedArena;
605     use std::cell::Cell;
606
607     #[allow(dead_code)]
608     #[derive(Debug, Eq, PartialEq)]
609     struct Point {
610         x: i32,
611         y: i32,
612         z: i32,
613     }
614
615     #[test]
616     pub fn test_unused() {
617         let arena: TypedArena<Point> = TypedArena::default();
618         assert!(arena.chunks.borrow().is_empty());
619     }
620
621     #[test]
622     fn test_arena_alloc_nested() {
623         struct Inner {
624             value: u8,
625         }
626         struct Outer<'a> {
627             inner: &'a Inner,
628         }
629         enum EI<'e> {
630             I(Inner),
631             O(Outer<'e>),
632         }
633
634         struct Wrap<'a>(TypedArena<EI<'a>>);
635
636         impl<'a> Wrap<'a> {
637             fn alloc_inner<F: Fn() -> Inner>(&self, f: F) -> &Inner {
638                 let r: &EI<'_> = self.0.alloc(EI::I(f()));
639                 if let &EI::I(ref i) = r {
640                     i
641                 } else {
642                     panic!("mismatch");
643                 }
644             }
645             fn alloc_outer<F: Fn() -> Outer<'a>>(&self, f: F) -> &Outer<'_> {
646                 let r: &EI<'_> = self.0.alloc(EI::O(f()));
647                 if let &EI::O(ref o) = r {
648                     o
649                 } else {
650                     panic!("mismatch");
651                 }
652             }
653         }
654
655         let arena = Wrap(TypedArena::default());
656
657         let result = arena.alloc_outer(|| Outer {
658             inner: arena.alloc_inner(|| Inner { value: 10 }),
659         });
660
661         assert_eq!(result.inner.value, 10);
662     }
663
664     #[test]
665     pub fn test_copy() {
666         let arena = TypedArena::default();
667         for _ in 0..100000 {
668             arena.alloc(Point { x: 1, y: 2, z: 3 });
669         }
670     }
671
672     #[bench]
673     pub fn bench_copy(b: &mut Bencher) {
674         let arena = TypedArena::default();
675         b.iter(|| arena.alloc(Point { x: 1, y: 2, z: 3 }))
676     }
677
678     #[bench]
679     pub fn bench_copy_nonarena(b: &mut Bencher) {
680         b.iter(|| {
681             let _: Box<_> = Box::new(Point { x: 1, y: 2, z: 3 });
682         })
683     }
684
685     #[allow(dead_code)]
686     struct Noncopy {
687         string: String,
688         array: Vec<i32>,
689     }
690
691     #[test]
692     pub fn test_noncopy() {
693         let arena = TypedArena::default();
694         for _ in 0..100000 {
695             arena.alloc(Noncopy {
696                 string: "hello world".to_string(),
697                 array: vec![1, 2, 3, 4, 5],
698             });
699         }
700     }
701
702     #[test]
703     pub fn test_typed_arena_zero_sized() {
704         let arena = TypedArena::default();
705         for _ in 0..100000 {
706             arena.alloc(());
707         }
708     }
709
710     #[test]
711     pub fn test_typed_arena_clear() {
712         let mut arena = TypedArena::default();
713         for _ in 0..10 {
714             arena.clear();
715             for _ in 0..10000 {
716                 arena.alloc(Point { x: 1, y: 2, z: 3 });
717             }
718         }
719     }
720
721     #[bench]
722     pub fn bench_typed_arena_clear(b: &mut Bencher) {
723         let mut arena = TypedArena::default();
724         b.iter(|| {
725             arena.alloc(Point { x: 1, y: 2, z: 3 });
726             arena.clear();
727         })
728     }
729
730     // Drop tests
731
732     struct DropCounter<'a> {
733         count: &'a Cell<u32>,
734     }
735
736     impl Drop for DropCounter<'_> {
737         fn drop(&mut self) {
738             self.count.set(self.count.get() + 1);
739         }
740     }
741
742     #[test]
743     fn test_typed_arena_drop_count() {
744         let counter = Cell::new(0);
745         {
746             let arena: TypedArena<DropCounter<'_>> = TypedArena::default();
747             for _ in 0..100 {
748                 // Allocate something with drop glue to make sure it doesn't leak.
749                 arena.alloc(DropCounter { count: &counter });
750             }
751         };
752         assert_eq!(counter.get(), 100);
753     }
754
755     #[test]
756     fn test_typed_arena_drop_on_clear() {
757         let counter = Cell::new(0);
758         let mut arena: TypedArena<DropCounter<'_>> = TypedArena::default();
759         for i in 0..10 {
760             for _ in 0..100 {
761                 // Allocate something with drop glue to make sure it doesn't leak.
762                 arena.alloc(DropCounter { count: &counter });
763             }
764             arena.clear();
765             assert_eq!(counter.get(), i * 100 + 100);
766         }
767     }
768
769     thread_local! {
770         static DROP_COUNTER: Cell<u32> = Cell::new(0)
771     }
772
773     struct SmallDroppable;
774
775     impl Drop for SmallDroppable {
776         fn drop(&mut self) {
777             DROP_COUNTER.with(|c| c.set(c.get() + 1));
778         }
779     }
780
781     #[test]
782     fn test_typed_arena_drop_small_count() {
783         DROP_COUNTER.with(|c| c.set(0));
784         {
785             let arena: TypedArena<SmallDroppable> = TypedArena::default();
786             for _ in 0..100 {
787                 // Allocate something with drop glue to make sure it doesn't leak.
788                 arena.alloc(SmallDroppable);
789             }
790             // dropping
791         };
792         assert_eq!(DROP_COUNTER.with(|c| c.get()), 100);
793     }
794
795     #[bench]
796     pub fn bench_noncopy(b: &mut Bencher) {
797         let arena = TypedArena::default();
798         b.iter(|| {
799             arena.alloc(Noncopy {
800                 string: "hello world".to_string(),
801                 array: vec![1, 2, 3, 4, 5],
802             })
803         })
804     }
805
806     #[bench]
807     pub fn bench_noncopy_nonarena(b: &mut Bencher) {
808         b.iter(|| {
809             let _: Box<_> = Box::new(Noncopy {
810                 string: "hello world".to_string(),
811                 array: vec![1, 2, 3, 4, 5],
812             });
813         })
814     }
815 }