stoolap 0.4.0

High-performance embedded SQL database with MVCC, time-travel queries, and full ACID compliance
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
// Copyright 2025 Stoolap Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! CompactVec - A 16-byte vector optimized for Row storage
//!
//! Standard Vec<T> is 24 bytes (ptr + len + cap as usize).
//! CompactVec<T> is 16 bytes (ptr + packed len/cap as u32).
//!
//! Benefits:
//! - 33% smaller than Vec (16 vs 24 bytes)
//! - O(1) len() access (unlike ThinVec which requires dereference)
//! - Faster moves due to smaller size
//! - Supports up to 4 billion elements (u32::MAX)

use std::alloc::{alloc, dealloc, realloc, Layout};
use std::fmt;
use std::iter::FromIterator;
use std::mem::{self, ManuallyDrop};
use std::ops::{Deref, DerefMut, Index, IndexMut};
use std::ptr::{self, NonNull};
use std::slice;

/// A compact vector that uses 16 bytes instead of Vec's 24 bytes.
/// Stores length and capacity as u32 (max 4 billion elements).
pub struct CompactVec<T> {
    ptr: NonNull<T>,
    /// Packed length (low 32 bits) and capacity (high 32 bits)
    len_cap: u64,
}

// SAFETY: CompactVec has the same thread-safety as Vec - it can be sent
// between threads if T can be sent, as it owns its data exclusively.
unsafe impl<T: Send> Send for CompactVec<T> {}
// SAFETY: CompactVec can be shared between threads if T can be shared,
// as it only provides shared access to its elements through &self methods.
unsafe impl<T: Sync> Sync for CompactVec<T> {}

impl<T> CompactVec<T> {
    /// Pack length and capacity into a single u64
    #[inline(always)]
    const fn pack(len: u32, cap: u32) -> u64 {
        (len as u64) | ((cap as u64) << 32)
    }

    /// Unpack length from len_cap
    #[inline(always)]
    const fn unpack_len(len_cap: u64) -> u32 {
        len_cap as u32
    }

    /// Unpack capacity from len_cap
    #[inline(always)]
    const fn unpack_cap(len_cap: u64) -> u32 {
        (len_cap >> 32) as u32
    }

    /// Creates an empty CompactVec.
    #[inline]
    pub const fn new() -> Self {
        Self {
            ptr: NonNull::dangling(),
            len_cap: 0,
        }
    }

    /// Creates a CompactVec with the specified capacity.
    #[inline]
    pub fn with_capacity(capacity: usize) -> Self {
        if capacity == 0 {
            return Self::new();
        }

        let cap = capacity.min(u32::MAX as usize) as u32;

        // Allocate memory
        let layout = Layout::array::<T>(cap as usize).unwrap();
        // SAFETY: Layout is valid (non-zero size, proper alignment for T).
        let ptr = unsafe { alloc(layout) as *mut T };

        if ptr.is_null() {
            std::alloc::handle_alloc_error(layout);
        }

        Self {
            // SAFETY: We just checked that ptr is not null above.
            ptr: unsafe { NonNull::new_unchecked(ptr) },
            len_cap: Self::pack(0, cap),
        }
    }

    /// Returns the number of elements in the vector.
    #[inline(always)]
    pub const fn len(&self) -> usize {
        Self::unpack_len(self.len_cap) as usize
    }

    /// Returns true if the vector contains no elements.
    #[inline(always)]
    pub const fn is_empty(&self) -> bool {
        Self::unpack_len(self.len_cap) == 0
    }

    /// Returns the capacity of the vector.
    #[inline(always)]
    pub const fn capacity(&self) -> usize {
        Self::unpack_cap(self.len_cap) as usize
    }

    /// Set the length.
    ///
    /// # Safety
    ///
    /// - `new_len` must be less than or equal to `capacity()`
    /// - The elements at `old_len..new_len` must be initialized (if growing)
    /// - The elements at `new_len..old_len` will NOT be dropped (if shrinking)
    #[inline(always)]
    pub unsafe fn set_len(&mut self, new_len: usize) {
        let cap = Self::unpack_cap(self.len_cap);
        self.len_cap = Self::pack(new_len as u32, cap);
    }

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

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

    /// Appends an element to the back of the vector.
    #[inline]
    pub fn push(&mut self, value: T) {
        // Unpack once instead of calling len() and capacity() separately
        let len = Self::unpack_len(self.len_cap) as usize;
        let cap = Self::unpack_cap(self.len_cap) as usize;

        if len == cap {
            self.grow();
        }

        // SAFETY: After grow(), we have capacity > len, so ptr.add(len) is valid.
        // The memory at that location is uninitialized but allocated for T.
        unsafe {
            ptr::write(self.ptr.as_ptr().add(len), value);
            self.set_len(len + 1);
        }
    }

    /// Removes the last element from the vector and returns it.
    #[inline]
    pub fn pop(&mut self) -> Option<T> {
        let len = self.len();
        if len == 0 {
            return None;
        }

        // SAFETY: len > 0, so len - 1 is a valid index. The element at that
        // position is initialized. After read, we decrement len so the moved
        // element won't be dropped again.
        unsafe {
            self.set_len(len - 1);
            Some(ptr::read(self.ptr.as_ptr().add(len - 1)))
        }
    }

