dyn_stack/
lib.rs

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
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
#![no_std]
#![cfg_attr(feature = "nightly", feature(allocator_api, dropck_eyepatch))]
#![cfg_attr(docsrs, feature(doc_cfg))]

//! Stack that allows users to allocate dynamically sized arrays.
//!
//! The stack wraps a buffer of bytes that it uses as a workspace.
//! Allocating an array takes a chunk of memory from the stack, which can be reused once the array
//! is dropped.
//!
//! # Examples:
//! ```
//! use core::mem::MaybeUninit;
//! use dyn_stack::{DynStack, StackReq};
//!
//! // We allocate enough storage for 3 `i32` and 4 `u8`.
//! let mut buf = [MaybeUninit::uninit();
//!     StackReq::new::<i32>(3)
//!         .and(StackReq::new::<u8>(4))
//!         .unaligned_bytes_required()];
//! let stack = DynStack::new(&mut buf);
//!
//! {
//!     // We can have nested allocations.
//!     // 3×`i32`
//!     let (array_i32, substack) = stack.make_with::<i32>(3, |i| i as i32);
//!     // and 4×`u8`
//!     let (mut array_u8, _) = substack.make_with::<u8>(4, |_| 0);
//!
//!     // We can read from the arrays,
//!     assert_eq!(array_i32[0], 0);
//!     assert_eq!(array_i32[1], 1);
//!     assert_eq!(array_i32[2], 2);
//!
//!     // and write to them.
//!     array_u8[0] = 1;
//!
//!     assert_eq!(array_u8[0], 1);
//!     assert_eq!(array_u8[1], 0);
//!     assert_eq!(array_u8[2], 0);
//!     assert_eq!(array_u8[3], 0);
//! }
//!
//! // We can also have disjoint allocations.
//! {
//!     // 3×`i32`
//!     let (mut array_i32, _) = stack.make_with::<i32>(3, |i| i as i32);
//!     assert_eq!(array_i32[0], 0);
//!     assert_eq!(array_i32[1], 1);
//!     assert_eq!(array_i32[2], 2);
//! }
//!
//! {
//!     // or 4×`u8`
//!     let (mut array_u8, _) = stack.make_with::<i32>(4, |i| i as i32 + 3);
//!     assert_eq!(array_u8[0], 3);
//!     assert_eq!(array_u8[1], 4);
//!     assert_eq!(array_u8[2], 5);
//!     assert_eq!(array_u8[3], 6);
//! }
//! ```

extern crate alloc;

pub mod mem;

use bytemuck::Pod;
#[cfg(feature = "nightly")]
pub use mem::MemBuffer;

pub use mem::GlobalMemBuffer;
pub use mem::GlobalPodBuffer;

mod stack_req;
pub use stack_req::{SizeOverflow, StackReq};

use core::fmt::Debug;
use core::marker::PhantomData;
use core::mem::MaybeUninit;
use core::ptr::NonNull;

/// Stack wrapper around a buffer of uninitialized bytes.
#[repr(transparent)]
pub struct DynStack {
    buffer: [MaybeUninit<u8>],
}
/// Stack wrapper around a buffer of bytes.
#[repr(transparent)]
pub struct PodStack {
    buffer: [u8],
}

/// Owns an unsized array of data, allocated from some stack.
pub struct DynArray<'a, T> {
    ptr: NonNull<T>,
    len: usize,
    __marker: PhantomData<(&'a (), T)>,
}

/// Owns an unsized array of data, allocated from some stack.
pub struct UnpodStack<'a> {
    ptr: NonNull<u8>,
    len: usize,
    __marker: PhantomData<&'a ()>,
}

impl<'a, T: Debug> Debug for DynArray<'a, T> {
    fn fmt(&self, fmt: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> {
        (**self).fmt(fmt)
    }
}

unsafe impl<'a, T> Send for DynArray<'a, T> where T: Send {}
unsafe impl<'a, T> Sync for DynArray<'a, T> where T: Sync {}
unsafe impl<'a> Send for UnpodStack<'a> {}
unsafe impl<'a> Sync for UnpodStack<'a> {}

impl<'a, T> DynArray<'a, T> {
    #[inline]
    fn get_data(self) -> &'a mut [T] {
        let len = self.len;
        let data = self.ptr.as_ptr();
        core::mem::forget(self);
        unsafe { core::slice::from_raw_parts_mut(data, len) }
    }
}

impl<'a, T> Drop for DynArray<'a, T> {
    #[inline]
    fn drop(&mut self) {
        unsafe {
            core::ptr::drop_in_place(
                core::slice::from_raw_parts_mut(self.ptr.as_ptr(), self.len) as *mut [T]
            )
        };
    }
}

const BYTE: u8 = 0xCD;
impl<'a> Drop for UnpodStack<'a> {
    #[inline]
    fn drop(&mut self) {
        unsafe { core::ptr::write_bytes(self.ptr.as_ptr(), BYTE, self.len) }
    }
}

impl<'a, T> core::ops::Deref for DynArray<'a, T> {
    type Target = [T];

    #[inline]
    fn deref(&self) -> &'_ Self::Target {
        unsafe { core::slice::from_raw_parts(self.ptr.as_ptr(), self.len) }
    }
}

