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
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
use core::alloc::Layout;
use core::fmt;
use core::marker::PhantomData;
use core::mem::{align_of, ManuallyDrop};
use core::ptr::{self, NonNull};

#[cfg(feature = "allocator-api2")]
pub use allocator_api2::alloc::{Allocator, Global};

#[cfg(all(feature = "alloc", not(feature = "allocator-api2")))]
use alloc::alloc::{alloc as raw_alloc, dealloc as raw_dealloc};
#[cfg(all(feature = "alloc", not(feature = "allocator-api2")))]
use core::mem::transmute;

use crate::error::StorageError;

use super::utils::layout_aligned_bytes;
use super::{ByteStorage, RawBuffer};

pub trait RawAlloc {
    fn try_alloc(&self, layout: Layout) -> Result<NonNull<[u8]>, StorageError>;

    #[inline]
    fn try_alloc_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, StorageError> {
        let ptr = self.try_alloc(layout)?;
        unsafe { ptr::write_bytes(ptr.cast::<u8>().as_ptr(), 0, ptr.len()) };
        Ok(ptr)
    }

    unsafe fn try_resize(
        &self,
        ptr: NonNull<u8>,
        old_layout: Layout,
        new_layout: Layout,
    ) -> Result<NonNull<[u8]>, StorageError> {
        // Default implementation simply allocates and copies over the contents.
        // NB: not copying the entire previous buffer seems to defeat some automatic
        // optimization and results in much worse performance (on MacOS 14 at least).
        let new_ptr = self.try_alloc(new_layout)?;
        let cp_len = old_layout.size().min(new_ptr.len());
        if cp_len > 0 {
            ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_ptr().cast(), cp_len);
        }
        self.release(ptr, old_layout);
        Ok(new_ptr)
    }

    unsafe fn release(&self, ptr: NonNull<u8>, layout: Layout);
}

pub trait RawAllocIn: Sized {
    type RawAlloc: RawAlloc;

    fn try_alloc_in(self, layout: Layout) -> Result<(NonNull<[u8]>, Self::RawAlloc), StorageError>;

    #[inline]
    fn try_alloc_in_zeroed(
        self,
        layout: Layout,
    ) -> Result<(NonNull<[u8]>, Self::RawAlloc), StorageError> {
        let (ptr, alloc) = self.try_alloc_in(layout)?;
        unsafe { ptr::write_bytes(ptr.cast::<u8>().as_ptr(), 0, ptr.len()) };
        Ok((ptr, alloc))
    }
}

impl<A: RawAlloc> RawAllocIn for A {
    type RawAlloc = A;

    #[inline]
    fn try_alloc_in(self, layout: Layout) -> Result<(NonNull<[u8]>, Self::RawAlloc), StorageError> {
        let data = self.try_alloc(layout)?;
        Ok((data, self))
    }

    #[inline]
    fn try_alloc_in_zeroed(
        self,
        layout: Layout,
    ) -> Result<(NonNull<[u8]>, Self::RawAlloc), StorageError> {
        let data = self.try_alloc_zeroed(layout)?;
        Ok((data, self))
    }
}

pub trait RawAllocNew: RawAlloc + Clone {
    const NEW: Self;
}

#[cfg(not(feature = "allocator-api2"))]
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
#[cfg_attr(feature = "alloc", derive(Default, Copy))]
pub struct Global;

#[cfg(feature = "allocator-api2")]
impl<A: Allocator> RawAlloc for A {
    #[inline]
    fn try_alloc(&self, layout: Layout) -> Result<NonNull<[u8]>, StorageError> {
        self.allocate(layout).map_err(|_| StorageError::AllocError)
    }

    #[inline]
    fn try_alloc_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, StorageError> {
        self.allocate_zeroed(layout)
            .map_err(|_| StorageError::AllocError)
    }

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

#[cfg(all(feature = "alloc", not(feature = "allocator-api2")))]
impl RawAlloc for Global {
    #[inline]
    fn try_alloc(&self, layout: Layout) -> Result<NonNull<[u8]>, StorageError> {
        let ptr = if layout.size() == 0 {
            // FIXME: use Layout::dangling when stabilized
            unsafe { NonNull::new_unchecked(transmute(layout.align())) }
        } else {
            let Some(ptr) = NonNull::new(unsafe { raw_alloc(layout) }) else {
                return Err(StorageError::AllocError);
            };
            ptr
        };
        Ok(NonNull::slice_from_raw_parts(ptr, layout.size()))
    }

