slabigator 0.9.5

A fixed-capacity linked list with stable element addressing and no dynamic allocations
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
#![doc = include_str!("../README.md")]
#![warn(rustdoc::broken_intra_doc_links)]
#![warn(missing_docs)]
#![warn(clippy::pedantic)]
#![allow(clippy::module_name_repetitions)]
#![allow(clippy::missing_errors_doc)]
#![allow(clippy::cast_possible_truncation)]

//! # Slabigator
//!
//! A high-performance linked list with fixed capacity that doesn't perform dynamic memory
//! allocations after initialization. It provides O(1) operations for adding, removing,
//! and accessing elements.
//!
//! ## Overview
//!
//! Slabigator is designed for scenarios where memory allocation predictability is critical
//! and you need stable references to elements. It allocates all memory upfront and provides
//! slot numbers as stable references to elements.
//!
//! ## Key Features
//!
//! - Fixed capacity - no allocations during operations
//! - O(1) push_front operation
//! - O(1) pop_back operation
//! - O(1) removal of any element by slot
//! - Slots provide stable references to elements
//! - Implements useful Rust traits like `FromIterator` and `Extend`
//!
//! ## Basic Usage
//!
//! ```rust
//! use slabigator::Slab;
//!
//! // Create a slab with capacity for 3 elements
//! let mut slab = Slab::with_capacity(3).unwrap();
//!
//! // Push elements to the front (returns slot numbers)
//! let a = slab.push_front("a").unwrap();
//! let b = slab.push_front("b").unwrap();
//! let c = slab.push_front("c").unwrap();
//!
//! // Access by slot
//! assert_eq!(slab.get(a).unwrap(), &"a");
//! assert_eq!(slab.get(b).unwrap(), &"b");
//! assert_eq!(slab.get(c).unwrap(), &"c");
//!
//! // Remove an element
//! slab.remove(b).unwrap();
//! assert_eq!(slab.len(), 2);
//!
//! // Iterate (order is from head to tail)
//! let elements: Vec<_> = slab.iter().collect();
//! assert_eq!(elements, vec![&"c", &"a"]);
//!
//! // Pop from the back (FIFO queue behavior)
//! assert_eq!(slab.pop_back().unwrap(), "a");
//! assert_eq!(slab.pop_back().unwrap(), "c");
//! assert!(slab.is_empty());
//! ```
//!
//! ## Advanced Features
//!
//! ### Default capacity
//!
//! ```rust
//! use slabigator::Slab;
//!
//! // Creates a slab with default capacity (16)
//! let slab: Slab<i32> = Slab::default();
//! assert_eq!(slab.capacity(), 16);
//! ```
//!
//! ### Creating from an iterator
//!
//! ```rust
//! use slabigator::Slab;
//!
//! let values = vec![1, 2, 3, 4, 5];
//! let slab: Slab<_> = values.iter().copied().collect();
//!
//! assert_eq!(slab.len(), 5);
//! ```
//!
//! ### Extending a slab
//!
//! ```rust
//! use slabigator::Slab;
//!
//! let mut slab = Slab::with_capacity(5).unwrap();
//! slab.push_front(1).unwrap();
//! slab.push_front(2).unwrap();
//!
//! // Extend with more elements
//! slab.extend(vec![3, 4, 5]);
//! assert_eq!(slab.len(), 5);
//! ```

use std::iter::Iterator;

#[cfg(all(feature = "slot_u64", not(feature = "slot_usize")))]
/// Slot type used for element references.
/// This is u64 when the `slot_u64` feature is enabled.
pub type Slot = u64;
#[cfg(feature = "slot_usize")]
/// Slot type used for element references.
/// This is usize when the `slot_usize` feature is enabled.
pub type Slot = usize;
#[cfg(not(any(
    all(feature = "slot_u64", not(feature = "slot_usize")),
    feature = "slot_usize"
)))]
/// Slot type used for element references.
/// This is u32 by default or when the `slot_u32` feature is enabled.
pub type Slot = u32;

const NUL: Slot = Slot::MAX;

