Debian Codegraph @

debian/rust-vendor/dlv-list/src/lib.rs

raw
1 //! Crate that implements a semi-doubly linked list via a vector.
2 //!
3 //! See [`VecList`] for more information.
4 //!
5 //! # Features
6 //!
7 //! By default, this crate uses the Rust standard library. To disable this, disable the default
8 //! `no_std` feature. Without this feature, certain methods will not be available.
9
10 #![allow(unsafe_code)]
11 #![cfg_attr(coverage_nightly, feature(coverage_attribute))]
12 #![cfg_attr(not(any(feature = "std", test)), no_std)]
13
14 extern crate alloc;
15
16 use alloc::{collections::LinkedList, vec::Vec};
17 use core::{
18 cmp::Ordering,
19 fmt::{self, Debug, Formatter},
20 hash::{Hash, Hasher},
21 hint::unreachable_unchecked,
22 iter::{FromIterator, FusedIterator},
23 marker::PhantomData,
24 mem,
25 num::NonZeroUsize,
26 ops,
27 };
28
29 #[cfg(feature = "std")]
30 use std::collections::HashMap;
31
32 #[cfg(feature = "serde")]
33 mod serde;
34
35 /// Number type that's capable of representing [0, usize::MAX - 1]
36 #[repr(transparent)]
37 #[derive(Clone, Copy, Eq, Hash, Ord, PartialEq, PartialOrd)]
38 struct NonMaxUsize(NonZeroUsize);
39
40 impl Debug for NonMaxUsize {
41 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
42 write!(f, "{}", self.get())
43 }
44 }
45
46 impl NonMaxUsize {
47 /// Convert an index to a usize
48 #[cfg_attr(mutants, mutants::skip)]
49 #[inline]
50 const fn get(&self) -> usize {
51 self.0.get() - 1
52 }
53
54 /// Create a new index from a usize, if `index` is `usize::MAX` then `None` is returned
55 #[inline]
56 const fn new(index: usize) -> Option<Self> {
57 match NonZeroUsize::new(index.wrapping_add(1)) {
58 Some(index) => Some(Self(index)),
59 None => None,
60 }
61 }
62
63 /// Create a new index from a usize, without checking if `index` is `usize::MAX`.
64 ///
65 /// # Safety
66 ///
67 /// `index` must not be `usize::MAX`
68 #[cfg(feature = "std")]
69 #[inline]
70 const unsafe fn new_unchecked(index: usize) -> Self {
71 Self(unsafe { NonZeroUsize::new_unchecked(index + 1) })
72 }
73
74 /// 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`
75 #[cfg(feature = "std")]
76 #[inline]
77 fn checked_add(&self, rhs: usize) -> Option<Self> {
78 self.0.checked_add(rhs).map(Self)
79 }
80
81 /// Subtract an unsigned integer from a index. Check for bound violation and return `None` if the result will be less than 0.
82 #[cfg(feature = "std")]
83 #[inline]
84 fn checked_sub(&self, rhs: usize) -> Option<Self> {
85 // Safety: `self` is less than `usize::MAX`, so `self - rhs` can only be less than `usize::MAX`
86 self
87 .get()
88 .checked_sub(rhs)
89 .map(|i| unsafe { Self::new_unchecked(i) })
90 }
91
92 #[cfg(feature = "std")]
93 #[inline]
94 const fn zero() -> Self {
95 Self(unsafe { NonZeroUsize::new_unchecked(1) })
96 }
97 }
98
99 impl PartialEq<usize> for NonMaxUsize {
100 fn eq(&self, other: &usize) -> bool {
101 self.get() == *other
102 }
103 }
104
105 impl PartialOrd<usize> for NonMaxUsize {
106 fn partial_cmp(&self, other: &usize) -> Option<Ordering> {
107 self.get().partial_cmp(other)
108 }
109 }
110
111 /// A semi-doubly linked list implemented with a vector.
112 ///
113 /// This provides many of the benefits of an actual linked list with a few tradeoffs. First, due to the use of an
114 /// underlying vector, an individual insert operation may be O(n) due to allocating more space for the vector. However,
115 /// it is amortized O(1) and it avoids the frequent allocations that traditional linked lists suffer from.
116 ///
117 /// Another tradeoff is that extending a traditional linked list with another list is O(1) but a vector based
118 /// implementation is O(n). Splicing has a similar disadvantage.
119 ///
120 /// Lastly, the vector based implementation is likely to have better cache locality in general.
121 pub struct VecList<T> {
122 /// The backing storage for the list. This includes both used and unused indices.
123 entries: Vec<Entry<T>>,
124
125 /// The current generation of the list. This is used to avoid the ABA problem.
126 generation: u64,
127
128 /// The index of the head of the list.
129 head: Option<NonMaxUsize>,
130
131 /// The length of the list since we cannot rely on the length of [`VecList::entries`] because it includes unused
132 /// indices.
133 length: usize,
134
135 /// The index of the tail of the list.
136 tail: Option<NonMaxUsize>,
137
138 /// The index of the head of the vacant indices.
139 vacant_head: Option<NonMaxUsize>,
140 }
141
142 impl<T: Clone> Clone for VecList<T> {
143 fn clone(&self) -> Self {
144 Self {
145 entries: self.entries.clone(),
146 generation: self.generation,
147 head: self.head,
148 length: self.length,
149 tail: self.tail,
150 vacant_head: self.vacant_head,
151 }
152 }
153
154 fn clone_from(&mut self, source: &Self) {
155 self.entries.clone_from(&source.entries);
156 self.generation = source.generation;
157 self.head = source.head;
158 self.length = source.length;
159 self.tail = source.tail;
160 self.vacant_head = source.vacant_head;
161 }
162 }
163
164 impl<T> VecList<T> {
165 /// Returns an immutable reference to the value at the back of the list, if it exists.
166 ///
167 /// Complexity: O(1)
168 ///
169 /// # Examples
170 ///
171 /// ```
172 /// use dlv_list::VecList;
173 ///
174 /// let mut list = VecList::new();
175 /// assert_eq!(list.back(), None);
176 ///
177 /// list.push_back(0);
178 /// list.push_back(5);
179 /// assert_eq!(list.back(), Some(&5));
180 /// ```
181 #[must_use]
182 pub fn back(&self) -> Option<&T> {
183 let index = self.tail?.get();
184
185 match &self.entries[index] {
186 Entry::Occupied(entry) => Some(&entry.value),
187 _ => None,
188 }
189 }
190
191 /// Returns the index of the value at the back of the list, if it exists.
192 ///
193 /// Complexity: O(1)
194 ///
195 /// # Examples
196 ///
197 /// ```
198 /// use dlv_list::VecList;
199 ///
200 /// let mut list = VecList::new();
201 /// assert_eq!(list.back_index(), None);
202 ///
203 /// list.push_back(0);
204 /// let index = list.push_back(5);
205 /// assert_eq!(list.back_index(), Some(index));
206 /// ```
207 #[must_use]
208 pub fn back_index(&self) -> Option<Index<T>> {
209 let index = self.tail?;
210 let entry = self.entries[index.get()].occupied_ref();
211 let index = Index::new(index, entry.generation);
212 Some(index)
213 }
214
215 /// Returns a mutable reference to the value at the back of the list, if it exists.
216 ///
217 /// Complexity: O(1)
218 ///
219 /// # Examples
220 ///
221 /// ```
222 /// use dlv_list::VecList;
223 ///
224 /// let mut list = VecList::new();
225 /// assert_eq!(list.back_mut(), None);
226 ///
227 /// list.push_back(0);
228 /// list.push_back(5);
229 ///
230 /// let mut back = list.back_mut().unwrap();
231 /// assert_eq!(back, &mut 5);
232 /// *back *= 2;
233 ///
234 /// assert_eq!(list.back(), Some(&10));
235 /// ```
236 #[must_use]
237 pub fn back_mut(&mut self) -> Option<&mut T> {
238 let index = self.tail?.get();
239
240 match &mut self.entries[index] {
241 Entry::Occupied(entry) => Some(&mut entry.value),
242 _ => None,
243 }
244 }
245
246 /// Returns the capacity of the list.
247 ///
248 /// # Examples
249 ///
250 /// ```
251 /// use dlv_list::VecList;
252 ///
253 /// let list: VecList<u32> = VecList::new();
254 /// assert_eq!(list.capacity(), 0);
255 ///
256 /// let list: VecList<u32> = VecList::with_capacity(10);
257 /// assert_eq!(list.capacity(), 10);
258 /// ```
259 #[must_use]
260 pub fn capacity(&self) -> usize {
261 self.entries.capacity()
262 }
263
264 /// Removes all values from the list and invalidates all existing indices.
265 ///
266 /// Complexity: O(n)
267 ///
268 /// # Examples
269 ///
270 /// ```
271 /// use dlv_list::VecList;
272 ///
273 /// let mut list = VecList::new();
274 ///
275 /// list.push_back(5);
276 /// assert!(!list.is_empty());
277 ///
278 /// list.clear();
279 /// assert!(list.is_empty());
280 /// ```
281 pub fn clear(&mut self) {
282 self.entries.clear();
283 self.generation = self.generation.wrapping_add(1);
284 self.head = None;
285 self.length = 0;
286 self.tail = None;
287 self.vacant_head = None;
288 }
289
290 /// Returns whether or not the list contains the given value.
291 ///
292 /// Complexity: O(n)
293 ///
294 /// # Examples
295 ///
296 /// ```
297 /// use dlv_list::VecList;
298 ///
299 /// let mut list = VecList::new();
300 /// assert!(!list.contains(&0));
301 ///
302 /// list.push_back(0);
303 /// assert!(list.contains(&0));
304 /// ```
305 #[must_use]
306 pub fn contains(&self, value: &T) -> bool
307 where
308 T: PartialEq,
309 {
310 self.iter().any(|entry| entry == value)
311 }
312
313 /// Creates a draining iterator that removes all values from the list and yields them in order.
314 ///
315 /// All values are removed even if the iterator is only partially consumed or not consumed at all.
316 ///
317 /// # Examples
318 ///
319 /// ```
320 /// use dlv_list::VecList;
321 ///
322 /// let mut list = VecList::new();
323 /// list.push_back(0);
324 /// list.push_back(5);
325 ///
326 /// {
327 /// let mut iter = list.drain();
328 /// assert_eq!(iter.next(), Some(0));
329 /// assert_eq!(iter.next(), Some(5));
330 /// assert_eq!(iter.next(), None);
331 /// }
332 ///
333 /// println!("{}", list.len());
334 /// assert!(list.is_empty());
335 /// ```
336 pub fn drain(&mut self) -> Drain<'_, T> {
337 Drain {
338 head: self.head,
339 remaining: self.length,
340 tail: self.tail,
341 list: self,
342 }
343 }
344
345 /// Returns an immutable reference to the value at the front of the list, if it exists.
346 ///
347 /// Complexity: O(1)
348 ///
349 /// # Examples
350 ///
351 /// ```
352 /// use dlv_list::VecList;
353 ///
354 /// let mut list = VecList::new();
355 /// assert_eq!(list.front(), None);
356 ///
357 /// list.push_front(0);
358 /// list.push_front(5);
359 /// assert_eq!(list.front(), Some(&5));
360 /// ```
361 #[must_use]
362 pub fn front(&self) -> Option<&T> {
363 let index = self.head?.get();
364
365 match &self.entries[index] {
366 Entry::Occupied(entry) => Some(&entry.value),
367 _ => None,
368 }
369 }
370
371 /// Returns the index of the value at the front of the list, if it exists.
372 ///
373 /// Complexity: O(1)
374 ///
375 /// # Examples
376 ///
377 /// ```
378 /// use dlv_list::VecList;
379 ///
380 /// let mut list = VecList::new();
381 /// assert_eq!(list.front_index(), None);
382 ///
383 /// list.push_front(0);
384 /// let index = list.push_front(5);
385 /// assert_eq!(list.front_index(), Some(index));
386 /// ```
387 #[must_use]
388 pub fn front_index(&self) -> Option<Index<T>> {
389 let index = self.head?;
390 let entry = self.entries[index.get()].occupied_ref();
391 let index = Index::new(index, entry.generation);
392 Some(index)
393 }
394
395 /// Returns a mutable reference to the value at the front of the list, if it exists.
396 ///
397 /// Complexity: O(1)
398 ///
399 /// # Examples
400 ///
401 /// ```
402 /// use dlv_list::VecList;
403 ///
404 /// let mut list = VecList::new();
405 /// assert_eq!(list.front_mut(), None);
406 ///
407 /// list.push_front(0);
408 /// list.push_front(5);
409 ///
410 /// let mut front = list.front_mut().unwrap();
411 /// assert_eq!(front, &mut 5);
412 /// *front *= 2;
413 ///
414 /// assert_eq!(list.front(), Some(&10));
415 /// ```
416 #[must_use]
417 pub fn front_mut(&mut self) -> Option<&mut T> {
418 let index = self.head?.get();
419
420 match &mut self.entries[index] {
421 Entry::Occupied(entry) => Some(&mut entry.value),
422 _ => None,
423 }
424 }
425
426 /// Returns an immutable reference to the value at the given index.
427 ///
428 /// If the index refers to an index not in the list anymore or if the index has been invalidated, then [`None`] will
429 /// be returned.
430 ///
431 /// Complexity: O(1)
432 ///
433 /// # Examples
434 ///
435 /// ```
436 /// use dlv_list::VecList;
437 ///
438 /// let mut list = VecList::new();
439 /// let index = list.push_front(0);
440 /// assert_eq!(list.get(index), Some(&0));
441 ///
442 /// let index = list.push_front(5);
443 /// assert_eq!(list.get(index), Some(&5));
444 /// ```
445 #[must_use]
446 pub fn get(&self, index: Index<T>) -> Option<&T> {
447 match self.entries.get(index.index())? {
448 Entry::Occupied(entry) if entry.generation == index.generation => Some(&entry.value),
449 _ => None,
450 }
451 }
452
453 /// Returns an immutable reference to the value at the given index.
454 ///
455 /// Complexity: O(1)
456 ///
457 /// # Safety
458 ///
459 /// Caller needs to guarantee that the index is in bound, and has never been removed from the
460 /// list. This function does not perform generation checks. So if an element is removed then a
461 /// new element is added at the same index, then the returned reference will be to the new
462 /// element.
463 #[must_use]
464 pub unsafe fn get_unchecked(&self, index: Index<T>) -> &T {
465 match unsafe { self.entries.get_unchecked(index.index()) } {
466 Entry::Occupied(entry) => &entry.value,
467 _ => unsafe { unreachable_unchecked() },
468 }
469 }
470
471 /// Returns a mutable reference to the value at the given index.
472 ///
473 /// If the index refers to an index not in the list anymore or if the index has been invalidated, then [`None`] will
474 /// be returned.
475 ///
476 /// Complexity: O(1)
477 ///
478 /// # Examples
479 ///
480 /// ```
481 /// use dlv_list::VecList;
482 ///
483 /// let mut list = VecList::new();
484 /// let index = list.push_front(0);
485 /// let value = list.get_mut(index).unwrap();
486 /// *value = 100;
487 /// assert_eq!(list.get(index), Some(&100));
488 /// ```
489 #[must_use]
490 pub fn get_mut(&mut self, index: Index<T>) -> Option<&mut T> {
491 match self.entries.get_mut(index.index())? {
492 Entry::Occupied(entry) if entry.generation == index.generation => Some(&mut entry.value),
493 _ => None,
494 }
495 }
496
497 /// Returns an mutable reference to the value at the given index.
498 ///
499 /// # Safety
500 ///
501 /// Caller needs to guarantee that the index is in bound, and has never been removed from the list.
502 /// See also: [`VecList::get_unchecked`].
503 ///
504 /// Complexity: O(1)
505 #[must_use]
506 pub unsafe fn get_unchecked_mut(&mut self, index: Index<T>) -> &mut T {
507 match unsafe { self.entries.get_unchecked_mut(index.index()) } {
508 Entry::Occupied(entry) => &mut entry.value,
509 _ => unsafe { unreachable_unchecked() },
510 }
511 }
512
513 /// Returns the index of the value next to the value at the given index.
514 ///
515 /// If the index refers to an index not in the list anymore or if the index has been invalidated, then [`None`] will
516 /// be returned.
517 ///
518 /// Complexity: O(1)
519 ///
520 /// # Examples
521 ///
522 /// ```
523 /// use dlv_list::VecList;
524 ///
525 /// let mut list = VecList::new();
526 ///
527 /// let index_1 = list.push_back(0);
528 /// assert_eq!(list.get_next_index(index_1), None);
529 ///
530 /// let index_2 = list.push_back(5);
531 /// assert_eq!(list.get_next_index(index_1), Some(index_2));
532 /// ```
533 #[must_use]
534 pub fn get_next_index(&self, index: Index<T>) -> Option<Index<T>> {
535 match self.entries.get(index.index())? {
536 Entry::Occupied(entry) if entry.generation == index.generation => {
537 let next_index = entry.next?;
538 let next_entry = self.entries[next_index.get()].occupied_ref();
539 Some(Index::new(next_index, next_entry.generation))
540 }
541 _ => None,
542 }
543 }
544
545 /// Returns the index of the value previous to the value at the given index.
546 ///
547 /// If the index refers to an index not in the list anymore or if the index has been invalidated, then [`None`] will
548 /// be returned.
549 ///
550 /// Complexity: O(1)
551 ///
552 /// # Examples
553 ///
554 /// ```
555 /// use dlv_list::VecList;
556 ///
557 /// let mut list = VecList::new();
558 ///
559 /// let index_1 = list.push_front(0);
560 /// assert_eq!(list.get_previous_index(index_1), None);
561 ///
562 /// let index_2 = list.push_front(5);
563 /// assert_eq!(list.get_previous_index(index_1), Some(index_2));
564 /// ```
565 #[must_use]
566 pub fn get_previous_index(&self, index: Index<T>) -> Option<Index<T>> {
567 match self.entries.get(index.index())? {
568 Entry::Occupied(entry) if entry.generation == index.generation => {
569 let previous_index = entry.previous?;
570 let previous_entry = self.entries[previous_index.get()].occupied_ref();
571 Some(Index::new(previous_index, previous_entry.generation))
572 }
573 _ => None,
574 }
575 }
576
577 /// Connect the node at `index` to the node at `next`. If `index` is `None`, then the head will be
578 /// set to `next`; if `next` is `None`, then the tail will be set to `index`.
579 #[inline]
580 fn update_link(&mut self, index: Option<NonMaxUsize>, next: Option<NonMaxUsize>) {
581 if let Some(index) = index {
582 let entry = self.entries[index.get()].occupied_mut();
583 entry.next = next;
584 } else {
585 self.head = next
586 }
587 if let Some(next) = next {
588 let entry = self.entries[next.get()].occupied_mut();
589 entry.previous = index;
590 } else {
591 self.tail = index;
592 }
593 }
594
595 /// Move the node at `index` to after the node at `target`.
596 ///
597 /// # Panics
598 ///
599 /// Panics if either `index` or `target` is invalidated. Also panics if `index` is the same as `target`.
600 ///
601 /// # Examples
602 ///
603 /// ```
604 /// use dlv_list::VecList;
605 ///
606 /// let mut list = VecList::new();
607 /// let index_1 = list.push_back(0);
608 /// let index_2 = list.push_back(1);
609 /// let index_3 = list.push_back(2);
610 /// let index_4 = list.push_back(3);
611 ///
612 /// list.move_after(index_1, index_3);
613 /// assert_eq!(list.iter().copied().collect::<Vec<_>>(), vec![1, 2, 0, 3]);
614 /// assert_eq!(list.iter().rev().copied().collect::<Vec<_>>(), vec![3, 0, 2, 1]);
615 /// ```
616 pub fn move_after(&mut self, index: Index<T>, target: Index<T>) {
617 let (previous_index, next_index) = match &self.entries[index.index()] {
618 Entry::Occupied(entry) if entry.generation == index.generation => {
619 (entry.previous, entry.next)
620 }
621 _ => panic!("expected occupied entry with correct generation at `index`"),
622 };
623 let target_next_index = match &self.entries[target.index()] {
624 Entry::Occupied(entry) if entry.generation == target.generation => entry.next,
625 _ => panic!("expected occupied entry with correct generation at `target`"),
626 };
627 if target.index == index.index {
628 panic!("cannot move after `index` itself");
629 }
630 if previous_index == Some(target.index) {
631 // Already in the right place
632 return;
633 }
634 self.update_link(previous_index, next_index);
635 self.update_link(Some(target.index), Some(index.index));
636 self.update_link(Some(index.index), target_next_index);
637 }
638
639 /// Move the node at `index` to before the node at `target`.
640 ///
641 /// # Panics
642 ///
643 /// Panics if either `index` or `target` is invalidated. Also panics if `index` is the same as `target`.
644 ///
645 /// # Examples
646 ///
647 /// ```
648 /// use dlv_list::VecList;
649 ///
650 /// let mut list = VecList::new();
651 /// let index_1 = list.push_back(0);
652 /// let index_2 = list.push_back(1);
653 /// let index_3 = list.push_back(2);
654 /// let index_4 = list.push_back(3);
655 ///
656 /// list.move_before(index_1, index_3);
657 /// assert_eq!(list.iter().copied().collect::<Vec<_>>(), vec![1, 0, 2, 3]);
658 /// assert_eq!(list.iter().rev().copied().collect::<Vec<_>>(), vec![3, 2, 0, 1]);
659 /// ```
660 pub fn move_before(&mut self, index: Index<T>, target: Index<T>) {
661 let (previous_index, next_index) = match &self.entries[index.index()] {
662 Entry::Occupied(entry) if entry.generation == index.generation => {
663 (entry.previous, entry.next)
664 }
665 _ => panic!("expected occupied entry with correct generation at `index`"),
666 };
667 let target_previous_index = match &self.entries[target.index()] {
668 Entry::Occupied(entry) if entry.generation == target.generation => entry.previous,
669 _ => panic!("expected occupied entry with correct generation at `target`"),
670 };
671 if target.index == index.index {
672 panic!("cannot move before `index` itself");
673 }
674 if next_index == Some(target.index) {
675 // Already in the right place
676 return;
677 }
678 self.update_link(previous_index, next_index);
679 self.update_link(Some(index.index), Some(target.index));
680 self.update_link(target_previous_index, Some(index.index));
681 }
682
683 /// Creates an indices iterator which will yield all indices of the list in order.
684 ///
685 /// # Examples
686 ///
687 /// ```
688 /// use dlv_list::VecList;
689 ///
690 /// let mut list = VecList::new();
691 /// list.push_front(0);
692 /// list.push_front(5);
693 ///
694 /// let mut indices = list.indices();
695 /// let index = indices.next().unwrap();
696 /// assert_eq!(list.get(index), Some(&5));
697 ///
698 /// let index = indices.next().unwrap();
699 /// assert_eq!(list.get(index), Some(&0));
700 ///
701 /// assert_eq!(indices.next(), None);
702 /// ```
703 #[must_use]
704 pub fn indices(&self) -> Indices<'_, T> {
705 Indices {
706 entries: &self.entries,
707 head: self.head,
708 remaining: self.length,
709 tail: self.tail,
710 }
711 }
712
713 /// Inserts the given value after the value at the given index.
714 ///
715 /// The index of the newly inserted value will be returned.
716 ///
717 /// Complexity: amortized O(1)
718 ///
719 /// # Panics
720 ///
721 /// Panics if the index refers to an index not in the list anymore or if the index has been invalidated. This is
722 /// enforced because this function will consume the value to be inserted, and if it cannot be inserted (due to the
723 /// index not being valid), then it will be lost.
724 ///
725 /// Also panics if the new capacity overflows `usize`.
726 ///
727 /// # Examples
728 ///
729 /// ```
730 /// use dlv_list::VecList;
731 ///
732 /// let mut list = VecList::new();
733 /// list.push_front(0);
734 /// let index_1 = list.push_front(5);
735 /// list.push_front(10);
736 ///
737 /// let index_2 = list.insert_after(index_1, 1000);
738 /// assert_eq!(list.get_next_index(index_1), Some(index_2));
739 /// ```
740 pub fn insert_after(&mut self, index: Index<T>, value: T) -> Index<T> {
741 let next_index = match &mut self.entries[index.index()] {
742 Entry::Occupied(entry) if entry.generation == index.generation => entry.next,
743 _ => panic!("expected occupied entry with correct generation"),
744 };
745 let new_index = self.insert_new(value, Some(index.index), next_index);
746 let entry = self.entries[index.index()].occupied_mut();
747 entry.next = Some(new_index);
748
749 if Some(index.index) == self.tail {
750 self.tail = Some(new_index);
751 }
752
753 if let Some(next_index) = next_index {
754 self.entries[next_index.get()].occupied_mut().previous = Some(new_index);
755 }
756
757 Index::new(new_index, self.generation)
758 }
759
760 /// Inserts the given value before the value at the given index.
761 ///
762 /// The index of the newly inserted value will be returned.
763 ///
764 /// Complexity: amortized O(1)
765 ///
766 /// # Panics
767 ///
768 /// Panics if the index refers to an index not in the list anymore or if the index has been invalidated. This is
769 /// enforced because this function will consume the value to be inserted, and if it cannot be inserted (due to the
770 /// index not being valid), then it will be lost.
771 ///
772 /// Also panics if the new capacity overflows `usize`.
773 ///
774 /// # Examples
775 ///
776 /// ```
777 /// use dlv_list::VecList;
778 ///
779 /// let mut list = VecList::new();
780 /// list.push_front(0);
781 /// let index_1 = list.push_front(5);
782 /// list.push_front(10);
783 ///
784 /// let index_2 = list.insert_before(index_1, 1000);
785 /// assert_eq!(list.get_previous_index(index_1), Some(index_2));
786 /// ```
787 pub fn insert_before(&mut self, index: Index<T>, value: T) -> Index<T> {
788 let previous_index = match &mut self.entries[index.index()] {
789 Entry::Occupied(entry) if entry.generation == index.generation => entry.previous,
790 _ => panic!("expected occupied entry with correct generation"),
791 };
792 let new_index = self.insert_new(value, previous_index, Some(index.index));
793 let entry = self.entries[index.index()].occupied_mut();
794 entry.previous = Some(new_index);
795
796 if Some(index.index) == self.head {
797 self.head = Some(new_index);
798 }
799
800 if let Some(previous_index) = previous_index {
801 self.entries[previous_index.get()].occupied_mut().next = Some(new_index);
802 }
803
804 Index::new(new_index, self.generation)
805 }
806
807 /// Inserts the given value into the list with the assumption that it is currently empty.
808 ///
809 /// # Panics
810 ///
811 /// Panics if the new capacity overflows `usize`.
812 fn insert_empty(&mut self, value: T) -> Index<T> {
813 let generation = self.generation;
814 let index = self.insert_new(value, None, None);
815 self.head = Some(index);
816 self.tail = Some(index);
817 Index::new(index, generation)
818 }
819
820 /// Inserts the given value into the list with its expected previous and next value indices.
821 ///
822 /// # Panics
823 ///
824 /// Panics if the new capacity overflows `usize`.
825 fn insert_new(
826 &mut self,
827 value: T,
828 previous: Option<NonMaxUsize>,
829 next: Option<NonMaxUsize>,
830 ) -> NonMaxUsize {
831 self.length += 1;
832
833 if self.length == usize::max_value() {
834 panic!("reached maximum possible length");
835 }
836
837 match self.vacant_head {
838 Some(index) => {
839 self.vacant_head = self.entries[index.get()].vacant_ref().next;
840 self.entries[index.get()] =
841 Entry::Occupied(OccupiedEntry::new(self.generation, previous, next, value));
842 index
843 }
844 None => {
845 self.entries.push(Entry::Occupied(OccupiedEntry::new(
846 self.generation,
847 previous,
848 next,
849 value,
850 )));
851 NonMaxUsize::new(self.entries.len() - 1).unwrap()
852 }
853 }
854 }
855
856 /// Returns whether or not the list is empty.
857 ///
858 /// # Examples
859 ///
860 /// ```
861 /// use dlv_list::VecList;
862 ///
863 /// let mut list = VecList::new();
864 /// assert!(list.is_empty());
865 ///
866 /// list.push_back(0);
867 /// assert!(!list.is_empty());
868 /// ```
869 #[must_use]
870 pub fn is_empty(&self) -> bool {
871 self.length == 0
872 }
873
874 /// Creates an iterator that yields immutable references to values in the list in order.
875 ///
876 /// # Examples
877 ///
878 /// ```
879 /// use dlv_list::VecList;
880 ///
881 /// let mut list = VecList::new();
882 /// list.push_back(0);
883 /// list.push_back(10);
884 /// list.push_back(200);
885 /// list.push_back(-10);
886 ///
887 /// let mut iter = list.iter();
888 /// assert_eq!(iter.next(), Some(&0));
889 /// assert_eq!(iter.next(), Some(&10));
890 /// assert_eq!(iter.next(), Some(&200));
891 /// assert_eq!(iter.next(), Some(&-10));
892 /// assert_eq!(iter.next(), None);
893 /// ```
894 #[must_use]
895 pub fn iter(&self) -> Iter<'_, T> {
896 Iter {
897 entries: &self.entries,
898 head: self.head,
899 remaining: self.length,
900 tail: self.tail,
901 }
902 }
903
904 /// Creates an iterator that yields mutable references to values in the list in order.
905 ///
906 /// # Examples
907 ///
908 /// ```
909 /// use dlv_list::VecList;
910 ///
911 /// let mut list = VecList::new();
912 /// list.push_back(0);
913 /// list.push_back(10);
914 /// list.push_back(200);
915 /// list.push_back(-10);
916 ///
917 /// let mut iter = list.iter_mut();
918 /// assert_eq!(iter.next(), Some(&mut 0));
919 /// assert_eq!(iter.next(), Some(&mut 10));
920 /// assert_eq!(iter.next(), Some(&mut 200));
921 /// assert_eq!(iter.next(), Some(&mut -10));
922 /// assert_eq!(iter.next(), None);
923 /// ```
924 #[must_use]
925 pub fn iter_mut(&mut self) -> IterMut<'_, T> {
926 IterMut {
927 entries: &mut self.entries,
928 head: self.head,
929 phantom: PhantomData,
930 remaining: self.length,
931 tail: self.tail,
932 }
933 }
934
935 /// Returns the number of values in the list.
936 ///
937 /// # Examples
938 ///
939 /// ```
940 /// use dlv_list::VecList;
941 ///
942 /// let mut list = VecList::new();
943 /// assert_eq!(list.len(), 0);
944 ///
945 /// list.push_back(0);
946 /// list.push_back(1);
947 /// list.push_back(2);
948 /// assert_eq!(list.len(), 3);
949 /// ```
950 #[must_use]
951 pub fn len(&self) -> usize {
952 self.length
953 }
954
955 /// Creates a new list with no initial capacity.
956 ///
957 /// # Examples
958 ///
959 /// ```
960 /// use dlv_list::VecList;
961 ///
962 /// let mut list = VecList::new();
963 /// let index = list.push_back(0);
964 /// assert_eq!(list.get(index), Some(&0));
965 /// ```
966 #[must_use]
967 pub fn new() -> Self {
968 VecList::default()
969 }
970
971 /// Reorganizes the existing values to ensure maximum cache locality and shrinks the list such that the capacity is
972 /// exactly [`minimum_capacity`].
973 ///
974 /// This function can be used to actually increase the capacity of the list.
975 ///
976 /// Complexity: O(n)
977 ///
978 /// # Panics
979 ///
980 /// Panics if the given minimum capacity is less than the current length of the list.
981 ///
982 /// # Examples
983 ///
984 /// ```
985 /// use dlv_list::VecList;
986 ///
987 /// let mut list = VecList::new();
988 /// let index_1 = list.push_back(5);
989 /// let index_2 = list.push_back(10);
990 /// let index_3 = list.push_front(100);
991 /// list.remove(index_1);
992 ///
993 /// assert!(list.capacity() >= 3);
994 ///
995 /// let mut map = list.pack_to(list.len() + 5);
996 /// assert_eq!(list.capacity(), 7);
997 /// assert_eq!(map.len(), 2);
998 ///
999 /// let index_2 = map.remove(&index_2).unwrap();
1000 /// let index_3 = map.remove(&index_3).unwrap();
1001 ///
1002 /// assert_eq!(list.get(index_2), Some(&10));
1003 /// assert_eq!(list.get(index_3), Some(&100));
1004 ///
1005 /// let mut iter = list.iter();
1006 /// assert_eq!(iter.next(), Some(&100));
1007 /// assert_eq!(iter.next(), Some(&10));
1008 /// assert_eq!(iter.next(), None);
1009 /// ```
1010 #[cfg(feature = "std")]
1011 pub fn pack_to(&mut self, minimum_capacity: usize) -> HashMap<Index<T>, Index<T>> {
1012 assert!(
1013 minimum_capacity >= self.length,
1014 "cannot shrink to capacity lower than current length"
1015 );
1016
1017 let mut count = NonMaxUsize::zero();
1018 let mut entries = Vec::with_capacity(minimum_capacity);
1019 let generation = create_initial_generation();
1020 let length = self.length;
1021 let mut map = HashMap::with_capacity(length);
1022 let mut next_index = self.head;
1023
1024 while let Some(index) = next_index {
1025 let mut entry = self.remove_entry(index).expect("expected occupied entry");
1026 next_index = entry.next;
1027
1028 let _ = map.insert(
1029 Index::new(index, entry.generation),
1030 Index::new(count, generation),
1031 );
1032
1033 entry.generation = generation;
1034 entry.previous = if count > 0 {
1035 Some(count.checked_sub(1).unwrap())
1036 } else {
1037 None
1038 };
1039 entry.next = if count < length - 1 {
1040 Some(count.checked_add(1).expect("overflow"))
1041 } else {
1042 None
1043 };
1044
1045 entries.push(Entry::Occupied(entry));
1046 count = count.checked_add(1).expect("overflow");
1047 }
1048
1049 self.entries = entries;
1050 self.generation = generation;
1051 self.length = length;
1052 self.vacant_head = None;
1053
1054 if self.length > 0 {
1055 self.head = Some(NonMaxUsize::zero());
1056 // Safety: `self.length - 1` is always less than `usize::MAX`.
1057 self.tail = Some(unsafe { NonMaxUsize::new_unchecked(length - 1) });
1058 } else {
1059 self.head = None;
1060 self.tail = None;
1061 }
1062
1063 map
1064 }
1065
1066 /// Reorganizes the existing values to ensure maximum cache locality and shrinks the list such that no additional
1067 /// capacity exists.
1068 ///
1069 /// This is equivalent to calling [`VecList::pack_to`] with the current length.
1070 ///
1071 /// Complexity: O(n)
1072 ///
1073 /// # Examples
1074 ///
1075 /// ```
1076 /// use dlv_list::VecList;
1077 ///
1078 /// let mut list = VecList::new();
1079 /// let index_1 = list.push_back(5);
1080 /// let index_2 = list.push_back(10);
1081 /// let index_3 = list.push_front(100);
1082 /// list.remove(index_1);
1083 ///
1084 /// assert!(list.capacity() >= 3);
1085 ///
1086 /// let mut map = list.pack_to_fit();
1087 /// assert_eq!(list.capacity(), 2);
1088 /// assert_eq!(map.len(), 2);
1089 ///
1090 /// let index_2 = map.remove(&index_2).unwrap();
1091 /// let index_3 = map.remove(&index_3).unwrap();
1092 ///
1093 /// assert_eq!(list.get(index_2), Some(&10));
1094 /// assert_eq!(list.get(index_3), Some(&100));
1095 ///
1096 /// let mut iter = list.iter();
1097 /// assert_eq!(iter.next(), Some(&100));
1098 /// assert_eq!(iter.next(), Some(&10));
1099 /// assert_eq!(iter.next(), None);
1100 /// ```
1101 #[cfg(feature = "std")]
1102 pub fn pack_to_fit(&mut self) -> HashMap<Index<T>, Index<T>> {
1103 self.pack_to(self.length)
1104 }
1105
1106 /// Removes and returns the value at the back of the list, if it exists.
1107 ///
1108 /// Complexity: O(1)
1109 ///
1110 /// # Examples
1111 ///
1112 /// ```
1113 /// use dlv_list::VecList;
1114 ///
1115 /// let mut list = VecList::new();
1116 /// assert_eq!(list.pop_back(), None);
1117 ///
1118 /// list.push_back(0);
1119 /// list.push_back(1);
1120 /// list.push_back(2);
1121 /// assert_eq!(list.len(), 3);
1122 ///
1123 /// assert_eq!(list.pop_back(), Some(2));
1124 /// assert_eq!(list.len(), 2);
1125 /// ```
1126 pub fn pop_back(&mut self) -> Option<T> {
1127 self.remove_entry(self.tail?).map(|entry| entry.value)
1128 }
1129
1130 /// Removes and returns the value at the front of the list, if it exists.
1131 ///
1132 /// Complexity: O(1)
1133 ///
1134 /// # Examples
1135 ///
1136 /// ```
1137 /// use dlv_list::VecList;
1138 ///
1139 /// let mut list = VecList::new();
1140 /// assert_eq!(list.pop_front(), None);
1141 ///
1142 /// list.push_front(0);
1143 /// list.push_front(1);
1144 /// list.push_front(2);
1145 /// assert_eq!(list.len(), 3);
1146 ///
1147 /// assert_eq!(list.pop_front(), Some(2));
1148 /// assert_eq!(list.len(), 2);
1149 /// ```
1150 pub fn pop_front(&mut self) -> Option<T> {
1151 self.remove_entry(self.head?).map(|entry| entry.value)
1152 }
1153
1154 /// Inserts the given value to the back of the list.
1155 ///
1156 /// The index of the newly inserted value will be returned.
1157 ///
1158 /// Complexity: amortized O(1)
1159 ///
1160 /// # Panics
1161 ///
1162 /// Panics if the new capacity overflows `usize`.
1163 ///
1164 /// # Examples
1165 ///
1166 /// ```
1167 /// use dlv_list::VecList;
1168 ///
1169 /// let mut list = VecList::new();
1170 /// let index = list.push_back(0);
1171 /// assert_eq!(list.get(index), Some(&0));
1172 /// ```
1173 pub fn push_back(&mut self, value: T) -> Index<T> {
1174 let tail_index = match self.tail {
1175 Some(index) => index,
1176 None => return self.insert_empty(value),
1177 };
1178 let index = self.insert_new(value, Some(tail_index), None);
1179 self.entries[tail_index.get()].occupied_mut().next = Some(index);
1180 self.tail = Some(index);
1181 Index::new(index, self.generation)
1182 }
1183
1184 /// Inserts the given value to the front of the list.
1185 ///
1186 /// The index of the newly inserted value will be returned.
1187 ///
1188 /// Complexity: amortized O(1)
1189 ///
1190 /// # Panics
1191 ///
1192 /// Panics if the new capacity overflows `usize`.
1193 ///
1194 /// # Examples
1195 ///
1196 /// ```
1197 /// use dlv_list::VecList;
1198 ///
1199 /// let mut list = VecList::new();
1200 /// let index = list.push_front(0);
1201 /// assert_eq!(list.get(index), Some(&0));
1202 /// ```
1203 pub fn push_front(&mut self, value: T) -> Index<T> {
1204 let head_index = match self.head {
1205 Some(index) => index,
1206 None => return self.insert_empty(value),
1207 };
1208 let index = self.insert_new(value, None, Some(head_index));
1209 self.entries[head_index.get()].occupied_mut().previous = Some(index);
1210 self.head = Some(index);
1211 Index::new(index, self.generation)
1212 }
1213
1214 /// Removes and returns the value at the given index, if it exists.
1215 ///
1216 /// If the index refers to an index not in the list anymore or if the index has been invalidated, then [`None`] will
1217 /// be returned and the list will be unaffected.
1218 ///
1219 /// Complexity: O(1)
1220 ///
1221 /// # Examples
1222 ///
1223 /// ```
1224 /// use dlv_list::VecList;
1225 ///
1226 /// let mut list = VecList::new();
1227 /// let index = list.push_back(0);
1228 /// assert_eq!(list.remove(index), Some(0));
1229 /// assert_eq!(list.remove(index), None);
1230 /// ```
1231 pub fn remove(&mut self, index: Index<T>) -> Option<T> {
1232 let (previous_index, next_index) = match &self.entries[index.index()] {
1233 Entry::Occupied(entry) if entry.generation == index.generation => {
1234 (entry.previous, entry.next)
1235 }
1236 _ => return None,
1237 };
1238 Some(
1239 self
1240 .remove_helper(previous_index, index.index, next_index)
1241 .value,
1242 )
1243 }
1244
1245 /// Removes and returns the entry at the given index, if it exists.
1246 ///
1247 /// If the index refers to an index not in the list anymore or if the index has been invalidated, then [`None`] will
1248 /// be returned and the list will be unaffected.
1249 fn remove_entry(&mut self, index: NonMaxUsize) -> Option<OccupiedEntry<T>> {
1250 let (previous_index, next_index) = match &self.entries[index.get()] {
1251 Entry::Occupied(entry) => (entry.previous, entry.next),
1252 Entry::Vacant(_) => return None,
1253 };
1254 Some(self.remove_helper(previous_index, index, next_index))
1255 }
1256
1257 /// Removes and returns the entry at the given index with the entries previous and next index
1258 /// values.
1259 ///
1260 /// It is assumed that there is an entry at the given index.
1261 ///
1262 /// # Panics
1263 ///
1264 /// Panics if called when the list is empty. Behavior is undefined if provided indices do not follow the expected
1265 /// constraints.
1266 fn remove_helper(
1267 &mut self,
1268 previous_index: Option<NonMaxUsize>,
1269 index: NonMaxUsize,
1270 next_index: Option<NonMaxUsize>,
1271 ) -> OccupiedEntry<T> {
1272 let head_index = self.head.expect("expected head index");
1273 let tail_index = self.tail.expect("expected tail index");
1274 let vacant_head = self.vacant_head;
1275 let removed_entry = mem::replace(
1276 &mut self.entries[index.get()],
1277 Entry::Vacant(VacantEntry::new(vacant_head)),
1278 );
1279
1280 self.generation = self.generation.wrapping_add(1);
1281 self.length -= 1;
1282 self.vacant_head = Some(index);
1283
1284 if index == head_index && index == tail_index {
1285 self.head = None;
1286 self.tail = None;
1287 } else if index == head_index {
1288 self.entries[next_index.expect("expected next entry to exist").get()]
1289 .occupied_mut()
1290 .previous = None;
1291 self.head = next_index;
1292 } else if index == tail_index {
1293 self.entries[previous_index
1294 .expect("expected previous entry to exist")
1295 .get()]
1296 .occupied_mut()
1297 .next = None;
1298 self.tail = previous_index;
1299 } else {
1300 self.entries[next_index.expect("expected next entry to exist").get()]
1301 .occupied_mut()
1302 .previous = previous_index;
1303 self.entries[previous_index
1304 .expect("expected previous entry to exist")
1305 .get()]
1306 .occupied_mut()
1307 .next = next_index;
1308 }
1309
1310 removed_entry.occupied()
1311 }
1312
1313 /// Reserves capacity for the given expected size increase.
1314 ///
1315 /// The collection may reserve more space to avoid frequent reallocations. After calling this function, capacity will
1316 /// be greater than or equal to `self.len() + additional_capacity`. Does nothing if the current capacity is already
1317 /// sufficient.
1318 ///
1319 /// # Panics
1320 ///
1321 /// Panics if the new capacity overflows `usize`.
1322 ///
1323 /// # Examples
1324 ///
1325 /// ```
1326 /// use dlv_list::VecList;
1327 ///
1328 /// let mut list: VecList<u32> = VecList::new();
1329 /// assert_eq!(list.capacity(), 0);
1330 ///
1331 /// list.reserve(10);
1332 /// assert!(list.capacity() >= 10);
1333 /// ```
1334 pub fn reserve(&mut self, additional_capacity: usize) {
1335 self.entries.reserve(additional_capacity);
1336 }
1337
1338 /// Removes all elements from the list not satisfying the given predicate.
1339 ///
1340 /// Complexity: O(n)
1341 ///
1342 /// # Examples
1343 ///
1344 /// ```
1345 /// use dlv_list::VecList;
1346 ///
1347 /// let mut list = VecList::new();
1348 /// list.push_back(0);
1349 /// list.push_back(-1);
1350 /// list.push_back(1);
1351 /// list.push_back(-2);
1352 /// list.retain(|&mut value| value >= 0);
1353 ///
1354 /// let mut iter = list.iter();
1355 /// assert_eq!(iter.next(), Some(&0));
1356 /// assert_eq!(iter.next(), Some(&1));
1357 /// assert_eq!(iter.next(), None);
1358 /// ```
1359 pub fn retain<Predicate>(&mut self, mut predicate: Predicate)
1360 where
1361 Predicate: FnMut(&mut T) -> bool,
1362 {
1363 let mut next_index = self.head;
1364
1365 while let Some(index) = next_index {
1366 let entry = self.entries[index.get()].occupied_mut();
1367 next_index = entry.next;
1368
1369 if !predicate(&mut entry.value) {
1370 let _ = self.remove_entry(index);
1371 }
1372 }
1373 }
1374
1375 /// Creates a new list with the given capacity.
1376 ///
1377 /// # Examples
1378 ///
1379 /// ```
1380 /// use dlv_list::VecList;
1381 ///
1382 /// let mut list: VecList<u32> = VecList::new();
1383 /// assert_eq!(list.capacity(), 0);
1384 ///
1385 /// let mut list: VecList<u32> = VecList::with_capacity(10);
1386 /// assert_eq!(list.capacity(), 10);
1387 /// ```
1388 #[must_use]
1389 pub fn with_capacity(capacity: usize) -> Self {
1390 VecList {
1391 entries: Vec::with_capacity(capacity),
1392 generation: create_initial_generation(),
1393 head: None,
1394 length: 0,
1395 tail: None,
1396 vacant_head: None,
1397 }
1398 }
1399 }
1400
1401 impl<T> Debug for VecList<T>
1402 where
1403 T: Debug,
1404 {
1405 fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
1406 formatter.debug_list().entries(self.iter()).finish()
1407 }
1408 }
1409
1410 impl<T> Default for VecList<T> {
1411 fn default() -> Self {
1412 VecList {
1413 entries: Vec::default(),
1414 generation: create_initial_generation(),
1415 head: None,
1416 length: 0,
1417 tail: None,
1418 vacant_head: None,
1419 }
1420 }
1421 }
1422
1423 impl<T> Eq for VecList<T> where T: Eq {}
1424
1425 impl<T> Extend<T> for VecList<T> {
1426 fn extend<Iter>(&mut self, iter: Iter)
1427 where
1428 Iter: IntoIterator<Item = T>,
1429 {
1430 let iter = iter.into_iter();
1431 self.reserve(iter.size_hint().0);
1432
1433 for value in iter {
1434 let _ = self.push_back(value);
1435 }
1436 }
1437 }
1438
1439 impl<'a, T> Extend<&'a T> for VecList<T>
1440 where
1441 T: 'a + Copy,
1442 {
1443 fn extend<Iter>(&mut self, iter: Iter)
1444 where
1445 Iter: IntoIterator<Item = &'a T>,
1446 {
1447 self.extend(iter.into_iter().copied());
1448 }
1449 }
1450
1451 impl<T> FromIterator<T> for VecList<T> {
1452 fn from_iter<Iter>(iter: Iter) -> Self
1453 where
1454 Iter: IntoIterator<Item = T>,
1455 {
1456 let mut list = VecList::new();
1457 list.extend(iter);
1458 list
1459 }
1460 }
1461
1462 impl<T> Hash for VecList<T>
1463 where
1464 T: Hash,
1465 {
1466 fn hash<StateHasher>(&self, state: &mut StateHasher)
1467 where
1468 StateHasher: Hasher,
1469 {
1470 self.len().hash(state);
1471
1472 for value in self {
1473 value.hash(state);
1474 }
1475 }
1476 }
1477
1478 impl<T> ops::Index<Index<T>> for VecList<T> {
1479 type Output = T;
1480
1481 fn index(&self, index: Index<T>) -> &Self::Output {
1482 self.get(index).expect("expected entry at index")
1483 }
1484 }
1485
1486 impl<T> ops::IndexMut<Index<T>> for VecList<T> {
1487 fn index_mut(&mut self, index: Index<T>) -> &mut Self::Output {
1488 self.get_mut(index).expect("expected entry at index")
1489 }
1490 }
1491
1492 impl<T> IntoIterator for VecList<T> {
1493 type IntoIter = IntoIter<T>;
1494 type Item = T;
1495
1496 fn into_iter(self) -> Self::IntoIter {
1497 IntoIter {
1498 head: self.head,
1499 remaining: self.length,
1500 tail: self.tail,
1501 list: self,
1502 }
1503 }
1504 }
1505
1506 impl<'a, T> IntoIterator for &'a VecList<T> {
1507 type IntoIter = Iter<'a, T>;
1508 type Item = &'a T;
1509
1510 fn into_iter(self) -> Self::IntoIter {
1511 Iter {
1512 entries: &self.entries,
1513 head: self.head,
1514 remaining: self.length,
1515 tail: self.tail,
1516 }
1517 }
1518 }
1519
1520 impl<'a, T> IntoIterator for &'a mut VecList<T> {
1521 type IntoIter = IterMut<'a, T>;
1522 type Item = &'a mut T;
1523
1524 fn into_iter(self) -> Self::IntoIter {
1525 IterMut {
1526 entries: &mut self.entries,
1527 head: self.head,
1528 phantom: PhantomData,
1529 remaining: self.length,
1530 tail: self.tail,
1531 }
1532 }
1533 }
1534
1535 impl<T> Ord for VecList<T>
1536 where
1537 T: Ord,
1538 {
1539 fn cmp(&self, other: &Self) -> Ordering {
1540 self.iter().cmp(other)
1541 }
1542 }
1543
1544 impl<T> PartialEq for VecList<T>
1545 where
1546 T: PartialEq,
1547 {
1548 fn eq(&self, other: &Self) -> bool {
1549 self.len() == other.len() && self.iter().eq(other)
1550 }
1551 }
1552
1553 impl<T> PartialEq<LinkedList<T>> for VecList<T>
1554 where
1555 T: PartialEq,
1556 {
1557 fn eq(&self, other: &LinkedList<T>) -> bool {
1558 self.len() == other.len() && self.iter().eq(other)
1559 }
1560 }
1561
1562 impl<T> PartialEq<VecList<T>> for LinkedList<T>
1563 where
1564 T: PartialEq,
1565 {
1566 fn eq(&self, other: &VecList<T>) -> bool {
1567 other == self
1568 }
1569 }
1570
1571 impl<T> PartialEq<Vec<T>> for VecList<T>
1572 where
1573 T: PartialEq,
1574 {
1575 fn eq(&self, other: &Vec<T>) -> bool {
1576 self.len() == other.len() && self.iter().eq(other)
1577 }
1578 }
1579
1580 impl<T> PartialEq<VecList<T>> for Vec<T>
1581 where
1582 T: PartialEq,
1583 {
1584 fn eq(&self, other: &VecList<T>) -> bool {
1585 other == self
1586 }
1587 }
1588
1589 impl<T, const N: usize> PartialEq<[T; N]> for VecList<T>
1590 where
1591 T: PartialEq,
1592 {
1593 fn eq(&self, other: &[T; N]) -> bool {
1594 self.len() == other.len() && self.iter().eq(other.iter())
1595 }
1596 }
1597
1598 impl<T, const N: usize> PartialEq<VecList<T>> for [T; N]
1599 where
1600 T: PartialEq,
1601 {
1602 fn eq(&self, other: &VecList<T>) -> bool {
1603 other == self
1604 }
1605 }
1606
1607 impl<'a, T> PartialEq<&'a [T]> for VecList<T>
1608 where
1609 T: PartialEq,
1610 {
1611 fn eq(&self, other: &&'a [T]) -> bool {
1612 self.len() == other.len() && self.iter().eq(other.iter())
1613 }
1614 }
1615
1616 impl<T> PartialEq<VecList<T>> for &'_ [T]
1617 where
1618 T: PartialEq,
1619 {
1620 fn eq(&self, other: &VecList<T>) -> bool {
1621 other == self
1622 }
1623 }
1624
1625 impl<T> PartialOrd for VecList<T>
1626 where
1627 T: PartialOrd<T>,
1628 {
1629 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1630 self.iter().partial_cmp(other)
1631 }
1632 }
1633
1634 /// A wrapper type that indicates an index into the list.
1635 ///
1636 /// This index may be invalidated by operations on the list itself.
1637 pub struct Index<T> {
1638 /// The generation of the entry currently at this index. This is used to avoid the ABA problem.
1639 generation: u64,
1640
1641 /// The actual index into the entry list.
1642 index: NonMaxUsize,
1643
1644 /// This type is parameterized on the entry data type to avoid indices being used across differently typed lists.
1645 phantom: PhantomData<T>,
1646 }
1647
1648 impl<T> Clone for Index<T> {
1649 fn clone(&self) -> Self {
1650 *self
1651 }
1652 }
1653
1654 impl<T> Copy for Index<T> {}
1655
1656 impl<T> Debug for Index<T> {
1657 fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
1658 formatter
1659 .debug_tuple("Index")
1660 .field(&self.index)
1661 .field(&self.generation)
1662 .finish()
1663 }
1664 }
1665
1666 impl<T> Eq for Index<T> {}
1667
1668 impl<T> Hash for Index<T> {
1669 fn hash<StateHasher>(&self, hasher: &mut StateHasher)
1670 where
1671 StateHasher: Hasher,
1672 {
1673 self.index.hash(hasher);
1674 self.generation.hash(hasher);
1675 }
1676 }
1677
1678 impl<T> PartialEq for Index<T> {
1679 fn eq(&self, other: &Self) -> bool {
1680 self.generation == other.generation && self.index == other.index
1681 }
1682 }
1683
1684 impl<T> Index<T> {
1685 /// Convenience function for creating new index.
1686 #[must_use]
1687 pub(self) fn new(index: NonMaxUsize, generation: u64) -> Index<T> {
1688 Index {
1689 generation,
1690 index,
1691 phantom: PhantomData,
1692 }
1693 }
1694
1695 /// Get the index as usize
1696 #[inline]
1697 pub(self) fn index(&self) -> usize {
1698 self.index.get()
1699 }
1700 }
1701
1702 /// An entry in the list. This can be either occupied or vacant.
1703 #[derive(Clone)]
1704 enum Entry<T> {
1705 /// An occupied entry contains actual entry data inserted by the user.
1706 Occupied(OccupiedEntry<T>),
1707
1708 /// A vacant entry is one that can be reused.
1709 Vacant(VacantEntry),
1710 }
1711
1712 impl<T> Entry<T> {
1713 /// Returns the occupied entry by moving it out of the entry.
1714 ///
1715 /// # Panics
1716 ///
1717 /// Panics if the variant is actually [`Entry::Vacant`].
1718 #[must_use]
1719 pub fn occupied(self) -> OccupiedEntry<T> {
1720 match self {
1721 Entry::Occupied(entry) => entry,
1722 Entry::Vacant(_) => panic!("expected occupied entry"),
1723 }
1724 }
1725
1726 /// Returns an immutable reference to the occupied entry.
1727 ///
1728 /// # Panics
1729 ///
1730 /// Panics if the variant is actually [`Entry::Vacant`].
1731 #[must_use]
1732 pub fn occupied_ref(&self) -> &OccupiedEntry<T> {
1733 match self {
1734 Entry::Occupied(entry) => entry,
1735 Entry::Vacant(_) => panic!("expected occupied entry"),
1736 }
1737 }
1738
1739 /// Returns a mutable reference to the occupied entry.
1740 ///
1741 /// # Panics
1742 ///
1743 /// Panics if the variant is actually [`Entry::Vacant`].
1744 #[must_use]
1745 pub fn occupied_mut(&mut self) -> &mut OccupiedEntry<T> {
1746 match self {
1747 Entry::Occupied(entry) => entry,
1748 Entry::Vacant(_) => panic!("expected occupied entry"),
1749 }
1750 }
1751
1752 /// Returns an immutable reference to the vacant entry.
1753 ///
1754 /// # Panics
1755 ///
1756 /// Panics if the variant is actually [`Entry::Occupied`].
1757 #[must_use]
1758 pub fn vacant_ref(&self) -> &VacantEntry {
1759 match self {
1760 Entry::Vacant(entry) => entry,
1761 Entry::Occupied(_) => panic!("expected vacant entry"),
1762 }
1763 }
1764 }
1765
1766 /// An occupied entry in the list.
1767 #[derive(Clone)]
1768 struct OccupiedEntry<T> {
1769 /// The generation of when this entry was inserted. This is used to avoid the ABA problem.
1770 generation: u64,
1771
1772 /// The index of the next occupied entry in the list.
1773 next: Option<NonMaxUsize>,
1774
1775 /// The index of the previous occupied entry in the list.
1776 previous: Option<NonMaxUsize>,
1777
1778 /// The actual value being stored in this entry.
1779 value: T,
1780 }
1781
1782 impl<T> OccupiedEntry<T> {
1783 /// Convenience function for creating a new occupied entry.
1784 #[must_use]
1785 pub fn new(
1786 generation: u64,
1787 previous: Option<NonMaxUsize>,
1788 next: Option<NonMaxUsize>,
1789 value: T,
1790 ) -> OccupiedEntry<T> {
1791 OccupiedEntry {
1792 generation,
1793 next,
1794 previous,
1795 value,
1796 }
1797 }
1798 }
1799
1800 /// A vacant entry in the list.
1801 #[derive(Clone, Debug)]
1802 struct VacantEntry {
1803 /// The index of the next vacant entry in the list.
1804 next: Option<NonMaxUsize>,
1805 }
1806
1807 impl VacantEntry {
1808 /// Convenience function for creating a new vacant entry.
1809 #[must_use]
1810 pub fn new(next: Option<NonMaxUsize>) -> VacantEntry {
1811 VacantEntry { next }
1812 }
1813 }
1814
1815 /// An iterator that yields and removes all entries from the list.
1816 pub struct Drain<'a, T> {
1817 /// The index of the head of the unvisited portion of the list.
1818 head: Option<NonMaxUsize>,
1819
1820 /// A reference to the entry list.
1821 list: &'a mut VecList<T>,
1822
1823 /// The number of entries that have not been visited.
1824 remaining: usize,
1825
1826 /// The index of the tail of the unvisited portion of the list.
1827 tail: Option<NonMaxUsize>,
1828 }
1829
1830 impl<T> Drain<'_, T> {
1831 /// Creates an iterator that yields immutable references to entries in the list.
1832 #[must_use]
1833 pub fn iter(&self) -> Iter<'_, T> {
1834 Iter {
1835 entries: &self.list.entries,
1836 head: self.head,
1837 remaining: self.remaining,
1838 tail: self.tail,
1839 }
1840 }
1841 }
1842
1843 impl<T> Debug for Drain<'_, T>
1844 where
1845 T: Debug,
1846 {
1847 fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
1848 formatter.write_str("Drain(")?;
1849 formatter.debug_list().entries(self.iter()).finish()?;
1850 formatter.write_str(")")
1851 }
1852 }
1853
1854 impl<T> DoubleEndedIterator for Drain<'_, T> {
1855 fn next_back(&mut self) -> Option<Self::Item> {
1856 if self.remaining == 0 {
1857 None
1858 } else {
1859 self.tail.map(|index| {
1860 let entry = self
1861 .list
1862 .remove_entry(index)
1863 .expect("expected occupied entry");
1864 self.tail = entry.previous;
1865 self.remaining -= 1;
1866 entry.value
1867 })
1868 }
1869 }
1870 }
1871
1872 impl<T> Drop for Drain<'_, T> {
1873 fn drop(&mut self) {
1874 self.list.clear();
1875 }
1876 }
1877
1878 impl<T> ExactSizeIterator for Drain<'_, T> {}
1879
1880 impl<T> FusedIterator for Drain<'_, T> {}
1881
1882 impl<T> Iterator for Drain<'_, T> {
1883 type Item = T;
1884
1885 fn next(&mut self) -> Option<Self::Item> {
1886 if self.remaining == 0 {
1887 None
1888 } else {
1889 self.head.map(|index| {
1890 let entry = self
1891 .list
1892 .remove_entry(index)
1893 .expect("expected occupied entry");
1894 self.head = entry.next;
1895 self.remaining -= 1;
1896 entry.value
1897 })
1898 }
1899 }
1900
1901 fn size_hint(&self) -> (usize, Option<usize>) {
1902 (self.remaining, Some(self.remaining))
1903 }
1904 }
1905
1906 /// An iterator that yields all indices in the list.
1907 pub struct Indices<'a, T> {
1908 /// A reference to the actual storage for the entry list.
1909 entries: &'a Vec<Entry<T>>,
1910
1911 /// The index of the head of the unvisited portion of the list.
1912 head: Option<NonMaxUsize>,
1913
1914 /// The number of entries that have not been visited.
1915 remaining: usize,
1916
1917 /// The index of the tail of the unvisited portion of the list.
1918 tail: Option<NonMaxUsize>,
1919 }
1920
1921 impl<T> Clone for Indices<'_, T> {
1922 fn clone(&self) -> Self {
1923 Indices {
1924 entries: self.entries,
1925 head: self.head,
1926 remaining: self.remaining,
1927 tail: self.tail,
1928 }
1929 }
1930 }
1931
1932 impl<T> Debug for Indices<'_, T>
1933 where
1934 T: Debug,
1935 {
1936 fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
1937 formatter.write_str("Indices(")?;
1938 formatter.debug_list().entries(self.clone()).finish()?;
1939 formatter.write_str(")")
1940 }
1941 }
1942
1943 impl<T> DoubleEndedIterator for Indices<'_, T> {
1944 fn next_back(&mut self) -> Option<Self::Item> {
1945 if self.remaining == 0 {
1946 None
1947 } else {
1948 self.tail.map(|index| {
1949 let entry = self.entries[index.get()].occupied_ref();
1950 let index = Index::new(index, entry.generation);
1951 self.tail = entry.previous;
1952 self.remaining -= 1;
1953 index
1954 })
1955 }
1956 }
1957 }
1958
1959 impl<T> ExactSizeIterator for Indices<'_, T> {}
1960
1961 impl<T> FusedIterator for Indices<'_, T> {}
1962
1963 impl<T> Iterator for Indices<'_, T> {
1964 type Item = Index<T>;
1965
1966 fn next(&mut self) -> Option<Self::Item> {
1967 if self.remaining == 0 {
1968 None
1969 } else {
1970 self.head.map(|index| {
1971 let entry = self.entries[index.get()].occupied_ref();
1972 let index = Index::new(index, entry.generation);
1973 self.head = entry.next;
1974 self.remaining -= 1;
1975 index
1976 })
1977 }
1978 }
1979
1980 fn size_hint(&self) -> (usize, Option<usize>) {
1981 (self.remaining, Some(self.remaining))
1982 }
1983 }
1984
1985 /// An iterator that moves all entries out of the entry list.
1986 #[derive(Clone)]
1987 pub struct IntoIter<T> {
1988 /// The index of the head of the unvisited portion of the list.
1989 head: Option<NonMaxUsize>,
1990
1991 /// The entry list from which entries are yielded.
1992 list: VecList<T>,
1993
1994 /// The number of entries that have not been visited.
1995 remaining: usize,
1996
1997 /// The index of the tail of the unvisited portion of the list.
1998 tail: Option<NonMaxUsize>,
1999 }
2000
2001 impl<T> IntoIter<T> {
2002 /// Creates an iterator that yields immutable references to entries in the list.
2003 #[must_use]
2004 pub fn iter(&self) -> Iter<'_, T> {
2005 Iter {
2006 entries: &self.list.entries,
2007 head: self.head,
2008 remaining: self.remaining,
2009 tail: self.tail,
2010 }
2011 }
2012 }
2013
2014 impl<T> Debug for IntoIter<T>
2015 where
2016 T: Debug,
2017 {
2018 fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
2019 formatter.write_str("IntoIter(")?;
2020 formatter.debug_list().entries(self.iter()).finish()?;
2021 formatter.write_str(")")
2022 }
2023 }
2024
2025 impl<T> DoubleEndedIterator for IntoIter<T> {
2026 fn next_back(&mut self) -> Option<Self::Item> {
2027 if self.remaining == 0 {
2028 None
2029 } else {
2030 self.tail.map(|index| {
2031 let entry = self
2032 .list
2033 .remove_entry(index)
2034 .expect("expected occupied entry");
2035 self.tail = entry.previous;
2036 self.remaining -= 1;
2037 entry.value
2038 })
2039 }
2040 }
2041 }
2042
2043 impl<T> ExactSizeIterator for IntoIter<T> {}
2044
2045 impl<T> FusedIterator for IntoIter<T> {}
2046
2047 impl<T> Iterator for IntoIter<T> {
2048 type Item = T;
2049
2050 fn next(&mut self) -> Option<Self::Item> {
2051 if self.remaining == 0 {
2052 None
2053 } else {
2054 self.head.map(|index| {
2055 let entry = self
2056 .list
2057 .remove_entry(index)
2058 .expect("expected occupied entry");
2059 self.head = entry.next;
2060 self.remaining -= 1;
2061 entry.value
2062 })
2063 }
2064 }
2065
2066 fn size_hint(&self) -> (usize, Option<usize>) {
2067 (self.remaining, Some(self.remaining))
2068 }
2069 }
2070
2071 /// An iterator that yields immutable references to entries in the list.
2072 pub struct Iter<'a, T> {
2073 /// A reference to the actual storage for the entry list.
2074 entries: &'a Vec<Entry<T>>,
2075
2076 /// The index of the head of the unvisited portion of the list.
2077 head: Option<NonMaxUsize>,
2078
2079 /// The number of entries that have not been visited.
2080 remaining: usize,
2081
2082 /// The index of the tail of the unvisited portion of the list.
2083 tail: Option<NonMaxUsize>,
2084 }
2085
2086 impl<'a, T> Clone for Iter<'a, T> {
2087 fn clone(&self) -> Iter<'a, T> {
2088 Iter {
2089 entries: self.entries,
2090 head: self.head,
2091 remaining: self.remaining,
2092 tail: self.tail,
2093 }
2094 }
2095 }
2096
2097 impl<T> Debug for Iter<'_, T>
2098 where
2099 T: Debug,
2100 {
2101 fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
2102 formatter.write_str("Iter(")?;
2103 formatter.debug_list().entries(self.clone()).finish()?;
2104 formatter.write_str(")")
2105 }
2106 }
2107
2108 impl<T> DoubleEndedIterator for Iter<'_, T> {
2109 fn next_back(&mut self) -> Option<Self::Item> {
2110 if self.remaining == 0 {
2111 None
2112 } else {
2113 self.tail.map(|index| {
2114 let entry = self.entries[index.get()].occupied_ref();
2115 self.tail = entry.previous;
2116 self.remaining -= 1;
2117 &entry.value
2118 })
2119 }
2120 }
2121 }
2122
2123 impl<T> ExactSizeIterator for Iter<'_, T> {}
2124
2125 impl<T> FusedIterator for Iter<'_, T> {}
2126
2127 impl<'a, T> Iterator for Iter<'a, T> {
2128 type Item = &'a T;
2129
2130 fn next(&mut self) -> Option<Self::Item> {
2131 if self.remaining == 0 {
2132 None
2133 } else {
2134 self.head.map(|index| {
2135 let entry = self.entries[index.get()].occupied_ref();
2136 self.head = entry.next;
2137 self.remaining -= 1;
2138 &entry.value
2139 })
2140 }
2141 }
2142
2143 fn size_hint(&self) -> (usize, Option<usize>) {
2144 (self.remaining, Some(self.remaining))
2145 }
2146 }
2147
2148 /// An iterator that yields mutable references to entries in the list.
2149 pub struct IterMut<'a, T> {
2150 entries: *mut Vec<Entry<T>>,
2151
2152 /// The index of the head of the unvisited portion of the list.
2153 head: Option<NonMaxUsize>,
2154
2155 /// Because [`IterMut::entries`] is a pointer, we need to have a phantom data here for the lifetime parameter.
2156 phantom: PhantomData<&'a mut Vec<Entry<T>>>,
2157
2158 /// The number of entries that have not been visited.
2159 remaining: usize,
2160
2161 /// The index of the tail of the unvisited portion of the list.
2162 tail: Option<NonMaxUsize>,
2163 }
2164
2165 impl<T> IterMut<'_, T> {
2166 /// Creates an iterator that yields immutable references to entries in the list.
2167 #[must_use]
2168 pub fn iter(&self) -> Iter<'_, T> {
2169 Iter {
2170 entries: unsafe { &*self.entries },
2171 head: self.head,
2172 remaining: self.remaining,
2173 tail: self.tail,
2174 }
2175 }
2176 }
2177
2178 impl<T> Debug for IterMut<'_, T>
2179 where
2180 T: Debug,
2181 {
2182 fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
2183 formatter.write_str("IterMut(")?;
2184 formatter.debug_list().entries(self.iter()).finish()?;
2185 formatter.write_str(")")
2186 }
2187 }
2188
2189 impl<T> DoubleEndedIterator for IterMut<'_, T> {
2190 fn next_back(&mut self) -> Option<Self::Item> {
2191 if self.remaining == 0 {
2192 None
2193 } else {
2194 self.tail.map(|index| {
2195 let entry = unsafe { &mut (*self.entries)[index.get()] }.occupied_mut();
2196 self.tail = entry.previous;
2197 self.remaining -= 1;
2198 &mut entry.value
2199 })
2200 }
2201 }
2202 }
2203
2204 impl<T> ExactSizeIterator for IterMut<'_, T> {}
2205
2206 impl<T> FusedIterator for IterMut<'_, T> {}
2207
2208 impl<'a, T> Iterator for IterMut<'a, T> {
2209 type Item = &'a mut T;
2210
2211 fn next(&mut self) -> Option<Self::Item> {
2212 if self.remaining == 0 {
2213 None
2214 } else {
2215 self.head.map(|index| {
2216 let entry = unsafe { &mut (*self.entries)[index.get()] }.occupied_mut();
2217 self.head = entry.next;
2218 self.remaining -= 1;
2219 &mut entry.value
2220 })
2221 }
2222 }
2223
2224 fn size_hint(&self) -> (usize, Option<usize>) {
2225 (self.remaining, Some(self.remaining))
2226 }
2227 }
2228
2229 unsafe impl<T> Send for IterMut<'_, T> where T: Send {}
2230
2231 unsafe impl<T> Sync for IterMut<'_, T> where T: Sync {}
2232
2233 /// Creates the initial generation seeded by the current time.
2234 #[must_use]
2235 fn create_initial_generation() -> u64 {
2236 #[cfg(feature = "std")]
2237 {
2238 use std::{collections::hash_map::RandomState, hash::BuildHasher};
2239
2240 let mut hasher = RandomState::new().build_hasher();
2241 hasher.write_u32(0);
2242 hasher.finish()
2243 }
2244
2245 #[cfg(not(feature = "std"))]
2246 {
2247 use core::sync::atomic::{AtomicU32, Ordering};
2248
2249 // Generate a u32 randomly.
2250 #[cfg_attr(mutants, mutants::skip)]
2251 fn gen_u32() -> u32 {
2252 static SEED: AtomicU32 = AtomicU32::new({
2253 // Random seed generated at compile time.
2254 const_random::const_random!(u32)
2255 });
2256
2257 // Xorshift is "good enough" in most cases.
2258 let mut x = SEED.load(Ordering::Relaxed);
2259
2260 loop {
2261 let mut random = x;
2262 random ^= random << 13;
2263 random ^= random >> 17;
2264 random ^= random << 5;
2265
2266 // Put the new seed in.
2267 if let Err(actual) = SEED.compare_exchange(x, random, Ordering::SeqCst, Ordering::SeqCst) {
2268 x = actual;
2269 } else {
2270 return random;
2271 }
2272 }
2273 }
2274
2275 // Put two u32's together
2276 gen_u32() as u64 | ((gen_u32() as u64) << 32)
2277 }
2278 }
2279
2280 #[allow(unused_results)]
2281 #[cfg(test)]
2282 mod test {
2283 use coverage_helper::test;
2284
2285 use super::*;
2286 use alloc::{format, vec};
2287
2288 #[cfg(feature = "std")]
2289 use std::{collections::hash_map::RandomState, hash::BuildHasher};
2290
2291 #[test]
2292 fn test_bounds() {
2293 fn check_bounds<Type: Send + Sync>() {}
2294
2295 check_bounds::<VecList<()>>();
2296 check_bounds::<Index<()>>();
2297 check_bounds::<Drain<'_, ()>>();
2298 check_bounds::<Indices<'_, ()>>();
2299 check_bounds::<IntoIter<()>>();
2300 check_bounds::<Iter<'_, ()>>();
2301 check_bounds::<IterMut<'_, ()>>();
2302 }
2303
2304 #[cfg(feature = "std")]
2305 #[test]
2306 fn test_non_max_usize_eq() {
2307 let zero = NonMaxUsize::zero();
2308 assert_eq!(zero, 0usize);
2309 assert_ne!(zero, 1usize);
2310 }
2311
2312 #[test]
2313 fn test_drain_debug() {
2314 let mut list = VecList::new();
2315 list.push_back(0);
2316 list.push_back(1);
2317 list.push_back(-1);
2318 list.push_back(2);
2319 list.push_back(-2);
2320
2321 let drain = list.drain();
2322 assert_eq!(format!("{drain:?}"), "Drain([0, 1, -1, 2, -2])");
2323 }
2324
2325 #[test]
2326 fn test_drain_double_ended() {
2327 let mut list = VecList::new();
2328 list.push_back(0);
2329 list.push_back(1);
2330 list.push_back(-1);
2331 list.push_back(2);
2332 list.push_back(-2);
2333
2334 let mut drain = list.drain();
2335 assert_eq!(drain.next(), Some(0));
2336 assert_eq!(drain.next_back(), Some(-2));
2337 assert_eq!(drain.next(), Some(1));
2338 assert_eq!(drain.next_back(), Some(2));
2339 assert_eq!(drain.next(), Some(-1));
2340 assert_eq!(drain.next_back(), None);
2341 }
2342
2343 #[test]
2344 fn test_drain_empty() {
2345 let mut list: VecList<i32> = VecList::new();
2346 let mut drain = list.drain();
2347 assert_eq!(drain.next(), None);
2348 }
2349
2350 #[test]
2351 fn test_drain_fused() {
2352 let mut list: VecList<i32> = VecList::new();
2353 list.push_back(0);
2354 let mut drain = list.drain();
2355 assert_eq!(drain.next(), Some(0));
2356 assert_eq!(drain.next(), None);
2357 assert_eq!(drain.next(), None);
2358 assert_eq!(drain.next(), None);
2359 }
2360
2361 #[test]
2362 fn test_drain_size_hint() {
2363 let mut list = VecList::new();
2364 list.push_back(0);
2365 list.push_back(1);
2366 list.push_back(-1);
2367 list.push_back(2);
2368 list.push_back(-2);
2369
2370 let mut drain = list.drain();
2371
2372 assert_eq!(drain.size_hint(), (5, Some(5)));
2373 drain.next();
2374 assert_eq!(drain.size_hint(), (4, Some(4)));
2375 drain.next();
2376 assert_eq!(drain.size_hint(), (3, Some(3)));
2377 drain.next();
2378 assert_eq!(drain.size_hint(), (2, Some(2)));
2379 drain.next();
2380 assert_eq!(drain.size_hint(), (1, Some(1)));
2381 drain.next();
2382 assert_eq!(drain.size_hint(), (0, Some(0)));
2383 }
2384
2385 #[test]
2386 fn test_index_debug() {
2387 let mut list = VecList::new();
2388 let index = list.push_back(5);
2389
2390 assert_eq!(
2391 format!("{index:?}"),
2392 format!("Index(0, {})", index.generation)
2393 );
2394 }
2395
2396 #[test]
2397 fn test_index_equality() {
2398 let mut list = VecList::new();
2399 let index_1 = list.push_back(0);
2400 let index_2 = list.indices().next().unwrap();
2401 assert_eq!(index_1, index_2);
2402
2403 let index_3 = list.push_back(1);
2404 assert_ne!(index_1, index_3);
2405 }
2406
2407 #[cfg(feature = "std")]
2408 #[test]
2409 fn test_index_hash() {
2410 let state = RandomState::new();
2411
2412 fn hash(state: &RandomState, value: &Index<usize>) -> u64 {
2413 let mut hasher = state.build_hasher();
2414 value.hash(&mut hasher);
2415 hasher.finish()
2416 }
2417
2418 let mut list = VecList::new();
2419 let index_1 = list.push_back(0);
2420 let index_2 = list.push_back(2);
2421
2422 assert_eq!(hash(&state, &index_1), hash(&state, &index_1));
2423 assert_ne!(hash(&state, &index_1), hash(&state, &index_2));
2424 }
2425
2426 #[test]
2427 fn test_indices_debug() {
2428 let mut list = VecList::new();
2429 list.push_back(0);
2430 list.push_back(1);
2431 list.push_back(-1);
2432 list.push_back(2);
2433 list.push_back(-2);
2434
2435 let indices = list.indices();
2436 assert_eq!(
2437 format!("{indices:?}"),
2438 format!(
2439 "Indices([Index(0, {}), Index(1, {}), Index(2, {}), Index(3, {}), Index(4, {})])",
2440 list.generation, list.generation, list.generation, list.generation, list.generation
2441 )
2442 );
2443 }
2444
2445 #[test]
2446 fn test_indices_double_ended() {
2447 let mut list = VecList::new();
2448 list.push_back(0);
2449 list.push_back(1);
2450 list.push_back(-1);
2451 list.push_back(2);
2452 list.push_back(-2);
2453
2454 let mut indices = list.indices();
2455 assert_eq!(indices.next().unwrap().index.get(), 0);
2456 assert_eq!(indices.next_back().unwrap().index.get(), 4);
2457 assert_eq!(indices.next().unwrap().index.get(), 1);
2458 assert_eq!(indices.next_back().unwrap().index.get(), 3);
2459 assert_eq!(indices.next().unwrap().index.get(), 2);
2460 assert_eq!(indices.next_back(), None);
2461 }
2462
2463 #[test]
2464 fn test_indices_empty() {
2465 let list: VecList<i32> = VecList::new();
2466 let mut indices = list.indices();
2467 assert_eq!(indices.next(), None);
2468 }
2469
2470 #[test]
2471 fn test_indices_fused() {
2472 let mut list: VecList<i32> = VecList::new();
2473 list.push_back(0);
2474 let mut indices = list.indices();
2475 assert_eq!(indices.next().unwrap().index.get(), 0);
2476 assert_eq!(indices.next(), None);
2477 assert_eq!(indices.next(), None);
2478 assert_eq!(indices.next(), None);
2479 }
2480
2481 #[test]
2482 fn test_indices_size_hint() {
2483 let mut list = VecList::new();
2484 list.push_back(0);
2485 list.push_back(1);
2486 list.push_back(-1);
2487 list.push_back(2);
2488 list.push_back(-2);
2489
2490 let mut indices = list.indices();
2491
2492 assert_eq!(indices.size_hint(), (5, Some(5)));
2493 indices.next();
2494 assert_eq!(indices.size_hint(), (4, Some(4)));
2495 indices.next();
2496 assert_eq!(indices.size_hint(), (3, Some(3)));
2497 indices.next();
2498 assert_eq!(indices.size_hint(), (2, Some(2)));
2499 indices.next();
2500 assert_eq!(indices.size_hint(), (1, Some(1)));
2501 indices.next();
2502 assert_eq!(indices.size_hint(), (0, Some(0)));
2503 }
2504
2505 #[test]
2506 fn test_into_iter_debug() {
2507 let mut list = VecList::new();
2508 list.push_back(0);
2509 list.push_back(1);
2510 list.push_back(-1);
2511 list.push_back(2);
2512 list.push_back(-2);
2513
2514 let iter = list.into_iter();
2515 assert_eq!(format!("{iter:?}"), "IntoIter([0, 1, -1, 2, -2])");
2516 }
2517
2518 #[test]
2519 fn test_into_iter_double_ended() {
2520 let mut list = VecList::new();
2521 list.push_back(0);
2522 list.push_back(1);
2523 list.push_back(-1);
2524 list.push_back(2);
2525 list.push_back(-2);
2526
2527 let mut iter = list.into_iter();
2528 assert_eq!(iter.next(), Some(0));
2529 assert_eq!(iter.next_back(), Some(-2));
2530 assert_eq!(iter.next(), Some(1));
2531 assert_eq!(iter.next_back(), Some(2));
2532 assert_eq!(iter.next(), Some(-1));
2533 assert_eq!(iter.next_back(), None);
2534 }
2535
2536 #[test]
2537 fn test_into_iter_empty() {
2538 let list: VecList<i32> = VecList::new();
2539 let mut iter = list.into_iter();
2540 assert_eq!(iter.next(), None);
2541 }
2542
2543 #[test]
2544 fn test_into_iter_fused() {
2545 let mut list: VecList<i32> = VecList::new();
2546 list.push_back(0);
2547 let mut iter = list.into_iter();
2548 assert_eq!(iter.next(), Some(0));
2549 assert_eq!(iter.next(), None);
2550 assert_eq!(iter.next(), None);
2551 assert_eq!(iter.next(), None);
2552 }
2553
2554 #[test]
2555 fn test_into_iter_size_hint() {
2556 let mut list = VecList::new();
2557 list.push_back(0);
2558 list.push_back(1);
2559 list.push_back(-1);
2560 list.push_back(2);
2561 list.push_back(-2);
2562
2563 let mut iter = list.into_iter();
2564
2565 assert_eq!(iter.size_hint(), (5, Some(5)));
2566 iter.next();
2567 assert_eq!(iter.size_hint(), (4, Some(4)));
2568 iter.next();
2569 assert_eq!(iter.size_hint(), (3, Some(3)));
2570 iter.next();
2571 assert_eq!(iter.size_hint(), (2, Some(2)));
2572 iter.next();
2573 assert_eq!(iter.size_hint(), (1, Some(1)));
2574 iter.next();
2575 assert_eq!(iter.size_hint(), (0, Some(0)));
2576 }
2577
2578 #[test]
2579 fn test_iter_debug() {
2580 let mut list = VecList::new();
2581 list.push_back(0);
2582 list.push_back(1);
2583 list.push_back(-1);
2584 list.push_back(2);
2585 list.push_back(-2);
2586
2587 let iter = list.iter();
2588 assert_eq!(format!("{iter:?}"), "Iter([0, 1, -1, 2, -2])");
2589 }
2590
2591 #[test]
2592 fn test_iter_double_ended() {
2593 let mut list = VecList::new();
2594 list.push_back(0);
2595 list.push_back(1);
2596 list.push_back(-1);
2597 list.push_back(2);
2598 list.push_back(-2);
2599
2600 let mut iter = list.iter();
2601 assert_eq!(iter.next(), Some(&0));
2602 assert_eq!(iter.next_back(), Some(&-2));
2603 assert_eq!(iter.next(), Some(&1));
2604 assert_eq!(iter.next_back(), Some(&2));
2605 assert_eq!(iter.next(), Some(&-1));
2606 assert_eq!(iter.next_back(), None);
2607 }
2608
2609 #[test]
2610 fn test_iter_empty() {
2611 let list: VecList<i32> = VecList::new();
2612 let mut iter = list.iter();
2613 assert_eq!(iter.next(), None);
2614 }
2615
2616 #[test]
2617 fn test_iter_fused() {
2618 let mut list: VecList<i32> = VecList::new();
2619 list.push_back(0);
2620 let mut iter = list.iter();
2621 assert_eq!(iter.next(), Some(&0));
2622 assert_eq!(iter.next(), None);
2623 assert_eq!(iter.next(), None);
2624 assert_eq!(iter.next(), None);
2625 }
2626
2627 #[test]
2628 fn test_iter_size_hint() {
2629 let mut list = VecList::new();
2630 list.push_back(0);
2631 list.push_back(1);
2632 list.push_back(-1);
2633 list.push_back(2);
2634 list.push_back(-2);
2635
2636 let mut iter = list.iter();
2637
2638 assert_eq!(iter.size_hint(), (5, Some(5)));
2639 iter.next();
2640 assert_eq!(iter.size_hint(), (4, Some(4)));
2641 iter.next();
2642 assert_eq!(iter.size_hint(), (3, Some(3)));
2643 iter.next();
2644 assert_eq!(iter.size_hint(), (2, Some(2)));
2645 iter.next();
2646 assert_eq!(iter.size_hint(), (1, Some(1)));
2647 iter.next();
2648 assert_eq!(iter.size_hint(), (0, Some(0)));
2649 }
2650
2651 #[test]
2652 fn test_iter_mut_debug() {
2653 let mut list = VecList::new();
2654 list.push_back(0);
2655 list.push_back(1);
2656 list.push_back(-1);
2657 list.push_back(2);
2658 list.push_back(-2);
2659
2660 let iter = list.iter_mut();
2661 assert_eq!(format!("{iter:?}"), "IterMut([0, 1, -1, 2, -2])");
2662 }
2663
2664 #[test]
2665 fn test_iter_mut_double_ended() {
2666 let mut list = VecList::new();
2667 list.push_back(0);
2668 list.push_back(1);
2669 list.push_back(-1);
2670 list.push_back(2);
2671 list.push_back(-2);
2672
2673 let mut iter = list.iter_mut();
2674 assert_eq!(iter.next(), Some(&mut 0));
2675 assert_eq!(iter.next_back(), Some(&mut -2));
2676 assert_eq!(iter.next(), Some(&mut 1));
2677 assert_eq!(iter.next_back(), Some(&mut 2));
2678 assert_eq!(iter.next(), Some(&mut -1));
2679 assert_eq!(iter.next_back(), None);
2680 }
2681
2682 #[test]
2683 fn test_iter_mut_empty() {
2684 let mut list: VecList<i32> = VecList::new();
2685 let mut iter = list.iter_mut();
2686 assert_eq!(iter.next(), None);
2687 }
2688
2689 #[test]
2690 fn test_iter_mut_fused() {
2691 let mut list: VecList<i32> = VecList::new();
2692 list.push_back(0);
2693 let mut iter = list.iter_mut();
2694 assert_eq!(iter.next(), Some(&mut 0));
2695 assert_eq!(iter.next(), None);
2696 assert_eq!(iter.next(), None);
2697 assert_eq!(iter.next(), None);
2698 }
2699
2700 #[test]
2701 fn test_iter_mut_size_hint() {
2702 let mut list = VecList::new();
2703 list.push_back(0);
2704 list.push_back(1);
2705 list.push_back(-1);
2706 list.push_back(2);
2707 list.push_back(-2);
2708
2709 let mut iter = list.iter_mut();
2710
2711 assert_eq!(iter.size_hint(), (5, Some(5)));
2712 iter.next();
2713 assert_eq!(iter.size_hint(), (4, Some(4)));
2714 iter.next();
2715 assert_eq!(iter.size_hint(), (3, Some(3)));
2716 iter.next();
2717 assert_eq!(iter.size_hint(), (2, Some(2)));
2718 iter.next();
2719 assert_eq!(iter.size_hint(), (1, Some(1)));
2720 iter.next();
2721 assert_eq!(iter.size_hint(), (0, Some(0)));
2722 }
2723
2724 #[test]
2725 fn test_vec_list_back() {
2726 let mut list = VecList::new();
2727 assert_eq!(list.back(), None);
2728
2729 let index_1 = list.push_back(0);
2730 assert_eq!(list.back(), Some(&0));
2731
2732 let index_2 = list.push_back(1);
2733 assert_eq!(list.back(), Some(&1));
2734
2735 list.remove(index_2);
2736 assert_eq!(list.back(), Some(&0));
2737
2738 list.remove(index_1);
2739 assert_eq!(list.back(), None);
2740 }
2741
2742 #[test]
2743 fn test_vec_list_back_mut() {
2744 let mut list = VecList::new();
2745 assert_eq!(list.back_mut(), None);
2746
2747 let index_1 = list.push_back(0);
2748 assert_eq!(list.back_mut(), Some(&mut 0));
2749
2750 let index_2 = list.push_back(1);
2751 assert_eq!(list.back_mut(), Some(&mut 1));
2752
2753 list.remove(index_2);
2754 assert_eq!(list.back_mut(), Some(&mut 0));
2755
2756 list.remove(index_1);
2757 assert_eq!(list.back_mut(), None);
2758 }
2759
2760 #[test]
2761 fn test_vec_list_capacity() {
2762 let list: VecList<i32> = VecList::new();
2763 assert_eq!(list.capacity(), 0);
2764 }
2765
2766 #[test]
2767 fn test_vec_list_clear() {
2768 let mut list = VecList::new();
2769 let index = list.push_back(0);
2770 list.clear();
2771 assert!(list.is_empty());
2772 assert_eq!(list.get(index), None);
2773 }
2774
2775 #[test]
2776 fn test_vec_list_contains() {
2777 let mut list = VecList::new();
2778 assert!(!list.contains(&0));
2779
2780 let index = list.push_back(0);
2781 assert!(list.contains(&0));
2782
2783 list.remove(index);
2784 assert!(!list.contains(&0));
2785 }
2786
2787 #[test]
2788 fn test_vec_list_drain() {
2789 let mut list = VecList::new();
2790 list.drain();
2791 assert!(list.is_empty());
2792
2793 list.push_back(0);
2794 list.push_back(1);
2795 list.push_back(-1);
2796 list.drain();
2797 assert!(list.is_empty());
2798 }
2799
2800 #[test]
2801 fn test_vec_list_debug() {
2802 let mut list = VecList::new();
2803 list.push_back(0);
2804 list.push_back(1);
2805 list.push_back(-1);
2806 list.push_back(2);
2807 list.push_back(-2);
2808
2809 assert_eq!(format!("{list:?}"), "[0, 1, -1, 2, -2]");
2810 }
2811
2812 #[test]
2813 fn test_vec_list_equality() {
2814 let mut list_1 = VecList::new();
2815 list_1.push_back(0);
2816 list_1.push_back(1);
2817 list_1.push_back(-1);
2818 list_1.push_back(2);
2819 list_1.push_back(-2);
2820
2821 assert_eq!(list_1, Vec::from_iter([0, 1, -1, 2, -2]));
2822 assert_eq!(Vec::from_iter([0, 1, -1, 2, -2]), list_1);
2823 assert_ne!(list_1, Vec::new());
2824 assert_ne!(Vec::new(), list_1);
2825
2826 assert_eq!(list_1, LinkedList::from_iter([0, 1, -1, 2, -2]));
2827 assert_eq!(LinkedList::from_iter([0, 1, -1, 2, -2]), list_1);
2828 assert_ne!(list_1, LinkedList::new());
2829 assert_ne!(LinkedList::new(), list_1);
2830
2831 assert_eq!(list_1, [0, 1, -1, 2, -2]);
2832 assert_eq!([0, 1, -1, 2, -2], list_1);
2833 assert_ne!(list_1, []);
2834 assert_ne!([], list_1);
2835
2836 assert_eq!(list_1, [0, 1, -1, 2, -2].as_slice());
2837 assert_eq!([0, 1, -1, 2, -2].as_slice(), list_1);
2838 assert_ne!(list_1, [].as_slice());
2839 assert_ne!([].as_slice(), list_1);
2840
2841 let mut list_2 = list_1.clone();
2842 list_2.pop_back();
2843 assert_ne!(list_1, list_2);
2844
2845 list_2.push_back(-2);
2846 assert_eq!(list_1, list_2);
2847 }
2848
2849 #[cfg(feature = "std")]
2850 #[test]
2851 fn test_vec_list_hash() {
2852 let state = RandomState::new();
2853 fn hash(state: &RandomState, value: &VecList<usize>) -> u64 {
2854 let mut hasher = state.build_hasher();
2855 value.hash(&mut hasher);
2856 hasher.finish()
2857 }
2858
2859 let mut list_1 = VecList::new();
2860 list_1.push_back(0);
2861
2862 let list_2 = VecList::new();
2863
2864 assert_eq!(hash(&state, &list_1), hash(&state, &list_1));
2865 assert_ne!(hash(&state, &list_1), hash(&state, &list_2));
2866 }
2867
2868 #[test]
2869 fn test_vec_list_extend() {
2870 let mut list = VecList::new();
2871 list.push_back(0);
2872 list.push_back(1);
2873 list.extend([-1, 2, -2].iter());
2874
2875 assert_eq!(list, &[0, 1, -1, 2, -2][..]);
2876 }
2877
2878 #[test]
2879 fn test_vec_list_from_iterator() {
2880 let list = VecList::from_iter([0, 1, -1, 2, -2].iter().cloned());
2881 assert_eq!(list, &[0, 1, -1, 2, -2][..]);
2882 }
2883
2884 #[test]
2885 fn test_vec_list_front() {
2886 let mut list = VecList::new();
2887 assert_eq!(list.front(), None);
2888
2889 let index_1 = list.push_front(0);
2890 assert_eq!(list.front(), Some(&0));
2891
2892 let index_2 = list.push_front(1);
2893 assert_eq!(list.front(), Some(&1));
2894
2895 list.remove(index_2);
2896 assert_eq!(list.front(), Some(&0));
2897
2898 list.remove(index_1);
2899 assert_eq!(list.front(), None);
2900 }
2901
2902 #[test]
2903 fn test_vec_list_front_mut() {
2904 let mut list = VecList::new();
2905 assert_eq!(list.front_mut(), None);
2906
2907 let index_1 = list.push_front(0);
2908 assert_eq!(list.front_mut(), Some(&mut 0));
2909
2910 let index_2 = list.push_front(1);
2911 assert_eq!(list.front_mut(), Some(&mut 1));
2912
2913 list.remove(index_2);
2914 assert_eq!(list.front_mut(), Some(&mut 0));
2915
2916 list.remove(index_1);
2917 assert_eq!(list.front_mut(), None);
2918 }
2919
2920 #[cfg(feature = "std")]
2921 #[test]
2922 fn test_vec_list_get() {
2923 let mut list = VecList::new();
2924 let index = list.push_back(0);
2925 assert_eq!(list.get(index), Some(&0));
2926 list.remove(index);
2927 assert_eq!(list.get(index), None);
2928
2929 let mut list = VecList::new();
2930 let index_1 = list.push_back(0);
2931 let index_2 = list.push_back(1);
2932 let index_3 = list.push_back(2);
2933
2934 list.remove(index_1);
2935 list.pack_to_fit();
2936 assert_eq!(list.get(index_1), None);
2937 assert_eq!(list.get(index_2), None);
2938 assert_eq!(list.get(index_3), None);
2939 }
2940
2941 #[cfg(feature = "std")]
2942 #[test]
2943 fn test_vec_list_get_mut() {
2944 let mut list = VecList::new();
2945 let index = list.push_back(0);
2946 assert_eq!(list.get_mut(index), Some(&mut 0));
2947 list.remove(index);
2948 assert_eq!(list.get_mut(index), None);
2949
2950 let mut list = VecList::new();
2951 let index_1 = list.push_back(0);
2952 let index_2 = list.push_back(1);
2953 let index_3 = list.push_back(2);
2954
2955 list.remove(index_1);
2956 list.pack_to_fit();
2957 assert_eq!(list.get_mut(index_1), None);
2958 assert_eq!(list.get_mut(index_2), None);
2959 assert_eq!(list.get_mut(index_3), None);
2960 }
2961
2962 #[test]
2963 fn test_vec_list_get_unchecked() {
2964 let mut list = VecList::new();
2965 let index = list.push_back(0);
2966 assert_eq!(unsafe { list.get_unchecked(index) }, &0);
2967
2968 let mut list = VecList::new();
2969 let index_1 = list.push_back(0);
2970 let index_2 = list.push_back(1);
2971 let index_3 = list.push_back(2);
2972
2973 list.remove(index_1);
2974 assert_eq!(unsafe { list.get_unchecked(index_2) }, &1);
2975 assert_eq!(unsafe { list.get_unchecked(index_3) }, &2);
2976 }
2977
2978 #[test]
2979 fn test_vec_list_get_unchecked_mut() {
2980 let mut list = VecList::new();
2981 let index = list.push_back(0);
2982 assert_eq!(unsafe { list.get_unchecked_mut(index) }, &mut 0);
2983
2984 let mut list = VecList::new();
2985 let index_1 = list.push_back(0);
2986 let index_2 = list.push_back(1);
2987 let index_3 = list.push_back(2);
2988
2989 list.remove(index_1);
2990 assert_eq!(unsafe { list.get_unchecked_mut(index_2) }, &mut 1);
2991 assert_eq!(unsafe { list.get_unchecked_mut(index_3) }, &mut 2);
2992 }
2993
2994 #[test]
2995 fn test_vec_list_get_next_index() {
2996 let mut list = VecList::new();
2997
2998 let index = list.push_back(0);
2999 assert_eq!(list.get_next_index(index), None);
3000
3001 list.push_back(1);
3002 assert_eq!(list.get_next_index(index).unwrap().index.get(), 1);
3003 }
3004
3005 #[test]
3006 fn test_vec_list_get_previous_index() {
3007 let mut list = VecList::new();
3008
3009 let index = list.push_front(0);
3010 assert_eq!(list.get_previous_index(index), None);
3011
3012 list.push_front(1);
3013 assert_eq!(list.get_previous_index(index).unwrap().index.get(), 1);
3014 }
3015
3016 #[test]
3017 fn test_vec_list_index() {
3018 let mut list = VecList::new();
3019
3020 let index = list.push_back(5);
3021 assert_eq!(list[index], 5);
3022
3023 list[index] = 10;
3024 assert_eq!(list[index], 10);
3025 }
3026
3027 #[should_panic]
3028 #[test]
3029 fn test_vec_list_index_panic() {
3030 let mut list = VecList::new();
3031 let index = list.push_back(0);
3032 list.pop_back();
3033 let _ = list[index];
3034 }
3035
3036 #[cfg(feature = "std")]
3037 #[test]
3038 fn test_vec_list_indices() {
3039 let mut list = VecList::new();
3040 let mut iter = list.indices();
3041 assert_eq!(iter.next(), None);
3042
3043 list.push_back(0);
3044 let index = list.push_back(1);
3045 list.push_back(-1);
3046 list.remove(index);
3047
3048 let mut iter = list.indices();
3049 assert_eq!(iter.next().unwrap().index.get(), 0);
3050 assert_eq!(iter.next().unwrap().index.get(), 2);
3051 assert_eq!(iter.next(), None);
3052
3053 list.pack_to_fit();
3054
3055 let mut iter = list.indices();
3056 assert_eq!(iter.next().unwrap().index.get(), 0);
3057 assert_eq!(iter.next().unwrap().index.get(), 1);
3058 assert_eq!(iter.next(), None);
3059 }
3060
3061 #[test]
3062 fn test_vec_list_insert_after() {
3063 let mut list = VecList::new();
3064 let index_1 = list.push_front(0);
3065 let index_2 = list.insert_after(index_1, 1);
3066
3067 assert_eq!(list.back(), Some(&1));
3068 assert_eq!(list.get_previous_index(index_2), Some(index_1));
3069 assert_eq!(list.get_next_index(index_1), Some(index_2));
3070
3071 let index_3 = list.insert_after(index_1, 2);
3072
3073 assert_eq!(list.get_previous_index(index_3), Some(index_1));
3074 assert_eq!(list.get_next_index(index_1), Some(index_3));
3075 assert_eq!(list.get_next_index(index_3), Some(index_2));
3076 }
3077
3078 #[should_panic]
3079 #[test]
3080 fn test_vec_list_insert_after_panic_index_invalidated() {
3081 let mut list = VecList::new();
3082 let index = list.push_front(0);
3083 list.remove(index);
3084 list.insert_after(index, 1);
3085 }
3086
3087 #[cfg(feature = "std")]
3088 #[should_panic]
3089 #[test]
3090 fn test_vec_list_insert_after_panic_index_out_of_bounds() {
3091 let mut list = VecList::new();
3092 let index_1 = list.push_back(0);
3093 list.push_back(1);
3094 let index_2 = list.push_back(2);
3095
3096 list.remove(index_1);
3097 list.pack_to_fit();
3098 list.insert_after(index_2, 3);
3099 }
3100
3101 #[test]
3102 fn test_vec_list_insert_before() {
3103 let mut list = VecList::new();
3104 let index_1 = list.push_back(0);
3105 let index_2 = list.insert_before(index_1, 1);
3106
3107 assert_eq!(list.front(), Some(&1));
3108 assert_eq!(list.get_previous_index(index_1), Some(index_2));
3109 assert_eq!(list.get_next_index(index_2), Some(index_1));
3110
3111 let index_3 = list.insert_before(index_1, 2);
3112
3113 assert_eq!(list.get_previous_index(index_1), Some(index_3));
3114 assert_eq!(list.get_next_index(index_3), Some(index_1));
3115 assert_eq!(list.get_next_index(index_2), Some(index_3));
3116 }
3117
3118 #[should_panic]
3119 #[test]
3120 fn test_vec_list_insert_before_panic_index_invalidated() {
3121 let mut list = VecList::new();
3122 let index = list.push_front(0);
3123 list.remove(index);
3124 list.insert_before(index, 1);
3125 }
3126
3127 #[cfg(feature = "std")]
3128 #[should_panic]
3129 #[test]
3130 fn test_vec_list_insert_before_panic_index_out_of_bounds() {
3131 let mut list = VecList::new();
3132 let index_1 = list.push_back(0);
3133 list.push_back(1);
3134 let index_2 = list.push_back(2);
3135
3136 list.remove(index_1);
3137 list.pack_to_fit();
3138 list.insert_before(index_2, 3);
3139 }
3140
3141 #[test]
3142 fn test_vec_list_into_iterator() {
3143 let mut list = VecList::new();
3144 list.push_back(0);
3145 list.push_back(1);
3146 list.push_back(-1);
3147 list.push_back(2);
3148 list.push_back(-2);
3149
3150 assert_eq!(list.into_iter().collect::<Vec<_>>(), [0, 1, -1, 2, -2]);
3151 }
3152
3153 #[test]
3154 fn test_vec_list_is_empty() {
3155 let mut list = VecList::new();
3156 assert!(list.is_empty());
3157 list.push_back(0);
3158 assert!(!list.is_empty());
3159 }
3160
3161 #[test]
3162 fn test_vec_list_iter() {
3163 let mut list = VecList::new();
3164 list.push_back(0);
3165 list.push_back(1);
3166 list.push_back(2);
3167
3168 let mut iter = list.iter();
3169 assert_eq!(iter.next(), Some(&0));
3170 assert_eq!(iter.next(), Some(&1));
3171 assert_eq!(iter.next(), Some(&2));
3172 assert_eq!(iter.next(), None);
3173 }
3174
3175 #[test]
3176 fn test_vec_list_iter_mut() {
3177 let mut list = VecList::new();
3178 list.push_back(0);
3179 list.push_back(1);
3180 list.push_back(2);
3181
3182 let mut iter = list.iter_mut();
3183 let value = iter.next().unwrap();
3184 *value = 100;
3185
3186 assert_eq!(iter.next(), Some(&mut 1));
3187 assert_eq!(iter.next(), Some(&mut 2));
3188 assert_eq!(iter.next(), None);
3189 assert_eq!(list.front(), Some(&100));
3190 }
3191
3192 #[test]
3193 fn test_vec_list_len() {
3194 let mut list = VecList::new();
3195 assert_eq!(list.len(), 0);
3196 let index = list.push_back(0);
3197 assert_eq!(list.len(), 1);
3198 list.remove(index);
3199 assert_eq!(list.len(), 0);
3200 }
3201
3202 #[test]
3203 fn test_vec_list_new() {
3204 let list: VecList<i32> = VecList::new();
3205 assert_eq!(list.capacity(), 0);
3206 assert_eq!(list.len(), 0);
3207 }
3208
3209 #[test]
3210 fn test_vec_list_ordering() {
3211 let mut list_1 = VecList::new();
3212 list_1.push_back(0);
3213 list_1.push_back(1);
3214 list_1.push_back(-1);
3215 list_1.push_back(2);
3216 list_1.push_back(-2);
3217
3218 let mut list_2 = list_1.clone();
3219
3220 list_2.push_back(5);
3221 assert!(list_1 < list_2);
3222
3223 list_2.pop_back();
3224 list_2.pop_back();
3225 assert!(list_1 > list_2);
3226
3227 list_2.push_back(3);
3228 assert!(list_1 < list_2);
3229
3230 list_2.pop_back();
3231 list_2.push_back(-3);
3232 assert!(list_1 > list_2);
3233 }
3234
3235 #[test]
3236 fn test_vec_list_pop_back() {
3237 let mut list = VecList::new();
3238 assert_eq!(list.pop_back(), None);
3239
3240 list.push_back(0);
3241 assert_eq!(list.pop_back(), Some(0));
3242 }
3243
3244 #[test]
3245 fn test_vec_list_pop_front() {
3246 let mut list = VecList::new();
3247 assert_eq!(list.pop_front(), None);
3248
3249 list.push_front(0);
3250 assert_eq!(list.pop_front(), Some(0));
3251 }
3252
3253 #[test]
3254 fn test_vec_list_push_back() {
3255 let mut list = VecList::new();
3256 list.push_back(0);
3257 assert_eq!(list.back(), Some(&0));
3258 list.push_back(1);
3259 assert_eq!(list.back(), Some(&1));
3260 list.push_back(2);
3261 assert_eq!(list.back(), Some(&2));
3262 }
3263
3264 #[test]
3265 fn test_vec_list_push_back_capacity_increases() {
3266 let mut list = VecList::with_capacity(1);
3267 assert_eq!(list.capacity(), 1);
3268
3269 let index = list.push_back(0);
3270 assert_eq!(list.capacity(), 1);
3271
3272 list.remove(index);
3273 assert_eq!(list.capacity(), 1);
3274
3275 list.push_back(0);
3276 assert_eq!(list.capacity(), 1);
3277
3278 list.push_back(1);
3279 assert!(list.capacity() > 1);
3280 }
3281
3282 #[test]
3283 fn test_vec_list_push_front() {
3284 let mut list = VecList::new();
3285 list.push_front(0);
3286 assert_eq!(list.front(), Some(&0));
3287 list.push_front(1);
3288 assert_eq!(list.front(), Some(&1));
3289 list.push_front(2);
3290 assert_eq!(list.front(), Some(&2));
3291 }
3292
3293 #[test]
3294 fn test_vec_list_remove() {
3295 let mut list = VecList::new();
3296 let index = list.push_back(0);
3297 assert_eq!(list.remove(index), Some(0));
3298 assert_eq!(list.remove(index), None);
3299 }
3300
3301 #[test]
3302 fn test_vec_list_reserve() {
3303 let mut list: VecList<i32> = VecList::new();
3304 assert_eq!(list.capacity(), 0);
3305
3306 list.reserve(10);
3307 let capacity = list.capacity();
3308
3309 assert!(capacity >= 10);
3310 list.reserve(5);
3311
3312 assert_eq!(list.capacity(), capacity);
3313 }
3314
3315 #[test]
3316 fn test_vec_list_retain() {
3317 let mut list = VecList::new();
3318 list.push_back(0);
3319 list.push_back(1);
3320 list.push_back(-1);
3321 list.push_back(2);
3322 list.push_back(-2);
3323
3324 list.retain(|&mut value| value >= 0);
3325 assert_eq!(list.into_iter().collect::<Vec<_>>(), [0, 1, 2]);
3326 }
3327
3328 #[cfg(feature = "std")]
3329 #[test]
3330 fn test_vec_list_pack_to() {
3331 let mut list = VecList::new();
3332 let index_1 = list.push_back(0);
3333 let index_2 = list.push_back(1);
3334 let index_3 = list.push_back(2);
3335 assert!(list.capacity() >= 3);
3336
3337 list.remove(index_1);
3338 assert!(list.capacity() >= 3);
3339
3340 let indices = list.indices();
3341 assert_eq!(
3342 indices.map(|index| index.index.get()).collect::<Vec<_>>(),
3343 [1, 2]
3344 );
3345
3346 let map = list.pack_to(5);
3347 assert_eq!(list.capacity(), 5);
3348
3349 let indices = list.indices();
3350 assert_eq!(
3351 indices.map(|index| index.index.get()).collect::<Vec<_>>(),
3352 [0, 1]
3353 );
3354
3355 assert_eq!(map.len(), 2);
3356 assert_eq!(map.get(&index_2).unwrap().index.get(), 0);
3357 assert_eq!(map.get(&index_3).unwrap().index.get(), 1);
3358 }
3359
3360 #[cfg(feature = "std")]
3361 #[test]
3362 fn test_vec_list_pack_to_empty() {
3363 let mut list: VecList<i32> = VecList::with_capacity(5);
3364 list.pack_to(0);
3365 assert_eq!(list.capacity(), 0);
3366 }
3367
3368 #[cfg(feature = "std")]
3369 #[should_panic]
3370 #[test]
3371 fn test_vec_list_pack_to_panic() {
3372 let mut list = VecList::new();
3373 list.push_back(0);
3374 list.push_back(1);
3375 list.push_back(2);
3376 list.pack_to(2);
3377 }
3378
3379 #[cfg(feature = "std")]
3380 #[test]
3381 fn test_vec_list_pack_to_fit() {
3382 let mut list = VecList::new();
3383 let index_1 = list.push_back(0);
3384 let index_2 = list.push_back(1);
3385 let index_3 = list.push_back(2);
3386 assert!(list.capacity() >= 3);
3387
3388 list.remove(index_1);
3389 assert!(list.capacity() >= 3);
3390
3391 let indices = list.indices();
3392 assert_eq!(
3393 indices.map(|index| index.index.get()).collect::<Vec<_>>(),
3394 [1, 2]
3395 );
3396
3397 let map = list.pack_to_fit();
3398 assert_eq!(list.capacity(), 2);
3399
3400 let indices = list.indices();
3401 assert_eq!(
3402 indices.map(|index| index.index.get()).collect::<Vec<_>>(),
3403 [0, 1]
3404 );
3405
3406 assert_eq!(map.len(), 2);
3407 assert_eq!(map.get(&index_2).unwrap().index.get(), 0);
3408 assert_eq!(map.get(&index_3).unwrap().index.get(), 1);
3409 }
3410
3411 #[test]
3412 fn test_vec_list_with_capacity() {
3413 let list: VecList<i32> = VecList::with_capacity(10);
3414 assert_eq!(list.capacity(), 10);
3415 }
3416
3417 #[test]
3418 fn test_vec_list_clone_from() {
3419 let mut list = VecList::new();
3420 let index_1 = list.push_back(0);
3421 let index_2 = list.push_back(1);
3422 let index_3 = list.push_back(2);
3423
3424 let mut list2 = VecList::new();
3425 list2.clone_from(&list);
3426 assert_eq!(list2.get(index_1), Some(&0));
3427 assert_eq!(list2.get(index_2), Some(&1));
3428 assert_eq!(list2.get(index_3), Some(&2));
3429 }
3430
3431 #[test]
3432 fn test_move_individual_elements() {
3433 let mut list = VecList::new();
3434 let index_1 = list.push_back(0);
3435 let index_2 = list.push_back(1);
3436 let index_3 = list.push_back(2);
3437 let index_4 = list.push_back(3);
3438
3439 // Move to tail
3440 list.move_after(index_1, index_4);
3441 assert_eq!(list.iter().copied().collect::<Vec<_>>(), vec![1, 2, 3, 0]);
3442 assert_eq!(
3443 list.iter().rev().copied().collect::<Vec<_>>(),
3444 vec![0, 3, 2, 1]
3445 );
3446 assert_eq!(list.back(), list.get(index_1));
3447
3448 // Move to head
3449 list.move_before(index_1, index_2);
3450 assert_eq!(list.iter().copied().collect::<Vec<_>>(), vec![0, 1, 2, 3]);
3451 assert_eq!(
3452 list.iter().rev().copied().collect::<Vec<_>>(),
3453 vec![3, 2, 1, 0]
3454 );
3455
3456 // Move non-tail/head node
3457 list.move_before(index_3, index_2);
3458 assert_eq!(list.iter().copied().collect::<Vec<_>>(), vec![0, 2, 1, 3]);
3459 assert_eq!(
3460 list.iter().rev().copied().collect::<Vec<_>>(),
3461 vec![3, 1, 2, 0]
3462 );
3463 }
3464
3465 #[test]
3466 fn test_move_back_index_front_index() {
3467 let mut list = VecList::new();
3468 let index_1 = list.push_back(0);
3469 list.push_back(1);
3470 list.push_back(2);
3471 list.push_back(3);
3472
3473 // Move to tail
3474 list.move_after(index_1, list.back_index().unwrap());
3475 assert_eq!(list.iter().copied().collect::<Vec<_>>(), vec![1, 2, 3, 0]);
3476 assert_eq!(
3477 list.iter().rev().copied().collect::<Vec<_>>(),
3478 vec![0, 3, 2, 1]
3479 );
3480 assert_eq!(list.back(), list.get(index_1));
3481
3482 // Move to head
3483 list.move_before(index_1, list.front_index().unwrap());
3484 assert_eq!(list.iter().copied().collect::<Vec<_>>(), vec![0, 1, 2, 3]);
3485 assert_eq!(
3486 list.iter().rev().copied().collect::<Vec<_>>(),
3487 vec![3, 2, 1, 0]
3488 );
3489 }
3490
3491 #[should_panic]
3492 #[test]
3493 fn test_move_after_panic1() {
3494 let mut list = VecList::new();
3495 let index_1 = list.push_back(0);
3496 let index_2 = list.push_back(1);
3497 list.remove(index_1);
3498 list.move_after(index_1, index_2);
3499 }
3500
3501 #[should_panic]
3502 #[test]
3503 fn test_move_after_panic2() {
3504 let mut list = VecList::new();
3505 let index_1 = list.push_back(0);
3506 let index_2 = list.push_back(1);
3507 list.remove(index_1);
3508 list.move_after(index_2, index_1);
3509 }
3510
3511 #[should_panic]
3512 #[test]
3513 fn test_move_after_panic3() {
3514 let mut list = VecList::new();
3515 let index_1 = list.push_back(0);
3516 list.move_after(index_1, index_1);
3517 }
3518
3519 #[should_panic]
3520 #[test]
3521 fn test_move_before_panic1() {
3522 let mut list = VecList::new();
3523 let index_1 = list.push_back(0);
3524 let index_2 = list.push_back(1);
3525 list.remove(index_1);
3526 list.move_before(index_1, index_2);
3527 }
3528
3529 #[should_panic]
3530 #[test]
3531 fn test_move_before_panic2() {
3532 let mut list = VecList::new();
3533 let index_1 = list.push_back(0);
3534 let index_2 = list.push_back(1);
3535 list.remove(index_1);
3536 list.move_before(index_2, index_1);
3537 }
3538
3539 #[should_panic]
3540 #[test]
3541 fn test_move_before_panic3() {
3542 let mut list = VecList::new();
3543 let index_1 = list.push_back(0);
3544 list.move_before(index_1, index_1);
3545 }
3546 }