asupersync 0.3.1

Spec-first, cancel-correct, capability-secure async runtime for Rust.
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
//! Token slab allocator for waker mapping.
//!
//! This module provides efficient management of I/O source registrations,
//! mapping compact integer tokens to task wakers. When the reactor reports
//! events, the token is used to find and wake the correct task.
//!
//! # Design
//!
//! The slab allocator uses a free list for O(1) allocation and deallocation.
//! Each token includes a generation counter to prevent ABA problems where
//! a freed slot is reallocated and a stale token references the wrong waker.
//!
//! # Example
//!
//! ```ignore
//! use std::task::Waker;
//!
//! let mut slab = TokenSlab::new();
//! let token = slab.insert(waker);
//!
//! // Later, when event arrives:
//! if let Some(waker) = slab.get(token) {
//!     waker.wake_by_ref();
//! }
//!
//! // When deregistering:
//! slab.remove(token);
//! ```

use std::task::Waker;

// SlabToken encodes two u32 fields (index + generation) into usize.
// On 64-bit targets, this is completely lossless (32 bits each).
// On 32-bit targets, it uses 24 bits for the index and 8 bits for the generation.

/// Compact identifier for registered I/O sources.
///
/// Tokens are indexes into a slab allocator. They encode:
/// - Index: which slot in the slab
/// - Generation: catches use-after-free (ABA prevention)
///
/// The generation counter ensures that if a token is freed and the slot
/// is reused, any stale tokens referencing the old allocation will fail
/// to match.
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
pub struct SlabToken {
    index: u32,
    generation: u32,
}

impl SlabToken {
    /// Creates a new token with the given index and generation.
    const fn new(index: u32, generation: u32) -> Self {
        Self { index, generation }
    }

    /// Returns the index portion of the token.
    #[must_use]
    pub const fn index(&self) -> u32 {
        self.index
    }

    /// Returns the generation portion of the token.
    #[must_use]
    pub const fn generation(&self) -> u32 {
        self.generation
    }

    /// Packs the token into a single usize for reactor APIs (mio compatibility).
    ///
    /// On 64-bit platforms: generation is in upper 32 bits, index in lower 32 bits.
    /// On 32-bit platforms: generation is in upper 8 bits, index in lower 24 bits.
    #[must_use]
    pub const fn to_usize(self) -> usize {
        #[cfg(target_pointer_width = "64")]
        {
            ((self.generation as usize) << 32) | (self.index as usize)
        }
        #[cfg(target_pointer_width = "32")]
        {
            ((self.generation as usize & 0xFF) << 24) | (self.index as usize & 0xFF_FFFF)
        }
        #[cfg(not(any(target_pointer_width = "64", target_pointer_width = "32")))]
        {
            0 // Fallback for unsupported platforms
        }
    }

    /// Unpacks a usize into a token.
    #[must_use]
    pub const fn from_usize(val: usize) -> Self {
        #[cfg(target_pointer_width = "64")]
        {
            Self {
                index: val as u32,
                generation: (val >> 32) as u32,
            }
        }
        #[cfg(target_pointer_width = "32")]
        {
            Self {
                index: (val & 0xFF_FFFF) as u32,
                generation: (val >> 24) as u32,
            }
        }
        #[cfg(not(any(target_pointer_width = "64", target_pointer_width = "32")))]
        {
            Self {
                index: 0,
                generation: 0,
            }
        }
    }

    /// The maximum generation value supported on this platform.
    #[cfg(target_pointer_width = "64")]
    pub const MAX_GENERATION: u32 = u32::MAX;

    /// The maximum generation value supported on this platform.
    #[cfg(target_pointer_width = "32")]
    pub const MAX_GENERATION: u32 = 0xFF;

    /// Returns an invalid token that will never match any slab entry.
    #[must_use]
    pub const fn invalid() -> Self {
        Self {
            index: u32::MAX,
            generation: u32::MAX,
        }
    }
}