    /// Clears the vector, removing all values.
    #[inline]
    pub fn clear(&mut self) {
        let len = self.len();
        if len == 0 {
            return;
        }

        // SAFETY: All elements [0..len] are initialized. After dropping them,
        // we set len to 0 so they won't be dropped again.
        unsafe {
            ptr::drop_in_place(ptr::slice_from_raw_parts_mut(self.ptr.as_ptr(), len));
            self.set_len(0);
        }
    }

    /// Reserves capacity for at least `additional` more elements.
    #[inline]
    pub fn reserve(&mut self, additional: usize) {
        // Unpack once
        let len = Self::unpack_len(self.len_cap) as usize;
        let cap = Self::unpack_cap(self.len_cap) as usize;
        let required = len.saturating_add(additional);

        if required > cap {
            // Calculate new capacity directly, avoid second capacity() call
            let new_cap = required.min(u32::MAX as usize);
            self.realloc(new_cap);
        }
    }

    /// Grow the vector (double capacity or start at 4)
    fn grow(&mut self) {
        let cap = self.capacity();
        let new_cap = if cap == 0 {
            4
        } else {
            cap.saturating_mul(2).min(u32::MAX as usize)
        };

        self.realloc(new_cap);
    }

    /// Reallocate to new capacity
    fn realloc(&mut self, new_cap: usize) {
        let len = self.len();
        let old_cap = self.capacity();
        let new_cap = new_cap as u32;

        if mem::size_of::<T>() == 0 {
            // ZST - no actual allocation needed
            self.len_cap = Self::pack(len as u32, new_cap);
            return;
        }

        let new_layout = Layout::array::<T>(new_cap as usize).unwrap();

        let new_ptr = if old_cap == 0 {
            // Fresh allocation
            // SAFETY: new_layout is valid (non-zero size, proper alignment).
            unsafe { alloc(new_layout) as *mut T }
        } else {
            // Realloc existing
            let old_layout = Layout::array::<T>(old_cap).unwrap();
            // SAFETY: self.ptr was allocated with old_layout, and new_layout.size()
            // is valid. The allocator will copy existing data to new location.
            unsafe {
                realloc(self.ptr.as_ptr() as *mut u8, old_layout, new_layout.size()) as *mut T
            }
        };

        if new_ptr.is_null() {
            std::alloc::handle_alloc_error(new_layout);
        }

        // SAFETY: We just checked that new_ptr is not null above.
        self.ptr = unsafe { NonNull::new_unchecked(new_ptr) };
        self.len_cap = Self::pack(len as u32, new_cap);
    }

    /// Truncates the vector, keeping the first `len` elements.
    #[inline]
    pub fn truncate(&mut self, len: usize) {
        let current_len = self.len();
        if len >= current_len {
            return;
        }

        // SAFETY: Elements [len..current_len] are initialized. After dropping,
        // we set length to `len` so they won't be dropped again.
        unsafe {
            let remaining = current_len - len;
            ptr::drop_in_place(ptr::slice_from_raw_parts_mut(
                self.ptr.as_ptr().add(len),
                remaining,
            ));
            self.set_len(len);
        }
    }

    /// Removes and returns the element at position `index`, shifting all elements after it.
    #[inline]
    pub fn remove(&mut self, index: usize) -> T {
        let len = self.len();
        assert!(index < len, "removal index out of bounds");

        // SAFETY: index < len is asserted above, so the element is valid.
        // After reading, we shift remaining elements and decrement length.
        unsafe {
            let ptr = self.ptr.as_ptr().add(index);
            let value = ptr::read(ptr);

            // Shift elements down
            ptr::copy(ptr.add(1), ptr, len - index - 1);
            self.set_len(len - 1);

            value
        }
    }

    /// Removes an element from the vector and returns it, replacing it with the last element.
    #[inline]
    pub fn swap_remove(&mut self, index: usize) -> T {
        let len = self.len();
        assert!(index < len, "swap_remove index out of bounds");

        // SAFETY: index < len is asserted above. We read the element at index,
        // then copy the last element to fill the gap, and decrement length.
        unsafe {
            let ptr = self.ptr.as_ptr();
            let value = ptr::read(ptr.add(index));

            // Copy last element to the removed position (if not removing last)
            if index < len - 1 {
                ptr::copy_nonoverlapping(ptr.add(len - 1), ptr.add(index), 1);
            }

            self.set_len(len - 1);
            value
        }
    }

    /// Inserts an element at position `index`, shifting all elements after it to the right.
    ///
    /// # Panics
    /// Panics if `index > len`.
    #[inline]
    pub fn insert(&mut self, index: usize, element: T) {
        let len = self.len();
        assert!(index <= len, "insertion index out of bounds");

        // Ensure we have capacity for one more element
        if len == self.capacity() {
            self.grow();
        }

        // SAFETY: index <= len is asserted above. After grow(), capacity > len.
        // We shift elements right to make room, then write the new element.
        unsafe {
            let ptr = self.ptr.as_ptr().add(index);

            // Shift elements to the right
            if index < len {
                ptr::copy(ptr, ptr.add(1), len - index);
            }

            // Write the new element
            ptr::write(ptr, element);
            self.set_len(len + 1);
        }
    }

