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