-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathintrusive_list.rs
More file actions
2591 lines (2331 loc) · 79.1 KB
/
intrusive_list.rs
File metadata and controls
2591 lines (2331 loc) · 79.1 KB
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
//! Intrusive doubly linked list backed by [`SlotArena`].
//!
//! Stores list nodes in a [`SlotArena`] and links them via
//! [`SlotId`], enabling stable handles and O(1) splice/move
//! operations. Ideal for LRU ordering, eviction queues, and policy metadata.
//!
//! ## Architecture
//!
//! ```text
//! ┌──────────────────────────────────────────────────────────────────────────┐
//! │ IntrusiveList Layout │
//! │ │
//! │ ┌─────────────────────────────────────────────────────────────────┐ │
//! │ │ arena: SlotArena<Node<T>> │ │
//! │ │ │ │
//! │ │ ┌────────┬─────────────────────────────────────────────────┐ │ │
//! │ │ │ SlotId │ Node { value, prev, next, epoch } │ │ │
//! │ │ ├────────┼─────────────────────────────────────────────────┤ │ │
//! │ │ │ id_0 │ { "A", prev: None, next: Some(id_1), 0 } │ │ │
//! │ │ │ id_1 │ { "B", prev: Some(id_0), next: Some(id_2), 0 } │ │ │
//! │ │ │ id_2 │ { "C", prev: Some(id_1), next: None, 0 } │ │ │
//! │ │ └────────┴─────────────────────────────────────────────────┘ │ │
//! │ └─────────────────────────────────────────────────────────────────┘ │
//! │ │
//! │ Doubly Linked Structure: │
//! │ │
//! │ head tail │
//! │ │ │ │
//! │ ▼ ▼ │
//! │ ┌──────┐ ┌──────┐ ┌──────┐ │
//! │ │ id_0 │ ◄──► │ id_1 │ ◄──► │ id_2 │ │
//! │ │ "A" │ │ "B" │ │ "C" │ │
//! │ └──────┘ └──────┘ └──────┘ │
//! │ MRU LRU │
//! │ (front) (back) │
//! └──────────────────────────────────────────────────────────────────────────┘
//!
//! Move to Front (LRU access pattern)
//! ───────────────────────────────────
//! move_to_front(id_2):
//!
//! Before: head ──► [A] ◄──► [B] ◄──► [C] ◄── tail
//!
//! 1. Detach id_2: [A] ◄──► [B] [C]
//! 2. Update tail: [A] ◄──► [B] ◄── tail
//! 3. Attach front: [C] ◄──► [A] ◄──► [B]
//! 4. Update head: head ──► [C]
//!
//! After: head ──► [C] ◄──► [A] ◄──► [B] ◄── tail
//!
//! List Variants
//! ─────────────
//! ┌─────────────────────────────────────────────────────────────────────┐
//! │ IntrusiveList<T> Single-threaded, direct &T access │
//! ├─────────────────────────────────────────────────────────────────────┤
//! │ ConcurrentIntrusiveList<T> Thread-safe via RwLock │
//! │ Uses closures: get_with(id, |v| ...) │
//! └─────────────────────────────────────────────────────────────────────┘
//! ```
//!
//! ## Key Components
//!
//! - [`IntrusiveList`]: Single-threaded doubly linked list
//! - [`ConcurrentIntrusiveList`]: Thread-safe wrapper with `RwLock`
//! - [`SlotId`]: Stable handle for O(1) node access
//!
//! ## Operations
//!
//! | Operation | Description | Complexity |
//! |-----------------|------------------------------------|------------|
//! | `push_front` | Insert at head | O(1) |
//! | `push_back` | Insert at tail | O(1) |
//! | `pop_front` | Remove and return head | O(1) |
//! | `pop_back` | Remove and return tail | O(1) |
//! | `move_to_front` | Move existing node to head | O(1) |
//! | `move_to_back` | Move existing node to tail | O(1) |
//! | `remove` | Remove node by SlotId | O(1) |
//! | `get` / `get_mut` | Access value by SlotId | O(1) |
//! | `iter` | Iterate front to back | O(n) |
//!
//! ## Use Cases
//!
//! - **LRU cache ordering**: Move accessed items to front, evict from back
//! - **FIFO queues**: Push to back, pop from front
//! - **Eviction policies**: Track recency with O(1) reordering
//!
//! ## Example Usage
//!
//! ```
//! use cachekit::ds::IntrusiveList;
//!
//! let mut list = IntrusiveList::new();
//!
//! // Build LRU order: most recent at front
//! let a = list.push_back("page_a");
//! let b = list.push_back("page_b");
//! let c = list.push_back("page_c");
//!
//! // Access "page_a" - move to front (MRU)
//! list.move_to_front(a);
//!
//! // Order is now: page_a, page_b, page_c
//! assert_eq!(list.front(), Some(&"page_a"));
//! assert_eq!(list.back(), Some(&"page_c"));
//!
//! // Evict LRU (back)
//! let evicted = list.pop_back();
//! assert_eq!(evicted, Some("page_c"));
//! ```
//!
//! ## Epoch Tracking
//!
//! Nodes can store an `epoch` value for versioning or timestamp tracking:
//!
//! ```
//! use cachekit::ds::IntrusiveList;
//!
//! let mut list = IntrusiveList::new();
//! let id = list.push_front_with_epoch("data", 42);
//!
//! assert_eq!(list.epoch(id), Some(42));
//! list.set_epoch(id, 100);
//! assert_eq!(list.epoch(id), Some(100));
//! ```
//!
//! ## Thread Safety
//!
//! - [`IntrusiveList`]: Not thread-safe, use in single-threaded contexts
//! - [`ConcurrentIntrusiveList`]: Thread-safe via `parking_lot::RwLock`
//!
//! ## Implementation Notes
//!
//! - Backed by [`SlotArena`] for stable handles
//! - No pointer chasing; links are `SlotId` indices
//! - `debug_validate_invariants()` available in debug/test builds
#[cfg(feature = "concurrency")]
use parking_lot::RwLock;
use std::iter::FusedIterator;
use crate::ds::slot_arena::{SlotArena, SlotId};
/// Internal node with cache-line optimized layout.
/// Link pointers (prev/next) are placed first as they're accessed on every
/// list operation. Epoch is used for versioning. Value is accessed last.
#[derive(Debug, Clone)]
#[repr(C)]
struct Node<T> {
// Hot fields - accessed during every list traversal
prev: Option<SlotId>,
next: Option<SlotId>,
epoch: u64,
// Cold field - accessed on get/peek
value: T,
}
/// Doubly linked list backed by [`SlotArena`].
///
/// Provides O(1) insertion, removal, and reordering operations. Each node
/// is identified by a stable [`SlotId`] that remains valid
/// until the node is removed.
///
/// # Example
///
/// ```
/// use cachekit::ds::IntrusiveList;
///
/// let mut list = IntrusiveList::new();
///
/// // Insert nodes
/// let a = list.push_front("first");
/// let b = list.push_back("second");
/// let c = list.push_back("third");
///
/// // Access by position
/// assert_eq!(list.front(), Some(&"first"));
/// assert_eq!(list.back(), Some(&"third"));
///
/// // Reorder: move "third" to front
/// list.move_to_front(c);
/// assert_eq!(list.front(), Some(&"third"));
///
/// // Remove by handle
/// assert_eq!(list.remove(b), Some("second"));
/// assert_eq!(list.len(), 2);
/// ```
///
/// # Use Case: LRU Eviction Order
///
/// ```
/// use cachekit::ds::IntrusiveList;
///
/// let mut lru: IntrusiveList<&str> = IntrusiveList::new();
///
/// // Insert items (oldest at back)
/// let page1 = lru.push_back("page1");
/// let page2 = lru.push_back("page2");
/// let page3 = lru.push_back("page3");
///
/// // Access page3 - move to front (most recently used)
/// lru.move_to_front(page3);
/// // Order: page3, page1, page2
///
/// // Evict LRU (back)
/// assert_eq!(lru.pop_back(), Some("page2")); // page2 is now oldest
/// ```
#[derive(Debug, Clone)]
pub struct IntrusiveList<T> {
arena: SlotArena<Node<T>>,
head: Option<SlotId>,
tail: Option<SlotId>,
}
impl<T> IntrusiveList<T> {
/// Worst-case heap bytes consumed per filled slot, excluding the
/// fixed-size outer struct.
///
/// This is the exact compile-time sum of the per-slot footprint of
/// the backing [`SlotArena`]:
///
/// - `size_of::<Option<Node<T>>>()` for the payload (`T` plus the
/// prev/next/epoch link overhead and the arena's live/empty
/// discriminant, including alignment padding).
/// - `size_of::<u32>()` for the generation counter.
/// - `size_of::<usize>()` for a free-list entry (one per slot in the
/// worst case, when every slot has been reused).
///
/// Intended for callers that need to budget a hard upper bound on a
/// list's memory footprint at a given capacity (e.g. when clamping
/// untrusted capacity values to a byte budget). Because it is derived
/// directly from the real internal types, it stays correct under any
/// future change to the node layout.
pub const BYTES_PER_ENTRY: usize = std::mem::size_of::<Option<Node<T>>>()
+ std::mem::size_of::<u32>()
+ std::mem::size_of::<usize>();
/// Creates an empty list.
///
/// # Example
///
/// ```
/// use cachekit::ds::IntrusiveList;
///
/// let list: IntrusiveList<i32> = IntrusiveList::new();
/// assert!(list.is_empty());
/// ```
pub fn new() -> Self {
Self {
arena: SlotArena::new(),
head: None,
tail: None,
}
}
/// Creates an empty list with pre-allocated node capacity.
///
/// # Example
///
/// ```
/// use cachekit::ds::IntrusiveList;
///
/// let list: IntrusiveList<String> = IntrusiveList::with_capacity(1000);
/// assert!(list.is_empty());
/// ```
pub fn with_capacity(capacity: usize) -> Self {
Self {
arena: SlotArena::with_capacity(capacity),
head: None,
tail: None,
}
}
/// Returns the number of nodes in the list.
///
/// # Example
///
/// ```
/// use cachekit::ds::IntrusiveList;
///
/// let mut list = IntrusiveList::new();
/// assert_eq!(list.len(), 0);
///
/// list.push_back(1);
/// list.push_back(2);
/// assert_eq!(list.len(), 2);
/// ```
#[inline]
pub fn len(&self) -> usize {
self.arena.len()
}
/// Returns `true` if the list is empty.
///
/// # Example
///
/// ```
/// use cachekit::ds::IntrusiveList;
///
/// let mut list = IntrusiveList::new();
/// assert!(list.is_empty());
///
/// list.push_back(1);
/// assert!(!list.is_empty());
/// ```
#[inline]
pub fn is_empty(&self) -> bool {
self.arena.is_empty()
}
/// Returns `true` if `id` is currently a node in this list.
///
/// # Example
///
/// ```
/// use cachekit::ds::IntrusiveList;
///
/// let mut list = IntrusiveList::new();
/// let id = list.push_back("value");
///
/// assert!(list.contains(id));
/// list.remove(id);
/// assert!(!list.contains(id));
/// ```
#[inline]
pub fn contains(&self, id: SlotId) -> bool {
self.arena.contains(id)
}
/// Returns the value at the front (head/MRU) of the list.
///
/// # Example
///
/// ```
/// use cachekit::ds::IntrusiveList;
///
/// let mut list = IntrusiveList::new();
/// assert_eq!(list.front(), None);
///
/// list.push_front("first");
/// list.push_back("second");
/// assert_eq!(list.front(), Some(&"first"));
/// ```
#[inline]
pub fn front(&self) -> Option<&T> {
self.head
.and_then(|id| self.arena.get(id).map(|node| &node.value))
}
/// Returns the [`SlotId`] at the front.
///
/// # Example
///
/// ```
/// use cachekit::ds::IntrusiveList;
///
/// let mut list = IntrusiveList::new();
/// let id = list.push_front("value");
/// assert_eq!(list.front_id(), Some(id));
/// ```
#[inline]
pub fn front_id(&self) -> Option<SlotId> {
self.head
}
/// Returns the value at the back (tail/LRU) of the list.
///
/// # Example
///
/// ```
/// use cachekit::ds::IntrusiveList;
///
/// let mut list = IntrusiveList::new();
/// list.push_back("first");
/// list.push_back("second");
/// assert_eq!(list.back(), Some(&"second"));
/// ```
#[inline]
pub fn back(&self) -> Option<&T> {
self.tail
.and_then(|id| self.arena.get(id).map(|node| &node.value))
}
/// Returns the [`SlotId`] at the back.
///
/// # Example
///
/// ```
/// use cachekit::ds::IntrusiveList;
///
/// let mut list = IntrusiveList::new();
/// list.push_back("first");
/// let id = list.push_back("second");
/// assert_eq!(list.back_id(), Some(id));
/// ```
#[inline]
pub fn back_id(&self) -> Option<SlotId> {
self.tail
}
/// Returns an iterator over values from front to back.
///
/// # Example
///
/// ```
/// use cachekit::ds::IntrusiveList;
///
/// let mut list = IntrusiveList::new();
/// list.push_back(1);
/// list.push_back(2);
/// list.push_back(3);
///
/// let values: Vec<_> = list.iter().copied().collect();
/// assert_eq!(values, vec![1, 2, 3]);
/// ```
pub fn iter(&self) -> IntrusiveListIter<'_, T> {
IntrusiveListIter {
list: self,
current: self.head,
}
}
/// Returns an iterator of [`SlotId`]s from front to back.
///
/// # Example
///
/// ```
/// use cachekit::ds::IntrusiveList;
///
/// let mut list = IntrusiveList::new();
/// let a = list.push_back("a");
/// let b = list.push_back("b");
///
/// let ids: Vec<_> = list.iter_ids().collect();
/// assert_eq!(ids, vec![a, b]);
/// ```
pub fn iter_ids(&self) -> IntrusiveListIdIter<'_, T> {
IntrusiveListIdIter {
list: self,
current: self.head,
}
}
/// Returns an iterator of `(SlotId, &T)` pairs from front to back.
///
/// # Example
///
/// ```
/// use cachekit::ds::IntrusiveList;
///
/// let mut list = IntrusiveList::new();
/// let a = list.push_back("a");
/// let b = list.push_back("b");
///
/// let entries: Vec<_> = list.iter_entries().map(|(id, v)| (id, *v)).collect();
/// assert_eq!(entries, vec![(a, "a"), (b, "b")]);
/// ```
pub fn iter_entries(&self) -> IntrusiveListEntryIter<'_, T> {
IntrusiveListEntryIter {
list: self,
current: self.head,
}
}
/// Returns the value for a node by its [`SlotId`].
///
/// # Example
///
/// ```
/// use cachekit::ds::IntrusiveList;
///
/// let mut list = IntrusiveList::new();
/// let id = list.push_back(42);
///
/// assert_eq!(list.get(id), Some(&42));
/// ```
#[inline]
pub fn get(&self, id: SlotId) -> Option<&T> {
self.arena.get(id).map(|node| &node.value)
}
/// Returns a mutable reference to a node's value.
///
/// # Example
///
/// ```
/// use cachekit::ds::IntrusiveList;
///
/// let mut list = IntrusiveList::new();
/// let id = list.push_back(1);
///
/// if let Some(v) = list.get_mut(id) {
/// *v = 2;
/// }
/// assert_eq!(list.get(id), Some(&2));
/// ```
#[inline]
pub fn get_mut(&mut self, id: SlotId) -> Option<&mut T> {
self.arena.get_mut(id).map(|node| &mut node.value)
}
/// Inserts a value at the front and returns its [`SlotId`].
///
/// # Example
///
/// ```
/// use cachekit::ds::IntrusiveList;
///
/// let mut list = IntrusiveList::new();
/// list.push_back("second");
/// list.push_front("first");
///
/// assert_eq!(list.front(), Some(&"first"));
/// ```
#[inline]
pub fn push_front(&mut self, value: T) -> SlotId {
self.push_front_with_epoch(value, 0)
}
/// Inserts a value at the front with an epoch and returns its [`SlotId`].
///
/// # Example
///
/// ```
/// use cachekit::ds::IntrusiveList;
///
/// let mut list = IntrusiveList::new();
/// let id = list.push_front_with_epoch("data", 42);
///
/// assert_eq!(list.epoch(id), Some(42));
/// ```
#[inline]
pub fn push_front_with_epoch(&mut self, value: T, epoch: u64) -> SlotId {
let id = self.arena.insert(Node {
value,
prev: None,
next: self.head,
epoch,
});
if let Some(head) = self.head {
if let Some(node) = self.arena.get_mut(head) {
node.prev = Some(id);
}
} else {
self.tail = Some(id);
}
self.head = Some(id);
id
}
/// Inserts a value at the back and returns its [`SlotId`].
///
/// # Example
///
/// ```
/// use cachekit::ds::IntrusiveList;
///
/// let mut list = IntrusiveList::new();
/// list.push_back("first");
/// list.push_back("second");
///
/// assert_eq!(list.back(), Some(&"second"));
/// ```
#[inline]
pub fn push_back(&mut self, value: T) -> SlotId {
self.push_back_with_epoch(value, 0)
}
/// Inserts a value at the back with an epoch and returns its [`SlotId`].
///
/// # Example
///
/// ```
/// use cachekit::ds::IntrusiveList;
///
/// let mut list = IntrusiveList::new();
/// let id = list.push_back_with_epoch("data", 99);
///
/// assert_eq!(list.epoch(id), Some(99));
/// ```
#[inline]
pub fn push_back_with_epoch(&mut self, value: T, epoch: u64) -> SlotId {
let id = self.arena.insert(Node {
value,
prev: self.tail,
next: None,
epoch,
});
if let Some(tail) = self.tail {
if let Some(node) = self.arena.get_mut(tail) {
node.next = Some(id);
}
} else {
self.head = Some(id);
}
self.tail = Some(id);
id
}
/// Returns the epoch recorded for `id`, if present.
///
/// # Example
///
/// ```
/// use cachekit::ds::IntrusiveList;
///
/// let mut list = IntrusiveList::new();
/// let id = list.push_front_with_epoch("item", 5);
///
/// assert_eq!(list.epoch(id), Some(5));
/// ```
pub fn epoch(&self, id: SlotId) -> Option<u64> {
self.arena.get(id).map(|node| node.epoch)
}
/// Sets the epoch for `id`; returns `false` if `id` is not present.
///
/// # Example
///
/// ```
/// use cachekit::ds::IntrusiveList;
///
/// let mut list = IntrusiveList::new();
/// let id = list.push_back("item");
///
/// assert!(list.set_epoch(id, 10));
/// assert_eq!(list.epoch(id), Some(10));
/// ```
pub fn set_epoch(&mut self, id: SlotId, epoch: u64) -> bool {
if let Some(node) = self.arena.get_mut(id) {
node.epoch = epoch;
true
} else {
false
}
}
/// Removes and returns the front value.
///
/// # Example
///
/// ```
/// use cachekit::ds::IntrusiveList;
///
/// let mut list = IntrusiveList::new();
/// list.push_back(1);
/// list.push_back(2);
///
/// assert_eq!(list.pop_front(), Some(1));
/// assert_eq!(list.pop_front(), Some(2));
/// assert_eq!(list.pop_front(), None);
/// ```
#[inline]
pub fn pop_front(&mut self) -> Option<T> {
let id = self.head?;
self.detach(id)?;
self.arena.remove(id).map(|node| node.value)
}
/// Removes and returns the back value.
///
/// # Example
///
/// ```
/// use cachekit::ds::IntrusiveList;
///
/// let mut list = IntrusiveList::new();
/// list.push_back(1);
/// list.push_back(2);
///
/// assert_eq!(list.pop_back(), Some(2));
/// assert_eq!(list.pop_back(), Some(1));
/// assert_eq!(list.pop_back(), None);
/// ```
#[inline]
pub fn pop_back(&mut self) -> Option<T> {
let id = self.tail?;
self.detach(id)?;
self.arena.remove(id).map(|node| node.value)
}
/// Removes the node `id` and returns its value.
///
/// # Example
///
/// ```
/// use cachekit::ds::IntrusiveList;
///
/// let mut list = IntrusiveList::new();
/// let a = list.push_back("a");
/// let b = list.push_back("b");
/// let c = list.push_back("c");
///
/// // Remove middle element
/// assert_eq!(list.remove(b), Some("b"));
/// let values: Vec<_> = list.iter().copied().collect();
/// assert_eq!(values, vec!["a", "c"]);
/// ```
#[inline]
pub fn remove(&mut self, id: SlotId) -> Option<T> {
self.detach(id)?;
self.arena.remove(id).map(|node| node.value)
}
/// Moves an existing node to the front; returns `false` if `id` is not present.
///
/// # Example
///
/// ```
/// use cachekit::ds::IntrusiveList;
///
/// let mut list = IntrusiveList::new();
/// list.push_back("a");
/// list.push_back("b");
/// let c = list.push_back("c");
///
/// // Move "c" to front
/// assert!(list.move_to_front(c));
/// assert_eq!(list.front(), Some(&"c"));
///
/// let values: Vec<_> = list.iter().copied().collect();
/// assert_eq!(values, vec!["c", "a", "b"]);
/// ```
#[inline]
pub fn move_to_front(&mut self, id: SlotId) -> bool {
if !self.arena.contains(id) {
return false;
}
if Some(id) == self.head {
return true;
}
self.detach(id);
self.attach_front(id);
true
}
/// Moves an existing node to the back; returns `false` if `id` is not present.
///
/// # Example
///
/// ```
/// use cachekit::ds::IntrusiveList;
///
/// let mut list = IntrusiveList::new();
/// let a = list.push_back("a");
/// list.push_back("b");
/// list.push_back("c");
///
/// // Move "a" to back
/// assert!(list.move_to_back(a));
/// assert_eq!(list.back(), Some(&"a"));
///
/// let values: Vec<_> = list.iter().copied().collect();
/// assert_eq!(values, vec!["b", "c", "a"]);
/// ```
#[inline]
pub fn move_to_back(&mut self, id: SlotId) -> bool {
if !self.arena.contains(id) {
return false;
}
if Some(id) == self.tail {
return true;
}
self.detach(id);
self.attach_back(id);
true
}
/// Clears the list and frees all nodes.
///
/// # Example
///
/// ```
/// use cachekit::ds::IntrusiveList;
///
/// let mut list = IntrusiveList::new();
/// let id = list.push_back(1);
/// list.push_back(2);
///
/// list.clear();
/// assert!(list.is_empty());
/// assert!(!list.contains(id));
/// ```
pub fn clear(&mut self) {
self.arena.clear();
self.head = None;
self.tail = None;
}
/// Clears the list and shrinks internal storage.
///
/// # Example
///
/// ```
/// use cachekit::ds::IntrusiveList;
///
/// let mut list = IntrusiveList::with_capacity(100);
/// list.push_back(1);
/// list.clear_shrink();
/// assert!(list.is_empty());
/// ```
pub fn clear_shrink(&mut self) {
self.clear();
self.arena.shrink_to_fit();
}
/// Returns an approximate memory footprint in bytes.
///
/// # Example
///
/// ```
/// use cachekit::ds::IntrusiveList;
///
/// let list: IntrusiveList<u64> = IntrusiveList::with_capacity(100);
/// let bytes = list.approx_bytes();
/// assert!(bytes > 0);
/// ```
pub fn approx_bytes(&self) -> usize {
// arena.approx_bytes() includes size_of::<SlotArena<Node<T>>>() which
// is already part of size_of::<Self>(), so subtract it to avoid
// double-counting the arena's inline footprint.
std::mem::size_of::<Self>() + self.arena.approx_bytes()
- std::mem::size_of::<SlotArena<Node<T>>>()
}
#[cfg(any(test, debug_assertions))]
#[doc(hidden)]
/// Returns the list order as SlotIds from head to tail.
pub fn debug_snapshot_ids(&self) -> Vec<SlotId> {
self.iter_ids().collect()
}
#[cfg(any(test, debug_assertions))]
#[doc(hidden)]
/// Returns SlotIds sorted by index for deterministic snapshots.
pub fn debug_snapshot_ids_sorted(&self) -> Vec<SlotId> {
let mut ids: Vec<_> = self.iter_ids().collect();
ids.sort_by_key(|id| id.index());
ids
}
#[inline]
fn detach(&mut self, id: SlotId) -> Option<()> {
let (prev, next) = {
let node = self.arena.get(id)?;
(node.prev, node.next)
};
if let Some(prev_id) = prev {
if let Some(prev_node) = self.arena.get_mut(prev_id) {
prev_node.next = next;
}
} else {
self.head = next;
}
if let Some(next_id) = next {
if let Some(next_node) = self.arena.get_mut(next_id) {
next_node.prev = prev;
}
} else {
self.tail = prev;
}
if let Some(node) = self.arena.get_mut(id) {
node.prev = None;
node.next = None;
}
Some(())
}
#[inline]
fn attach_front(&mut self, id: SlotId) -> Option<()> {
let old_head = self.head;
if let Some(node) = self.arena.get_mut(id) {
node.prev = None;
node.next = old_head;
} else {
return None;
}
if let Some(old_head) = old_head {
if let Some(head_node) = self.arena.get_mut(old_head) {
head_node.prev = Some(id);
}
} else {
self.tail = Some(id);
}
self.head = Some(id);
Some(())
}
#[inline]
fn attach_back(&mut self, id: SlotId) -> Option<()> {
let old_tail = self.tail;
if let Some(node) = self.arena.get_mut(id) {
node.next = None;
node.prev = old_tail;
} else {
return None;
}
if let Some(old_tail) = old_tail {
if let Some(tail_node) = self.arena.get_mut(old_tail) {
tail_node.next = Some(id);
}
} else {
self.head = Some(id);
}
self.tail = Some(id);
Some(())
}
#[cfg(any(test, debug_assertions))]
#[doc(hidden)]
///
/// # Panics
///
/// Panics if the list contains broken forward/backward links, duplicate
/// nodes in traversal order, or a node count that does not match the arena.
pub fn debug_validate_invariants(&self) {
if self.head.is_none() || self.tail.is_none() {
assert!(self.head.is_none());
assert!(self.tail.is_none());
assert_eq!(self.len(), 0);
return;
}
let mut seen = std::collections::HashSet::new();
let mut count = 0usize;
let mut current = self.head;
let mut prev = None;
while let Some(id) = current {
assert!(seen.insert(id));
let node = self.arena.get(id).expect("node missing");
assert_eq!(node.prev, prev);
if let Some(next_id) = node.next {
let next_node = self.arena.get(next_id).expect("next node missing");
assert_eq!(next_node.prev, Some(id));
} else {
assert_eq!(self.tail, Some(id));
}
prev = Some(id);
current = node.next;
count += 1;
assert!(count <= self.len());
}
assert_eq!(count, self.len());
assert_eq!(self.arena.len(), self.len());
}
}
/// Iterator over values from front to back.
#[derive(Debug)]
pub struct IntrusiveListIter<'a, T> {
list: &'a IntrusiveList<T>,
current: Option<SlotId>,
}
impl<'a, T> Iterator for IntrusiveListIter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
let id = self.current?;
let node = self.list.arena.get(id)?;
self.current = node.next;
Some(&node.value)
}
}
impl<T> FusedIterator for IntrusiveListIter<'_, T> {}
/// Iterator over [`SlotId`]s from front to back.
#[derive(Debug)]
pub struct IntrusiveListIdIter<'a, T> {
list: &'a IntrusiveList<T>,
current: Option<SlotId>,
}
impl<'a, T> Iterator for IntrusiveListIdIter<'a, T> {
type Item = SlotId;
fn next(&mut self) -> Option<Self::Item> {
let id = self.current?;
let node = self.list.arena.get(id)?;
self.current = node.next;
Some(id)
}
}
impl<T> FusedIterator for IntrusiveListIdIter<'_, T> {}
/// Iterator over `(SlotId, &T)` pairs from front to back.
#[derive(Debug)]
pub struct IntrusiveListEntryIter<'a, T> {
list: &'a IntrusiveList<T>,
current: Option<SlotId>,
}
impl<'a, T> Iterator for IntrusiveListEntryIter<'a, T> {