    /// Retains only the elements specified by the predicate.
    ///
    /// Removes all elements `e` such that `f(&e)` returns `false`.
    /// This method operates in place, visiting each element exactly once in the
    /// original order, and preserves the order of the retained elements.
    #[inline]
    pub fn retain<F>(&mut self, mut f: F)
    where
        F: FnMut(&T) -> bool,
    {
        let len = self.len();
        let ptr = self.ptr.as_ptr();
        let mut write_idx = 0;

        for read_idx in 0..len {
            // SAFETY: read_idx < len, so the element is valid and initialized.
            // We either keep it (move to write_idx) or drop it.
            unsafe {
                let elem = &*ptr.add(read_idx);
                if f(elem) {
                    // Keep this element
                    if write_idx != read_idx {
                        // Move element from read_idx to write_idx
                        ptr::copy_nonoverlapping(ptr.add(read_idx), ptr.add(write_idx), 1);
                    }
                    write_idx += 1;
                } else {
                    // Drop this element
                    ptr::drop_in_place(ptr.add(read_idx));
                }
            }
        }

        // SAFETY: write_idx <= len, and exactly write_idx elements are initialized.
        unsafe {
            self.set_len(write_idx);
        }
    }

    /// Extends the vector with elements from an iterator.
    #[inline]
    pub fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
        let iter = iter.into_iter();
        let (lower, upper) = iter.size_hint();

        // If exact size is known, write directly with bounds protection
        if Some(lower) == upper && lower > 0 {
            self.reserve(lower);
            let original_len = self.len();
            let cap = self.capacity();

            // RAII guard for panic safety: if iter.next() panics, we set the length
            // to the number of successfully written elements so Drop can clean up.
            struct ExtendGuard<'a, T> {
                vec: &'a mut CompactVec<T>,
                written_count: usize,
            }