/// A fixed-capacity linked list that doesn't perform dynamic memory allocations after initialization.
///
/// # Overview
///
/// `Slab<D>` is a specialized data structure that allocates all of its memory upfront and provides
/// stable slot numbers as references to elements. This makes it ideal for performance-critical
/// applications where:
///
/// - Memory allocation patterns need to be predictable
/// - You need stable references to elements
/// - Fast O(1) operations are required
/// - You know the maximum capacity in advance
///
/// # Core Operations
///
/// - **`push_front`**: Add elements to the head of the list in O(1) time
/// - **`pop_back`**: Remove and return an element from the tail in O(1) time
/// - **remove**: Delete any element by its slot number in O(1) time
/// - **`get/get_mut`**: Access any element by its slot number in O(1) time
///
/// # Memory Behavior
///
/// The slab allocates all memory during creation with `with_capacity()`. No further allocations
/// occur during subsequent operations. This provides predictable memory usage and avoids
/// allocation-related performance issues.
///
/// # Implementation Details
///
/// Internally, the slab maintains:
/// - A vector of elements
/// - A linked list structure for tracking the order of elements
/// - A free list for quick reuse of slots
/// - A bitmap for validating slot access (when not using `releasefast` feature)
///
/// # Examples
///
/// ## Basic Operations
///
/// ```
/// use slabigator::Slab;
///
/// // Create a new slab with capacity for 3 elements
/// let mut slab = Slab::with_capacity(3).unwrap();
///
/// // Push elements to the front - each operation returns a slot number
/// // The slot numbers are stable references that won't change
/// // even when other elements are added or removed
/// let slot_a = slab.push_front("a").unwrap();
/// let slot_b = slab.push_front("b").unwrap();
/// let slot_c = slab.push_front("c").unwrap();
///
/// // Slab is now full
/// assert!(slab.is_full());
/// assert_eq!(slab.len(), 3);
///
/// // Access elements by slot - these are direct lookups
/// assert_eq!(slab.get(slot_a).unwrap(), &"a");
/// assert_eq!(slab.get(slot_b).unwrap(), &"b");
/// assert_eq!(slab.get(slot_c).unwrap(), &"c");
///
/// // Remove an element by slot
/// slab.remove(slot_b).unwrap();
/// assert_eq!(slab.len(), 2);
/// #[cfg(not(feature = "releasefast"))]
/// assert!(slab.get(slot_b).is_err()); // Slot b is no longer valid
///
/// // Pop elements from the back (FIFO order)
/// let value = slab.pop_back().unwrap();
/// assert_eq!(value, "a");
/// assert_eq!(slab.len(), 1);
///
/// let value = slab.pop_back().unwrap();
/// assert_eq!(value, "c");
/// assert!(slab.is_empty());
/// ```
///
/// ## Using as a FIFO Queue
///
/// ```
/// use slabigator::Slab;
///
/// let mut queue = Slab::with_capacity(10).unwrap();
///
/// // Enqueue items (push to front)
/// queue.push_front("first").unwrap();
/// queue.push_front("second").unwrap();
/// queue.push_front("third").unwrap();
///
/// // Dequeue items (pop from back) - FIFO order
/// assert_eq!(queue.pop_back().unwrap(), "first");
/// assert_eq!(queue.pop_back().unwrap(), "second");
/// assert_eq!(queue.pop_back().unwrap(), "third");
/// ```
///
/// ## Using for Object Pooling
///
/// ```
/// use slabigator::Slab;
///
/// #[derive(Debug, PartialEq)]
/// struct GameObject {
///     id: u32,
///     active: bool,
/// }
///
/// // Create a pool of game objects
/// let mut pool = Slab::with_capacity(100).unwrap();
///
/// // Create and add objects to the pool
/// let slot1 = pool.push_front(GameObject { id: 1, active: true }).unwrap();
/// let slot2 = pool.push_front(GameObject { id: 2, active: true }).unwrap();
///
/// // Deactivate an object (by mutating it)
/// if let Ok(object) = pool.get_mut(slot1) {
///     object.active = false;
/// }
///
/// // Remove an object from the pool when no longer needed
/// pool.remove(slot2).unwrap();
/// ```
#[derive(Debug)]
pub struct Slab<D: Sized> {
    vec_next: Vec<Slot>,
    vec_prev: Vec<Slot>,
    free_head: Slot,
    head: Slot,
    tail: Slot,
    len: usize,
    data: Vec<Option<D>>,
    #[cfg(not(feature = "releasefast"))]
    bitmap: Vec<u8>,
}

/// Error types that can occur during Slab operations.
///
/// The Slab API follows a design philosophy where operations that could fail return
/// a `Result<T, Error>` rather than panicking. This allows error handling to be more
/// explicit and gives the caller control over how to handle error conditions.
///
/// # Examples
///
/// ```
/// use slabigator::{Slab, Error};
///
/// let mut slab = Slab::with_capacity(1).unwrap();
/// slab.push_front("only element").unwrap();
///
/// // Attempt to add another element when slab is full
/// match slab.push_front("one too many") {
///     Ok(_) => println!("Element added successfully"),
///     Err(Error::Full) => println!("Cannot add element: slab is full"),
///     Err(_) => println!("Other error occurred"),
/// }
///
/// // Attempt to access an invalid slot
/// match slab.get(999) {
///     Ok(_) => println!("Element retrieved"),
///     Err(Error::InvalidSlot) => println!("Invalid slot"),
///     Err(_) => println!("Other error occurred"),
/// }
/// ```
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub enum Error {
    /// Returned when the requested capacity during creation is too large for the
    /// selected slot type. This occurs when the capacity would cause the slot index
    /// to exceed the maximum value for the slot type (u32, u64, or usize).
    TooLarge,

    /// Returned when attempting to add an element to a slab that already contains
    /// its maximum capacity of elements. Check `is_full()` before adding elements
    /// or handle this error to implement graceful fallbacks.
    Full,

    /// Returned when:
    /// - Accessing a slot that is out of bounds (>= capacity)
    /// - Accessing a slot that doesn't contain an element (was never set or was removed)
    /// - Attempting to remove an element from a slot that is invalid
    ///
    /// When not using the `releasefast` feature, all slot validity is checked.
    InvalidSlot,

    /// Returned when attempting to access or remove elements from an empty slab.
    /// Check `is_empty()` before these operations or handle this error appropriately.
    Empty,
}