    #[inline]
    unsafe fn release(&self, ptr: NonNull<u8>, layout: Layout) {
        if layout.size() > 0 {
            raw_dealloc(ptr.as_ptr(), layout);
        }
    }
}

#[cfg(not(feature = "alloc"))]
// Stub implementation to allow Global as the default allocator type
// even when the `alloc` feature is not enabled.
impl RawAlloc for Global {
    fn try_alloc(&self, _layout: Layout) -> Result<NonNull<[u8]>, StorageError> {
        unimplemented!();
    }

    unsafe fn release(&self, _ptr: NonNull<u8>, _layout: Layout) {
        unimplemented!();
    }
}

#[cfg(feature = "alloc")]
impl RawAllocNew for Global {
    const NEW: Self = Global;
}

pub trait AllocHeader: Copy + Clone + Sized {
    const EMPTY: Self;

    fn is_empty(&self) -> bool;
}

pub trait AllocLayout {
    type Header: AllocHeader;
    type Data;

    fn layout(header: &Self::Header) -> Result<Layout, StorageError>;

    fn update_header(header: &mut Self::Header, layout: Layout);
}

pub trait AllocHandle: RawBuffer<RawData = <Self::Meta as AllocLayout>::Data> {
    type Alloc: RawAlloc;
    type Meta: AllocLayout;

    fn allocator(&self) -> &Self::Alloc;

    fn is_empty_handle(&self) -> bool;

    /// SAFETY: is_empty_handle must return false
    unsafe fn header(&self) -> &<Self::Meta as AllocLayout>::Header;

    /// SAFETY: is_empty_handle must return false
    unsafe fn header_mut(&mut self) -> &mut <Self::Meta as AllocLayout>::Header;

    fn alloc_handle_in<A>(
        alloc_in: A,
        header: <Self::Meta as AllocLayout>::Header,
        exact: bool,
    ) -> Result<Self, StorageError>
    where
        A: RawAllocIn<RawAlloc = Self::Alloc>;

    fn resize_handle(
        &mut self,
        new_header: <Self::Meta as AllocLayout>::Header,
        exact: bool,
    ) -> Result<(), StorageError>;

    #[inline]
    fn spawn_handle(
        &self,
        header: <Self::Meta as AllocLayout>::Header,
        exact: bool,
    ) -> Result<Self, StorageError>
    where
        Self::Alloc: Clone,
    {
        Self::alloc_handle_in(self.allocator().clone(), header, exact)
    }
}

pub trait AllocHandleNew: AllocHandle {
    const NEW: Self;
    const NEW_ALLOC: Self::Alloc;
}

pub type AllocParts<Handle> = (
    <<Handle as AllocHandle>::Meta as AllocLayout>::Header,
    NonNull<<<Handle as AllocHandle>::Meta as AllocLayout>::Data>,
    <Handle as AllocHandle>::Alloc,
);

pub trait AllocHandleParts: AllocHandle {
    fn handle_from_parts(
        header: <Self::Meta as AllocLayout>::Header,
        data: NonNull<<Self::Meta as AllocLayout>::Data>,
        alloc: Self::Alloc,
    ) -> Self;

    fn handle_into_parts(self) -> AllocParts<Self>;
}

#[derive(Debug)]
pub struct FatAllocHandle<Meta: AllocLayout, Alloc: RawAlloc> {
    header: Meta::Header,
    data: NonNull<Meta::Data>,
    alloc: Alloc,
}

impl<Meta: AllocLayout, Alloc: RawAlloc> FatAllocHandle<Meta, Alloc> {
    #[inline]
    const fn new(header: Meta::Header, data: NonNull<u8>, alloc: Alloc) -> Self {
        Self {
            header,
            data: data.cast(),
            alloc,
        }
    }

    #[inline]
    pub const fn dangling(header: Meta::Header, alloc: Alloc) -> Self {
        Self::new(header, NonNull::<Meta::Data>::dangling().cast(), alloc)
    }

    #[inline]
    fn is_dangling(&self) -> bool {
        ptr::eq(self.data.as_ptr(), NonNull::dangling().as_ptr())
    }