            impl<T> Drop for ExtendGuard<'_, T> {
                fn drop(&mut self) {
                    // SAFETY: written_count tracks how many elements were successfully
                    // written before a panic. Setting len to this value ensures Drop
                    // will clean up exactly those elements. This is only reached on panic
                    // (normal path uses mem::forget).
                    unsafe {
                        self.vec.set_len(self.written_count);
                    }
                }
            }

            let mut guard = ExtendGuard {
                vec: self,
                written_count: original_len,
            };

            // SAFETY:
            // - reserve(lower) guarantees capacity for `lower` more elements
            // - We add bounds check (len < cap) to protect against malicious iterators
            //   that yield more elements than size_hint promised
            // - If iter.next() panics, guard drops and sets len, ensuring cleanup
            unsafe {
                let ptr = guard.vec.ptr.as_ptr();
                for item in iter {
                    if guard.written_count >= cap {
                        // Iterator lied about size - fall back to safe push
                        // Guard already has correct written_count, push updates len
                        let count = guard.written_count;
                        guard.vec.set_len(count);
                        guard.vec.push(item);
                        guard.written_count = guard.vec.len();
                        continue;
                    }
                    ptr::write(ptr.add(guard.written_count), item);
                    guard.written_count += 1;
                }
            }

            // Success! Set final length and forget the guard
            let final_len = guard.written_count;
            mem::forget(guard);
            // SAFETY: final_len equals the number of elements written by the loop.
            // reserve() ensured capacity, and the loop wrote exactly final_len elements.
            unsafe {
                self.set_len(final_len);
            }
        } else {
            // Fallback for unknown size - push is already panic-safe
            self.reserve(lower);
            for item in iter {
                self.push(item);
            }
        }
    }

    /// Extend from a slice, cloning each element.
    ///
    /// This is faster than `extend(slice.iter().cloned())` because it avoids
    /// the `Cloned` iterator adapter overhead. Profile shows the adapter adds
    /// 7x overhead vs actual clone cost.
    ///
    /// OPTIMIZATION: Uses pointer increment instead of indexed access to reduce
    /// per-element overhead from enumerate() + ptr.add(i).
    #[inline]
    pub fn extend_clone(&mut self, slice: &[T])
    where
        T: Clone,
    {
        let slice_len = slice.len();
        if slice_len == 0 {
            return;
        }
        self.reserve(slice_len);
        let original_len = self.len();

        // RAII guard for panic safety: if clone() panics, we set the length
        // to the number of successfully cloned elements so Drop can clean up.
        struct ExtendCloneGuard<'a, T> {
            vec: &'a mut CompactVec<T>,
            written_count: usize,
        }

        impl<T> Drop for ExtendCloneGuard<'_, T> {
            fn drop(&mut self) {
                // SAFETY: written_count tracks how many elements were successfully
                // cloned before a panic. Setting len to this value ensures Drop
                // will clean up exactly those elements. This is only reached on panic
                // (normal path uses mem::forget).
                unsafe {
                    self.vec.set_len(self.written_count);
                }
            }
        }

        let mut guard = ExtendCloneGuard {
            vec: self,
            written_count: original_len,
        };

        // SAFETY: reserve() guarantees capacity for slice_len more elements
        // If clone() panics, guard drops and sets len, ensuring cleanup
        unsafe {
            let mut dst = guard.vec.ptr.as_ptr().add(original_len);
            for item in slice {
                ptr::write(dst, item.clone());
                guard.written_count += 1;
                dst = dst.add(1);
            }
        }

        // Success! Set final length and forget the guard
        let final_len = guard.written_count;
        mem::forget(guard);
        // SAFETY: final_len equals original_len + slice_len. reserve() ensured capacity,
        // and the loop successfully cloned all slice_len elements.
        unsafe {
            self.set_len(final_len);
        }
    }

    /// Extends the vector by copying elements from a slice (optimized for Copy types).
    ///
    /// This uses `ptr::copy_nonoverlapping` (memcpy) which is significantly faster
    /// than iterating and cloning for simple types like i64.
    #[inline]
    pub fn extend_copy(&mut self, slice: &[T])
    where
        T: Copy,
    {
        let slice_len = slice.len();
        if slice_len == 0 {
            return;
        }
        self.reserve(slice_len);
        let len = self.len();

        // SAFETY:
        // - reserve() guarantees capacity
        // - T is Copy, so no panic safety issues during copy
        // - ptrs are valid
        unsafe {
            let dst = self.ptr.as_ptr().add(len);
            ptr::copy_nonoverlapping(slice.as_ptr(), dst, slice_len);
            self.set_len(len + slice_len);
        }
    }

    /// Returns a slice containing all elements.
    #[inline(always)]
    pub fn as_slice(&self) -> &[T] {
        // SAFETY: ptr is valid and aligned, and len() elements are initialized.
        unsafe { slice::from_raw_parts(self.ptr.as_ptr(), self.len()) }
    }

    /// Returns a mutable slice containing all elements.
    #[inline(always)]
    pub fn as_mut_slice(&mut self) -> &mut [T] {
        // SAFETY: ptr is valid and aligned, len elements are initialized
        unsafe { &mut *ptr::slice_from_raw_parts_mut(self.ptr.as_ptr(), self.len()) }
    }

    /// Returns an iterator over the vector.
    #[inline]
    pub fn iter(&self) -> slice::Iter<'_, T> {
        self.as_slice().iter()
    }

    /// Returns a mutable iterator over the vector.
    #[inline]
    pub fn iter_mut(&mut self) -> slice::IterMut<'_, T> {
        self.as_mut_slice().iter_mut()
    }

    /// Drains elements from `start` to end, returning an iterator.
    /// Elements are removed from the vector.
    #[inline]
    pub fn drain(&mut self, range: std::ops::RangeFrom<usize>) -> Drain<'_, T> {
        let start = range.start;
        let len = self.len();
        assert!(start <= len, "drain start index out of bounds");

        Drain {
            vec: self,
            start,
            current: start,
            end: len,
        }
    }

    /// Gets a reference to an element.
    #[inline(always)]
    pub fn get(&self, index: usize) -> Option<&T> {
        if index < self.len() {
            // SAFETY: index < len is checked above, so the element is valid.
            unsafe { Some(&*self.ptr.as_ptr().add(index)) }
        } else {
            None
        }
    }

    /// Gets a mutable reference to an element.
    #[inline(always)]
    pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
        if index < self.len() {
            // SAFETY: index < len is checked above, so the element is valid.
            unsafe { Some(&mut *self.ptr.as_ptr().add(index)) }
        } else {
            None
        }
    }

    /// Converts the vector into a standard Vec.
    #[inline]
    pub fn into_vec(self) -> Vec<T> {
        let len = self.len();
        let cap = self.capacity();

        if cap == 0 {
            mem::forget(self);
            return Vec::new();
        }

        let ptr = self.ptr.as_ptr();
        mem::forget(self);

        // SAFETY: ptr was allocated by the global allocator with the given capacity,
        // len elements are initialized, and we've forgotten self to prevent double-free.
        unsafe { Vec::from_raw_parts(ptr, len, cap) }
    }

    /// Converts the vector into a boxed slice.
    #[inline]
    pub fn into_boxed_slice(self) -> Box<[T]> {
        self.into_vec().into_boxed_slice()
    }

    /// Creates a CompactVec from a standard Vec.
    #[inline]
    pub fn from_vec(vec: Vec<T>) -> Self {
        let len = vec.len().min(u32::MAX as usize) as u32;
        let cap = vec.capacity().min(u32::MAX as usize) as u32;

        if cap == 0 {
            mem::forget(vec);
            return Self::new();
        }

        let mut vec = ManuallyDrop::new(vec);
        let ptr = vec.as_mut_ptr();

        Self {
            // SAFETY: Vec always has a non-null pointer when capacity > 0.
            ptr: unsafe { NonNull::new_unchecked(ptr) },
            len_cap: Self::pack(len, cap),
        }
    }
}

impl<T: Clone> CompactVec<T> {
    /// Resizes the vector to `new_len`, filling with clones of `value`.
    pub fn resize(&mut self, new_len: usize, value: T) {
        let len = self.len();

        if new_len > len {
            self.reserve(new_len - len);
            for _ in len..new_len {
                self.push(value.clone());
            }
        } else {
            self.truncate(new_len);
        }
    }
}

impl<T> Drop for CompactVec<T> {
    fn drop(&mut self) {
        if self.capacity() == 0 {
            return;
        }

        // Drop all elements
        let len = self.len();
        if len > 0 {
            // SAFETY: All len elements are initialized and valid for dropping.
            unsafe {
                ptr::drop_in_place(ptr::slice_from_raw_parts_mut(self.ptr.as_ptr(), len));
            }
        }

        // Deallocate memory
        if mem::size_of::<T>() > 0 {
            let layout = Layout::array::<T>(self.capacity()).unwrap();
            // SAFETY: ptr was allocated with this layout and capacity > 0.
            unsafe {
                dealloc(self.ptr.as_ptr() as *mut u8, layout);
            }
        }
    }
}

