frame_mem_utils 0.2.5

a few stack oriented utileties designed with unsafe in mind
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
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
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
//this module has a lot of raw pointers betterbe explicit
#![allow(clippy::needless_lifetimes)]

use crate::refs::RefBox;
use core::fmt::Write;
use core::marker::PhantomData;
use core::mem::MaybeUninit;
use core::ops::Index;
use core::ops::IndexMut;
use core::ptr;
use core::slice;
use core::slice::from_raw_parts_mut;

/// A helper function to create an uninitialized array for backing storage.
///
/// This is a convenience function to avoid unsafe code in user code.
pub fn make_storage<T, const N: usize>() -> [MaybeUninit<T>; N] {
    // SAFETY: MaybeUninit is safe to use uninitialized.
    unsafe { MaybeUninit::uninit().assume_init() }
}

/// A checkpoint for the stack, allowing to rewind to a previous state.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct StackCheckPoint<T>(*mut T);

/*──────────────────── stack type ───────────────────────*/
/// A down-growing, fixed-capacity LIFO stack backed by a slice.
///
/// `DownStack` manages a region of memory as a stack that grows from a high memory
/// address towards a lower one. This is in contrast to typical stack implementations
/// that grow upwards. It's designed for scenarios where you need a stack but want to
/// avoid heap allocations, such as in embedded systems or performance-critical code.
///
/// The internal pointers are not dereferenced during operations, which allows for
/// creating safe aliases to its memory, enabling advanced, unsafe patterns if needed.
///
/// # Layout (high address at the top):
///
/// ```text
///                    above ┐
//////   [ x x x x ...free... ][ ...dead space ...]
///     ▲     ▲
///     │     └─ head
///     └──────── end (low addr)
/// ```
///
/// # Example
///
/// ```rust
/// use frame_mem_utils::stack::{DownStack, make_storage};
/// use core::mem::MaybeUninit;
///
/// let mut storage: [MaybeUninit<i32>; 4] = make_storage();
/// let mut stack = DownStack::from_slice(&mut storage);
///
/// stack.push(10).unwrap();
/// stack.push(20).unwrap();
///
/// assert_eq!(stack.len(), 2);
/// assert_eq!(stack.pop(), Some(20));
/// assert_eq!(stack.pop(), Some(10));
/// assert!(stack.is_empty());
/// ```
pub struct DownStack<'mem, T> {
    //the fact rust is missing const makes this make less effishent code than i would like...
    above: *mut T, // one-past the *highest* live element
    head: *mut T,  // next pop / current top (lowest live element)
    end: *mut T,   // lowest address in the backing buffer
    _ph: PhantomData<&'mem mut [MaybeUninit<T>]>,
}

unsafe impl<'m, T: Send> Send for DownStack<'m, T> {}
unsafe impl<'m, T: Sync> Sync for DownStack<'m, T> {}

impl<T> Drop for DownStack<'_, T> {
    fn drop(&mut self) {
        while let Some(_) = self.pop() {}
    }
}

/*──────────────────── constructors ────────────────────*/
impl<'mem, T> DownStack<'mem, T> {
    /// Creates an empty `DownStack` from a given slice of `MaybeUninit<T>`.
    ///
    /// The stack will use this slice as its backing storage.
    #[inline]
    pub const fn from_slice(buf: &'mem mut [MaybeUninit<T>]) -> Self {
        let end = buf.as_mut_ptr() as *mut T; // low addr
        let above = unsafe { end.add(buf.len()) }; // one-past high addr
        Self {
            above,
            head: above,
            end,
            _ph: PhantomData,
        }
    }

    /// Creates an empty `DownStack` from a raw pointer to a slice of `MaybeUninit<T>`.
    ///
    /// # Safety
    ///
    /// The caller must ensure that the pointer is valid for the lifetime `'mem`.
    #[inline]
    pub const unsafe fn from_slice_raw(buf: *mut [MaybeUninit<T>]) -> Self {
        let end = buf as *mut T; // low addr
        let above = unsafe { end.add((buf).len()) }; // one-past high addr
        Self {
            above,
            head: above,
            end,
            _ph: PhantomData,
        }
    }

    /// Creates a `DownStack` from a slice of already initialized data.
    ///
    /// The stack will be full and all elements will be considered live.
    #[inline]
    pub const fn new_full(buf: &'mem mut [T]) -> Self
    where
        T: Copy,
    {
        let end = buf.as_mut_ptr(); // low addr
        let above = unsafe { end.add(buf.len()) }; // one-past high addr
        Self {
            above,
            head: end,
            end,
            _ph: PhantomData,
        }
    }

    /// Converts the `DownStack` back into the backing slice.
    #[inline]
    pub fn to_slice(self) -> &'mem mut [MaybeUninit<T>] {
        unsafe {
            let len = self.above.offset_from(self.end) as usize;
            let end = self.end as *mut _;
            core::mem::forget(self);
            from_raw_parts_mut(end, len)
        }
    }