    #[inline]
    pub fn into_raw_parts(self) -> (Meta::Header, NonNull<u8>, Alloc) {
        let parts = ManuallyDrop::new(self);
        let header = unsafe { ptr::read(&parts.header) };
        let alloc = unsafe { ptr::read(&parts.alloc) };
        let data = parts.data.cast();
        (header, data, alloc)
    }
}

impl<Meta: AllocLayout, Alloc: RawAlloc> RawBuffer for FatAllocHandle<Meta, Alloc> {
    type RawData = Meta::Data;

    #[inline]
    fn data_ptr(&self) -> *const Self::RawData {
        self.data.as_ptr()
    }

    #[inline]
    fn data_ptr_mut(&mut self) -> *mut Self::RawData {
        self.data.as_ptr()
    }
}

impl<Meta: AllocLayout, Alloc: RawAlloc> AllocHandle for FatAllocHandle<Meta, Alloc> {
    type Alloc = Alloc;
    type Meta = Meta;

    #[inline]
    fn allocator(&self) -> &Self::Alloc {
        &self.alloc
    }

    #[inline]
    fn is_empty_handle(&self) -> bool {
        self.header.is_empty()
    }

    #[inline]
    unsafe fn header(&self) -> &Meta::Header {
        &self.header
    }

    #[inline]
    unsafe fn header_mut(&mut self) -> &mut Meta::Header {
        &mut self.header
    }

    #[inline]
    fn alloc_handle_in<A>(
        alloc_in: A,
        mut header: <Self::Meta as AllocLayout>::Header,
        exact: bool,
    ) -> Result<Self, StorageError>
    where
        A: RawAllocIn<RawAlloc = Self::Alloc>,
    {
        let mut layout = Meta::layout(&header)?;
        let (ptr, alloc) = alloc_in.try_alloc_in(layout)?;
        if !exact && layout.size() != ptr.len() {
            layout = unsafe { Layout::from_size_align_unchecked(ptr.len(), layout.align()) };
            Meta::update_header(&mut header, layout);
        }
        Ok(Self::new(header, ptr.cast(), alloc))
    }

    #[inline]
    fn resize_handle(
        &mut self,
        mut new_header: Meta::Header,
        exact: bool,
    ) -> Result<(), StorageError> {
        if new_header.is_empty() {
            if !self.is_dangling() {
                let layout = Meta::layout(&self.header)?;
                unsafe { self.alloc.release(self.data.cast(), layout) };
                self.data = NonNull::dangling();
            }
        } else {
            let new_layout = Meta::layout(&new_header)?;
            let ptr = if self.is_dangling() {
                self.alloc.try_alloc(new_layout)?
            } else {
                let old_layout: Layout = Meta::layout(&self.header)?;
                unsafe {
                    self.alloc
                        .try_resize(self.data.cast(), old_layout, new_layout)
                }?
            };
            if !exact && new_layout.size() != ptr.len() {
                let layout =
                    unsafe { Layout::from_size_align_unchecked(ptr.len(), new_layout.align()) };
                Meta::update_header(&mut new_header, layout);
            }
            self.data = ptr.cast();
        }
        self.header = new_header;
        Ok(())
    }
}

impl<Meta: AllocLayout, Alloc: RawAllocNew> AllocHandleNew for FatAllocHandle<Meta, Alloc> {
    const NEW: Self = Self::dangling(Meta::Header::EMPTY, Self::NEW_ALLOC);
    const NEW_ALLOC: Self::Alloc = Alloc::NEW;
}

impl<Meta: AllocLayout, Alloc: RawAlloc> AllocHandleParts for FatAllocHandle<Meta, Alloc> {
    #[inline]
    fn handle_from_parts(
        header: <Self::Meta as AllocLayout>::Header,
        data: NonNull<<Self::Meta as AllocLayout>::Data>,
        alloc: Self::Alloc,
    ) -> Self {
        Self {
            header,
            data,
            alloc,
        }
    }