impl<T: Clone> Clone for CompactVec<T> {
    fn clone(&self) -> Self {
        let len = self.len();
        if len == 0 {
            return Self::new();
        }

        let mut new_vec = Self::with_capacity(len);

        // RAII guard for panic safety: if clone() panics, we set the length
        // to the number of successfully cloned elements so Drop can clean up.
        struct CloneGuard<'a, T> {
            vec: &'a mut CompactVec<T>,
            cloned_count: usize,
        }

        impl<T> Drop for CloneGuard<'_, T> {
            fn drop(&mut self) {
                // SAFETY: cloned_count tracks how many elements were successfully
                // cloned before a panic. Setting len to this value ensures Drop
                // will clean up exactly those elements. This is only reached on panic
                // (normal path uses mem::forget).
                unsafe {
                    self.vec.set_len(self.cloned_count);
                }
            }
        }

        let mut guard = CloneGuard {
            vec: &mut new_vec,
            cloned_count: 0,
        };

        // SAFETY:
        // - with_capacity(len) guarantees capacity >= len
        // - We write elements to indices 0..len
        // - If clone() panics, guard drops and sets len to cloned_count,
        //   ensuring proper cleanup of partially cloned elements
        unsafe {
            let src = self.ptr.as_ptr();
            let dst = guard.vec.ptr.as_ptr();
            for i in 0..len {
                ptr::write(dst.add(i), (*src.add(i)).clone());
                guard.cloned_count += 1;
            }
        }

        // Success! Set final length and forget the guard (prevent double-set)
        let cloned = guard.cloned_count;
        mem::forget(guard);
        // SAFETY: cloned equals len (the number of elements in self).
        // with_capacity(len) ensured capacity, and all len elements were cloned.
        unsafe {
            new_vec.set_len(cloned);
        }
        new_vec
    }
}

impl<T> Default for CompactVec<T> {
    #[inline]
    fn default() -> Self {
        Self::new()
    }
}

impl<T: fmt::Debug> fmt::Debug for CompactVec<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_list().entries(self.iter()).finish()
    }
}

impl<T> Deref for CompactVec<T> {
    type Target = [T];

    #[inline(always)]
    fn deref(&self) -> &[T] {
        self.as_slice()
    }
}

impl<T> DerefMut for CompactVec<T> {
    #[inline(always)]
    fn deref_mut(&mut self) -> &mut [T] {
        self.as_mut_slice()
    }
}

impl<T> Index<usize> for CompactVec<T> {
    type Output = T;

    #[inline(always)]
    fn index(&self, index: usize) -> &T {
        &self.as_slice()[index]
    }
}

impl<T> IndexMut<usize> for CompactVec<T> {
    #[inline(always)]
    fn index_mut(&mut self, index: usize) -> &mut T {
        &mut self.as_mut_slice()[index]
    }
}

impl<T> Index<std::ops::Range<usize>> for CompactVec<T> {
    type Output = [T];

    #[inline(always)]
    fn index(&self, range: std::ops::Range<usize>) -> &[T] {
        &self.as_slice()[range]
    }
}

impl<T> Index<std::ops::RangeFrom<usize>> for CompactVec<T> {
    type Output = [T];

    #[inline(always)]
    fn index(&self, range: std::ops::RangeFrom<usize>) -> &[T] {
        &self.as_slice()[range]
    }
}

impl<T> Index<std::ops::RangeTo<usize>> for CompactVec<T> {
    type Output = [T];

    #[inline(always)]
    fn index(&self, range: std::ops::RangeTo<usize>) -> &[T] {
        &self.as_slice()[range]
    }
}

impl<T> Index<std::ops::RangeFull> for CompactVec<T> {
    type Output = [T];

    #[inline(always)]
    fn index(&self, _range: std::ops::RangeFull) -> &[T] {
        self.as_slice()
    }
}

impl<T> FromIterator<T> for CompactVec<T> {
    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
        let iter = iter.into_iter();
        let (lower, upper) = iter.size_hint();

        // If exact size is known, write directly with bounds protection
        if Some(lower) == upper && lower > 0 {
            let mut vec = Self::with_capacity(lower);
            let cap = vec.capacity();

            // RAII guard for panic safety: if iter.next() panics, we set the length
            // to the number of successfully written elements so Drop can clean up.
            struct FromIterGuard<'a, T> {
                vec: &'a mut CompactVec<T>,
                written_count: usize,
            }

