Skip to main content

rustc_arena/
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// tidy-alphabetical-start
11#![allow(clippy::mut_from_ref)] // Arena allocators are one place where this pattern is fine.
12#![allow(internal_features)]
13#![cfg_attr(bootstrap, feature(unwrap_infallible))]
14#![cfg_attr(test, feature(test))]
15#![deny(unsafe_op_in_unsafe_fn)]
16#![doc(test(no_crate_inject, attr(deny(warnings))))]
17#![feature(decl_macro)]
18#![feature(dropck_eyepatch)]
19#![feature(rustc_attrs)]
20// tidy-alphabetical-end
21
22use std::alloc::Layout;
23use std::cell::{Cell, RefCell};
24use std::marker::PhantomData;
25use std::mem::{self, MaybeUninit};
26use std::ptr::{self, NonNull};
27use std::{cmp, hint, slice};
28
29use smallvec::SmallVec;
30
31/// This calls the passed function while ensuring it won't be inlined into the caller.
32#[inline(never)]
33#[cold]
34fn outline<F: FnOnce() -> R, R>(f: F) -> R {
35    f()
36}
37
38struct ArenaChunk<T = u8> {
39    /// The raw storage for the arena chunk.
40    storage: NonNull<[MaybeUninit<T>]>,
41    /// The number of valid entries in the chunk.
42    entries: usize,
43}
44
45unsafe impl<#[may_dangle] T> Drop for ArenaChunk<T> {
46    fn drop(&mut self) {
47        unsafe { drop(Box::from_raw(self.storage.as_mut())) }
48    }
49}
50
51impl<T> ArenaChunk<T> {
52    #[inline]
53    unsafe fn new(capacity: usize) -> ArenaChunk<T> {
54        ArenaChunk { storage: Box::into_non_null(Box::new_uninit_slice(capacity)), entries: 0 }
55    }
56
57    /// Destroys this arena chunk.
58    ///
59    /// # Safety
60    ///
61    /// The caller must ensure that `len` elements of this chunk have been initialized.
62    #[inline]
63    unsafe fn destroy(&mut self, len: usize) {
64        // The branch on needs_drop() is an -O1 performance optimization.
65        // Without the branch, dropping TypedArena<T> takes linear time.
66        if mem::needs_drop::<T>() {
67            // SAFETY: The caller must ensure that `len` elements of this chunk have
68            // been initialized.
69            unsafe {
70                let slice = self.storage.as_mut();
71                slice[..len].assume_init_drop();
72            }
73        }
74    }
75
76    // Returns a pointer to the first allocated object.
77    #[inline]
78    fn start(&mut self) -> *mut T {
79        self.storage.as_ptr() as *mut T
80    }
81
82    // Returns a pointer to the end of the allocated space.
83    #[inline]
84    fn end(&mut self) -> *mut T {
85        unsafe {
86            if size_of::<T>() == 0 {
87                // A pointer as large as possible for zero-sized elements.
88                ptr::without_provenance_mut(!0)
89            } else {
90                self.start().add(self.storage.len())
91            }
92        }
93    }
94}
95
96// The arenas start with PAGE-sized chunks, and then each new chunk is twice as
97// big as its predecessor, up until we reach HUGE_PAGE-sized chunks, whereupon
98// we stop growing. This scales well, from arenas that are barely used up to
99// arenas that are used for 100s of MiBs. Note also that the chosen sizes match
100// the usual sizes of pages and huge pages on Linux.
101const PAGE: usize = 4096;
102const HUGE_PAGE: usize = 2 * 1024 * 1024;
103
104/// An arena that can hold objects of only one type.
105pub struct TypedArena<T> {
106    /// A pointer to the next object to be allocated.
107    ptr: Cell<*mut T>,
108
109    /// A pointer to the end of the allocated area. When this pointer is
110    /// reached, a new chunk is allocated.
111    end: Cell<*mut T>,
112
113    /// A vector of arena chunks.
114    chunks: RefCell<Vec<ArenaChunk<T>>>,
115
116    /// Marker indicating that dropping the arena causes its owned
117    /// instances of `T` to be dropped.
118    _own: PhantomData<T>,
119}
120
121impl<T> Default for TypedArena<T> {
122    /// Creates a new `TypedArena`.
123    fn default() -> TypedArena<T> {
124        TypedArena {
125            // We set both `ptr` and `end` to 0 so that the first call to
126            // alloc() will trigger a grow().
127            ptr: Cell::new(ptr::null_mut()),
128            end: Cell::new(ptr::null_mut()),
129            chunks: Default::default(),
130            _own: PhantomData,
131        }
132    }
133}
134
135impl<T> TypedArena<T> {
136    /// Allocates an object in the `TypedArena`, returning a reference to it.
137    #[inline]
138    pub fn alloc(&self, object: T) -> &mut T {
139        if !(size_of::<T>() != 0) {
    ::core::panicking::panic("assertion failed: size_of::<T>() != 0")
};assert!(size_of::<T>() != 0);
140
141        if self.ptr == self.end {
142            self.grow(1)
143        }
144
145        unsafe {
146            let ptr = self.ptr.get();
147            // Advance the pointer.
148            self.ptr.set(self.ptr.get().add(1));
149            // Write into uninitialized memory.
150            ptr::write(ptr, object);
151            &mut *ptr
152        }
153    }
154
155    #[inline]
156    fn can_allocate(&self, additional: usize) -> bool {
157        // FIXME: this should *likely* use `offset_from`, but more
158        // investigation is needed (including running tests in miri).
159        let available_bytes = self.end.get().addr() - self.ptr.get().addr();
160        let additional_bytes = additional.checked_mul(size_of::<T>()).unwrap();
161        available_bytes >= additional_bytes
162    }
163
164    /// Allocates storage for `len >= 1` values in this arena, and returns a
165    /// raw pointer to the first value's storage.
166    ///
167    /// # Safety
168    ///
169    /// Caller must initialize each of the `len` slots to a droppable value
170    /// before the arena is dropped.
171    ///
172    /// In practice, this typically means that the caller must be able to
173    /// raw-copy `len` already-initialized values into the slice without any
174    /// possibility of panicking.
175    ///
176    /// FIXME(Zalathar): This is *very* fragile; perhaps we need a different
177    /// approach to arena-allocating slices of droppable values.
178    #[inline]
179    unsafe fn alloc_raw_slice(&self, len: usize) -> *mut T {
180        if !(size_of::<T>() != 0) {
    ::core::panicking::panic("assertion failed: size_of::<T>() != 0")
};assert!(size_of::<T>() != 0);
181        if !(len != 0) { ::core::panicking::panic("assertion failed: len != 0") };assert!(len != 0);
182
183        // Ensure the current chunk can fit `len` objects.
184        if !self.can_allocate(len) {
185            self.grow(len);
186            if true {
    if !self.can_allocate(len) {
        ::core::panicking::panic("assertion failed: self.can_allocate(len)")
    };
};debug_assert!(self.can_allocate(len));
187        }
188
189        let start_ptr = self.ptr.get();
190        // SAFETY: `can_allocate`/`grow` ensures that there is enough space for
191        // `len` elements.
192        unsafe { self.ptr.set(start_ptr.add(len)) };
193        start_ptr
194    }
195
196    /// Allocates the elements of this iterator into a contiguous slice in the `TypedArena`.
197    ///
198    /// Note: for reasons of reentrancy and panic safety we collect into a `SmallVec<[_; 8]>` before
199    /// storing the elements in the arena.
200    #[inline]
201    pub fn alloc_from_iter<I: IntoIterator<Item = T>>(&self, iter: I) -> &mut [T] {
202        self.try_alloc_from_iter(iter.into_iter().map(Ok::<T, !>)).into_ok()
203    }
204
205    /// Allocates the elements of this iterator into a contiguous slice in the `TypedArena`.
206    ///
207    /// Note: for reasons of reentrancy and panic safety we collect into a `SmallVec<[_; 8]>` before
208    /// storing the elements in the arena.
209    #[inline]
210    pub fn try_alloc_from_iter<E>(
211        &self,
212        iter: impl IntoIterator<Item = Result<T, E>>,
213    ) -> Result<&mut [T], E> {
214        // Despite the similarity with `DroplessArena`, we cannot reuse their fast case. The reason
215        // is subtle: these arenas are reentrant. In other words, `iter` may very well be holding a
216        // reference to `self` and adding elements to the arena during iteration.
217        //
218        // For this reason, if we pre-allocated any space for the elements of this iterator, we'd
219        // have to track that some uninitialized elements are followed by some initialized elements,
220        // else we might accidentally drop uninitialized memory if something panics or if the
221        // iterator doesn't fill all the length we expected.
222        //
223        // So we collect all the elements beforehand, which takes care of reentrancy and panic
224        // safety. This function is much less hot than `DroplessArena::alloc_from_iter`, so it
225        // doesn't need to be hyper-optimized.
226        if !(size_of::<T>() != 0) {
    ::core::panicking::panic("assertion failed: size_of::<T>() != 0")
};assert!(size_of::<T>() != 0);
227
228        let vec: Result<SmallVec<[T; 8]>, E> = iter.into_iter().collect();
229        let mut vec = vec?;
230        if vec.is_empty() {
231            return Ok(&mut []);
232        }
233        // Move the content to the arena by copying and then forgetting it.
234        let len = vec.len();
235
236        // SAFETY: After allocating raw storage for exactly `len` values, we
237        // must fully initialize the storage without panicking, and we must
238        // also prevent the stale values in the vec from being dropped.
239        Ok(unsafe {
240            let start_ptr = self.alloc_raw_slice(len);
241            // Initialize the newly-allocated storage without panicking.
242            vec.as_ptr().copy_to_nonoverlapping(start_ptr, len);
243            // Prevent the stale values in the vec from being dropped.
244            vec.set_len(0);
245            slice::from_raw_parts_mut(start_ptr, len)
246        })
247    }
248
249    /// Grows the arena.
250    #[inline(never)]
251    #[cold]
252    fn grow(&self, additional: usize) {
253        unsafe {
254            // We need the element size to convert chunk sizes (ranging from
255            // PAGE to HUGE_PAGE bytes) to element counts.
256            let elem_size = cmp::max(1, size_of::<T>());
257            let mut chunks = self.chunks.borrow_mut();
258            let mut new_cap;
259            if let Some(last_chunk) = chunks.last_mut() {
260                // If a type is `!needs_drop`, we don't need to keep track of how many elements
261                // the chunk stores - the field will be ignored anyway.
262                if mem::needs_drop::<T>() {
263                    // FIXME: this should *likely* use `offset_from`, but more
264                    // investigation is needed (including running tests in miri).
265                    let used_bytes = self.ptr.get().addr() - last_chunk.start().addr();
266                    last_chunk.entries = used_bytes / size_of::<T>();
267                }
268
269                // If the previous chunk's len is less than HUGE_PAGE
270                // bytes, then this chunk will be least double the previous
271                // chunk's size.
272                new_cap = last_chunk.storage.len().min(HUGE_PAGE / elem_size / 2);
273                new_cap *= 2;
274            } else {
275                new_cap = PAGE / elem_size;
276            }
277            // Also ensure that this chunk can fit `additional`.
278            new_cap = cmp::max(additional, new_cap);
279
280            let chunk = chunks.push_mut(ArenaChunk::<T>::new(new_cap));
281            self.ptr.set(chunk.start());
282            self.end.set(chunk.end());
283        }
284    }
285
286    // Drops the contents of the last chunk. The last chunk is partially empty, unlike all other
287    // chunks.
288    fn clear_last_chunk(&self, last_chunk: &mut ArenaChunk<T>) {
289        // Determine how much was filled.
290        let start = last_chunk.start().addr();
291        // We obtain the value of the pointer to the first uninitialized element.
292        let end = self.ptr.get().addr();
293        // We then calculate the number of elements to be dropped in the last chunk,
294        // which is the filled area's length.
295        {
    match (&size_of::<T>(), &0) {
        (left_val, right_val) => {
            if *left_val == *right_val {
                let kind = ::core::panicking::AssertKind::Ne;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_ne!(size_of::<T>(), 0);
296        // FIXME: this should *likely* use `offset_from`, but more
297        // investigation is needed (including running tests in miri).
298        let diff = (end - start) / size_of::<T>();
299        // Pass that to the `destroy` method.
300        unsafe {
301            last_chunk.destroy(diff);
302        }
303        // Reset the chunk.
304        self.ptr.set(last_chunk.start());
305    }
306}
307
308unsafe impl<#[may_dangle] T> Drop for TypedArena<T> {
309    fn drop(&mut self) {
310        unsafe {
311            // Determine how much was filled.
312            let mut chunks_borrow = self.chunks.borrow_mut();
313            if let Some(mut last_chunk) = chunks_borrow.pop() {
314                // Drop the contents of the last chunk.
315                self.clear_last_chunk(&mut last_chunk);
316                // The last chunk will be dropped. Destroy all other chunks.
317                for chunk in chunks_borrow.iter_mut() {
318                    chunk.destroy(chunk.entries);
319                }
320            }
321            // Box handles deallocation of `last_chunk` and `self.chunks`.
322        }
323    }
324}
325
326unsafe impl<T: Send> Send for TypedArena<T> {}
327
328#[inline(always)]
329fn align_down(val: usize, align: usize) -> usize {
330    if true {
    if !align.is_power_of_two() {
        ::core::panicking::panic("assertion failed: align.is_power_of_two()")
    };
};debug_assert!(align.is_power_of_two());
331    val & !(align - 1)
332}
333
334#[inline(always)]
335fn align_up(val: usize, align: usize) -> usize {
336    if true {
    if !align.is_power_of_two() {
        ::core::panicking::panic("assertion failed: align.is_power_of_two()")
    };
};debug_assert!(align.is_power_of_two());
337    (val + align - 1) & !(align - 1)
338}
339
340// Pointer alignment is common in compiler types, so keep `DroplessArena` aligned to them
341// to optimize away alignment code.
342const DROPLESS_ALIGNMENT: usize = align_of::<usize>();
343
344/// An arena that can hold objects of multiple different types that impl `Copy`
345/// and/or satisfy `!mem::needs_drop`.
346pub struct DroplessArena {
347    /// A pointer to the start of the free space.
348    start: Cell<*mut u8>,
349
350    /// A pointer to the end of free space.
351    ///
352    /// The allocation proceeds downwards from the end of the chunk towards the
353    /// start. (This is slightly simpler and faster than allocating upwards,
354    /// see <https://fitzgeraldnick.com/2019/11/01/always-bump-downwards.html>.)
355    /// When this pointer crosses the start pointer, a new chunk is allocated.
356    ///
357    /// This is kept aligned to DROPLESS_ALIGNMENT.
358    end: Cell<*mut u8>,
359
360    /// A vector of arena chunks.
361    chunks: RefCell<Vec<ArenaChunk>>,
362}
363
364unsafe impl Send for DroplessArena {}
365
366impl Default for DroplessArena {
367    #[inline]
368    fn default() -> DroplessArena {
369        DroplessArena {
370            // We set both `start` and `end` to 0 so that the first call to
371            // alloc() will trigger a grow().
372            start: Cell::new(ptr::null_mut()),
373            end: Cell::new(ptr::null_mut()),
374            chunks: Default::default(),
375        }
376    }
377}
378
379impl DroplessArena {
380    #[inline(never)]
381    #[cold]
382    fn grow(&self, layout: Layout) {
383        // Add some padding so we can align `self.end` while
384        // still fitting in a `layout` allocation.
385        let additional = layout.size() + cmp::max(DROPLESS_ALIGNMENT, layout.align()) - 1;
386
387        unsafe {
388            let mut chunks = self.chunks.borrow_mut();
389            let mut new_cap;
390            if let Some(last_chunk) = chunks.last_mut() {
391                // There is no need to update `last_chunk.entries` because that
392                // field isn't used by `DroplessArena`.
393
394                // If the previous chunk's len is less than HUGE_PAGE
395                // bytes, then this chunk will be least double the previous
396                // chunk's size.
397                new_cap = last_chunk.storage.len().min(HUGE_PAGE / 2);
398                new_cap *= 2;
399            } else {
400                new_cap = PAGE;
401            }
402            // Also ensure that this chunk can fit `additional`.
403            new_cap = cmp::max(additional, new_cap);
404
405            let chunk = chunks.push_mut(ArenaChunk::new(align_up(new_cap, PAGE)));
406            self.start.set(chunk.start());
407
408            // Align the end to DROPLESS_ALIGNMENT.
409            let end = align_down(chunk.end().addr(), DROPLESS_ALIGNMENT);
410
411            // Make sure we don't go past `start`. This should not happen since the allocation
412            // should be at least DROPLESS_ALIGNMENT - 1 bytes.
413            if true {
    if !(chunk.start().addr() <= end) {
        ::core::panicking::panic("assertion failed: chunk.start().addr() <= end")
    };
};debug_assert!(chunk.start().addr() <= end);
414
415            self.end.set(chunk.end().with_addr(end));
416        }
417    }
418
419    #[inline]
420    pub fn alloc_raw(&self, layout: Layout) -> *mut u8 {
421        if !(layout.size() != 0) {
    ::core::panicking::panic("assertion failed: layout.size() != 0")
};assert!(layout.size() != 0);
422
423        // This loop executes once or twice: if allocation fails the first
424        // time, the `grow` ensures it will succeed the second time.
425        loop {
426            let start = self.start.get().addr();
427            let old_end = self.end.get();
428            let end = old_end.addr();
429
430            // Align allocated bytes so that `self.end` stays aligned to
431            // DROPLESS_ALIGNMENT.
432            let bytes = align_up(layout.size(), DROPLESS_ALIGNMENT);
433
434            // Tell LLVM that `end` is aligned to DROPLESS_ALIGNMENT.
435            unsafe { hint::assert_unchecked(end == align_down(end, DROPLESS_ALIGNMENT)) };
436
437            if let Some(sub) = end.checked_sub(bytes) {
438                let new_end = align_down(sub, layout.align());
439                if start <= new_end {
440                    let new_end = old_end.with_addr(new_end);
441                    // `new_end` is aligned to DROPLESS_ALIGNMENT as `align_down`
442                    // preserves alignment as both `end` and `bytes` are already
443                    // aligned to DROPLESS_ALIGNMENT.
444                    self.end.set(new_end);
445                    return new_end;
446                }
447            }
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);
452        }
453    }
454
455    #[inline]
456    pub fn alloc<T>(&self, object: T) -> &mut T {
457        if !!mem::needs_drop::<T>() {
    ::core::panicking::panic("assertion failed: !mem::needs_drop::<T>()")
};assert!(!mem::needs_drop::<T>());
458        if !(size_of::<T>() != 0) {
    ::core::panicking::panic("assertion failed: size_of::<T>() != 0")
};assert!(size_of::<T>() != 0);
459
460        let mem = self.alloc_raw(Layout::new::<T>()) as *mut T;
461
462        unsafe {
463            // Write into uninitialized memory.
464            ptr::write(mem, object);
465            &mut *mem
466        }
467    }
468
469    /// Allocates a slice of objects that are copied into the `DroplessArena`, returning a mutable
470    /// reference to it. Will panic if passed a zero-sized type.
471    ///
472    /// Panics:
473    ///
474    ///  - Zero-sized types
475    ///  - Zero-length slices
476    #[inline]
477    pub fn alloc_slice<T>(&self, slice: &[T]) -> &mut [T]
478    where
479        T: Copy,
480    {
481        if !!mem::needs_drop::<T>() {
    ::core::panicking::panic("assertion failed: !mem::needs_drop::<T>()")
};assert!(!mem::needs_drop::<T>());
482        if !(size_of::<T>() != 0) {
    ::core::panicking::panic("assertion failed: size_of::<T>() != 0")
};assert!(size_of::<T>() != 0);
483        if !!slice.is_empty() {
    ::core::panicking::panic("assertion failed: !slice.is_empty()")
};assert!(!slice.is_empty());
484
485        let mem = self.alloc_raw(Layout::for_value::<[T]>(slice)) as *mut T;
486
487        unsafe {
488            mem.copy_from_nonoverlapping(slice.as_ptr(), slice.len());
489            slice::from_raw_parts_mut(mem, slice.len())
490        }
491    }
492
493    /// Allocates a string slice that is copied into the `DroplessArena`, returning a
494    /// reference to it. Will panic if passed an empty string.
495    ///
496    /// Panics:
497    ///
498    ///  - Zero-length string
499    #[inline]
500    pub fn alloc_str(&self, string: &str) -> &str {
501        let slice = self.alloc_slice(string.as_bytes());
502
503        // SAFETY: the result has a copy of the same valid UTF-8 bytes.
504        unsafe { std::str::from_utf8_unchecked(slice) }
505    }
506
507    /// # Safety
508    ///
509    /// The caller must ensure that `mem` is valid for writes up to `size_of::<T>() * len`, and that
510    /// that memory stays allocated and not shared for the lifetime of `self`. This must hold even
511    /// if `iter.next()` allocates onto `self`.
512    #[inline]
513    unsafe fn write_from_iter<T, I: Iterator<Item = T>>(
514        &self,
515        mut iter: I,
516        len: usize,
517        mem: *mut T,
518    ) -> &mut [T] {
519        let mut i = 0;
520        // Use a manual loop since LLVM manages to optimize it better for
521        // slice iterators
522        loop {
523            // SAFETY: The caller must ensure that `mem` is valid for writes up to
524            // `size_of::<T>() * len`.
525            unsafe {
526                match iter.next() {
527                    Some(value) if i < len => mem.add(i).write(value),
528                    Some(_) | None => {
529                        // We only return as many items as the iterator gave us, even
530                        // though it was supposed to give us `len`
531                        return slice::from_raw_parts_mut(mem, i);
532                    }
533                }
534            }
535            i += 1;
536        }
537    }
538
539    #[inline]
540    pub fn alloc_from_iter<T, I: IntoIterator<Item = T>>(&self, iter: I) -> &mut [T] {
541        if !!mem::needs_drop::<T>() {
    ::core::panicking::panic("assertion failed: !mem::needs_drop::<T>()")
};assert!(!mem::needs_drop::<T>());
542        if !(size_of::<T>() != 0) {
    ::core::panicking::panic("assertion failed: size_of::<T>() != 0")
};assert!(size_of::<T>() != 0);
543
544        // Warning: this function is reentrant: `iter` could hold a reference to `&self` and
545        // allocate additional elements while we're iterating.
546        let iter = iter.into_iter();
547
548        let size_hint = iter.size_hint();
549
550        match size_hint {
551            (min, Some(max)) if min == max => {
552                // We know the exact number of elements the iterator expects to produce here.
553                let len = min;
554
555                if len == 0 {
556                    return &mut [];
557                }
558
559                let mem = self.alloc_raw(Layout::array::<T>(len).unwrap()) as *mut T;
560                // SAFETY: `write_from_iter` doesn't touch `self`. It only touches the slice we just
561                // reserved. If the iterator panics or doesn't output `len` elements, this will
562                // leave some unallocated slots in the arena, which is fine because we do not call
563                // `drop`.
564                unsafe { self.write_from_iter(iter, len, mem) }
565            }
566            (_, _) => outline(move || self.try_alloc_from_iter(iter.map(Ok::<T, !>)).into_ok()),
567        }
568    }
569
570    #[inline]
571    pub fn try_alloc_from_iter<T, E>(
572        &self,
573        iter: impl IntoIterator<Item = Result<T, E>>,
574    ) -> Result<&mut [T], E> {
575        // Despite the similarity with `alloc_from_iter`, we cannot reuse their fast case, as we
576        // cannot know the minimum length of the iterator in this case.
577        if !!mem::needs_drop::<T>() {
    ::core::panicking::panic("assertion failed: !mem::needs_drop::<T>()")
};assert!(!mem::needs_drop::<T>());
578        if !(size_of::<T>() != 0) {
    ::core::panicking::panic("assertion failed: size_of::<T>() != 0")
};assert!(size_of::<T>() != 0);
579
580        // Takes care of reentrancy.
581        let vec: Result<SmallVec<[T; 8]>, E> = iter.into_iter().collect();
582        let mut vec = vec?;
583        if vec.is_empty() {
584            return Ok(&mut []);
585        }
586        // Move the content to the arena by copying and then forgetting it.
587        let len = vec.len();
588        Ok(unsafe {
589            let start_ptr = self.alloc_raw(Layout::for_value::<[T]>(vec.as_slice())) as *mut T;
590            vec.as_ptr().copy_to_nonoverlapping(start_ptr, len);
591            vec.set_len(0);
592            slice::from_raw_parts_mut(start_ptr, len)
593        })
594    }
595}
596
597/// Declares an `Arena` that can allocate values of a variety of `Copy`, `needs_drop` and
598/// `!needs_drop` types.
599///
600/// The declared arena actually contains a single [`DroplessArena`], plus a separate
601/// [`TypedArena`] for each of the types listed in the body of the macro invocation.
602///
603/// Any type that is `Copy` can be allocated in the arena without needing to be listed
604/// explicitly. Those values will be stored in the [`DroplessArena`].
605///
606/// Types that are `!Copy` can only be allocated if they are listed in the macro invocation.
607/// For types that are `!Copy + needs_drop`, values will be stored in the corresponding
608/// [`TypedArena`] and will be dropped when the arena is dropped.
609///
610/// As an optimization, types that are `!Copy + !needs_drop` will actually be stored in the
611/// [`DroplessArena`], and the corresponding [`TypedArena`] will remain empty. This makes
612/// better use of the dropless arena's storage blocks, while the overhead of having a few
613/// unused typed-arenas is negligible.
614#[rustc_macro_transparency = "semiopaque"]
615pub macro declare_arena(
616    // Each of these entries becomes a `$name: TypedArena<$ty>` field in the arena.
617    // This allows values of non-copy type $ty to be allocated in the arena.
618    // The field names must be distinct, but have no further significance.
619    $(
620        $name:ident: $ty:ty,
621    )*
622) {
623    #[derive(Default)]
624    pub struct Arena<'tcx> {
625        pub dropless: $crate::DroplessArena,
626        $($name: $crate::TypedArena<$ty>,)*
627    }
628
629    pub trait ArenaAllocatable<'tcx, C = rustc_arena::IsNotCopy>: Sized {
630        #[allow(clippy::mut_from_ref)]
631        fn allocate_on(self, arena: &'tcx Arena<'tcx>) -> &'tcx mut Self;
632        #[allow(clippy::mut_from_ref)]
633        fn allocate_from_iter(
634            arena: &'tcx Arena<'tcx>,
635            iter: impl ::std::iter::IntoIterator<Item = Self>,
636        ) -> &'tcx mut [Self];
637    }
638
639    // Any type that impls `Copy` can be arena-allocated in the `DroplessArena`.
640    impl<'tcx, T: Copy> ArenaAllocatable<'tcx, rustc_arena::IsCopy> for T {
641        #[inline]
642        #[allow(clippy::mut_from_ref)]
643        fn allocate_on(self, arena: &'tcx Arena<'tcx>) -> &'tcx mut Self {
644            arena.dropless.alloc(self)
645        }
646        #[inline]
647        #[allow(clippy::mut_from_ref)]
648        fn allocate_from_iter(
649            arena: &'tcx Arena<'tcx>,
650            iter: impl ::std::iter::IntoIterator<Item = Self>,
651        ) -> &'tcx mut [Self] {
652            arena.dropless.alloc_from_iter(iter)
653        }
654    }
655    $(
656        impl<'tcx> ArenaAllocatable<'tcx, rustc_arena::IsNotCopy> for $ty {
657            #[inline]
658            fn allocate_on(self, arena: &'tcx Arena<'tcx>) -> &'tcx mut Self {
659                if !::std::mem::needs_drop::<Self>() {
660                    arena.dropless.alloc(self)
661                } else {
662                    arena.$name.alloc(self)
663                }
664            }
665
666            #[inline]
667            #[allow(clippy::mut_from_ref)]
668            fn allocate_from_iter(
669                arena: &'tcx Arena<'tcx>,
670                iter: impl ::std::iter::IntoIterator<Item = Self>,
671            ) -> &'tcx mut [Self] {
672                if !::std::mem::needs_drop::<Self>() {
673                    arena.dropless.alloc_from_iter(iter)
674                } else {
675                    arena.$name.alloc_from_iter(iter)
676                }
677            }
678        }
679    )*
680
681    impl<'tcx> Arena<'tcx> {
682        #[inline]
683        #[allow(clippy::mut_from_ref)]
684        pub fn alloc<T: ArenaAllocatable<'tcx, C>, C>(&'tcx self, value: T) -> &mut T {
685            value.allocate_on(self)
686        }
687
688        // Any type that impls `Copy` can have slices be arena-allocated in the `DroplessArena`.
689        #[inline]
690        #[allow(clippy::mut_from_ref)]
691        pub fn alloc_slice<T: ::std::marker::Copy>(&self, value: &[T]) -> &mut [T] {
692            if value.is_empty() {
693                return &mut [];
694            }
695            self.dropless.alloc_slice(value)
696        }
697
698        #[inline]
699        pub fn alloc_str(&self, string: &str) -> &str {
700            if string.is_empty() {
701                return "";
702            }
703            self.dropless.alloc_str(string)
704        }
705
706        #[inline]
707        pub fn alloc_os_str(&self, os_str: &::std::ffi::OsStr) -> &::std::ffi::OsStr {
708            use ::std::ffi::OsStr;
709            if os_str.is_empty() {
710                return OsStr::new("");
711            }
712            let bytes = self.dropless.alloc_slice(os_str.as_encoded_bytes());
713            // SAFETY: These bytes are an exact copy of `os_str.as_encoded_bytes()`.
714            unsafe { OsStr::from_encoded_bytes_unchecked(bytes) }
715        }
716
717        #[inline]
718        pub fn alloc_path(&self, path: &::std::path::Path) -> &::std::path::Path {
719            use ::std::path::Path;
720            Path::new(self.alloc_os_str(path.as_os_str()))
721        }
722
723        #[allow(clippy::mut_from_ref)]
724        pub fn alloc_from_iter<T: ArenaAllocatable<'tcx, C>, C>(
725            &'tcx self,
726            iter: impl ::std::iter::IntoIterator<Item = T>,
727        ) -> &mut [T] {
728            T::allocate_from_iter(self, iter)
729        }
730
731        #[allow(clippy::mut_from_ref)]
732        pub fn alloc_index_slice_from_iter<I, T, C>(
733            &'tcx self,
734            iter: impl ::std::iter::IntoIterator<Item = T>,
735        ) -> &mut ::rustc_index::IndexSlice<I, T>
736        where
737            I: ::rustc_index::Idx,
738            T: ArenaAllocatable<'tcx, C>,
739        {
740            ::rustc_index::IndexSlice::from_raw_mut(self.alloc_from_iter(iter))
741        }
742    }
743}
744
745// Marker types that let us give different behaviour for arenas allocating
746// `Copy` types vs `!Copy` types.
747pub struct IsCopy;
748pub struct IsNotCopy;
749
750#[cfg(test)]
751mod tests;