    #[inline]
    fn handle_into_parts(
        self,
    ) -> (
        <Self::Meta as AllocLayout>::Header,
        NonNull<<Self::Meta as AllocLayout>::Data>,
        Self::Alloc,
    ) {
        let slf = ManuallyDrop::new(self);
        (unsafe { ptr::read(&slf.header) }, slf.data, unsafe {
            ptr::read(&slf.alloc)
        })
    }
}

impl<Meta: AllocLayout, Alloc: RawAlloc> Drop for FatAllocHandle<Meta, Alloc> {
    fn drop(&mut self) {
        if !self.is_dangling() {
            let layout = Meta::layout(&self.header).expect("error calculating layout");
            unsafe {
                self.alloc.release(self.data.cast(), layout);
            }
        }
    }
}

struct ThinPtr<Meta: AllocLayout>(NonNull<Meta::Data>);

impl<Meta: AllocLayout> ThinPtr<Meta> {
    const DATA_OFFSET: usize = data_offset::<Meta::Header, Meta::Data>();

    #[inline]
    pub const fn dangling() -> Self {
        Self(NonNull::dangling())
    }

    #[inline]
    pub fn is_dangling(&self) -> bool {
        ptr::eq(self.0.as_ptr(), NonNull::dangling().as_ptr())
    }

    #[inline]
    pub const fn from_alloc(ptr: NonNull<[u8]>) -> Self {
        Self(unsafe {
            NonNull::new_unchecked(
                (ptr.as_ptr() as *mut u8).add(Self::DATA_OFFSET) as *mut Meta::Data
            )
        })
    }

    #[inline]
    pub const fn to_alloc(&self) -> NonNull<u8> {
        unsafe { NonNull::new_unchecked(self.header_ptr()) }.cast()
    }

    #[inline]
    pub const fn as_ptr(&self) -> *mut Meta::Data {
        self.0.as_ptr()
    }

    #[inline]
    pub const fn header_ptr(&self) -> *mut Meta::Header {
        unsafe { (self.0.as_ptr() as *mut u8).sub(Self::DATA_OFFSET) as *mut _ }
    }
}

impl<Meta: AllocLayout> fmt::Debug for ThinPtr<Meta> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:?}", &self.0)
    }
}

#[derive(Debug)]
pub struct ThinAllocHandle<Meta: AllocLayout, Alloc: RawAlloc> {
    data: ThinPtr<Meta>,
    alloc: Alloc,
}

impl<Meta: AllocLayout, Alloc: RawAlloc> ThinAllocHandle<Meta, Alloc> {
    #[inline]
    const fn new(data: ThinPtr<Meta>, alloc: Alloc) -> Self {
        ThinAllocHandle { data, alloc }
    }

    #[inline]
    pub const fn dangling(alloc: Alloc) -> Self {
        Self::new(ThinPtr::dangling(), alloc)
    }

    #[inline]
    fn combined_layout(data_layout: Layout, is_empty: bool) -> Result<Layout, StorageError> {
        if data_layout.size() == 0 && is_empty {
            Ok(unsafe { Layout::from_size_align_unchecked(0, align_of::<Meta::Header>()) })
        } else {
            match Layout::new::<Meta::Header>().extend(data_layout) {
                Ok((layout, _)) => Ok(layout),
                Err(err) => Err(StorageError::LayoutError(err)),
            }
        }
    }

    #[inline]
    fn update_header(ptr: NonNull<[u8]>, header: &mut Meta::Header, data_layout: Layout) {
        let data_len = ptr.len() - ThinPtr::<Meta>::DATA_OFFSET;
        let layout = unsafe { Layout::from_size_align_unchecked(data_len, data_layout.align()) };
        Meta::update_header(header, layout);
    }
}

impl<Meta: AllocLayout, Alloc: RawAlloc> RawBuffer for ThinAllocHandle<Meta, Alloc> {
    type RawData = Meta::Data;

    #[inline]
    fn data_ptr(&self) -> *const Self::RawData {
        self.data.as_ptr()
    }

    #[inline]
    fn data_ptr_mut(&mut self) -> *mut Self::RawData {
        self.data.as_ptr()
    }
}

impl<Meta: AllocLayout, Alloc: RawAlloc> AllocHandle for ThinAllocHandle<Meta, Alloc> {
    type Alloc = Alloc;
    type Meta = Meta;

    #[inline]
    fn allocator(&self) -> &Self::Alloc {
        &self.alloc
    }

    #[inline]
    fn is_empty_handle(&self) -> bool {
        // no header exists for a dangling data pointer
        self.data.is_dangling()
    }

    #[inline]
    unsafe fn header(&self) -> &<Self::Meta as AllocLayout>::Header {
        &*self.data.header_ptr()
    }