impl<'a, T> core::ops::DerefMut for DynArray<'a, T> {
    #[inline]
    fn deref_mut(&mut self) -> &mut Self::Target {
        unsafe { core::slice::from_raw_parts_mut(self.ptr.as_ptr(), self.len) }
    }
}

impl<'a, T> AsRef<[T]> for DynArray<'a, T> {
    #[inline]
    fn as_ref(&self) -> &'_ [T] {
        unsafe { core::slice::from_raw_parts(self.ptr.as_ptr(), self.len) }
    }
}

impl<'a, T> AsMut<[T]> for DynArray<'a, T> {
    #[inline]
    fn as_mut(&mut self) -> &'_ mut [T] {
        unsafe { core::slice::from_raw_parts_mut(self.ptr.as_ptr(), self.len) }
    }
}

impl<'a> core::ops::Deref for UnpodStack<'a> {
    type Target = DynStack;

    #[inline]
    fn deref(&self) -> &'_ Self::Target {
        unsafe {
            &*(core::slice::from_raw_parts(self.ptr.as_ptr(), self.len) as *const [_]
                as *const DynStack)
        }
    }
}

impl<'a> core::ops::DerefMut for UnpodStack<'a> {
    #[inline]
    fn deref_mut(&mut self) -> &mut Self::Target {
        unsafe {
            &mut *(core::slice::from_raw_parts_mut(self.ptr.as_ptr(), self.len) as *mut [_]
                as *mut DynStack)
        }
    }
}

#[inline]
unsafe fn transmute_slice<T>(slice: &mut [MaybeUninit<u8>], size: usize) -> &mut [T] {
    core::slice::from_raw_parts_mut(slice.as_mut_ptr() as *mut T, size)
}
#[inline]
unsafe fn transmute_pod_slice<T: Pod>(slice: &mut [u8], size: usize) -> &mut [T] {
    core::slice::from_raw_parts_mut(slice.as_mut_ptr() as *mut T, size)
}

struct DropGuard<T> {
    ptr: *mut T,
    len: usize,
}

impl<T> Drop for DropGuard<T> {
    #[inline]
    fn drop(&mut self) {
        unsafe {
            core::ptr::drop_in_place(core::slice::from_raw_parts_mut(self.ptr, self.len) as *mut [T])
        };
    }
}

#[inline]
fn init_array_with<T>(mut f: impl FnMut(usize) -> T, array: &mut [MaybeUninit<T>]) -> &mut [T] {
    let len = array.len();
    let ptr = array.as_mut_ptr() as *mut T;

    let mut guard = DropGuard { ptr, len: 0 };

    for i in 0..len {
        guard.len = i;
        unsafe { ptr.add(i).write(f(i)) };
    }
    core::mem::forget(guard);

    unsafe { core::slice::from_raw_parts_mut(ptr, len) }
}

#[inline]
fn init_pod_array_with<T: Pod>(mut f: impl FnMut(usize) -> T, array: &mut [T]) -> &mut [T] {
    for (i, x) in array.iter_mut().enumerate() {
        *x = f(i);
    }
    array
}

#[inline]
unsafe fn init_array_with_iter<T, I: Iterator<Item = T>>(
    iter: I,
    ptr: &mut [MaybeUninit<T>],
) -> usize {
    let max_len = ptr.len();
    let ptr = ptr.as_mut_ptr();
    let mut guard = DropGuard { ptr, len: 0 };

    iter.take(max_len).enumerate().for_each(|(i, item)| {
        *ptr.add(i) = MaybeUninit::new(item);
        guard.len += 1;
    });

    let len = guard.len;
    core::mem::forget(guard);

    len
}

#[inline]
fn init_pod_array_with_iter<T: Pod, I: Iterator<Item = T>>(iter: I, ptr: &mut [T]) -> usize {
    let mut len = 0;
    iter.zip(ptr).for_each(|(item, dst)| {
        *dst = item;
        len += 1;
    });
    len
}

#[track_caller]
#[inline]
fn check_alignment(align: usize, alignof_val: usize, type_name: &'static str) {
    assert!(
        (align & (align.wrapping_sub(1))) == 0,
        r#"
requested alignment is not a power of two:
 - requested alignment: {}
"#,
        align
    );
    assert!(
        alignof_val <= align,
        r#"
requested alignment is less than the minimum valid alignment for `{}`:
 - requested alignment: {}
 - minimum alignment: {}
"#,
        type_name,
        align,
        alignof_val,
    );
}

#[track_caller]
#[inline]
fn check_enough_space_for_align_offset(len: usize, align: usize, align_offset: usize) {
    assert!(
        len >= align_offset,
        r#"
buffer is not large enough to accomodate the requested alignment
 - buffer length: {}
 - requested alignment: {}
 - byte offset for alignment: {}
"#,
        align,
        align_offset,
        len,
    );
}

#[track_caller]
#[inline]
fn check_enough_space_for_array(
    remaining_len: usize,
    sizeof_val: usize,
    array_len: usize,
    type_name: &'static str,
) {
    if sizeof_val == 0 {
        return;
    }
    assert!(
        remaining_len / sizeof_val >= array_len,
        r#"
buffer is not large enough to allocate an array of type `{}` of the requested length:
 - remaining buffer length (after adjusting for alignment): {},
 - requested array length: {} ({} bytes),
"#,
        type_name,
        remaining_len,
        array_len,
        array_len * sizeof_val,
    );
}