impl std::error::Error for Error {}

impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
        match self {
            Error::TooLarge => write!(f, "Capacity is too large for the slot type"),
            Error::Full => write!(f, "Slab is full and cannot accept more elements"),
            Error::InvalidSlot => write!(f, "Invalid slot or slot doesn't contain an element"),
            Error::Empty => write!(f, "Slab is empty"),
        }
    }
}

impl<D: Sized> Slab<D> {
    /// Creates a new slab with the given capacity.
    ///
    /// # Arguments
    ///
    /// * `capacity` - The maximum number of elements the slab can hold.
    ///
    /// # Returns
    ///
    /// * `Ok(Slab<D>)` - A new slab with the requested capacity.
    /// * `Err(Error::TooLarge)` - If the capacity is too large for the slot type.
    ///
    /// # Examples
    ///
    /// ```
    /// use slabigator::Slab;
    ///
    /// let slab = Slab::<String>::with_capacity(10).unwrap();
    /// assert_eq!(slab.capacity(), 10);
    /// assert_eq!(slab.len(), 0);
    /// assert!(slab.is_empty());
    /// ```
    pub fn with_capacity(capacity: usize) -> Result<Self, Error> {
        if capacity as Slot == NUL {
            return Err(Error::TooLarge);
        }
        let mut vec_next = Vec::with_capacity(capacity);
        for i in 0..(capacity - 1) {
            vec_next.push(i as Slot + 1);
        }
        vec_next.push(NUL);

        let mut vec_prev = Vec::with_capacity(capacity);
        vec_prev.push(NUL);
        for i in 1..capacity {
            vec_prev.push(i as Slot - 1);
        }

        // Initialize data with None values instead of MaybeUninit
        let mut data = Vec::with_capacity(capacity);
        for _ in 0..capacity {
            data.push(None);
        }

        #[cfg(not(feature = "releasefast"))]
        let bitmap_size = (capacity + 7) / 8; // TODO: Replace with capacity.div_ceil(8) when stable

        Ok(Self {
            vec_next,
            vec_prev,
            free_head: 0,
            head: NUL,
            tail: NUL,
            len: 0,
            data,
            #[cfg(not(feature = "releasefast"))]
            bitmap: vec![0u8; bitmap_size],
        })
    }

    /// Returns the capacity of the slab.
    ///
    /// # Examples
    ///
    /// ```
    /// use slabigator::Slab;
    ///
    /// let slab = Slab::<i32>::with_capacity(10).unwrap();
    /// assert_eq!(slab.capacity(), 10);
    /// ```
    #[inline]
    #[must_use]
    pub fn capacity(&self) -> usize {
        self.data.capacity()
    }

    /// Returns the number of elements in the slab.
    ///
    /// # Examples
    ///
    /// ```
    /// use slabigator::Slab;
    ///
    /// let mut slab = Slab::with_capacity(10).unwrap();
    /// assert_eq!(slab.len(), 0);
    ///
    /// slab.push_front(42).unwrap();
    /// assert_eq!(slab.len(), 1);
    /// ```
    #[inline]
    #[must_use]
    pub fn len(&self) -> usize {
        self.len
    }

    /// Returns the number of elements that can still be stored.
    ///
    /// # Examples
    ///
    /// ```
    /// use slabigator::Slab;
    ///
    /// let mut slab = Slab::with_capacity(3).unwrap();
    /// assert_eq!(slab.free(), 3);
    ///
    /// slab.push_front(42).unwrap();
    /// assert_eq!(slab.free(), 2);
    /// ```
    #[inline]
    #[must_use]
    pub fn free(&self) -> usize {
        self.capacity() - self.len()
    }

    /// Returns `true` if the slab contains no elements.
    ///
    /// # Examples
    ///
    /// ```
    /// use slabigator::Slab;
    ///
    /// let mut slab = Slab::with_capacity(10).unwrap();
    /// assert!(slab.is_empty());
    ///
    /// slab.push_front(42).unwrap();
    /// assert!(!slab.is_empty());
    /// ```
    #[inline]
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Returns `true` if the slab cannot hold any more elements.
    ///
    /// # Examples
    ///
    /// ```
    /// use slabigator::Slab;
    ///
    /// let mut slab = Slab::with_capacity(2).unwrap();
    /// assert!(!slab.is_full());
    ///
    /// slab.push_front(1).unwrap();
    /// slab.push_front(2).unwrap();
    /// assert!(slab.is_full());
    /// ```
    #[inline]
    #[must_use]
    pub fn is_full(&self) -> bool {
        self.free_head == NUL
    }