impl Default for SlabToken {
    fn default() -> Self {
        Self::invalid()
    }
}

/// Entry in the token slab.
#[derive(Debug)]
enum Entry {
    /// Occupied slot with a waker.
    Occupied { waker: Waker, generation: u32 },
    /// Vacant slot pointing to the next free slot.
    Vacant { next_free: u32, generation: u32 },
}

impl Entry {
    /// Returns the generation of this entry.
    fn generation(&self) -> u32 {
        match self {
            Self::Occupied { generation, .. } | Self::Vacant { generation, .. } => *generation,
        }
    }
}

/// Sentinel value indicating end of free list.
const FREE_LIST_END: u32 = u32::MAX;

/// Slab allocator for waker tokens.
///
/// The slab provides O(1) insert, get, and remove operations. It maintains
/// a free list of available slots and tracks generation counters to prevent
/// ABA problems.
///
/// # Thread Safety
///
/// `TokenSlab` is not thread-safe. For concurrent access, wrap it in a
/// synchronization primitive like `Mutex` or use per-thread slabs.
#[derive(Debug)]
pub struct TokenSlab {
    /// Storage for entries.
    entries: Vec<Entry>,
    /// Head of the free list (index of first free slot).
    free_head: u32,
    /// Number of occupied entries.
    len: usize,
}

impl TokenSlab {
    /// Creates a new empty token slab.
    #[must_use]
    pub fn new() -> Self {
        Self {
            entries: Vec::new(),
            free_head: FREE_LIST_END,
            len: 0,
        }
    }