            impl<T> Drop for FromIterGuard<'_, T> {
                fn drop(&mut self) {
                    // SAFETY: written_count tracks how many elements were successfully
                    // written before a panic. Setting len to this value ensures Drop
                    // will clean up exactly those elements. This is only reached on panic
                    // (normal path uses mem::forget).
                    unsafe {
                        self.vec.set_len(self.written_count);
                    }
                }
            }

            let mut guard = FromIterGuard {
                vec: &mut vec,
                written_count: 0,
            };

            // SAFETY:
            // - with_capacity(lower) guarantees capacity >= lower
            // - We add bounds check (len < cap) to protect against malicious iterators
            //   that yield more elements than size_hint promised
            // - If iter.next() panics, guard drops and sets len, ensuring cleanup
            unsafe {
                let ptr = guard.vec.ptr.as_ptr();
                for item in iter {
                    if guard.written_count >= cap {
                        // Iterator lied about size - fall back to safe push
                        let count = guard.written_count;
                        guard.vec.set_len(count);
                        guard.vec.push(item);
                        guard.written_count = guard.vec.len();
                        continue;
                    }
                    ptr::write(ptr.add(guard.written_count), item);
                    guard.written_count += 1;
                }
            }

            // Success! Set final length and forget the guard
            let final_len = guard.written_count;
            mem::forget(guard);
            // SAFETY: final_len equals the number of elements written by the loop.
            // with_capacity() ensured capacity, and the loop wrote exactly final_len elements.
            unsafe {
                vec.set_len(final_len);
            }
            vec
        } else {
            // Fallback for unknown size - push is already panic-safe
            let mut vec = Self::with_capacity(lower);
            for item in iter {
                vec.push(item);
            }
            vec
        }
    }
}

impl<T> IntoIterator for CompactVec<T> {
    type Item = T;
    type IntoIter = IntoIter<T>;

    fn into_iter(self) -> IntoIter<T> {
        IntoIter::new(self)
    }
}

impl<'a, T> IntoIterator for &'a CompactVec<T> {
    type Item = &'a T;
    type IntoIter = slice::Iter<'a, T>;

    fn into_iter(self) -> slice::Iter<'a, T> {
        self.iter()
    }
}

impl<'a, T> IntoIterator for &'a mut CompactVec<T> {
    type Item = &'a mut T;
    type IntoIter = slice::IterMut<'a, T>;

    fn into_iter(self) -> slice::IterMut<'a, T> {
        self.iter_mut()
    }
}

impl<T: PartialEq> PartialEq for CompactVec<T> {
    fn eq(&self, other: &Self) -> bool {
        self.as_slice() == other.as_slice()
    }
}

impl<T: Eq> Eq for CompactVec<T> {}

impl<T> From<Vec<T>> for CompactVec<T> {
    fn from(vec: Vec<T>) -> Self {
        Self::from_vec(vec)
    }
}

impl<T> From<CompactVec<T>> for Vec<T> {
    fn from(vec: CompactVec<T>) -> Self {
        vec.into_vec()
    }
}

/// Drain iterator for CompactVec.
/// Removes elements from the vector as they are iterated.
pub struct Drain<'a, T> {
    vec: &'a mut CompactVec<T>,
    start: usize,
    current: usize,
    end: usize,
}

impl<'a, T> Iterator for Drain<'a, T> {
    type Item = T;

    #[inline]
    fn next(&mut self) -> Option<T> {
        if self.current < self.end {
            // SAFETY: current < end <= original len, so the element is valid.
            // After reading, we increment current so it won't be read again.
            let item = unsafe { ptr::read(self.vec.ptr.as_ptr().add(self.current)) };
            self.current += 1;
            Some(item)
        } else {
            None
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = self.end - self.current;
        (remaining, Some(remaining))
    }
}

impl<'a, T> ExactSizeIterator for Drain<'a, T> {
    fn len(&self) -> usize {
        self.end - self.current
    }
}

impl<'a, T> Drop for Drain<'a, T> {
    fn drop(&mut self) {
        // Drop any remaining elements not yet consumed
        while self.current < self.end {
            // SAFETY: Elements [current..end] are initialized but not yet consumed.
            unsafe {
                ptr::drop_in_place(self.vec.ptr.as_ptr().add(self.current));
            }
            self.current += 1;
        }

        // SAFETY: Elements [0..start] are still valid, elements [start..end] have
        // been consumed or dropped, so we set len to start.
        unsafe {
            self.vec.set_len(self.start);
        }
    }
}

/// Owning iterator for CompactVec.
pub struct IntoIter<T> {
    vec: CompactVec<T>,
    index: usize,
}

impl<T> IntoIter<T> {
    fn new(vec: CompactVec<T>) -> Self {
        Self { vec, index: 0 }
    }
}

impl<T> Iterator for IntoIter<T> {
    type Item = T;