    /// Clones the content of this stack to another `DownStack`.
    ///
    /// The other stack will be cleared before the copy.
    pub fn set_other<'b>(&self, other: &mut DownStack<'b, T>) -> Result<(), usize>
    where
        T: Clone,
    {
        other.flush(other.len());
        for (i, x) in self.peek_all().iter().rev().enumerate() {
            other.push(x.clone()).map_err(|_| i)?;
        }
        Ok(())
    }

    /*──────────────────── invariants ───────────────────────*/
    /// Returns the number of live elements in the stack.
    #[inline]
    pub fn write_index(&self) -> usize {
        unsafe { self.above.offset_from(self.head) as usize }
    }

    /// Returns the number of available slots in the stack.
    #[inline]
    pub fn room_left(&self) -> usize {
        unsafe { self.head.offset_from(self.end) as usize }
    }

    /// **Unchecked**: set depth directly (0 ≤ `idx` ≤ capacity).
    /// # Safety
    /// - the index must be in the stacks range
    /// - this now allows bad reads but non would be executed automatically
    #[inline]
    pub unsafe fn set_write_index(&mut self, idx: usize) {
        unsafe {
            self.head = self.above.sub(idx);
        }
    }

    /// Returns the number of elements in the stack.
    #[inline]
    pub fn len(&self) -> usize {
        self.write_index()
    }

    /// Returns `true` if the stack contains no elements.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Returns a raw pointer to the end of the stack's buffer.
    #[inline(always)]
    pub fn get_end(&self) -> *mut T {
        self.end
    }

    ///this is used to manually set the capacity of the stack
    ///# Safety
    /// obviously this is very unsafe and all the underlying memory must be valid
    /// further it needs to be the same allocation
    #[inline(always)]
    pub unsafe fn set_end(&mut self, end: *mut T) {
        self.end = end;
    }

    /// Returns a raw pointer to the head of the stack.
    #[inline(always)]
    pub fn get_head(&self) -> *mut T {
        self.head
    }

    /// # Safety
    /// if head is set outside the allocation (not including 1 above) subsequent ops would be UB
    /// if head is set below its current possition then reads/writes to these elements from things like pop are UB    
    /// if head is set above its current position skiped items wont be dropped
    #[inline(always)]
    pub unsafe fn set_head(&mut self, head: *mut T) {
        self.head = head
    }

    /// Returns a raw pointer to 1 above the stack's buffer.
    #[inline(always)]
    pub fn get_above(&self) -> *mut T {
        self.above
    }

    ///this is used to manually remove/extend the logical bottom of the stack (phisical top)
    ///# Safety
    /// obviously this is very unsafe and all the underlying memory must be valid
    /// further it needs to be the same allocation
    #[inline(always)]
    pub unsafe fn set_above(&mut self, above: *mut T) {
        self.above = above;
    }

    /*──────────────────── push / pop ───────────────────────*/
    /// Pushes a value onto the top of the stack.
    ///
    /// Returns `Err(v)` if the stack is full.
    #[inline]
    pub fn push(&mut self, v: T) -> Result<(), T> {
        if self.room_left() == 0 {
            return Err(v);
        }
        unsafe {
            self.head = self.head.sub(1);
            self.head.write(v);
        }
        Ok(())
    }

    /// Pops a value from the top of the stack.
    ///
    /// Returns `None` if the stack is empty.
    #[inline]
    pub fn pop(&mut self) -> Option<T> {
        if self.write_index() == 0 {
            return None;
        }
        unsafe {
            let v = self.head.read();
            self.head = self.head.add(1);
            Some(v)
        }
    }

    /// Pushes an array of `N` elements onto the stack.
    ///
    /// Returns `Err(arr)` if there is not enough room.
    #[inline]
    pub fn push_n<const N: usize>(&mut self, arr: [T; N]) -> Result<(), [T; N]> {
        if self.room_left() < N {
            return Err(arr);
        }
        unsafe {
            self.head = self.head.sub(N);
            (self.head as *mut [T; N]).write(arr);
        }
        Ok(())
    }

    /// Pops an array of `N` elements from the stack.
    ///
    /// Returns `None` if there are not enough elements.
    #[inline]
    pub fn pop_n<const N: usize>(&mut self) -> Option<[T; N]> {
        if self.write_index() < N {
            return None;
        }
        unsafe {
            let out = (self.head as *mut [T; N]).read();
            self.head = self.head.add(N);
            Some(out)
        }
    }

    /// Pushes a slice of elements onto the stack.
    ///
    /// Returns `None` if there is not enough room.
    #[inline]
    pub fn push_slice(&mut self, src: &[T]) -> Option<()>
    where
        T: Clone,
    {
        if self.room_left() < src.len() {
            return None;
        }
        unsafe {
            self.head = self.head.sub(src.len());
            let dst = slice::from_raw_parts_mut(self.head, src.len());
            dst.clone_from_slice(src);
        }
        Some(())
    }

    /// Pops `n` elements from the stack and returns them as a `RefBox<[T]>`.
    ///
    /// Returns `None` if there are not enough elements.
    #[inline]
    pub fn pop_many<'b>(&'b mut self, n: usize) -> Option<RefBox<'b, [T]>> {
        if self.write_index() < n {
            return None;
        }
        unsafe {
            let p = self.head;
            self.head = self.head.add(n);
            Some(RefBox::new(slice::from_raw_parts_mut(p, n)))
        }
    }

    /*──────────────────── allocs ───────────────────────*/
    /// Removes `len` elements from the top of the stack, calling their destructors.
    #[inline]
    pub fn flush(&mut self, len: usize) -> Option<()> {
        if self.write_index() < len {
            return None;
        }
        unsafe {
            //force a drop of these elements
            for x in from_raw_parts_mut(self.head, len) {
                ptr::read(x);
            }

            self.head = self.head.add(len);
            Some(())
        }
    }

    /// Removes `len` elements from the top of the stack without calling their destructors.
    #[inline]
    pub fn free(&mut self, len: usize) -> Option<()> {
        if self.write_index() < len {
            return None;
        }
        unsafe {
            self.head = self.head.add(len);
            Some(())
        }
    }

    /// Allocates `len` uninitialized elements on the stack.
    ///
    /// # Safety
    /// Calling this puts invalid memory on the stack.
    /// Using any read operations on it is UB.
    /// This includes flush; however, free is fine.
    #[inline]
    pub unsafe fn alloc(&mut self, len: usize) -> Option<()> {
        if self.room_left() < len {
            return None;
        }
        self.head = unsafe { self.head.sub(len) };
        Some(())
    }
    /*──────────────────── checkpoint ───────────────────────*/

    /// Creates a checkpoint of the current stack state.
    #[inline]
    pub fn check_point(&self) -> StackCheckPoint<T> {
        StackCheckPoint(self.head)
    }

    /// Rewinds the stack to a previously created checkpoint.
    ///
    /// # Safety
    /// The caller must ensure that no pointers to the freed memory exist.
    #[inline]
    pub unsafe fn goto_checkpoint(&mut self, check_point: StackCheckPoint<T>) {
        self.head = check_point.0;
    }
    /*──────────────────── peek helpers ─────────────────────*/
    /// Returns a reference to the top element of the stack.
    #[inline]
    pub fn peek<'b>(&'b self) -> Option<&'b T> {
        self.peek_n::<1>().map(|a| &a[0])
    }

    /// Returns a reference to the top `N` elements of the stack.
    #[inline]
    pub fn peek_n<'b, const N: usize>(&'b self) -> Option<&'b [T; N]> {
        if self.write_index() < N {
            None
        } else {
            unsafe { Some(&*(self.head as *const [T; N])) }
        }
    }

    /// Returns a slice of the top `n` elements of the stack.
    #[inline]
    pub fn peek_many<'b>(&'b self, n: usize) -> Option<&'b [T]> {
        if self.write_index() < n {
            None
        } else {
            unsafe { Some(slice::from_raw_parts(self.head, n)) }
        }
    }

    /// Returns a slice containing all elements in the stack, from top to bottom.
    #[inline]
    pub fn peek_all<'b>(&'b self) -> &'b [T] {
        unsafe { slice::from_raw_parts(self.head, self.write_index()) }
    }

    /// Returns a mutable reference to the top element of the stack.
    #[inline]
    pub fn peek_mut<'b>(&'b mut self) -> Option<&'b mut T> {
        self.peek_n_mut::<1>().map(|a| &mut a[0])
    }

    /// Returns a mutable reference to the top `N` elements of the stack.
    #[inline]
    pub fn peek_n_mut<'b, const N: usize>(&'b mut self) -> Option<&'b mut [T; N]> {
        if self.write_index() < N {
            None
        } else {
            unsafe { Some(&mut *(self.head as *mut [T; N])) }
        }
    }

    /// Returns a mutable slice of the top `n` elements of the stack.
    #[inline]
    pub fn peek_many_mut<'b>(&'b mut self, n: usize) -> Option<&'b mut [T]> {
        if self.write_index() < n {
            None
        } else {
            unsafe { Some(slice::from_raw_parts_mut(self.head, n)) }
        }
    }

    /// Returns a mutable slice of all elements in the stack.
    #[inline]
    pub fn peek_all_mut<'b>(&'b mut self) -> &'b mut [T] {
        unsafe { slice::from_raw_parts_mut(self.head, self.write_index()) }
    }

    /// Returns a mutable reference to the element at `n` from the top of the stack.
    #[inline]
    pub fn spot<'b>(&'b mut self, n: usize) -> Option<&'b mut T> {
        if self.write_index() <= n {
            None
        } else {
            unsafe { Some(&mut *self.head.add(n)) }
        }
    }

    /// Returns a raw pointer to the element at `n` from the top of the stack.
    #[inline]
    pub fn spot_raw(&self, n: usize) -> Option<*mut T> {
        if self.write_index() <= n {
            None
        } else {
            unsafe { Some(self.head.add(n)) }
        }
    }

    /*──────────────────── complex handeling ─────────────────────*/
    /// Drop `count` items located `skip` elements below the top.
    pub fn drop_inside(&mut self, skip: usize, count: usize) -> Option<()> {
        if skip + count > self.write_index() {
            return None;
        }
        unsafe {
            let p = self.head.add(skip);
            // Explicitly drop the region [p, p+count)
            for x in from_raw_parts_mut(p, count) {
                ptr::read(x);
            }
            // Move the upper part down
            ptr::copy(self.head, self.head.add(count), skip);
            self.head = self.head.add(count);
        }
        Some(())
    }

    /// Splits the stack into a slice of its elements and an empty `DownStack`.
    /// (live slice on the left, empty stack on the right)
    #[inline]
    pub fn split<'b>(&'b mut self) -> (&'b mut [T], DownStack<'b, T>) {
        let live = self.write_index();
        let left = unsafe { slice::from_raw_parts_mut(self.head, live) };
        let right = DownStack {
            above: self.head,
            head: self.head,
            end: self.end,
            _ph: PhantomData,
        };
        (left, right)
    }

    /// Consumes the stack and returns a slice of its elements and an empty `DownStack`.
    #[inline]
    pub fn split_consume(self) -> (&'mem mut [T], DownStack<'mem, T>) {
        let live = self.write_index();
        let left = unsafe { slice::from_raw_parts_mut(self.head, live) };
        let right = DownStack {
            above: self.head,
            head: self.head,
            end: self.end,
            _ph: PhantomData,
        };
        (left, right)
    }

    /// Raw pointer to live slice + empty right-hand stack (no borrow).
    #[inline]
    pub fn split_raw(&mut self) -> (*mut T, DownStack<'_, T>) {
        let ptr_live = self.head;
        let right = DownStack {
            above: self.head,
            head: self.head,
            end: self.end,
            _ph: PhantomData,
        };
        (ptr_live, right)
    }
}
/*──────────────────── iterator ─────────────────────────*/
impl<T> Iterator for DownStack<'_, T> {
    type Item = T;
    fn next(&mut self) -> Option<T> {
        self.pop()
    }
}

