-
Notifications
You must be signed in to change notification settings - Fork 7
/
lib.rs
3535 lines (3115 loc) · 88.8 KB
/
lib.rs
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
//! Crate that implements a semi-doubly linked list via a vector.
//!
//! See [`VecList`] for more information.
//!
//! # Features
//!
//! By default, this crate uses the Rust standard library. To disable this, disable the default
//! `no_std` feature. Without this feature, certain methods will not be available.
#![allow(unsafe_code)]
#![cfg_attr(coverage_nightly, feature(coverage_attribute))]
#![cfg_attr(not(any(feature = "std", test)), no_std)]
extern crate alloc;
use alloc::{collections::LinkedList, vec::Vec};
use core::{
cmp::Ordering,
fmt::{self, Debug, Formatter},
hash::{Hash, Hasher},
hint::unreachable_unchecked,
iter::{FromIterator, FusedIterator},
marker::PhantomData,
mem,
num::NonZeroUsize,
ops,
};
#[cfg(feature = "std")]
use std::collections::HashMap;
#[cfg(feature = "serde")]
mod serde;
/// Number type that's capable of representing [0, usize::MAX - 1]
#[repr(transparent)]
#[derive(Clone, Copy, Eq, Hash, Ord, PartialEq, PartialOrd)]
struct NonMaxUsize(NonZeroUsize);
impl Debug for NonMaxUsize {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.get())
}
}
impl NonMaxUsize {
/// Convert an index to a usize
#[cfg_attr(mutants, mutants::skip)]
#[inline]
const fn get(&self) -> usize {
self.0.get() - 1
}
/// Create a new index from a usize, if `index` is `usize::MAX` then `None` is returned
#[inline]
const fn new(index: usize) -> Option<Self> {
match NonZeroUsize::new(index.wrapping_add(1)) {
Some(index) => Some(Self(index)),
None => None,
}
}
/// Create a new index from a usize, without checking if `index` is `usize::MAX`.
///
/// # Safety
///
/// `index` must not be `usize::MAX`
#[cfg(feature = "std")]
#[inline]
const unsafe fn new_unchecked(index: usize) -> Self {
Self(unsafe { NonZeroUsize::new_unchecked(index + 1) })
}
/// Add an unsigned integer to a index. Check for bound violation and return `None` if the result will be larger than or equal to `usize::MAX`
#[cfg(feature = "std")]
#[inline]
fn checked_add(&self, rhs: usize) -> Option<Self> {
self.0.checked_add(rhs).map(Self)
}
/// Subtract an unsigned integer from a index. Check for bound violation and return `None` if the result will be less than 0.
#[cfg(feature = "std")]
#[inline]
fn checked_sub(&self, rhs: usize) -> Option<Self> {
// Safety: `self` is less than `usize::MAX`, so `self - rhs` can only be less than `usize::MAX`
self
.get()
.checked_sub(rhs)
.map(|i| unsafe { Self::new_unchecked(i) })
}
#[cfg(feature = "std")]
#[inline]
const fn zero() -> Self {
Self(unsafe { NonZeroUsize::new_unchecked(1) })
}
}
impl PartialEq<usize> for NonMaxUsize {
fn eq(&self, other: &usize) -> bool {
self.get() == *other
}
}
impl PartialOrd<usize> for NonMaxUsize {
fn partial_cmp(&self, other: &usize) -> Option<Ordering> {
self.get().partial_cmp(other)
}
}
/// A semi-doubly linked list implemented with a vector.
///
/// This provides many of the benefits of an actual linked list with a few tradeoffs. First, due to the use of an
/// underlying vector, an individual insert operation may be O(n) due to allocating more space for the vector. However,
/// it is amortized O(1) and it avoids the frequent allocations that traditional linked lists suffer from.
///
/// Another tradeoff is that extending a traditional linked list with another list is O(1) but a vector based
/// implementation is O(n). Splicing has a similar disadvantage.
///
/// Lastly, the vector based implementation is likely to have better cache locality in general.
pub struct VecList<T> {
/// The backing storage for the list. This includes both used and unused indices.
entries: Vec<Entry<T>>,
/// The current generation of the list. This is used to avoid the ABA problem.
generation: u64,
/// The index of the head of the list.
head: Option<NonMaxUsize>,
/// The length of the list since we cannot rely on the length of [`VecList::entries`] because it includes unused
/// indices.
length: usize,
/// The index of the tail of the list.
tail: Option<NonMaxUsize>,
/// The index of the head of the vacant indices.
vacant_head: Option<NonMaxUsize>,
}
impl<T: Clone> Clone for VecList<T> {
fn clone(&self) -> Self {
Self {
entries: self.entries.clone(),
generation: self.generation,
head: self.head,
length: self.length,
tail: self.tail,
vacant_head: self.vacant_head,
}
}
fn clone_from(&mut self, source: &Self) {
self.entries.clone_from(&source.entries);
self.generation = source.generation;
self.head = source.head;
self.length = source.length;
self.tail = source.tail;
self.vacant_head = source.vacant_head;
}
}
impl<T> VecList<T> {
/// Returns an immutable reference to the value at the back of the list, if it exists.
///
/// Complexity: O(1)
///
/// # Examples
///
/// ```
/// use dlv_list::VecList;
///
/// let mut list = VecList::new();
/// assert_eq!(list.back(), None);
///
/// list.push_back(0);
/// list.push_back(5);
/// assert_eq!(list.back(), Some(&5));
/// ```
#[must_use]
pub fn back(&self) -> Option<&T> {
let index = self.tail?.get();
match &self.entries[index] {
Entry::Occupied(entry) => Some(&entry.value),
_ => None,
}
}
/// Returns the index of the value at the back of the list, if it exists.
///
/// Complexity: O(1)
///
/// # Examples
///
/// ```
/// use dlv_list::VecList;
///
/// let mut list = VecList::new();
/// assert_eq!(list.back_index(), None);
///
/// list.push_back(0);
/// let index = list.push_back(5);
/// assert_eq!(list.back_index(), Some(index));
/// ```
#[must_use]
pub fn back_index(&self) -> Option<Index<T>> {
let index = self.tail?;
let entry = self.entries[index.get()].occupied_ref();
let index = Index::new(index, entry.generation);
Some(index)
}
/// Returns a mutable reference to the value at the back of the list, if it exists.
///
/// Complexity: O(1)
///
/// # Examples
///
/// ```
/// use dlv_list::VecList;
///
/// let mut list = VecList::new();
/// assert_eq!(list.back_mut(), None);
///
/// list.push_back(0);
/// list.push_back(5);
///
/// let mut back = list.back_mut().unwrap();
/// assert_eq!(back, &mut 5);
/// *back *= 2;
///
/// assert_eq!(list.back(), Some(&10));
/// ```
#[must_use]
pub fn back_mut(&mut self) -> Option<&mut T> {
let index = self.tail?.get();
match &mut self.entries[index] {
Entry::Occupied(entry) => Some(&mut entry.value),
_ => None,
}
}
/// Returns the capacity of the list.
///
/// # Examples
///
/// ```
/// use dlv_list::VecList;
///
/// let list: VecList<u32> = VecList::new();
/// assert_eq!(list.capacity(), 0);
///
/// let list: VecList<u32> = VecList::with_capacity(10);
/// assert_eq!(list.capacity(), 10);
/// ```
#[must_use]
pub fn capacity(&self) -> usize {
self.entries.capacity()
}
/// Removes all values from the list and invalidates all existing indices.
///
/// Complexity: O(n)
///
/// # Examples
///
/// ```
/// use dlv_list::VecList;
///
/// let mut list = VecList::new();
///
/// list.push_back(5);
/// assert!(!list.is_empty());
///
/// list.clear();
/// assert!(list.is_empty());
/// ```
pub fn clear(&mut self) {
self.entries.clear();
self.generation = self.generation.wrapping_add(1);
self.head = None;
self.length = 0;
self.tail = None;
self.vacant_head = None;
}
/// Returns whether or not the list contains the given value.
///
/// Complexity: O(n)
///
/// # Examples
///
/// ```
/// use dlv_list::VecList;
///
/// let mut list = VecList::new();
/// assert!(!list.contains(&0));
///
/// list.push_back(0);
/// assert!(list.contains(&0));
/// ```
#[must_use]
pub fn contains(&self, value: &T) -> bool
where
T: PartialEq,
{
self.iter().any(|entry| entry == value)
}
/// Creates a draining iterator that removes all values from the list and yields them in order.
///
/// All values are removed even if the iterator is only partially consumed or not consumed at all.
///
/// # Examples
///
/// ```
/// use dlv_list::VecList;
///
/// let mut list = VecList::new();
/// list.push_back(0);
/// list.push_back(5);
///
/// {
/// let mut iter = list.drain();
/// assert_eq!(iter.next(), Some(0));
/// assert_eq!(iter.next(), Some(5));
/// assert_eq!(iter.next(), None);
/// }
///
/// println!("{}", list.len());
/// assert!(list.is_empty());
/// ```
pub fn drain(&mut self) -> Drain<'_, T> {
Drain {
head: self.head,
remaining: self.length,
tail: self.tail,
list: self,
}
}
/// Returns an immutable reference to the value at the front of the list, if it exists.
///
/// Complexity: O(1)
///
/// # Examples
///
/// ```
/// use dlv_list::VecList;
///
/// let mut list = VecList::new();
/// assert_eq!(list.front(), None);
///
/// list.push_front(0);
/// list.push_front(5);
/// assert_eq!(list.front(), Some(&5));
/// ```
#[must_use]
pub fn front(&self) -> Option<&T> {
let index = self.head?.get();
match &self.entries[index] {
Entry::Occupied(entry) => Some(&entry.value),
_ => None,
}
}
/// Returns the index of the value at the front of the list, if it exists.
///
/// Complexity: O(1)
///
/// # Examples
///
/// ```
/// use dlv_list::VecList;
///
/// let mut list = VecList::new();
/// assert_eq!(list.front_index(), None);
///
/// list.push_front(0);
/// let index = list.push_front(5);
/// assert_eq!(list.front_index(), Some(index));
/// ```
#[must_use]
pub fn front_index(&self) -> Option<Index<T>> {
let index = self.head?;
let entry = self.entries[index.get()].occupied_ref();
let index = Index::new(index, entry.generation);
Some(index)
}
/// Returns a mutable reference to the value at the front of the list, if it exists.
///
/// Complexity: O(1)
///
/// # Examples
///
/// ```
/// use dlv_list::VecList;
///
/// let mut list = VecList::new();
/// assert_eq!(list.front_mut(), None);
///
/// list.push_front(0);
/// list.push_front(5);
///
/// let mut front = list.front_mut().unwrap();
/// assert_eq!(front, &mut 5);
/// *front *= 2;
///
/// assert_eq!(list.front(), Some(&10));
/// ```
#[must_use]
pub fn front_mut(&mut self) -> Option<&mut T> {
let index = self.head?.get();
match &mut self.entries[index] {
Entry::Occupied(entry) => Some(&mut entry.value),
_ => None,
}
}
/// Returns an immutable reference to the value at the given index.
///
/// If the index refers to an index not in the list anymore or if the index has been invalidated, then [`None`] will
/// be returned.
///
/// Complexity: O(1)
///
/// # Examples
///
/// ```
/// use dlv_list::VecList;
///
/// let mut list = VecList::new();
/// let index = list.push_front(0);
/// assert_eq!(list.get(index), Some(&0));
///
/// let index = list.push_front(5);
/// assert_eq!(list.get(index), Some(&5));
/// ```
#[must_use]
pub fn get(&self, index: Index<T>) -> Option<&T> {
match self.entries.get(index.index())? {
Entry::Occupied(entry) if entry.generation == index.generation => Some(&entry.value),
_ => None,
}
}
/// Returns an immutable reference to the value at the given index.
///
/// Complexity: O(1)
///
/// # Safety
///
/// Caller needs to guarantee that the index is in bound, and has never been removed from the
/// list. This function does not perform generation checks. So if an element is removed then a
/// new element is added at the same index, then the returned reference will be to the new
/// element.
#[must_use]
pub unsafe fn get_unchecked(&self, index: Index<T>) -> &T {
match unsafe { self.entries.get_unchecked(index.index()) } {
Entry::Occupied(entry) => &entry.value,
_ => unsafe { unreachable_unchecked() },
}
}
/// Returns a mutable reference to the value at the given index.
///
/// If the index refers to an index not in the list anymore or if the index has been invalidated, then [`None`] will
/// be returned.
///
/// Complexity: O(1)
///
/// # Examples
///
/// ```
/// use dlv_list::VecList;
///
/// let mut list = VecList::new();
/// let index = list.push_front(0);
/// let value = list.get_mut(index).unwrap();
/// *value = 100;
/// assert_eq!(list.get(index), Some(&100));
/// ```
#[must_use]
pub fn get_mut(&mut self, index: Index<T>) -> Option<&mut T> {
match self.entries.get_mut(index.index())? {
Entry::Occupied(entry) if entry.generation == index.generation => Some(&mut entry.value),
_ => None,
}
}
/// Returns an mutable reference to the value at the given index.
///
/// # Safety
///
/// Caller needs to guarantee that the index is in bound, and has never been removed from the list.
/// See also: [`VecList::get_unchecked`].
///
/// Complexity: O(1)
#[must_use]
pub unsafe fn get_unchecked_mut(&mut self, index: Index<T>) -> &mut T {
match unsafe { self.entries.get_unchecked_mut(index.index()) } {
Entry::Occupied(entry) => &mut entry.value,
_ => unsafe { unreachable_unchecked() },
}
}
/// Returns the index of the value next to the value at the given index.
///
/// If the index refers to an index not in the list anymore or if the index has been invalidated, then [`None`] will
/// be returned.
///
/// Complexity: O(1)
///
/// # Examples
///
/// ```
/// use dlv_list::VecList;
///
/// let mut list = VecList::new();
///
/// let index_1 = list.push_back(0);
/// assert_eq!(list.get_next_index(index_1), None);
///
/// let index_2 = list.push_back(5);
/// assert_eq!(list.get_next_index(index_1), Some(index_2));
/// ```
#[must_use]
pub fn get_next_index(&self, index: Index<T>) -> Option<Index<T>> {
match self.entries.get(index.index())? {
Entry::Occupied(entry) if entry.generation == index.generation => {
let next_index = entry.next?;
let next_entry = self.entries[next_index.get()].occupied_ref();
Some(Index::new(next_index, next_entry.generation))
}
_ => None,
}
}
/// Returns the index of the value previous to the value at the given index.
///
/// If the index refers to an index not in the list anymore or if the index has been invalidated, then [`None`] will
/// be returned.
///
/// Complexity: O(1)
///
/// # Examples
///
/// ```
/// use dlv_list::VecList;
///
/// let mut list = VecList::new();
///
/// let index_1 = list.push_front(0);
/// assert_eq!(list.get_previous_index(index_1), None);
///
/// let index_2 = list.push_front(5);
/// assert_eq!(list.get_previous_index(index_1), Some(index_2));
/// ```
#[must_use]
pub fn get_previous_index(&self, index: Index<T>) -> Option<Index<T>> {
match self.entries.get(index.index())? {
Entry::Occupied(entry) if entry.generation == index.generation => {
let previous_index = entry.previous?;
let previous_entry = self.entries[previous_index.get()].occupied_ref();
Some(Index::new(previous_index, previous_entry.generation))
}
_ => None,
}
}
/// Connect the node at `index` to the node at `next`. If `index` is `None`, then the head will be
/// set to `next`; if `next` is `None`, then the tail will be set to `index`.
#[inline]
fn update_link(&mut self, index: Option<NonMaxUsize>, next: Option<NonMaxUsize>) {
if let Some(index) = index {
let entry = self.entries[index.get()].occupied_mut();
entry.next = next;
} else {
self.head = next
}
if let Some(next) = next {
let entry = self.entries[next.get()].occupied_mut();
entry.previous = index;
} else {
self.tail = index;
}
}
/// Move the node at `index` to after the node at `target`.
///
/// # Panics
///
/// Panics if either `index` or `target` is invalidated. Also panics if `index` is the same as `target`.
///
/// # Examples
///
/// ```
/// use dlv_list::VecList;
///
/// let mut list = VecList::new();
/// let index_1 = list.push_back(0);
/// let index_2 = list.push_back(1);
/// let index_3 = list.push_back(2);
/// let index_4 = list.push_back(3);
///
/// list.move_after(index_1, index_3);
/// assert_eq!(list.iter().copied().collect::<Vec<_>>(), vec![1, 2, 0, 3]);
/// assert_eq!(list.iter().rev().copied().collect::<Vec<_>>(), vec![3, 0, 2, 1]);
/// ```
pub fn move_after(&mut self, index: Index<T>, target: Index<T>) {
let (previous_index, next_index) = match &self.entries[index.index()] {
Entry::Occupied(entry) if entry.generation == index.generation => {
(entry.previous, entry.next)
}
_ => panic!("expected occupied entry with correct generation at `index`"),
};
let target_next_index = match &self.entries[target.index()] {
Entry::Occupied(entry) if entry.generation == target.generation => entry.next,
_ => panic!("expected occupied entry with correct generation at `target`"),
};
if target.index == index.index {
panic!("cannot move after `index` itself");
}
if previous_index == Some(target.index) {
// Already in the right place
return;
}
self.update_link(previous_index, next_index);
self.update_link(Some(target.index), Some(index.index));
self.update_link(Some(index.index), target_next_index);
}
/// Move the node at `index` to before the node at `target`.
///
/// # Panics
///
/// Panics if either `index` or `target` is invalidated. Also panics if `index` is the same as `target`.
///
/// # Examples
///
/// ```
/// use dlv_list::VecList;
///
/// let mut list = VecList::new();
/// let index_1 = list.push_back(0);
/// let index_2 = list.push_back(1);
/// let index_3 = list.push_back(2);
/// let index_4 = list.push_back(3);
///
/// list.move_before(index_1, index_3);
/// assert_eq!(list.iter().copied().collect::<Vec<_>>(), vec![1, 0, 2, 3]);
/// assert_eq!(list.iter().rev().copied().collect::<Vec<_>>(), vec![3, 2, 0, 1]);
/// ```
pub fn move_before(&mut self, index: Index<T>, target: Index<T>) {
let (previous_index, next_index) = match &self.entries[index.index()] {
Entry::Occupied(entry) if entry.generation == index.generation => {
(entry.previous, entry.next)
}
_ => panic!("expected occupied entry with correct generation at `index`"),
};
let target_previous_index = match &self.entries[target.index()] {
Entry::Occupied(entry) if entry.generation == target.generation => entry.previous,
_ => panic!("expected occupied entry with correct generation at `target`"),
};
if target.index == index.index {
panic!("cannot move before `index` itself");
}
if next_index == Some(target.index) {
// Already in the right place
return;
}
self.update_link(previous_index, next_index);
self.update_link(Some(index.index), Some(target.index));
self.update_link(target_previous_index, Some(index.index));
}
/// Creates an indices iterator which will yield all indices of the list in order.
///
/// # Examples
///
/// ```
/// use dlv_list::VecList;
///
/// let mut list = VecList::new();
/// list.push_front(0);
/// list.push_front(5);
///
/// let mut indices = list.indices();
/// let index = indices.next().unwrap();
/// assert_eq!(list.get(index), Some(&5));
///
/// let index = indices.next().unwrap();
/// assert_eq!(list.get(index), Some(&0));
///
/// assert_eq!(indices.next(), None);
/// ```
#[must_use]
pub fn indices(&self) -> Indices<'_, T> {
Indices {
entries: &self.entries,
head: self.head,
remaining: self.length,
tail: self.tail,
}
}
/// Inserts the given value after the value at the given index.
///
/// The index of the newly inserted value will be returned.
///
/// Complexity: amortized O(1)
///
/// # Panics
///
/// Panics if the index refers to an index not in the list anymore or if the index has been invalidated. This is
/// enforced because this function will consume the value to be inserted, and if it cannot be inserted (due to the
/// index not being valid), then it will be lost.
///
/// Also panics if the new capacity overflows `usize`.
///
/// # Examples
///
/// ```
/// use dlv_list::VecList;
///
/// let mut list = VecList::new();
/// list.push_front(0);
/// let index_1 = list.push_front(5);
/// list.push_front(10);
///
/// let index_2 = list.insert_after(index_1, 1000);
/// assert_eq!(list.get_next_index(index_1), Some(index_2));
/// ```
pub fn insert_after(&mut self, index: Index<T>, value: T) -> Index<T> {
let next_index = match &mut self.entries[index.index()] {
Entry::Occupied(entry) if entry.generation == index.generation => entry.next,
_ => panic!("expected occupied entry with correct generation"),
};
let new_index = self.insert_new(value, Some(index.index), next_index);
let entry = self.entries[index.index()].occupied_mut();
entry.next = Some(new_index);
if Some(index.index) == self.tail {
self.tail = Some(new_index);
}
if let Some(next_index) = next_index {
self.entries[next_index.get()].occupied_mut().previous = Some(new_index);
}
Index::new(new_index, self.generation)
}
/// Inserts the given value before the value at the given index.
///
/// The index of the newly inserted value will be returned.
///
/// Complexity: amortized O(1)
///
/// # Panics
///
/// Panics if the index refers to an index not in the list anymore or if the index has been invalidated. This is
/// enforced because this function will consume the value to be inserted, and if it cannot be inserted (due to the
/// index not being valid), then it will be lost.
///
/// Also panics if the new capacity overflows `usize`.
///
/// # Examples
///
/// ```
/// use dlv_list::VecList;
///
/// let mut list = VecList::new();
/// list.push_front(0);
/// let index_1 = list.push_front(5);
/// list.push_front(10);
///
/// let index_2 = list.insert_before(index_1, 1000);
/// assert_eq!(list.get_previous_index(index_1), Some(index_2));
/// ```
pub fn insert_before(&mut self, index: Index<T>, value: T) -> Index<T> {
let previous_index = match &mut self.entries[index.index()] {
Entry::Occupied(entry) if entry.generation == index.generation => entry.previous,
_ => panic!("expected occupied entry with correct generation"),
};
let new_index = self.insert_new(value, previous_index, Some(index.index));
let entry = self.entries[index.index()].occupied_mut();
entry.previous = Some(new_index);
if Some(index.index) == self.head {
self.head = Some(new_index);
}
if let Some(previous_index) = previous_index {
self.entries[previous_index.get()].occupied_mut().next = Some(new_index);
}
Index::new(new_index, self.generation)
}
/// Inserts the given value into the list with the assumption that it is currently empty.
///
/// # Panics
///
/// Panics if the new capacity overflows `usize`.
fn insert_empty(&mut self, value: T) -> Index<T> {
let generation = self.generation;
let index = self.insert_new(value, None, None);
self.head = Some(index);
self.tail = Some(index);
Index::new(index, generation)
}
/// Inserts the given value into the list with its expected previous and next value indices.
///
/// # Panics
///
/// Panics if the new capacity overflows `usize`.
fn insert_new(
&mut self,
value: T,
previous: Option<NonMaxUsize>,
next: Option<NonMaxUsize>,
) -> NonMaxUsize {
self.length += 1;
if self.length == usize::max_value() {
panic!("reached maximum possible length");
}
match self.vacant_head {
Some(index) => {
self.vacant_head = self.entries[index.get()].vacant_ref().next;
self.entries[index.get()] =
Entry::Occupied(OccupiedEntry::new(self.generation, previous, next, value));
index
}
None => {
self.entries.push(Entry::Occupied(OccupiedEntry::new(
self.generation,
previous,
next,
value,
)));
NonMaxUsize::new(self.entries.len() - 1).unwrap()
}
}
}
/// Returns whether or not the list is empty.
///
/// # Examples
///
/// ```
/// use dlv_list::VecList;
///
/// let mut list = VecList::new();
/// assert!(list.is_empty());
///
/// list.push_back(0);
/// assert!(!list.is_empty());
/// ```
#[must_use]
pub fn is_empty(&self) -> bool {
self.length == 0
}
/// Creates an iterator that yields immutable references to values in the list in order.
///
/// # Examples
///
/// ```
/// use dlv_list::VecList;
///
/// let mut list = VecList::new();
/// list.push_back(0);
/// list.push_back(10);
/// list.push_back(200);
/// list.push_back(-10);
///
/// let mut iter = list.iter();
/// assert_eq!(iter.next(), Some(&0));
/// assert_eq!(iter.next(), Some(&10));
/// assert_eq!(iter.next(), Some(&200));
/// assert_eq!(iter.next(), Some(&-10));
/// assert_eq!(iter.next(), None);
/// ```
#[must_use]
pub fn iter(&self) -> Iter<'_, T> {
Iter {
entries: &self.entries,
head: self.head,
remaining: self.length,
tail: self.tail,
}
}
/// Creates an iterator that yields mutable references to values in the list in order.
///
/// # Examples
///
/// ```
/// use dlv_list::VecList;
///
/// let mut list = VecList::new();
/// list.push_back(0);
/// list.push_back(10);
/// list.push_back(200);
/// list.push_back(-10);
///
/// let mut iter = list.iter_mut();
/// assert_eq!(iter.next(), Some(&mut 0));
/// assert_eq!(iter.next(), Some(&mut 10));
/// assert_eq!(iter.next(), Some(&mut 200));
/// assert_eq!(iter.next(), Some(&mut -10));
/// assert_eq!(iter.next(), None);
/// ```
#[must_use]
pub fn iter_mut(&mut self) -> IterMut<'_, T> {
IterMut {
entries: &mut self.entries,
head: self.head,
phantom: PhantomData,
remaining: self.length,
tail: self.tail,
}
}
/// Returns the number of values in the list.
///
/// # Examples
///
/// ```
/// use dlv_list::VecList;
///
/// let mut list = VecList::new();
/// assert_eq!(list.len(), 0);
///
/// list.push_back(0);
/// list.push_back(1);
/// list.push_back(2);
/// assert_eq!(list.len(), 3);
/// ```
#[must_use]
pub fn len(&self) -> usize {
self.length
}
/// Creates a new list with no initial capacity.
///
/// # Examples
///
/// ```
/// use dlv_list::VecList;
///
/// let mut list = VecList::new();
/// let index = list.push_back(0);
/// assert_eq!(list.get(index), Some(&0));
/// ```
#[must_use]
pub fn new() -> Self {
VecList::default()
}
/// Reorganizes the existing values to ensure maximum cache locality and shrinks the list such that the capacity is
/// exactly [`minimum_capacity`].
///
/// This function can be used to actually increase the capacity of the list.
///
/// Complexity: O(n)
///
/// # Panics
///
/// Panics if the given minimum capacity is less than the current length of the list.
///
/// # Examples
///
/// ```
/// use dlv_list::VecList;
///
/// let mut list = VecList::new();
/// let index_1 = list.push_back(5);
/// let index_2 = list.push_back(10);
/// let index_3 = list.push_front(100);
/// list.remove(index_1);
///
/// assert!(list.capacity() >= 3);
///
/// let mut map = list.pack_to(list.len() + 5);
/// assert_eq!(list.capacity(), 7);
/// assert_eq!(map.len(), 2);
///
/// let index_2 = map.remove(&index_2).unwrap();
/// let index_3 = map.remove(&index_3).unwrap();