impl DynStack {
    /// Returns a new [`DynStack`] from the provided memory buffer.
    #[inline]
    pub fn new(buffer: &mut [MaybeUninit<u8>]) -> &mut Self {
        unsafe { &mut *(buffer as *mut [MaybeUninit<u8>] as *mut Self) }
    }

    /// Returns a new [`DynStack`] from the provided memory buffer.
    #[inline]
    pub fn new_any<T>(buffer: &mut [MaybeUninit<T>]) -> &mut Self {
        let len = buffer.len() * size_of::<T>();
        Self::new(unsafe { core::slice::from_raw_parts_mut(buffer.as_mut_ptr() as *mut _, len) })
    }

    /// Returns `true` if the stack can hold an allocation with the given size and alignment
    /// requirements.
    #[inline]
    #[must_use]
    pub fn can_hold(&self, alloc_req: StackReq) -> bool {
        let align = alloc_req.align_bytes();
        let size = alloc_req.size_bytes();
        let align_offset = self.buffer.as_ptr().align_offset(align);
        let self_size = self.buffer.len();
        (self_size >= align_offset) && (self_size - align_offset >= size)
    }

    /// Returns the number of bytes that this stack can hold.
    #[inline]
    pub fn len_bytes(&self) -> usize {
        self.buffer.len()
    }

    /// Returns a pointer to the (possibly uninitialized) stack memory.
    #[inline]
    pub fn as_ptr(&self) -> *const u8 {
        self.buffer.as_ptr() as _
    }

