1 //! A doubly-linked list with owned nodes.
3 //! The `LinkedList` allows pushing and popping elements at either end
6 //! Almost always it is better to use `Vec` or [`VecDeque`] instead of
7 //! [`LinkedList`]. In general, array-based containers are faster,
8 //! more memory efficient and make better use of CPU cache.
10 //! [`LinkedList`]: ../linked_list/struct.LinkedList.html
11 //! [`VecDeque`]: ../vec_deque/struct.VecDeque.html
13 #![stable(feature = "rust1", since = "1.0.0")]
15 use core::cmp::Ordering;
17 use core::hash::{Hasher, Hash};
18 use core::iter::{FromIterator, FusedIterator};
19 use core::marker::PhantomData;
21 use core::ptr::NonNull;
23 use crate::boxed::Box;
24 use super::SpecExtend;
26 /// A doubly-linked list with owned nodes.
28 /// The `LinkedList` allows pushing and popping elements at either end
31 /// Almost always it is better to use `Vec` or `VecDeque` instead of
32 /// `LinkedList`. In general, array-based containers are faster,
33 /// more memory efficient and make better use of CPU cache.
34 #[stable(feature = "rust1", since = "1.0.0")]
35 pub struct LinkedList<T> {
36 head: Option<NonNull<Node<T>>>,
37 tail: Option<NonNull<Node<T>>>,
39 marker: PhantomData<Box<Node<T>>>,
43 next: Option<NonNull<Node<T>>>,
44 prev: Option<NonNull<Node<T>>>,
48 /// An iterator over the elements of a `LinkedList`.
50 /// This `struct` is created by the [`iter`] method on [`LinkedList`]. See its
51 /// documentation for more.
53 /// [`iter`]: struct.LinkedList.html#method.iter
54 /// [`LinkedList`]: struct.LinkedList.html
55 #[stable(feature = "rust1", since = "1.0.0")]
56 pub struct Iter<'a, T: 'a> {
57 head: Option<NonNull<Node<T>>>,
58 tail: Option<NonNull<Node<T>>>,
60 marker: PhantomData<&'a Node<T>>,
63 #[stable(feature = "collection_debug", since = "1.17.0")]
64 impl<T: fmt::Debug> fmt::Debug for Iter<'_, T> {
65 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
73 #[stable(feature = "rust1", since = "1.0.0")]
74 impl<T> Clone for Iter<'_, T> {
75 fn clone(&self) -> Self {
80 /// A mutable iterator over the elements of a `LinkedList`.
82 /// This `struct` is created by the [`iter_mut`] method on [`LinkedList`]. See its
83 /// documentation for more.
85 /// [`iter_mut`]: struct.LinkedList.html#method.iter_mut
86 /// [`LinkedList`]: struct.LinkedList.html
87 #[stable(feature = "rust1", since = "1.0.0")]
88 pub struct IterMut<'a, T: 'a> {
89 // We do *not* exclusively own the entire list here, references to node's `element`
90 // have been handed out by the iterator! So be careful when using this; the methods
91 // called must be aware that there can be aliasing pointers to `element`.
92 list: &'a mut LinkedList<T>,
93 head: Option<NonNull<Node<T>>>,
94 tail: Option<NonNull<Node<T>>>,
98 #[stable(feature = "collection_debug", since = "1.17.0")]
99 impl<T: fmt::Debug> fmt::Debug for IterMut<'_, T> {
100 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
101 f.debug_tuple("IterMut")
108 /// An owning iterator over the elements of a `LinkedList`.
110 /// This `struct` is created by the [`into_iter`] method on [`LinkedList`][`LinkedList`]
111 /// (provided by the `IntoIterator` trait). See its documentation for more.
113 /// [`into_iter`]: struct.LinkedList.html#method.into_iter
114 /// [`LinkedList`]: struct.LinkedList.html
116 #[stable(feature = "rust1", since = "1.0.0")]
117 pub struct IntoIter<T> {
121 #[stable(feature = "collection_debug", since = "1.17.0")]
122 impl<T: fmt::Debug> fmt::Debug for IntoIter<T> {
123 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
124 f.debug_tuple("IntoIter")
131 fn new(element: T) -> Self {
139 fn into_element(self: Box<Self>) -> T {
145 impl<T> LinkedList<T> {
146 /// Adds the given node to the front of the list.
148 fn push_front_node(&mut self, mut node: Box<Node<T>>) {
149 // This method takes care not to create mutable references to whole nodes,
150 // to maintain validity of aliasing pointers into `element`.
152 node.next = self.head;
154 let node = Some(Box::into_raw_non_null(node));
157 None => self.tail = node,
158 // Not creating new mutable (unique!) references overlapping `element`.
159 Some(head) => (*head.as_ptr()).prev = node,
167 /// Removes and returns the node at the front of the list.
169 fn pop_front_node(&mut self) -> Option<Box<Node<T>>> {
170 // This method takes care not to create mutable references to whole nodes,
171 // to maintain validity of aliasing pointers into `element`.
172 self.head.map(|node| unsafe {
173 let node = Box::from_raw(node.as_ptr());
174 self.head = node.next;
177 None => self.tail = None,
178 // Not creating new mutable (unique!) references overlapping `element`.
179 Some(head) => (*head.as_ptr()).prev = None,
187 /// Adds the given node to the back of the list.
189 fn push_back_node(&mut self, mut node: Box<Node<T>>) {
190 // This method takes care not to create mutable references to whole nodes,
191 // to maintain validity of aliasing pointers into `element`.
194 node.prev = self.tail;
195 let node = Some(Box::into_raw_non_null(node));
198 None => self.head = node,
199 // Not creating new mutable (unique!) references overlapping `element`.
200 Some(tail) => (*tail.as_ptr()).next = node,
208 /// Removes and returns the node at the back of the list.
210 fn pop_back_node(&mut self) -> Option<Box<Node<T>>> {
211 // This method takes care not to create mutable references to whole nodes,
212 // to maintain validity of aliasing pointers into `element`.
213 self.tail.map(|node| unsafe {
214 let node = Box::from_raw(node.as_ptr());
215 self.tail = node.prev;
218 None => self.head = None,
219 // Not creating new mutable (unique!) references overlapping `element`.
220 Some(tail) => (*tail.as_ptr()).next = None,
228 /// Unlinks the specified node from the current list.
230 /// Warning: this will not check that the provided node belongs to the current list.
232 /// This method takes care not to create mutable references to `element`, to
233 /// maintain validity of aliasing pointers.
235 unsafe fn unlink_node(&mut self, mut node: NonNull<Node<T>>) {
236 let node = node.as_mut(); // this one is ours now, we can create an &mut.
238 // Not creating new mutable (unique!) references overlapping `element`.
240 Some(prev) => (*prev.as_ptr()).next = node.next,
241 // this node is the head node
242 None => self.head = node.next,
246 Some(next) => (*next.as_ptr()).prev = node.prev,
247 // this node is the tail node
248 None => self.tail = node.prev,
255 #[stable(feature = "rust1", since = "1.0.0")]
256 impl<T> Default for LinkedList<T> {
257 /// Creates an empty `LinkedList<T>`.
259 fn default() -> Self {
264 impl<T> LinkedList<T> {
265 /// Creates an empty `LinkedList`.
270 /// use std::collections::LinkedList;
272 /// let list: LinkedList<u32> = LinkedList::new();
275 #[stable(feature = "rust1", since = "1.0.0")]
276 pub fn new() -> Self {
285 /// Moves all elements from `other` to the end of the list.
287 /// This reuses all the nodes from `other` and moves them into `self`. After
288 /// this operation, `other` becomes empty.
290 /// This operation should compute in O(1) time and O(1) memory.
295 /// use std::collections::LinkedList;
297 /// let mut list1 = LinkedList::new();
298 /// list1.push_back('a');
300 /// let mut list2 = LinkedList::new();
301 /// list2.push_back('b');
302 /// list2.push_back('c');
304 /// list1.append(&mut list2);
306 /// let mut iter = list1.iter();
307 /// assert_eq!(iter.next(), Some(&'a'));
308 /// assert_eq!(iter.next(), Some(&'b'));
309 /// assert_eq!(iter.next(), Some(&'c'));
310 /// assert!(iter.next().is_none());
312 /// assert!(list2.is_empty());
314 #[stable(feature = "rust1", since = "1.0.0")]
315 pub fn append(&mut self, other: &mut Self) {
317 None => mem::swap(self, other),
319 // `as_mut` is okay here because we have exclusive access to the entirety
321 if let Some(mut other_head) = other.head.take() {
323 tail.as_mut().next = Some(other_head);
324 other_head.as_mut().prev = Some(tail);
327 self.tail = other.tail.take();
328 self.len += mem::replace(&mut other.len, 0);
334 /// Provides a forward iterator.
339 /// use std::collections::LinkedList;
341 /// let mut list: LinkedList<u32> = LinkedList::new();
343 /// list.push_back(0);
344 /// list.push_back(1);
345 /// list.push_back(2);
347 /// let mut iter = list.iter();
348 /// assert_eq!(iter.next(), Some(&0));
349 /// assert_eq!(iter.next(), Some(&1));
350 /// assert_eq!(iter.next(), Some(&2));
351 /// assert_eq!(iter.next(), None);
354 #[stable(feature = "rust1", since = "1.0.0")]
355 pub fn iter(&self) -> Iter<'_, T> {
364 /// Provides a forward iterator with mutable references.
369 /// use std::collections::LinkedList;
371 /// let mut list: LinkedList<u32> = LinkedList::new();
373 /// list.push_back(0);
374 /// list.push_back(1);
375 /// list.push_back(2);
377 /// for element in list.iter_mut() {
381 /// let mut iter = list.iter();
382 /// assert_eq!(iter.next(), Some(&10));
383 /// assert_eq!(iter.next(), Some(&11));
384 /// assert_eq!(iter.next(), Some(&12));
385 /// assert_eq!(iter.next(), None);
388 #[stable(feature = "rust1", since = "1.0.0")]
389 pub fn iter_mut(&mut self) -> IterMut<'_, T> {
398 /// Returns `true` if the `LinkedList` is empty.
400 /// This operation should compute in O(1) time.
405 /// use std::collections::LinkedList;
407 /// let mut dl = LinkedList::new();
408 /// assert!(dl.is_empty());
410 /// dl.push_front("foo");
411 /// assert!(!dl.is_empty());
414 #[stable(feature = "rust1", since = "1.0.0")]
415 pub fn is_empty(&self) -> bool {
419 /// Returns the length of the `LinkedList`.
421 /// This operation should compute in O(1) time.
426 /// use std::collections::LinkedList;
428 /// let mut dl = LinkedList::new();
430 /// dl.push_front(2);
431 /// assert_eq!(dl.len(), 1);
433 /// dl.push_front(1);
434 /// assert_eq!(dl.len(), 2);
437 /// assert_eq!(dl.len(), 3);
440 #[stable(feature = "rust1", since = "1.0.0")]
441 pub fn len(&self) -> usize {
445 /// Removes all elements from the `LinkedList`.
447 /// This operation should compute in O(n) time.
452 /// use std::collections::LinkedList;
454 /// let mut dl = LinkedList::new();
456 /// dl.push_front(2);
457 /// dl.push_front(1);
458 /// assert_eq!(dl.len(), 2);
459 /// assert_eq!(dl.front(), Some(&1));
462 /// assert_eq!(dl.len(), 0);
463 /// assert_eq!(dl.front(), None);
466 #[stable(feature = "rust1", since = "1.0.0")]
467 pub fn clear(&mut self) {
471 /// Returns `true` if the `LinkedList` contains an element equal to the
477 /// use std::collections::LinkedList;
479 /// let mut list: LinkedList<u32> = LinkedList::new();
481 /// list.push_back(0);
482 /// list.push_back(1);
483 /// list.push_back(2);
485 /// assert_eq!(list.contains(&0), true);
486 /// assert_eq!(list.contains(&10), false);
488 #[stable(feature = "linked_list_contains", since = "1.12.0")]
489 pub fn contains(&self, x: &T) -> bool
490 where T: PartialEq<T>
492 self.iter().any(|e| e == x)
495 /// Provides a reference to the front element, or `None` if the list is
501 /// use std::collections::LinkedList;
503 /// let mut dl = LinkedList::new();
504 /// assert_eq!(dl.front(), None);
506 /// dl.push_front(1);
507 /// assert_eq!(dl.front(), Some(&1));
510 #[stable(feature = "rust1", since = "1.0.0")]
511 pub fn front(&self) -> Option<&T> {
513 self.head.as_ref().map(|node| &node.as_ref().element)
517 /// Provides a mutable reference to the front element, or `None` if the list
523 /// use std::collections::LinkedList;
525 /// let mut dl = LinkedList::new();
526 /// assert_eq!(dl.front(), None);
528 /// dl.push_front(1);
529 /// assert_eq!(dl.front(), Some(&1));
531 /// match dl.front_mut() {
533 /// Some(x) => *x = 5,
535 /// assert_eq!(dl.front(), Some(&5));
538 #[stable(feature = "rust1", since = "1.0.0")]
539 pub fn front_mut(&mut self) -> Option<&mut T> {
541 self.head.as_mut().map(|node| &mut node.as_mut().element)
545 /// Provides a reference to the back element, or `None` if the list is
551 /// use std::collections::LinkedList;
553 /// let mut dl = LinkedList::new();
554 /// assert_eq!(dl.back(), None);
557 /// assert_eq!(dl.back(), Some(&1));
560 #[stable(feature = "rust1", since = "1.0.0")]
561 pub fn back(&self) -> Option<&T> {
563 self.tail.as_ref().map(|node| &node.as_ref().element)
567 /// Provides a mutable reference to the back element, or `None` if the list
573 /// use std::collections::LinkedList;
575 /// let mut dl = LinkedList::new();
576 /// assert_eq!(dl.back(), None);
579 /// assert_eq!(dl.back(), Some(&1));
581 /// match dl.back_mut() {
583 /// Some(x) => *x = 5,
585 /// assert_eq!(dl.back(), Some(&5));
588 #[stable(feature = "rust1", since = "1.0.0")]
589 pub fn back_mut(&mut self) -> Option<&mut T> {
591 self.tail.as_mut().map(|node| &mut node.as_mut().element)
595 /// Adds an element first in the list.
597 /// This operation should compute in O(1) time.
602 /// use std::collections::LinkedList;
604 /// let mut dl = LinkedList::new();
606 /// dl.push_front(2);
607 /// assert_eq!(dl.front().unwrap(), &2);
609 /// dl.push_front(1);
610 /// assert_eq!(dl.front().unwrap(), &1);
612 #[stable(feature = "rust1", since = "1.0.0")]
613 pub fn push_front(&mut self, elt: T) {
614 self.push_front_node(box Node::new(elt));
617 /// Removes the first element and returns it, or `None` if the list is
620 /// This operation should compute in O(1) time.
625 /// use std::collections::LinkedList;
627 /// let mut d = LinkedList::new();
628 /// assert_eq!(d.pop_front(), None);
632 /// assert_eq!(d.pop_front(), Some(3));
633 /// assert_eq!(d.pop_front(), Some(1));
634 /// assert_eq!(d.pop_front(), None);
636 #[stable(feature = "rust1", since = "1.0.0")]
637 pub fn pop_front(&mut self) -> Option<T> {
638 self.pop_front_node().map(Node::into_element)
641 /// Appends an element to the back of a list.
643 /// This operation should compute in O(1) time.
648 /// use std::collections::LinkedList;
650 /// let mut d = LinkedList::new();
653 /// assert_eq!(3, *d.back().unwrap());
655 #[stable(feature = "rust1", since = "1.0.0")]
656 pub fn push_back(&mut self, elt: T) {
657 self.push_back_node(box Node::new(elt));
660 /// Removes the last element from a list and returns it, or `None` if
663 /// This operation should compute in O(1) time.
668 /// use std::collections::LinkedList;
670 /// let mut d = LinkedList::new();
671 /// assert_eq!(d.pop_back(), None);
674 /// assert_eq!(d.pop_back(), Some(3));
676 #[stable(feature = "rust1", since = "1.0.0")]
677 pub fn pop_back(&mut self) -> Option<T> {
678 self.pop_back_node().map(Node::into_element)
681 /// Splits the list into two at the given index. Returns everything after the given index,
682 /// including the index.
684 /// This operation should compute in O(n) time.
688 /// Panics if `at > len`.
693 /// use std::collections::LinkedList;
695 /// let mut d = LinkedList::new();
701 /// let mut splitted = d.split_off(2);
703 /// assert_eq!(splitted.pop_front(), Some(1));
704 /// assert_eq!(splitted.pop_front(), None);
706 #[stable(feature = "rust1", since = "1.0.0")]
707 pub fn split_off(&mut self, at: usize) -> LinkedList<T> {
708 let len = self.len();
709 assert!(at <= len, "Cannot split off at a nonexistent index");
711 return mem::take(self);
712 } else if at == len {
716 // Below, we iterate towards the `i-1`th node, either from the start or the end,
717 // depending on which would be faster.
718 let split_node = if at - 1 <= len - 1 - (at - 1) {
719 let mut iter = self.iter_mut();
720 // instead of skipping using .skip() (which creates a new struct),
721 // we skip manually so we can access the head field without
722 // depending on implementation details of Skip
728 // better off starting from the end
729 let mut iter = self.iter_mut();
730 for _ in 0..len - 1 - (at - 1) {
736 // The split node is the new tail node of the first part and owns
737 // the head of the second part.
738 let second_part_head;
741 second_part_head = split_node.unwrap().as_mut().next.take();
742 if let Some(mut head) = second_part_head {
743 head.as_mut().prev = None;
747 let second_part = LinkedList {
748 head: second_part_head,
754 // Fix the tail ptr of the first part
755 self.tail = split_node;
761 /// Creates an iterator which uses a closure to determine if an element should be removed.
763 /// If the closure returns true, then the element is removed and yielded.
764 /// If the closure returns false, the element will remain in the list and will not be yielded
767 /// Note that `drain_filter` lets you mutate every element in the filter closure, regardless of
768 /// whether you choose to keep or remove it.
772 /// Splitting a list into evens and odds, reusing the original list:
775 /// #![feature(drain_filter)]
776 /// use std::collections::LinkedList;
778 /// let mut numbers: LinkedList<u32> = LinkedList::new();
779 /// numbers.extend(&[1, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15]);
781 /// let evens = numbers.drain_filter(|x| *x % 2 == 0).collect::<LinkedList<_>>();
782 /// let odds = numbers;
784 /// assert_eq!(evens.into_iter().collect::<Vec<_>>(), vec![2, 4, 6, 8, 14]);
785 /// assert_eq!(odds.into_iter().collect::<Vec<_>>(), vec![1, 3, 5, 9, 11, 13, 15]);
787 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
788 pub fn drain_filter<F>(&mut self, filter: F) -> DrainFilter<'_, T, F>
789 where F: FnMut(&mut T) -> bool
791 // avoid borrow issues.
793 let old_len = self.len;
805 #[stable(feature = "rust1", since = "1.0.0")]
806 unsafe impl<#[may_dangle] T> Drop for LinkedList<T> {
808 while let Some(_) = self.pop_front_node() {}
812 #[stable(feature = "rust1", since = "1.0.0")]
813 impl<'a, T> Iterator for Iter<'a, T> {
817 fn next(&mut self) -> Option<&'a T> {
821 self.head.map(|node| unsafe {
822 // Need an unbound lifetime to get 'a
823 let node = &*node.as_ptr();
825 self.head = node.next;
832 fn size_hint(&self) -> (usize, Option<usize>) {
833 (self.len, Some(self.len))
837 fn last(mut self) -> Option<&'a T> {
842 #[stable(feature = "rust1", since = "1.0.0")]
843 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
845 fn next_back(&mut self) -> Option<&'a T> {
849 self.tail.map(|node| unsafe {
850 // Need an unbound lifetime to get 'a
851 let node = &*node.as_ptr();
853 self.tail = node.prev;
860 #[stable(feature = "rust1", since = "1.0.0")]
861 impl<T> ExactSizeIterator for Iter<'_, T> {}
863 #[stable(feature = "fused", since = "1.26.0")]
864 impl<T> FusedIterator for Iter<'_, T> {}
866 #[stable(feature = "rust1", since = "1.0.0")]
867 impl<'a, T> Iterator for IterMut<'a, T> {
868 type Item = &'a mut T;
871 fn next(&mut self) -> Option<&'a mut T> {
875 self.head.map(|node| unsafe {
876 // Need an unbound lifetime to get 'a
877 let node = &mut *node.as_ptr();
879 self.head = node.next;
886 fn size_hint(&self) -> (usize, Option<usize>) {
887 (self.len, Some(self.len))
891 fn last(mut self) -> Option<&'a mut T> {
896 #[stable(feature = "rust1", since = "1.0.0")]
897 impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
899 fn next_back(&mut self) -> Option<&'a mut T> {
903 self.tail.map(|node| unsafe {
904 // Need an unbound lifetime to get 'a
905 let node = &mut *node.as_ptr();
907 self.tail = node.prev;
914 #[stable(feature = "rust1", since = "1.0.0")]
915 impl<T> ExactSizeIterator for IterMut<'_, T> {}
917 #[stable(feature = "fused", since = "1.26.0")]
918 impl<T> FusedIterator for IterMut<'_, T> {}
920 impl<T> IterMut<'_, T> {
921 /// Inserts the given element just after the element most recently returned by `.next()`.
922 /// The inserted element does not appear in the iteration.
927 /// #![feature(linked_list_extras)]
929 /// use std::collections::LinkedList;
931 /// let mut list: LinkedList<_> = vec![1, 3, 4].into_iter().collect();
934 /// let mut it = list.iter_mut();
935 /// assert_eq!(it.next().unwrap(), &1);
936 /// // insert `2` after `1`
937 /// it.insert_next(2);
940 /// let vec: Vec<_> = list.into_iter().collect();
941 /// assert_eq!(vec, [1, 2, 3, 4]);
945 #[unstable(feature = "linked_list_extras",
946 reason = "this is probably better handled by a cursor type -- we'll see",
948 pub fn insert_next(&mut self, element: T) {
950 // `push_back` is okay with aliasing `element` references
951 None => self.list.push_back(element),
952 Some(head) => unsafe {
953 let prev = match head.as_ref().prev {
954 // `push_front` is okay with aliasing nodes
955 None => return self.list.push_front(element),
959 let node = Some(Box::into_raw_non_null(box Node {
965 // Not creating references to entire nodes to not invalidate the
966 // reference to `element` we handed to the user.
967 (*prev.as_ptr()).next = node;
968 (*head.as_ptr()).prev = node;
975 /// Provides a reference to the next element, without changing the iterator.
980 /// #![feature(linked_list_extras)]
982 /// use std::collections::LinkedList;
984 /// let mut list: LinkedList<_> = vec![1, 2, 3].into_iter().collect();
986 /// let mut it = list.iter_mut();
987 /// assert_eq!(it.next().unwrap(), &1);
988 /// assert_eq!(it.peek_next().unwrap(), &2);
989 /// // We just peeked at 2, so it was not consumed from the iterator.
990 /// assert_eq!(it.next().unwrap(), &2);
993 #[unstable(feature = "linked_list_extras",
994 reason = "this is probably better handled by a cursor type -- we'll see",
996 pub fn peek_next(&mut self) -> Option<&mut T> {
1001 self.head.as_mut().map(|node| &mut node.as_mut().element)
1007 /// An iterator produced by calling `drain_filter` on LinkedList.
1008 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
1009 pub struct DrainFilter<'a, T: 'a, F: 'a>
1010 where F: FnMut(&mut T) -> bool,
1012 list: &'a mut LinkedList<T>,
1013 it: Option<NonNull<Node<T>>>,
1019 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
1020 impl<T, F> Iterator for DrainFilter<'_, T, F>
1021 where F: FnMut(&mut T) -> bool,
1025 fn next(&mut self) -> Option<T> {
1026 while let Some(mut node) = self.it {
1028 self.it = node.as_ref().next;
1031 if (self.pred)(&mut node.as_mut().element) {
1032 // `unlink_node` is okay with aliasing `element` references.
1033 self.list.unlink_node(node);
1034 return Some(Box::from_raw(node.as_ptr()).element);
1042 fn size_hint(&self) -> (usize, Option<usize>) {
1043 (0, Some(self.old_len - self.idx))
1047 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
1048 impl<T, F> Drop for DrainFilter<'_, T, F>
1049 where F: FnMut(&mut T) -> bool,
1051 fn drop(&mut self) {
1052 self.for_each(drop);
1056 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
1057 impl<T: fmt::Debug, F> fmt::Debug for DrainFilter<'_, T, F>
1058 where F: FnMut(&mut T) -> bool
1060 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1061 f.debug_tuple("DrainFilter")
1067 #[stable(feature = "rust1", since = "1.0.0")]
1068 impl<T> Iterator for IntoIter<T> {
1072 fn next(&mut self) -> Option<T> {
1073 self.list.pop_front()
1077 fn size_hint(&self) -> (usize, Option<usize>) {
1078 (self.list.len, Some(self.list.len))
1082 #[stable(feature = "rust1", since = "1.0.0")]
1083 impl<T> DoubleEndedIterator for IntoIter<T> {
1085 fn next_back(&mut self) -> Option<T> {
1086 self.list.pop_back()
1090 #[stable(feature = "rust1", since = "1.0.0")]
1091 impl<T> ExactSizeIterator for IntoIter<T> {}
1093 #[stable(feature = "fused", since = "1.26.0")]
1094 impl<T> FusedIterator for IntoIter<T> {}
1096 #[stable(feature = "rust1", since = "1.0.0")]
1097 impl<T> FromIterator<T> for LinkedList<T> {
1098 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
1099 let mut list = Self::new();
1105 #[stable(feature = "rust1", since = "1.0.0")]
1106 impl<T> IntoIterator for LinkedList<T> {
1108 type IntoIter = IntoIter<T>;
1110 /// Consumes the list into an iterator yielding elements by value.
1112 fn into_iter(self) -> IntoIter<T> {
1113 IntoIter { list: self }
1117 #[stable(feature = "rust1", since = "1.0.0")]
1118 impl<'a, T> IntoIterator for &'a LinkedList<T> {
1120 type IntoIter = Iter<'a, T>;
1122 fn into_iter(self) -> Iter<'a, T> {
1127 #[stable(feature = "rust1", since = "1.0.0")]
1128 impl<'a, T> IntoIterator for &'a mut LinkedList<T> {
1129 type Item = &'a mut T;
1130 type IntoIter = IterMut<'a, T>;
1132 fn into_iter(self) -> IterMut<'a, T> {
1137 #[stable(feature = "rust1", since = "1.0.0")]
1138 impl<T> Extend<T> for LinkedList<T> {
1139 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1140 <Self as SpecExtend<I>>::spec_extend(self, iter);
1144 impl<I: IntoIterator> SpecExtend<I> for LinkedList<I::Item> {
1145 default fn spec_extend(&mut self, iter: I) {
1146 iter.into_iter().for_each(move |elt| self.push_back(elt));
1150 impl<T> SpecExtend<LinkedList<T>> for LinkedList<T> {
1151 fn spec_extend(&mut self, ref mut other: LinkedList<T>) {
1156 #[stable(feature = "extend_ref", since = "1.2.0")]
1157 impl<'a, T: 'a + Copy> Extend<&'a T> for LinkedList<T> {
1158 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
1159 self.extend(iter.into_iter().cloned());
1163 #[stable(feature = "rust1", since = "1.0.0")]
1164 impl<T: PartialEq> PartialEq for LinkedList<T> {
1165 fn eq(&self, other: &Self) -> bool {
1166 self.len() == other.len() && self.iter().eq(other)
1169 fn ne(&self, other: &Self) -> bool {
1170 self.len() != other.len() || self.iter().ne(other)
1174 #[stable(feature = "rust1", since = "1.0.0")]
1175 impl<T: Eq> Eq for LinkedList<T> {}
1177 #[stable(feature = "rust1", since = "1.0.0")]
1178 impl<T: PartialOrd> PartialOrd for LinkedList<T> {
1179 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1180 self.iter().partial_cmp(other)
1184 #[stable(feature = "rust1", since = "1.0.0")]
1185 impl<T: Ord> Ord for LinkedList<T> {
1187 fn cmp(&self, other: &Self) -> Ordering {
1188 self.iter().cmp(other)
1192 #[stable(feature = "rust1", since = "1.0.0")]
1193 impl<T: Clone> Clone for LinkedList<T> {
1194 fn clone(&self) -> Self {
1195 self.iter().cloned().collect()
1199 #[stable(feature = "rust1", since = "1.0.0")]
1200 impl<T: fmt::Debug> fmt::Debug for LinkedList<T> {
1201 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1202 f.debug_list().entries(self).finish()
1206 #[stable(feature = "rust1", since = "1.0.0")]
1207 impl<T: Hash> Hash for LinkedList<T> {
1208 fn hash<H: Hasher>(&self, state: &mut H) {
1209 self.len().hash(state);
1216 // Ensure that `LinkedList` and its read-only iterators are covariant in their type parameters.
1218 fn assert_covariance() {
1219 fn a<'a>(x: LinkedList<&'static str>) -> LinkedList<&'a str> {
1222 fn b<'i, 'a>(x: Iter<'i, &'static str>) -> Iter<'i, &'a str> {
1225 fn c<'a>(x: IntoIter<&'static str>) -> IntoIter<&'a str> {
1230 #[stable(feature = "rust1", since = "1.0.0")]
1231 unsafe impl<T: Send> Send for LinkedList<T> {}
1233 #[stable(feature = "rust1", since = "1.0.0")]
1234 unsafe impl<T: Sync> Sync for LinkedList<T> {}
1236 #[stable(feature = "rust1", since = "1.0.0")]
1237 unsafe impl<T: Sync> Send for Iter<'_, T> {}
1239 #[stable(feature = "rust1", since = "1.0.0")]
1240 unsafe impl<T: Sync> Sync for Iter<'_, T> {}
1242 #[stable(feature = "rust1", since = "1.0.0")]
1243 unsafe impl<T: Send> Send for IterMut<'_, T> {}
1245 #[stable(feature = "rust1", since = "1.0.0")]
1246 unsafe impl<T: Sync> Sync for IterMut<'_, T> {}
1253 use rand::{thread_rng, RngCore};
1255 use super::{LinkedList, Node};
1258 fn list_from<T: Clone>(v: &[T]) -> LinkedList<T> {
1259 v.iter().cloned().collect()
1262 pub fn check_links<T>(list: &LinkedList<T>) {
1265 let mut last_ptr: Option<&Node<T>> = None;
1266 let mut node_ptr: &Node<T>;
1269 // tail node should also be None.
1270 assert!(list.tail.is_none());
1271 assert_eq!(0, list.len);
1274 Some(node) => node_ptr = &*node.as_ptr(),
1277 match (last_ptr, node_ptr.prev) {
1279 (None, _) => panic!("prev link for head"),
1280 (Some(p), Some(pptr)) => {
1281 assert_eq!(p as *const Node<T>, pptr.as_ptr() as *const Node<T>);
1283 _ => panic!("prev link is none, not good"),
1285 match node_ptr.next {
1287 last_ptr = Some(node_ptr);
1288 node_ptr = &*next.as_ptr();
1298 // verify that the tail node points to the last node.
1299 let tail = list.tail.as_ref().expect("some tail node").as_ref();
1300 assert_eq!(tail as *const Node<T>, node_ptr as *const Node<T>);
1301 // check that len matches interior links.
1302 assert_eq!(len, list.len);
1310 let mut m = LinkedList::<i32>::new();
1311 let mut n = LinkedList::new();
1314 assert_eq!(m.len(), 0);
1315 assert_eq!(n.len(), 0);
1317 // Non-empty to empty
1319 let mut m = LinkedList::new();
1320 let mut n = LinkedList::new();
1324 assert_eq!(m.len(), 1);
1325 assert_eq!(m.pop_back(), Some(2));
1326 assert_eq!(n.len(), 0);
1329 // Empty to non-empty
1331 let mut m = LinkedList::new();
1332 let mut n = LinkedList::new();
1336 assert_eq!(m.len(), 1);
1337 assert_eq!(m.pop_back(), Some(2));
1341 // Non-empty to non-empty
1342 let v = vec![1, 2, 3, 4, 5];
1343 let u = vec![9, 8, 1, 2, 3, 4, 5];
1344 let mut m = list_from(&v);
1345 let mut n = list_from(&u);
1349 sum.extend_from_slice(&u);
1350 assert_eq!(sum.len(), m.len());
1352 assert_eq!(m.pop_front(), Some(elt))
1354 assert_eq!(n.len(), 0);
1355 // let's make sure it's working properly, since we
1356 // did some direct changes to private members
1358 assert_eq!(n.len(), 1);
1359 assert_eq!(n.pop_front(), Some(3));
1364 fn test_insert_prev() {
1365 let mut m = list_from(&[0, 2, 4, 6, 8]);
1368 let mut it = m.iter_mut();
1374 it.insert_next(*elt + 1);
1375 match it.peek_next() {
1376 Some(x) => assert_eq!(*x, *elt + 2),
1377 None => assert_eq!(8, *elt),
1386 assert_eq!(m.len(), 3 + len * 2);
1387 assert_eq!(m.into_iter().collect::<Vec<_>>(),
1388 [-2, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1]);
1392 #[cfg_attr(target_os = "emscripten", ignore)]
1393 #[cfg(not(miri))] // Miri does not support threads
1395 let n = list_from(&[1, 2, 3]);
1396 thread::spawn(move || {
1398 let a: &[_] = &[&1, &2, &3];
1399 assert_eq!(a, &*n.iter().collect::<Vec<_>>());
1411 #[cfg(not(miri))] // Miri is too slow
1418 // There was a bug in split_off that failed to null out the RHS's head's prev ptr.
1419 // This caused the RHS's dtor to walk up into the LHS at drop and delete all of
1422 // https://github.com/rust-lang/rust/issues/26021
1423 let mut v1 = LinkedList::new();
1428 let _ = v1.split_off(3); // Dropping this now should not cause laundry consumption
1429 assert_eq!(v1.len(), 3);
1431 assert_eq!(v1.iter().len(), 3);
1432 assert_eq!(v1.iter().collect::<Vec<_>>().len(), 3);
1436 fn test_split_off() {
1437 let mut v1 = LinkedList::new();
1444 for ix in 0..1 + v1.len() {
1445 let mut a = v1.clone();
1446 let b = a.split_off(ix);
1455 fn fuzz_test(sz: i32) {
1456 let mut m: LinkedList<_> = LinkedList::new();
1460 let r: u8 = thread_rng().next_u32() as u8;
1486 for (a, &b) in m.into_iter().zip(&v) {
1490 assert_eq!(i, v.len());
1494 fn drain_filter_test() {
1495 let mut m: LinkedList<u32> = LinkedList::new();
1496 m.extend(&[1, 2, 3, 4, 5, 6]);
1497 let deleted = m.drain_filter(|v| *v < 4).collect::<Vec<_>>();
1501 assert_eq!(deleted, &[1, 2, 3]);
1502 assert_eq!(m.into_iter().collect::<Vec<_>>(), &[4, 5, 6]);
1506 fn drain_to_empty_test() {
1507 let mut m: LinkedList<u32> = LinkedList::new();
1508 m.extend(&[1, 2, 3, 4, 5, 6]);
1509 let deleted = m.drain_filter(|_| true).collect::<Vec<_>>();
1513 assert_eq!(deleted, &[1, 2, 3, 4, 5, 6]);
1514 assert_eq!(m.into_iter().collect::<Vec<_>>(), &[]);