    #[inline]
    unsafe fn header_mut(&mut self) -> &mut <Self::Meta as AllocLayout>::Header {
        &mut *self.data.header_ptr()
    }

    #[inline]
    fn alloc_handle_in<A>(
        alloc_in: A,
        mut header: <Self::Meta as AllocLayout>::Header,
        exact: bool,
    ) -> Result<Self, StorageError>
    where
        A: RawAllocIn<RawAlloc = Self::Alloc>,
    {
        let data_layout = Meta::layout(&header)?;
        let alloc_layout = Self::combined_layout(data_layout, header.is_empty())?;
        let (ptr, alloc) = alloc_in.try_alloc_in(alloc_layout)?;
        if ptr.len() < ThinPtr::<Meta>::DATA_OFFSET {
            unsafe { alloc.release(ptr.cast(), alloc_layout) };
            return if ptr.len() == 0 && data_layout.size() == 0 {
                Ok(ThinAllocHandle::dangling(alloc))
            } else {
                Err(StorageError::CapacityLimit)
            };
        }
        if !exact && alloc_layout.size() != ptr.len() {
            Self::update_header(ptr, &mut header, data_layout);
        }
        let data = ThinPtr::<Meta>::from_alloc(ptr);
        unsafe { data.header_ptr().write(header) };
        Ok(Self::new(data, alloc))
    }

    #[inline]
    fn resize_handle(
        &mut self,
        mut new_header: Meta::Header,
        exact: bool,
    ) -> Result<(), StorageError> {
        let data_layout = Meta::layout(&new_header)?;
        let alloc_layout = Self::combined_layout(data_layout, new_header.is_empty())?;
        let ptr = if self.data.is_dangling() {
            self.alloc.try_alloc(alloc_layout)?
        } else {
            let old_layout = Self::combined_layout(Meta::layout(unsafe { self.header() })?, false)?;
            unsafe {
                self.alloc
                    .try_resize(self.data.to_alloc(), old_layout, alloc_layout)
            }?
        };
        if ptr.len() < ThinPtr::<Meta>::DATA_OFFSET {
            unsafe { self.alloc.release(ptr.cast(), alloc_layout) };
            return if ptr.len() == 0 && data_layout.size() == 0 {
                self.data = ThinPtr::dangling();
                Ok(())
            } else {
                Err(StorageError::CapacityLimit)
            };
        }
        if !exact && alloc_layout.size() != ptr.len() {
            Self::update_header(ptr, &mut new_header, data_layout);
        }
        let data = ThinPtr::<Meta>::from_alloc(ptr);
        unsafe { data.header_ptr().write(new_header) };
        self.data = data;
        Ok(())
    }
}

impl<Meta: AllocLayout, Alloc: RawAllocNew> AllocHandleNew for ThinAllocHandle<Meta, Alloc> {
    const NEW: Self = Self::dangling(Self::NEW_ALLOC);
    const NEW_ALLOC: Self::Alloc = Alloc::NEW;
}

impl<Meta: AllocLayout, Alloc: RawAlloc> Drop for ThinAllocHandle<Meta, Alloc> {
    fn drop(&mut self) {
        if !self.data.is_dangling() {
            let layout = Meta::layout(unsafe { self.header() })
                .and_then(|layout| Self::combined_layout(layout, false))
                .expect("error calculating layout");
            unsafe {
                self.alloc.release(self.data.to_alloc(), layout);
            }
        }
    }
}

#[derive(Debug, Default, PartialEq, Eq)]
pub struct FixedAlloc<'a>(PhantomData<&'a mut ()>);

impl FixedAlloc<'_> {
    pub(crate) const NEW: Self = Self(PhantomData);
}

impl RawAlloc for FixedAlloc<'_> {
    #[inline]
    fn try_alloc(&self, _layout: Layout) -> Result<NonNull<[u8]>, StorageError> {
        Err(StorageError::CapacityLimit)
    }

    #[inline]
    unsafe fn try_resize(
        &self,
        ptr: NonNull<u8>,
        old_layout: Layout,
        new_layout: Layout,
    ) -> Result<NonNull<[u8]>, StorageError> {
        if old_layout.align() != new_layout.align() || new_layout.size() > old_layout.size() {
            Err(StorageError::CapacityLimit)
        } else {
            Ok(NonNull::slice_from_raw_parts(ptr, old_layout.size()))
        }
    }

    #[inline]
    unsafe fn release(&self, _ptr: NonNull<u8>, _layout: Layout) {}
}