    #[track_caller]
    #[inline]
    fn split_buffer<'out>(
        buffer: &'out mut [MaybeUninit<u8>],
        size: usize,
        align: usize,
        sizeof_val: usize,
        alignof_val: usize,
        type_name: &'static str,
    ) -> (&'out mut [MaybeUninit<u8>], &'out mut [MaybeUninit<u8>]) {
        let len = buffer.len();
        let align_offset = buffer.as_mut_ptr().align_offset(align);

        check_alignment(align, alignof_val, type_name);
        check_enough_space_for_align_offset(len, align, align_offset);
        check_enough_space_for_array(len - align_offset, sizeof_val, size, type_name);

        let buffer = unsafe { buffer.get_unchecked_mut(align_offset..) };
        let len = len - align_offset;

        let begin = buffer.as_mut_ptr();
        let begin_len = size * sizeof_val;
        let mid = unsafe { begin.add(begin_len) };
        let mid_len = len - begin_len;
        unsafe {
            (
                core::slice::from_raw_parts_mut(begin, begin_len),
                core::slice::from_raw_parts_mut(mid, mid_len),
            )
        }
    }

    /// Returns a new aligned and uninitialized [`DynArray`] and a stack over the remainder of the
    /// buffer.
    ///
    /// # Panics
    ///
    /// Panics if the stack isn't large enough to allocate the array.
    #[track_caller]
    #[inline]
    #[must_use]
    pub fn make_aligned_uninit<T>(
        &mut self,
        size: usize,
        align: usize,
    ) -> (DynArray<'_, MaybeUninit<T>>, &mut Self) {
        let (taken, remaining) = Self::split_buffer(
            &mut self.buffer,
            size,
            align,
            core::mem::size_of::<T>(),
            core::mem::align_of::<T>(),
            core::any::type_name::<T>(),
        );

        let (len, ptr) = {
            let taken = unsafe { transmute_slice::<MaybeUninit<T>>(taken, size) };
            (taken.len(), taken.as_mut_ptr())
        };
        (
            DynArray {
                ptr: unsafe { NonNull::<MaybeUninit<T>>::new_unchecked(ptr) },
                len,
                __marker: PhantomData,
            },
            DynStack::new(remaining),
        )
    }

    /// Returns a new aligned [`DynArray`], initialized with the provided function, and a stack
    /// over the remainder of the buffer.
    ///
    /// # Panics
    ///
    /// Panics if the stack isn't large enough to allocate the array, or if the provided function
    /// panics.
    #[track_caller]
    #[inline]
    #[must_use]
    pub fn make_aligned_with<T>(
        &mut self,
        size: usize,
        align: usize,
        f: impl FnMut(usize) -> T,
    ) -> (DynArray<'_, T>, &mut Self) {
        let (taken, remaining) = self.make_aligned_uninit(size, align);
        let (len, ptr) = {
            let taken = init_array_with(f, taken.get_data());
            (taken.len(), taken.as_mut_ptr())
        };
        (
            DynArray {
                ptr: unsafe { NonNull::<T>::new_unchecked(ptr) },
                len,
                __marker: PhantomData,
            },
            remaining,
        )
    }

    /// Returns a new uninitialized [`DynArray`] and a stack over the remainder of the buffer.
    ///
    /// # Panics
    ///
    /// Panics if the stack isn't large enough to allocate the array.
    #[track_caller]
    #[inline]
    #[must_use]
    pub fn make_uninit<T>(&mut self, size: usize) -> (DynArray<'_, MaybeUninit<T>>, &mut Self) {
        self.make_aligned_uninit(size, core::mem::align_of::<T>())
    }

    /// Returns a new [`DynArray`], initialized with the provided function, and a stack over the
    /// remainder of the buffer.
    ///
    /// # Panics
    ///
    /// Panics if the stack isn't large enough to allocate the array, or if the provided function
    /// panics.
    #[track_caller]
    #[inline]
    #[must_use]
    pub fn make_with<T>(
        &mut self,
        size: usize,
        f: impl FnMut(usize) -> T,
    ) -> (DynArray<'_, T>, &mut Self) {
        self.make_aligned_with(size, core::mem::align_of::<T>(), f)
    }

    /// Returns a new aligned [`DynArray`], initialized with the provided iterator, and a stack
    /// over the remainder of the buffer.  
    /// If there isn't enough space for all the iterator items, then the returned array only
    /// contains the first elements that fit into the stack.
    ///
    /// # Panics
    ///
    /// Panics if the provided iterator panics.
    #[track_caller]
    #[inline]
    #[must_use]
    pub fn collect_aligned<I: IntoIterator>(
        &mut self,
        align: usize,
        iter: I,
    ) -> (DynArray<'_, I::Item>, &mut Self) {
        self.collect_aligned_impl(align, iter.into_iter())
    }

    /// Returns a new [`DynArray`], initialized with the provided iterator, and a stack over the
    /// remainder of the buffer.  
    /// If there isn't enough space for all the iterator items, then the returned array only
    /// contains the first elements that fit into the stack.
    ///
    /// # Panics
    ///
    /// Panics if the provided iterator panics.
    #[track_caller]
    #[inline]
    #[must_use]
    pub fn collect<I: IntoIterator>(&mut self, iter: I) -> (DynArray<'_, I::Item>, &mut Self) {
        self.collect_aligned_impl(core::mem::align_of::<I::Item>(), iter.into_iter())
    }

    #[track_caller]
    #[inline]
    fn collect_aligned_impl<I: Iterator>(
        &mut self,
        align: usize,
        iter: I,
    ) -> (DynArray<'_, I::Item>, &mut Self) {
        let sizeof_val = core::mem::size_of::<I::Item>();
        let alignof_val = core::mem::align_of::<I::Item>();
        let align_offset = self.buffer.as_mut_ptr().align_offset(align);

        check_alignment(align, alignof_val, core::any::type_name::<I::Item>());
        check_enough_space_for_align_offset(self.buffer.len(), align, align_offset);

        let buffer = unsafe { self.buffer.get_unchecked_mut(align_offset..) };
        let buffer_len = buffer.len();
        let buffer_ptr = buffer.as_mut_ptr();
        unsafe {
            let len = init_array_with_iter(
                iter,
                core::slice::from_raw_parts_mut(
                    buffer_ptr as *mut MaybeUninit<I::Item>,
                    if sizeof_val == 0 {
                        usize::MAX
                    } else {
                        buffer_len / sizeof_val
                    },
                ),
            );

            let remaining_slice = core::slice::from_raw_parts_mut(
                buffer_ptr.add(len * sizeof_val),
                buffer.len() - len * sizeof_val,
            );
            (
                DynArray {
                    ptr: NonNull::new_unchecked(buffer_ptr as *mut I::Item),
                    len,
                    __marker: PhantomData,
                },
                Self::new(remaining_slice),
            )
        }
    }
}

impl PodStack {
    /// Returns a new [`PodStack`] from the provided memory buffer.
    #[inline]
    pub fn new(buffer: &mut [u8]) -> &mut Self {
        unsafe { &mut *(buffer as *mut [u8] as *mut Self) }
    }

    /// Returns a new [`DynStack`] from the provided memory buffer.
    #[inline]
    pub fn new_any<T: Pod>(buffer: &mut [T]) -> &mut Self {
        let len = buffer.len() * size_of::<T>();
        Self::new(unsafe { core::slice::from_raw_parts_mut(buffer.as_mut_ptr() as *mut _, len) })
    }

    /// Returns `true` if the stack can hold an allocation with the given size and alignment
    /// requirements.
    #[inline]
    #[must_use]
    pub fn can_hold(&self, alloc_req: StackReq) -> bool {
        let align = alloc_req.align_bytes();
        let size = alloc_req.size_bytes();
        let align_offset = self.buffer.as_ptr().align_offset(align);
        let self_size = self.buffer.len();
        (self_size >= align_offset) && (self_size - align_offset >= size)
    }

    /// Returns the number of bytes that this stack can hold.
    #[inline]
    pub fn len_bytes(&self) -> usize {
        self.buffer.len()
    }

    /// Returns a pointer to the stack memory.
    #[inline]
    pub fn as_ptr(&self) -> *const u8 {
        self.buffer.as_ptr() as _
    }