impl<T> Index<usize> for DownStack<'_, T> {
    type Output = T;
    fn index<'a>(&'a self, id: usize) -> &'a T {
        if self.len() <= id {
            panic!("out of bound index");
        }
        unsafe { &*self.above.sub(1 + id) }
    }
}

impl<T> IndexMut<usize> for DownStack<'_, T> {
    fn index_mut<'a>(&'a mut self, id: usize) -> &'a mut T {
        if self.len() <= id {
            panic!("out of bound index");
        }
        unsafe { &mut *self.above.sub(1 + id) }
    }
}

#[test]
fn test_index_and_index_mut_basic() {
    let mut storage = make_storage::<u32, 4>();
    let mut stack = DownStack::from_slice(&mut storage);

    for v in 1..=3 {
        stack.push(v).unwrap();
    } // 1 oldest … 3 newest

    // Read through Index
    assert_eq!(stack[0], 1);
    assert_eq!(stack[1], 2);
    assert_eq!(stack[2], 3);

    // Mutate the middle element
    stack[1] = 42;
    // Pop order is still newest-first
    assert_eq!(stack.pop(), Some(3));
    assert_eq!(stack.pop(), Some(42));
    assert_eq!(stack.pop(), Some(1));
    assert!(stack.pop().is_none());
}

