stumpalo 0.5.0

A fast, zero-dependency, memory efficient bump allocator with chunk reuse and scoped stack support
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
#![warn(clippy::pedantic)]
#![doc = include_str!(concat!(env!("OUT_DIR"), "/README-rustdocified.md"))]

#[cfg(any(feature = "allocator-api2", feature = "nightly"))]
mod allocator_api;

#[cfg(nightly)]
use core::iter::TrustedLen;
use core::{
    alloc::Layout,
    cell::Cell,
    ptr::{self, NonNull},
};
use core_alloc::boxed::Box;
use core_alloc::vec::Vec;

type Result<T> = core::result::Result<T, Error>;

use crate::{
    arena_ref::ArenaRef,
    chunk::{ChunkHeader, FIRST_HEADER, HEADER_SIZE, INITIAL_CHUNK_CAPACITY},
    errors::*,
    join_chunk_chains,
};

// INVARIANT: `layout.size()` is a multiple of `layout.align()`, in
// all layouts passed to the internal allocation routines.
//
// Layouts are either constructed from `Layout::new::<T>()` or
// `Layout::array::<T>(len)`, which uphold this invariant, or are
// caller-provided layouts normalized with `Layout::pad_to_align()`.
//
// The Rust language guarantees `size_of::<T>() % align_of::<T>() == 0`
// for all types (<https://doc.rust-lang.org/reference/type-layout.html>).

#[doc(hidden)]
extern crate alloc as core_alloc;

/// A bump allocator whose fast path compiles to as few as six instructions.
///
/// Create one with [`Arena::new()`], then allocate via [`alloc`](Arena::alloc),
/// [`alloc_slice_copy`](Arena::alloc_slice_copy), etc.  Chunks are allocated lazily
/// and freed on drop.  All allocation methods take `&self` (interior mutability
/// via [`Cell`]).
///
// # Layout compatibility with `ArenaRef`
//
// `Arena` and `ArenaRef` have the same `repr(C)` field layout so that
// [`as_arena_ref`](Arena::as_arena_ref) can reinterpret `&Arena` as
// `&ArenaRef<'_>` without undefined behaviour.
#[repr(C)]
pub struct Arena {
    pub(crate) top: Cell<*mut u8>,
    pub(crate) bottom: Cell<*mut ChunkHeader>,
    pub(crate) fresh_chunks: Cell<*mut ChunkHeader>,
    // Padding: matches the size of ArenaRef's `arena_ptr` field so that
    // `as_arena_ref` can cast &Arena -> &ArenaRef without reading past the
    // allocation. The reinterpreted `arena_ptr` is never dereferenced.
    // It would aparently be undefined behaviour to have this, even though
    // the field is never read (according to miri, anyway).
    pub(crate) _padding: *const (),
}

// Arena owns all of its state.
// Calls to the global alloc/dealloc are fine to call from any thread.
unsafe impl Send for Arena {}

impl Default for Arena {
    fn default() -> Self {
        Self::new()
    }
}

impl Arena {
    /// Create an empty arena.  No chunk is allocated until the first `alloc`.
    #[must_use]
    pub fn new() -> Self {
        let header = ptr::from_ref(&FIRST_HEADER).cast_mut();
        let bottom = unsafe { header.add(1) };
        Self {
            top: Cell::new(bottom.cast::<u8>()),
            bottom: Cell::new(bottom),
            fresh_chunks: Cell::new(ptr::null_mut()),
            _padding: ptr::null(),
        }
    }

    /// Create a new arena with the default chunk size.
    /// and allocate a chunk of that size.
    /// See [`with_chunk`](Arena::with_chunk) for a reason why you might want to
    /// do this.
    #[must_use]
    pub fn with_default_chunk() -> Self {
        Self::with_chunk(INITIAL_CHUNK_CAPACITY)
    }

    /// Fallible version of [`with_chunk`](Self::with_chunk).
    #[must_use]
    pub fn try_with_default_chunk() -> Result<Self> {
        Self::try_with_chunk(INITIAL_CHUNK_CAPACITY)
    }