    /// Returns a reference to an element given its slot number.
    ///
    /// # Arguments
    ///
    /// * `slot` - The slot number of the element to retrieve.
    ///
    /// # Returns
    ///
    /// * `Ok(&D)` - A reference to the element.
    /// * `Err(Error::InvalidSlot)` - If the slot is invalid or doesn't contain an element.
    ///
    /// # Examples
    ///
    /// ```
    /// use slabigator::Slab;
    ///
    /// let mut slab = Slab::with_capacity(10).unwrap();
    /// let slot = slab.push_front("hello").unwrap();
    ///
    /// assert_eq!(slab.get(slot).unwrap(), &"hello");
    /// ```
    pub fn get(&self, slot: Slot) -> Result<&D, Error> {
        let index = slot as usize;
        if index >= self.capacity() {
            return Err(Error::InvalidSlot);
        }

        #[cfg(not(feature = "releasefast"))]
        {
            if !self.bitmap_get(slot) {
                return Err(Error::InvalidSlot);
            }
        }

        // Use pattern matching to safely access the Option<D>
        match &self.data[index] {
            Some(value) => Ok(value),
            None => Err(Error::InvalidSlot),
        }
    }

    /// Returns a mutable reference to an element given its slot number.
    ///
    /// # Arguments
    ///
    /// * `slot` - The slot number of the element to retrieve.
    ///
    /// # Returns
    ///
    /// * `Ok(&mut D)` - A mutable reference to the element.
    /// * `Err(Error::InvalidSlot)` - If the slot is invalid or doesn't contain an element.
    ///
    /// # Examples
    ///
    /// ```
    /// use slabigator::Slab;
    ///
    /// let mut slab = Slab::with_capacity(10).unwrap();
    /// let slot = slab.push_front("hello").unwrap();
    ///
    /// *slab.get_mut(slot).unwrap() = "world";
    /// assert_eq!(slab.get(slot).unwrap(), &"world");
    /// ```
    pub fn get_mut(&mut self, slot: Slot) -> Result<&mut D, Error> {
        let index = slot as usize;
        if index >= self.capacity() {
            return Err(Error::InvalidSlot);
        }

        #[cfg(not(feature = "releasefast"))]
        {
            if !self.bitmap_get(slot) {
                return Err(Error::InvalidSlot);
            }
        }

        // Use pattern matching to safely access the Option<D>
        match &mut self.data[index] {
            Some(value) => Ok(value),
            None => Err(Error::InvalidSlot),
        }
    }

    /// Prepends an element to the beginning of the slab.
    ///
    /// # Arguments
    ///
    /// * `value` - The value to prepend.
    ///
    /// # Returns
    ///
    /// * `Ok(Slot)` - The slot number of the newly added element.
    /// * `Err(Error::Full)` - If the slab is full.
    ///
    /// # Examples
    ///
    /// ```
    /// use slabigator::Slab;
    ///
    /// let mut slab = Slab::with_capacity(3).unwrap();
    ///
    /// let a = slab.push_front("a").unwrap();
    /// let b = slab.push_front("b").unwrap();
    /// let c = slab.push_front("c").unwrap();
    ///
    /// // Elements are in reverse order of insertion
    /// let mut iter = slab.iter();
    /// assert_eq!(iter.next(), Some(&"c"));
    /// assert_eq!(iter.next(), Some(&"b"));
    /// assert_eq!(iter.next(), Some(&"a"));
    /// assert_eq!(iter.next(), None);
    /// ```
    pub fn push_front(&mut self, value: D) -> Result<Slot, Error> {
        let free_slot = self.free_head;
        if free_slot == NUL {
            return Err(Error::Full);
        }

        let free_index = free_slot as usize;
        let prev = self.vec_prev[free_index];
        let next = self.vec_next[free_index];

        if prev != NUL {
            debug_assert_eq!(self.vec_next[prev as usize], free_slot);
            self.vec_next[prev as usize] = next;
        }

        if next != NUL {
            if !self.is_empty() {
                debug_assert_eq!(self.vec_prev[next as usize], free_slot);
            }
            self.vec_prev[next as usize] = prev;
        }

        if self.head != NUL {
            self.vec_prev[self.head as usize] = free_slot;
        }

        self.free_head = next;
        self.vec_next[free_index] = self.head;
        self.vec_prev[free_index] = NUL;

        if self.head == NUL {
            self.tail = free_slot;
        }

        self.head = free_slot;

        // Store the value safely using Option
        self.data[free_index] = Some(value);

        self.len += 1;
        debug_assert!(self.len <= self.capacity());

        #[cfg(not(feature = "releasefast"))]
        {
            self.bitmap_set(free_slot);
        }

        Ok(free_slot)
    }