    #[track_caller]
    #[inline]
    fn split_buffer<'out>(
        buffer: &'out mut [u8],
        size: usize,
        align: usize,
        sizeof_val: usize,
        alignof_val: usize,
        type_name: &'static str,
    ) -> (&'out mut [u8], &'out mut [u8]) {
        let len = buffer.len();
        let align_offset = buffer.as_mut_ptr().align_offset(align);

        check_alignment(align, alignof_val, type_name);
        check_enough_space_for_align_offset(len, align, align_offset);
        check_enough_space_for_array(len - align_offset, sizeof_val, size, type_name);

        let buffer = unsafe { buffer.get_unchecked_mut(align_offset..) };
        let len = len - align_offset;

        let begin = buffer.as_mut_ptr();
        let begin_len = size * sizeof_val;
        let mid = unsafe { begin.add(begin_len) };
        let mid_len = len - begin_len;
        unsafe {
            (
                core::slice::from_raw_parts_mut(begin, begin_len),
                core::slice::from_raw_parts_mut(mid, mid_len),
            )
        }
    }

    /// Returns a new aligned and uninitialized slice and a stack over the remainder of the
    /// buffer.
    ///
    /// # Panics
    ///
    /// Panics if the stack isn't large enough to allocate the array.
    #[track_caller]
    #[inline]
    #[must_use]
    pub fn make_aligned_raw<T: Pod>(&mut self, size: usize, align: usize) -> (&mut [T], &mut Self) {
        let (taken, remaining) = Self::split_buffer(
            &mut self.buffer,
            size,
            align,
            core::mem::size_of::<T>(),
            core::mem::align_of::<T>(),
            core::any::type_name::<T>(),
        );

        let taken = unsafe { transmute_pod_slice::<T>(taken, size) };
        (taken, Self::new(remaining))
    }

    /// Returns a new aligned and uninitialized slice and a stack over the remainder of the
    /// buffer.
    ///
    /// # Panics
    ///
    /// Panics if the stack isn't large enough to allocate the array.
    ///
    /// # Safety
    ///
    /// The return value must be dropped if any uninitialized values are written to the bytes by the time the borrow ends.
    pub unsafe fn make_aligned_unpod(
        &mut self,
        size: usize,
        align: usize,
    ) -> (UnpodStack, &mut Self) {
        let (taken, remaining) = Self::split_buffer(&mut self.buffer, size, align, 1, 1, "[Bytes]");
        (
            UnpodStack {
                ptr: NonNull::new_unchecked(taken.as_mut_ptr()),
                len: size,
                __marker: PhantomData,
            },
            Self::new(remaining),
        )
    }

    /// Returns a new aligned slice, initialized with the provided function, and a stack
    /// over the remainder of the buffer.
    ///
    /// # Panics
    ///
    /// Panics if the stack isn't large enough to allocate the array, or if the provided function
    /// panics.
    #[track_caller]
    #[inline]
    #[must_use]
    pub fn make_aligned_with<T: Pod>(
        &mut self,
        size: usize,
        align: usize,
        f: impl FnMut(usize) -> T,
    ) -> (&mut [T], &mut Self) {
        let (taken, remaining) = self.make_aligned_raw(size, align);
        let taken = init_pod_array_with(f, taken);
        (taken, remaining)
    }

    /// Returns a new uninitialized slice and a stack over the remainder of the buffer.
    ///
    /// # Panics
    ///
    /// Panics if the stack isn't large enough to allocate the array.
    #[track_caller]
    #[inline]
    #[must_use]
    pub fn make_raw<T: Pod>(&mut self, size: usize) -> (&mut [T], &mut Self) {
        self.make_aligned_raw(size, core::mem::align_of::<T>())
    }

    /// Returns a new slice, initialized with the provided function, and a stack over the
    /// remainder of the buffer.
    ///
    /// # Panics
    ///
    /// Panics if the stack isn't large enough to allocate the array, or if the provided function
    /// panics.
    #[track_caller]
    #[inline]
    #[must_use]
    pub fn make_with<T: Pod>(
        &mut self,
        size: usize,
        f: impl FnMut(usize) -> T,
    ) -> (&mut [T], &mut Self) {
        self.make_aligned_with(size, core::mem::align_of::<T>(), f)
    }

    /// Returns a new aligned slice, initialized with the provided iterator, and a stack
    /// over the remainder of the buffer.  
    /// If there isn't enough space for all the iterator items, then the returned array only
    /// contains the first elements that fit into the stack.
    ///
    /// # Panics
    ///
    /// Panics if the provided iterator panics.
    #[track_caller]
    #[inline]
    #[must_use]
    pub fn collect_aligned<I: IntoIterator>(
        &mut self,
        align: usize,
        iter: I,
    ) -> (&mut [I::Item], &mut Self)
    where
        I::Item: Pod,
    {
        self.collect_aligned_impl(align, iter.into_iter())
    }

    /// Returns a new slice, initialized with the provided iterator, and a stack over the
    /// remainder of the buffer.  
    /// If there isn't enough space for all the iterator items, then the returned array only
    /// contains the first elements that fit into the stack.
    ///
    /// # Panics
    ///
    /// Panics if the provided iterator panics.
    #[track_caller]
    #[inline]
    #[must_use]
    pub fn collect<I: IntoIterator>(&mut self, iter: I) -> (&mut [I::Item], &mut Self)
    where
        I::Item: Pod,
    {
        self.collect_aligned_impl(core::mem::align_of::<I::Item>(), iter.into_iter())
    }

    #[track_caller]
    #[inline]
    fn collect_aligned_impl<I: Iterator>(
        &mut self,
        align: usize,
        iter: I,
    ) -> (&mut [I::Item], &mut Self)
    where
        I::Item: Pod,
    {
        let sizeof_val = core::mem::size_of::<I::Item>();
        let alignof_val = core::mem::align_of::<I::Item>();
        let align_offset = self.buffer.as_mut_ptr().align_offset(align);

        check_alignment(align, alignof_val, core::any::type_name::<I::Item>());
        check_enough_space_for_align_offset(self.buffer.len(), align, align_offset);

        let buffer = unsafe { self.buffer.get_unchecked_mut(align_offset..) };
        let buffer_len = buffer.len();
        let buffer_ptr = buffer.as_mut_ptr();
        unsafe {
            let len = init_pod_array_with_iter(
                iter,
                core::slice::from_raw_parts_mut(
                    buffer_ptr as *mut I::Item,
                    if sizeof_val == 0 {
                        usize::MAX
                    } else {
                        buffer_len / sizeof_val
                    },
                ),
            );

            let taken = core::slice::from_raw_parts_mut(buffer_ptr as *mut I::Item, len);
            let remaining_slice = core::slice::from_raw_parts_mut(
                buffer_ptr.add(len * sizeof_val),
                buffer_len - len * sizeof_val,
            );
            (taken, Self::new(remaining_slice))
        }
    }
}