    fn next(&mut self) -> Option<T> {
        if self.index < self.vec.len() {
            // SAFETY: index < len, so the element is valid. After reading,
            // we increment index so it won't be read again.
            let item = unsafe { ptr::read(self.vec.ptr.as_ptr().add(self.index)) };
            self.index += 1;
            Some(item)
        } else {
            None
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = self.vec.len() - self.index;
        (remaining, Some(remaining))
    }
}

impl<T> ExactSizeIterator for IntoIter<T> {
    fn len(&self) -> usize {
        self.vec.len() - self.index
    }
}

impl<T> Drop for IntoIter<T> {
    fn drop(&mut self) {
        let len = self.vec.len();
        if self.index < len {
            // SAFETY:
            // - Elements [index..len] have not been read/moved out yet
            // - They are valid initialized elements that need dropping
            // - After drop_in_place, we set len=0 to prevent double-drop
            unsafe {
                let remaining = len - self.index;
                ptr::drop_in_place(ptr::slice_from_raw_parts_mut(
                    self.vec.ptr.as_ptr().add(self.index),
                    remaining,
                ));
            }
        }

        // SAFETY: All elements are now dropped, set len=0 to prevent double-drop
        unsafe {
            self.vec.set_len(0);
        }
    }
}

/// Creates a [`CompactVec`] containing the arguments.
///
/// `compact_vec!` allows creating a `CompactVec` with the same syntax as `vec![]`:
///
/// ```ignore
/// let v = compact_vec![1, 2, 3];
/// assert_eq!(v.as_slice(), &[1, 2, 3]);
/// ```
#[macro_export]
macro_rules! compact_vec {
    () => {
        $crate::common::CompactVec::new()
    };
    ($($elem:expr),+ $(,)?) => {{
        // Use array to get count at compile time, then collect
        let arr = [$($elem),+];
        let mut vec = $crate::common::CompactVec::with_capacity(arr.len());
        for elem in arr {
            vec.push(elem);
        }
        vec
    }};
}

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

    #[test]
    fn test_size() {
        assert_eq!(std::mem::size_of::<CompactVec<u8>>(), 16);
        assert_eq!(std::mem::size_of::<CompactVec<u64>>(), 16);
        assert_eq!(std::mem::size_of::<Vec<u8>>(), 24);
    }

    #[test]
    fn test_basic_operations() {
        let mut vec = CompactVec::new();
        assert!(vec.is_empty());
        assert_eq!(vec.len(), 0);

        vec.push(1);
        vec.push(2);
        vec.push(3);

        assert_eq!(vec.len(), 3);
        assert_eq!(vec[0], 1);
        assert_eq!(vec[1], 2);
        assert_eq!(vec[2], 3);

        assert_eq!(vec.pop(), Some(3));
        assert_eq!(vec.len(), 2);
    }

    #[test]
    fn test_with_capacity() {
        let vec: CompactVec<i32> = CompactVec::with_capacity(100);
        assert!(vec.is_empty());
        assert!(vec.capacity() >= 100);
    }

    #[test]
    fn test_clone() {
        let mut vec = CompactVec::new();
        vec.push(1);
        vec.push(2);
        vec.push(3);

        let cloned = vec.clone();
        assert_eq!(vec.as_slice(), cloned.as_slice());
    }

    #[test]
    fn test_iteration() {
        let mut vec = CompactVec::new();
        vec.push(1);
        vec.push(2);
        vec.push(3);

        let sum: i32 = vec.iter().sum();
        assert_eq!(sum, 6);

        let collected: Vec<i32> = vec.into_iter().collect();
        assert_eq!(collected, vec![1, 2, 3]);
    }

    #[test]
    fn test_from_iterator() {
        let vec: CompactVec<i32> = (0..5).collect();
        assert_eq!(vec.len(), 5);
        assert_eq!(vec.as_slice(), &[0, 1, 2, 3, 4]);
    }

    #[test]
    fn test_extend() {
        let mut vec = CompactVec::new();
        vec.push(1);
        vec.extend(vec![2, 3, 4]);
        assert_eq!(vec.as_slice(), &[1, 2, 3, 4]);
    }

    #[test]
    fn test_truncate() {
        let mut vec: CompactVec<i32> = (0..10).collect();
        vec.truncate(5);
        assert_eq!(vec.len(), 5);
        assert_eq!(vec.as_slice(), &[0, 1, 2, 3, 4]);
    }

    #[test]
    fn test_clear() {
        let mut vec: CompactVec<i32> = (0..10).collect();
        let cap = vec.capacity();
        vec.clear();
        assert!(vec.is_empty());
        assert_eq!(vec.capacity(), cap); // Capacity preserved
    }

    #[test]
    fn test_swap_remove() {
        let mut vec = CompactVec::new();
        vec.push(1);
        vec.push(2);
        vec.push(3);

        assert_eq!(vec.swap_remove(0), 1);
        assert_eq!(vec.as_slice(), &[3, 2]);
    }

    #[test]
    fn test_into_vec_and_back() {
        let compact: CompactVec<i32> = (0..5).collect();
        let std_vec: Vec<i32> = compact.into_vec();
        assert_eq!(std_vec, vec![0, 1, 2, 3, 4]);

        let compact_again = CompactVec::from_vec(std_vec);
        assert_eq!(compact_again.as_slice(), &[0, 1, 2, 3, 4]);
    }

    #[test]
    fn test_with_strings() {
        let mut vec = CompactVec::new();
        vec.push(String::from("hello"));
        vec.push(String::from("world"));

        assert_eq!(vec[0], "hello");
        assert_eq!(vec[1], "world");

        let cloned = vec.clone();
        assert_eq!(cloned[0], "hello");
    }