#[test]
fn test_lifo_order() {
    let mut storage = make_storage::<&'static str, 3>();
    let mut stack = DownStack::from_slice(&mut storage);

    stack.push("first").unwrap();
    stack.push("second").unwrap();
    stack.push("third").unwrap();

    assert_eq!(stack.pop(), Some("third"));
    assert_eq!(stack.peek(), Some("second").as_ref());
    assert_eq!(stack.pop(), Some("second"));
    assert_eq!(stack.pop(), Some("first"));
    assert_eq!(stack.pop(), None);
}

#[test]
fn test_peek_n() {
    let mut storage = make_storage::<u32, 5>();
    let mut stack = DownStack::from_slice(&mut storage);

    for v in 1..=5 {
        stack.push(v).unwrap();
    }

    // Top-first order: 5 4 3
    assert_eq!(stack.peek_n::<3>().unwrap(), &[5, 4, 3]);

    assert!(stack.peek_n::<6>().is_none());
    assert!(stack.peek_n::<5>().is_some());

    assert_eq!(stack.pop(), Some(5));
    assert!(stack.peek_n::<3>().is_some());

    assert_eq!(stack.pop(), Some(4));
    assert!(stack.peek_n::<4>().is_none());
}

#[test]
fn test_peek_many() {
    let mut storage = make_storage::<u32, 6>();
    let mut stack = DownStack::from_slice(&mut storage);

    for i in 1..=5 {
        stack.push(i).unwrap();
    }

    assert_eq!(stack.peek_many(3).unwrap(), &[5, 4, 3]);
    assert!(stack.peek_many(6).is_none());
    assert_eq!(stack.peek_many(5).unwrap(), &[5, 4, 3, 2, 1]);

    stack.pop();
    stack.pop();
    assert!(stack.peek_many(4).is_none());
    assert_eq!(stack.peek_many(3).unwrap(), &[3, 2, 1]);
}

#[test]
fn test_push_n_and_pop_n_success() {
    let mut storage = make_storage::<u32, 6>();
    let mut stack = DownStack::from_slice(&mut storage);

    let arr1 = [10, 20];
    let arr2 = [30, 40, 50];

    stack.push_n(arr1).unwrap();
    stack.push_n(arr2).unwrap();

    assert_eq!(stack.pop_n::<3>().unwrap(), [30, 40, 50]);
    assert_eq!(stack.pop_n::<2>().unwrap(), [10, 20]);
    assert!(stack.pop_n::<1>().is_none());
}

#[test]
fn test_push_n_overflow() {
    let mut storage = make_storage::<u32, 4>();
    let mut stack = DownStack::from_slice(&mut storage);

    let ok = [1, 2];
    let fail = [3, 4, 5];

    assert!(stack.push_n(ok).is_ok());
    assert_eq!(stack.push_n(fail), Err(fail));
}

#[test]
fn test_pop_n_underflow() {
    let mut storage = make_storage::<u32, 3>();
    let mut stack = DownStack::from_slice(&mut storage);

    stack.push(1).unwrap();
    assert!(stack.pop_n::<2>().is_none());
    assert!(stack.pop_n::<1>().is_some());
    assert!(stack.pop_n::<1>().is_none());
}

#[test]
fn test_mixed_push_pop_n() {
    let mut storage = make_storage::<u32, 6>();
    let mut stack = DownStack::from_slice(&mut storage);

    stack.push_n([1, 2, 3]).unwrap();
    stack.push(4).unwrap();
    stack.push_n([5, 6]).unwrap();

    assert_eq!(stack.pop_n::<2>(), Some([5, 6]));
    assert_eq!(stack.pop(), Some(4));
    assert_eq!(stack.pop_n::<3>(), Some([1, 2, 3]));
    assert!(stack.pop().is_none());
}

#[test]
fn test_slice_conversion_basic() {
    let mut storage = make_storage::<u32, 4>();
    let mut stack = DownStack::from_slice(&mut storage);

    assert_eq!(stack.pop(), None);

    stack.push(10).unwrap();
    stack.push(20).unwrap();

    let idx = stack.write_index();
    assert_eq!(idx, 2);

    let slice = stack.to_slice();
    let mut stack = DownStack::from_slice(slice);
    unsafe { stack.set_write_index(idx) };

    assert_eq!(stack.pop(), Some(20));
    assert_eq!(stack.pop(), Some(10));
    assert_eq!(stack.pop(), None);
}

#[test]
fn test_split_stack() {
    let mut storage = make_storage::<u32, 6>();
    let mut original = DownStack::from_slice(&mut storage);

    original.push(1).unwrap();
    original.push(2).unwrap();
    original.push(3).unwrap();

    let (left, mut right) = original.split();

    assert_eq!(left, [3, 2, 1]); // top-first
    assert_eq!(right.pop(), None);

    right.push(10).unwrap();
    assert_eq!(right.pop(), Some(10));
}