    /// Create an arena, allocating the first chunk upfront.
    /// This can avoid reinforcing the wrong conditional branch
    /// on the first call to `alloc`.
    #[must_use]
    pub fn with_chunk(default_chunk_size: usize) -> Self {
        let header = ChunkHeader::new(default_chunk_size, ptr::null_mut());
        let bottom = unsafe { header.add(1) };
        let top = unsafe { bottom.byte_add((*header).capacity).cast::<u8>() };
        Self {
            top: Cell::new(top),
            bottom: Cell::new(bottom),
            fresh_chunks: Cell::new(ptr::null_mut()),
            _padding: ptr::null(),
        }
    }

    /// Fallible version of [`with_chunk`](Self::with_chunk).
    pub fn try_with_chunk(first_chunk_size: usize) -> Result<Self> {
        let header = ChunkHeader::try_new(first_chunk_size, ptr::null_mut())?;
        let bottom = unsafe { header.add(1) };
        let top = unsafe { bottom.byte_add((*header).capacity).cast::<u8>() };
        Ok(Self {
            top: Cell::new(top),
            bottom: Cell::new(bottom),
            fresh_chunks: Cell::new(ptr::null_mut()),
            _padding: ptr::null(),
        })
    }

    // --- Allocation forwarding methods ---
    // These forward to ArenaRef by reinterpreting &self as &ArenaRef via
    // transmute. Arena and ArenaRef share the same repr(C) layout for their
    // first three fields (top, bottom, fresh_chunks), so treating an Arena
    // as an ArenaRef is sound.  The arena pointer field in the reinterpreted
    // ArenaRef is never read during allocation (only in ArenaRef::Drop,
    // which does not run on references), so dangling bytes there are harmless.