    /// Creates a new token slab with the specified initial capacity.
    #[must_use]
    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            entries: Vec::with_capacity(capacity),
            free_head: FREE_LIST_END,
            len: 0,
        }
    }

    /// Inserts a waker into the slab and returns its token.
    ///
    /// If there's a free slot, it will be reused. Otherwise, a new slot
    /// is allocated at the end.
    pub fn insert(&mut self, waker: Waker) -> SlabToken {
        if self.free_head == FREE_LIST_END {
            // Allocate a new slot.
            let index = self.entries.len() as u32;
            #[cfg(target_pointer_width = "32")]
            assert!(
                index < 0xFF_FFFF,
                "TokenSlab capacity exceeded 16.7M entries on 32-bit platform"
            );
            #[cfg(target_pointer_width = "64")]
            assert!(
                self.entries.len() < u32::MAX as usize,
                "TokenSlab capacity exceeded u32::MAX - 1 (conflicts with FREE_LIST_END)"
            );
            let generation = 0;

            self.entries.push(Entry::Occupied { waker, generation });
            self.len += 1;

            SlabToken::new(index, generation)
        } else {
            // Reuse a free slot.
            let index = self.free_head;
            let entry = &mut self.entries[index as usize];

            // Get generation and next free from the vacant entry.
            let (generation, next_free) = match entry {
                Entry::Vacant {
                    next_free,
                    generation,
                } => (*generation, *next_free),
                Entry::Occupied { .. } => {
                    // This should never happen if our invariants are maintained.
                    unreachable!("free list pointed to occupied entry");
                }
            };

            // Convert to occupied entry (generation incremented on removal).
            *entry = Entry::Occupied { waker, generation };
            self.free_head = next_free;
            self.len += 1;

            SlabToken::new(index, generation)
        }
    }

    /// Returns a reference to the waker associated with the token.
    ///
    /// Returns `None` if the token is invalid, has been removed, or
    /// the generation doesn't match (stale token).
    #[must_use]
    pub fn get(&self, token: SlabToken) -> Option<&Waker> {
        let index = token.index as usize;
        if index >= self.entries.len() {
            return None;
        }

        match &self.entries[index] {
            Entry::Occupied { waker, generation } if *generation == token.generation => Some(waker),
            _ => None,
        }
    }

    /// Returns a mutable reference to the waker associated with the token.
    ///
    /// Returns `None` if the token is invalid, has been removed, or
    /// the generation doesn't match (stale token).
    #[must_use]
    pub fn get_mut(&mut self, token: SlabToken) -> Option<&mut Waker> {
        let index = token.index as usize;
        if index >= self.entries.len() {
            return None;
        }

        match &mut self.entries[index] {
            Entry::Occupied { waker, generation } if *generation == token.generation => Some(waker),
            _ => None,
        }
    }

    /// Removes the waker associated with the token and returns it.
    ///
    /// Returns `None` if the token is invalid, has been removed, or
    /// the generation doesn't match (stale token).
    ///
    /// The slot is added to the free list for reuse. The generation counter
    /// is incremented to invalidate any remaining references to this slot.
    pub fn remove(&mut self, token: SlabToken) -> Option<Waker> {
        let index = token.index as usize;
        if index >= self.entries.len() {
            return None;
        }

        let current_generation = self.entries[index].generation();

        if current_generation != token.generation {
            return None;
        }

        if matches!(self.entries[index], Entry::Occupied { .. }) {
            // Increment generation to invalidate stale tokens.
            let new_generation = current_generation.wrapping_add(1) & SlabToken::MAX_GENERATION;

            if current_generation == SlabToken::MAX_GENERATION {
                // Generation overflow: mark the slot permanently unusable
                // by not adding it back to the free list.
                let old_entry = std::mem::replace(
                    &mut self.entries[index],
                    Entry::Vacant {
                        next_free: FREE_LIST_END,
                        generation: new_generation,
                    },
                );

                self.len -= 1;

                match old_entry {
                    Entry::Occupied { waker, .. } => Some(waker),
                    Entry::Vacant { .. } => unreachable!(),
                }
            } else {
                // Take the waker and convert to vacant.
                let old_entry = std::mem::replace(
                    &mut self.entries[index],
                    Entry::Vacant {
                        next_free: self.free_head,
                        generation: new_generation,
                    },
                );

                self.free_head = index as u32;
                self.len -= 1;

                match old_entry {
                    Entry::Occupied { waker, .. } => Some(waker),
                    Entry::Vacant { .. } => unreachable!(),
                }
            }
        } else {
            None
        }
    }

    /// Returns `true` if the token is valid (points to an occupied entry).
    #[must_use]
    pub fn contains(&self, token: SlabToken) -> bool {
        self.get(token).is_some()
    }

    /// Returns the number of wakers in the slab.
    #[must_use]
    pub fn len(&self) -> usize {
        self.len
    }

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

    /// Returns the total capacity (including free slots).
    #[must_use]
    pub fn capacity(&self) -> usize {
        self.entries.capacity()
    }

    /// Clears all entries from the slab.
    pub fn clear(&mut self) {
        self.free_head = FREE_LIST_END;
        for index in (0..self.entries.len()).rev() {
            let current_generation = self.entries[index].generation();
            let generation = current_generation.wrapping_add(1) & SlabToken::MAX_GENERATION;
            if current_generation == SlabToken::MAX_GENERATION {
                self.entries[index] = Entry::Vacant {
                    next_free: FREE_LIST_END,
                    generation,
                };
            } else {
                self.entries[index] = Entry::Vacant {
                    next_free: self.free_head,
                    generation,
                };
                self.free_head = index as u32;
            }
        }
        self.len = 0;
    }

    /// Retains only the wakers that satisfy the predicate.
    ///
    /// Wakers for which the predicate returns `false` are removed.
    pub fn retain<F>(&mut self, mut f: F)
    where
        F: FnMut(SlabToken, &Waker) -> bool,
    {
        for index in 0..self.entries.len() {
            let mut remove = false;
            let current_generation = self.entries[index].generation();

            if let Entry::Occupied { waker, generation } = &self.entries[index] {
                let token = SlabToken::new(index as u32, *generation);
                if !f(token, waker) {
                    remove = true;
                }
            }

            if remove {
                let new_generation = current_generation.wrapping_add(1) & SlabToken::MAX_GENERATION;
                if current_generation == SlabToken::MAX_GENERATION {
                    self.entries[index] = Entry::Vacant {
                        next_free: FREE_LIST_END,
                        generation: new_generation,
                    };
                } else {
                    self.entries[index] = Entry::Vacant {
                        next_free: self.free_head,
                        generation: new_generation,
                    };
                    self.free_head = index as u32;
                }
                self.len -= 1;
            }
        }
    }

    /// Iterates over all occupied entries.
    pub fn iter(&self) -> impl Iterator<Item = (SlabToken, &Waker)> {
        self.entries
            .iter()
            .enumerate()
            .filter_map(|(index, entry)| {
                if let Entry::Occupied { waker, generation } = entry {
                    Some((SlabToken::new(index as u32, *generation), waker))
                } else {
                    None
                }
            })
    }
}

