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.
910// 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
2021use 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};
2728use smallvec::SmallVec;
2930/// 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 {
34f()
35}
3637struct ArenaChunk<T = u8> {
38/// The raw storage for the arena chunk.
39storage: NonNull<[MaybeUninit<T>]>,
40/// The number of valid entries in the chunk.
41entries: usize,
42}
4344unsafe impl<#[may_dangle] T> Dropfor ArenaChunk<T> {
45fn drop(&mut self) {
46unsafe { drop(Box::from_raw(self.storage.as_mut())) }
47 }
48}
4950impl<T> ArenaChunk<T> {
51#[inline]
52unsafe fn new(capacity: usize) -> ArenaChunk<T> {
53ArenaChunk { storage: Box::into_non_null(Box::new_uninit_slice(capacity)), entries: 0 }
54 }
5556/// Destroys this arena chunk.
57 ///
58 /// # Safety
59 ///
60 /// The caller must ensure that `len` elements of this chunk have been initialized.
61#[inline]
62unsafe 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.
65if mem::needs_drop::<T>() {
66// SAFETY: The caller must ensure that `len` elements of this chunk have
67 // been initialized.
68unsafe {
69let slice = self.storage.as_mut();
70slice[..len].assume_init_drop();
71 }
72 }
73 }
7475// Returns a pointer to the first allocated object.
76#[inline]
77fn start(&mut self) -> *mut T {
78self.storage.as_ptr() as *mut T
79 }
8081// Returns a pointer to the end of the allocated space.
82#[inline]
83fn end(&mut self) -> *mut T {
84unsafe {
85if size_of::<T>() == 0 {
86// A pointer as large as possible for zero-sized elements.
87ptr::without_provenance_mut(!0)
88 } else {
89self.start().add(self.storage.len())
90 }
91 }
92 }
93}
9495// 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;
102103/// An arena that can hold objects of only one type.
104pub struct TypedArena<T> {
105/// A pointer to the next object to be allocated.
106ptr: Cell<*mut T>,
107108/// A pointer to the end of the allocated area. When this pointer is
109 /// reached, a new chunk is allocated.
110end: Cell<*mut T>,
111112/// A vector of arena chunks.
113chunks: RefCell<Vec<ArenaChunk<T>>>,
114115/// Marker indicating that dropping the arena causes its owned
116 /// instances of `T` to be dropped.
117_own: PhantomData<T>,
118}
119120impl<T> Defaultfor TypedArena<T> {
121/// Creates a new `TypedArena`.
122fn default() -> TypedArena<T> {
123TypedArena {
124// We set both `ptr` and `end` to 0 so that the first call to
125 // alloc() will trigger a grow().
126ptr: Cell::new(ptr::null_mut()),
127 end: Cell::new(ptr::null_mut()),
128 chunks: Default::default(),
129 _own: PhantomData,
130 }
131 }
132}
133134impl<T> TypedArena<T> {
135/// Allocates an object in the `TypedArena`, returning a reference to it.
136#[inline]
137pub fn alloc(&self, object: T) -> &mut T {
138if !(size_of::<T>() != 0) {
::core::panicking::panic("assertion failed: size_of::<T>() != 0")
};assert!(size_of::<T>() != 0);
139140if self.ptr == self.end {
141self.grow(1)
142 }
143144unsafe {
145let ptr = self.ptr.get();
146// Advance the pointer.
147self.ptr.set(self.ptr.get().add(1));
148// Write into uninitialized memory.
149ptr::write(ptr, object);
150&mut *ptr151 }
152 }
153154#[inline]
155fn 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).
158let available_bytes = self.end.get().addr() - self.ptr.get().addr();
159let additional_bytes = additional.checked_mul(size_of::<T>()).unwrap();
160available_bytes >= additional_bytes161 }
162163/// 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]
178unsafe fn alloc_raw_slice(&self, len: usize) -> *mut T {
179if !(size_of::<T>() != 0) {
::core::panicking::panic("assertion failed: size_of::<T>() != 0")
};assert!(size_of::<T>() != 0);
180if !(len != 0) { ::core::panicking::panic("assertion failed: len != 0") };assert!(len != 0);
181182// Ensure the current chunk can fit `len` objects.
183if !self.can_allocate(len) {
184self.grow(len);
185if true {
if !self.can_allocate(len) {
::core::panicking::panic("assertion failed: self.can_allocate(len)")
};
};debug_assert!(self.can_allocate(len));
186 }
187188let start_ptr = self.ptr.get();
189// SAFETY: `can_allocate`/`grow` ensures that there is enough space for
190 // `len` elements.
191unsafe { self.ptr.set(start_ptr.add(len)) };
192start_ptr193 }
194195/// 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]
200pub fn alloc_from_iter<I: IntoIterator<Item = T>>(&self, iter: I) -> &mut [T] {
201self.try_alloc_from_iter(iter.into_iter().map(Ok::<T, !>)).into_ok()
202 }
203204/// 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]
209pub 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.
225if !(size_of::<T>() != 0) {
::core::panicking::panic("assertion failed: size_of::<T>() != 0")
};assert!(size_of::<T>() != 0);
226227let vec: Result<SmallVec<[T; 8]>, E> = iter.into_iter().collect();
228let mut vec = vec?;
229if vec.is_empty() {
230return Ok(&mut []);
231 }
232// Move the content to the arena by copying and then forgetting it.
233let len = vec.len();
234235// 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.
238Ok(unsafe {
239let start_ptr = self.alloc_raw_slice(len);
240// Initialize the newly-allocated storage without panicking.
241vec.as_ptr().copy_to_nonoverlapping(start_ptr, len);
242// Prevent the stale values in the vec from being dropped.
243vec.set_len(0);
244 slice::from_raw_parts_mut(start_ptr, len)
245 })
246 }
247248/// Grows the arena.
249#[inline(never)]
250 #[cold]
251fn grow(&self, additional: usize) {
252unsafe {
253// We need the element size to convert chunk sizes (ranging from
254 // PAGE to HUGE_PAGE bytes) to element counts.
255let elem_size = cmp::max(1, size_of::<T>());
256let mut chunks = self.chunks.borrow_mut();
257let mut new_cap;
258if 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.
261if mem::needs_drop::<T>() {
262// FIXME: this should *likely* use `offset_from`, but more
263 // investigation is needed (including running tests in miri).
264let used_bytes = self.ptr.get().addr() - last_chunk.start().addr();
265last_chunk.entries = used_bytes / size_of::<T>();
266 }
267268// 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.
271new_cap = last_chunk.storage.len().min(HUGE_PAGE / elem_size / 2);
272new_cap*= 2;
273 } else {
274new_cap = PAGE / elem_size;
275 }
276// Also ensure that this chunk can fit `additional`.
277new_cap = cmp::max(additional, new_cap);
278279let chunk = chunks.push_mut(ArenaChunk::<T>::new(new_cap));
280self.ptr.set(chunk.start());
281self.end.set(chunk.end());
282 }
283 }
284285// Drops the contents of the last chunk. The last chunk is partially empty, unlike all other
286 // chunks.
287fn clear_last_chunk(&self, last_chunk: &mut ArenaChunk<T>) {
288// Determine how much was filled.
289let start = last_chunk.start().addr();
290// We obtain the value of the pointer to the first uninitialized element.
291let 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).
297let diff = (end - start) / size_of::<T>();
298// Pass that to the `destroy` method.
299unsafe {
300last_chunk.destroy(diff);
301 }
302// Reset the chunk.
303self.ptr.set(last_chunk.start());
304 }
305}
306307unsafe impl<#[may_dangle] T> Dropfor TypedArena<T> {
308fn drop(&mut self) {
309unsafe {
310// Determine how much was filled.
311let mut chunks_borrow = self.chunks.borrow_mut();
312if let Some(mut last_chunk) = chunks_borrow.pop() {
313// Drop the contents of the last chunk.
314self.clear_last_chunk(&mut last_chunk);
315// The last chunk will be dropped. Destroy all other chunks.
316for 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}
324325unsafe impl<T: Send> Sendfor TypedArena<T> {}
326327#[inline(always)]
328fn align_down(val: usize, align: usize) -> usize {
329if true {
if !align.is_power_of_two() {
::core::panicking::panic("assertion failed: align.is_power_of_two()")
};
};debug_assert!(align.is_power_of_two());
330val & !(align - 1)
331}
332333#[inline(always)]
334fn align_up(val: usize, align: usize) -> usize {
335if 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}
338339// 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>();
342343/// 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.
347start: Cell<*mut u8>,
348349/// 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.
357end: Cell<*mut u8>,
358359/// A vector of arena chunks.
360chunks: RefCell<Vec<ArenaChunk>>,
361}
362363unsafe impl Sendfor DroplessArena {}
364365impl Defaultfor DroplessArena {
366#[inline]
367fn default() -> DroplessArena {
368DroplessArena {
369// We set both `start` and `end` to 0 so that the first call to
370 // alloc() will trigger a grow().
371start: Cell::new(ptr::null_mut()),
372 end: Cell::new(ptr::null_mut()),
373 chunks: Default::default(),
374 }
375 }
376}
377378impl DroplessArena {
379#[inline(never)]
380 #[cold]
381fn grow(&self, layout: Layout) {
382// Add some padding so we can align `self.end` while
383 // still fitting in a `layout` allocation.
384let additional = layout.size() + cmp::max(DROPLESS_ALIGNMENT, layout.align()) - 1;
385386unsafe {
387let mut chunks = self.chunks.borrow_mut();
388let mut new_cap;
389if 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`.
392393 // 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.
396new_cap = last_chunk.storage.len().min(HUGE_PAGE / 2);
397new_cap*= 2;
398 } else {
399new_cap = PAGE;
400 }
401// Also ensure that this chunk can fit `additional`.
402new_cap = cmp::max(additional, new_cap);
403404let chunk = chunks.push_mut(ArenaChunk::new(align_up(new_cap, PAGE)));
405self.start.set(chunk.start());
406407// Align the end to DROPLESS_ALIGNMENT.
408let end = align_down(chunk.end().addr(), DROPLESS_ALIGNMENT);
409410// Make sure we don't go past `start`. This should not happen since the allocation
411 // should be at least DROPLESS_ALIGNMENT - 1 bytes.
412if true {
if !(chunk.start().addr() <= end) {
::core::panicking::panic("assertion failed: chunk.start().addr() <= end")
};
};debug_assert!(chunk.start().addr() <= end);
413414self.end.set(chunk.end().with_addr(end));
415 }
416 }
417418#[inline]
419pub fn alloc_raw(&self, layout: Layout) -> *mut u8 {
420if !(layout.size() != 0) {
::core::panicking::panic("assertion failed: layout.size() != 0")
};assert!(layout.size() != 0);
421422// This loop executes once or twice: if allocation fails the first
423 // time, the `grow` ensures it will succeed the second time.
424loop {
425let start = self.start.get().addr();
426let old_end = self.end.get();
427let end = old_end.addr();
428429// Align allocated bytes so that `self.end` stays aligned to
430 // DROPLESS_ALIGNMENT.
431let bytes = align_up(layout.size(), DROPLESS_ALIGNMENT);
432433// Tell LLVM that `end` is aligned to DROPLESS_ALIGNMENT.
434unsafe { hint::assert_unchecked(end == align_down(end, DROPLESS_ALIGNMENT)) };
435436if let Some(sub) = end.checked_sub(bytes) {
437let new_end = align_down(sub, layout.align());
438if start <= new_end {
439let 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.
443self.end.set(new_end);
444return new_end;
445 }
446 }
447448// No free space left. Allocate a new chunk to satisfy the request.
449 // On failure the grow will panic or abort.
450self.grow(layout);
451 }
452 }
453454#[inline]
455pub fn alloc<T>(&self, object: T) -> &mut T {
456if !!mem::needs_drop::<T>() {
::core::panicking::panic("assertion failed: !mem::needs_drop::<T>()")
};assert!(!mem::needs_drop::<T>());
457if !(size_of::<T>() != 0) {
::core::panicking::panic("assertion failed: size_of::<T>() != 0")
};assert!(size_of::<T>() != 0);
458459let mem = self.alloc_raw(Layout::new::<T>()) as *mut T;
460461unsafe {
462// Write into uninitialized memory.
463ptr::write(mem, object);
464&mut *mem465 }
466 }
467468/// 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]
476pub fn alloc_slice<T>(&self, slice: &[T]) -> &mut [T]
477where
478T: Copy,
479 {
480if !!mem::needs_drop::<T>() {
::core::panicking::panic("assertion failed: !mem::needs_drop::<T>()")
};assert!(!mem::needs_drop::<T>());
481if !(size_of::<T>() != 0) {
::core::panicking::panic("assertion failed: size_of::<T>() != 0")
};assert!(size_of::<T>() != 0);
482if !!slice.is_empty() {
::core::panicking::panic("assertion failed: !slice.is_empty()")
};assert!(!slice.is_empty());
483484let mem = self.alloc_raw(Layout::for_value::<[T]>(slice)) as *mut T;
485486unsafe {
487mem.copy_from_nonoverlapping(slice.as_ptr(), slice.len());
488 slice::from_raw_parts_mut(mem, slice.len())
489 }
490 }
491492/// 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]
499pub fn alloc_str(&self, string: &str) -> &str {
500let slice = self.alloc_slice(string.as_bytes());
501502// SAFETY: the result has a copy of the same valid UTF-8 bytes.
503unsafe { std::str::from_utf8_unchecked(slice) }
504 }
505506/// # 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]
512unsafe fn write_from_iter<T, I: Iterator<Item = T>>(
513&self,
514mut iter: I,
515 len: usize,
516 mem: *mut T,
517 ) -> &mut [T] {
518let mut i = 0;
519// Use a manual loop since LLVM manages to optimize it better for
520 // slice iterators
521loop {
522// SAFETY: The caller must ensure that `mem` is valid for writes up to
523 // `size_of::<T>() * len`.
524unsafe {
525match iter.next() {
526Some(value) if i < len => mem.add(i).write(value),
527Some(_) | None => {
528// We only return as many items as the iterator gave us, even
529 // though it was supposed to give us `len`
530return slice::from_raw_parts_mut(mem, i);
531 }
532 }
533 }
534i += 1;
535 }
536 }
537538#[inline]
539pub fn alloc_from_iter<T, I: IntoIterator<Item = T>>(&self, iter: I) -> &mut [T] {
540if !!mem::needs_drop::<T>() {
::core::panicking::panic("assertion failed: !mem::needs_drop::<T>()")
};assert!(!mem::needs_drop::<T>());
541if !(size_of::<T>() != 0) {
::core::panicking::panic("assertion failed: size_of::<T>() != 0")
};assert!(size_of::<T>() != 0);
542543// Warning: this function is reentrant: `iter` could hold a reference to `&self` and
544 // allocate additional elements while we're iterating.
545let iter = iter.into_iter();
546547let size_hint = iter.size_hint();
548549match size_hint {
550 (min, Some(max)) if min == max => {
551// We know the exact number of elements the iterator expects to produce here.
552let len = min;
553554if len == 0 {
555return &mut [];
556 }
557558let 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`.
563unsafe { self.write_from_iter(iter, len, mem) }
564 }
565 (_, _) => outline(move || self.try_alloc_from_iter(iter.map(Ok::<T, !>)).into_ok()),
566 }
567 }
568569#[inline]
570pub 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.
576if !!mem::needs_drop::<T>() {
::core::panicking::panic("assertion failed: !mem::needs_drop::<T>()")
};assert!(!mem::needs_drop::<T>());
577if !(size_of::<T>() != 0) {
::core::panicking::panic("assertion failed: size_of::<T>() != 0")
};assert!(size_of::<T>() != 0);
578579// Takes care of reentrancy.
580let vec: Result<SmallVec<[T; 8]>, E> = iter.into_iter().collect();
581let mut vec = vec?;
582if vec.is_empty() {
583return Ok(&mut []);
584 }
585// Move the content to the arena by copying and then forgetting it.
586let len = vec.len();
587Ok(unsafe {
588let start_ptr = self.alloc_raw(Layout::for_value::<[T]>(vec.as_slice())) as *mut T;
589vec.as_ptr().copy_to_nonoverlapping(start_ptr, len);
590vec.set_len(0);
591 slice::from_raw_parts_mut(start_ptr, len)
592 })
593 }
594}
595596/// 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)]
623pub struct Arena<'tcx> {
624pub dropless: $crate::DroplessArena,
625 $($name: $crate::TypedArena<$ty>,)*
626 }
627628pub trait ArenaAllocatable<'tcx, C = rustc_arena::IsNotCopy>: Sized {
629#[allow(clippy::mut_from_ref)]
630fn allocate_on(self, arena: &'tcx Arena<'tcx>) -> &'tcx mut Self;
631#[allow(clippy::mut_from_ref)]
632fn allocate_from_iter(
633 arena: &'tcx Arena<'tcx>,
634 iter: impl ::std::iter::IntoIterator<Item = Self>,
635 ) -> &'tcx mut [Self];
636 }
637638// Any type that impls `Copy` can be arena-allocated in the `DroplessArena`.
639impl<'tcx, T: Copy> ArenaAllocatable<'tcx, rustc_arena::IsCopy> for T {
640#[inline]
641 #[allow(clippy::mut_from_ref)]
642fn allocate_on(self, arena: &'tcx Arena<'tcx>) -> &'tcx mut Self {
643 arena.dropless.alloc(self)
644 }
645#[inline]
646 #[allow(clippy::mut_from_ref)]
647fn 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 $(
655impl<'tcx> ArenaAllocatable<'tcx, rustc_arena::IsNotCopy> for $ty {
656#[inline]
657fn allocate_on(self, arena: &'tcx Arena<'tcx>) -> &'tcx mut Self {
658if !::std::mem::needs_drop::<Self>() {
659 arena.dropless.alloc(self)
660 } else {
661 arena.$name.alloc(self)
662 }
663 }
664665#[inline]
666 #[allow(clippy::mut_from_ref)]
667fn allocate_from_iter(
668 arena: &'tcx Arena<'tcx>,
669 iter: impl ::std::iter::IntoIterator<Item = Self>,
670 ) -> &'tcx mut [Self] {
671if !::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 )*
679680impl<'tcx> Arena<'tcx> {
681#[inline]
682 #[allow(clippy::mut_from_ref)]
683pub fn alloc<T: ArenaAllocatable<'tcx, C>, C>(&'tcx self, value: T) -> &mut T {
684 value.allocate_on(self)
685 }
686687// Any type that impls `Copy` can have slices be arena-allocated in the `DroplessArena`.
688#[inline]
689 #[allow(clippy::mut_from_ref)]
690pub fn alloc_slice<T: ::std::marker::Copy>(&self, value: &[T]) -> &mut [T] {
691if value.is_empty() {
692return &mut [];
693 }
694self.dropless.alloc_slice(value)
695 }
696697#[inline]
698pub fn alloc_str(&self, string: &str) -> &str {
699if string.is_empty() {
700return "";
701 }
702self.dropless.alloc_str(string)
703 }
704705#[inline]
706pub fn alloc_os_str(&self, os_str: &::std::ffi::OsStr) -> &::std::ffi::OsStr {
707use ::std::ffi::OsStr;
708if os_str.is_empty() {
709return OsStr::new("");
710 }
711let bytes = self.dropless.alloc_slice(os_str.as_encoded_bytes());
712// SAFETY: These bytes are an exact copy of `os_str.as_encoded_bytes()`.
713unsafe { OsStr::from_encoded_bytes_unchecked(bytes) }
714 }
715716#[inline]
717pub fn alloc_path(&self, path: &::std::path::Path) -> &::std::path::Path {
718use ::std::path::Path;
719 Path::new(self.alloc_os_str(path.as_os_str()))
720 }
721722#[allow(clippy::mut_from_ref)]
723pub 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 }
729730#[allow(clippy::mut_from_ref)]
731pub 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>
735where
736I: ::rustc_index::Idx,
737 T: ArenaAllocatable<'tcx, C>,
738 {
739 ::rustc_index::IndexSlice::from_raw_mut(self.alloc_from_iter(iter))
740 }
741 }
742}
743744// Marker types that let us give different behaviour for arenas allocating
745// `Copy` types vs `!Copy` types.
746pub struct IsCopy;
747pub struct IsNotCopy;
748749#[cfg(test)]
750mod tests;