    /// Removes an element from the slab given its slot.
    ///
    /// # Arguments
    ///
    /// * `slot` - The slot number of the element to remove.
    ///
    /// # Returns
    ///
    /// * `Ok(())` - If the element was successfully removed.
    /// * `Err(Error::InvalidSlot)` - If the slot is invalid or doesn't contain an element.
    ///
    /// # Examples
    ///
    /// ```
    /// use slabigator::Slab;
    ///
    /// let mut slab = Slab::with_capacity(3).unwrap();
    /// let a = slab.push_front("a").unwrap();
    /// let b = slab.push_front("b").unwrap();
    /// let c = slab.push_front("c").unwrap();
    ///
    /// assert_eq!(slab.len(), 3);
    ///
    /// slab.remove(b).unwrap();
    /// assert_eq!(slab.len(), 2);
    ///
    /// // The element at slot `b` is no longer accessible
    /// #[cfg(not(feature = "releasefast"))]
    /// assert!(slab.get(b).is_err());
    /// ```
    pub fn remove(&mut self, slot: Slot) -> Result<(), Error> {
        let index = slot as usize;
        if index >= self.capacity() {
            return Err(Error::InvalidSlot);
        }

        #[cfg(not(feature = "releasefast"))]
        {
            if !self.bitmap_get(slot) {
                return Err(Error::InvalidSlot);
            }
        }

        // Check if there's actually an element at this slot
        if self.data[index].is_none() {
            return Err(Error::InvalidSlot);
        }

        // Clear the data by replacing it with None
        self.data[index] = None;

        let prev = self.vec_prev[index];
        let next = self.vec_next[index];

        if prev != NUL {
            debug_assert_eq!(self.vec_next[prev as usize], slot);
            self.vec_next[prev as usize] = next;
        }

        if next != NUL {
            if !self.is_empty() {
                debug_assert_eq!(self.vec_prev[next as usize], slot);
            }
            self.vec_prev[next as usize] = prev;
        }

        if self.tail == slot {
            self.tail = prev;
        }

        if self.head == slot {
            self.head = next;
        }

        self.vec_prev[index] = NUL;
        self.vec_next[index] = self.free_head;

        if self.free_head != NUL {
            self.vec_prev[self.free_head as usize] = slot;
        }

        self.free_head = slot;
        debug_assert!(self.len > 0);
        self.len -= 1;

        #[cfg(not(feature = "releasefast"))]
        {
            self.bitmap_unset(slot);
        }

        Ok(())
    }

    /// Removes and returns the tail element of the slab.
    ///
    /// # Returns
    ///
    /// * `Some(D)` - The removed element.
    /// * `None` - If the slab is empty.
    ///
    /// # Examples
    ///
    /// ```
    /// use slabigator::Slab;
    ///
    /// let mut slab = Slab::with_capacity(3).unwrap();
    /// slab.push_front("a").unwrap();
    /// slab.push_front("b").unwrap();
    /// slab.push_front("c").unwrap();
    ///
    /// assert_eq!(slab.pop_back(), Some("a"));
    /// assert_eq!(slab.pop_back(), Some("b"));
    /// assert_eq!(slab.pop_back(), Some("c"));
    /// assert_eq!(slab.pop_back(), None);
    /// ```
    pub fn pop_back(&mut self) -> Option<D> {
        let slot = self.tail;
        if slot == NUL {
            return None;
        }

        let index = slot as usize;

        // Take the value out, replacing it with None
        let value = self.data[index].take()?;

        let prev = self.vec_prev[index];
        debug_assert_eq!(self.vec_next[index], NUL);

        if prev != NUL {
            debug_assert_eq!(self.vec_next[prev as usize], slot);
            self.vec_next[prev as usize] = NUL;
        }

        self.tail = prev;

        if self.head == slot {
            self.head = NUL;
        }

        self.vec_prev[index] = NUL;
        self.vec_next[index] = self.free_head;

        if self.free_head != NUL {
            self.vec_prev[self.free_head as usize] = slot;
        }

        self.free_head = slot;
        debug_assert!(self.len > 0);
        self.len -= 1;

        #[cfg(not(feature = "releasefast"))]
        {
            self.bitmap_unset(slot);
        }

        Some(value)
    }