impl Default for TokenSlab {
    fn default() -> Self {
        Self::new()
    }
}

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

    fn test_waker() -> Waker {
        std::task::Waker::noop().clone()
    }

    fn init_test(name: &str) {
        init_test_logging();
        crate::test_phase!(name);
    }

    #[test]
    fn token_pack_unpack() {
        init_test("token_pack_unpack");
        let token = SlabToken::new(42, 7);
        let packed = token.to_usize();
        let unpacked = SlabToken::from_usize(packed);

        crate::assert_with_log!(token == unpacked, "token round-trip", token, unpacked);
        crate::assert_with_log!(
            unpacked.index() == 42,
            "index round-trip",
            42u32,
            unpacked.index()
        );
        crate::assert_with_log!(
            unpacked.generation() == 7,
            "generation round-trip",
            7u32,
            unpacked.generation()
        );
        crate::test_complete!("token_pack_unpack");
    }

    #[test]
    fn token_pack_unpack_max_values() {
        init_test("token_pack_unpack_max_values");
        #[cfg(target_pointer_width = "64")]
        let max_index = u32::MAX - 1;
        #[cfg(target_pointer_width = "32")]
        let max_index = 0xFF_FFFF - 1;

        let token = SlabToken::new(max_index, SlabToken::MAX_GENERATION);
        let packed = token.to_usize();
        let unpacked = SlabToken::from_usize(packed);

        crate::assert_with_log!(token == unpacked, "max token round-trip", token, unpacked);
        crate::test_complete!("token_pack_unpack_max_values");
    }

    #[test]
    fn slab_insert_and_get() {
        init_test("slab_insert_and_get");
        let mut slab = TokenSlab::new();
        let waker = test_waker();

        let token = slab.insert(waker);

        crate::assert_with_log!(slab.len() == 1, "len after insert", 1usize, slab.len());
        crate::assert_with_log!(!slab.is_empty(), "slab not empty", false, slab.is_empty());
        let contains = slab.contains(token);
        crate::assert_with_log!(contains, "slab contains token", true, contains);
        let get_some = slab.get(token).is_some();
        crate::assert_with_log!(get_some, "slab get returns", true, get_some);
        crate::test_complete!("slab_insert_and_get");
    }

    #[test]
    fn slab_remove() {
        init_test("slab_remove");
        let mut slab = TokenSlab::new();
        let waker = test_waker();

        let token = slab.insert(waker);
        let removed = slab.remove(token);

        crate::assert_with_log!(
            removed.is_some(),
            "remove returns some",
            true,
            removed.is_some()
        );
        crate::assert_with_log!(slab.is_empty(), "len after remove", 0usize, slab.len());
        crate::assert_with_log!(
            slab.is_empty(),
            "slab empty after remove",
            true,
            slab.is_empty()
        );
        let contains = slab.contains(token);
        crate::assert_with_log!(!contains, "token removed", false, contains);
        let get_none = slab.get(token).is_none();
        crate::assert_with_log!(get_none, "get returns none", true, get_none);
        crate::test_complete!("slab_remove");
    }

    #[test]
    fn slab_generation_prevents_aba() {
        init_test("slab_generation_prevents_aba");
        let mut slab = TokenSlab::new();

        // Insert first waker.
        let token1 = slab.insert(test_waker());
        crate::assert_with_log!(
            token1.generation() == 0,
            "initial generation",
            0u32,
            token1.generation()
        );

        // Remove it.
        slab.remove(token1);

        // Insert second waker (reuses the slot).
        let token2 = slab.insert(test_waker());
        crate::assert_with_log!(
            token2.index() == token1.index(),
            "slot reused",
            token1.index(),
            token2.index()
        );
        crate::assert_with_log!(
            token2.generation() == 1,
            "generation incremented",
            1u32,
            token2.generation()
        );

        // Old token should not work.
        let contains_old = slab.contains(token1);
        crate::assert_with_log!(!contains_old, "old token invalid", false, contains_old);
        let old_get = slab.get(token1).is_none();
        crate::assert_with_log!(old_get, "old token get none", true, old_get);

        // New token should work.
        let contains_new = slab.contains(token2);
        crate::assert_with_log!(contains_new, "new token valid", true, contains_new);
        let new_get = slab.get(token2).is_some();
        crate::assert_with_log!(new_get, "new token get some", true, new_get);
        crate::test_complete!("slab_generation_prevents_aba");
    }

    #[test]
    fn slab_reuses_free_slots() {
        init_test("slab_reuses_free_slots");
        let mut slab = TokenSlab::new();

        // Insert three wakers.
        let t1 = slab.insert(test_waker());
        let t2 = slab.insert(test_waker());
        let t3 = slab.insert(test_waker());

        crate::assert_with_log!(slab.len() == 3, "len after inserts", 3usize, slab.len());

        // Remove the middle one.
        slab.remove(t2);
        crate::assert_with_log!(slab.len() == 2, "len after remove", 2usize, slab.len());

        // Insert a new one - should reuse t2's slot.
        let t4 = slab.insert(test_waker());
        crate::assert_with_log!(
            t4.index() == t2.index(),
            "reused slot index",
            t2.index(),
            t4.index()
        );
        crate::assert_with_log!(
            t4.generation() != t2.generation(),
            "generation advanced",
            true,
            t4.generation() != t2.generation()
        );

        // Old tokens still work.
        let contains_t1 = slab.contains(t1);
        let contains_t3 = slab.contains(t3);
        let contains_t4 = slab.contains(t4);
        let contains_t2 = slab.contains(t2);
        crate::assert_with_log!(contains_t1, "t1 still valid", true, contains_t1);
        crate::assert_with_log!(contains_t3, "t3 still valid", true, contains_t3);
        crate::assert_with_log!(contains_t4, "t4 valid", true, contains_t4);
        crate::assert_with_log!(!contains_t2, "t2 invalidated", false, contains_t2);
        crate::test_complete!("slab_reuses_free_slots");
    }

    #[test]
    fn slab_multiple_inserts_removes() {
        init_test("slab_multiple_inserts_removes");
        let mut slab = TokenSlab::new();
        let mut tokens = Vec::new();

        // Insert many wakers.
        for _ in 0..100 {
            tokens.push(slab.insert(test_waker()));
        }
        crate::assert_with_log!(slab.len() == 100, "len after inserts", 100usize, slab.len());

        // Remove every other one.
        for i in (0..100).step_by(2) {
            slab.remove(tokens[i]);
        }
        crate::assert_with_log!(slab.len() == 50, "len after removes", 50usize, slab.len());

        // Insert more.
        for _ in 0..25 {
            tokens.push(slab.insert(test_waker()));
        }
        crate::assert_with_log!(slab.len() == 75, "len after reinserts", 75usize, slab.len());
        crate::test_complete!("slab_multiple_inserts_removes");
    }

    #[test]
    fn slab_get_invalid_index() {
        init_test("slab_get_invalid_index");
        let slab = TokenSlab::new();
        let token = SlabToken::new(999, 0);

        let contains = slab.contains(token);
        crate::assert_with_log!(!contains, "invalid token not contained", false, contains);
        let get_none = slab.get(token).is_none();
        crate::assert_with_log!(get_none, "invalid token get none", true, get_none);
        crate::test_complete!("slab_get_invalid_index");
    }

    #[test]
    fn slab_remove_invalid_generation() {
        init_test("slab_remove_invalid_generation");
        let mut slab = TokenSlab::new();

        let token = slab.insert(test_waker());
        let stale_token = SlabToken::new(token.index(), token.generation() + 1);

        // Remove with wrong generation should fail.
        let removed = slab.remove(stale_token).is_none();
        crate::assert_with_log!(removed, "stale remove fails", true, removed);
        // Original token should still work.
        let contains = slab.contains(token);
        crate::assert_with_log!(contains, "original token still valid", true, contains);
        crate::test_complete!("slab_remove_invalid_generation");
    }

    #[test]
    fn slab_double_remove() {
        init_test("slab_double_remove");
        let mut slab = TokenSlab::new();

        let token = slab.insert(test_waker());
        let removed1 = slab.remove(token);
        let removed2 = slab.remove(token);

        crate::assert_with_log!(
            removed1.is_some(),
            "first remove succeeds",
            true,
            removed1.is_some()
        );
        crate::assert_with_log!(
            removed2.is_none(),
            "second remove fails",
            true,
            removed2.is_none()
        );
        crate::test_complete!("slab_double_remove");
    }

    #[test]
    fn slab_clear() {
        init_test("slab_clear");
        let mut slab = TokenSlab::new();

        for _ in 0..10 {
            slab.insert(test_waker());
        }
        crate::assert_with_log!(slab.len() == 10, "len before clear", 10usize, slab.len());

        slab.clear();
        crate::assert_with_log!(slab.is_empty(), "len after clear", 0usize, slab.len());
        crate::assert_with_log!(
            slab.is_empty(),
            "slab empty after clear",
            true,
            slab.is_empty()
        );
        crate::test_complete!("slab_clear");
    }

    #[test]
    fn slab_retain() {
        init_test("slab_retain");
        let mut slab = TokenSlab::new();

        let tokens: Vec<_> = (0..10).map(|_| slab.insert(test_waker())).collect();
        crate::assert_with_log!(slab.len() == 10, "len before retain", 10usize, slab.len());

        // Keep only even indices.
        slab.retain(|token, _| token.index() % 2 == 0);
        crate::assert_with_log!(slab.len() == 5, "len after retain", 5usize, slab.len());

        // Verify even tokens are retained, odd are removed.
        for (i, token) in tokens.iter().enumerate() {
            let contains = slab.contains(*token);
            if i % 2 == 0 {
                crate::assert_with_log!(contains, "even token retained", true, contains);
            } else {
                crate::assert_with_log!(!contains, "odd token removed", false, contains);
            }
        }
        crate::test_complete!("slab_retain");
    }

    #[test]
    fn slab_iter() {
        init_test("slab_iter");
        let mut slab = TokenSlab::new();

        let tokens: Vec<_> = (0..5).map(|_| slab.insert(test_waker())).collect();

        // Remove one.
        slab.remove(tokens[2]);

        // Iterate - should see 4 entries.
        let iter_tokens: Vec<_> = slab.iter().map(|(t, _)| t).collect();
        crate::assert_with_log!(
            iter_tokens.len() == 4,
            "iter length",
            4usize,
            iter_tokens.len()
        );
        let contains_0 = iter_tokens.contains(&tokens[0]);
        let contains_1 = iter_tokens.contains(&tokens[1]);
        let contains_2 = iter_tokens.contains(&tokens[2]);
        let contains_3 = iter_tokens.contains(&tokens[3]);
        let contains_4 = iter_tokens.contains(&tokens[4]);
        crate::assert_with_log!(contains_0, "iter contains token 0", true, contains_0);
        crate::assert_with_log!(contains_1, "iter contains token 1", true, contains_1);
        crate::assert_with_log!(!contains_2, "iter omits removed", false, contains_2);
        crate::assert_with_log!(contains_3, "iter contains token 3", true, contains_3);
        crate::assert_with_log!(contains_4, "iter contains token 4", true, contains_4);
        crate::test_complete!("slab_iter");
    }

    #[test]
    fn slab_with_capacity() {
        init_test("slab_with_capacity");
        let slab = TokenSlab::with_capacity(100);
        crate::assert_with_log!(
            slab.capacity() >= 100,
            "capacity at least requested",
            true,
            slab.capacity() >= 100
        );
        crate::assert_with_log!(slab.is_empty(), "slab starts empty", true, slab.is_empty());
        crate::test_complete!("slab_with_capacity");
    }

    #[test]
    fn token_invalid() {
        init_test("token_invalid");
        let token = SlabToken::invalid();
        crate::assert_with_log!(
            token.index() == u32::MAX,
            "invalid index",
            u32::MAX,
            token.index()
        );
        crate::assert_with_log!(
            token.generation() == u32::MAX,
            "invalid generation",
            u32::MAX,
            token.generation()
        );
        crate::test_complete!("token_invalid");
    }

    #[test]
    fn slab_get_mut() {
        init_test("slab_get_mut");
        let mut slab = TokenSlab::new();

        let token = slab.insert(test_waker());

        // Get mutable reference.
        let has_mut = slab.get_mut(token).is_some();
        crate::assert_with_log!(has_mut, "get_mut succeeds", true, has_mut);

        // Remove and try again.
        slab.remove(token);
        let has_mut_after = slab.get_mut(token).is_none();
        crate::assert_with_log!(has_mut_after, "get_mut after remove", true, has_mut_after);
        crate::test_complete!("slab_get_mut");
    }

    #[test]
    fn slab_clear_invalidates_stale_tokens() {
        init_test("slab_clear_invalidates_stale_tokens");
        let mut slab = TokenSlab::new();

        let stale = slab.insert(test_waker());
        slab.clear();

        let contains_stale = slab.contains(stale);
        crate::assert_with_log!(
            !contains_stale,
            "stale token invalid after clear",
            false,
            contains_stale
        );

        let fresh = slab.insert(test_waker());
        crate::assert_with_log!(
            fresh.index() == stale.index(),
            "slot reused after clear",
            stale.index(),
            fresh.index()
        );
        crate::assert_with_log!(
            fresh.generation() != stale.generation(),
            "generation advanced across clear",
            true,
            fresh.generation() != stale.generation()
        );
        crate::assert_with_log!(
            slab.get(stale).is_none(),
            "old token still rejected after reuse",
            true,
            slab.get(stale).is_none()
        );
        crate::test_complete!("slab_clear_invalidates_stale_tokens");
    }

    #[test]
    fn token_default() {
        init_test("token_default");
        let token = SlabToken::default();
        crate::assert_with_log!(
            token == SlabToken::invalid(),
            "default is invalid",
            SlabToken::invalid(),
            token
        );
        crate::test_complete!("token_default");
    }

    #[test]
    fn slab_token_debug_clone_copy_hash() {
        use std::collections::HashSet;

        let t = SlabToken::from_usize(42);
        let dbg = format!("{t:?}");
        assert!(dbg.contains("SlabToken"));

        let t2 = t;
        assert_eq!(t, t2);

        // Copy
        let t3 = t;
        assert_eq!(t, t3);

        // Hash
        let mut set = HashSet::new();
        set.insert(t);
        set.insert(SlabToken::from_usize(99));
        assert_eq!(set.len(), 2);
        assert!(set.contains(&t));
    }
}