    #[inline(always)]
    pub fn as_arena_ref(&self) -> &ArenaRef<'_> {
        // SAFETY: Arena and ArenaRef have identical #[repr(C)] layouts for
        // the first three fields (top, bottom, fresh_chunks). The arena
        // field is only accessed in ArenaRef::Drop, which does not run on
        // the returned reference.
        unsafe { &*(ptr::from_ref(self).cast::<ArenaRef<'_>>()) }
    }

    #[inline(always)]
    pub fn as_arena_ref_mut(&mut self) -> &mut ArenaRef<'_> {
        // SAFETY: Arena and ArenaRef have identical #[repr(C)] layouts for
        // the first three fields (top, bottom, fresh_chunks). The arena
        // field is only accessed in ArenaRef::Drop, which does not run on
        // the returned reference.
        unsafe { &mut *(ptr::from_mut(self).cast::<ArenaRef<'_>>()) }
    }

    /// Allocate a `T` into the arena. Returns a mutable reference to the copy.
    /// Note that `T`'s destructor will *not* be called on the copy.
    #[inline]
    pub fn alloc<T>(&self, data: T) -> &mut T {
        self.as_arena_ref().alloc(data)
    }

    /// Fallible version of [`alloc`](Self::alloc).
    #[inline]
    pub fn try_alloc<T>(&self, data: T) -> Result<&mut T> {
        self.as_arena_ref().try_alloc(data)
    }

    /// This is a version of [alloc](ArenaRef::alloc), marked as `#[inline(never)]`.
    /// This can be useful if you want to optimize for code size, as it
    /// doesn't emit a new conditional branch, it may even be faster when you have
    /// lots of different allocations in your codepath, as it'll free up branch
    /// predictor cache.
    /// You should default to `alloc`.
    #[inline(never)]
    pub fn alloc_no_inline<T>(&self, data: T) -> &mut T {
        self.alloc(data)
    }

    /// Fallible version of [`alloc_no_inline`](Self::alloc_no_inline).
    #[inline(never)]
    pub fn try_alloc_no_inline<T>(&self, data: T) -> Result<&mut T> {
        self.try_alloc(data)
    }

    /// Allocate a `T` into the arena, as constructed by the closure.
    /// Returns a mutable reference to the allocated value.
    #[inline]
    pub fn alloc_with<F, T>(&self, f: F) -> &mut T
    where
        F: FnOnce() -> T,
    {
        self.as_arena_ref().alloc_with(f)
    }

    /// Fallible version of [`alloc_with`](Self::alloc_with).
    #[inline]
    pub fn try_alloc_with<F, T>(&self, f: F) -> Result<&mut T>
    where
        F: FnOnce() -> T,
    {
        self.as_arena_ref().try_alloc_with(f)
    }

    /// Copy a vector into the arena, consuming it.
    /// This is more efficient than calling `arena.alloc_slice_fill_iter(vec.into_iter())`.
    #[inline]
    pub fn alloc_vec<T>(&self, data: Vec<T>) -> &mut [T] {
        self.as_arena_ref().alloc_vec(data)
    }

    /// Fallible version of [`alloc_vec`](Self::alloc_vec).
    #[inline]
    pub fn try_alloc_vec<T>(&self, data: Vec<T>) -> Result<&mut [T]> {
        self.as_arena_ref().try_alloc_vec(data)
    }

    /// Copy a boxed slice into the arena, consuming it.
    /// This is more efficient than calling `arena.alloc_slice_fill_iter(boxed_slice.into_iter())`.
    #[inline]
    pub fn alloc_boxed_slice<T>(&self, data: Box<[T]>) -> &mut [T] {
        self.as_arena_ref().alloc_boxed_slice(data)
    }

    /// Fallible version of [`alloc_boxed_slice`](Self::alloc_boxed_slice).
    #[inline]
    pub fn try_alloc_boxed_slice<T>(&self, data: Box<[T]>) -> Result<&mut [T]> {
        self.as_arena_ref().try_alloc_boxed_slice(data)
    }

    /// Allocate space for an object with the given [`Layout`].
    ///
    /// The returned pointer points at uninitialized memory.
    ///
    /// # Panics
    ///
    /// Panics if reserving space matching `layout` fails.
    #[inline]
    pub fn alloc_layout(&self, layout: Layout) -> NonNull<[u8]> {
        self.as_arena_ref().alloc_layout(layout)
    }

    /// Fallible version of [`alloc_layout`](Self::alloc_layout).
    #[inline]
    pub fn try_alloc_layout(&self, layout: Layout) -> Result<NonNull<[u8]>> {
        self.as_arena_ref().try_alloc_layout(layout)
    }

    /// Copy a slice into the arena. Returns a mutable reference to the copy.
    #[inline]
    pub fn alloc_slice_copy<T: Copy>(&self, data: &[T]) -> &mut [T] {
        self.as_arena_ref().alloc_slice_copy(data)
    }

    /// Fallible version of [`alloc_slice_copy`](Self::alloc_slice_copy).
    #[inline]
    pub fn try_alloc_slice_copy<T: Copy>(&self, data: &[T]) -> Result<&mut [T]> {
        self.as_arena_ref().try_alloc_slice_copy(data)
    }

    /// Copy a slice literal into the arena. Returns a mutable reference to the copy.
    /// This is faster than [`alloc_slice_copy`](Arena::alloc_slice_copy), as it assumes the size is
    /// available at compile-time.
    /// If you use this on a non-literal slice, (eg. one produced by [leak](Box::leak)),
    /// then this will have slightly worse performance than [`alloc_slice_copy`](Arena::alloc_slice_copy).
    #[inline]
    pub fn alloc_slice_lit_copy<T: Copy>(&self, data: &'static [T]) -> &mut [T] {
        self.as_arena_ref().alloc_slice_lit_copy(data)
    }

    /// Fallible version of [`alloc_slice_lit_copy`](Self::alloc_slice_lit_copy).
    #[inline]
    pub fn try_alloc_slice_lit_copy<T: Copy>(&self, data: &'static [T]) -> Result<&mut [T]> {
        self.as_arena_ref().try_alloc_slice_lit_copy(data)
    }

    /// Copy a slice into the arena via cloning. Returns a mutable reference to the copy.
    #[inline]
    pub fn alloc_slice_clone<T: Clone>(&self, data: &[T]) -> &mut [T] {
        self.as_arena_ref().alloc_slice_clone(data)
    }

    /// Fallible version of [`alloc_slice_clone`](Self::alloc_slice_clone).
    #[inline]
    pub fn try_alloc_slice_clone<T: Clone>(&self, data: &[T]) -> Result<&mut [T]> {
        self.as_arena_ref().try_alloc_slice_clone(data)
    }

    /// Allocate an array of known size, populated by a function.
    #[inline]
    pub fn alloc_sized_slice_with<T, const N: usize, F>(&self, f: F) -> &mut [T; N]
    where
        F: FnOnce() -> [T; N],
    {
        self.as_arena_ref().alloc_sized_slice_with(f)
    }

    /// Fallible version of [`alloc_sized_slice_with`](Self::alloc_sized_slice_with).
    #[inline]
    pub fn try_alloc_sized_slice_with<T, const N: usize, F>(&self, f: F) -> Result<&mut [T; N]>
    where
        F: FnOnce() -> [T; N],
    {
        self.as_arena_ref().try_alloc_sized_slice_with(f)
    }

    /// Allocate an array of known size, populated element-by-element.
    #[inline]
    pub fn alloc_sized_slice_fill_with<T, const N: usize, F>(&self, f: F) -> &mut [T; N]
    where
        F: FnMut(usize) -> T,
    {
        self.as_arena_ref().alloc_sized_slice_fill_with(f)
    }

    /// Fallible version of [`alloc_sized_slice_fill_with`](Self::alloc_sized_slice_fill_with).
    #[inline]
    pub fn try_alloc_sized_slice_fill_with<T, const N: usize, F>(&self, f: F) -> Result<&mut [T; N]>
    where
        F: FnMut(usize) -> T,
    {
        self.as_arena_ref().try_alloc_sized_slice_fill_with(f)
    }

    /// Allocate a slice, populating all slots uniformly by a function.
    ///
    /// # Panics
    ///
    /// Panics if the size of the array would exceed [`isize::MAX`](isize::MAX).
    #[inline]
    pub fn alloc_slice_fill_with<T, F>(&self, len: usize, f: F) -> &mut [T]
    where
        F: FnMut(usize) -> T,
    {
        self.as_arena_ref().alloc_slice_fill_with(len, f)
    }

    /// Fallible version of [`alloc_slice_fill_with`](Self::alloc_slice_fill_with).
    #[inline]
    pub fn try_alloc_slice_fill_with<T, F>(&self, len: usize, f: F) -> Result<&mut [T]>
    where
        F: FnMut(usize) -> T,
    {
        self.as_arena_ref().try_alloc_slice_fill_with(len, f)
    }

    /// Allocate a slice, populating all slots uniformly by a fallible function.
    ///
    /// # Errors
    ///
    /// Returns the first error returned by `f`.
    /// In case of error, the arena will revert to its state before this call.
    ///
    /// # Panics
    ///
    /// Panics if the size of the array would exceed [`isize::MAX`](isize::MAX).
    #[inline]
    pub fn alloc_slice_try_fill_with<T, E, F>(
        &self,
        len: usize,
        f: F,
    ) -> core::result::Result<&mut [T], E>
    where
        F: FnMut(usize) -> core::result::Result<T, E>,
    {
        self.as_arena_ref().alloc_slice_try_fill_with(len, f)
    }

    /// Copy a fixed-size array into the arena. Returns a mutable reference.
    #[inline]
    pub fn alloc_sized_slice_copy<T: Copy, const N: usize>(&self, data: &[T; N]) -> &mut [T; N] {
        self.as_arena_ref().alloc_sized_slice_copy(data)
    }

    /// Fallible version of [`alloc_sized_slice_copy`](Self::alloc_sized_slice_copy).
    #[inline]
    pub fn try_alloc_sized_slice_copy<T: Copy, const N: usize>(
        &self,
        data: &[T; N],
    ) -> Result<&mut [T; N]> {
        self.as_arena_ref().try_alloc_sized_slice_copy(data)
    }

    /// Copy a fixed-size array into the arena via cloning.
    #[inline]
    pub fn alloc_sized_slice_clone<T: Clone, const N: usize>(&self, data: &[T; N]) -> &mut [T; N] {
        self.as_arena_ref().alloc_sized_slice_clone(data)
    }

    /// Fallible version of [`alloc_sized_slice_clone`](Self::alloc_sized_slice_clone).
    #[inline]
    pub fn try_alloc_sized_slice_clone<T: Clone, const N: usize>(
        &self,
        data: &[T; N],
    ) -> Result<&mut [T; N]> {
        self.as_arena_ref().try_alloc_sized_slice_clone(data)
    }

    /// Allocate a fixed-size array filled with [Default] values.
    #[inline]
    pub fn alloc_sized_slice_fill_default<T: Default, const N: usize>(&self) -> &mut [T; N] {
        self.as_arena_ref().alloc_sized_slice_fill_default()
    }

    /// Fallible version of [`alloc_sized_slice_fill_default`](Self::alloc_sized_slice_fill_default).
    #[inline]
    pub fn try_alloc_sized_slice_fill_default<T: Default, const N: usize>(
        &self,
    ) -> Result<&mut [T; N]> {
        self.as_arena_ref().try_alloc_sized_slice_fill_default()
    }

    /// Allocate a slice filled with [Default] values.
    ///
    /// # Panics
    ///
    /// Panics if the size of the array would exceed [`isize::MAX`](isize::MAX).
    #[inline]
    pub fn alloc_slice_fill_default<T: Default>(&self, len: usize) -> &mut [T] {
        self.as_arena_ref().alloc_slice_fill_default(len)
    }

    /// Fallible version of [`alloc_slice_fill_default`](Self::alloc_slice_fill_default).
    #[inline]
    pub fn try_alloc_slice_fill_default<T: Default>(&self, len: usize) -> Result<&mut [T]> {
        self.as_arena_ref().try_alloc_slice_fill_default(len)
    }

    /// Allocate a slice from an iterator with a known size.
    /// Returns a mutable reference to the allocated slice.
    ///
    /// # Panics
    ///
    /// Panics if the iterator doesn't have as many elements as its `.len()` promises.
    /// Panics if the size of the array would exceed [`isize::MAX`](isize::MAX).
    #[inline]
    pub fn alloc_slice_fill_iter<T, I>(&self, iter: I) -> &mut [T]
    where
        I: IntoIterator<Item = T>,
        <I as IntoIterator>::IntoIter: ExactSizeIterator,
    {
        self.as_arena_ref().alloc_slice_fill_iter(iter)
    }

    /// Fallible version of [`alloc_slice_fill_iter`](Self::alloc_slice_fill_iter).
    #[inline]
    pub fn try_alloc_slice_fill_iter<T, I>(&self, iter: I) -> Result<&mut [T]>
    where
        I: IntoIterator<Item = T>,
        <I as IntoIterator>::IntoIter: ExactSizeIterator,
    {
        self.as_arena_ref().try_alloc_slice_fill_iter(iter)
    }

    /// Allocate a slice from an iterator with a trusted known size.
    /// Returns a mutable reference to the allocated slice.
    ///
    /// # Panics
    ///
    /// Panics if the iterator doesn't have as many elements as its `.len()` promises.
    /// Panics if the size of the array would exceed [`isize::MAX`](isize::MAX).
    #[inline]
    #[cfg(nightly)]
    pub fn alloc_slice_fill_iter_trusted<T, I>(&self, iter: I) -> &mut [T]
    where
        I: IntoIterator<Item = T>,
        <I as IntoIterator>::IntoIter: TrustedLen,
    {
        self.as_arena_ref().alloc_slice_fill_iter_trusted(iter)
    }

    /// Copy a string into the arena. Returns a mutable reference to the copy.
    #[inline]
    pub fn alloc_str(&self, s: &str) -> &mut str {
        self.as_arena_ref().alloc_str(s)
    }

    /// Fallible version of [`alloc_str`](Self::alloc_str).
    #[inline]
    pub fn try_alloc_str(&self, s: &str) -> Result<&mut str> {
        self.as_arena_ref().try_alloc_str(s)
    }

    /// Copy a string literal into the arena. Returns a mutable reference to the copy.
    /// This is faster than [`alloc_str`](Arena::alloc_str), as it assumes the size is
    /// available at compile-time.
    /// If you use this on a non-literal string, (eg. one produced by [leak](String::leak)),
    /// then this will have slightly worse performance than [`alloc_str`](Arena::alloc_str).
    #[inline]
    pub fn alloc_str_lit(&self, s: &'static str) -> &mut str {
        self.as_arena_ref().alloc_str_lit(s)
    }

    /// Fallible version of [`alloc_str_lit`](Self::alloc_str_lit).
    #[inline]
    pub fn try_alloc_str_lit(&self, s: &'static str) -> Result<&mut str> {
        self.as_arena_ref().try_alloc_str_lit(s)
    }

    /// Counts the size of all chunks in this arena, whether those chunks are
    /// in use or not. Doesn't include chunk metadata.
    pub fn allocated_bytes(&self) -> usize {
        self.as_arena_ref().allocated_bytes()
    }

    /// Counts the size of all chunks in this arena, whether those chunks are
    /// in use or not. Includes chunk metadata.
    pub fn allocated_bytes_including_metadata(&self) -> usize {
        self.as_arena_ref().allocated_bytes_including_metadata()
    }

    /// Returns the capacity of the current chunk.
    pub fn chunk_capacity(&self) -> usize {
        self.as_arena_ref().chunk_capacity()
    }

    /// Returns whether the arena has any fresh chunks allocated.
    pub fn has_fresh_chunks(&self) -> bool {
        self.as_arena_ref().has_fresh_chunks()
    }

    fn header(&self) -> *mut ChunkHeader {
        let ptr = self.bottom.get();
        unsafe { ptr.sub(1) }
    }

    /// Clear the arena, invalidating all references to arena-allocated data
    /// at compile time. Chunks that have already been allocated are reused
    /// in subsequent allocations.
    /// If you want to actually free those chunks, just recreate the arena.
    pub fn clear(&mut self) {
        let current = self.header();
        let capacity = unsafe { (*current).capacity };
        // Guard against the FIRST_HEADER sentinel (capacity 0), which
        // lives in read-only static memory and must not be mutated.
        if capacity == 0 {
            return;
        }

        // Reset top to end of current chunk
        self.top
            .set(unsafe { (current.add(1).cast::<u8>()).byte_add(capacity) });
        // Move used chain to fresh_chunks
        let used_chain = unsafe { (*current).next };
        unsafe { (*current).next = ptr::null_mut() };
        self.fresh_chunks
            .set(join_chunk_chains(self.fresh_chunks.get(), used_chain));
    }

    /// Free all chunks in the 'fresh chunk' list.
    /// Fresh chunks only occur if you're using scoped arenas (see [`with_scope`](Self::with_scope)),
    /// or if you've called [clear](Self::clear).
    pub fn free_fresh_chunks(&mut self) {
        unsafe { ChunkHeader::free_chunk_chain(self.fresh_chunks.get()) };
    }

    /// Alias for [clear](Arena::clear).
    pub fn reset(&mut self) {
        self.clear();
    }

    /// Run a closure with a sub-scoped arena.  References returned by the
    /// closure are bounded by the closure's scope (not the parent arena's
    /// lifetime), and the arena state is reverted on return (chunks are
    /// reused, not freed).
    ///
    /// Takes `&mut self`, making references from `alloc` are invalidated.
    /// This is intentional. If you need to use outer allocations after
    /// a scope closes, use an [`ArenaRef`], by calling
    /// [`as_arena_ref_mut`](Arena::as_arena_ref_mut).
    pub fn with_scope<'brand, F, R>(&'brand mut self, f: F) -> R
    where
        F: for<'scope> FnOnce(&'scope mut ArenaRef<'scope>) -> R,
    {
        unsafe { self.as_arena_ref_mut().with_scope_unchecked(f) }
    }
}

impl Drop for Arena {
    fn drop(&mut self) {
        unsafe {
            let bottom = self.bottom.get();
            if !bottom.is_null() {
                let current = bottom.byte_sub(HEADER_SIZE).cast::<ChunkHeader>();
                ChunkHeader::free_chunk_chain(current);
            }
            ChunkHeader::free_chunk_chain(self.fresh_chunks.get());
        }
    }
}