    /// Returns an iterator over the elements of the slab.
    ///
    /// The iterator yields elements in order from head to tail.
    ///
    /// # Examples
    ///
    /// ```
    /// use slabigator::Slab;
    ///
    /// let mut slab = Slab::with_capacity(3).unwrap();
    /// slab.push_front("a").unwrap();
    /// slab.push_front("b").unwrap();
    /// slab.push_front("c").unwrap();
    ///
    /// let mut iter = slab.iter();
    /// assert_eq!(iter.next(), Some(&"c"));
    /// assert_eq!(iter.next(), Some(&"b"));
    /// assert_eq!(iter.next(), Some(&"a"));
    /// assert_eq!(iter.next(), None);
    /// ```
    #[must_use]
    pub fn iter(&self) -> SlabIterator<D> {
        SlabIterator {
            list: self,
            slot: None,
        }
    }

    /// Checks if the slot contains an element.
    ///
    /// This method is only available when not using the `releasefast` feature.
    ///
    /// # Arguments
    ///
    /// * `slot` - The slot to check.
    ///
    /// # Returns
    ///
    /// * `true` - If the slot contains an element.
    /// * `false` - If the slot is invalid or doesn't contain an element.
    ///
    /// # Examples
    ///
    /// ```
    /// use slabigator::Slab;
    ///
    /// let mut slab = Slab::with_capacity(3).unwrap();
    /// let slot = slab.push_front("hello").unwrap();
    ///
    /// assert!(slab.contains_slot(slot));
    ///
    /// slab.remove(slot).unwrap();
    /// assert!(!slab.contains_slot(slot));
    /// ```
    #[cfg(not(feature = "releasefast"))]
    #[must_use]
    pub fn contains_slot(&self, slot: Slot) -> bool {
        if (slot as usize) >= self.capacity() {
            return false;
        }
        self.bitmap_get(slot)
    }

    #[cfg(not(feature = "releasefast"))]
    #[inline]
    fn bitmap_get(&self, slot: Slot) -> bool {
        (self.bitmap[(slot as usize) / 8] & (1 << ((slot as usize) & 7))) != 0
    }

    #[cfg(not(feature = "releasefast"))]
    #[inline]
    fn bitmap_set(&mut self, slot: Slot) {
        self.bitmap[(slot as usize) / 8] |= 1 << ((slot as usize) & 7);
    }

    #[cfg(not(feature = "releasefast"))]
    #[inline]
    fn bitmap_unset(&mut self, slot: Slot) {
        self.bitmap[(slot as usize) / 8] &= !(1 << ((slot as usize) & 7));
    }

    /// Clears the slab, removing all elements.
    ///
    /// # Examples
    ///
    /// ```
    /// use slabigator::Slab;
    ///
    /// let mut slab = Slab::with_capacity(3).unwrap();
    /// slab.push_front("a").unwrap();
    /// slab.push_front("b").unwrap();
    ///
    /// assert_eq!(slab.len(), 2);
    /// slab.clear();
    /// assert_eq!(slab.len(), 0);
    /// assert!(slab.is_empty());
    /// ```
    pub fn clear(&mut self) {
        // Drop all elements
        let mut slot = self.head;
        while slot != NUL {
            let next = self.vec_next[slot as usize];
            self.data[slot as usize] = None;

            #[cfg(not(feature = "releasefast"))]
            {
                self.bitmap_unset(slot);
            }

            slot = next;
        }

        // Reset the slab state
        let capacity = self.capacity();
        for i in 0..(capacity - 1) {
            self.vec_next[i] = (i + 1) as Slot;
        }
        self.vec_next[capacity - 1] = NUL;

        self.vec_prev[0] = NUL;
        for i in 1..capacity {
            self.vec_prev[i] = (i - 1) as Slot;
        }

        self.free_head = 0;
        self.head = NUL;
        self.tail = NUL;
        self.len = 0;
    }
}

impl<D> Default for Slab<D> {
    /// Creates a new empty slab with a default capacity.
    ///
    /// # Examples
    ///
    /// ```
    /// use slabigator::Slab;
    ///
    /// let slab: Slab<i32> = Slab::default();
    /// assert!(slab.is_empty());
    /// assert_eq!(slab.capacity(), 16);
    /// ```
    fn default() -> Self {
        Self::with_capacity(16).expect("Default capacity should always be valid")
    }
}

impl<D> core::ops::Index<Slot> for Slab<D> {
    type Output = D;

    fn index(&self, slot: Slot) -> &Self::Output {
        self.get(slot).expect("Invalid slot index")
    }
}

impl<D> core::ops::IndexMut<Slot> for Slab<D> {
    fn index_mut(&mut self, slot: Slot) -> &mut Self::Output {
        self.get_mut(slot).expect("Invalid slot index")
    }
}

/// An iterator over the elements of a slab.
///
/// This iterator yields elements from the slab in order from head to tail.
#[derive(Debug)]
pub struct SlabIterator<'a, D> {
    list: &'a Slab<D>,
    slot: Option<Slot>,
}

impl<'a, D> Iterator for SlabIterator<'a, D> {
    type Item = &'a D;