#[cfg(all(feature = "nightly", test))]
mod tests_nightly {
    use super::*;

    use alloc::alloc::Global;

    #[test]
    fn empty() {
        let mut buf = MemBuffer::new(Global, StackReq::new::<i32>(0));
        let stack = DynStack::new(&mut buf);
        let (_arr0, _stack) = stack.make_with::<i32>(0, |i| i as i32);
    }

    #[test]
    #[should_panic]
    fn empty_overflow() {
        let mut buf = MemBuffer::new(Global, StackReq::new::<i32>(0));
        let stack = DynStack::new(&mut buf);
        let (_arr0, _stack) = stack.make_with::<i32>(1, |i| i as i32);
    }

    #[test]
    fn empty_collect() {
        let mut buf = MemBuffer::new(Global, StackReq::new::<i32>(0));
        let stack = DynStack::new(&mut buf);
        let (_arr0, _stack) = stack.collect(0..0);
    }

    #[test]
    fn empty_collect_overflow() {
        let mut buf = MemBuffer::new(Global, StackReq::new::<i32>(0));
        let stack = DynStack::new(&mut buf);
        let (arr0, _stack) = stack.collect(0..1);
        assert!(arr0.is_empty());
    }

    #[test]
    #[should_panic]
    fn overflow() {
        let mut buf = MemBuffer::new(Global, StackReq::new::<i32>(1));
        let stack = DynStack::new(&mut buf);
        let (_arr0, _stack) = stack.make_with::<i32>(2, |i| i as i32);
    }

    #[test]
    fn collect_overflow() {
        let mut buf = MemBuffer::new(Global, StackReq::new::<i32>(1));
        let stack = DynStack::new(&mut buf);
        let (arr0, _stack) = stack.collect(1..3);
        assert_eq!(arr0.len(), 1);
        assert_eq!(arr0[0], 1)
    }
}

#[cfg(test)]
mod dyn_stack_tests {
    use super::*;

    #[test]
    fn empty() {
        let mut buf = GlobalMemBuffer::new(StackReq::new::<i32>(0));
        let stack = DynStack::new(&mut buf);
        let (_arr0, _stack) = stack.make_with::<i32>(0, |i| i as i32);
    }

    #[test]
    #[should_panic]
    fn empty_overflow() {
        let mut buf = GlobalMemBuffer::new(StackReq::new::<i32>(0));
        let stack = DynStack::new(&mut buf);
        let (_arr0, _stack) = stack.make_with::<i32>(1, |i| i as i32);
    }

    #[test]
    fn empty_collect() {
        let mut buf = GlobalMemBuffer::new(StackReq::new::<i32>(0));
        let stack = DynStack::new(&mut buf);
        let (_arr0, _stack) = stack.collect(0..0);
    }

    #[test]
    fn empty_collect_overflow() {
        let mut buf = GlobalMemBuffer::new(StackReq::new::<i32>(0));
        let stack = DynStack::new(&mut buf);
        let (arr0, _stack) = stack.collect(0..1);
        assert!(arr0.is_empty());
    }

    #[test]
    #[should_panic]
    fn overflow() {
        let mut buf = GlobalMemBuffer::new(StackReq::new::<i32>(1));
        let stack = DynStack::new(&mut buf);
        let (_arr0, _stack) = stack.make_with::<i32>(2, |i| i as i32);
    }

    #[test]
    fn collect_overflow() {
        let mut buf = GlobalMemBuffer::new(StackReq::new::<i32>(1));
        let stack = DynStack::new(&mut buf);
        let (arr0, _stack) = stack.collect(1..3);
        assert_eq!(arr0.len(), 1);
        assert_eq!(arr0[0], 1)
    }

