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
// TODO: Figure out a way to make coverage report not suck because of `if UP { ... } else { ... }`.
#![allow(clippy::unnecessary_wraps)]

use allocator_api2::alloc::{AllocError, Allocator};
use core::{alloc::Layout, num::NonZeroUsize, ptr::NonNull};

use crate::{
    bump_down, polyfill::nonnull, up_align_usize_unchecked, BaseAllocator, Bump, BumpScope, MinimumAlignment,
    SupportedMinimumAlignment,
};

unsafe impl<A, const MIN_ALIGN: usize, const UP: bool, const GUARANTEED_ALLOCATED: bool> Allocator
    for BumpScope<'_, A, MIN_ALIGN, UP, GUARANTEED_ALLOCATED>
where
    MinimumAlignment<MIN_ALIGN>: SupportedMinimumAlignment,
    A: BaseAllocator<GUARANTEED_ALLOCATED>,
{
    #[inline(always)]
    fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
        allocate(self, layout)
    }

    #[inline(always)]
    unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
        deallocate(self, ptr, layout);
    }

    #[inline(always)]
    unsafe fn grow(&self, ptr: NonNull<u8>, old_layout: Layout, new_layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
        grow(self, ptr, old_layout, new_layout)
    }

    #[inline(always)]
    unsafe fn grow_zeroed(
        &self,
        ptr: NonNull<u8>,
        old_layout: Layout,
        new_layout: Layout,
    ) -> Result<NonNull<[u8]>, AllocError> {
        grow_zeroed(self, ptr, old_layout, new_layout)
    }

    #[inline(always)]
    unsafe fn shrink(&self, ptr: NonNull<u8>, old_layout: Layout, new_layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
        shrink(self, ptr, old_layout, new_layout)
    }
}

unsafe impl<A, const MIN_ALIGN: usize, const UP: bool, const GUARANTEED_ALLOCATED: bool> Allocator
    for Bump<A, MIN_ALIGN, UP, GUARANTEED_ALLOCATED>
where
    MinimumAlignment<MIN_ALIGN>: SupportedMinimumAlignment,
    A: BaseAllocator<GUARANTEED_ALLOCATED>,
{
    #[inline(always)]
    fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
        self.as_scope().allocate(layout)
    }

    #[inline(always)]
    unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
        self.as_scope().deallocate(ptr, layout);
    }

    #[inline(always)]
    unsafe fn grow(&self, ptr: NonNull<u8>, old_layout: Layout, new_layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
        self.as_scope().grow(ptr, old_layout, new_layout)
    }

    #[inline(always)]
    unsafe fn grow_zeroed(
        &self,
        ptr: NonNull<u8>,
        old_layout: Layout,
        new_layout: Layout,
    ) -> Result<NonNull<[u8]>, AllocError> {
        self.as_scope().grow_zeroed(ptr, old_layout, new_layout)
    }

    #[inline(always)]
    unsafe fn shrink(&self, ptr: NonNull<u8>, old_layout: Layout, new_layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
        self.as_scope().shrink(ptr, old_layout, new_layout)
    }
}

#[inline(always)]
fn allocate<A, const MIN_ALIGN: usize, const UP: bool, const GUARANTEED_ALLOCATED: bool>(
    bump: &BumpScope<A, MIN_ALIGN, UP, GUARANTEED_ALLOCATED>,
    layout: Layout,
) -> Result<NonNull<[u8]>, AllocError>
where
    MinimumAlignment<MIN_ALIGN>: SupportedMinimumAlignment,
    A: BaseAllocator<GUARANTEED_ALLOCATED>,
{
    Ok(nonnull::slice_from_raw_parts(bump.try_alloc_layout(layout)?, layout.size()))
}

#[inline(always)]
unsafe fn deallocate<const MIN_ALIGN: usize, const UP: bool, const GUARANTEED_ALLOCATED: bool, A>(
    bump: &BumpScope<A, MIN_ALIGN, UP, GUARANTEED_ALLOCATED>,
    ptr: NonNull<u8>,
    layout: Layout,
) where
    MinimumAlignment<MIN_ALIGN>: SupportedMinimumAlignment,
{
    // free allocated space if this is the last allocation
    if is_last(bump, ptr, layout) {
        deallocate_assume_last(bump, ptr, layout);
    }
}

