bumpalo/lib.rs
1#![doc = include_str!("../README.md")]
2#![deny(missing_debug_implementations)]
3#![deny(missing_docs)]
4#![cfg_attr(not(feature = "std"), no_std)]
5#![cfg_attr(feature = "allocator_api", feature(allocator_api))]
6
7#[doc(hidden)]
8pub extern crate alloc as core_alloc;
9
10#[cfg(feature = "boxed")]
11pub mod boxed;
12#[cfg(feature = "collections")]
13pub mod collections;
14
15mod alloc;
16
17use core::cell::Cell;
18use core::cmp::Ordering;
19use core::fmt::Display;
20use core::iter;
21use core::marker::PhantomData;
22use core::mem;
23use core::ptr::{self, NonNull};
24use core::slice;
25use core::str;
26use core_alloc::alloc::{alloc, dealloc, Layout};
27
28#[cfg(feature = "allocator_api")]
29use core_alloc::alloc::{AllocError, Allocator};
30
31#[cfg(all(feature = "allocator-api2", not(feature = "allocator_api")))]
32use allocator_api2::alloc::{AllocError, Allocator};
33
34pub use alloc::AllocErr;
35
36/// An error returned from [`Bump::try_alloc_try_with`].
37#[derive(Clone, PartialEq, Eq, Debug)]
38pub enum AllocOrInitError<E> {
39 /// Indicates that the initial allocation failed.
40 Alloc(AllocErr),
41 /// Indicates that the initializer failed with the contained error after
42 /// allocation.
43 ///
44 /// It is possible but not guaranteed that the allocated memory has been
45 /// released back to the allocator at this point.
46 Init(E),
47}
48impl<E> From<AllocErr> for AllocOrInitError<E> {
49 fn from(e: AllocErr) -> Self {
50 Self::Alloc(e)
51 }
52}
53impl<E: Display> Display for AllocOrInitError<E> {
54 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
55 match self {
56 AllocOrInitError::Alloc(err) => err.fmt(f),
57 AllocOrInitError::Init(err) => write!(f, "initialization failed: {}", err),
58 }
59 }
60}
61
62/// An RAII guard to rewind an allocation on drop (due to failed initialization
63/// of the allocation).
64#[derive(Debug)]
65struct RewindGuard<'a, const MIN_ALIGN: usize> {
66 bump: &'a Bump<MIN_ALIGN>,
67
68 /// The pointer we are guarding.
69 ptr: NonNull<u8>,
70
71 /// The `ChunkFooter` we are rewinding to.
72 rewind_footer: NonNull<ChunkFooter>,
73
74 /// The bump pointer within that `ChunkFooter` we are rewinding to.
75 rewind_footer_ptr: NonNull<u8>,
76
77 /// Whether the guard is active, and should rewind on drop.
78 active: bool,
79}
80
81impl<'a, const MIN_ALIGN: usize> RewindGuard<'a, MIN_ALIGN> {
82 /// # Safety
83 ///
84 /// * `ptr` must be the most-recent allocation in `bump`
85 ///
86 /// * `ptr` must have been allocated with the given `layout`.
87 ///
88 /// * `rewind_footer` must be the `bump`'s chunk footer pointer just before
89 /// `ptr`'s allocation.
90 ///
91 /// * `rewind_footer_ptr` must be the `bump`'s chunk footer's bump pointer
92 /// just before `ptr`'s allocation.
93 ///
94 /// Ownership of `ptr` is moved into this guard, and it must not be used
95 /// again except through this guard.
96 unsafe fn new(
97 bump: &'a Bump<MIN_ALIGN>,
98 ptr: NonNull<u8>,
99 rewind_footer: NonNull<ChunkFooter>,
100 rewind_footer_ptr: NonNull<u8>,
101 ) -> Self {
102 Self {
103 bump,
104 ptr,
105 rewind_footer,
106 rewind_footer_ptr,
107 active: true,
108 }
109 }
110
111 /// Finish this guard, yielding ownership of its pointer.
112 fn finish(mut self) -> NonNull<u8> {
113 self.active = false;
114 self.ptr
115 }
116}
117
118impl<const MIN_ALIGN: usize> Drop for RewindGuard<'_, MIN_ALIGN> {
119 fn drop(&mut self) {
120 if !self.active || !self.bump.is_last_allocation(self.ptr) {
121 return;
122 }
123
124 // When our pointer was the last allocation in the bump, we can reclaim
125 // its space. In fact, sometimes we can do even better than simply
126 // calling `dealloc`: we can reclaim any alignment padding we might have
127 // added (which `dealloc` cannot do) if we didn't allocate a new chunk
128 // for this result.
129 unsafe {
130 let current_footer = self.bump.current_chunk_footer.get();
131 if current_footer == self.rewind_footer {
132 // It's still the same chunk, so rewind the bump pointer to its
133 // original value (reclaiming any alignment padding we may have
134 // added).
135 current_footer.as_ref().ptr.set(self.rewind_footer_ptr);
136 } else {
137 // We allocated a new chunk for this pointer.
138 //
139 // We know our pointer is the only allocation in this chunk:
140 // `self.ptr` was the most-recent allocation in `self.bump`
141 // (guaranteed by `RewindGuard::new` callers) and if control reaches
142 // here then it is also the last allocation in `self.bump`, and
143 // therefore it is the only allocation in this chunk.
144 //
145 // Because this is the only allocation in this chunk, we can reset
146 // the chunk's bump pointer to the start of the chunk.
147 let bump_ptr =
148 round_mut_ptr_down_to(current_footer.cast::<u8>().as_ptr(), MIN_ALIGN);
149 debug_assert_eq!(bump_ptr as usize % MIN_ALIGN, 0);
150 let data = current_footer.as_ref().data;
151 let bump_ptr = NonNull::new_unchecked(bump_ptr);
152 debug_assert!(
153 data <= bump_ptr,
154 "bump pointer {bump_ptr:#p} should still be greater than or equal to the \
155 start of the bump chunk {data:#p}"
156 );
157 current_footer.as_ref().ptr.set(bump_ptr);
158 }
159 }
160 }
161}
162
163/// An arena to bump allocate into.
164///
165/// ## No `Drop`s
166///
167/// Objects that are bump-allocated will never have their [`Drop`] implementation
168/// called — unless you do it manually yourself. This makes it relatively
169/// easy to leak memory or other resources.
170///
171/// If you have a type which internally manages
172///
173/// * an allocation from the global heap (e.g. [`Vec<T>`]),
174/// * open file descriptors (e.g. [`std::fs::File`]), or
175/// * any other resource that must be cleaned up (e.g. an `mmap`)
176///
177/// and relies on its `Drop` implementation to clean up the internal resource,
178/// then if you allocate that type with a `Bump`, you need to find a new way to
179/// clean up after it yourself.
180///
181/// Potential solutions are:
182///
183/// * Using [`bumpalo::boxed::Box::new_in`] instead of [`Bump::alloc`], that
184/// will drop wrapped values similarly to [`std::boxed::Box`]. Note that this
185/// requires enabling the `"boxed"` Cargo feature for this crate. **This is
186/// often the easiest solution.**
187///
188/// * Calling [`drop_in_place`][drop_in_place] or using
189/// [`std::mem::ManuallyDrop`][manuallydrop] to manually drop these types.
190///
191/// * Using [`bumpalo::collections::Vec`] instead of [`std::vec::Vec`].
192///
193/// * Avoiding allocating these problematic types within a `Bump`.
194///
195/// Note that not calling `Drop` is memory safe! Destructors are never
196/// guaranteed to run in Rust, you can't rely on them for enforcing memory
197/// safety.
198///
199/// [`Drop`]: https://doc.rust-lang.org/std/ops/trait.Drop.html
200/// [`Vec<T>`]: https://doc.rust-lang.org/std/vec/struct.Vec.html
201/// [`std::fs::File`]: https://doc.rust-lang.org/std/fs/struct.File.html
202/// [drop_in_place]: https://doc.rust-lang.org/std/ptr/fn.drop_in_place.html
203/// [manuallydrop]: https://doc.rust-lang.org/std/mem/struct.ManuallyDrop.html
204/// [`bumpalo::collections::Vec`]: collections/vec/struct.Vec.html
205/// [`std::vec::Vec`]: https://doc.rust-lang.org/std/vec/struct.Vec.html
206/// [`bumpalo::boxed::Box::new_in`]: boxed/struct.Box.html#method.new_in
207/// [`std::boxed::Box`]: https://doc.rust-lang.org/std/boxed/struct.Box.html
208///
209/// ## Example
210///
211/// ```
212/// use bumpalo::Bump;
213///
214/// // Create a new bump arena.
215/// let bump = Bump::new();
216///
217/// // Allocate values into the arena.
218/// let forty_two = bump.alloc(42);
219/// assert_eq!(*forty_two, 42);
220///
221/// // Mutable references are returned from allocation.
222/// let mut s = bump.alloc("bumpalo");
223/// *s = "the bump allocator; and also is a buffalo";
224/// ```
225///
226/// ## Allocation Methods Come in Many Flavors
227///
228/// There are various allocation methods on `Bump`, the simplest being
229/// [`alloc`][Bump::alloc]. The others exist to satisfy some combination of
230/// fallible allocation and initialization. The allocation methods are
231/// summarized in the following table:
232///
233/// <table>
234/// <thead>
235/// <tr>
236/// <th></th>
237/// <th>Infallible Allocation</th>
238/// <th>Fallible Allocation</th>
239/// </tr>
240/// </thead>
241/// <tr>
242/// <th>By Value</th>
243/// <td><a href="#method.alloc"><code>alloc</code></a></td>
244/// <td><a href="#method.try_alloc"><code>try_alloc</code></a></td>
245/// </tr>
246/// <tr>
247/// <th>Infallible Initializer Function</th>
248/// <td><a href="#method.alloc_with"><code>alloc_with</code></a></td>
249/// <td><a href="#method.try_alloc_with"><code>try_alloc_with</code></a></td>
250/// </tr>
251/// <tr>
252/// <th>Fallible Initializer Function</th>
253/// <td><a href="#method.alloc_try_with"><code>alloc_try_with</code></a></td>
254/// <td><a href="#method.try_alloc_try_with"><code>try_alloc_try_with</code></a></td>
255/// </tr>
256/// <tbody>
257/// </tbody>
258/// </table>
259///
260/// ### Fallible Allocation: The `try_alloc_` Method Prefix
261///
262/// These allocation methods let you recover from out-of-memory (OOM)
263/// scenarios, rather than raising a panic on OOM.
264///
265/// ```
266/// use bumpalo::Bump;
267///
268/// let bump = Bump::new();
269///
270/// match bump.try_alloc(MyStruct {
271/// // ...
272/// }) {
273/// Ok(my_struct) => {
274/// // Allocation succeeded.
275/// }
276/// Err(e) => {
277/// // Out of memory.
278/// }
279/// }
280///
281/// struct MyStruct {
282/// // ...
283/// }
284/// ```
285///
286/// ### Initializer Functions: The `_with` Method Suffix
287///
288/// Calling one of the generic `…alloc(x)` methods is essentially equivalent to
289/// the matching [`…alloc_with(|| x)`](?search=alloc_with). However if you use
290/// `…alloc_with`, then the closure will not be invoked until after allocating
291/// space for storing `x` on the heap.
292///
293/// This can be useful in certain edge-cases related to compiler optimizations.
294/// When evaluating for example `bump.alloc(x)`, semantically `x` is first put
295/// on the stack and then moved onto the heap. In some cases, the compiler is
296/// able to optimize this into constructing `x` directly on the heap, however
297/// in many cases it does not.
298///
299/// The `…alloc_with` functions try to help the compiler be smarter. In most
300/// cases doing for example `bump.try_alloc_with(|| x)` on release mode will be
301/// enough to help the compiler realize that this optimization is valid and
302/// to construct `x` directly onto the heap.
303///
304/// #### Warning
305///
306/// These functions critically depend on compiler optimizations to achieve their
307/// desired effect. This means that it is not an effective tool when compiling
308/// without optimizations on.
309///
310/// Even when optimizations are on, these functions do not **guarantee** that
311/// the value is constructed on the heap. To the best of our knowledge no such
312/// guarantee can be made in stable Rust as of 1.54.
313///
314/// ### Fallible Initialization: The `_try_with` Method Suffix
315///
316/// The generic [`…alloc_try_with(|| x)`](?search=_try_with) methods behave
317/// like the purely `_with` suffixed methods explained above. However, they
318/// allow for fallible initialization by accepting a closure that returns a
319/// [`Result`] and will attempt to undo the initial allocation if this closure
320/// returns [`Err`].
321///
322/// #### Warning
323///
324/// If the inner closure returns [`Ok`], space for the entire [`Result`] remains
325/// allocated inside `self`. This can be a problem especially if the [`Err`]
326/// variant is larger, but even otherwise there may be overhead for the
327/// [`Result`]'s discriminant.
328///
329/// <p><details><summary>Undoing the allocation in the <code>Err</code> case
330/// always fails if <code>f</code> successfully made any additional allocations
331/// in <code>self</code>.</summary>
332///
333/// For example, the following will always leak also space for the [`Result`]
334/// into this `Bump`, even though the inner reference isn't kept and the [`Err`]
335/// payload is returned semantically by value:
336///
337/// ```rust
338/// let bump = bumpalo::Bump::new();
339///
340/// let r: Result<&mut [u8; 1000], ()> = bump.alloc_try_with(|| {
341/// let _ = bump.alloc(0_u8);
342/// Err(())
343/// });
344///
345/// assert!(r.is_err());
346/// ```
347///
348///</details></p>
349///
350/// Since [`Err`] payloads are first placed on the heap and then moved to the
351/// stack, `bump.…alloc_try_with(|| x)?` is likely to execute more slowly than
352/// the matching `bump.…alloc(x?)` in case of initialization failure. If this
353/// happens frequently, using the plain un-suffixed method may perform better.
354///
355/// [`Result`]: https://doc.rust-lang.org/std/result/enum.Result.html
356/// [`Ok`]: https://doc.rust-lang.org/std/result/enum.Result.html#variant.Ok
357/// [`Err`]: https://doc.rust-lang.org/std/result/enum.Result.html#variant.Err
358///
359/// ### `Bump` Allocation Limits
360///
361/// `bumpalo` supports setting a limit on the maximum bytes of memory that can
362/// be allocated for use in a particular `Bump` arena. This limit can be set and removed with
363/// [`set_allocation_limit`][Bump::set_allocation_limit].
364/// The allocation limit is only enforced when allocating new backing chunks for
365/// a `Bump`. Updating the allocation limit will not affect existing allocations
366/// or any future allocations within the `Bump`'s current chunk.
367///
368/// #### Example
369///
370/// ```
371/// let bump = bumpalo::Bump::new();
372///
373/// assert_eq!(bump.allocation_limit(), None);
374/// bump.set_allocation_limit(Some(0));
375///
376/// assert!(bump.try_alloc(5).is_err());
377///
378/// bump.set_allocation_limit(Some(6));
379///
380/// assert_eq!(bump.allocation_limit(), Some(6));
381///
382/// bump.set_allocation_limit(None);
383///
384/// assert_eq!(bump.allocation_limit(), None);
385/// ```
386///
387/// #### Warning
388///
389/// Because of backwards compatibility, allocations that fail
390/// due to allocation limits will not present differently than
391/// errors due to resource exhaustion.
392#[derive(Debug)]
393pub struct Bump<const MIN_ALIGN: usize = 1> {
394 // The current chunk we are bump allocating within.
395 current_chunk_footer: Cell<NonNull<ChunkFooter>>,
396 allocation_limit: Cell<Option<usize>>,
397}
398
399#[repr(C)]
400#[repr(align(16))]
401#[derive(Debug)]
402struct ChunkFooter {
403 // Pointer to the start of this chunk allocation. This footer is always at
404 // the end of the chunk.
405 data: NonNull<u8>,
406
407 // The layout of this chunk's allocation.
408 layout: Layout,
409
410 // Link to the previous chunk.
411 //
412 // Note that the last node in the `prev` linked list is the canonical empty
413 // chunk, whose `prev` link points to itself.
414 prev: Cell<NonNull<ChunkFooter>>,
415
416 // Bump allocation finger that is always in the range `self.data..=self`.
417 ptr: Cell<NonNull<u8>>,
418
419 // The bytes allocated in all chunks so far, the canonical empty chunk has
420 // a size of 0 and for all other chunks, `allocated_bytes` will be
421 // the allocated_bytes of the current chunk plus the allocated bytes
422 // of the `prev` chunk.
423 allocated_bytes: usize,
424}
425
426/// A wrapper type for the canonical, statically allocated empty chunk.
427///
428/// For the canonical empty chunk to be `static`, its type must be `Sync`, which
429/// is the purpose of this wrapper type. This is safe because the empty chunk is
430/// immutable and never actually modified.
431#[repr(transparent)]
432struct EmptyChunkFooter(ChunkFooter);
433
434unsafe impl Sync for EmptyChunkFooter {}
435
436static EMPTY_CHUNK: EmptyChunkFooter = EmptyChunkFooter(ChunkFooter {
437 // This chunk is empty (except the foot itself).
438 layout: Layout::new::<ChunkFooter>(),
439
440 // The start of the (empty) allocatable region for this chunk is itself.
441 data: unsafe { NonNull::new_unchecked(&EMPTY_CHUNK as *const EmptyChunkFooter as *mut u8) },
442
443 // The end of the (empty) allocatable region for this chunk is also itself.
444 ptr: Cell::new(unsafe {
445 NonNull::new_unchecked(&EMPTY_CHUNK as *const EmptyChunkFooter as *mut u8)
446 }),
447
448 // Invariant: the last chunk footer in all `ChunkFooter::prev` linked lists
449 // is the empty chunk footer, whose `prev` points to itself.
450 prev: Cell::new(unsafe {
451 NonNull::new_unchecked(&EMPTY_CHUNK as *const EmptyChunkFooter as *mut ChunkFooter)
452 }),
453
454 // Empty chunks count as 0 allocated bytes in an arena.
455 allocated_bytes: 0,
456});
457
458impl EmptyChunkFooter {
459 fn get(&'static self) -> NonNull<ChunkFooter> {
460 NonNull::from(&self.0)
461 }
462}
463
464impl ChunkFooter {
465 // Returns the start and length of the currently allocated region of this
466 // chunk.
467 fn as_raw_parts(&self) -> (*const u8, usize) {
468 let data = self.data.as_ptr() as *const u8;
469 let ptr = self.ptr.get().as_ptr() as *const u8;
470 debug_assert!(data <= ptr);
471 debug_assert!(ptr <= self as *const ChunkFooter as *const u8);
472 let len = unsafe { (self as *const ChunkFooter as *const u8).offset_from(ptr) as usize };
473 (ptr, len)
474 }
475
476 /// Is this chunk the last empty chunk?
477 fn is_empty(&self) -> bool {
478 ptr::eq(self, EMPTY_CHUNK.get().as_ptr())
479 }
480}
481
482impl<const MIN_ALIGN: usize> Default for Bump<MIN_ALIGN> {
483 fn default() -> Self {
484 Self::with_min_align()
485 }
486}
487
488impl<const MIN_ALIGN: usize> Drop for Bump<MIN_ALIGN> {
489 fn drop(&mut self) {
490 unsafe {
491 dealloc_chunk_list(self.current_chunk_footer.get());
492 }
493 }
494}
495
496#[inline]
497unsafe fn dealloc_chunk_list(mut footer: NonNull<ChunkFooter>) {
498 while !footer.as_ref().is_empty() {
499 let f = footer;
500 footer = f.as_ref().prev.get();
501 dealloc(f.as_ref().data.as_ptr(), f.as_ref().layout);
502 }
503}
504
505// `Bump`s are safe to send between threads because nothing aliases its owned
506// chunks until you start allocating from it. But by the time you allocate from
507// it, the returned references to allocations borrow the `Bump` and therefore
508// prevent sending the `Bump` across threads until the borrows end.
509unsafe impl<const MIN_ALIGN: usize> Send for Bump<MIN_ALIGN> {}
510
511#[inline]
512fn is_pointer_aligned_to<T>(pointer: *mut T, align: usize) -> bool {
513 debug_assert!(align.is_power_of_two());
514
515 let pointer = pointer as usize;
516 let pointer_aligned = round_down_to(pointer, align);
517 pointer == pointer_aligned
518}
519
520#[inline]
521pub(crate) const fn round_up_to(n: usize, divisor: usize) -> Option<usize> {
522 debug_assert!(divisor > 0);
523 debug_assert!(divisor.is_power_of_two());
524 match n.checked_add(divisor - 1) {
525 Some(x) => Some(x & !(divisor - 1)),
526 None => None,
527 }
528}
529
530/// Like `round_up_to` but turns overflow into undefined behavior rather than
531/// returning `None`.
532#[inline]
533pub(crate) unsafe fn round_up_to_unchecked(n: usize, divisor: usize) -> usize {
534 match round_up_to(n, divisor) {
535 Some(x) => x,
536 None => {
537 debug_assert!(false, "round_up_to_unchecked failed");
538 core::hint::unreachable_unchecked()
539 }
540 }
541}
542
543#[inline]
544pub(crate) fn round_down_to(n: usize, divisor: usize) -> usize {
545 debug_assert!(divisor > 0);
546 debug_assert!(divisor.is_power_of_two());
547 n & !(divisor - 1)
548}
549
550/// Same as `round_down_to` but preserves pointer provenance.
551#[inline]
552pub(crate) fn round_mut_ptr_down_to(ptr: *mut u8, divisor: usize) -> *mut u8 {
553 debug_assert!(divisor > 0);
554 debug_assert!(divisor.is_power_of_two());
555 ptr.wrapping_sub(ptr as usize & (divisor - 1))
556}
557
558#[inline]
559pub(crate) unsafe fn round_mut_ptr_up_to_unchecked(ptr: *mut u8, divisor: usize) -> *mut u8 {
560 debug_assert!(divisor > 0);
561 debug_assert!(divisor.is_power_of_two());
562 let aligned = round_up_to_unchecked(ptr as usize, divisor);
563 let delta = aligned - (ptr as usize);
564 ptr.add(delta)
565}
566
567// The typical page size these days.
568//
569// Note that we don't need to exactly match page size for correctness, and it is
570// okay if this is smaller than the real page size in practice. It isn't worth
571// the portability concerns and lack of const propagation that dynamically
572// looking up the actual page size implies.
573const TYPICAL_PAGE_SIZE: usize = 0x1000;
574
575// We only support alignments of up to 16 bytes for iter_allocated_chunks.
576const SUPPORTED_ITER_ALIGNMENT: usize = 16;
577const CHUNK_ALIGN: usize = SUPPORTED_ITER_ALIGNMENT;
578const FOOTER_SIZE: usize = mem::size_of::<ChunkFooter>();
579
580// Assert that `ChunkFooter` is at the supported alignment. This will give a
581// compile time error if it is not the case
582const _FOOTER_ALIGN_ASSERTION: () = {
583 assert!(mem::align_of::<ChunkFooter>() == CHUNK_ALIGN);
584};
585
586// Maximum typical overhead per allocation imposed by allocators.
587const MALLOC_OVERHEAD: usize = 16;
588
589// This is the overhead from malloc, footer and alignment. For instance, if
590// we want to request a chunk of memory that has at least X bytes usable for
591// allocations (where X is aligned to CHUNK_ALIGN), then we expect that the
592// after adding a footer, malloc overhead and alignment, the chunk of memory
593// the allocator actually sets aside for us is X+OVERHEAD rounded up to the
594// nearest suitable size boundary.
595const OVERHEAD: usize = match round_up_to(MALLOC_OVERHEAD + FOOTER_SIZE, CHUNK_ALIGN) {
596 Some(x) => x,
597 None => panic!(),
598};
599
600// The target size of our first allocation, including our overhead. The
601// available bump capacity will be smaller.
602const FIRST_ALLOCATION_GOAL: usize = 1 << 9;
603
604// The actual size of the first allocation is going to be a bit smaller than the
605// goal. We need to make room for the footer, and we also need take the
606// alignment into account. We're trying to avoid this kind of situation:
607// https://blog.mozilla.org/nnethercote/2011/08/05/clownshoes-available-in-sizes-2101-and-up/
608const DEFAULT_CHUNK_SIZE_WITHOUT_FOOTER: usize = FIRST_ALLOCATION_GOAL - OVERHEAD;
609
610/// The memory size and alignment details for a potential new chunk
611/// allocation.
612#[derive(Debug, Clone, Copy)]
613struct NewChunkMemoryDetails {
614 new_size_without_footer: usize,
615 align: usize,
616 size: usize,
617}
618
619/// Wrapper around `Layout::from_size_align` that adds debug assertions.
620#[inline]
621fn layout_from_size_align(size: usize, align: usize) -> Result<Layout, AllocErr> {
622 Layout::from_size_align(size, align).map_err(|_| AllocErr)
623}
624
625#[cold]
626#[inline(never)]
627fn allocation_size_overflow<T>() -> T {
628 panic!("requested allocation size overflowed")
629}
630
631// NB: We don't have constructors as methods on `impl<N> Bump<N>` that return
632// `Self` because then `rustc` can't infer the `N` if it isn't explicitly
633// provided, even though it has a default value. There doesn't seem to be a good
634// workaround, other than putting constructors on the `Bump<DEFAULT>`; even
635// `std` does this same thing with `HashMap`, for example.
636impl Bump<1> {
637 /// Construct a new arena to bump allocate into.
638 ///
639 /// ## Example
640 ///
641 /// ```
642 /// let bump = bumpalo::Bump::new();
643 /// # let _ = bump;
644 /// ```
645 pub fn new() -> Self {
646 Self::with_capacity(0)
647 }
648
649 /// Attempt to construct a new arena to bump allocate into.
650 ///
651 /// ## Example
652 ///
653 /// ```
654 /// let bump = bumpalo::Bump::try_new();
655 /// # let _ = bump.unwrap();
656 /// ```
657 pub fn try_new() -> Result<Self, AllocErr> {
658 Bump::try_with_capacity(0)
659 }
660
661 /// Construct a new arena with the specified byte capacity to bump allocate
662 /// into.
663 ///
664 /// ## Example
665 ///
666 /// ```
667 /// let bump = bumpalo::Bump::with_capacity(100);
668 /// # let _ = bump;
669 /// ```
670 ///
671 /// ## Panics
672 ///
673 /// Panics if allocating the initial capacity fails.
674 pub fn with_capacity(capacity: usize) -> Self {
675 Self::try_with_capacity(capacity).unwrap_or_else(|_| oom())
676 }
677
678 /// Attempt to construct a new arena with the specified byte capacity to
679 /// bump allocate into.
680 ///
681 /// Propagates errors when allocating the initial capacity.
682 ///
683 /// ## Example
684 ///
685 /// ```
686 /// # fn _foo() -> Result<(), bumpalo::AllocErr> {
687 /// let bump = bumpalo::Bump::try_with_capacity(100)?;
688 /// # let _ = bump;
689 /// # Ok(())
690 /// # }
691 /// ```
692 pub fn try_with_capacity(capacity: usize) -> Result<Self, AllocErr> {
693 Self::try_with_min_align_and_capacity(capacity)
694 }
695}
696
697impl<const MIN_ALIGN: usize> Bump<MIN_ALIGN> {
698 /// Create a new `Bump` that enforces a minimum alignment.
699 ///
700 /// The minimum alignment must be a power of two and no larger than `16`.
701 ///
702 /// Enforcing a minimum alignment can speed up allocation of objects with
703 /// alignment less than or equal to the minimum alignment. This comes at the
704 /// cost of introducing otherwise-unnecessary padding between allocations of
705 /// objects with alignment less than the minimum.
706 ///
707 /// # Example
708 ///
709 /// ```
710 /// type BumpAlign8 = bumpalo::Bump<8>;
711 /// let bump = BumpAlign8::with_min_align();
712 /// for x in 0..u8::MAX {
713 /// let x = bump.alloc(x);
714 /// assert_eq!((x as *mut _ as usize) % 8, 0, "x is aligned to 8");
715 /// }
716 /// ```
717 ///
718 /// # Panics
719 ///
720 /// Panics on invalid minimum alignments.
721 //
722 // Because of `rustc`'s poor type inference for default type/const
723 // parameters (see the comment above the `impl Bump` block with no const
724 // `MIN_ALIGN` parameter) and because we don't want to force everyone to
725 // specify a minimum alignment with `Bump::new()` et al, we have a separate
726 // constructor for specifying the minimum alignment.
727 pub fn with_min_align() -> Self {
728 assert!(
729 MIN_ALIGN.is_power_of_two(),
730 "MIN_ALIGN must be a power of two; found {MIN_ALIGN}"
731 );
732 assert!(
733 MIN_ALIGN <= CHUNK_ALIGN,
734 "MIN_ALIGN may not be larger than {CHUNK_ALIGN}; found {MIN_ALIGN}"
735 );
736
737 Bump {
738 current_chunk_footer: Cell::new(EMPTY_CHUNK.get()),
739 allocation_limit: Cell::new(None),
740 }
741 }
742
743 /// Create a new `Bump` that enforces a minimum alignment and starts with
744 /// room for at least `capacity` bytes.
745 ///
746 /// The minimum alignment must be a power of two and no larger than `16`.
747 ///
748 /// Enforcing a minimum alignment can speed up allocation of objects with
749 /// alignment less than or equal to the minimum alignment. This comes at the
750 /// cost of introducing otherwise-unnecessary padding between allocations of
751 /// objects with alignment less than the minimum.
752 ///
753 /// # Example
754 ///
755 /// ```
756 /// type BumpAlign8 = bumpalo::Bump<8>;
757 /// let mut bump = BumpAlign8::with_min_align_and_capacity(8 * 100);
758 /// for x in 0..100_u64 {
759 /// let x = bump.alloc(x);
760 /// assert_eq!((x as *mut _ as usize) % 8, 0, "x is aligned to 8");
761 /// }
762 /// assert_eq!(
763 /// bump.iter_allocated_chunks().count(), 1,
764 /// "initial chunk had capacity for all allocations",
765 /// );
766 /// ```
767 ///
768 /// # Panics
769 ///
770 /// Panics on invalid minimum alignments.
771 ///
772 /// Panics if allocating the initial capacity fails.
773 pub fn with_min_align_and_capacity(capacity: usize) -> Self {
774 Self::try_with_min_align_and_capacity(capacity).unwrap_or_else(|_| oom())
775 }
776
777 /// Create a new `Bump` that enforces a minimum alignment and starts with
778 /// room for at least `capacity` bytes.
779 ///
780 /// The minimum alignment must be a power of two and no larger than `16`.
781 ///
782 /// Enforcing a minimum alignment can speed up allocation of objects with
783 /// alignment less than or equal to the minimum alignment. This comes at the
784 /// cost of introducing otherwise-unnecessary padding between allocations of
785 /// objects with alignment less than the minimum.
786 ///
787 /// # Example
788 ///
789 /// ```
790 /// # fn _foo() -> Result<(), bumpalo::AllocErr> {
791 /// type BumpAlign8 = bumpalo::Bump<8>;
792 /// let mut bump = BumpAlign8::try_with_min_align_and_capacity(8 * 100)?;
793 /// for x in 0..100_u64 {
794 /// let x = bump.alloc(x);
795 /// assert_eq!((x as *mut _ as usize) % 8, 0, "x is aligned to 8");
796 /// }
797 /// assert_eq!(
798 /// bump.iter_allocated_chunks().count(), 1,
799 /// "initial chunk had capacity for all allocations",
800 /// );
801 /// # Ok(())
802 /// # }
803 /// ```
804 ///
805 /// # Panics
806 ///
807 /// Panics on invalid minimum alignments.
808 ///
809 /// Panics if allocating the initial capacity fails.
810 pub fn try_with_min_align_and_capacity(capacity: usize) -> Result<Self, AllocErr> {
811 assert!(
812 MIN_ALIGN.is_power_of_two(),
813 "MIN_ALIGN must be a power of two; found {MIN_ALIGN}"
814 );
815 assert!(
816 MIN_ALIGN <= CHUNK_ALIGN,
817 "MIN_ALIGN may not be larger than {CHUNK_ALIGN}; found {MIN_ALIGN}"
818 );
819
820 if capacity == 0 {
821 return Ok(Bump {
822 current_chunk_footer: Cell::new(EMPTY_CHUNK.get()),
823 allocation_limit: Cell::new(None),
824 });
825 }
826
827 let layout = layout_from_size_align(capacity, MIN_ALIGN)?;
828
829 let chunk_footer = unsafe {
830 Self::new_chunk(
831 Self::new_chunk_memory_details(None, layout).ok_or(AllocErr)?,
832 layout,
833 EMPTY_CHUNK.get(),
834 )
835 .ok_or(AllocErr)?
836 };
837
838 Ok(Bump {
839 current_chunk_footer: Cell::new(chunk_footer),
840 allocation_limit: Cell::new(None),
841 })
842 }
843
844 /// Get this bump arena's minimum alignment.
845 ///
846 /// All objects allocated in this arena get aligned to this value.
847 ///
848 /// ## Example
849 ///
850 /// ```
851 /// let bump2 = bumpalo::Bump::<2>::with_min_align();
852 /// assert_eq!(bump2.min_align(), 2);
853 ///
854 /// let bump4 = bumpalo::Bump::<4>::with_min_align();
855 /// assert_eq!(bump4.min_align(), 4);
856 /// ```
857 #[inline]
858 pub fn min_align(&self) -> usize {
859 MIN_ALIGN
860 }
861
862 /// The allocation limit for this arena in bytes.
863 ///
864 /// ## Example
865 ///
866 /// ```
867 /// let bump = bumpalo::Bump::with_capacity(0);
868 ///
869 /// assert_eq!(bump.allocation_limit(), None);
870 ///
871 /// bump.set_allocation_limit(Some(6));
872 ///
873 /// assert_eq!(bump.allocation_limit(), Some(6));
874 ///
875 /// bump.set_allocation_limit(None);
876 ///
877 /// assert_eq!(bump.allocation_limit(), None);
878 /// ```
879 pub fn allocation_limit(&self) -> Option<usize> {
880 self.allocation_limit.get()
881 }
882
883 /// Set the allocation limit in bytes for this arena.
884 ///
885 /// The allocation limit is only enforced when allocating new backing chunks for
886 /// a `Bump`. Updating the allocation limit will not affect existing allocations
887 /// or any future allocations within the `Bump`'s current chunk.
888 ///
889 /// ## Example
890 ///
891 /// ```
892 /// let bump = bumpalo::Bump::with_capacity(0);
893 ///
894 /// bump.set_allocation_limit(Some(0));
895 ///
896 /// assert!(bump.try_alloc(5).is_err());
897 /// ```
898 pub fn set_allocation_limit(&self, limit: Option<usize>) {
899 self.allocation_limit.set(limit);
900 }
901
902 /// How much headroom an arena has before it hits its allocation
903 /// limit.
904 fn allocation_limit_remaining(&self) -> Option<usize> {
905 self.allocation_limit.get().and_then(|allocation_limit| {
906 let allocated_bytes = self.allocated_bytes();
907 if allocated_bytes > allocation_limit {
908 None
909 } else {
910 Some(usize::abs_diff(allocation_limit, allocated_bytes))
911 }
912 })
913 }
914
915 /// Whether a request to allocate a new chunk with a given size for a given
916 /// requested layout will fit under the allocation limit set on a `Bump`.
917 fn chunk_fits_under_limit(
918 allocation_limit_remaining: Option<usize>,
919 new_chunk_memory_details: NewChunkMemoryDetails,
920 ) -> bool {
921 allocation_limit_remaining
922 .map(|allocation_limit_left| {
923 allocation_limit_left >= new_chunk_memory_details.new_size_without_footer
924 })
925 .unwrap_or(true)
926 }
927
928 /// Determine the memory details including final size, alignment and final
929 /// size without footer for a new chunk that would be allocated to fulfill
930 /// an allocation request.
931 fn new_chunk_memory_details(
932 new_size_without_footer: Option<usize>,
933 requested_layout: Layout,
934 ) -> Option<NewChunkMemoryDetails> {
935 // We must have `CHUNK_ALIGN` or better alignment...
936 let align = CHUNK_ALIGN
937 // and we have to have at least our configured minimum alignment...
938 .max(MIN_ALIGN)
939 // and make sure we satisfy the requested allocation's alignment.
940 .max(requested_layout.align());
941
942 let mut new_size_without_footer =
943 new_size_without_footer.unwrap_or(DEFAULT_CHUNK_SIZE_WITHOUT_FOOTER);
944
945 let requested_size =
946 round_up_to(requested_layout.size(), align).unwrap_or_else(allocation_size_overflow);
947 new_size_without_footer = new_size_without_footer.max(requested_size);
948
949 // We want our allocations to play nice with the memory allocator, and
950 // waste as little memory as possible. For small allocations, this means
951 // that the entire allocation including the chunk footer and mallocs
952 // internal overhead is as close to a power of two as we can go without
953 // going over. For larger allocations, we only need to get close to a
954 // page boundary without going over.
955 if new_size_without_footer < TYPICAL_PAGE_SIZE {
956 new_size_without_footer =
957 (new_size_without_footer + OVERHEAD).next_power_of_two() - OVERHEAD;
958 } else {
959 new_size_without_footer =
960 round_up_to(new_size_without_footer + OVERHEAD, TYPICAL_PAGE_SIZE)? - OVERHEAD;
961 }
962
963 debug_assert_eq!(align % CHUNK_ALIGN, 0);
964 debug_assert_eq!(new_size_without_footer % CHUNK_ALIGN, 0);
965 let size = new_size_without_footer
966 .checked_add(FOOTER_SIZE)
967 .unwrap_or_else(allocation_size_overflow);
968
969 Some(NewChunkMemoryDetails {
970 new_size_without_footer,
971 size,
972 align,
973 })
974 }
975
976 /// Allocate a new chunk and return its initialized footer.
977 ///
978 /// If given, `layouts` is a tuple of the current chunk size and the
979 /// layout of the allocation request that triggered us to fall back to
980 /// allocating a new chunk of memory.
981 unsafe fn new_chunk(
982 new_chunk_memory_details: NewChunkMemoryDetails,
983 requested_layout: Layout,
984 prev: NonNull<ChunkFooter>,
985 ) -> Option<NonNull<ChunkFooter>> {
986 let NewChunkMemoryDetails {
987 new_size_without_footer,
988 align,
989 size,
990 } = new_chunk_memory_details;
991
992 let layout = layout_from_size_align(size, align).ok()?;
993
994 debug_assert!(size >= requested_layout.size());
995
996 let data = alloc(layout);
997 let data = NonNull::new(data)?;
998
999 // The `ChunkFooter` is at the end of the chunk.
1000 let footer_ptr = data.as_ptr().add(new_size_without_footer);
1001 debug_assert_eq!((data.as_ptr() as usize) % align, 0);
1002 debug_assert_eq!(footer_ptr as usize % CHUNK_ALIGN, 0);
1003 let footer_ptr = footer_ptr as *mut ChunkFooter;
1004
1005 // The bump pointer is initialized to the end of the range we will bump
1006 // out of, rounded down to the minimum alignment. It is the
1007 // `NewChunkMemoryDetails` constructor's responsibility to ensure that
1008 // even after this rounding we have enough non-zero capacity in the
1009 // chunk.
1010 let ptr = round_mut_ptr_down_to(footer_ptr.cast::<u8>(), MIN_ALIGN);
1011 debug_assert_eq!(ptr as usize % MIN_ALIGN, 0);
1012 debug_assert!(
1013 data.as_ptr() <= ptr,
1014 "bump pointer {ptr:#p} should still be greater than or equal to the \
1015 start of the bump chunk {data:#p}"
1016 );
1017 debug_assert_eq!(
1018 (ptr as usize) - (data.as_ptr() as usize),
1019 new_size_without_footer
1020 );
1021
1022 let ptr = Cell::new(NonNull::new_unchecked(ptr));
1023
1024 // The `allocated_bytes` of a new chunk counts the total size
1025 // of the chunks, not how much of the chunks are used.
1026 let allocated_bytes = prev.as_ref().allocated_bytes + new_size_without_footer;
1027
1028 ptr::write(
1029 footer_ptr,
1030 ChunkFooter {
1031 data,
1032 layout,
1033 prev: Cell::new(prev),
1034 ptr,
1035 allocated_bytes,
1036 },
1037 );
1038
1039 Some(NonNull::new_unchecked(footer_ptr))
1040 }
1041
1042 /// Reset this bump allocator.
1043 ///
1044 /// Performs mass deallocation on everything allocated in this arena by
1045 /// resetting the pointer into the underlying chunk of memory to the start
1046 /// of the chunk. Does not run any `Drop` implementations on deallocated
1047 /// objects; see [the top-level documentation](struct.Bump.html) for details.
1048 ///
1049 /// If this arena has allocated multiple chunks to bump allocate into, then
1050 /// the excess chunks are returned to the global allocator.
1051 ///
1052 /// ## Example
1053 ///
1054 /// ```
1055 /// let mut bump = bumpalo::Bump::new();
1056 ///
1057 /// // Allocate a bunch of things.
1058 /// {
1059 /// for i in 0..100 {
1060 /// bump.alloc(i);
1061 /// }
1062 /// }
1063 ///
1064 /// // Reset the arena.
1065 /// bump.reset();
1066 ///
1067 /// // Allocate some new things in the space previously occupied by the
1068 /// // original things.
1069 /// for j in 200..400 {
1070 /// bump.alloc(j);
1071 /// }
1072 ///```
1073 pub fn reset(&mut self) {
1074 // Takes `&mut self` so `self` must be unique and there can't be any
1075 // borrows active that would get invalidated by resetting.
1076 unsafe {
1077 if self.current_chunk_footer.get().as_ref().is_empty() {
1078 return;
1079 }
1080
1081 let mut cur_chunk = self.current_chunk_footer.get();
1082
1083 // Deallocate all chunks except the current one
1084 let prev_chunk = cur_chunk.as_ref().prev.replace(EMPTY_CHUNK.get());
1085 dealloc_chunk_list(prev_chunk);
1086
1087 // Reset the bump finger to the end of the chunk.
1088 debug_assert!(
1089 is_pointer_aligned_to(cur_chunk.as_ptr(), MIN_ALIGN),
1090 "bump pointer {cur_chunk:#p} should be aligned to the minimum alignment of {MIN_ALIGN:#x}"
1091 );
1092 cur_chunk.as_ref().ptr.set(cur_chunk.cast());
1093
1094 // Reset the allocated size of the chunk.
1095 cur_chunk.as_mut().allocated_bytes = cur_chunk.as_ref().layout.size() - FOOTER_SIZE;
1096
1097 debug_assert!(
1098 self.current_chunk_footer
1099 .get()
1100 .as_ref()
1101 .prev
1102 .get()
1103 .as_ref()
1104 .is_empty(),
1105 "We should only have a single chunk"
1106 );
1107 debug_assert_eq!(
1108 self.current_chunk_footer.get().as_ref().ptr.get(),
1109 self.current_chunk_footer.get().cast(),
1110 "Our chunk's bump finger should be reset to the start of its allocation"
1111 );
1112 }
1113 }
1114
1115 /// Allocate an object in this `Bump` and return an exclusive reference to
1116 /// it.
1117 ///
1118 /// ## Panics
1119 ///
1120 /// Panics if reserving space for `T` fails.
1121 ///
1122 /// ## Example
1123 ///
1124 /// ```
1125 /// let bump = bumpalo::Bump::new();
1126 /// let x = bump.alloc("hello");
1127 /// assert_eq!(*x, "hello");
1128 /// ```
1129 #[inline(always)]
1130 pub fn alloc<T>(&self, val: T) -> &mut T {
1131 self.alloc_with(|| val)
1132 }
1133
1134 /// Try to allocate an object in this `Bump` and return an exclusive
1135 /// reference to it.
1136 ///
1137 /// ## Errors
1138 ///
1139 /// Errors if reserving space for `T` fails.
1140 ///
1141 /// ## Example
1142 ///
1143 /// ```
1144 /// let bump = bumpalo::Bump::new();
1145 /// let x = bump.try_alloc("hello");
1146 /// assert_eq!(x, Ok(&mut "hello"));
1147 /// ```
1148 #[inline(always)]
1149 pub fn try_alloc<T>(&self, val: T) -> Result<&mut T, AllocErr> {
1150 self.try_alloc_with(|| val)
1151 }
1152
1153 /// Pre-allocate space for an object in this `Bump`, initializes it using
1154 /// the closure, then returns an exclusive reference to it.
1155 ///
1156 /// See [The `_with` Method Suffix](#initializer-functions-the-_with-method-suffix) for a
1157 /// discussion on the differences between the `_with` suffixed methods and
1158 /// those methods without it, their performance characteristics, and when
1159 /// you might or might not choose a `_with` suffixed method.
1160 ///
1161 /// ## Panics
1162 ///
1163 /// Panics if reserving space for `T` fails.
1164 ///
1165 /// ## Example
1166 ///
1167 /// ```
1168 /// let bump = bumpalo::Bump::new();
1169 /// let x = bump.alloc_with(|| "hello");
1170 /// assert_eq!(*x, "hello");
1171 /// ```
1172 #[inline(always)]
1173 pub fn alloc_with<F, T>(&self, f: F) -> &mut T
1174 where
1175 F: FnOnce() -> T,
1176 {
1177 #[inline(always)]
1178 unsafe fn inner_writer<T, F>(ptr: *mut T, f: F)
1179 where
1180 F: FnOnce() -> T,
1181 {
1182 // This function is translated as:
1183 // - allocate space for a T on the stack
1184 // - call f() with the return value being put onto this stack space
1185 // - memcpy from the stack to the heap
1186 //
1187 // Ideally we want LLVM to always realize that doing a stack
1188 // allocation is unnecessary and optimize the code so it writes
1189 // directly into the heap instead. It seems we get it to realize
1190 // this most consistently if we put this critical line into it's
1191 // own function instead of inlining it into the surrounding code.
1192 ptr::write(ptr, f());
1193 }
1194
1195 let layout = Layout::new::<T>();
1196
1197 unsafe {
1198 let p = self.alloc_layout(layout);
1199 let p = p.as_ptr() as *mut T;
1200 inner_writer(p, f);
1201 &mut *p
1202 }
1203 }
1204
1205 /// Tries to pre-allocate space for an object in this `Bump`, initializes
1206 /// it using the closure, then returns an exclusive reference to it.
1207 ///
1208 /// See [The `_with` Method Suffix](#initializer-functions-the-_with-method-suffix) for a
1209 /// discussion on the differences between the `_with` suffixed methods and
1210 /// those methods without it, their performance characteristics, and when
1211 /// you might or might not choose a `_with` suffixed method.
1212 ///
1213 /// ## Errors
1214 ///
1215 /// Errors if reserving space for `T` fails.
1216 ///
1217 /// ## Example
1218 ///
1219 /// ```
1220 /// let bump = bumpalo::Bump::new();
1221 /// let x = bump.try_alloc_with(|| "hello");
1222 /// assert_eq!(x, Ok(&mut "hello"));
1223 /// ```
1224 #[inline(always)]
1225 pub fn try_alloc_with<F, T>(&self, f: F) -> Result<&mut T, AllocErr>
1226 where
1227 F: FnOnce() -> T,
1228 {
1229 #[inline(always)]
1230 unsafe fn inner_writer<T, F>(ptr: *mut T, f: F)
1231 where
1232 F: FnOnce() -> T,
1233 {
1234 // This function is translated as:
1235 // - allocate space for a T on the stack
1236 // - call f() with the return value being put onto this stack space
1237 // - memcpy from the stack to the heap
1238 //
1239 // Ideally we want LLVM to always realize that doing a stack
1240 // allocation is unnecessary and optimize the code so it writes
1241 // directly into the heap instead. It seems we get it to realize
1242 // this most consistently if we put this critical line into it's
1243 // own function instead of inlining it into the surrounding code.
1244 ptr::write(ptr, f());
1245 }
1246
1247 //SAFETY: Self-contained:
1248 // `p` is allocated for `T` and then a `T` is written.
1249 let layout = Layout::new::<T>();
1250 let p = self.try_alloc_layout(layout)?;
1251 let p = p.as_ptr() as *mut T;
1252
1253 unsafe {
1254 inner_writer(p, f);
1255 Ok(&mut *p)
1256 }
1257 }
1258
1259 /// Pre-allocates space for a [`Result`] in this `Bump`, initializes it using
1260 /// the closure, then returns an exclusive reference to its `T` if [`Ok`].
1261 ///
1262 /// Iff the allocation fails, the closure is not run.
1263 ///
1264 /// Iff [`Err`], an allocator rewind is *attempted* and the `E` instance is
1265 /// moved out of the allocator to be consumed or dropped as normal.
1266 ///
1267 /// See [The `_with` Method Suffix](#initializer-functions-the-_with-method-suffix) for a
1268 /// discussion on the differences between the `_with` suffixed methods and
1269 /// those methods without it, their performance characteristics, and when
1270 /// you might or might not choose a `_with` suffixed method.
1271 ///
1272 /// For caveats specific to fallible initialization, see
1273 /// [The `_try_with` Method Suffix](#fallible-initialization-the-_try_with-method-suffix).
1274 ///
1275 /// [`Result`]: https://doc.rust-lang.org/std/result/enum.Result.html
1276 /// [`Ok`]: https://doc.rust-lang.org/std/result/enum.Result.html#variant.Ok
1277 /// [`Err`]: https://doc.rust-lang.org/std/result/enum.Result.html#variant.Err
1278 ///
1279 /// ## Errors
1280 ///
1281 /// Iff the allocation succeeds but `f` fails, that error is forwarded by value.
1282 ///
1283 /// ## Panics
1284 ///
1285 /// Panics if reserving space for `Result<T, E>` fails.
1286 ///
1287 /// ## Example
1288 ///
1289 /// ```
1290 /// let bump = bumpalo::Bump::new();
1291 /// let x = bump.alloc_try_with(|| Ok("hello"))?;
1292 /// assert_eq!(*x, "hello");
1293 /// # Result::<_, ()>::Ok(())
1294 /// ```
1295 #[inline(always)]
1296 pub fn alloc_try_with<F, T, E>(&self, f: F) -> Result<&mut T, E>
1297 where
1298 F: FnOnce() -> Result<T, E>,
1299 {
1300 match self.try_alloc_try_with(f) {
1301 Ok(x) => Ok(x),
1302 Err(AllocOrInitError::Init(e)) => Err(e),
1303 Err(AllocOrInitError::Alloc(_)) => oom(),
1304 }
1305 }
1306
1307 /// Tries to pre-allocates space for a [`Result`] in this `Bump`,
1308 /// initializes it using the closure, then returns an exclusive reference
1309 /// to its `T` if all [`Ok`].
1310 ///
1311 /// Iff the allocation fails, the closure is not run.
1312 ///
1313 /// Iff the closure returns [`Err`], an allocator rewind is *attempted* and
1314 /// the `E` instance is moved out of the allocator to be consumed or dropped
1315 /// as normal.
1316 ///
1317 /// See [The `_with` Method Suffix](#initializer-functions-the-_with-method-suffix) for a
1318 /// discussion on the differences between the `_with` suffixed methods and
1319 /// those methods without it, their performance characteristics, and when
1320 /// you might or might not choose a `_with` suffixed method.
1321 ///
1322 /// For caveats specific to fallible initialization, see
1323 /// [The `_try_with` Method Suffix](#fallible-initialization-the-_try_with-method-suffix).
1324 ///
1325 /// [`Result`]: https://doc.rust-lang.org/std/result/enum.Result.html
1326 /// [`Ok`]: https://doc.rust-lang.org/std/result/enum.Result.html#variant.Ok
1327 /// [`Err`]: https://doc.rust-lang.org/std/result/enum.Result.html#variant.Err
1328 ///
1329 /// ## Errors
1330 ///
1331 /// Errors with the [`Alloc`](`AllocOrInitError::Alloc`) variant iff
1332 /// reserving space for `Result<T, E>` fails.
1333 ///
1334 /// Iff the allocation succeeds but `f` fails, that error is forwarded by
1335 /// value inside the [`Init`](`AllocOrInitError::Init`) variant.
1336 ///
1337 /// ## Example
1338 ///
1339 /// ```
1340 /// let bump = bumpalo::Bump::new();
1341 /// let x = bump.try_alloc_try_with(|| Ok("hello"))?;
1342 /// assert_eq!(*x, "hello");
1343 /// # Result::<_, bumpalo::AllocOrInitError<()>>::Ok(())
1344 /// ```
1345 #[inline(always)]
1346 pub fn try_alloc_try_with<F, T, E>(&self, f: F) -> Result<&mut T, AllocOrInitError<E>>
1347 where
1348 F: FnOnce() -> Result<T, E>,
1349 {
1350 let rewind_footer = self.current_chunk_footer.get();
1351 let rewind_footer_ptr = unsafe { rewind_footer.as_ref() }.ptr.get();
1352 let ptr = self.try_alloc_with(f)?;
1353 let ptr = NonNull::from(ptr).cast::<u8>();
1354 let guard = unsafe { RewindGuard::new(self, ptr, rewind_footer, rewind_footer_ptr) };
1355 match unsafe { guard.ptr.cast::<Result<T, E>>().as_mut() } {
1356 Ok(t) => {
1357 guard.finish();
1358 Ok(unsafe { NonNull::from(t).as_mut() })
1359 }
1360 Err(e) => unsafe {
1361 // Read the error out and then let the guard rewind.
1362 Err(AllocOrInitError::Init(NonNull::from(e).as_ptr().read()))
1363 },
1364 }
1365 }
1366
1367 /// `Copy` a slice into this `Bump` and return an exclusive reference to
1368 /// the copy.
1369 ///
1370 /// ## Panics
1371 ///
1372 /// Panics if reserving space for the slice fails.
1373 ///
1374 /// ## Example
1375 ///
1376 /// ```
1377 /// let bump = bumpalo::Bump::new();
1378 /// let x = bump.alloc_slice_copy(&[1, 2, 3]);
1379 /// assert_eq!(x, &[1, 2, 3]);
1380 /// ```
1381 #[inline(always)]
1382 pub fn alloc_slice_copy<T>(&self, src: &[T]) -> &mut [T]
1383 where
1384 T: Copy,
1385 {
1386 let layout = Layout::for_value(src);
1387 let dst = self.alloc_layout(layout).cast::<T>();
1388
1389 unsafe {
1390 ptr::copy_nonoverlapping(src.as_ptr(), dst.as_ptr(), src.len());
1391 slice::from_raw_parts_mut(dst.as_ptr(), src.len())
1392 }
1393 }
1394
1395 /// Like `alloc_slice_copy`, but does not panic in case of allocation failure.
1396 ///
1397 /// ## Example
1398 ///
1399 /// ```
1400 /// let bump = bumpalo::Bump::new();
1401 /// let x = bump.try_alloc_slice_copy(&[1, 2, 3]);
1402 /// assert_eq!(x, Ok(&mut[1, 2, 3] as &mut [_]));
1403 ///
1404 ///
1405 /// let bump = bumpalo::Bump::new();
1406 /// bump.set_allocation_limit(Some(4));
1407 /// let x = bump.try_alloc_slice_copy(&[1, 2, 3, 4, 5, 6]);
1408 /// assert_eq!(x, Err(bumpalo::AllocErr)); // too big
1409 /// ```
1410 #[inline(always)]
1411 pub fn try_alloc_slice_copy<T>(&self, src: &[T]) -> Result<&mut [T], AllocErr>
1412 where
1413 T: Copy,
1414 {
1415 let layout = Layout::for_value(src);
1416 let dst = self.try_alloc_layout(layout)?.cast::<T>();
1417 let result = unsafe {
1418 core::ptr::copy_nonoverlapping(src.as_ptr(), dst.as_ptr(), src.len());
1419 slice::from_raw_parts_mut(dst.as_ptr(), src.len())
1420 };
1421 Ok(result)
1422 }
1423
1424 /// `Clone` a slice into this `Bump` and return an exclusive reference to
1425 /// the clone. Prefer [`alloc_slice_copy`](#method.alloc_slice_copy) if `T` is `Copy`.
1426 ///
1427 /// ## Panics
1428 ///
1429 /// Panics if reserving space for the slice fails.
1430 ///
1431 /// ## Example
1432 ///
1433 /// ```
1434 /// #[derive(Clone, Debug, Eq, PartialEq)]
1435 /// struct Sheep {
1436 /// name: String,
1437 /// }
1438 ///
1439 /// let originals = [
1440 /// Sheep { name: "Alice".into() },
1441 /// Sheep { name: "Bob".into() },
1442 /// Sheep { name: "Cathy".into() },
1443 /// ];
1444 ///
1445 /// let bump = bumpalo::Bump::new();
1446 /// let clones = bump.alloc_slice_clone(&originals);
1447 /// assert_eq!(originals, clones);
1448 /// ```
1449 #[inline(always)]
1450 pub fn alloc_slice_clone<T>(&self, src: &[T]) -> &mut [T]
1451 where
1452 T: Clone,
1453 {
1454 let layout = Layout::for_value(src);
1455 let dst = self.alloc_layout(layout).cast::<T>();
1456
1457 unsafe {
1458 for (i, val) in src.iter().cloned().enumerate() {
1459 ptr::write(dst.as_ptr().add(i), val);
1460 }
1461
1462 slice::from_raw_parts_mut(dst.as_ptr(), src.len())
1463 }
1464 }
1465
1466 /// Like `alloc_slice_clone` but does not panic on failure.
1467 #[inline(always)]
1468 pub fn try_alloc_slice_clone<T>(&self, src: &[T]) -> Result<&mut [T], AllocErr>
1469 where
1470 T: Clone,
1471 {
1472 let layout = Layout::for_value(src);
1473 let dst = self.try_alloc_layout(layout)?.cast::<T>();
1474
1475 unsafe {
1476 for (i, val) in src.iter().cloned().enumerate() {
1477 ptr::write(dst.as_ptr().add(i), val);
1478 }
1479
1480 Ok(slice::from_raw_parts_mut(dst.as_ptr(), src.len()))
1481 }
1482 }
1483
1484 /// `Copy` a string slice into this `Bump` and return an exclusive reference to it.
1485 ///
1486 /// ## Panics
1487 ///
1488 /// Panics if reserving space for the string fails.
1489 ///
1490 /// ## Example
1491 ///
1492 /// ```
1493 /// let bump = bumpalo::Bump::new();
1494 /// let hello = bump.alloc_str("hello world");
1495 /// assert_eq!("hello world", hello);
1496 /// ```
1497 #[inline(always)]
1498 pub fn alloc_str(&self, src: &str) -> &mut str {
1499 let buffer = self.alloc_slice_copy(src.as_bytes());
1500 unsafe {
1501 // This is OK, because it already came in as str, so it is guaranteed to be utf8
1502 str::from_utf8_unchecked_mut(buffer)
1503 }
1504 }
1505
1506 /// Same as `alloc_str` but does not panic on failure.
1507 ///
1508 /// ## Example
1509 ///
1510 /// ```
1511 /// let bump = bumpalo::Bump::new();
1512 /// let hello = bump.try_alloc_str("hello world").unwrap();
1513 /// assert_eq!("hello world", hello);
1514 ///
1515 ///
1516 /// let bump = bumpalo::Bump::new();
1517 /// bump.set_allocation_limit(Some(5));
1518 /// let hello = bump.try_alloc_str("hello world");
1519 /// assert_eq!(Err(bumpalo::AllocErr), hello);
1520 /// ```
1521 #[inline(always)]
1522 pub fn try_alloc_str(&self, src: &str) -> Result<&mut str, AllocErr> {
1523 let buffer = self.try_alloc_slice_copy(src.as_bytes())?;
1524 unsafe {
1525 // This is OK, because it already came in as str, so it is guaranteed to be utf8
1526 Ok(str::from_utf8_unchecked_mut(buffer))
1527 }
1528 }
1529
1530 /// Allocates a new slice of size `len` into this `Bump` and returns an
1531 /// exclusive reference to the copy.
1532 ///
1533 /// The elements of the slice are initialized using the supplied closure.
1534 /// The closure argument is the position in the slice.
1535 ///
1536 /// ## Panics
1537 ///
1538 /// Panics if reserving space for the slice fails.
1539 ///
1540 /// ## Example
1541 ///
1542 /// ```
1543 /// let bump = bumpalo::Bump::new();
1544 /// let x = bump.alloc_slice_fill_with(5, |i| 5 * (i + 1));
1545 /// assert_eq!(x, &[5, 10, 15, 20, 25]);
1546 /// ```
1547 #[inline(always)]
1548 pub fn alloc_slice_fill_with<T, F>(&self, len: usize, mut f: F) -> &mut [T]
1549 where
1550 F: FnMut(usize) -> T,
1551 {
1552 let layout = Layout::array::<T>(len).unwrap_or_else(|_| oom());
1553 let guard = self.alloc_layout_with_rewind(layout);
1554
1555 unsafe {
1556 let mut dst = guard.ptr.cast::<T>();
1557 for i in 0..len {
1558 ptr::write(dst.as_ptr(), f(i));
1559 dst = NonNull::new_unchecked(dst.as_ptr().add(1));
1560 }
1561
1562 let ptr = guard.finish();
1563 let result = slice::from_raw_parts_mut(ptr.cast::<T>().as_ptr(), len);
1564 debug_assert_eq!(Layout::for_value(result), layout);
1565 result
1566 }
1567 }
1568
1569 /// Allocates a new slice of size `len` into this `Bump` and returns an
1570 /// exclusive reference to the copy, failing if the closure return an Err.
1571 ///
1572 /// The elements of the slice are initialized using the supplied closure.
1573 /// The closure argument is the position in the slice.
1574 ///
1575 /// ## Panics
1576 ///
1577 /// Panics if reserving space for the slice fails.
1578 ///
1579 /// ## Example
1580 ///
1581 /// ```
1582 /// let bump = bumpalo::Bump::new();
1583 /// let x: Result<&mut [usize], ()> = bump.alloc_slice_try_fill_with(5, |i| Ok(5 * i));
1584 /// assert_eq!(x, Ok(bump.alloc_slice_copy(&[0, 5, 10, 15, 20])));
1585 /// ```
1586 ///
1587 /// ```
1588 /// let bump = bumpalo::Bump::new();
1589 /// let x: Result<&mut [usize], ()> = bump.alloc_slice_try_fill_with(
1590 /// 5,
1591 /// |n| if n == 2 { Err(()) } else { Ok(n) }
1592 /// );
1593 /// assert_eq!(x, Err(()));
1594 /// ```
1595 #[inline(always)]
1596 pub fn alloc_slice_try_fill_with<T, F, E>(&self, len: usize, mut f: F) -> Result<&mut [T], E>
1597 where
1598 F: FnMut(usize) -> Result<T, E>,
1599 {
1600 let layout = Layout::array::<T>(len).unwrap_or_else(|_| oom());
1601 let guard = self.alloc_layout_with_rewind(layout);
1602
1603 unsafe {
1604 let mut dst = guard.ptr.cast::<T>();
1605 for i in 0..len {
1606 match f(i) {
1607 Ok(el) => {
1608 ptr::write(dst.as_ptr(), el);
1609 dst = NonNull::new_unchecked(dst.as_ptr().add(1));
1610 }
1611 Err(e) => return Err(e),
1612 }
1613 }
1614
1615 let ptr = guard.finish();
1616 let result = slice::from_raw_parts_mut(ptr.cast::<T>().as_ptr(), len);
1617 debug_assert_eq!(Layout::for_value(result), layout);
1618 Ok(result)
1619 }
1620 }
1621
1622 /// Allocates a new slice of size `len` into this `Bump` and returns an
1623 /// exclusive reference to the copy.
1624 ///
1625 /// The elements of the slice are initialized using the supplied closure.
1626 /// The closure argument is the position in the slice.
1627 ///
1628 /// ## Example
1629 ///
1630 /// ```
1631 /// let bump = bumpalo::Bump::new();
1632 /// let x = bump.try_alloc_slice_fill_with(5, |i| 5 * (i + 1));
1633 /// assert_eq!(x, Ok(&mut[5usize, 10, 15, 20, 25] as &mut [_]));
1634 ///
1635 ///
1636 /// let bump = bumpalo::Bump::new();
1637 /// bump.set_allocation_limit(Some(4));
1638 /// let x = bump.try_alloc_slice_fill_with(10, |i| 5 * (i + 1));
1639 /// assert_eq!(x, Err(bumpalo::AllocErr));
1640 /// ```
1641 #[inline(always)]
1642 pub fn try_alloc_slice_fill_with<T, F>(
1643 &self,
1644 len: usize,
1645 mut f: F,
1646 ) -> Result<&mut [T], AllocErr>
1647 where
1648 F: FnMut(usize) -> T,
1649 {
1650 let layout = Layout::array::<T>(len).map_err(|_| AllocErr)?;
1651 let guard = self.try_alloc_layout_with_rewind(layout)?;
1652
1653 unsafe {
1654 let mut dst = guard.ptr.cast::<T>();
1655 for i in 0..len {
1656 ptr::write(dst.as_ptr(), f(i));
1657 dst = NonNull::new_unchecked(dst.as_ptr().add(1));
1658 }
1659
1660 let ptr = guard.finish();
1661 let result = slice::from_raw_parts_mut(ptr.cast::<T>().as_ptr(), len);
1662 debug_assert_eq!(Layout::for_value(result), layout);
1663 Ok(result)
1664 }
1665 }
1666
1667 /// Allocates a new slice of size `len` into this `Bump` and returns an
1668 /// exclusive reference to the copy.
1669 ///
1670 /// All elements of the slice are initialized to `value`.
1671 ///
1672 /// ## Panics
1673 ///
1674 /// Panics if reserving space for the slice fails.
1675 ///
1676 /// ## Example
1677 ///
1678 /// ```
1679 /// let bump = bumpalo::Bump::new();
1680 /// let x = bump.alloc_slice_fill_copy(5, 42);
1681 /// assert_eq!(x, &[42, 42, 42, 42, 42]);
1682 /// ```
1683 #[inline(always)]
1684 pub fn alloc_slice_fill_copy<T: Copy>(&self, len: usize, value: T) -> &mut [T] {
1685 self.alloc_slice_fill_with(len, |_| value)
1686 }
1687
1688 /// Same as `alloc_slice_fill_copy` but does not panic on failure.
1689 #[inline(always)]
1690 pub fn try_alloc_slice_fill_copy<T: Copy>(
1691 &self,
1692 len: usize,
1693 value: T,
1694 ) -> Result<&mut [T], AllocErr> {
1695 self.try_alloc_slice_fill_with(len, |_| value)
1696 }
1697
1698 /// Allocates a new slice of size `len` slice into this `Bump` and return an
1699 /// exclusive reference to the copy.
1700 ///
1701 /// All elements of the slice are initialized to `value.clone()`.
1702 ///
1703 /// ## Panics
1704 ///
1705 /// Panics if reserving space for the slice fails.
1706 ///
1707 /// ## Example
1708 ///
1709 /// ```
1710 /// let bump = bumpalo::Bump::new();
1711 /// let s: String = "Hello Bump!".to_string();
1712 /// let x: &[String] = bump.alloc_slice_fill_clone(2, &s);
1713 /// assert_eq!(x.len(), 2);
1714 /// assert_eq!(&x[0], &s);
1715 /// assert_eq!(&x[1], &s);
1716 /// ```
1717 #[inline(always)]
1718 pub fn alloc_slice_fill_clone<T: Clone>(&self, len: usize, value: &T) -> &mut [T] {
1719 self.alloc_slice_fill_with(len, |_| value.clone())
1720 }
1721
1722 /// Like `alloc_slice_fill_clone` but does not panic on failure.
1723 #[inline(always)]
1724 pub fn try_alloc_slice_fill_clone<T: Clone>(
1725 &self,
1726 len: usize,
1727 value: &T,
1728 ) -> Result<&mut [T], AllocErr> {
1729 self.try_alloc_slice_fill_with(len, |_| value.clone())
1730 }
1731
1732 /// Allocates a new slice of size `len` slice into this `Bump` and return an
1733 /// exclusive reference to the copy.
1734 ///
1735 /// The elements are initialized using the supplied iterator.
1736 ///
1737 /// ## Panics
1738 ///
1739 /// Panics if reserving space for the slice fails, or if the supplied
1740 /// iterator returns fewer elements than it promised.
1741 ///
1742 /// ## Example
1743 ///
1744 /// ```
1745 /// let bump = bumpalo::Bump::new();
1746 /// let x: &[i32] = bump.alloc_slice_fill_iter([2, 3, 5].iter().cloned().map(|i| i * i));
1747 /// assert_eq!(x, [4, 9, 25]);
1748 /// ```
1749 #[inline(always)]
1750 pub fn alloc_slice_fill_iter<T, I>(&self, iter: I) -> &mut [T]
1751 where
1752 I: IntoIterator<Item = T>,
1753 I::IntoIter: ExactSizeIterator,
1754 {
1755 let mut iter = iter.into_iter();
1756 self.alloc_slice_fill_with(iter.len(), |_| {
1757 iter.next().expect("Iterator supplied too few elements")
1758 })
1759 }
1760
1761 /// Allocates a new slice of size `len` slice into this `Bump` and return an
1762 /// exclusive reference to the copy, failing if the iterator returns an Err.
1763 ///
1764 /// The elements are initialized using the supplied iterator.
1765 ///
1766 /// ## Panics
1767 ///
1768 /// Panics if reserving space for the slice fails, or if the supplied
1769 /// iterator returns fewer elements than it promised.
1770 ///
1771 /// ## Examples
1772 ///
1773 /// ```
1774 /// let bump = bumpalo::Bump::new();
1775 /// let x: Result<&mut [i32], ()> = bump.alloc_slice_try_fill_iter(
1776 /// [2, 3, 5].iter().cloned().map(|i| Ok(i * i))
1777 /// );
1778 /// assert_eq!(x, Ok(bump.alloc_slice_copy(&[4, 9, 25])));
1779 /// ```
1780 ///
1781 /// ```
1782 /// let bump = bumpalo::Bump::new();
1783 /// let x: Result<&mut [i32], ()> = bump.alloc_slice_try_fill_iter(
1784 /// [Ok(2), Err(()), Ok(5)].iter().cloned()
1785 /// );
1786 /// assert_eq!(x, Err(()));
1787 /// ```
1788 #[inline(always)]
1789 pub fn alloc_slice_try_fill_iter<T, I, E>(&self, iter: I) -> Result<&mut [T], E>
1790 where
1791 I: IntoIterator<Item = Result<T, E>>,
1792 I::IntoIter: ExactSizeIterator,
1793 {
1794 let mut iter = iter.into_iter();
1795 self.alloc_slice_try_fill_with(iter.len(), |_| {
1796 iter.next().expect("Iterator supplied too few elements")
1797 })
1798 }
1799
1800 /// Allocates a new slice of size `iter.len()` slice into this `Bump` and return an
1801 /// exclusive reference to the copy. Does not panic on failure.
1802 ///
1803 /// The elements are initialized using the supplied iterator.
1804 ///
1805 /// ## Example
1806 ///
1807 /// ```
1808 /// let bump = bumpalo::Bump::new();
1809 /// let x: &[i32] = bump.try_alloc_slice_fill_iter([2, 3, 5]
1810 /// .iter().cloned().map(|i| i * i)).unwrap();
1811 /// assert_eq!(x, [4, 9, 25]);
1812 /// ```
1813 #[inline(always)]
1814 pub fn try_alloc_slice_fill_iter<T, I>(&self, iter: I) -> Result<&mut [T], AllocErr>
1815 where
1816 I: IntoIterator<Item = T>,
1817 I::IntoIter: ExactSizeIterator,
1818 {
1819 let mut iter = iter.into_iter();
1820 self.try_alloc_slice_fill_with(iter.len(), |_| {
1821 iter.next().expect("Iterator supplied too few elements")
1822 })
1823 }
1824
1825 /// Allocates a new slice of size `len` slice into this `Bump` and return an
1826 /// exclusive reference to the copy.
1827 ///
1828 /// All elements of the slice are initialized to [`T::default()`].
1829 ///
1830 /// [`T::default()`]: https://doc.rust-lang.org/std/default/trait.Default.html#tymethod.default
1831 ///
1832 /// ## Panics
1833 ///
1834 /// Panics if reserving space for the slice fails.
1835 ///
1836 /// ## Example
1837 ///
1838 /// ```
1839 /// let bump = bumpalo::Bump::new();
1840 /// let x = bump.alloc_slice_fill_default::<u32>(5);
1841 /// assert_eq!(x, &[0, 0, 0, 0, 0]);
1842 /// ```
1843 #[inline(always)]
1844 pub fn alloc_slice_fill_default<T: Default>(&self, len: usize) -> &mut [T] {
1845 self.alloc_slice_fill_with(len, |_| T::default())
1846 }
1847
1848 /// Like `alloc_slice_fill_default` but does not panic on failure.
1849 #[inline(always)]
1850 pub fn try_alloc_slice_fill_default<T: Default>(
1851 &self,
1852 len: usize,
1853 ) -> Result<&mut [T], AllocErr> {
1854 self.try_alloc_slice_fill_with(len, |_| T::default())
1855 }
1856
1857 /// Allocate space for an object with the given `Layout`.
1858 ///
1859 /// The returned pointer points at uninitialized memory, and should be
1860 /// initialized with
1861 /// [`std::ptr::write`](https://doc.rust-lang.org/std/ptr/fn.write.html).
1862 ///
1863 /// # Panics
1864 ///
1865 /// Panics if reserving space matching `layout` fails.
1866 #[inline(always)]
1867 pub fn alloc_layout(&self, layout: Layout) -> NonNull<u8> {
1868 self.try_alloc_layout(layout).unwrap_or_else(|_| oom())
1869 }
1870
1871 /// Attempts to allocate space for an object with the given `Layout` or else returns
1872 /// an `Err`.
1873 ///
1874 /// The returned pointer points at uninitialized memory, and should be
1875 /// initialized with
1876 /// [`std::ptr::write`](https://doc.rust-lang.org/std/ptr/fn.write.html).
1877 ///
1878 /// # Errors
1879 ///
1880 /// Errors if reserving space matching `layout` fails.
1881 #[inline(always)]
1882 pub fn try_alloc_layout(&self, layout: Layout) -> Result<NonNull<u8>, AllocErr> {
1883 if let Some(p) = self.try_alloc_layout_fast(layout) {
1884 Ok(p)
1885 } else {
1886 self.alloc_layout_slow(layout).ok_or(AllocErr)
1887 }
1888 }
1889
1890 #[inline(always)]
1891 fn try_alloc_layout_fast(&self, layout: Layout) -> Option<NonNull<u8>> {
1892 // We don't need to check for ZSTs here since they will automatically
1893 // be handled properly: the pointer will be bumped by zero bytes,
1894 // modulo alignment. This keeps the fast path optimized for non-ZSTs,
1895 // which are much more common.
1896 unsafe {
1897 let footer_ptr = self.current_chunk_footer.get();
1898 let footer = footer_ptr.as_ref();
1899
1900 let ptr = footer.ptr.get().as_ptr();
1901 let start = footer.data.as_ptr();
1902 debug_assert!(
1903 start <= ptr,
1904 "start pointer {start:#p} should be less than or equal to bump pointer {ptr:#p}"
1905 );
1906 debug_assert!(
1907 ptr <= footer_ptr.cast::<u8>().as_ptr(),
1908 "bump pointer {ptr:#p} should be less than or equal to footer pointer {footer_ptr:#p}"
1909 );
1910 debug_assert!(
1911 is_pointer_aligned_to(ptr, MIN_ALIGN),
1912 "bump pointer {ptr:#p} should be aligned to the minimum alignment of {MIN_ALIGN:#x}"
1913 );
1914 // This `match` should be boiled away by LLVM: `MIN_ALIGN` is a
1915 // constant and the layout's alignment is also constant in practice
1916 // after inlining.
1917 let aligned_ptr = match layout.align().cmp(&MIN_ALIGN) {
1918 Ordering::Less => {
1919 // We need to round the size up to a multiple of `MIN_ALIGN`
1920 // to preserve the minimum alignment. This might overflow
1921 // since we cannot rely on `Layout`'s guarantees.
1922 let aligned_size = round_up_to(layout.size(), MIN_ALIGN)?;
1923
1924 let capacity = (ptr as usize) - (start as usize);
1925 if aligned_size > capacity {
1926 return None;
1927 }
1928
1929 ptr.wrapping_sub(aligned_size)
1930 }
1931 Ordering::Equal => {
1932 // `Layout` guarantees that rounding the size up to its
1933 // align cannot overflow (but does not guarantee that the
1934 // size is initially a multiple of the alignment, which is
1935 // why we need to do this rounding).
1936 let aligned_size = round_up_to_unchecked(layout.size(), layout.align());
1937
1938 let capacity = (ptr as usize) - (start as usize);
1939 if aligned_size > capacity {
1940 return None;
1941 }
1942
1943 ptr.wrapping_sub(aligned_size)
1944 }
1945 Ordering::Greater => {
1946 // `Layout` guarantees that rounding the size up to its
1947 // align cannot overflow (but does not guarantee that the
1948 // size is initially a multiple of the alignment, which is
1949 // why we need to do this rounding).
1950 let aligned_size = round_up_to_unchecked(layout.size(), layout.align());
1951
1952 let aligned_ptr = round_mut_ptr_down_to(ptr, layout.align());
1953 let capacity = (aligned_ptr as usize).wrapping_sub(start as usize);
1954 if aligned_ptr < start || aligned_size > capacity {
1955 return None;
1956 }
1957
1958 aligned_ptr.wrapping_sub(aligned_size)
1959 }
1960 };
1961
1962 debug_assert!(
1963 is_pointer_aligned_to(aligned_ptr, layout.align()),
1964 "pointer {aligned_ptr:#p} should be aligned to layout alignment of {:#}",
1965 layout.align()
1966 );
1967 debug_assert!(
1968 is_pointer_aligned_to(aligned_ptr, MIN_ALIGN),
1969 "pointer {aligned_ptr:#p} should be aligned to minimum alignment of {:#}",
1970 MIN_ALIGN
1971 );
1972 debug_assert!(
1973 start <= aligned_ptr && aligned_ptr <= ptr,
1974 "pointer {aligned_ptr:#p} should be in range {start:#p}..{ptr:#p}"
1975 );
1976
1977 debug_assert!(!aligned_ptr.is_null());
1978 let aligned_ptr = NonNull::new_unchecked(aligned_ptr);
1979
1980 footer.ptr.set(aligned_ptr);
1981 Some(aligned_ptr)
1982 }
1983 }
1984
1985 /// Gets the remaining capacity in the current chunk (in bytes).
1986 ///
1987 /// ## Example
1988 ///
1989 /// ```
1990 /// use bumpalo::Bump;
1991 ///
1992 /// let bump = Bump::with_capacity(100);
1993 ///
1994 /// let capacity = bump.chunk_capacity();
1995 /// assert!(capacity >= 100);
1996 /// ```
1997 pub fn chunk_capacity(&self) -> usize {
1998 let current_footer = self.current_chunk_footer.get();
1999 let current_footer = unsafe { current_footer.as_ref() };
2000
2001 current_footer.ptr.get().as_ptr() as usize - current_footer.data.as_ptr() as usize
2002 }
2003
2004 /// Slow path allocation for when we need to allocate a new chunk from the
2005 /// parent bump set because there isn't enough room in our current chunk.
2006 #[inline(never)]
2007 #[cold]
2008 fn alloc_layout_slow(&self, layout: Layout) -> Option<NonNull<u8>> {
2009 unsafe {
2010 let allocation_limit_remaining = self.allocation_limit_remaining();
2011
2012 // Get a new chunk from the global allocator.
2013 let current_footer = self.current_chunk_footer.get();
2014 let current_layout = current_footer.as_ref().layout;
2015
2016 // By default, we want our new chunk to be about twice as big
2017 // as the previous chunk. If the global allocator refuses it,
2018 // we try to divide it by half until it works or the requested
2019 // size is smaller than the default footer size.
2020 let min_new_chunk_size = layout.size().max(DEFAULT_CHUNK_SIZE_WITHOUT_FOOTER);
2021 let mut base_size = (current_layout.size() - FOOTER_SIZE)
2022 .checked_mul(2)?
2023 .max(min_new_chunk_size);
2024 let chunk_memory_details = iter::from_fn(|| {
2025 let bypass_min_chunk_size_for_small_limits = matches!(self.allocation_limit(), Some(limit) if layout.size() < limit
2026 && base_size >= layout.size()
2027 && limit < DEFAULT_CHUNK_SIZE_WITHOUT_FOOTER
2028 && self.allocated_bytes() == 0);
2029
2030 if base_size >= min_new_chunk_size || bypass_min_chunk_size_for_small_limits {
2031 let size = base_size;
2032 base_size /= 2;
2033 Self::new_chunk_memory_details(Some(size), layout)
2034 } else {
2035 None
2036 }
2037 });
2038
2039 let new_footer = chunk_memory_details
2040 .filter_map(|chunk_memory_details| {
2041 if Self::chunk_fits_under_limit(
2042 allocation_limit_remaining,
2043 chunk_memory_details,
2044 ) {
2045 Self::new_chunk(chunk_memory_details, layout, current_footer)
2046 } else {
2047 None
2048 }
2049 })
2050 .next()?;
2051
2052 debug_assert_eq!(
2053 new_footer.as_ref().data.as_ptr() as usize % layout.align(),
2054 0
2055 );
2056
2057 // Set the new chunk as our new current chunk.
2058 self.current_chunk_footer.set(new_footer);
2059
2060 // And then we can rely on `try_alloc_layout_fast` to allocate
2061 // space within this chunk.
2062 let ptr = self.try_alloc_layout_fast(layout);
2063 debug_assert!(ptr.is_some());
2064 ptr
2065 }
2066 }
2067
2068 #[inline]
2069 fn try_alloc_layout_with_rewind(
2070 &self,
2071 layout: Layout,
2072 ) -> Result<RewindGuard<'_, MIN_ALIGN>, AllocErr> {
2073 let rewind_footer = self.current_chunk_footer.get();
2074 let rewind_footer_ptr = unsafe { rewind_footer.as_ref().ptr.get() };
2075 let ptr = self.try_alloc_layout(layout)?;
2076 Ok(unsafe { RewindGuard::new(self, ptr, rewind_footer, rewind_footer_ptr) })
2077 }
2078
2079 #[inline]
2080 fn alloc_layout_with_rewind(&self, layout: Layout) -> RewindGuard<'_, MIN_ALIGN> {
2081 self.try_alloc_layout_with_rewind(layout)
2082 .unwrap_or_else(|_| oom())
2083 }
2084
2085 /// Returns an iterator over each chunk of allocated memory that
2086 /// this arena has bump allocated into.
2087 ///
2088 /// The chunks are returned ordered by allocation time, with the most
2089 /// recently allocated chunk being returned first, and the least recently
2090 /// allocated chunk being returned last.
2091 ///
2092 /// The values inside each chunk are also ordered by allocation time, with
2093 /// the most recent allocation being earlier in the slice, and the least
2094 /// recent allocation being towards the end of the slice.
2095 ///
2096 /// ## Safety
2097 ///
2098 /// Because this method takes `&mut self`, we know that the bump arena
2099 /// reference is unique and therefore there aren't any active references to
2100 /// any of the objects we've allocated in it either. This potential aliasing
2101 /// of exclusive references is one common footgun for unsafe code that we
2102 /// don't need to worry about here.
2103 ///
2104 /// However, there could be regions of uninitialized memory used as padding
2105 /// between allocations, which is why this iterator has items of type
2106 /// `[MaybeUninit<u8>]`, instead of simply `[u8]`.
2107 ///
2108 /// The only way to guarantee that there is no padding between allocations
2109 /// or within allocated objects is if all of these properties hold:
2110 ///
2111 /// 1. Every object allocated in this arena has the same alignment,
2112 /// and that alignment is at most 16.
2113 /// 2. Every object's size is a multiple of its alignment.
2114 /// 3. None of the objects allocated in this arena contain any internal
2115 /// padding.
2116 ///
2117 /// If you want to use this `iter_allocated_chunks` method, it is *your*
2118 /// responsibility to ensure that these properties hold before calling
2119 /// `MaybeUninit::assume_init` or otherwise reading the returned values.
2120 ///
2121 /// Finally, you must also ensure that any values allocated into the bump
2122 /// arena have not had their `Drop` implementations called on them,
2123 /// e.g. after dropping a [`bumpalo::boxed::Box<T>`][crate::boxed::Box].
2124 ///
2125 /// ## Example
2126 ///
2127 /// ```
2128 /// let mut bump = bumpalo::Bump::new();
2129 ///
2130 /// // Allocate a bunch of `i32`s in this bump arena, potentially causing
2131 /// // additional memory chunks to be reserved.
2132 /// for i in 0..10000 {
2133 /// bump.alloc(i);
2134 /// }
2135 ///
2136 /// // Iterate over each chunk we've bump allocated into. This is safe
2137 /// // because we have only allocated `i32`s in this arena, which fulfills
2138 /// // the above requirements.
2139 /// for ch in bump.iter_allocated_chunks() {
2140 /// println!("Used a chunk that is {} bytes long", ch.len());
2141 /// println!("The first byte is {:?}", unsafe {
2142 /// ch[0].assume_init()
2143 /// });
2144 /// }
2145 ///
2146 /// // Within a chunk, allocations are ordered from most recent to least
2147 /// // recent. If we allocated 'a', then 'b', then 'c', when we iterate
2148 /// // through the chunk's data, we get them in the order 'c', then 'b',
2149 /// // then 'a'.
2150 ///
2151 /// bump.reset();
2152 /// bump.alloc(b'a');
2153 /// bump.alloc(b'b');
2154 /// bump.alloc(b'c');
2155 ///
2156 /// assert_eq!(bump.iter_allocated_chunks().count(), 1);
2157 /// let chunk = bump.iter_allocated_chunks().nth(0).unwrap();
2158 /// assert_eq!(chunk.len(), 3);
2159 ///
2160 /// // Safe because we've only allocated `u8`s in this arena, which
2161 /// // fulfills the above requirements.
2162 /// unsafe {
2163 /// assert_eq!(chunk[0].assume_init(), b'c');
2164 /// assert_eq!(chunk[1].assume_init(), b'b');
2165 /// assert_eq!(chunk[2].assume_init(), b'a');
2166 /// }
2167 /// ```
2168 pub fn iter_allocated_chunks(&mut self) -> ChunkIter<'_, MIN_ALIGN> {
2169 // Safety: Ensured by mutable borrow of `self`.
2170 let raw = unsafe { self.iter_allocated_chunks_raw() };
2171 ChunkIter {
2172 raw,
2173 bump: PhantomData,
2174 }
2175 }
2176
2177 /// Returns an iterator over raw pointers to chunks of allocated memory that
2178 /// this arena has bump allocated into.
2179 ///
2180 /// This is an unsafe version of [`iter_allocated_chunks()`](Bump::iter_allocated_chunks),
2181 /// with the caller responsible for safe usage of the returned pointers as
2182 /// well as ensuring that the iterator is not invalidated by new
2183 /// allocations.
2184 ///
2185 /// ## Safety
2186 ///
2187 /// Allocations from this arena must not be performed while the returned
2188 /// iterator is alive. If reading the chunk data (or casting to a reference)
2189 /// the caller must ensure that there exist no mutable references to
2190 /// previously allocated data.
2191 ///
2192 /// In addition, all of the caveats when reading the chunk data from
2193 /// [`iter_allocated_chunks()`](Bump::iter_allocated_chunks) still apply.
2194 pub unsafe fn iter_allocated_chunks_raw(&self) -> ChunkRawIter<'_, MIN_ALIGN> {
2195 ChunkRawIter {
2196 footer: self.current_chunk_footer.get(),
2197 bump: PhantomData,
2198 }
2199 }
2200
2201 /// Calculates the number of bytes currently allocated across all chunks in
2202 /// this bump arena.
2203 ///
2204 /// If you allocate types of different alignments or types with
2205 /// larger-than-typical alignment in the same arena, some padding
2206 /// bytes might get allocated in the bump arena. Note that those padding
2207 /// bytes will add to this method's resulting sum, so you cannot rely
2208 /// on it only counting the sum of the sizes of the things
2209 /// you've allocated in the arena.
2210 ///
2211 /// The allocated bytes do not include the size of bumpalo's metadata,
2212 /// so the amount of memory requested from the Rust allocator is higher
2213 /// than the returned value.
2214 ///
2215 /// ## Example
2216 ///
2217 /// ```
2218 /// let bump = bumpalo::Bump::new();
2219 /// let _x = bump.alloc_slice_fill_default::<u32>(5);
2220 /// let bytes = bump.allocated_bytes();
2221 /// assert!(bytes >= core::mem::size_of::<u32>() * 5);
2222 /// ```
2223 pub fn allocated_bytes(&self) -> usize {
2224 let footer = self.current_chunk_footer.get();
2225
2226 unsafe { footer.as_ref().allocated_bytes }
2227 }
2228
2229 /// Calculates the number of bytes requested from the Rust allocator for this `Bump`.
2230 ///
2231 /// This number is equal to the [`allocated_bytes()`](Self::allocated_bytes) plus
2232 /// the size of the bump metadata.
2233 pub fn allocated_bytes_including_metadata(&self) -> usize {
2234 let metadata_size =
2235 unsafe { self.iter_allocated_chunks_raw().count() * mem::size_of::<ChunkFooter>() };
2236 self.allocated_bytes() + metadata_size
2237 }
2238
2239 #[inline]
2240 fn is_last_allocation(&self, ptr: NonNull<u8>) -> bool {
2241 unsafe {
2242 let footer = self.current_chunk_footer.get();
2243 let footer = footer.as_ref();
2244 footer.ptr.get() == ptr
2245 }
2246 }
2247
2248 #[inline]
2249 unsafe fn dealloc(&self, ptr: NonNull<u8>, layout: Layout) {
2250 // If the pointer is the last allocation we made, we can reuse the bytes,
2251 // otherwise they are simply leaked -- at least until somebody calls reset().
2252 if self.is_last_allocation(ptr) {
2253 let ptr = self.current_chunk_footer.get().as_ref().ptr.get();
2254 let ptr = ptr.as_ptr().add(layout.size());
2255
2256 let ptr = round_mut_ptr_up_to_unchecked(ptr, MIN_ALIGN);
2257 debug_assert!(
2258 is_pointer_aligned_to(ptr, MIN_ALIGN),
2259 "bump pointer {ptr:#p} should be aligned to the minimum alignment of {MIN_ALIGN:#x}"
2260 );
2261 let ptr = NonNull::new_unchecked(ptr);
2262 self.current_chunk_footer.get().as_ref().ptr.set(ptr);
2263 }
2264 }
2265
2266 #[inline]
2267 unsafe fn shrink(
2268 &self,
2269 ptr: NonNull<u8>,
2270 old_layout: Layout,
2271 new_layout: Layout,
2272 ) -> Result<NonNull<u8>, AllocErr> {
2273 // If the new layout demands greater alignment than the old layout has,
2274 // then either
2275 //
2276 // 1. the pointer happens to satisfy the new layout's alignment, so we
2277 // got lucky and can return the pointer as-is, or
2278 //
2279 // 2. the pointer is not aligned to the new layout's demanded alignment,
2280 // and we are unlucky.
2281 //
2282 // In the case of (2), to successfully "shrink" the allocation, we have
2283 // to allocate a whole new region for the new layout.
2284 if old_layout.align() < new_layout.align() {
2285 return if is_pointer_aligned_to(ptr.as_ptr(), new_layout.align()) {
2286 Ok(ptr)
2287 } else {
2288 let new_ptr = self.try_alloc_layout(new_layout)?;
2289
2290 // We know that these regions are nonoverlapping because
2291 // `new_ptr` is a fresh allocation.
2292 ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_ptr(), new_layout.size());
2293
2294 Ok(new_ptr)
2295 };
2296 }
2297
2298 debug_assert!(is_pointer_aligned_to(ptr.as_ptr(), new_layout.align()));
2299
2300 let old_size = old_layout.size();
2301 let new_size = new_layout.size();
2302
2303 // This is how much space we would *actually* reclaim while satisfying
2304 // the requested alignment.
2305 let delta = round_down_to(old_size - new_size, new_layout.align().max(MIN_ALIGN));
2306
2307 if self.is_last_allocation(ptr)
2308 // Only reclaim the excess space (which requires a copy) if it
2309 // is worth it: we are actually going to recover "enough" space
2310 // and we can do a non-overlapping copy.
2311 //
2312 // We do `(old_size + 1) / 2` so division rounds up rather than
2313 // down. Consider when:
2314 //
2315 // old_size = 5
2316 // new_size = 3
2317 //
2318 // If we do not take care to round up, this will result in:
2319 //
2320 // delta = 2
2321 // (old_size / 2) = (5 / 2) = 2
2322 //
2323 // And the the check will succeed even though we are have
2324 // overlapping ranges:
2325 //
2326 // |--------old-allocation-------|
2327 // |------from-------|
2328 // |-------to--------|
2329 // +-----+-----+-----+-----+-----+
2330 // | a | b | c | . | . |
2331 // +-----+-----+-----+-----+-----+
2332 //
2333 // But we MUST NOT have overlapping ranges because we use
2334 // `copy_nonoverlapping` below! Therefore, we round the division
2335 // up to avoid this issue.
2336 && delta >= (old_size + 1) / 2
2337 {
2338 let footer = self.current_chunk_footer.get();
2339 let footer = footer.as_ref();
2340
2341 // NB: new_ptr is aligned, because ptr *has to* be aligned, and we
2342 // made sure delta is aligned.
2343 let new_ptr = NonNull::new_unchecked(footer.ptr.get().as_ptr().add(delta));
2344 debug_assert!(
2345 is_pointer_aligned_to(new_ptr.as_ptr(), MIN_ALIGN),
2346 "bump pointer {new_ptr:#p} should be aligned to the minimum alignment of {MIN_ALIGN:#x}"
2347 );
2348 footer.ptr.set(new_ptr);
2349
2350 // NB: we know it is non-overlapping because of the size check
2351 // in the `if` condition.
2352 ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_ptr(), new_size);
2353
2354 return Ok(new_ptr);
2355 }
2356
2357 // If this wasn't the last allocation, or shrinking wasn't worth it,
2358 // simply return the old pointer as-is.
2359 Ok(ptr)
2360 }
2361
2362 #[inline]
2363 unsafe fn grow(
2364 &self,
2365 ptr: NonNull<u8>,
2366 old_layout: Layout,
2367 new_layout: Layout,
2368 ) -> Result<NonNull<u8>, AllocErr> {
2369 let old_size = old_layout.size();
2370
2371 let new_size = new_layout.size();
2372 let new_size = round_up_to(new_size, MIN_ALIGN).ok_or(AllocErr)?;
2373
2374 let align_is_compatible = old_layout.align() >= new_layout.align();
2375
2376 if align_is_compatible && self.is_last_allocation(ptr) {
2377 // Try to allocate the delta size within this same block so we can
2378 // reuse the currently allocated space.
2379 let delta = new_size - old_size;
2380 if let Some(p) =
2381 self.try_alloc_layout_fast(layout_from_size_align(delta, old_layout.align())?)
2382 {
2383 ptr::copy(ptr.as_ptr(), p.as_ptr(), old_size);
2384 return Ok(p);
2385 }
2386 }
2387
2388 // Fallback: do a fresh allocation and copy the existing data into it.
2389 let new_ptr = self.try_alloc_layout(new_layout)?;
2390 ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_ptr(), old_size);
2391 Ok(new_ptr)
2392 }
2393}
2394
2395/// An iterator over each chunk of allocated memory that
2396/// an arena has bump allocated into.
2397///
2398/// The chunks are returned ordered by allocation time, with the most recently
2399/// allocated chunk being returned first.
2400///
2401/// The values inside each chunk are also ordered by allocation time, with the most
2402/// recent allocation being earlier in the slice.
2403///
2404/// This struct is created by the [`iter_allocated_chunks`] method on
2405/// [`Bump`]. See that function for a safety description regarding reading from the returned items.
2406///
2407/// [`Bump`]: struct.Bump.html
2408/// [`iter_allocated_chunks`]: struct.Bump.html#method.iter_allocated_chunks
2409#[derive(Debug)]
2410pub struct ChunkIter<'a, const MIN_ALIGN: usize = 1> {
2411 raw: ChunkRawIter<'a, MIN_ALIGN>,
2412 bump: PhantomData<&'a mut Bump>,
2413}
2414
2415impl<'a, const MIN_ALIGN: usize> Iterator for ChunkIter<'a, MIN_ALIGN> {
2416 type Item = &'a [mem::MaybeUninit<u8>];
2417
2418 fn next(&mut self) -> Option<Self::Item> {
2419 unsafe {
2420 let (ptr, len) = self.raw.next()?;
2421 let slice = slice::from_raw_parts(ptr as *const mem::MaybeUninit<u8>, len);
2422 Some(slice)
2423 }
2424 }
2425}
2426
2427impl<'a, const MIN_ALIGN: usize> iter::FusedIterator for ChunkIter<'a, MIN_ALIGN> {}
2428
2429/// An iterator over raw pointers to chunks of allocated memory that this
2430/// arena has bump allocated into.
2431///
2432/// See [`ChunkIter`] for details regarding the returned chunks.
2433///
2434/// This struct is created by the [`iter_allocated_chunks_raw`] method on
2435/// [`Bump`]. See that function for a safety description regarding reading from
2436/// the returned items.
2437///
2438/// [`Bump`]: struct.Bump.html
2439/// [`iter_allocated_chunks_raw`]: struct.Bump.html#method.iter_allocated_chunks_raw
2440#[derive(Debug)]
2441pub struct ChunkRawIter<'a, const MIN_ALIGN: usize = 1> {
2442 footer: NonNull<ChunkFooter>,
2443 bump: PhantomData<&'a Bump<MIN_ALIGN>>,
2444}
2445
2446impl<const MIN_ALIGN: usize> Iterator for ChunkRawIter<'_, MIN_ALIGN> {
2447 type Item = (*mut u8, usize);
2448 fn next(&mut self) -> Option<(*mut u8, usize)> {
2449 unsafe {
2450 let foot = self.footer.as_ref();
2451 if foot.is_empty() {
2452 return None;
2453 }
2454 let (ptr, len) = foot.as_raw_parts();
2455 self.footer = foot.prev.get();
2456 Some((ptr as *mut u8, len))
2457 }
2458 }
2459}
2460
2461impl<const MIN_ALIGN: usize> iter::FusedIterator for ChunkRawIter<'_, MIN_ALIGN> {}
2462
2463#[inline(never)]
2464#[cold]
2465fn oom() -> ! {
2466 panic!("out of memory")
2467}
2468
2469unsafe impl<'a, const MIN_ALIGN: usize> alloc::Alloc for &'a Bump<MIN_ALIGN> {
2470 #[inline(always)]
2471 unsafe fn alloc(&mut self, layout: Layout) -> Result<NonNull<u8>, AllocErr> {
2472 self.try_alloc_layout(layout)
2473 }
2474
2475 #[inline]
2476 unsafe fn dealloc(&mut self, ptr: NonNull<u8>, layout: Layout) {
2477 Bump::<MIN_ALIGN>::dealloc(self, ptr, layout);
2478 }
2479
2480 #[inline]
2481 unsafe fn realloc(
2482 &mut self,
2483 ptr: NonNull<u8>,
2484 old_layout: Layout,
2485 new_size: usize,
2486 ) -> Result<NonNull<u8>, AllocErr> {
2487 let old_size = old_layout.size();
2488 let new_layout = layout_from_size_align(new_size, old_layout.align())?;
2489
2490 if old_size == 0 {
2491 return self.try_alloc_layout(new_layout);
2492 }
2493
2494 if new_size <= old_size {
2495 Bump::shrink(self, ptr, old_layout, new_layout)
2496 } else {
2497 Bump::grow(self, ptr, old_layout, new_layout)
2498 }
2499 }
2500}
2501
2502/// This function tests that Bump isn't Sync.
2503/// ```compile_fail
2504/// use bumpalo::Bump;
2505/// fn _requires_sync<T: Sync>(_value: T) {}
2506/// fn _bump_not_sync(b: Bump) {
2507/// _requires_sync(b);
2508/// }
2509/// ```
2510#[cfg(doctest)]
2511fn _doctest_only() {}
2512
2513#[cfg(any(feature = "allocator_api", feature = "allocator-api2"))]
2514unsafe impl<'a, const MIN_ALIGN: usize> Allocator for &'a Bump<MIN_ALIGN> {
2515 #[inline]
2516 fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
2517 self.try_alloc_layout(layout)
2518 .map(|p| unsafe {
2519 NonNull::new_unchecked(ptr::slice_from_raw_parts_mut(p.as_ptr(), layout.size()))
2520 })
2521 .map_err(|_| AllocError)
2522 }
2523
2524 #[inline]
2525 unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
2526 Bump::<MIN_ALIGN>::dealloc(self, ptr, layout)
2527 }
2528
2529 #[inline]
2530 unsafe fn shrink(
2531 &self,
2532 ptr: NonNull<u8>,
2533 old_layout: Layout,
2534 new_layout: Layout,
2535 ) -> Result<NonNull<[u8]>, AllocError> {
2536 Bump::<MIN_ALIGN>::shrink(self, ptr, old_layout, new_layout)
2537 .map(|p| unsafe {
2538 NonNull::new_unchecked(ptr::slice_from_raw_parts_mut(p.as_ptr(), new_layout.size()))
2539 })
2540 .map_err(|_| AllocError)
2541 }
2542
2543 #[inline]
2544 unsafe fn grow(
2545 &self,
2546 ptr: NonNull<u8>,
2547 old_layout: Layout,
2548 new_layout: Layout,
2549 ) -> Result<NonNull<[u8]>, AllocError> {
2550 Bump::<MIN_ALIGN>::grow(self, ptr, old_layout, new_layout)
2551 .map(|p| unsafe {
2552 NonNull::new_unchecked(ptr::slice_from_raw_parts_mut(p.as_ptr(), new_layout.size()))
2553 })
2554 .map_err(|_| AllocError)
2555 }
2556
2557 #[inline]
2558 unsafe fn grow_zeroed(
2559 &self,
2560 ptr: NonNull<u8>,
2561 old_layout: Layout,
2562 new_layout: Layout,
2563 ) -> Result<NonNull<[u8]>, AllocError> {
2564 let new_ptr = self.grow(ptr, old_layout, new_layout)?;
2565
2566 // Zero the tail of the new allocation (the bytes past the copied old contents).
2567 // Write through a raw pointer rather than constructing a `&mut [u8]` over the full range,
2568 // because the tail is uninitialized and `&mut [u8]` spanning uninit bytes is UB.
2569 // `old_layout.size() <= new_layout.size()` (invariant of `Allocator` trait), so this cannot underflow.
2570 let tail_len = new_layout.size() - old_layout.size();
2571
2572 // SAFETY: `new_ptr` covers `new_layout.size()` bytes.
2573 // `old_layout.size() <= new_layout.size()` (invariant of `Allocator` trait).
2574 // So `tail_len` bytes starting at offset `old_layout.size()` are in bounds.
2575 unsafe {
2576 let dst_ptr = new_ptr.as_ptr().cast::<u8>().add(old_layout.size());
2577 ptr::write_bytes(dst_ptr, 0, tail_len);
2578 }
2579
2580 Ok(new_ptr)
2581 }
2582}
2583
2584// NB: Only tests which require private types, fields, or methods should be in
2585// here. Anything that can just be tested via public API surface should be in
2586// `bumpalo/tests/all/*`.
2587#[cfg(test)]
2588mod tests {
2589 use super::*;
2590
2591 // Uses private type `ChunkFooter`.
2592 #[test]
2593 fn chunk_footer_is_five_words() {
2594 assert_eq!(mem::size_of::<ChunkFooter>(), mem::size_of::<usize>() * 6);
2595 }
2596
2597 // Uses private `DEFAULT_CHUNK_SIZE_WITHOUT_FOOTER` and `FOOTER_SIZE`.
2598 #[test]
2599 fn allocated_bytes() {
2600 let mut b = Bump::with_capacity(1);
2601
2602 assert_eq!(b.allocated_bytes(), DEFAULT_CHUNK_SIZE_WITHOUT_FOOTER);
2603 assert_eq!(
2604 b.allocated_bytes_including_metadata(),
2605 DEFAULT_CHUNK_SIZE_WITHOUT_FOOTER + FOOTER_SIZE
2606 );
2607
2608 b.reset();
2609
2610 assert_eq!(b.allocated_bytes(), DEFAULT_CHUNK_SIZE_WITHOUT_FOOTER);
2611 assert_eq!(
2612 b.allocated_bytes_including_metadata(),
2613 DEFAULT_CHUNK_SIZE_WITHOUT_FOOTER + FOOTER_SIZE
2614 );
2615 }
2616
2617 // Uses private `alloc` module.
2618 #[test]
2619 fn test_realloc() {
2620 use crate::alloc::Alloc;
2621
2622 unsafe {
2623 const CAPACITY: usize = DEFAULT_CHUNK_SIZE_WITHOUT_FOOTER;
2624 let mut b = Bump::<1>::with_min_align_and_capacity(CAPACITY);
2625
2626 // `realloc` doesn't shrink allocations that aren't "worth it".
2627 let layout = Layout::from_size_align(100, 1).unwrap();
2628 let p = b.alloc_layout(layout);
2629 let q = (&b).realloc(p, layout, 51).unwrap();
2630 assert_eq!(p, q);
2631 b.reset();
2632
2633 // `realloc` will shrink allocations that are "worth it".
2634 let layout = Layout::from_size_align(100, 1).unwrap();
2635 let p = b.alloc_layout(layout);
2636 let q = (&b).realloc(p, layout, 50).unwrap();
2637 assert!(p != q);
2638 b.reset();
2639
2640 // `realloc` will reuse the last allocation when growing.
2641 let layout = Layout::from_size_align(10, 1).unwrap();
2642 let p = b.alloc_layout(layout);
2643 let q = (&b).realloc(p, layout, 11).unwrap();
2644 assert_eq!(q.as_ptr() as usize, p.as_ptr() as usize - 1);
2645 b.reset();
2646
2647 // `realloc` will allocate a new chunk when growing the last
2648 // allocation, if need be.
2649 let layout = Layout::from_size_align(1, 1).unwrap();
2650 let p = b.alloc_layout(layout);
2651 let q = (&b).realloc(p, layout, CAPACITY + 1).unwrap();
2652 assert_ne!(q.as_ptr() as usize, p.as_ptr() as usize - CAPACITY);
2653 b.reset();
2654
2655 // `realloc` will allocate and copy when reallocating anything that
2656 // wasn't the last allocation.
2657 let layout = Layout::from_size_align(1, 1).unwrap();
2658 let p = b.alloc_layout(layout);
2659 let _ = b.alloc_layout(layout);
2660 let q = (&b).realloc(p, layout, 2).unwrap();
2661 assert!(q.as_ptr() as usize != p.as_ptr() as usize - 1);
2662 b.reset();
2663 }
2664 }
2665
2666 // Uses private `alloc` module.
2667 #[test]
2668 fn realloc_old_size_zero() {
2669 use crate::alloc::Alloc;
2670
2671 let bump = Bump::new();
2672
2673 let old_layout = Layout::from_size_align(0, 1).unwrap();
2674 let old_ptr = bump.alloc_layout(old_layout);
2675 let new_size = 64;
2676 let new_ptr = unsafe { (&bump).realloc(old_ptr, old_layout, new_size).unwrap() };
2677 let new_ptr = new_ptr.as_ptr().cast::<u8>();
2678
2679 // Write to and read from the pointer. If it is invalid, then MIRI will
2680 // complain.
2681 unsafe {
2682 for i in 0..new_size {
2683 *new_ptr.add(i) = 0xAB;
2684 }
2685 for i in 0..new_size {
2686 assert_eq!(*new_ptr.add(i), 0xAB);
2687 }
2688 }
2689 }
2690
2691 // Uses our private `alloc` module.
2692 #[test]
2693 fn invalid_read() {
2694 use alloc::Alloc;
2695
2696 let mut b = &Bump::new();
2697
2698 unsafe {
2699 let l1 = Layout::from_size_align(12000, 4).unwrap();
2700 let p1 = Alloc::alloc(&mut b, l1).unwrap();
2701
2702 let l2 = Layout::from_size_align(1000, 4).unwrap();
2703 Alloc::alloc(&mut b, l2).unwrap();
2704
2705 let p1 = b.realloc(p1, l1, 24000).unwrap();
2706 let l3 = Layout::from_size_align(24000, 4).unwrap();
2707 b.realloc(p1, l3, 48000).unwrap();
2708 }
2709 }
2710}