    fn next(&mut self) -> Option<Self::Item> {
        let slot = self.slot.unwrap_or(self.list.head);
        if slot == NUL {
            return None;
        }

        let index = slot as usize;
        let res = self.list.data[index].as_ref()?;

        self.slot = Some(self.list.vec_next[index]);
        Some(res)
    }
}

impl<D> ExactSizeIterator for SlabIterator<'_, D> {
    fn len(&self) -> usize {
        self.list.len()
    }
}

impl<'a, D> DoubleEndedIterator for SlabIterator<'a, D> {
    fn next_back(&mut self) -> Option<&'a D> {
        let slot = self.slot.unwrap_or(self.list.tail);
        if slot == NUL {
            return None;
        }

        let index = slot as usize;
        let res = self.list.data[index].as_ref()?;

        self.slot = Some(self.list.vec_prev[index]);
        Some(res)
    }
}

impl<'a, D> IntoIterator for &'a Slab<D> {
    type IntoIter = SlabIterator<'a, D>;
    type Item = &'a D;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

impl<D: Clone> FromIterator<D> for Slab<D> {
    /// Creates a slab from an iterator.
    ///
    /// The slab will have a capacity equal to the number of elements in the iterator.
    /// Elements are inserted in reverse order, so that iterating the resulting slab
    /// will produce elements in the same order as the original iterator.
    ///
    /// # Examples
    ///
    /// ```
    /// use slabigator::Slab;
    ///
    /// let values = vec![1, 2, 3, 4, 5];
    /// let slab: Slab<_> = values.clone().into_iter().collect();
    ///
    /// // Verify size
    /// assert_eq!(slab.len(), 5);
    ///
    /// // Examine individual slots - elements are stored in reversed order
    /// // from the input sequence since push_front is used internally
    /// assert_eq!(*slab.get(0).unwrap(), 5);
    /// assert_eq!(*slab.get(1).unwrap(), 4);
    /// assert_eq!(*slab.get(2).unwrap(), 3);
    /// assert_eq!(*slab.get(3).unwrap(), 2);
    /// assert_eq!(*slab.get(4).unwrap(), 1);
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if the iterator contains too many elements for the slot type.
    fn from_iter<I: IntoIterator<Item = D>>(iter: I) -> Self {
        let iter = iter.into_iter();
        let (min, max_size) = iter.size_hint();

        // Use max_size if available, otherwise min
        let capacity = max_size.unwrap_or(min);

        // Try to create a slab with the estimated capacity
        let mut slab = Self::with_capacity(capacity).expect("Iterator too large for slab capacity");

        // Insert elements in reverse order (so iterating matches original order)
        let mut vec: Vec<D> = iter.collect();
        while let Some(item) = vec.pop() {
            if slab.push_front(item.clone()).is_err() {
                // If we get here, our size hint was wrong - try to recover by
                // creating a larger slab and moving elements
                let new_capacity = slab.capacity() * 2;
                let mut new_slab = Self::with_capacity(new_capacity)
                    .expect("Iterator too large for slab capacity");

                // Move elements from old slab to new one
                while let Some(old_item) = slab.pop_back() {
                    new_slab
                        .push_front(old_item)
                        .expect("New slab should have enough capacity");
                }

                // Add the current item
                new_slab
                    .push_front(item)
                    .expect("New slab should have enough capacity");

                // Replace with the new slab
                slab = new_slab;
            }
        }

        slab
    }
}

impl<D: Clone> Extend<D> for Slab<D> {
    /// Extends the slab with the elements from an iterator.
    ///
    /// # Examples
    ///
    /// ```
    /// use slabigator::Slab;
    ///
    /// let mut slab = Slab::with_capacity(10).unwrap();
    /// slab.push_front(1).unwrap();
    /// slab.push_front(2).unwrap();
    ///
    /// slab.extend(vec![3, 4, 5]);
    /// assert_eq!(slab.len(), 5);
    ///
    /// // The slot assignment is not sequential but depends on the internal free list.
    /// // We can verify the order by iterating instead.
    /// let items: Vec<_> = slab.iter().copied().collect();
    /// assert_eq!(items, vec![5, 4, 3, 2, 1]);
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if the slab doesn't have enough capacity for all elements in the iterator.
    fn extend<I: IntoIterator<Item = D>>(&mut self, iter: I) {
        for item in iter {
            self.push_front(item).expect("Slab full during extend");
        }
    }
}

// Test implementations
#[test]
fn test() {
    let mut slab = Slab::with_capacity(3).unwrap();
    let a = slab.push_front(Box::new(1)).unwrap();
    let b = slab.push_front(Box::new(2)).unwrap();
    slab.push_front(Box::new(3)).unwrap();
    assert_eq!(slab.len(), 3);
    assert!(slab.push_front(Box::new(4)).is_err());
    slab.remove(a).unwrap();
    slab.remove(b).unwrap();
    assert_eq!(slab.len(), 1);
    let cv = slab.pop_back().unwrap();
    assert_eq!(*cv, 3);
}

#[test]
fn test2() {
    use std::collections::VecDeque;

    use rand::prelude::*;

    let mut rng = rand::rng();
    let capacity = rng.random_range(1..=50);
    let mut slab = Slab::with_capacity(capacity).unwrap();

    let mut c: u64 = 0;
    let mut expected_len: usize = 0;
    let mut deque = VecDeque::with_capacity(capacity);
    for _ in 0..1_000_000 {
        let x = rng.random_range(0..=3);
        match x {
            0 => match slab.push_front(c) {
                Err(_) => {
                    assert!(slab.is_full());
                    assert_eq!(slab.free(), 0);
                }
                Ok(idx) => {
                    deque.push_front(idx);
                    expected_len += 1;
                    assert!(expected_len <= capacity);
                    assert_eq!(slab.free(), capacity - expected_len);
                }
            },
            1 => match slab.pop_back() {
                None => {
                    assert!(slab.is_empty());
                    assert_eq!(slab.free(), capacity);
                }
                Some(_x) => {
                    deque.pop_back().unwrap();
                    expected_len -= 1;
                    assert_eq!(slab.free(), capacity - expected_len);
                    if expected_len == 0 {
                        assert!(slab.is_empty());
                    }
                }
            },
            2 => {
                if slab.is_empty() {
                    continue;
                }
                let deque_len = deque.len();
                if deque_len == 0 {
                    continue;
                }
                let r = rng.random_range(0..deque_len);
                let idx = deque.remove(r).unwrap();
                slab.remove(idx).unwrap();
                expected_len -= 1;
                assert_eq!(slab.free(), capacity - expected_len);
            }
            3 => {
                // Only test slots that we know are valid in the deque
                if deque.is_empty() {
                    continue;
                }
                let r = rng.random_range(0..deque.len());
                let slot = deque[r];

                // Remove from the deque first
                let idx = deque.iter().position(|&x| x == slot).unwrap();
                deque.remove(idx);

                // Then remove from the slab
                slab.remove(slot).unwrap();
                expected_len -= 1;
                assert_eq!(slab.free(), capacity - expected_len);
            }
            _ => unreachable!(),
        }
        assert_eq!(slab.len(), expected_len);
        c += 1;
    }
}

#[test]
fn test_default() {
    let slab: Slab<i32> = Slab::default();
    assert_eq!(slab.capacity(), 16);
    assert_eq!(slab.len(), 0);
    assert!(slab.is_empty());
}

#[test]
fn test_from_iterator() {
    // Create a vector of test values
    let values = vec![1, 2, 3, 4, 5];

    // Create a slab from the vector
    let slab: Slab<i32> = values.clone().into_iter().collect();

    // Verify the length
    assert_eq!(slab.len(), 5);

    // Test the behavior more directly by comparing specific indices

    // The FromIterator implementation uses push_front, which should reverse the order
    // Manual verification of the data through slots
    if slab.len() == 5 {
        assert_eq!(*slab.get(0).unwrap(), 5); // Last element in input, first in slab
        assert_eq!(*slab.get(1).unwrap(), 4);
        assert_eq!(*slab.get(2).unwrap(), 3);
        assert_eq!(*slab.get(3).unwrap(), 2);
        assert_eq!(*slab.get(4).unwrap(), 1); // First element in input, last in slab
    }
}

#[test]
fn test_extend() {
    let mut slab = Slab::with_capacity(5).unwrap();
    slab.push_front(1).unwrap();
    slab.push_front(2).unwrap();

    slab.extend(vec![3, 4, 5]);
    assert_eq!(slab.len(), 5);

    // Collect the items to see what's actually there
    let items: Vec<_> = slab.iter().copied().collect();

    // Elements appear in the reverse order of how they were added
    // push_front(1), push_front(2), then extend with [3,4,5]
    // The extend implementation uses push_front for each element
    assert_eq!(items, vec![5, 4, 3, 2, 1]);
}

#[test]
fn test_clear() {
    let mut slab = Slab::with_capacity(3).unwrap();
    slab.push_front(1).unwrap();
    slab.push_front(2).unwrap();
    slab.push_front(3).unwrap();

    assert_eq!(slab.len(), 3);
    assert!(slab.is_full());

    slab.clear();

    assert_eq!(slab.len(), 0);
    assert!(slab.is_empty());
    assert!(!slab.is_full());

    // Should be able to add elements again
    let a = slab.push_front(4).unwrap();
    let b = slab.push_front(5).unwrap();
    let c = slab.push_front(6).unwrap();

    assert_eq!(slab.len(), 3);
    assert!(slab.is_full());

    // We can get elements by slot
    assert_eq!(*slab.get(a).unwrap(), 4);
    assert_eq!(*slab.get(b).unwrap(), 5);
    assert_eq!(*slab.get(c).unwrap(), 6);
}