#[inline(always)]
unsafe fn deallocate_assume_last<const MIN_ALIGN: usize, const UP: bool, const GUARANTEED_ALLOCATED: bool, A>(
    bump: &BumpScope<A, MIN_ALIGN, UP, GUARANTEED_ALLOCATED>,
    ptr: NonNull<u8>,
    layout: Layout,
) where
    MinimumAlignment<MIN_ALIGN>: SupportedMinimumAlignment,
{
    debug_assert!(is_last(bump, ptr, layout));

    if UP {
        bump.chunk.get().set_pos(ptr);
    } else {
        let mut addr = nonnull::addr(ptr).get();
        addr += layout.size();
        addr = up_align_usize_unchecked(addr, MIN_ALIGN);

        let pos = nonnull::with_addr(ptr, NonZeroUsize::new_unchecked(addr));
        bump.chunk.get().set_pos(pos);
    }
}

#[inline(always)]
unsafe fn is_last<const MIN_ALIGN: usize, const UP: bool, const GUARANTEED_ALLOCATED: bool, A>(
    bump: &BumpScope<A, MIN_ALIGN, UP, GUARANTEED_ALLOCATED>,
    ptr: NonNull<u8>,
    layout: Layout,
) -> bool
where
    MinimumAlignment<MIN_ALIGN>: SupportedMinimumAlignment,
{
    if UP {
        ptr.as_ptr().add(layout.size()) == bump.chunk.get().pos().as_ptr()
    } else {
        ptr == bump.chunk.get().pos()
    }
}

#[inline(always)]
unsafe fn grow<A, const MIN_ALIGN: usize, const UP: bool, const GUARANTEED_ALLOCATED: bool>(
    bump: &BumpScope<A, MIN_ALIGN, UP, GUARANTEED_ALLOCATED>,
    old_ptr: NonNull<u8>,
    old_layout: Layout,
    new_layout: Layout,
) -> Result<NonNull<[u8]>, AllocError>
where
    MinimumAlignment<MIN_ALIGN>: SupportedMinimumAlignment,
    A: BaseAllocator<GUARANTEED_ALLOCATED>,
{
    debug_assert!(
        new_layout.size() >= old_layout.size(),
        "`new_layout.size()` must be greater than or equal to `old_layout.size()`"
    );

    if UP {
        if is_last(bump, old_ptr, old_layout) & align_fits(old_ptr, old_layout, new_layout) {
            // We may be able to grow in place! Just need to check if there is enough space.

            let chunk_end = bump.chunk.get().content_end();
            let remaining = nonnull::addr(chunk_end).get() - nonnull::addr(old_ptr).get();

            if new_layout.size() <= remaining {
                // There is enough space! We will grow in place. Just need to update the bump pointer.

                let old_addr = nonnull::addr(old_ptr);

                // Up-aligning a pointer inside a chunks content by `MIN_ALIGN` never overflows.
                let new_pos = up_align_usize_unchecked(old_addr.get() + new_layout.size(), MIN_ALIGN);

                bump.chunk.get().set_pos_addr(new_pos);

                Ok(nonnull::slice_from_raw_parts(old_ptr, new_layout.size()))
            } else {
                // The current chunk doesn't have enough space to allocate this layout. We need to allocate in another chunk.
                let new_ptr = bump.alloc_in_another_chunk(new_layout)?;
                nonnull::copy_nonoverlapping(old_ptr, new_ptr, old_layout.size());
                Ok(nonnull::slice_from_raw_parts(new_ptr, new_layout.size()))
            }
        } else {
            // We can't grow in place. We have to make a new allocation.
            let new_ptr = bump.try_alloc_layout(new_layout)?;
            nonnull::copy_nonoverlapping(old_ptr, new_ptr, old_layout.size());
            Ok(nonnull::slice_from_raw_parts(new_ptr, new_layout.size()))
        }
    } else {
        if is_last(bump, old_ptr, old_layout) {
            // We may be able to reuse the currently allocated space. Just need to check if the current chunk has enough space for that.
            let additional_size = new_layout.size() - old_layout.size();

            let old_addr = nonnull::addr(old_ptr);
            let new_addr = bump_down(old_addr, additional_size, new_layout.align().max(MIN_ALIGN));

            let very_start = nonnull::addr(bump.chunk.get().content_start());

            if new_addr >= very_start.get() {
                // There is enough space in the current chunk! We will reuse the allocated space.

                let new_addr = NonZeroUsize::new_unchecked(new_addr);
                let new_addr_end = new_addr.get() + new_layout.size();

                let new_ptr = nonnull::with_addr(old_ptr, new_addr);

                // Check if the regions don't overlap so we may use the faster `copy_nonoverlapping`.
                if new_addr_end < old_addr.get() {
                    nonnull::copy_nonoverlapping(old_ptr, new_ptr, old_layout.size());
                } else {
                    nonnull::copy(old_ptr, new_ptr, old_layout.size());
                }

                bump.chunk.get().set_pos_addr(new_addr.get());
                Ok(nonnull::slice_from_raw_parts(new_ptr, new_layout.size()))
            } else {
                // The current chunk doesn't have enough space to allocate this layout. We need to allocate in another chunk.
                let new_ptr = bump.alloc_in_another_chunk(new_layout)?;
                nonnull::copy_nonoverlapping(old_ptr, new_ptr, old_layout.size());
                Ok(nonnull::slice_from_raw_parts(new_ptr, new_layout.size()))
            }
        } else {
            // We can't reuse the allocated space. We have to make a new allocation.
            let new_ptr = bump.try_alloc_layout(new_layout)?;
            nonnull::copy_nonoverlapping(old_ptr, new_ptr, old_layout.size());
            Ok(nonnull::slice_from_raw_parts(new_ptr, new_layout.size()))
        }
    }
}