#[test]
fn test_push_slice_success_and_error() {
    let mut storage = make_storage::<u32, 5>();
    let mut stack = DownStack::from_slice(&mut storage);

    let input1 = [1, 2, 3];
    assert_eq!(stack.push_slice(&input1), Some(()));
    assert_eq!(stack.peek_many(3), Some(&[1, 2, 3][..]));

    assert_eq!(stack.push_slice(&[4, 5, 6]), None);
    stack.push_slice(&[4, 5]).unwrap();

    assert_eq!(stack.write_index(), 5);
    assert!(stack.push_slice(&[99]).is_none());

    stack.pop().unwrap();
    assert!(stack.push_slice(&[99, 66]).is_none());

    stack.pop().unwrap();
    assert!(stack.push_slice(&[99, 66, 11]).is_none());
}

#[test]
fn test_weird_write_error() {
    let mut storage = make_storage::<i64, 6>();
    let mut stack = DownStack::from_slice(&mut storage);

    stack.push_slice(&[2]).unwrap();
    stack.push_n([1]).unwrap();

    stack.push_slice(&[2, 3]).unwrap();
    stack.push_n([2]).unwrap();

    assert!(stack.push_slice(&[1, 2, 3]).is_none());
}

#[test]
fn test_full_usage() {
    let mut data = [10, 20, 30, 40, 50, 60];
    let mut stack = DownStack::new_full(&mut data);

    assert_eq!(stack.write_index(), 6);
    assert_eq!(stack.room_left(), 0);

    // Top item (down-growing stack) is 10
    assert_eq!(stack.peek(), Some(&10));

    assert_eq!(stack.spot(2), Some(&mut 30));

    // Drop (40, 50)
    stack.drop_inside(3, 2).unwrap();
    assert_eq!(stack.room_left(), 2);

    // Pop remaining items in LIFO order
    assert_eq!(stack.pop(), Some(10));
    assert_eq!(stack.pop(), Some(20));
    assert_eq!(stack.room_left(), 4);

    assert_eq!(stack.pop(), Some(30));
    assert_eq!(stack.pop(), Some(60));
    assert_eq!(stack.room_left(), 6);

    assert_eq!(stack.pop(), None);

    stack.push(77).unwrap();
    assert_eq!(stack.peek(), Some(&77));
    stack.push(77).unwrap();

    stack.pop_many(4).ok_or(()).unwrap_err();
    stack.pop_many(2).unwrap();
}

#[test]
fn test_drop_in() {
    let mut data = [10, 20, 30, 40, 50, 60];
    let mut stack = DownStack::new_full(&mut data);

    assert_eq!(stack.write_index(), 6);
    assert_eq!(stack.room_left(), 0);

    // Top item (down-growing stack) is 10
    assert_eq!(stack.peek(), Some(&10));

    // Drop (30, 40, 50)
    stack.drop_inside(2, 3).unwrap();
    assert_eq!(stack.room_left(), 3);

    // Pop remaining items in LIFO order
    assert_eq!(stack.pop(), Some(10));
    assert_eq!(stack.pop(), Some(20));
    assert_eq!(stack.room_left(), 5);

    assert_eq!(stack.pop(), Some(60));
    assert_eq!(stack.room_left(), 6);

    assert_eq!(stack.pop(), None);

    stack.push(77).unwrap();
    assert_eq!(stack.peek(), Some(&77));
    stack.push(77).unwrap();

    stack.pop_many(4).ok_or(()).unwrap_err();
    stack.pop_many(2).unwrap();
}

#[test]
fn test_drop_inside_skip_zero_should_remove_top_items() {
    // stack top-to-bottom: 10 20 30 40
    let mut data = [10, 20, 30, 40];
    let mut stack = DownStack::new_full(&mut data);

    // Ask to drop the top two (10,20)
    stack.drop_inside(0, 2).unwrap();

    // ── Expected ─────────────────────────
    // write_index()            == 2
    // subsequent pops: 30 then 40
    // ── Actual with current impl ────────
    // write_index()            is still 4
    // pops start with 10       ← not removed!

    assert_eq!(stack.write_index(), 2, "top items were not removed");
    assert_eq!(stack.pop(), Some(30));
    assert_eq!(stack.pop(), Some(40));
    assert_eq!(stack.pop(), None);
}

#[test]
fn test_zero_capacity_stack() {
    use core::mem::MaybeUninit;

    let mut storage: [MaybeUninit<u32>; 0] = [];
    let mut stack = DownStack::from_slice(&mut storage);

    assert_eq!(stack.write_index(), 0);
    assert_eq!(stack.room_left(), 0);

    assert!(stack.pop().is_none());
    assert_eq!(stack.push(123), Err(123));

    let (slice, mut stack2) = stack.split();

    assert_eq!(slice.len(), 0);
    assert_eq!(stack2.write_index(), 0);
    assert_eq!(stack2.room_left(), 0);

    assert!(stack2.pop().is_none());
    assert_eq!(stack2.push(123), Err(123));
}

#[test]
fn test_stacref_set_other_copies_all() {
    let mut buf1 = make_storage::<i32, 6>();
    let mut buf2 = make_storage::<i32, 4>();

    let mut src = DownStack::from_slice(&mut buf1);
    let mut dst = DownStack::from_slice(&mut buf2);

    for v in 1..=3 {
        src.push(v).unwrap();
    }

    dst.push(23).unwrap(); //make sure we clear dst

    src.set_other(&mut dst).unwrap();

    assert_eq!(dst.pop(), Some(3));
    assert_eq!(dst.pop(), Some(2));
    assert_eq!(dst.pop(), Some(1));
    assert!(dst.is_empty());

    assert_eq!(src.pop(), Some(3));
    assert_eq!(src.pop(), Some(2));
    assert_eq!(src.pop(), Some(1));
    assert!(src.is_empty());
}

