dlv_list/
lib.rs

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