#[inline(always)]
unsafe fn grow_zeroed<A, const MIN_ALIGN: usize, const UP: bool, const GUARANTEED_ALLOCATED: bool>(
    bump: &BumpScope<A, MIN_ALIGN, UP, GUARANTEED_ALLOCATED>,
    old_ptr: NonNull<u8>,
    old_layout: Layout,
    new_layout: Layout,
) -> Result<NonNull<[u8]>, AllocError>
where
    MinimumAlignment<MIN_ALIGN>: SupportedMinimumAlignment,
    A: BaseAllocator<GUARANTEED_ALLOCATED>,
{
    let new_ptr = grow(bump, old_ptr, old_layout, new_layout)?;

    let delta = new_layout.size() - old_layout.size();
    new_ptr.cast::<u8>().as_ptr().add(old_layout.size()).write_bytes(0, delta);

    Ok(new_ptr)
}

#[inline(always)]
unsafe fn shrink<A, const MIN_ALIGN: usize, const UP: bool, const GUARANTEED_ALLOCATED: bool>(
    bump: &BumpScope<A, MIN_ALIGN, UP, GUARANTEED_ALLOCATED>,
    old_ptr: NonNull<u8>,
    old_layout: Layout,
    new_layout: Layout,
) -> Result<NonNull<[u8]>, AllocError>
where
    MinimumAlignment<MIN_ALIGN>: SupportedMinimumAlignment,
    A: BaseAllocator<GUARANTEED_ALLOCATED>,
{
    /// Called when `new_layout` doesn't fit alignment.
    /// Does ANY consumer cause this?
    /// Bumpalo just errors in this case..
    #[cold]
    #[inline(never)]
    unsafe fn shrink_unfit<A, const MIN_ALIGN: usize, const UP: bool, const GUARANTEED_ALLOCATED: bool>(
        bump: &BumpScope<A, MIN_ALIGN, UP, GUARANTEED_ALLOCATED>,
        old_ptr: NonNull<u8>,
        old_layout: Layout,
        new_layout: Layout,
    ) -> Result<NonNull<[u8]>, AllocError>
    where
        MinimumAlignment<MIN_ALIGN>: SupportedMinimumAlignment,
        A: BaseAllocator<GUARANTEED_ALLOCATED>,
    {
        if is_last(bump, old_ptr, old_layout) {
            let old_pos = bump.chunk.get().pos();
            deallocate_assume_last(bump, old_ptr, old_layout);

            let overlaps;
            let new_ptr;

            if let Some(in_chunk) = bump.alloc_in_current_chunk(new_layout) {
                new_ptr = in_chunk;
                overlaps = if UP {
                    let old_ptr_end = nonnull::add(old_ptr, new_layout.size());
                    old_ptr_end > new_ptr
                } else {
                    let new_ptr_end = nonnull::add(new_ptr, new_layout.size());
                    new_ptr_end > old_ptr
                }
            } else {
                new_ptr = match bump.alloc_in_another_chunk(new_layout) {
                    Ok(new_ptr) => new_ptr,
                    Err(error) => {
                        // Need to reset the bump pointer to the old position.
                        bump.chunk.get().set_pos(old_pos);
                        return Err(error);
                    }
                };
                overlaps = false;
            }

            if overlaps {
                nonnull::copy(old_ptr, new_ptr, new_layout.size());
            } else {
                nonnull::copy_nonoverlapping(old_ptr, new_ptr, new_layout.size());
            }

            Ok(nonnull::slice_from_raw_parts(new_ptr, new_layout.size()))
        } else {
            let new_ptr = bump.try_alloc_layout(new_layout)?;
            nonnull::copy_nonoverlapping(old_ptr, new_ptr, new_layout.size());
            Ok(nonnull::slice_from_raw_parts(new_ptr, new_layout.size()))
        }
    }

    debug_assert!(
        new_layout.size() <= old_layout.size(),
        "`new_layout.size()` must be smaller than or equal to `old_layout.size()`"
    );

    if !align_fits(old_ptr, old_layout, new_layout) {
        return shrink_unfit(bump, old_ptr, old_layout, new_layout);
    }

    // if that's not the last allocation, there is nothing we can do
    if !is_last(bump, old_ptr, old_layout) {
        // we return the size of the old layout
        return Ok(nonnull::slice_from_raw_parts(old_ptr, old_layout.size()));
    }

    if UP {
        let end = nonnull::addr(old_ptr).get() + new_layout.size();

        // Up-aligning a pointer inside a chunk by `MIN_ALIGN` never overflows.
        let new_pos = up_align_usize_unchecked(end, MIN_ALIGN);

        bump.chunk.get().set_pos_addr(new_pos);
        Ok(nonnull::slice_from_raw_parts(old_ptr, new_layout.size()))
    } else {
        let old_addr = nonnull::addr(old_ptr);
        let old_addr_old_end = NonZeroUsize::new_unchecked(old_addr.get() + old_layout.size());

        let new_addr = bump_down(old_addr_old_end, new_layout.size(), new_layout.align().max(MIN_ALIGN));
        let new_addr = NonZeroUsize::new_unchecked(new_addr);
        let old_addr_new_end = NonZeroUsize::new_unchecked(old_addr.get() + new_layout.size());

        let new_ptr = nonnull::with_addr(old_ptr, new_addr);

        let overlaps = old_addr_new_end > new_addr;

        if overlaps {
            nonnull::copy(old_ptr, new_ptr, new_layout.size());
        } else {
            nonnull::copy_nonoverlapping(old_ptr, new_ptr, new_layout.size());
        }

        bump.chunk.get().set_pos(new_ptr);
        Ok(nonnull::slice_from_raw_parts(new_ptr, new_layout.size()))
    }
}

#[inline(always)]
fn align_fits(old_ptr: NonNull<u8>, _old_layout: Layout, new_layout: Layout) -> bool {
    nonnull::is_aligned_to(old_ptr, new_layout.align())
}