/*──────────────────── StackVec ────────────────────────────────*/

/// A `Vec`-like implementation on a fixed-size buffer that grows upwards.
///
/// `StackVec` provides a familiar `Vec`-like interface for managing a contiguous
/// array, but it operates on a pre-allocated slice of memory instead of the heap.
/// It is a LIFO stack that grows from a low memory address towards a higher one.
///
/// This is useful for creating dynamic-length collections in environments where
/// heap allocation is not available or desirable.
///
/// # Layout (high address at the top):
///
/// ```text
///   base (low addr)
/////////   [ item1, item2, ... itemN, ... free space ... ]
//////                             └─ len points here (one-past-end)
/// ```
///
/// # Example
///
/// ```rust
/// use frame_mem_utils::stack::{StackVec, make_storage};
/// use core::mem::MaybeUninit;
///
/// let mut buffer: [MaybeUninit<u8>; 16] = make_storage();
/// let mut vec = StackVec::from_slice(&mut buffer);
///
/// vec.push(10u8).unwrap();
/// vec.push_slice(&[20, 30]).unwrap();
///
/// assert_eq!(vec.len(), 3);
/// assert_eq!(vec.peek_all(), &[10, 20, 30]);
/// assert_eq!(vec.pop(), Some(30));
/// ```
pub struct StackVec<'mem, T> {
    base: *mut T,
    len: usize,
    capacity: usize,
    _ph: PhantomData<&'mem mut [MaybeUninit<T>]>,
}

unsafe impl<'m, T: Send> Send for StackVec<'m, T> {}
unsafe impl<'m, T: Sync> Sync for StackVec<'m, T> {}

/*────────── constructors ──────────*/

impl<'mem, T> StackVec<'mem, T> {
    /// Creates an empty `StackVec` from a given slice of `MaybeUninit<T>`.
    ///
    /// The vector will use this slice as its backing storage.
    pub const fn from_slice(buf: &'mem mut [MaybeUninit<T>]) -> Self {
        Self {
            base: buf.as_mut_ptr() as *mut T,
            len: 0,
            capacity: buf.len(),
            _ph: PhantomData,
        }
    }

    /// Creates a `StackVec` from a slice of already initialized data.
    ///
    /// The vector will be full and all elements will be considered live.
    pub const fn new_full(buf: &'mem mut [T]) -> Self
    where
        T: Copy,
    {
        Self {
            base: buf.as_mut_ptr(),
            len: buf.len(),
            capacity: buf.len(),
            _ph: PhantomData,
        }
    }

    /// Converts the `StackVec` back into the backing slice.
    pub fn to_slice(self) -> &'mem mut [MaybeUninit<T>] {
        unsafe { slice::from_raw_parts_mut(self.base as *mut _, self.capacity) }
    }

    /// Clones the content of this vector to another `StackVec`.
    ///
    /// The other vector will be cleared before the copy.
    pub fn set_other<'b>(&self, other: &mut StackVec<'b, T>) -> Result<(), usize>
    where
        T: Clone,
    {
        other.flush(other.len());
        for (i, x) in self.peek_all().iter().enumerate() {
            other.push(x.clone()).map_err(|_| i)?;
        }
        Ok(())
    }
}

/*────────── invariants & meta ──────────*/

impl<T> StackVec<'_, T> {
    /// Returns the number of elements in the vector.
    #[inline]
    pub fn len(&self) -> usize {
        self.len
    }

    /// this is a weird mix of alloc and free it is mainly used for checkpoints
    /// # Safety
    /// 1. the length must be in bounds
    /// 2. if elements are alloced same as alloc
    pub unsafe fn set_len(&mut self, len: usize) {
        self.len = len;
    }

    pub fn capacity(&self) -> usize {
        self.capacity
    }

    /// Returns a raw pointer to the base of the vector's buffer.
    #[inline(always)]
    pub fn get_base(&self) -> *mut T {
        self.base
    }

    /// Returns `true` if the vector contains no elements.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.len == 0
    }
    /// Returns the number of additional elements the vector can hold.
    #[inline]
    pub fn room_left(&self) -> usize {
        self.capacity - self.len
    }
}

/*────────── push / pop ──────────*/

impl<'me, T> StackVec<'me, T> {
    /// Appends an element to the end of the vector.
    ///
    /// Returns `Err(v)` if the vector is full.
    #[inline]
    pub fn push(&mut self, v: T) -> Result<(), T> {
        if self.len == self.capacity {
            return Err(v);
        }
        unsafe {
            self.base.add(self.len).write(v);
        }
        self.len += 1;
        Ok(())
    }

    /// Removes the last element from the vector and returns it.
    ///
    /// Returns `None` if the vector is empty.
    #[inline]
    pub fn pop(&mut self) -> Option<T> {
        if self.len == 0 {
            return None;
        }
        self.len -= 1;
        unsafe { Some(self.base.add(self.len).read()) }
    }

    /*──── bulk helpers ────*/
    /// Appends an array of `N` elements to the end of the vector.
    ///
    /// Returns `Err(arr)` if there is not enough room.
    #[inline]
    pub fn push_n<const N: usize>(&mut self, arr: [T; N]) -> Result<(), [T; N]> {
        if self.room_left() < N {
            return Err(arr);
        }
        unsafe {
            (self.base.add(self.len) as *mut [T; N]).write(arr);
        }
        self.len += N;
        Ok(())
    }