    #[test]
    fn basic_nested() {
        let mut buf = GlobalMemBuffer::new(StackReq::new::<i32>(6));

        let stack = DynStack::new(&mut buf);
        assert!(stack.can_hold(StackReq::new::<i32>(6)));
        assert!(!stack.can_hold(StackReq::new::<i32>(7)));

        let (arr0, stack) = stack.make_with::<i32>(3, |i| i as i32);
        assert_eq!(arr0[0], 0);
        assert_eq!(arr0[1], 1);
        assert_eq!(arr0[2], 2);

        let (arr1, _) = stack.make_with::<i32>(3, |i| i as i32 + 3);

        // first values are untouched
        assert_eq!(arr0[0], 0);
        assert_eq!(arr0[1], 1);
        assert_eq!(arr0[2], 2);

        assert_eq!(arr1[0], 3);
        assert_eq!(arr1[1], 4);
        assert_eq!(arr1[2], 5);
    }

    #[test]
    fn basic_disjoint() {
        let mut buf = GlobalMemBuffer::new(StackReq::new::<i32>(3));

        let stack = DynStack::new(&mut buf);

        {
            let (arr0, _) = stack.make_with::<i32>(3, |i| i as i32);
            assert_eq!(arr0[0], 0);
            assert_eq!(arr0[1], 1);
            assert_eq!(arr0[2], 2);
        }
        {
            let (arr1, _) = stack.make_with::<i32>(3, |i| i as i32 + 3);

            assert_eq!(arr1[0], 3);
            assert_eq!(arr1[1], 4);
            assert_eq!(arr1[2], 5);
        }
    }

    #[test]
    fn basic_nested_collect() {
        let mut buf = GlobalMemBuffer::new(StackReq::new::<i32>(6));
        let stack = DynStack::new(&mut buf);

        let (arr0, stack) = stack.collect(0..3_i32);
        assert_eq!(arr0[0], 0);
        assert_eq!(arr0[1], 1);
        assert_eq!(arr0[2], 2);

        let (arr1, _) = stack.collect(3..6_i32);

        // first values are untouched
        assert_eq!(arr0[0], 0);
        assert_eq!(arr0[1], 1);
        assert_eq!(arr0[2], 2);

        assert_eq!(arr1[0], 3);
        assert_eq!(arr1[1], 4);
        assert_eq!(arr1[2], 5);
    }

    #[test]
    fn basic_disjoint_collect() {
        let mut buf = GlobalMemBuffer::new(StackReq::new::<i32>(3));

        let stack = DynStack::new(&mut buf);

        {
            let (arr0, _) = stack.collect(0..3_i32);
            assert_eq!(arr0[0], 0);
            assert_eq!(arr0[1], 1);
            assert_eq!(arr0[2], 2);
        }
        {
            let (arr1, _) = stack.collect(3..6_i32);

            assert_eq!(arr1[0], 3);
            assert_eq!(arr1[1], 4);
            assert_eq!(arr1[2], 5);
        }
    }

    #[test]
    fn drop_nested() {
        use core::sync::atomic::{AtomicI32, Ordering};
        static DROP_COUNT: AtomicI32 = AtomicI32::new(0);

        struct CountedDrop;
        impl Drop for CountedDrop {
            fn drop(&mut self) {
                DROP_COUNT.fetch_add(1, Ordering::SeqCst);
            }
        }

        let mut buf = GlobalMemBuffer::new(StackReq::new::<CountedDrop>(6));
        let stack = DynStack::new(&mut buf);

        let stack = {
            let (_arr, stack) = stack.make_with(3, |_| CountedDrop);
            stack
        };
        assert_eq!(DROP_COUNT.load(Ordering::SeqCst), 3);
        let _stack = {
            let (_arr, stack) = stack.make_with(4, |_| CountedDrop);
            stack
        };
        assert_eq!(DROP_COUNT.load(Ordering::SeqCst), 7);
    }

    #[test]
    fn drop_disjoint() {
        use core::sync::atomic::{AtomicI32, Ordering};
        static DROP_COUNT: AtomicI32 = AtomicI32::new(0);

        struct CountedDrop;
        impl Drop for CountedDrop {
            fn drop(&mut self) {
                DROP_COUNT.fetch_add(1, Ordering::SeqCst);
            }
        }

        let mut buf = GlobalMemBuffer::new(StackReq::new::<CountedDrop>(6));
        let stack = DynStack::new(&mut buf);

        {
            let _ = stack.make_with(3, |_| CountedDrop);
            assert_eq!(DROP_COUNT.load(Ordering::SeqCst), 3);
        }

        {
            let _ = stack.make_with(4, |_| CountedDrop);
            assert_eq!(DROP_COUNT.load(Ordering::SeqCst), 7);
        }
    }
}

#[cfg(test)]
mod pod_stack_tests {
    use super::*;

    #[test]
    fn empty() {
        let mut buf = GlobalPodBuffer::new(StackReq::new::<i32>(0));
        let stack = PodStack::new(&mut buf);
        let (_arr0, _stack) = stack.make_with::<i32>(0, |i| i as i32);
    }

