sync_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
10use std::alloc::Layout;
11use std::cell::{Cell, RefCell};
12use std::marker::PhantomData;
13use std::mem::{self, MaybeUninit};
14use std::ptr::{self, NonNull};
15use std::sync::RwLock;
16use std::{cmp, slice};
17
18use smallvec::SmallVec;
19
20/// This calls the passed function while ensuring it won't be inlined into the caller.
21#[inline(never)]
22#[cold]
23fn outline<F: FnOnce() -> R, R>(f: F) -> R {
24 f()
25}
26
27struct ArenaChunk<T = u8> {
28 /// The raw storage for the arena chunk.
29 storage: NonNull<[MaybeUninit<T>]>,
30 /// The number of valid entries in the chunk.
31 entries: usize,
32}
33
34impl<T> Drop for ArenaChunk<T> {
35 fn drop(&mut self) {
36 unsafe { drop(Box::from_raw(self.storage.as_mut())) }
37 }
38}
39
40impl<T> ArenaChunk<T> {
41 #[inline]
42 unsafe fn new(capacity: usize) -> ArenaChunk<T> {
43 ArenaChunk {
44 storage: NonNull::from(Box::leak(Box::new_uninit_slice(capacity))),
45 entries: 0,
46 }
47 }
48
49 /// Destroys this arena chunk.
50 ///
51 /// # Safety
52 ///
53 /// The caller must ensure that `len` elements of this chunk have been initialized.
54 #[inline]
55 unsafe fn destroy(&mut self, len: usize) {
56 // The branch on needs_drop() is an -O1 performance optimization.
57 // Without the branch, dropping TypedArena<T> takes linear time.
58 if mem::needs_drop::<T>() {
59 // SAFETY: The caller must ensure that `len` elements of this chunk have
60 // been initialized.
61 unsafe {
62 let slice = self.storage.as_mut();
63 // slice[..len].assume_init_drop();
64
65 /// See [`MaybeUninit::slice_assume_init_mut`].
66 pub const unsafe fn slice_assume_init_mut<T>(
67 slice: &mut [MaybeUninit<T>],
68 ) -> &mut [T] {
69 unsafe { &mut *(slice as *mut [MaybeUninit<T>] as *mut [T]) }
70 }
71 ptr::drop_in_place(slice_assume_init_mut(&mut slice[..len]));
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: RwLock<*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: RwLock<*mut T>,
112
113 /// A vector of arena chunks.
114 chunks: RwLock<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: RwLock::new(ptr::null_mut()),
128 end: RwLock::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 *self.ptr.read().unwrap() == *self.end.read().unwrap() {
140 self.grow(1)
141 }
142
143 unsafe {
144 if size_of::<T>() == 0 {
145 {
146 let mut ptr = self.ptr.write().unwrap();
147 *ptr = ptr.wrapping_byte_add(1);
148 }
149 let ptr = ptr::NonNull::<T>::dangling().as_ptr();
150 // Don't drop the object. This `write` is equivalent to `forget`.
151 ptr::write(ptr, object);
152 &mut *ptr
153 } else {
154 let mut p = self.ptr.write().unwrap();
155 let ptr = *p;
156 // Advance the pointer.
157 *p = ptr.add(1);
158 // Write into uninitialized memory.
159 ptr::write(ptr, object);
160 &mut *ptr
161 }
162 }
163 }
164
165 #[inline]
166 fn can_allocate(&self, additional: usize) -> bool {
167 // FIXME: this should *likely* use `offset_from`, but more
168 // investigation is needed (including running tests in miri).
169 let available_bytes = self.end.read().unwrap().addr() - self.ptr.read().unwrap().addr();
170 let additional_bytes = additional.checked_mul(size_of::<T>()).unwrap();
171 available_bytes >= additional_bytes
172 }
173
174 #[inline]
175 fn alloc_raw_slice(&self, len: usize) -> *mut T {
176 assert!(size_of::<T>() != 0);
177 assert!(len != 0);
178
179 // Ensure the current chunk can fit `len` objects.
180 if !self.can_allocate(len) {
181 self.grow(len);
182 debug_assert!(self.can_allocate(len));
183 }
184
185 let mut ptr = self.ptr.write().unwrap();
186 let start_ptr = *ptr;
187 // SAFETY: `can_allocate`/`grow` ensures that there is enough space for
188 // `len` elements.
189 unsafe { *ptr = start_ptr.add(len) }
190 start_ptr
191 }
192
193 /// Allocates the elements of this iterator into a contiguous slice in the `TypedArena`.
194 ///
195 /// Note: for reasons of reentrancy and panic safety we collect into a `SmallVec<[_; 8]>` before
196 /// storing the elements in the arena.
197 #[inline]
198 pub fn alloc_from_iter<I: IntoIterator<Item = T>>(&self, iter: I) -> &mut [T] {
199 // Despite the similarlty with `DroplessArena`, we cannot reuse their fast case. The reason
200 // is subtle: these arenas are reentrant. In other words, `iter` may very well be holding a
201 // reference to `self` and adding elements to the arena during iteration.
202 //
203 // For this reason, if we pre-allocated any space for the elements of this iterator, we'd
204 // have to track that some uninitialized elements are followed by some initialized elements,
205 // else we might accidentally drop uninitialized memory if something panics or if the
206 // iterator doesn't fill all the length we expected.
207 //
208 // So we collect all the elements beforehand, which takes care of reentrancy and panic
209 // safety. This function is much less hot than `DroplessArena::alloc_from_iter`, so it
210 // doesn't need to be hyper-optimized.
211 assert!(size_of::<T>() != 0);
212
213 let mut vec: SmallVec<[_; 8]> = iter.into_iter().collect();
214 if vec.is_empty() {
215 return &mut [];
216 }
217 // Move the content to the arena by copying and then forgetting it.
218 let len = vec.len();
219 let start_ptr = self.alloc_raw_slice(len);
220 unsafe {
221 vec.as_ptr().copy_to_nonoverlapping(start_ptr, len);
222 vec.set_len(0);
223 slice::from_raw_parts_mut(start_ptr, len)
224 }
225 }
226
227 /// Grows the arena.
228 #[inline(never)]
229 #[cold]
230 fn grow(&self, additional: usize) {
231 unsafe {
232 // We need the element size to convert chunk sizes (ranging from
233 // PAGE to HUGE_PAGE bytes) to element counts.
234 let elem_size = cmp::max(1, size_of::<T>());
235 let mut chunks = self.chunks.write().unwrap();
236 let mut new_cap;
237 if let Some(last_chunk) = chunks.last_mut() {
238 // If a type is `!needs_drop`, we don't need to keep track of how many elements
239 // the chunk stores - the field will be ignored anyway.
240 if mem::needs_drop::<T>() {
241 // FIXME: this should *likely* use `offset_from`, but more
242 // investigation is needed (including running tests in miri).
243 let used_bytes = self.ptr.read().unwrap().addr() - last_chunk.start().addr();
244 last_chunk.entries = used_bytes / size_of::<T>();
245 }
246
247 // If the previous chunk's len is less than HUGE_PAGE
248 // bytes, then this chunk will be least double the previous
249 // chunk's size.
250 new_cap = last_chunk.storage.len().min(HUGE_PAGE / elem_size / 2);
251 new_cap *= 2;
252 } else {
253 new_cap = PAGE / elem_size;
254 }
255 // Also ensure that this chunk can fit `additional`.
256 new_cap = cmp::max(additional, new_cap);
257
258 let mut chunk = ArenaChunk::<T>::new(new_cap);
259 *self.ptr.write().unwrap() = chunk.start();
260 *self.end.write().unwrap() = chunk.end();
261 chunks.push(chunk);
262 }
263 }
264
265 // Drops the contents of the last chunk. The last chunk is partially empty, unlike all other
266 // chunks.
267 fn clear_last_chunk(&self, last_chunk: &mut ArenaChunk<T>) {
268 // Determine how much was filled.
269 let start = last_chunk.start().addr();
270 // We obtain the value of the pointer to the first uninitialized element.
271 let end = self.ptr.read().unwrap().addr();
272 // We then calculate the number of elements to be dropped in the last chunk,
273 // which is the filled area's length.
274 let diff = if size_of::<T>() == 0 {
275 // `T` is ZST. It can't have a drop flag, so the value here doesn't matter. We get
276 // the number of zero-sized values in the last and only chunk, just out of caution.
277 // Recall that `end` was incremented for each allocated value.
278 end - start
279 } else {
280 // FIXME: this should *likely* use `offset_from`, but more
281 // investigation is needed (including running tests in miri).
282 (end - start) / size_of::<T>()
283 };
284 // Pass that to the `destroy` method.
285 unsafe {
286 last_chunk.destroy(diff);
287 }
288 // Reset the chunk.
289 *self.ptr.write().unwrap() = last_chunk.start();
290 }
291}
292
293impl<T> Drop for TypedArena<T> {
294 fn drop(&mut self) {
295 unsafe {
296 // Determine how much was filled.
297 let mut chunks_borrow = self.chunks.write().unwrap();
298 if let Some(mut last_chunk) = chunks_borrow.pop() {
299 // Drop the contents of the last chunk.
300 self.clear_last_chunk(&mut last_chunk);
301 // The last chunk will be dropped. Destroy all other chunks.
302 for chunk in chunks_borrow.iter_mut() {
303 chunk.destroy(chunk.entries);
304 }
305 }
306 // Box handles deallocation of `last_chunk` and `self.chunks`.
307 }
308 }
309}
310
311unsafe impl<T: Send> Send for TypedArena<T> {}
312
313#[inline(always)]
314fn align_down(val: usize, align: usize) -> usize {
315 debug_assert!(align.is_power_of_two());
316 val & !(align - 1)
317}
318
319#[inline(always)]
320fn align_up(val: usize, align: usize) -> usize {
321 debug_assert!(align.is_power_of_two());
322 (val + align - 1) & !(align - 1)
323}
324
325// Pointer alignment is common in compiler types, so keep `DroplessArena` aligned to them
326// to optimize away alignment code.
327const DROPLESS_ALIGNMENT: usize = align_of::<usize>();
328
329/// An arena that can hold objects of multiple different types that impl `Copy`
330/// and/or satisfy `!mem::needs_drop`.
331pub struct DroplessArena {
332 /// A pointer to the start of the free space.
333 start: Cell<*mut u8>,
334
335 /// A pointer to the end of free space.
336 ///
337 /// The allocation proceeds downwards from the end of the chunk towards the
338 /// start. (This is slightly simpler and faster than allocating upwards,
339 /// see <https://fitzgeraldnick.com/2019/11/01/always-bump-downwards.html>.)
340 /// When this pointer crosses the start pointer, a new chunk is allocated.
341 ///
342 /// This is kept aligned to DROPLESS_ALIGNMENT.
343 end: Cell<*mut u8>,
344
345 /// A vector of arena chunks.
346 chunks: RefCell<Vec<ArenaChunk>>,
347}
348
349unsafe impl Send for DroplessArena {}
350
351impl Default for DroplessArena {
352 #[inline]
353 fn default() -> DroplessArena {
354 DroplessArena {
355 // We set both `start` and `end` to 0 so that the first call to
356 // alloc() will trigger a grow().
357 start: Cell::new(ptr::null_mut()),
358 end: Cell::new(ptr::null_mut()),
359 chunks: Default::default(),
360 }
361 }
362}
363
364impl DroplessArena {
365 #[inline(never)]
366 #[cold]
367 fn grow(&self, layout: Layout) {
368 // Add some padding so we can align `self.end` while
369 // still fitting in a `layout` allocation.
370 let additional = layout.size() + cmp::max(DROPLESS_ALIGNMENT, layout.align()) - 1;
371
372 unsafe {
373 let mut chunks = self.chunks.borrow_mut();
374 let mut new_cap;
375 if let Some(last_chunk) = chunks.last_mut() {
376 // There is no need to update `last_chunk.entries` because that
377 // field isn't used by `DroplessArena`.
378
379 // If the previous chunk's len is less than HUGE_PAGE
380 // bytes, then this chunk will be least double the previous
381 // chunk's size.
382 new_cap = last_chunk.storage.len().min(HUGE_PAGE / 2);
383 new_cap *= 2;
384 } else {
385 new_cap = PAGE;
386 }
387 // Also ensure that this chunk can fit `additional`.
388 new_cap = cmp::max(additional, new_cap);
389
390 let mut chunk = ArenaChunk::new(align_up(new_cap, PAGE));
391 self.start.set(chunk.start());
392
393 // Align the end to DROPLESS_ALIGNMENT.
394 let end = align_down(chunk.end().addr(), DROPLESS_ALIGNMENT);
395
396 // Make sure we don't go past `start`. This should not happen since the allocation
397 // should be at least DROPLESS_ALIGNMENT - 1 bytes.
398 debug_assert!(chunk.start().addr() <= end);
399
400 self.end.set(chunk.end().with_addr(end));
401
402 chunks.push(chunk);
403 }
404 }
405
406 #[inline]
407 pub fn alloc_raw(&self, layout: Layout) -> *mut u8 {
408 assert!(layout.size() != 0);
409
410 // This loop executes once or twice: if allocation fails the first
411 // time, the `grow` ensures it will succeed the second time.
412 loop {
413 let start = self.start.get().addr();
414 let old_end = self.end.get();
415 let end = old_end.addr();
416
417 // Align allocated bytes so that `self.end` stays aligned to
418 // DROPLESS_ALIGNMENT.
419 let bytes = align_up(layout.size(), DROPLESS_ALIGNMENT);
420
421 if let Some(sub) = end.checked_sub(bytes) {
422 let new_end = align_down(sub, layout.align());
423 if start <= new_end {
424 let new_end = old_end.with_addr(new_end);
425 // `new_end` is aligned to DROPLESS_ALIGNMENT as `align_down`
426 // preserves alignment as both `end` and `bytes` are already
427 // aligned to DROPLESS_ALIGNMENT.
428 self.end.set(new_end);
429 return new_end;
430 }
431 }
432
433 // No free space left. Allocate a new chunk to satisfy the request.
434 // On failure the grow will panic or abort.
435 self.grow(layout);
436 }
437 }
438
439 #[inline]
440 pub fn alloc<T>(&self, object: T) -> &mut T {
441 assert!(!mem::needs_drop::<T>());
442 assert!(size_of::<T>() != 0);
443
444 let mem = self.alloc_raw(Layout::new::<T>()) as *mut T;
445
446 unsafe {
447 // Write into uninitialized memory.
448 ptr::write(mem, object);
449 &mut *mem
450 }
451 }
452
453 /// Allocates a slice of objects that are copied into the `DroplessArena`, returning a mutable
454 /// reference to it. Will panic if passed a zero-sized type.
455 ///
456 /// Panics:
457 ///
458 /// - Zero-sized types
459 /// - Zero-length slices
460 #[inline]
461 pub fn alloc_slice<T>(&self, slice: &[T]) -> &mut [T]
462 where
463 T: Copy,
464 {
465 assert!(!mem::needs_drop::<T>());
466 assert!(size_of::<T>() != 0);
467 assert!(!slice.is_empty());
468
469 let mem = self.alloc_raw(Layout::for_value::<[T]>(slice)) as *mut T;
470
471 unsafe {
472 mem.copy_from_nonoverlapping(slice.as_ptr(), slice.len());
473 slice::from_raw_parts_mut(mem, slice.len())
474 }
475 }
476
477 /// Used by `Lift` to check whether this slice is allocated
478 /// in this arena.
479 #[inline]
480 pub fn contains_slice<T>(&self, slice: &[T]) -> bool {
481 for chunk in self.chunks.borrow_mut().iter_mut() {
482 let ptr = slice.as_ptr().cast::<u8>().cast_mut();
483 if chunk.start() <= ptr && chunk.end() >= ptr {
484 return true;
485 }
486 }
487 false
488 }
489
490 /// Allocates a string slice that is copied into the `DroplessArena`, returning a
491 /// reference to it. Will panic if passed an empty string.
492 ///
493 /// Panics:
494 ///
495 /// - Zero-length string
496 #[inline]
497 pub fn alloc_str(&self, string: &str) -> &str {
498 let slice = self.alloc_slice(string.as_bytes());
499
500 // SAFETY: the result has a copy of the same valid UTF-8 bytes.
501 unsafe { std::str::from_utf8_unchecked(slice) }
502 }
503
504 /// # Safety
505 ///
506 /// The caller must ensure that `mem` is valid for writes up to `size_of::<T>() * len`, and that
507 /// that memory stays allocated and not shared for the lifetime of `self`. This must hold even
508 /// if `iter.next()` allocates onto `self`.
509 #[inline]
510 unsafe fn write_from_iter<T, I: Iterator<Item = T>>(
511 &self,
512 mut iter: I,
513 len: usize,
514 mem: *mut T,
515 ) -> &mut [T] {
516 let mut i = 0;
517 // Use a manual loop since LLVM manages to optimize it better for
518 // slice iterators
519 loop {
520 // SAFETY: The caller must ensure that `mem` is valid for writes up to
521 // `size_of::<T>() * len`.
522 unsafe {
523 match iter.next() {
524 Some(value) if i < len => mem.add(i).write(value),
525 Some(_) | None => {
526 // We only return as many items as the iterator gave us, even
527 // though it was supposed to give us `len`
528 return slice::from_raw_parts_mut(mem, i);
529 }
530 }
531 }
532 i += 1;
533 }
534 }
535
536 #[inline]
537 pub fn alloc_from_iter<T, I: IntoIterator<Item = T>>(&self, iter: I) -> &mut [T] {
538 // Warning: this function is reentrant: `iter` could hold a reference to `&self` and
539 // allocate additional elements while we're iterating.
540 let iter = iter.into_iter();
541 assert!(size_of::<T>() != 0);
542 assert!(!mem::needs_drop::<T>());
543
544 let size_hint = iter.size_hint();
545
546 match size_hint {
547 (min, Some(max)) if min == max => {
548 // We know the exact number of elements the iterator expects to produce here.
549 let len = min;
550
551 if len == 0 {
552 return &mut [];
553 }
554
555 let mem = self.alloc_raw(Layout::array::<T>(len).unwrap()) as *mut T;
556 // SAFETY: `write_from_iter` doesn't touch `self`. It only touches the slice we just
557 // reserved. If the iterator panics or doesn't output `len` elements, this will
558 // leave some unallocated slots in the arena, which is fine because we do not call
559 // `drop`.
560 unsafe { self.write_from_iter(iter, len, mem) }
561 }
562 (_, _) => {
563 outline(move || -> &mut [T] {
564 // Takes care of reentrancy.
565 let mut vec: SmallVec<[_; 8]> = iter.collect();
566 if vec.is_empty() {
567 return &mut [];
568 }
569 // Move the content to the arena by copying it and then forgetting
570 // the content of the SmallVec
571 unsafe {
572 let len = vec.len();
573 let start_ptr =
574 self.alloc_raw(Layout::for_value::<[T]>(vec.as_slice())) as *mut T;
575 vec.as_ptr().copy_to_nonoverlapping(start_ptr, len);
576 vec.set_len(0);
577 slice::from_raw_parts_mut(start_ptr, len)
578 }
579 })
580 }
581 }
582 }
583}
584
585/// Declare an `Arena` containing one dropless arena and many typed arenas (the
586/// types of the typed arenas are specified by the arguments).
587///
588/// There are three cases of interest.
589/// - Types that are `Copy`: these need not be specified in the arguments. They
590/// will use the `DroplessArena`.
591/// - Types that are `!Copy` and `!Drop`: these must be specified in the
592/// arguments. An empty `TypedArena` will be created for each one, but the
593/// `DroplessArena` will always be used and the `TypedArena` will stay empty.
594/// This is odd but harmless, because an empty arena allocates no memory.
595/// - Types that are `!Copy` and `Drop`: these must be specified in the
596/// arguments. The `TypedArena` will be used for them.
597///
598#[macro_export]
599macro_rules! declare_arena {
600 ([$($a:tt $name:ident: $ty:ty,)*])=> {
601 #[derive(Default)]
602 pub struct Arena<'tcx> {
603 pub dropless: $crate::DroplessArena,
604 $($name: $crate::TypedArena<$ty>,)*
605 }
606
607 pub trait ArenaAllocatable<'tcx, C = rustc_arena::IsNotCopy>: Sized {
608 #[allow(clippy::mut_from_ref)]
609 fn allocate_on(self, arena: &'tcx Arena<'tcx>) -> &'tcx mut Self;
610 #[allow(clippy::mut_from_ref)]
611 fn allocate_from_iter(
612 arena: &'tcx Arena<'tcx>,
613 iter: impl ::std::iter::IntoIterator<Item = Self>,
614 ) -> &'tcx mut [Self];
615 }
616
617 // Any type that impls `Copy` can be arena-allocated in the `DroplessArena`.
618 impl<'tcx, T: Copy> ArenaAllocatable<'tcx, rustc_arena::IsCopy> for T {
619 #[inline]
620 #[allow(clippy::mut_from_ref)]
621 fn allocate_on(self, arena: &'tcx Arena<'tcx>) -> &'tcx mut Self {
622 arena.dropless.alloc(self)
623 }
624 #[inline]
625 #[allow(clippy::mut_from_ref)]
626 fn allocate_from_iter(
627 arena: &'tcx Arena<'tcx>,
628 iter: impl ::std::iter::IntoIterator<Item = Self>,
629 ) -> &'tcx mut [Self] {
630 arena.dropless.alloc_from_iter(iter)
631 }
632 }
633 $(
634 impl<'tcx> ArenaAllocatable<'tcx, rustc_arena::IsNotCopy> for $ty {
635 #[inline]
636 fn allocate_on(self, arena: &'tcx Arena<'tcx>) -> &'tcx mut Self {
637 if !::std::mem::needs_drop::<Self>() {
638 arena.dropless.alloc(self)
639 } else {
640 arena.$name.alloc(self)
641 }
642 }
643
644 #[inline]
645 #[allow(clippy::mut_from_ref)]
646 fn allocate_from_iter(
647 arena: &'tcx Arena<'tcx>,
648 iter: impl ::std::iter::IntoIterator<Item = Self>,
649 ) -> &'tcx mut [Self] {
650 if !::std::mem::needs_drop::<Self>() {
651 arena.dropless.alloc_from_iter(iter)
652 } else {
653 arena.$name.alloc_from_iter(iter)
654 }
655 }
656 }
657 )*
658
659 impl<'tcx> Arena<'tcx> {
660 #[inline]
661 #[allow(clippy::mut_from_ref)]
662 pub fn alloc<T: ArenaAllocatable<'tcx, C>, C>(&'tcx self, value: T) -> &mut T {
663 value.allocate_on(self)
664 }
665
666 // Any type that impls `Copy` can have slices be arena-allocated in the `DroplessArena`.
667 #[inline]
668 #[allow(clippy::mut_from_ref)]
669 pub fn alloc_slice<T: ::std::marker::Copy>(&self, value: &[T]) -> &mut [T] {
670 if value.is_empty() {
671 return &mut [];
672 }
673 self.dropless.alloc_slice(value)
674 }
675
676 #[inline]
677 pub fn alloc_str(&self, string: &str) -> &str {
678 if string.is_empty() {
679 return "";
680 }
681 self.dropless.alloc_str(string)
682 }
683
684 #[allow(clippy::mut_from_ref)]
685 pub fn alloc_from_iter<T: ArenaAllocatable<'tcx, C>, C>(
686 &'tcx self,
687 iter: impl ::std::iter::IntoIterator<Item = T>,
688 ) -> &mut [T] {
689 T::allocate_from_iter(self, iter)
690 }
691 }
692 };
693}
694
695// Marker types that let us give different behaviour for arenas allocating
696// `Copy` types vs `!Copy` types.
697pub struct IsCopy;
698pub struct IsNotCopy;
699
700#[cfg(test)]
701mod tests;