impl<'a, T, const N: usize> RawAllocIn for &'a mut ByteStorage<T, N> {
    type RawAlloc = FixedAlloc<'a>;

    #[inline]
    fn try_alloc_in(self, layout: Layout) -> Result<(NonNull<[u8]>, Self::RawAlloc), StorageError> {
        let ptr = layout_aligned_bytes(self.as_uninit_slice(), layout)?;
        let alloc = FixedAlloc::default();
        Ok((ptr, alloc))
    }
}

#[derive(Debug)]
pub struct SpillAlloc<'a, A> {
    alloc: A,
    initial: *const u8,
    _fixed: FixedAlloc<'a>,
}

impl<A: RawAlloc> Default for SpillAlloc<'_, A>
where
    A: Default,
{
    #[inline]
    fn default() -> Self {
        Self::new(A::default(), ptr::null())
    }
}

impl<A: RawAlloc> SpillAlloc<'_, A> {
    pub(crate) const fn new(alloc: A, initial: *const u8) -> Self {
        Self {
            alloc,
            initial,
            _fixed: FixedAlloc::NEW,
        }
    }
}

impl<A: RawAlloc> RawAlloc for SpillAlloc<'_, A> {
    #[inline]
    fn try_alloc(&self, layout: Layout) -> Result<NonNull<[u8]>, StorageError> {
        self.alloc.try_alloc(layout)
    }

    #[inline]
    unsafe fn release(&self, ptr: NonNull<u8>, layout: Layout) {
        if !ptr::eq(self.initial, ptr.as_ptr()) {
            self.alloc.release(ptr, layout)
        }
    }
}

impl<'a, A: RawAllocNew> Clone for SpillAlloc<'a, A> {
    fn clone(&self) -> Self {
        Self::NEW
    }
}

impl<'a, A: RawAllocNew> RawAllocNew for SpillAlloc<'a, A> {
    const NEW: Self = Self::new(A::NEW, ptr::null());
}

#[derive(Debug, Default, Clone)]
pub struct SpillStorage<'a, I: 'a, A> {
    pub(crate) buffer: I,
    pub(crate) alloc: A,
    _pd: PhantomData<&'a mut ()>,
}

impl<I, A: RawAllocNew> SpillStorage<'_, I, A> {
    #[inline]
    pub fn new(buffer: I) -> Self {
        Self::new_in(buffer, A::NEW)
    }
}

impl<I, A: RawAlloc> SpillStorage<'_, I, A> {
    #[inline]
    pub fn new_in(buffer: I, alloc: A) -> Self {
        Self {
            buffer,
            alloc,
            _pd: PhantomData,
        }
    }
}

impl<'a, I, A> RawAllocIn for SpillStorage<'a, I, A>
where
    I: RawAllocIn<RawAlloc = FixedAlloc<'a>>,
    A: RawAlloc,
{
    type RawAlloc = SpillAlloc<'a, A>;

    #[inline]
    fn try_alloc_in(self, layout: Layout) -> Result<(NonNull<[u8]>, Self::RawAlloc), StorageError> {
        match self.buffer.try_alloc_in(layout) {
            Ok((ptr, fixed)) => {
                let alloc = SpillAlloc {
                    alloc: self.alloc,
                    initial: ptr.as_ptr().cast(),
                    _fixed: fixed,
                };
                Ok((ptr, alloc))
            }
            Err(StorageError::CapacityLimit) => {
                let ptr = self.alloc.try_alloc(layout)?;
                let alloc = SpillAlloc {
                    alloc: self.alloc,
                    initial: ptr::null(),
                    _fixed: FixedAlloc::default(),
                };
                Ok((ptr, alloc))
            }
            Err(err) => Err(err),
        }
    }
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct Thin;

// Calculate the byte offset of Data when following Header. This should
// be equivalent to offset_of!((Meta::Header, Meta::Data), 1)
// although repr(C) would need to be used to guarantee consistency.
// See `Layout::padding_needed_for`` (currently unstable) for reference.
const fn data_offset<Header, Data>() -> usize {
    let header = Layout::new::<Header>();
    let data_align = align_of::<Data>();
    header.size().wrapping_add(data_align).wrapping_sub(1) & !data_align.wrapping_sub(1)
}