]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_arena/src/lib.rs
Rollup merge of #80887 - camelid:fix-log-color-auto, r=RalfJung
[rust.git] / compiler / rustc_arena / src / 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 several kinds of arena.
9
10 #![doc(
11     html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/",
12     test(no_crate_inject, attr(deny(warnings)))
13 )]
14 #![feature(array_value_iter_slice)]
15 #![feature(dropck_eyepatch)]
16 #![feature(new_uninit)]
17 #![feature(maybe_uninit_slice)]
18 #![feature(array_value_iter)]
19 #![cfg_attr(bootstrap, feature(min_const_generics))]
20 #![feature(min_specialization)]
21 #![cfg_attr(test, feature(test))]
22
23 use smallvec::SmallVec;
24
25 use std::alloc::Layout;
26 use std::cell::{Cell, RefCell};
27 use std::cmp;
28 use std::marker::{PhantomData, Send};
29 use std::mem::{self, MaybeUninit};
30 use std::ptr;
31 use std::slice;
32
33 #[inline(never)]
34 #[cold]
35 pub fn cold_path<F: FnOnce() -> R, R>(f: F) -> R {
36     f()
37 }
38
39 /// An arena that can hold objects of only one type.
40 pub struct TypedArena<T> {
41     /// A pointer to the next object to be allocated.
42     ptr: Cell<*mut T>,
43
44     /// A pointer to the end of the allocated area. When this pointer is
45     /// reached, a new chunk is allocated.
46     end: Cell<*mut T>,
47
48     /// A vector of arena chunks.
49     chunks: RefCell<Vec<TypedArenaChunk<T>>>,
50
51     /// Marker indicating that dropping the arena causes its owned
52     /// instances of `T` to be dropped.
53     _own: PhantomData<T>,
54 }
55
56 struct TypedArenaChunk<T> {
57     /// The raw storage for the arena chunk.
58     storage: Box<[MaybeUninit<T>]>,
59     /// The number of valid entries in the chunk.
60     entries: usize,
61 }
62
63 impl<T> TypedArenaChunk<T> {
64     #[inline]
65     unsafe fn new(capacity: usize) -> TypedArenaChunk<T> {
66         TypedArenaChunk { storage: Box::new_uninit_slice(capacity), entries: 0 }
67     }
68
69     /// Destroys this arena chunk.
70     #[inline]
71     unsafe fn destroy(&mut self, len: usize) {
72         // The branch on needs_drop() is an -O1 performance optimization.
73         // Without the branch, dropping TypedArena<u8> takes linear time.
74         if mem::needs_drop::<T>() {
75             ptr::drop_in_place(MaybeUninit::slice_assume_init_mut(&mut self.storage[..len]));
76         }
77     }
78
79     // Returns a pointer to the first allocated object.
80     #[inline]
81     fn start(&mut self) -> *mut T {
82         MaybeUninit::slice_as_mut_ptr(&mut self.storage)
83     }
84
85     // Returns a pointer to the end of the allocated space.
86     #[inline]
87     fn end(&mut self) -> *mut T {
88         unsafe {
89             if mem::size_of::<T>() == 0 {
90                 // A pointer as large as possible for zero-sized elements.
91                 !0 as *mut T
92             } else {
93                 self.start().add(self.storage.len())
94             }
95         }
96     }
97 }
98
99 // The arenas start with PAGE-sized chunks, and then each new chunk is twice as
100 // big as its predecessor, up until we reach HUGE_PAGE-sized chunks, whereupon
101 // we stop growing. This scales well, from arenas that are barely used up to
102 // arenas that are used for 100s of MiBs. Note also that the chosen sizes match
103 // the usual sizes of pages and huge pages on Linux.
104 const PAGE: usize = 4096;
105 const HUGE_PAGE: usize = 2 * 1024 * 1024;
106
107 impl<T> Default for TypedArena<T> {
108     /// Creates a new `TypedArena`.
109     fn default() -> TypedArena<T> {
110         TypedArena {
111             // We set both `ptr` and `end` to 0 so that the first call to
112             // alloc() will trigger a grow().
113             ptr: Cell::new(ptr::null_mut()),
114             end: Cell::new(ptr::null_mut()),
115             chunks: RefCell::new(vec![]),
116             _own: PhantomData,
117         }
118     }
119 }
120
121 trait IterExt<T> {
122     fn alloc_from_iter(self, arena: &TypedArena<T>) -> &mut [T];
123 }
124
125 impl<I, T> IterExt<T> for I
126 where
127     I: IntoIterator<Item = T>,
128 {
129     #[inline]
130     default fn alloc_from_iter(self, arena: &TypedArena<T>) -> &mut [T] {
131         let vec: SmallVec<[_; 8]> = self.into_iter().collect();
132         vec.alloc_from_iter(arena)
133     }
134 }
135
136 impl<T, const N: usize> IterExt<T> for std::array::IntoIter<T, N> {
137     #[inline]
138     fn alloc_from_iter(self, arena: &TypedArena<T>) -> &mut [T] {
139         let len = self.len();
140         if len == 0 {
141             return &mut [];
142         }
143         // Move the content to the arena by copying and then forgetting it
144         unsafe {
145             let start_ptr = arena.alloc_raw_slice(len);
146             self.as_slice().as_ptr().copy_to_nonoverlapping(start_ptr, len);
147             mem::forget(self);
148             slice::from_raw_parts_mut(start_ptr, len)
149         }
150     }
151 }
152
153 impl<T> IterExt<T> for Vec<T> {
154     #[inline]
155     fn alloc_from_iter(mut self, arena: &TypedArena<T>) -> &mut [T] {
156         let len = self.len();
157         if len == 0 {
158             return &mut [];
159         }
160         // Move the content to the arena by copying and then forgetting it
161         unsafe {
162             let start_ptr = arena.alloc_raw_slice(len);
163             self.as_ptr().copy_to_nonoverlapping(start_ptr, len);
164             self.set_len(0);
165             slice::from_raw_parts_mut(start_ptr, len)
166         }
167     }
168 }
169
170 impl<A: smallvec::Array> IterExt<A::Item> for SmallVec<A> {
171     #[inline]
172     fn alloc_from_iter(mut self, arena: &TypedArena<A::Item>) -> &mut [A::Item] {
173         let len = self.len();
174         if len == 0 {
175             return &mut [];
176         }
177         // Move the content to the arena by copying and then forgetting it
178         unsafe {
179             let start_ptr = arena.alloc_raw_slice(len);
180             self.as_ptr().copy_to_nonoverlapping(start_ptr, len);
181             self.set_len(0);
182             slice::from_raw_parts_mut(start_ptr, len)
183         }
184     }
185 }
186
187 impl<T> TypedArena<T> {
188     /// Allocates an object in the `TypedArena`, returning a reference to it.
189     #[inline]
190     pub fn alloc(&self, object: T) -> &mut T {
191         if self.ptr == self.end {
192             self.grow(1)
193         }
194
195         unsafe {
196             if mem::size_of::<T>() == 0 {
197                 self.ptr.set((self.ptr.get() as *mut u8).wrapping_offset(1) as *mut T);
198                 let ptr = mem::align_of::<T>() as *mut T;
199                 // Don't drop the object. This `write` is equivalent to `forget`.
200                 ptr::write(ptr, object);
201                 &mut *ptr
202             } else {
203                 let ptr = self.ptr.get();
204                 // Advance the pointer.
205                 self.ptr.set(self.ptr.get().offset(1));
206                 // Write into uninitialized memory.
207                 ptr::write(ptr, object);
208                 &mut *ptr
209             }
210         }
211     }
212
213     #[inline]
214     fn can_allocate(&self, additional: usize) -> bool {
215         let available_bytes = self.end.get() as usize - self.ptr.get() as usize;
216         let additional_bytes = additional.checked_mul(mem::size_of::<T>()).unwrap();
217         available_bytes >= additional_bytes
218     }
219
220     /// Ensures there's enough space in the current chunk to fit `len` objects.
221     #[inline]
222     fn ensure_capacity(&self, additional: usize) {
223         if !self.can_allocate(additional) {
224             self.grow(additional);
225             debug_assert!(self.can_allocate(additional));
226         }
227     }
228
229     #[inline]
230     unsafe fn alloc_raw_slice(&self, len: usize) -> *mut T {
231         assert!(mem::size_of::<T>() != 0);
232         assert!(len != 0);
233
234         self.ensure_capacity(len);
235
236         let start_ptr = self.ptr.get();
237         self.ptr.set(start_ptr.add(len));
238         start_ptr
239     }
240
241     /// Allocates a slice of objects that are copied into the `TypedArena`, returning a mutable
242     /// reference to it. Will panic if passed a zero-sized types.
243     ///
244     /// Panics:
245     ///
246     ///  - Zero-sized types
247     ///  - Zero-length slices
248     #[inline]
249     pub fn alloc_slice(&self, slice: &[T]) -> &mut [T]
250     where
251         T: Copy,
252     {
253         unsafe {
254             let len = slice.len();
255             let start_ptr = self.alloc_raw_slice(len);
256             slice.as_ptr().copy_to_nonoverlapping(start_ptr, len);
257             slice::from_raw_parts_mut(start_ptr, len)
258         }
259     }
260
261     #[inline]
262     pub fn alloc_from_iter<I: IntoIterator<Item = T>>(&self, iter: I) -> &mut [T] {
263         assert!(mem::size_of::<T>() != 0);
264         iter.alloc_from_iter(self)
265     }
266
267     /// Grows the arena.
268     #[inline(never)]
269     #[cold]
270     fn grow(&self, additional: usize) {
271         unsafe {
272             // We need the element size to convert chunk sizes (ranging from
273             // PAGE to HUGE_PAGE bytes) to element counts.
274             let elem_size = cmp::max(1, mem::size_of::<T>());
275             let mut chunks = self.chunks.borrow_mut();
276             let mut new_cap;
277             if let Some(last_chunk) = chunks.last_mut() {
278                 // If a type is `!needs_drop`, we don't need to keep track of how many elements
279                 // the chunk stores - the field will be ignored anyway.
280                 if mem::needs_drop::<T>() {
281                     let used_bytes = self.ptr.get() as usize - last_chunk.start() as usize;
282                     last_chunk.entries = used_bytes / mem::size_of::<T>();
283                 }
284
285                 // If the previous chunk's len is less than HUGE_PAGE
286                 // bytes, then this chunk will be least double the previous
287                 // chunk's size.
288                 new_cap = last_chunk.storage.len().min(HUGE_PAGE / elem_size / 2);
289                 new_cap *= 2;
290             } else {
291                 new_cap = PAGE / elem_size;
292             }
293             // Also ensure that this chunk can fit `additional`.
294             new_cap = cmp::max(additional, new_cap);
295
296             let mut chunk = TypedArenaChunk::<T>::new(new_cap);
297             self.ptr.set(chunk.start());
298             self.end.set(chunk.end());
299             chunks.push(chunk);
300         }
301     }
302
303     /// Clears the arena. Deallocates all but the longest chunk which may be reused.
304     pub fn clear(&mut self) {
305         unsafe {
306             // Clear the last chunk, which is partially filled.
307             let mut chunks_borrow = self.chunks.borrow_mut();
308             if let Some(mut last_chunk) = chunks_borrow.last_mut() {
309                 self.clear_last_chunk(&mut last_chunk);
310                 let len = chunks_borrow.len();
311                 // If `T` is ZST, code below has no effect.
312                 for mut chunk in chunks_borrow.drain(..len - 1) {
313                     chunk.destroy(chunk.entries);
314                 }
315             }
316         }
317     }
318
319     // Drops the contents of the last chunk. The last chunk is partially empty, unlike all other
320     // chunks.
321     fn clear_last_chunk(&self, last_chunk: &mut TypedArenaChunk<T>) {
322         // Determine how much was filled.
323         let start = last_chunk.start() as usize;
324         // We obtain the value of the pointer to the first uninitialized element.
325         let end = self.ptr.get() as usize;
326         // We then calculate the number of elements to be dropped in the last chunk,
327         // which is the filled area's length.
328         let diff = if mem::size_of::<T>() == 0 {
329             // `T` is ZST. It can't have a drop flag, so the value here doesn't matter. We get
330             // the number of zero-sized values in the last and only chunk, just out of caution.
331             // Recall that `end` was incremented for each allocated value.
332             end - start
333         } else {
334             (end - start) / mem::size_of::<T>()
335         };
336         // Pass that to the `destroy` method.
337         unsafe {
338             last_chunk.destroy(diff);
339         }
340         // Reset the chunk.
341         self.ptr.set(last_chunk.start());
342     }
343 }
344
345 unsafe impl<#[may_dangle] T> Drop for TypedArena<T> {
346     fn drop(&mut self) {
347         unsafe {
348             // Determine how much was filled.
349             let mut chunks_borrow = self.chunks.borrow_mut();
350             if let Some(mut last_chunk) = chunks_borrow.pop() {
351                 // Drop the contents of the last chunk.
352                 self.clear_last_chunk(&mut last_chunk);
353                 // The last chunk will be dropped. Destroy all other chunks.
354                 for chunk in chunks_borrow.iter_mut() {
355                     chunk.destroy(chunk.entries);
356                 }
357             }
358             // Box handles deallocation of `last_chunk` and `self.chunks`.
359         }
360     }
361 }
362
363 unsafe impl<T: Send> Send for TypedArena<T> {}
364
365 pub struct DroplessArena {
366     /// A pointer to the start of the free space.
367     start: Cell<*mut u8>,
368
369     /// A pointer to the end of free space.
370     ///
371     /// The allocation proceeds from the end of the chunk towards the start.
372     /// When this pointer crosses the start pointer, a new chunk is allocated.
373     end: Cell<*mut u8>,
374
375     /// A vector of arena chunks.
376     chunks: RefCell<Vec<TypedArenaChunk<u8>>>,
377 }
378
379 unsafe impl Send for DroplessArena {}
380
381 impl Default for DroplessArena {
382     #[inline]
383     fn default() -> DroplessArena {
384         DroplessArena {
385             start: Cell::new(ptr::null_mut()),
386             end: Cell::new(ptr::null_mut()),
387             chunks: Default::default(),
388         }
389     }
390 }
391
392 impl DroplessArena {
393     #[inline(never)]
394     #[cold]
395     fn grow(&self, additional: usize) {
396         unsafe {
397             let mut chunks = self.chunks.borrow_mut();
398             let mut new_cap;
399             if let Some(last_chunk) = chunks.last_mut() {
400                 // There is no need to update `last_chunk.entries` because that
401                 // field isn't used by `DroplessArena`.
402
403                 // If the previous chunk's len is less than HUGE_PAGE
404                 // bytes, then this chunk will be least double the previous
405                 // chunk's size.
406                 new_cap = last_chunk.storage.len().min(HUGE_PAGE / 2);
407                 new_cap *= 2;
408             } else {
409                 new_cap = PAGE;
410             }
411             // Also ensure that this chunk can fit `additional`.
412             new_cap = cmp::max(additional, new_cap);
413
414             let mut chunk = TypedArenaChunk::<u8>::new(new_cap);
415             self.start.set(chunk.start());
416             self.end.set(chunk.end());
417             chunks.push(chunk);
418         }
419     }
420
421     /// Allocates a byte slice with specified layout from the current memory
422     /// chunk. Returns `None` if there is no free space left to satisfy the
423     /// request.
424     #[inline]
425     fn alloc_raw_without_grow(&self, layout: Layout) -> Option<*mut u8> {
426         let start = self.start.get() as usize;
427         let end = self.end.get() as usize;
428
429         let align = layout.align();
430         let bytes = layout.size();
431
432         let new_end = end.checked_sub(bytes)? & !(align - 1);
433         if start <= new_end {
434             let new_end = new_end as *mut u8;
435             self.end.set(new_end);
436             Some(new_end)
437         } else {
438             None
439         }
440     }
441
442     #[inline]
443     pub fn alloc_raw(&self, layout: Layout) -> *mut u8 {
444         assert!(layout.size() != 0);
445         loop {
446             if let Some(a) = self.alloc_raw_without_grow(layout) {
447                 break a;
448             }
449             // No free space left. Allocate a new chunk to satisfy the request.
450             // On failure the grow will panic or abort.
451             self.grow(layout.size());
452         }
453     }
454
455     #[inline]
456     pub fn alloc<T>(&self, object: T) -> &mut T {
457         assert!(!mem::needs_drop::<T>());
458
459         let mem = self.alloc_raw(Layout::for_value::<T>(&object)) as *mut T;
460
461         unsafe {
462             // Write into uninitialized memory.
463             ptr::write(mem, object);
464             &mut *mem
465         }
466     }
467
468     /// Allocates a slice of objects that are copied into the `DroplessArena`, returning a mutable
469     /// reference to it. Will panic if passed a zero-sized type.
470     ///
471     /// Panics:
472     ///
473     ///  - Zero-sized types
474     ///  - Zero-length slices
475     #[inline]
476     pub fn alloc_slice<T>(&self, slice: &[T]) -> &mut [T]
477     where
478         T: Copy,
479     {
480         assert!(!mem::needs_drop::<T>());
481         assert!(mem::size_of::<T>() != 0);
482         assert!(!slice.is_empty());
483
484         let mem = self.alloc_raw(Layout::for_value::<[T]>(slice)) as *mut T;
485
486         unsafe {
487             mem.copy_from_nonoverlapping(slice.as_ptr(), slice.len());
488             slice::from_raw_parts_mut(mem, slice.len())
489         }
490     }
491
492     #[inline]
493     unsafe fn write_from_iter<T, I: Iterator<Item = T>>(
494         &self,
495         mut iter: I,
496         len: usize,
497         mem: *mut T,
498     ) -> &mut [T] {
499         let mut i = 0;
500         // Use a manual loop since LLVM manages to optimize it better for
501         // slice iterators
502         loop {
503             let value = iter.next();
504             if i >= len || value.is_none() {
505                 // We only return as many items as the iterator gave us, even
506                 // though it was supposed to give us `len`
507                 return slice::from_raw_parts_mut(mem, i);
508             }
509             ptr::write(mem.add(i), value.unwrap());
510             i += 1;
511         }
512     }
513
514     #[inline]
515     pub fn alloc_from_iter<T, I: IntoIterator<Item = T>>(&self, iter: I) -> &mut [T] {
516         let iter = iter.into_iter();
517         assert!(mem::size_of::<T>() != 0);
518         assert!(!mem::needs_drop::<T>());
519
520         let size_hint = iter.size_hint();
521
522         match size_hint {
523             (min, Some(max)) if min == max => {
524                 // We know the exact number of elements the iterator will produce here
525                 let len = min;
526
527                 if len == 0 {
528                     return &mut [];
529                 }
530
531                 let mem = self.alloc_raw(Layout::array::<T>(len).unwrap()) as *mut T;
532                 unsafe { self.write_from_iter(iter, len, mem) }
533             }
534             (_, _) => {
535                 cold_path(move || -> &mut [T] {
536                     let mut vec: SmallVec<[_; 8]> = iter.collect();
537                     if vec.is_empty() {
538                         return &mut [];
539                     }
540                     // Move the content to the arena by copying it and then forgetting
541                     // the content of the SmallVec
542                     unsafe {
543                         let len = vec.len();
544                         let start_ptr =
545                             self.alloc_raw(Layout::for_value::<[T]>(vec.as_slice())) as *mut T;
546                         vec.as_ptr().copy_to_nonoverlapping(start_ptr, len);
547                         vec.set_len(0);
548                         slice::from_raw_parts_mut(start_ptr, len)
549                     }
550                 })
551             }
552         }
553     }
554 }
555
556 /// Calls the destructor for an object when dropped.
557 struct DropType {
558     drop_fn: unsafe fn(*mut u8),
559     obj: *mut u8,
560 }
561
562 unsafe fn drop_for_type<T>(to_drop: *mut u8) {
563     std::ptr::drop_in_place(to_drop as *mut T)
564 }
565
566 impl Drop for DropType {
567     fn drop(&mut self) {
568         unsafe { (self.drop_fn)(self.obj) }
569     }
570 }
571
572 /// An arena which can be used to allocate any type.
573 /// Allocating in this arena is unsafe since the type system
574 /// doesn't know which types it contains. In order to
575 /// allocate safely, you must store a PhantomData<T>
576 /// alongside this arena for each type T you allocate.
577 #[derive(Default)]
578 pub struct DropArena {
579     /// A list of destructors to run when the arena drops.
580     /// Ordered so `destructors` gets dropped before the arena
581     /// since its destructor can reference memory in the arena.
582     destructors: RefCell<Vec<DropType>>,
583     arena: DroplessArena,
584 }
585
586 impl DropArena {
587     #[inline]
588     pub unsafe fn alloc<T>(&self, object: T) -> &mut T {
589         let mem = self.arena.alloc_raw(Layout::new::<T>()) as *mut T;
590         // Write into uninitialized memory.
591         ptr::write(mem, object);
592         let result = &mut *mem;
593         // Record the destructor after doing the allocation as that may panic
594         // and would cause `object`'s destructor to run twice if it was recorded before
595         self.destructors
596             .borrow_mut()
597             .push(DropType { drop_fn: drop_for_type::<T>, obj: result as *mut T as *mut u8 });
598         result
599     }
600
601     #[inline]
602     pub unsafe fn alloc_from_iter<T, I: IntoIterator<Item = T>>(&self, iter: I) -> &mut [T] {
603         let mut vec: SmallVec<[_; 8]> = iter.into_iter().collect();
604         if vec.is_empty() {
605             return &mut [];
606         }
607         let len = vec.len();
608
609         let start_ptr = self.arena.alloc_raw(Layout::array::<T>(len).unwrap()) as *mut T;
610
611         let mut destructors = self.destructors.borrow_mut();
612         // Reserve space for the destructors so we can't panic while adding them
613         destructors.reserve(len);
614
615         // Move the content to the arena by copying it and then forgetting
616         // the content of the SmallVec
617         vec.as_ptr().copy_to_nonoverlapping(start_ptr, len);
618         mem::forget(vec.drain(..));
619
620         // Record the destructors after doing the allocation as that may panic
621         // and would cause `object`'s destructor to run twice if it was recorded before
622         for i in 0..len {
623             destructors
624                 .push(DropType { drop_fn: drop_for_type::<T>, obj: start_ptr.add(i) as *mut u8 });
625         }
626
627         slice::from_raw_parts_mut(start_ptr, len)
628     }
629 }
630
631 #[macro_export]
632 macro_rules! arena_for_type {
633     ([][$ty:ty]) => {
634         $crate::TypedArena<$ty>
635     };
636     ([few $(, $attrs:ident)*][$ty:ty]) => {
637         ::std::marker::PhantomData<$ty>
638     };
639     ([$ignore:ident $(, $attrs:ident)*]$args:tt) => {
640         $crate::arena_for_type!([$($attrs),*]$args)
641     };
642 }
643
644 #[macro_export]
645 macro_rules! which_arena_for_type {
646     ([][$arena:expr]) => {
647         ::std::option::Option::Some($arena)
648     };
649     ([few$(, $attrs:ident)*][$arena:expr]) => {
650         ::std::option::Option::None
651     };
652     ([$ignore:ident$(, $attrs:ident)*]$args:tt) => {
653         $crate::which_arena_for_type!([$($attrs),*]$args)
654     };
655 }
656
657 #[macro_export]
658 macro_rules! declare_arena {
659     ([], [$($a:tt $name:ident: $ty:ty,)*], $tcx:lifetime) => {
660         #[derive(Default)]
661         pub struct Arena<$tcx> {
662             pub dropless: $crate::DroplessArena,
663             drop: $crate::DropArena,
664             $($name: $crate::arena_for_type!($a[$ty]),)*
665         }
666
667         pub trait ArenaAllocatable<'tcx, T = Self>: Sized {
668             fn allocate_on<'a>(self, arena: &'a Arena<'tcx>) -> &'a mut Self;
669             fn allocate_from_iter<'a>(
670                 arena: &'a Arena<'tcx>,
671                 iter: impl ::std::iter::IntoIterator<Item = Self>,
672             ) -> &'a mut [Self];
673         }
674
675         impl<'tcx, T: Copy> ArenaAllocatable<'tcx, ()> for T {
676             #[inline]
677             fn allocate_on<'a>(self, arena: &'a Arena<'tcx>) -> &'a mut Self {
678                 arena.dropless.alloc(self)
679             }
680             #[inline]
681             fn allocate_from_iter<'a>(
682                 arena: &'a Arena<'tcx>,
683                 iter: impl ::std::iter::IntoIterator<Item = Self>,
684             ) -> &'a mut [Self] {
685                 arena.dropless.alloc_from_iter(iter)
686             }
687
688         }
689         $(
690             impl<$tcx> ArenaAllocatable<$tcx, $ty> for $ty {
691                 #[inline]
692                 fn allocate_on<'a>(self, arena: &'a Arena<$tcx>) -> &'a mut Self {
693                     if !::std::mem::needs_drop::<Self>() {
694                         return arena.dropless.alloc(self);
695                     }
696                     match $crate::which_arena_for_type!($a[&arena.$name]) {
697                         ::std::option::Option::<&$crate::TypedArena<Self>>::Some(ty_arena) => {
698                             ty_arena.alloc(self)
699                         }
700                         ::std::option::Option::None => unsafe { arena.drop.alloc(self) },
701                     }
702                 }
703
704                 #[inline]
705                 fn allocate_from_iter<'a>(
706                     arena: &'a Arena<$tcx>,
707                     iter: impl ::std::iter::IntoIterator<Item = Self>,
708                 ) -> &'a mut [Self] {
709                     if !::std::mem::needs_drop::<Self>() {
710                         return arena.dropless.alloc_from_iter(iter);
711                     }
712                     match $crate::which_arena_for_type!($a[&arena.$name]) {
713                         ::std::option::Option::<&$crate::TypedArena<Self>>::Some(ty_arena) => {
714                             ty_arena.alloc_from_iter(iter)
715                         }
716                         ::std::option::Option::None => unsafe { arena.drop.alloc_from_iter(iter) },
717                     }
718                 }
719             }
720         )*
721
722         impl<'tcx> Arena<'tcx> {
723             #[inline]
724             pub fn alloc<T: ArenaAllocatable<'tcx, U>, U>(&self, value: T) -> &mut T {
725                 value.allocate_on(self)
726             }
727
728             #[inline]
729             pub fn alloc_slice<T: ::std::marker::Copy>(&self, value: &[T]) -> &mut [T] {
730                 if value.is_empty() {
731                     return &mut [];
732                 }
733                 self.dropless.alloc_slice(value)
734             }
735
736             pub fn alloc_from_iter<'a, T: ArenaAllocatable<'tcx, U>, U>(
737                 &'a self,
738                 iter: impl ::std::iter::IntoIterator<Item = T>,
739             ) -> &'a mut [T] {
740                 T::allocate_from_iter(self, iter)
741             }
742         }
743     }
744 }
745
746 #[cfg(test)]
747 mod tests;