    #[test]
    #[should_panic]
    fn empty_overflow() {
        let mut buf = GlobalPodBuffer::new(StackReq::new::<i32>(0));
        let stack = PodStack::new(&mut buf);
        let (_arr0, _stack) = stack.make_with::<i32>(1, |i| i as i32);
    }

    #[test]
    fn empty_collect() {
        let mut buf = GlobalPodBuffer::new(StackReq::new::<i32>(0));
        let stack = PodStack::new(&mut buf);
        let (_arr0, _stack) = stack.collect(0..0);
    }

    #[test]
    fn empty_collect_overflow() {
        let mut buf = GlobalPodBuffer::new(StackReq::new::<i32>(0));
        let stack = PodStack::new(&mut buf);
        let (arr0, _stack) = stack.collect(0..1);
        assert!(arr0.is_empty());
    }

    #[test]
    #[should_panic]
    fn overflow() {
        let mut buf = GlobalPodBuffer::new(StackReq::new::<i32>(1));
        let stack = PodStack::new(&mut buf);
        let (_arr0, _stack) = stack.make_with::<i32>(2, |i| i as i32);
    }

    #[test]
    fn collect_overflow() {
        let mut buf = GlobalPodBuffer::new(StackReq::new::<i32>(1));
        let stack = PodStack::new(&mut buf);
        let (arr0, _stack) = stack.collect(1..3);
        assert_eq!(arr0.len(), 1);
        assert_eq!(arr0[0], 1)
    }

    #[test]
    fn basic_nested() {
        let mut buf = GlobalPodBuffer::new(StackReq::new::<i32>(6));

        let stack = PodStack::new(&mut buf);
        assert!(stack.can_hold(StackReq::new::<i32>(6)));
        assert!(!stack.can_hold(StackReq::new::<i32>(7)));

        let (arr0, stack) = stack.make_with::<i32>(3, |i| i as i32);
        assert_eq!(arr0[0], 0);
        assert_eq!(arr0[1], 1);
        assert_eq!(arr0[2], 2);

        let (arr1, _) = stack.make_with::<i32>(3, |i| i as i32 + 3);

        // first values are untouched
        assert_eq!(arr0[0], 0);
        assert_eq!(arr0[1], 1);
        assert_eq!(arr0[2], 2);

        assert_eq!(arr1[0], 3);
        assert_eq!(arr1[1], 4);
        assert_eq!(arr1[2], 5);
    }

    #[test]
    fn basic_disjoint() {
        let mut buf = GlobalPodBuffer::new(StackReq::new::<i32>(3));

        let stack = PodStack::new(&mut buf);

        {
            let (arr0, _) = stack.make_with::<i32>(3, |i| i as i32);
            assert_eq!(arr0[0], 0);
            assert_eq!(arr0[1], 1);
            assert_eq!(arr0[2], 2);
        }
        {
            let (arr1, _) = stack.make_with::<i32>(3, |i| i as i32 + 3);

            assert_eq!(arr1[0], 3);
            assert_eq!(arr1[1], 4);
            assert_eq!(arr1[2], 5);
        }
    }

    #[test]
    fn basic_nested_collect() {
        let mut buf = GlobalPodBuffer::new(StackReq::new::<i32>(6));
        let stack = PodStack::new(&mut buf);

        let (arr0, stack) = stack.collect(0..3_i32);
        assert_eq!(arr0[0], 0);
        assert_eq!(arr0[1], 1);
        assert_eq!(arr0[2], 2);

        let (arr1, _) = stack.collect(3..6_i32);

        // first values are untouched
        assert_eq!(arr0[0], 0);
        assert_eq!(arr0[1], 1);
        assert_eq!(arr0[2], 2);

        assert_eq!(arr1[0], 3);
        assert_eq!(arr1[1], 4);
        assert_eq!(arr1[2], 5);
    }

    #[test]
    fn basic_disjoint_collect() {
        let mut buf = GlobalPodBuffer::new(StackReq::new::<i32>(3));

        let stack = PodStack::new(&mut buf);

        {
            let (arr0, _) = stack.collect(0..3_i32);
            assert_eq!(arr0[0], 0);
            assert_eq!(arr0[1], 1);
            assert_eq!(arr0[2], 2);
        }
        {
            let (arr1, _) = stack.collect(3..6_i32);

            assert_eq!(arr1[0], 3);
            assert_eq!(arr1[1], 4);
            assert_eq!(arr1[2], 5);
        }
    }

    #[test]
    fn make_raw() {
        let mut buf = GlobalPodBuffer::new(StackReq::new::<i32>(3));

        let stack = PodStack::new(&mut buf);

        {
            let (arr0, _) = stack.make_raw::<i32>(3);
            assert_eq!(arr0[0], 0);
            assert_eq!(arr0[1], 0);
            assert_eq!(arr0[2], 0);
        }
        {
            let (arr0, _) = stack.collect(0..3_i32);
            assert_eq!(arr0[0], 0);
            assert_eq!(arr0[1], 1);
            assert_eq!(arr0[2], 2);
        }
        {
            let (arr1, _) = stack.make_raw::<i32>(3);

            assert_eq!(arr1[0], 0);
            assert_eq!(arr1[1], 1);
            assert_eq!(arr1[2], 2);
        }
    }
}