    /// Pops an array of `N` elements from the end of the vector.
    ///
    /// Returns `None` if there are not enough elements.
    #[inline]
    pub fn pop_n<const N: usize>(&mut self) -> Option<[T; N]> {
        if self.len < N {
            return None;
        }
        self.len -= N;
        unsafe { Some((self.base.add(self.len) as *mut [T; N]).read()) }
    }

    /// Pops `n` elements from the vector and returns them as a `RefBox<[T]>`.
    ///
    /// Returns `None` if there are not enough elements.
    #[inline]
    pub fn pop_many<'b>(&'b mut self, n: usize) -> Option<RefBox<'b, [T]>> {
        if self.len < n {
            None
        } else {
            unsafe {
                let base = self.base.add(self.len - n);
                self.len -= n;
                Some(RefBox::new(slice::from_raw_parts_mut(base, n)))
            }
        }
    }

    /// Appends a slice of elements to the end of the vector.
    ///
    /// Returns `None` if there is not enough room.
    #[inline]
    pub fn push_slice(&mut self, src: &[T]) -> Option<()>
    where
        T: Clone,
    {
        if self.room_left() < src.len() {
            return None;
        }
        unsafe {
            let dst = slice::from_raw_parts_mut(self.base.add(self.len), src.len());
            dst.clone_from_slice(src);
        }
        self.len += src.len();
        Some(())
    }

    /*────────── mem managment ──────────*/

    /// reserves `len` uninitialised slots (UB to read them).
    /// # Safety
    /// 1. the elements must eventually be inilized before a drop
    /// 2. no pops or peeks of these slots may happen
    #[inline]
    pub unsafe fn alloc(&mut self, len: usize) -> Option<()> {
        if self.room_left() < len {
            return None;
        }
        self.len += len;
        Some(())
    }

    /// Drops `len` values from the top (destructors *run*).
    pub fn flush(&mut self, len: usize) -> Option<()> {
        if self.len < len {
            return None;
        }
        unsafe {
            for i in 0..len {
                ptr::read(self.base.add(self.len - 1 - i));
            }
        }
        self.len -= len;
        Some(())
    }

    /// Discards `len` values from the top (**no** destructors).
    #[inline]
    pub fn free(&mut self, len: usize) -> Option<()> {
        if self.len < len {
            return None;
        }
        self.len -= len;
        Some(())
    }

    /*────────── peeks & spots ──────────*/

    /// Returns a reference to the last element of the vector.
    #[inline]
    pub fn peek(&self) -> Option<&T> {
        if self.len == 0 {
            None
        } else {
            unsafe { Some(&*self.base.add(self.len - 1)) }
        }
    }

    /// Returns a slice of the last `n` elements of the vector.
    #[inline]
    pub fn peek_many(&self, n: usize) -> Option<&[T]> {
        if self.len < n {
            None
        } else {
            unsafe {
                // contiguous bottom→top order: oldest … newest
                Some(slice::from_raw_parts(self.base.add(self.len - n), n))
            }
        }
    }

    /// Returns a slice containing all elements in the vector.
    #[inline]
    pub fn peek_all<'b>(&'b self) -> &'b [T] {
        unsafe { slice::from_raw_parts(self.base, self.len) }
    }

    /// Returns a mutable reference to the last element of the vector.
    #[inline]
    pub fn peek_mut(&mut self) -> Option<&mut T> {
        if self.len == 0 {
            None
        } else {
            unsafe { Some(&mut *self.base.add(self.len - 1)) }
        }
    }

    /// Returns a mutable slice of the last `n` elements of the vector.
    #[inline]
    pub fn peek_many_mut(&mut self, n: usize) -> Option<&mut [T]> {
        if self.len < n {
            None
        } else {
            unsafe {
                // contiguous bottom→top order: oldest … newest
                Some(slice::from_raw_parts_mut(self.base.add(self.len - n), n))
            }
        }
    }

    /// Returns a mutable slice of all elements in the vector.
    #[inline]
    pub fn peek_all_mut<'b>(&'b mut self) -> &'b mut [T] {
        unsafe { slice::from_raw_parts_mut(self.base, self.len) }
    }

    /// Raw pointer to the current top (no lifetime).
    #[inline]
    pub fn peek_raw(&self) -> Option<*mut T> {
        if self.len == 0 {
            None
        } else {
            Some(unsafe { self.base.add(self.len - 1) })
        }
    }

    /// Mutable ref to the *n*-th value below the top (0 == top).
    #[inline]
    pub fn spot(&mut self, n: usize) -> Option<&mut T> {
        if n >= self.len {
            return None;
        }
        unsafe { Some(&mut *self.base.add(self.len - 1 - n)) }
    }

    /// Raw pointer variant (no lifetime).
    #[inline]
    pub fn spot_raw(&self, n: usize) -> Option<*mut T> {
        if n >= self.len {
            return None;
        }
        Some(unsafe { self.base.add(self.len - 1 - n) })
    }

    /// Mutable ref to the *n*-th value from the start (start==0).
    #[inline]
    pub fn get(&self, id: usize) -> Option<&T> {
        if self.len <= id {
            return None;
        }
        unsafe { Some(&*self.base.add(id)) }
    }

    /// Mutable ref to the *n*-th value from the start (start==0).
    #[inline]
    pub fn get_mut(&mut self, id: usize) -> Option<&mut T> {
        if self.len <= id {
            return None;
        }
        unsafe { Some(&mut *self.base.add(id)) }
    }

    /// Pointer to the *n*-th value from the start (start==0).
    #[inline]
    pub fn get_raw(&self, id: usize) -> Option<*mut T> {
        if self.len <= id {
            return None;
        }
        unsafe { Some(self.base.add(id)) }
    }

    /*────────── split ──────────*/

    /// Splits the vector into a slice of its elements and an empty `StackVec`.
    /// (live slice on the left, empty StackVec on the right)
    #[inline]
    pub fn split<'b>(&'b mut self) -> (&'b mut [T], StackVec<'b, T>) {
        let live = self.len;
        let left = unsafe { slice::from_raw_parts_mut(self.base, live) };

        let right = StackVec {
            base: unsafe { self.base.add(live) },
            len: 0,
            capacity: self.capacity - live,
            _ph: PhantomData,
        };
        (left, right)
    }

    /// Consumes the vector and returns a slice of its elements and an empty `StackVec`.
    #[inline]
    pub fn split_consume(self) -> (&'me mut [T], StackVec<'me, T>) {
        let live = self.len;
        let left = unsafe { slice::from_raw_parts_mut(self.base, live) };

        let right = StackVec {
            base: unsafe { self.base.add(live) },
            len: 0,
            capacity: self.capacity - live,
            _ph: PhantomData,
        };
        (left, right)
    }

    /// Raw pointer to live slice + empty right-hand `StackVec` (no borrow).
    #[inline]
    pub fn split_raw<'b>(&'b mut self) -> (*mut T, StackVec<'b, T>) {
        let live = self.len;

        let right = StackVec {
            base: unsafe { self.base.add(live) },
            len: 0,
            capacity: self.capacity - live,
            _ph: PhantomData,
        };
        (self.base, right)
    }
}