    /// Test panic safety in Clone implementation
    #[test]
    fn test_clone_panic_safety() {
        use std::sync::atomic::{AtomicUsize, Ordering};

        static DROP_COUNT: AtomicUsize = AtomicUsize::new(0);
        static CLONE_COUNT: AtomicUsize = AtomicUsize::new(0);

        #[derive(Debug)]
        struct PanicOnThirdClone(usize);

        impl Clone for PanicOnThirdClone {
            fn clone(&self) -> Self {
                let count = CLONE_COUNT.fetch_add(1, Ordering::SeqCst);
                if count == 2 {
                    panic!("Intentional panic on third clone");
                }
                PanicOnThirdClone(self.0)
            }
        }

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

        // Reset counters
        DROP_COUNT.store(0, Ordering::SeqCst);
        CLONE_COUNT.store(0, Ordering::SeqCst);

        let mut vec = CompactVec::new();
        vec.push(PanicOnThirdClone(1));
        vec.push(PanicOnThirdClone(2));
        vec.push(PanicOnThirdClone(3));
        vec.push(PanicOnThirdClone(4));

        // Try to clone - should panic on third element
        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let _cloned = vec.clone();
        }));

        assert!(result.is_err(), "Should have panicked");

        // Verify panic safety: 2 successfully cloned elements should be dropped
        // by the CloneGuard when the panic unwinds
        let drops_from_cleanup = DROP_COUNT.load(Ordering::SeqCst);
        assert_eq!(
            drops_from_cleanup, 2,
            "Should have dropped 2 successfully cloned elements, got {}",
            drops_from_cleanup
        );

        // Now drop the original vec (4 elements)
        drop(vec);
        let total_drops = DROP_COUNT.load(Ordering::SeqCst);
        assert_eq!(
            total_drops, 6,
            "Total drops should be 6 (2 from cleanup + 4 from original), got {}",
            total_drops
        );
    }

    /// Test panic safety in extend_clone implementation
    #[test]
    fn test_extend_clone_panic_safety() {
        use std::sync::atomic::{AtomicUsize, Ordering};

        static DROP_COUNT: AtomicUsize = AtomicUsize::new(0);
        static CLONE_COUNT: AtomicUsize = AtomicUsize::new(0);

        #[derive(Debug)]
        struct PanicOnThirdClone(usize);

        impl Clone for PanicOnThirdClone {
            fn clone(&self) -> Self {
                let count = CLONE_COUNT.fetch_add(1, Ordering::SeqCst);
                if count == 2 {
                    panic!("Intentional panic on third clone");
                }
                PanicOnThirdClone(self.0)
            }
        }

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

        // Reset counters
        DROP_COUNT.store(0, Ordering::SeqCst);
        CLONE_COUNT.store(0, Ordering::SeqCst);

        // Create source slice (won't be dropped, just borrowed)
        let source = [
            PanicOnThirdClone(1),
            PanicOnThirdClone(2),
            PanicOnThirdClone(3),
            PanicOnThirdClone(4),
        ];

        let mut vec: CompactVec<PanicOnThirdClone> = CompactVec::new();

        // Try to extend_clone - should panic on third element
        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            vec.extend_clone(&source);
        }));

        assert!(result.is_err(), "Should have panicked");

        // The guard has set vec's length to 2 (the successfully cloned elements)
        // Now when we drop vec, those 2 elements should be properly dropped
        assert_eq!(
            vec.len(),
            2,
            "Guard should have set length to 2 (elements cloned before panic)"
        );

        // Drop vec - this should drop the 2 elements the guard accounted for
        drop(vec);
        let drops_after_vec_drop = DROP_COUNT.load(Ordering::SeqCst);
        assert_eq!(
            drops_after_vec_drop, 2,
            "Should have dropped 2 successfully cloned elements when vec dropped, got {}",
            drops_after_vec_drop
        );

        // Drop source (4 elements)
        drop(source);
        let total_drops = DROP_COUNT.load(Ordering::SeqCst);
        assert_eq!(
            total_drops, 6,
            "Total drops should be 6 (2 from vec + 4 from source), got {}",
            total_drops
        );
    }

    /// Test panic safety in from_iter implementation
    #[test]
    fn test_from_iter_panic_safety() {
        use std::sync::atomic::{AtomicUsize, Ordering};

        static DROP_COUNT: AtomicUsize = AtomicUsize::new(0);

        #[derive(Debug)]
        #[allow(dead_code)] // Field used to give struct a non-zero size
        struct PanicOnThirdNext(usize);

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

        // An iterator that panics on the third next() call
        struct PanickingIter {
            current: usize,
            max: usize,
        }

        impl Iterator for PanickingIter {
            type Item = PanicOnThirdNext;

            fn next(&mut self) -> Option<Self::Item> {
                if self.current >= self.max {
                    return None;
                }
                self.current += 1;
                if self.current == 3 {
                    panic!("Intentional panic on third next()");
                }
                Some(PanicOnThirdNext(self.current))
            }

            fn size_hint(&self) -> (usize, Option<usize>) {
                let remaining = self.max - self.current;
                (remaining, Some(remaining))
            }
        }

        impl ExactSizeIterator for PanickingIter {}

        // Reset counter
        DROP_COUNT.store(0, Ordering::SeqCst);

        // Try to collect - should panic on third element
        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let _vec: CompactVec<PanicOnThirdNext> = PanickingIter { current: 0, max: 5 }.collect();
        }));

        assert!(result.is_err(), "Should have panicked");

        // Verify panic safety: 2 successfully written elements should be dropped
        let drops_after_panic = DROP_COUNT.load(Ordering::SeqCst);
        assert_eq!(
            drops_after_panic, 2,
            "Should have dropped 2 successfully written elements, got {}",
            drops_after_panic
        );
    }
}