/*────────── Index / IndexMut ──────────*/

impl<T> Index<usize> for StackVec<'_, T> {
    type Output = T;
    fn index(&self, id: usize) -> &T {
        if id >= self.len {
            panic!("index out of bounds");
        }
        unsafe { &*self.base.add(id) }
    }
}

impl<T> IndexMut<usize> for StackVec<'_, T> {
    fn index_mut(&mut self, id: usize) -> &mut T {
        if id >= self.len {
            panic!("index out of bounds");
        }
        unsafe { &mut *self.base.add(id) }
    }
}

/*────────── Drop ──────────*/

impl<T> Drop for StackVec<'_, T> {
    fn drop(&mut self) {
        unsafe {
            for i in 0..self.len {
                ptr::drop_in_place(self.base.add(i));
            }
        }
    }
}

/*──────────────────── write ───────────────────────────*/

impl Write for StackVec<'_, u8> {
    fn write_str(&mut self, s: &str) -> Result<(), core::fmt::Error> {
        self.push_slice(s.as_bytes()).ok_or(core::fmt::Error)
    }
}

/*──────────────────── tests ───────────────────────────*/

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

    #[test]
    fn two_slice_concat_and_peek() {
        let mut buf = make_storage::<u32, 6>();
        let mut st = StackVec::from_slice(&mut buf);

        st.push_slice(&[10, 11]).unwrap(); // bottom
        st.push_slice(&[20, 21]).unwrap(); // now on top

        // Bottom→top order in memory: 10 11 20 21
        assert_eq!(st.peek_many(4).unwrap(), &[10, 11, 20, 21]);

        // Top value via peek / peek_raw
        assert_eq!(st.peek(), Some(&21));
        unsafe {
            assert_eq!(*st.peek_raw().unwrap(), 21);
        }
    }

    #[test]
    fn alloc_flush_free_cycle() {
        let mut buf = make_storage::<u8, 8>();
        let mut st = StackVec::from_slice(&mut buf);

        // Reserve space for 3 bytes (uninitialised)
        unsafe {
            st.alloc(3).unwrap();
        }
        assert_eq!(st.len(), 3);

        // Overwrite the raw slots properly
        for i in 0..3 {
            unsafe { *st.spot_raw(i).unwrap() = (i as u8) + 1 }
        }

        // Push two fully-initialised items
        st.push_slice(&[100, 101]).unwrap();
        assert_eq!(st.len(), 5);

        // Flush (drop) the two live items
        st.flush(2).unwrap();
        assert_eq!(st.len(), 3);

        // Discard the three raw bytes without drop
        st.free(3).unwrap();
        assert!(st.is_empty());
    }

    #[test]
    fn spot_and_mutate() {
        let mut buf = make_storage::<i32, 4>();
        let mut st = StackVec::from_slice(&mut buf);

        st.push_n([1, 2, 3, 4]).unwrap(); // top == 4
        *st.spot(1).unwrap() = 99; // change the 3

        assert_eq!(st.pop(), Some(4));
        assert_eq!(st.pop(), Some(99));
    }

    #[test]
    fn stackvec_set_other_copies_all() {
        let mut buf1 = make_storage::<i32, 4>();
        let mut buf2 = make_storage::<i32, 6>();

        let mut src = StackVec::from_slice(&mut buf1);
        let mut dst = StackVec::from_slice(&mut buf2);

        for v in 1..=3 {
            src.push(v).unwrap();
        }

        dst.push(23).unwrap(); //make sure we clear dst

        src.set_other(&mut dst).unwrap();

        assert_eq!(dst.pop(), Some(3));
        assert_eq!(dst.pop(), Some(2));
        assert_eq!(dst.pop(), Some(1));
        assert!(dst.is_empty());

        assert_eq!(src.pop(), Some(3));
        assert_eq!(src.pop(), Some(2));
        assert_eq!(src.pop(), Some(1));
        assert!(src.is_empty());
    }

    #[test]
    fn split_stackvec() {
        let mut storage = make_storage::<u32, 6>();
        let mut original = StackVec::from_slice(&mut storage);

        original.push(1).unwrap();
        original.push(2).unwrap();
        original.push(3).unwrap();

        let (left, mut right) = original.split();

        assert_eq!(left, [1, 2, 3]); // bottom→top order in memory
        assert_eq!(right.pop(), None);

        right.push(10).unwrap();
        assert_eq!(right.pop(), Some(10));
    }
}