1 //! A doubly-linked list with owned nodes.
3 //! The `LinkedList` allows pushing and popping elements at either end
6 //! NOTE: It is almost always better to use [`Vec`] or [`VecDeque`] because
7 //! array-based containers are generally faster,
8 //! more memory efficient, and make better use of CPU cache.
10 //! [`Vec`]: crate::vec::Vec
11 //! [`VecDeque`]: super::vec_deque::VecDeque
13 #![stable(feature = "rust1", since = "1.0.0")]
15 use core::cmp::Ordering;
17 use core::hash::{Hash, Hasher};
18 use core::iter::{FromIterator, FusedIterator};
19 use core::marker::PhantomData;
21 use core::ptr::NonNull;
23 use super::SpecExtend;
24 use crate::boxed::Box;
29 /// A doubly-linked list with owned nodes.
31 /// The `LinkedList` allows pushing and popping elements at either end
34 /// A `LinkedList` with a known list of items can be initialized from an array:
36 /// use std::collections::LinkedList;
38 /// let list = LinkedList::from([1, 2, 3]);
41 /// NOTE: It is almost always better to use `Vec` or `VecDeque` because
42 /// array-based containers are generally faster,
43 /// more memory efficient, and make better use of CPU cache.
44 #[stable(feature = "rust1", since = "1.0.0")]
45 #[cfg_attr(not(test), rustc_diagnostic_item = "LinkedList")]
46 pub struct LinkedList<T> {
47 head: Option<NonNull<Node<T>>>,
48 tail: Option<NonNull<Node<T>>>,
50 marker: PhantomData<Box<Node<T>>>,
54 next: Option<NonNull<Node<T>>>,
55 prev: Option<NonNull<Node<T>>>,
59 /// An iterator over the elements of a `LinkedList`.
61 /// This `struct` is created by [`LinkedList::iter()`]. See its
62 /// documentation for more.
63 #[stable(feature = "rust1", since = "1.0.0")]
64 pub struct Iter<'a, T: 'a> {
65 head: Option<NonNull<Node<T>>>,
66 tail: Option<NonNull<Node<T>>>,
68 marker: PhantomData<&'a Node<T>>,
71 #[stable(feature = "collection_debug", since = "1.17.0")]
72 impl<T: fmt::Debug> fmt::Debug for Iter<'_, T> {
73 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
75 .field(&*mem::ManuallyDrop::new(LinkedList {
86 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
87 #[stable(feature = "rust1", since = "1.0.0")]
88 impl<T> Clone for Iter<'_, T> {
89 fn clone(&self) -> Self {
94 /// A mutable iterator over the elements of a `LinkedList`.
96 /// This `struct` is created by [`LinkedList::iter_mut()`]. See its
97 /// documentation for more.
98 #[stable(feature = "rust1", since = "1.0.0")]
99 pub struct IterMut<'a, T: 'a> {
100 head: Option<NonNull<Node<T>>>,
101 tail: Option<NonNull<Node<T>>>,
103 marker: PhantomData<&'a mut Node<T>>,
106 #[stable(feature = "collection_debug", since = "1.17.0")]
107 impl<T: fmt::Debug> fmt::Debug for IterMut<'_, T> {
108 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
109 f.debug_tuple("IterMut")
110 .field(&*mem::ManuallyDrop::new(LinkedList {
121 /// An owning iterator over the elements of a `LinkedList`.
123 /// This `struct` is created by the [`into_iter`] method on [`LinkedList`]
124 /// (provided by the `IntoIterator` trait). See its documentation for more.
126 /// [`into_iter`]: LinkedList::into_iter
128 #[stable(feature = "rust1", since = "1.0.0")]
129 pub struct IntoIter<T> {
133 #[stable(feature = "collection_debug", since = "1.17.0")]
134 impl<T: fmt::Debug> fmt::Debug for IntoIter<T> {
135 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
136 f.debug_tuple("IntoIter").field(&self.list).finish()
141 fn new(element: T) -> Self {
142 Node { next: None, prev: None, element }
145 fn into_element(self: Box<Self>) -> T {
151 impl<T> LinkedList<T> {
152 /// Adds the given node to the front of the list.
154 fn push_front_node(&mut self, mut node: Box<Node<T>>) {
155 // This method takes care not to create mutable references to whole nodes,
156 // to maintain validity of aliasing pointers into `element`.
158 node.next = self.head;
160 let node = Some(Box::leak(node).into());
163 None => self.tail = node,
164 // Not creating new mutable (unique!) references overlapping `element`.
165 Some(head) => (*head.as_ptr()).prev = node,
173 /// Removes and returns the node at the front of the list.
175 fn pop_front_node(&mut self) -> Option<Box<Node<T>>> {
176 // This method takes care not to create mutable references to whole nodes,
177 // to maintain validity of aliasing pointers into `element`.
178 self.head.map(|node| unsafe {
179 let node = Box::from_raw(node.as_ptr());
180 self.head = node.next;
183 None => self.tail = None,
184 // Not creating new mutable (unique!) references overlapping `element`.
185 Some(head) => (*head.as_ptr()).prev = None,
193 /// Adds the given node to the back of the list.
195 fn push_back_node(&mut self, mut node: Box<Node<T>>) {
196 // This method takes care not to create mutable references to whole nodes,
197 // to maintain validity of aliasing pointers into `element`.
200 node.prev = self.tail;
201 let node = Some(Box::leak(node).into());
204 None => self.head = node,
205 // Not creating new mutable (unique!) references overlapping `element`.
206 Some(tail) => (*tail.as_ptr()).next = node,
214 /// Removes and returns the node at the back of the list.
216 fn pop_back_node(&mut self) -> Option<Box<Node<T>>> {
217 // This method takes care not to create mutable references to whole nodes,
218 // to maintain validity of aliasing pointers into `element`.
219 self.tail.map(|node| unsafe {
220 let node = Box::from_raw(node.as_ptr());
221 self.tail = node.prev;
224 None => self.head = None,
225 // Not creating new mutable (unique!) references overlapping `element`.
226 Some(tail) => (*tail.as_ptr()).next = None,
234 /// Unlinks the specified node from the current list.
236 /// Warning: this will not check that the provided node belongs to the current list.
238 /// This method takes care not to create mutable references to `element`, to
239 /// maintain validity of aliasing pointers.
241 unsafe fn unlink_node(&mut self, mut node: NonNull<Node<T>>) {
242 let node = unsafe { node.as_mut() }; // this one is ours now, we can create an &mut.
244 // Not creating new mutable (unique!) references overlapping `element`.
246 Some(prev) => unsafe { (*prev.as_ptr()).next = node.next },
247 // this node is the head node
248 None => self.head = node.next,
252 Some(next) => unsafe { (*next.as_ptr()).prev = node.prev },
253 // this node is the tail node
254 None => self.tail = node.prev,
260 /// Splices a series of nodes between two existing nodes.
262 /// Warning: this will not check that the provided node belongs to the two existing lists.
264 unsafe fn splice_nodes(
266 existing_prev: Option<NonNull<Node<T>>>,
267 existing_next: Option<NonNull<Node<T>>>,
268 mut splice_start: NonNull<Node<T>>,
269 mut splice_end: NonNull<Node<T>>,
270 splice_length: usize,
272 // This method takes care not to create multiple mutable references to whole nodes at the same time,
273 // to maintain validity of aliasing pointers into `element`.
274 if let Some(mut existing_prev) = existing_prev {
276 existing_prev.as_mut().next = Some(splice_start);
279 self.head = Some(splice_start);
281 if let Some(mut existing_next) = existing_next {
283 existing_next.as_mut().prev = Some(splice_end);
286 self.tail = Some(splice_end);
289 splice_start.as_mut().prev = existing_prev;
290 splice_end.as_mut().next = existing_next;
293 self.len += splice_length;
296 /// Detaches all nodes from a linked list as a series of nodes.
298 fn detach_all_nodes(mut self) -> Option<(NonNull<Node<T>>, NonNull<Node<T>>, usize)> {
299 let head = self.head.take();
300 let tail = self.tail.take();
301 let len = mem::replace(&mut self.len, 0);
302 if let Some(head) = head {
303 // SAFETY: In a LinkedList, either both the head and tail are None because
304 // the list is empty, or both head and tail are Some because the list is populated.
305 // Since we have verified the head is Some, we are sure the tail is Some too.
306 let tail = unsafe { tail.unwrap_unchecked() };
307 Some((head, tail, len))
314 unsafe fn split_off_before_node(
316 split_node: Option<NonNull<Node<T>>>,
319 // The split node is the new head node of the second part
320 if let Some(mut split_node) = split_node {
324 first_part_tail = split_node.as_mut().prev.take();
326 if let Some(mut tail) = first_part_tail {
328 tail.as_mut().next = None;
330 first_part_head = self.head;
332 first_part_head = None;
335 let first_part = LinkedList {
336 head: first_part_head,
337 tail: first_part_tail,
342 // Fix the head ptr of the second part
343 self.head = Some(split_node);
344 self.len = self.len - at;
348 mem::replace(self, LinkedList::new())
353 unsafe fn split_off_after_node(
355 split_node: Option<NonNull<Node<T>>>,
358 // The split node is the new tail node of the first part and owns
359 // the head of the second part.
360 if let Some(mut split_node) = split_node {
361 let second_part_head;
362 let second_part_tail;
364 second_part_head = split_node.as_mut().next.take();
366 if let Some(mut head) = second_part_head {
368 head.as_mut().prev = None;
370 second_part_tail = self.tail;
372 second_part_tail = None;
375 let second_part = LinkedList {
376 head: second_part_head,
377 tail: second_part_tail,
382 // Fix the tail ptr of the first part
383 self.tail = Some(split_node);
388 mem::replace(self, LinkedList::new())
393 #[stable(feature = "rust1", since = "1.0.0")]
394 impl<T> Default for LinkedList<T> {
395 /// Creates an empty `LinkedList<T>`.
397 fn default() -> Self {
402 impl<T> LinkedList<T> {
403 /// Creates an empty `LinkedList`.
408 /// use std::collections::LinkedList;
410 /// let list: LinkedList<u32> = LinkedList::new();
413 #[rustc_const_stable(feature = "const_linked_list_new", since = "1.32.0")]
414 #[stable(feature = "rust1", since = "1.0.0")]
415 pub const fn new() -> Self {
416 LinkedList { head: None, tail: None, len: 0, marker: PhantomData }
419 /// Moves all elements from `other` to the end of the list.
421 /// This reuses all the nodes from `other` and moves them into `self`. After
422 /// this operation, `other` becomes empty.
424 /// This operation should compute in *O*(1) time and *O*(1) memory.
429 /// use std::collections::LinkedList;
431 /// let mut list1 = LinkedList::new();
432 /// list1.push_back('a');
434 /// let mut list2 = LinkedList::new();
435 /// list2.push_back('b');
436 /// list2.push_back('c');
438 /// list1.append(&mut list2);
440 /// let mut iter = list1.iter();
441 /// assert_eq!(iter.next(), Some(&'a'));
442 /// assert_eq!(iter.next(), Some(&'b'));
443 /// assert_eq!(iter.next(), Some(&'c'));
444 /// assert!(iter.next().is_none());
446 /// assert!(list2.is_empty());
448 #[stable(feature = "rust1", since = "1.0.0")]
449 pub fn append(&mut self, other: &mut Self) {
451 None => mem::swap(self, other),
453 // `as_mut` is okay here because we have exclusive access to the entirety
455 if let Some(mut other_head) = other.head.take() {
457 tail.as_mut().next = Some(other_head);
458 other_head.as_mut().prev = Some(tail);
461 self.tail = other.tail.take();
462 self.len += mem::replace(&mut other.len, 0);
468 /// Provides a forward iterator.
473 /// use std::collections::LinkedList;
475 /// let mut list: LinkedList<u32> = LinkedList::new();
477 /// list.push_back(0);
478 /// list.push_back(1);
479 /// list.push_back(2);
481 /// let mut iter = list.iter();
482 /// assert_eq!(iter.next(), Some(&0));
483 /// assert_eq!(iter.next(), Some(&1));
484 /// assert_eq!(iter.next(), Some(&2));
485 /// assert_eq!(iter.next(), None);
488 #[stable(feature = "rust1", since = "1.0.0")]
489 pub fn iter(&self) -> Iter<'_, T> {
490 Iter { head: self.head, tail: self.tail, len: self.len, marker: PhantomData }
493 /// Provides a forward iterator with mutable references.
498 /// use std::collections::LinkedList;
500 /// let mut list: LinkedList<u32> = LinkedList::new();
502 /// list.push_back(0);
503 /// list.push_back(1);
504 /// list.push_back(2);
506 /// for element in list.iter_mut() {
510 /// let mut iter = list.iter();
511 /// assert_eq!(iter.next(), Some(&10));
512 /// assert_eq!(iter.next(), Some(&11));
513 /// assert_eq!(iter.next(), Some(&12));
514 /// assert_eq!(iter.next(), None);
517 #[stable(feature = "rust1", since = "1.0.0")]
518 pub fn iter_mut(&mut self) -> IterMut<'_, T> {
519 IterMut { head: self.head, tail: self.tail, len: self.len, marker: PhantomData }
522 /// Provides a cursor at the front element.
524 /// The cursor is pointing to the "ghost" non-element if the list is empty.
526 #[unstable(feature = "linked_list_cursors", issue = "58533")]
527 pub fn cursor_front(&self) -> Cursor<'_, T> {
528 Cursor { index: 0, current: self.head, list: self }
531 /// Provides a cursor with editing operations at the front element.
533 /// The cursor is pointing to the "ghost" non-element if the list is empty.
535 #[unstable(feature = "linked_list_cursors", issue = "58533")]
536 pub fn cursor_front_mut(&mut self) -> CursorMut<'_, T> {
537 CursorMut { index: 0, current: self.head, list: self }
540 /// Provides a cursor at the back element.
542 /// The cursor is pointing to the "ghost" non-element if the list is empty.
544 #[unstable(feature = "linked_list_cursors", issue = "58533")]
545 pub fn cursor_back(&self) -> Cursor<'_, T> {
546 Cursor { index: self.len.checked_sub(1).unwrap_or(0), current: self.tail, list: self }
549 /// Provides a cursor with editing operations at the back element.
551 /// The cursor is pointing to the "ghost" non-element if the list is empty.
553 #[unstable(feature = "linked_list_cursors", issue = "58533")]
554 pub fn cursor_back_mut(&mut self) -> CursorMut<'_, T> {
555 CursorMut { index: self.len.checked_sub(1).unwrap_or(0), current: self.tail, list: self }
558 /// Returns `true` if the `LinkedList` is empty.
560 /// This operation should compute in *O*(1) time.
565 /// use std::collections::LinkedList;
567 /// let mut dl = LinkedList::new();
568 /// assert!(dl.is_empty());
570 /// dl.push_front("foo");
571 /// assert!(!dl.is_empty());
574 #[stable(feature = "rust1", since = "1.0.0")]
575 pub fn is_empty(&self) -> bool {
579 /// Returns the length of the `LinkedList`.
581 /// This operation should compute in *O*(1) time.
586 /// use std::collections::LinkedList;
588 /// let mut dl = LinkedList::new();
590 /// dl.push_front(2);
591 /// assert_eq!(dl.len(), 1);
593 /// dl.push_front(1);
594 /// assert_eq!(dl.len(), 2);
597 /// assert_eq!(dl.len(), 3);
600 #[stable(feature = "rust1", since = "1.0.0")]
601 pub fn len(&self) -> usize {
605 /// Removes all elements from the `LinkedList`.
607 /// This operation should compute in *O*(*n*) time.
612 /// use std::collections::LinkedList;
614 /// let mut dl = LinkedList::new();
616 /// dl.push_front(2);
617 /// dl.push_front(1);
618 /// assert_eq!(dl.len(), 2);
619 /// assert_eq!(dl.front(), Some(&1));
622 /// assert_eq!(dl.len(), 0);
623 /// assert_eq!(dl.front(), None);
626 #[stable(feature = "rust1", since = "1.0.0")]
627 pub fn clear(&mut self) {
631 /// Returns `true` if the `LinkedList` contains an element equal to the
637 /// use std::collections::LinkedList;
639 /// let mut list: LinkedList<u32> = LinkedList::new();
641 /// list.push_back(0);
642 /// list.push_back(1);
643 /// list.push_back(2);
645 /// assert_eq!(list.contains(&0), true);
646 /// assert_eq!(list.contains(&10), false);
648 #[stable(feature = "linked_list_contains", since = "1.12.0")]
649 pub fn contains(&self, x: &T) -> bool
653 self.iter().any(|e| e == x)
656 /// Provides a reference to the front element, or `None` if the list is
662 /// use std::collections::LinkedList;
664 /// let mut dl = LinkedList::new();
665 /// assert_eq!(dl.front(), None);
667 /// dl.push_front(1);
668 /// assert_eq!(dl.front(), Some(&1));
671 #[stable(feature = "rust1", since = "1.0.0")]
672 pub fn front(&self) -> Option<&T> {
673 unsafe { self.head.as_ref().map(|node| &node.as_ref().element) }
676 /// Provides a mutable reference to the front element, or `None` if the list
682 /// use std::collections::LinkedList;
684 /// let mut dl = LinkedList::new();
685 /// assert_eq!(dl.front(), None);
687 /// dl.push_front(1);
688 /// assert_eq!(dl.front(), Some(&1));
690 /// match dl.front_mut() {
692 /// Some(x) => *x = 5,
694 /// assert_eq!(dl.front(), Some(&5));
697 #[stable(feature = "rust1", since = "1.0.0")]
698 pub fn front_mut(&mut self) -> Option<&mut T> {
699 unsafe { self.head.as_mut().map(|node| &mut node.as_mut().element) }
702 /// Provides a reference to the back element, or `None` if the list is
708 /// use std::collections::LinkedList;
710 /// let mut dl = LinkedList::new();
711 /// assert_eq!(dl.back(), None);
714 /// assert_eq!(dl.back(), Some(&1));
717 #[stable(feature = "rust1", since = "1.0.0")]
718 pub fn back(&self) -> Option<&T> {
719 unsafe { self.tail.as_ref().map(|node| &node.as_ref().element) }
722 /// Provides a mutable reference to the back element, or `None` if the list
728 /// use std::collections::LinkedList;
730 /// let mut dl = LinkedList::new();
731 /// assert_eq!(dl.back(), None);
734 /// assert_eq!(dl.back(), Some(&1));
736 /// match dl.back_mut() {
738 /// Some(x) => *x = 5,
740 /// assert_eq!(dl.back(), Some(&5));
743 #[stable(feature = "rust1", since = "1.0.0")]
744 pub fn back_mut(&mut self) -> Option<&mut T> {
745 unsafe { self.tail.as_mut().map(|node| &mut node.as_mut().element) }
748 /// Adds an element first in the list.
750 /// This operation should compute in *O*(1) time.
755 /// use std::collections::LinkedList;
757 /// let mut dl = LinkedList::new();
759 /// dl.push_front(2);
760 /// assert_eq!(dl.front().unwrap(), &2);
762 /// dl.push_front(1);
763 /// assert_eq!(dl.front().unwrap(), &1);
765 #[stable(feature = "rust1", since = "1.0.0")]
766 pub fn push_front(&mut self, elt: T) {
767 self.push_front_node(box Node::new(elt));
770 /// Removes the first element and returns it, or `None` if the list is
773 /// This operation should compute in *O*(1) time.
778 /// use std::collections::LinkedList;
780 /// let mut d = LinkedList::new();
781 /// assert_eq!(d.pop_front(), None);
785 /// assert_eq!(d.pop_front(), Some(3));
786 /// assert_eq!(d.pop_front(), Some(1));
787 /// assert_eq!(d.pop_front(), None);
789 #[stable(feature = "rust1", since = "1.0.0")]
790 pub fn pop_front(&mut self) -> Option<T> {
791 self.pop_front_node().map(Node::into_element)
794 /// Appends an element to the back of a list.
796 /// This operation should compute in *O*(1) time.
801 /// use std::collections::LinkedList;
803 /// let mut d = LinkedList::new();
806 /// assert_eq!(3, *d.back().unwrap());
808 #[stable(feature = "rust1", since = "1.0.0")]
809 pub fn push_back(&mut self, elt: T) {
810 self.push_back_node(box Node::new(elt));
813 /// Removes the last element from a list and returns it, or `None` if
816 /// This operation should compute in *O*(1) time.
821 /// use std::collections::LinkedList;
823 /// let mut d = LinkedList::new();
824 /// assert_eq!(d.pop_back(), None);
827 /// assert_eq!(d.pop_back(), Some(3));
829 #[stable(feature = "rust1", since = "1.0.0")]
830 pub fn pop_back(&mut self) -> Option<T> {
831 self.pop_back_node().map(Node::into_element)
834 /// Splits the list into two at the given index. Returns everything after the given index,
835 /// including the index.
837 /// This operation should compute in *O*(*n*) time.
841 /// Panics if `at > len`.
846 /// use std::collections::LinkedList;
848 /// let mut d = LinkedList::new();
854 /// let mut split = d.split_off(2);
856 /// assert_eq!(split.pop_front(), Some(1));
857 /// assert_eq!(split.pop_front(), None);
859 #[stable(feature = "rust1", since = "1.0.0")]
860 pub fn split_off(&mut self, at: usize) -> LinkedList<T> {
861 let len = self.len();
862 assert!(at <= len, "Cannot split off at a nonexistent index");
864 return mem::take(self);
865 } else if at == len {
869 // Below, we iterate towards the `i-1`th node, either from the start or the end,
870 // depending on which would be faster.
871 let split_node = if at - 1 <= len - 1 - (at - 1) {
872 let mut iter = self.iter_mut();
873 // instead of skipping using .skip() (which creates a new struct),
874 // we skip manually so we can access the head field without
875 // depending on implementation details of Skip
881 // better off starting from the end
882 let mut iter = self.iter_mut();
883 for _ in 0..len - 1 - (at - 1) {
888 unsafe { self.split_off_after_node(split_node, at) }
891 /// Removes the element at the given index and returns it.
893 /// This operation should compute in *O*(*n*) time.
896 /// Panics if at >= len
901 /// #![feature(linked_list_remove)]
902 /// use std::collections::LinkedList;
904 /// let mut d = LinkedList::new();
910 /// assert_eq!(d.remove(1), 2);
911 /// assert_eq!(d.remove(0), 3);
912 /// assert_eq!(d.remove(0), 1);
914 #[unstable(feature = "linked_list_remove", issue = "69210")]
915 pub fn remove(&mut self, at: usize) -> T {
916 let len = self.len();
917 assert!(at < len, "Cannot remove at an index outside of the list bounds");
919 // Below, we iterate towards the node at the given index, either from
920 // the start or the end, depending on which would be faster.
921 let offset_from_end = len - at - 1;
922 if at <= offset_from_end {
923 let mut cursor = self.cursor_front_mut();
927 cursor.remove_current().unwrap()
929 let mut cursor = self.cursor_back_mut();
930 for _ in 0..offset_from_end {
933 cursor.remove_current().unwrap()
937 /// Creates an iterator which uses a closure to determine if an element should be removed.
939 /// If the closure returns true, then the element is removed and yielded.
940 /// If the closure returns false, the element will remain in the list and will not be yielded
943 /// Note that `drain_filter` lets you mutate every element in the filter closure, regardless of
944 /// whether you choose to keep or remove it.
948 /// Splitting a list into evens and odds, reusing the original list:
951 /// #![feature(drain_filter)]
952 /// use std::collections::LinkedList;
954 /// let mut numbers: LinkedList<u32> = LinkedList::new();
955 /// numbers.extend(&[1, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15]);
957 /// let evens = numbers.drain_filter(|x| *x % 2 == 0).collect::<LinkedList<_>>();
958 /// let odds = numbers;
960 /// assert_eq!(evens.into_iter().collect::<Vec<_>>(), vec![2, 4, 6, 8, 14]);
961 /// assert_eq!(odds.into_iter().collect::<Vec<_>>(), vec![1, 3, 5, 9, 11, 13, 15]);
963 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
964 pub fn drain_filter<F>(&mut self, filter: F) -> DrainFilter<'_, T, F>
966 F: FnMut(&mut T) -> bool,
968 // avoid borrow issues.
970 let old_len = self.len;
972 DrainFilter { list: self, it, pred: filter, idx: 0, old_len }
976 #[stable(feature = "rust1", since = "1.0.0")]
977 unsafe impl<#[may_dangle] T> Drop for LinkedList<T> {
979 struct DropGuard<'a, T>(&'a mut LinkedList<T>);
981 impl<'a, T> Drop for DropGuard<'a, T> {
983 // Continue the same loop we do below. This only runs when a destructor has
984 // panicked. If another one panics this will abort.
985 while self.0.pop_front_node().is_some() {}
989 while let Some(node) = self.pop_front_node() {
990 let guard = DropGuard(self);
997 #[stable(feature = "rust1", since = "1.0.0")]
998 impl<'a, T> Iterator for Iter<'a, T> {
1002 fn next(&mut self) -> Option<&'a T> {
1006 self.head.map(|node| unsafe {
1007 // Need an unbound lifetime to get 'a
1008 let node = &*node.as_ptr();
1010 self.head = node.next;
1017 fn size_hint(&self) -> (usize, Option<usize>) {
1018 (self.len, Some(self.len))
1022 fn last(mut self) -> Option<&'a T> {
1027 #[stable(feature = "rust1", since = "1.0.0")]
1028 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
1030 fn next_back(&mut self) -> Option<&'a T> {
1034 self.tail.map(|node| unsafe {
1035 // Need an unbound lifetime to get 'a
1036 let node = &*node.as_ptr();
1038 self.tail = node.prev;
1045 #[stable(feature = "rust1", since = "1.0.0")]
1046 impl<T> ExactSizeIterator for Iter<'_, T> {}
1048 #[stable(feature = "fused", since = "1.26.0")]
1049 impl<T> FusedIterator for Iter<'_, T> {}
1051 #[stable(feature = "rust1", since = "1.0.0")]
1052 impl<'a, T> Iterator for IterMut<'a, T> {
1053 type Item = &'a mut T;
1056 fn next(&mut self) -> Option<&'a mut T> {
1060 self.head.map(|node| unsafe {
1061 // Need an unbound lifetime to get 'a
1062 let node = &mut *node.as_ptr();
1064 self.head = node.next;
1071 fn size_hint(&self) -> (usize, Option<usize>) {
1072 (self.len, Some(self.len))
1076 fn last(mut self) -> Option<&'a mut T> {
1081 #[stable(feature = "rust1", since = "1.0.0")]
1082 impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
1084 fn next_back(&mut self) -> Option<&'a mut T> {
1088 self.tail.map(|node| unsafe {
1089 // Need an unbound lifetime to get 'a
1090 let node = &mut *node.as_ptr();
1092 self.tail = node.prev;
1099 #[stable(feature = "rust1", since = "1.0.0")]
1100 impl<T> ExactSizeIterator for IterMut<'_, T> {}
1102 #[stable(feature = "fused", since = "1.26.0")]
1103 impl<T> FusedIterator for IterMut<'_, T> {}
1105 /// A cursor over a `LinkedList`.
1107 /// A `Cursor` is like an iterator, except that it can freely seek back-and-forth.
1109 /// Cursors always rest between two elements in the list, and index in a logically circular way.
1110 /// To accommodate this, there is a "ghost" non-element that yields `None` between the head and
1111 /// tail of the list.
1113 /// When created, cursors start at the front of the list, or the "ghost" non-element if the list is empty.
1114 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1115 pub struct Cursor<'a, T: 'a> {
1117 current: Option<NonNull<Node<T>>>,
1118 list: &'a LinkedList<T>,
1121 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1122 impl<T> Clone for Cursor<'_, T> {
1123 fn clone(&self) -> Self {
1124 let Cursor { index, current, list } = *self;
1125 Cursor { index, current, list }
1129 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1130 impl<T: fmt::Debug> fmt::Debug for Cursor<'_, T> {
1131 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1132 f.debug_tuple("Cursor").field(&self.list).field(&self.index()).finish()
1136 /// A cursor over a `LinkedList` with editing operations.
1138 /// A `Cursor` is like an iterator, except that it can freely seek back-and-forth, and can
1139 /// safely mutate the list during iteration. This is because the lifetime of its yielded
1140 /// references is tied to its own lifetime, instead of just the underlying list. This means
1141 /// cursors cannot yield multiple elements at once.
1143 /// Cursors always rest between two elements in the list, and index in a logically circular way.
1144 /// To accommodate this, there is a "ghost" non-element that yields `None` between the head and
1145 /// tail of the list.
1146 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1147 pub struct CursorMut<'a, T: 'a> {
1149 current: Option<NonNull<Node<T>>>,
1150 list: &'a mut LinkedList<T>,
1153 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1154 impl<T: fmt::Debug> fmt::Debug for CursorMut<'_, T> {
1155 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1156 f.debug_tuple("CursorMut").field(&self.list).field(&self.index()).finish()
1160 impl<'a, T> Cursor<'a, T> {
1161 /// Returns the cursor position index within the `LinkedList`.
1163 /// This returns `None` if the cursor is currently pointing to the
1164 /// "ghost" non-element.
1165 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1166 pub fn index(&self) -> Option<usize> {
1167 let _ = self.current?;
1171 /// Moves the cursor to the next element of the `LinkedList`.
1173 /// If the cursor is pointing to the "ghost" non-element then this will move it to
1174 /// the first element of the `LinkedList`. If it is pointing to the last
1175 /// element of the `LinkedList` then this will move it to the "ghost" non-element.
1176 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1177 pub fn move_next(&mut self) {
1178 match self.current.take() {
1179 // We had no current element; the cursor was sitting at the start position
1180 // Next element should be the head of the list
1182 self.current = self.list.head;
1185 // We had a previous element, so let's go to its next
1186 Some(current) => unsafe {
1187 self.current = current.as_ref().next;
1193 /// Moves the cursor to the previous element of the `LinkedList`.
1195 /// If the cursor is pointing to the "ghost" non-element then this will move it to
1196 /// the last element of the `LinkedList`. If it is pointing to the first
1197 /// element of the `LinkedList` then this will move it to the "ghost" non-element.
1198 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1199 pub fn move_prev(&mut self) {
1200 match self.current.take() {
1201 // No current. We're at the start of the list. Yield None and jump to the end.
1203 self.current = self.list.tail;
1204 self.index = self.list.len().checked_sub(1).unwrap_or(0);
1206 // Have a prev. Yield it and go to the previous element.
1207 Some(current) => unsafe {
1208 self.current = current.as_ref().prev;
1209 self.index = self.index.checked_sub(1).unwrap_or_else(|| self.list.len());
1214 /// Returns a reference to the element that the cursor is currently
1217 /// This returns `None` if the cursor is currently pointing to the
1218 /// "ghost" non-element.
1219 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1220 pub fn current(&self) -> Option<&'a T> {
1221 unsafe { self.current.map(|current| &(*current.as_ptr()).element) }
1224 /// Returns a reference to the next element.
1226 /// If the cursor is pointing to the "ghost" non-element then this returns
1227 /// the first element of the `LinkedList`. If it is pointing to the last
1228 /// element of the `LinkedList` then this returns `None`.
1229 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1230 pub fn peek_next(&self) -> Option<&'a T> {
1232 let next = match self.current {
1233 None => self.list.head,
1234 Some(current) => current.as_ref().next,
1236 next.map(|next| &(*next.as_ptr()).element)
1240 /// Returns a reference to the previous element.
1242 /// If the cursor is pointing to the "ghost" non-element then this returns
1243 /// the last element of the `LinkedList`. If it is pointing to the first
1244 /// element of the `LinkedList` then this returns `None`.
1245 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1246 pub fn peek_prev(&self) -> Option<&'a T> {
1248 let prev = match self.current {
1249 None => self.list.tail,
1250 Some(current) => current.as_ref().prev,
1252 prev.map(|prev| &(*prev.as_ptr()).element)
1256 /// Provides a reference to the front element of the cursor's parent list,
1257 /// or None if the list is empty.
1258 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1259 pub fn front(&self) -> Option<&'a T> {
1263 /// Provides a reference to the back element of the cursor's parent list,
1264 /// or None if the list is empty.
1265 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1266 pub fn back(&self) -> Option<&'a T> {
1271 impl<'a, T> CursorMut<'a, T> {
1272 /// Returns the cursor position index within the `LinkedList`.
1274 /// This returns `None` if the cursor is currently pointing to the
1275 /// "ghost" non-element.
1276 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1277 pub fn index(&self) -> Option<usize> {
1278 let _ = self.current?;
1282 /// Moves the cursor to the next element of the `LinkedList`.
1284 /// If the cursor is pointing to the "ghost" non-element then this will move it to
1285 /// the first element of the `LinkedList`. If it is pointing to the last
1286 /// element of the `LinkedList` then this will move it to the "ghost" non-element.
1287 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1288 pub fn move_next(&mut self) {
1289 match self.current.take() {
1290 // We had no current element; the cursor was sitting at the start position
1291 // Next element should be the head of the list
1293 self.current = self.list.head;
1296 // We had a previous element, so let's go to its next
1297 Some(current) => unsafe {
1298 self.current = current.as_ref().next;
1304 /// Moves the cursor to the previous element of the `LinkedList`.
1306 /// If the cursor is pointing to the "ghost" non-element then this will move it to
1307 /// the last element of the `LinkedList`. If it is pointing to the first
1308 /// element of the `LinkedList` then this will move it to the "ghost" non-element.
1309 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1310 pub fn move_prev(&mut self) {
1311 match self.current.take() {
1312 // No current. We're at the start of the list. Yield None and jump to the end.
1314 self.current = self.list.tail;
1315 self.index = self.list.len().checked_sub(1).unwrap_or(0);
1317 // Have a prev. Yield it and go to the previous element.
1318 Some(current) => unsafe {
1319 self.current = current.as_ref().prev;
1320 self.index = self.index.checked_sub(1).unwrap_or_else(|| self.list.len());
1325 /// Returns a reference to the element that the cursor is currently
1328 /// This returns `None` if the cursor is currently pointing to the
1329 /// "ghost" non-element.
1330 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1331 pub fn current(&mut self) -> Option<&mut T> {
1332 unsafe { self.current.map(|current| &mut (*current.as_ptr()).element) }
1335 /// Returns a reference to the next element.
1337 /// If the cursor is pointing to the "ghost" non-element then this returns
1338 /// the first element of the `LinkedList`. If it is pointing to the last
1339 /// element of the `LinkedList` then this returns `None`.
1340 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1341 pub fn peek_next(&mut self) -> Option<&mut T> {
1343 let next = match self.current {
1344 None => self.list.head,
1345 Some(current) => current.as_ref().next,
1347 next.map(|next| &mut (*next.as_ptr()).element)
1351 /// Returns a reference to the previous element.
1353 /// If the cursor is pointing to the "ghost" non-element then this returns
1354 /// the last element of the `LinkedList`. If it is pointing to the first
1355 /// element of the `LinkedList` then this returns `None`.
1356 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1357 pub fn peek_prev(&mut self) -> Option<&mut T> {
1359 let prev = match self.current {
1360 None => self.list.tail,
1361 Some(current) => current.as_ref().prev,
1363 prev.map(|prev| &mut (*prev.as_ptr()).element)
1367 /// Returns a read-only cursor pointing to the current element.
1369 /// The lifetime of the returned `Cursor` is bound to that of the
1370 /// `CursorMut`, which means it cannot outlive the `CursorMut` and that the
1371 /// `CursorMut` is frozen for the lifetime of the `Cursor`.
1372 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1373 pub fn as_cursor(&self) -> Cursor<'_, T> {
1374 Cursor { list: self.list, current: self.current, index: self.index }
1378 // Now the list editing operations
1380 impl<'a, T> CursorMut<'a, T> {
1381 /// Inserts a new element into the `LinkedList` after the current one.
1383 /// If the cursor is pointing at the "ghost" non-element then the new element is
1384 /// inserted at the front of the `LinkedList`.
1385 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1386 pub fn insert_after(&mut self, item: T) {
1388 let spliced_node = Box::leak(Box::new(Node::new(item))).into();
1389 let node_next = match self.current {
1390 None => self.list.head,
1391 Some(node) => node.as_ref().next,
1393 self.list.splice_nodes(self.current, node_next, spliced_node, spliced_node, 1);
1394 if self.current.is_none() {
1395 // The "ghost" non-element's index has changed.
1396 self.index = self.list.len;
1401 /// Inserts a new element into the `LinkedList` before the current one.
1403 /// If the cursor is pointing at the "ghost" non-element then the new element is
1404 /// inserted at the end of the `LinkedList`.
1405 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1406 pub fn insert_before(&mut self, item: T) {
1408 let spliced_node = Box::leak(Box::new(Node::new(item))).into();
1409 let node_prev = match self.current {
1410 None => self.list.tail,
1411 Some(node) => node.as_ref().prev,
1413 self.list.splice_nodes(node_prev, self.current, spliced_node, spliced_node, 1);
1418 /// Removes the current element from the `LinkedList`.
1420 /// The element that was removed is returned, and the cursor is
1421 /// moved to point to the next element in the `LinkedList`.
1423 /// If the cursor is currently pointing to the "ghost" non-element then no element
1424 /// is removed and `None` is returned.
1425 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1426 pub fn remove_current(&mut self) -> Option<T> {
1427 let unlinked_node = self.current?;
1429 self.current = unlinked_node.as_ref().next;
1430 self.list.unlink_node(unlinked_node);
1431 let unlinked_node = Box::from_raw(unlinked_node.as_ptr());
1432 Some(unlinked_node.element)
1436 /// Removes the current element from the `LinkedList` without deallocating the list node.
1438 /// The node that was removed is returned as a new `LinkedList` containing only this node.
1439 /// The cursor is moved to point to the next element in the current `LinkedList`.
1441 /// If the cursor is currently pointing to the "ghost" non-element then no element
1442 /// is removed and `None` is returned.
1443 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1444 pub fn remove_current_as_list(&mut self) -> Option<LinkedList<T>> {
1445 let mut unlinked_node = self.current?;
1447 self.current = unlinked_node.as_ref().next;
1448 self.list.unlink_node(unlinked_node);
1450 unlinked_node.as_mut().prev = None;
1451 unlinked_node.as_mut().next = None;
1453 head: Some(unlinked_node),
1454 tail: Some(unlinked_node),
1456 marker: PhantomData,
1461 /// Inserts the elements from the given `LinkedList` after the current one.
1463 /// If the cursor is pointing at the "ghost" non-element then the new elements are
1464 /// inserted at the start of the `LinkedList`.
1465 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1466 pub fn splice_after(&mut self, list: LinkedList<T>) {
1468 let (splice_head, splice_tail, splice_len) = match list.detach_all_nodes() {
1469 Some(parts) => parts,
1472 let node_next = match self.current {
1473 None => self.list.head,
1474 Some(node) => node.as_ref().next,
1476 self.list.splice_nodes(self.current, node_next, splice_head, splice_tail, splice_len);
1477 if self.current.is_none() {
1478 // The "ghost" non-element's index has changed.
1479 self.index = self.list.len;
1484 /// Inserts the elements from the given `LinkedList` before the current one.
1486 /// If the cursor is pointing at the "ghost" non-element then the new elements are
1487 /// inserted at the end of the `LinkedList`.
1488 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1489 pub fn splice_before(&mut self, list: LinkedList<T>) {
1491 let (splice_head, splice_tail, splice_len) = match list.detach_all_nodes() {
1492 Some(parts) => parts,
1495 let node_prev = match self.current {
1496 None => self.list.tail,
1497 Some(node) => node.as_ref().prev,
1499 self.list.splice_nodes(node_prev, self.current, splice_head, splice_tail, splice_len);
1500 self.index += splice_len;
1504 /// Splits the list into two after the current element. This will return a
1505 /// new list consisting of everything after the cursor, with the original
1506 /// list retaining everything before.
1508 /// If the cursor is pointing at the "ghost" non-element then the entire contents
1509 /// of the `LinkedList` are moved.
1510 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1511 pub fn split_after(&mut self) -> LinkedList<T> {
1512 let split_off_idx = if self.index == self.list.len { 0 } else { self.index + 1 };
1513 if self.index == self.list.len {
1514 // The "ghost" non-element's index has changed to 0.
1517 unsafe { self.list.split_off_after_node(self.current, split_off_idx) }
1520 /// Splits the list into two before the current element. This will return a
1521 /// new list consisting of everything before the cursor, with the original
1522 /// list retaining everything after.
1524 /// If the cursor is pointing at the "ghost" non-element then the entire contents
1525 /// of the `LinkedList` are moved.
1526 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1527 pub fn split_before(&mut self) -> LinkedList<T> {
1528 let split_off_idx = self.index;
1530 unsafe { self.list.split_off_before_node(self.current, split_off_idx) }
1533 /// Appends an element to the front of the cursor's parent list. The node
1534 /// that the cursor points to is unchanged, even if it is the "ghost" node.
1536 /// This operation should compute in O(1) time.
1537 // `push_front` continues to point to "ghost" when it addes a node to mimic
1538 // the behavior of `insert_before` on an empty list.
1539 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1540 pub fn push_front(&mut self, elt: T) {
1541 // Safety: We know that `push_front` does not change the position in
1542 // memory of other nodes. This ensures that `self.current` remains
1544 self.list.push_front(elt);
1548 /// Appends an element to the back of the cursor's parent list. The node
1549 /// that the cursor points to is unchanged, even if it is the "ghost" node.
1551 /// This operation should compute in O(1) time.
1552 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1553 pub fn push_back(&mut self, elt: T) {
1554 // Safety: We know that `push_back` does not change the position in
1555 // memory of other nodes. This ensures that `self.current` remains
1557 self.list.push_back(elt);
1558 if self.current().is_none() {
1559 // The index of "ghost" is the length of the list, so we just need
1560 // to increment self.index to reflect the new length of the list.
1565 /// Removes the first element from the cursor's parent list and returns it,
1566 /// or None if the list is empty. The element the cursor points to remains
1567 /// unchanged, unless it was pointing to the front element. In that case, it
1568 /// points to the new front element.
1570 /// This operation should compute in O(1) time.
1571 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1572 pub fn pop_front(&mut self) -> Option<T> {
1573 // We can't check if current is empty, we must check the list directly.
1574 // It is possible for `self.current == None` and the list to be
1576 if self.list.is_empty() {
1579 // We can't point to the node that we pop. Copying the behavior of
1580 // `remove_current`, we move on the the next node in the sequence.
1581 // If the list is of length 1 then we end pointing to the "ghost"
1582 // node at index 0, which is expected.
1583 if self.list.head == self.current {
1588 self.list.pop_front()
1592 /// Removes the last element from the cursor's parent list and returns it,
1593 /// or None if the list is empty. The element the cursor points to remains
1594 /// unchanged, unless it was pointing to the back element. In that case, it
1595 /// points to the "ghost" element.
1597 /// This operation should compute in O(1) time.
1598 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1599 pub fn pop_back(&mut self) -> Option<T> {
1600 if self.list.is_empty() {
1603 if self.list.tail == self.current {
1604 // The index now reflects the length of the list. It was the
1605 // length of the list minus 1, but now the list is 1 smaller. No
1606 // change is needed for `index`.
1607 self.current = None;
1608 } else if self.current.is_none() {
1609 self.index = self.list.len - 1;
1611 self.list.pop_back()
1615 /// Provides a reference to the front element of the cursor's parent list,
1616 /// or None if the list is empty.
1617 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1618 pub fn front(&self) -> Option<&T> {
1622 /// Provides a mutable reference to the front element of the cursor's
1623 /// parent list, or None if the list is empty.
1624 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1625 pub fn front_mut(&mut self) -> Option<&mut T> {
1626 self.list.front_mut()
1629 /// Provides a reference to the back element of the cursor's parent list,
1630 /// or None if the list is empty.
1631 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1632 pub fn back(&self) -> Option<&T> {
1636 /// Provides a mutable reference to back element of the cursor's parent
1637 /// list, or `None` if the list is empty.
1640 /// Building and mutating a list with a cursor, then getting the back element:
1642 /// #![feature(linked_list_cursors)]
1643 /// use std::collections::LinkedList;
1644 /// let mut dl = LinkedList::new();
1645 /// dl.push_front(3);
1646 /// dl.push_front(2);
1647 /// dl.push_front(1);
1648 /// let mut cursor = dl.cursor_front_mut();
1649 /// *cursor.current().unwrap() = 99;
1650 /// *cursor.back_mut().unwrap() = 0;
1651 /// let mut contents = dl.into_iter();
1652 /// assert_eq!(contents.next(), Some(99));
1653 /// assert_eq!(contents.next(), Some(2));
1654 /// assert_eq!(contents.next(), Some(0));
1655 /// assert_eq!(contents.next(), None);
1657 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1658 pub fn back_mut(&mut self) -> Option<&mut T> {
1659 self.list.back_mut()
1663 /// An iterator produced by calling `drain_filter` on LinkedList.
1664 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
1665 pub struct DrainFilter<'a, T: 'a, F: 'a>
1667 F: FnMut(&mut T) -> bool,
1669 list: &'a mut LinkedList<T>,
1670 it: Option<NonNull<Node<T>>>,
1676 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
1677 impl<T, F> Iterator for DrainFilter<'_, T, F>
1679 F: FnMut(&mut T) -> bool,
1683 fn next(&mut self) -> Option<T> {
1684 while let Some(mut node) = self.it {
1686 self.it = node.as_ref().next;
1689 if (self.pred)(&mut node.as_mut().element) {
1690 // `unlink_node` is okay with aliasing `element` references.
1691 self.list.unlink_node(node);
1692 return Some(Box::from_raw(node.as_ptr()).element);
1700 fn size_hint(&self) -> (usize, Option<usize>) {
1701 (0, Some(self.old_len - self.idx))
1705 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
1706 impl<T, F> Drop for DrainFilter<'_, T, F>
1708 F: FnMut(&mut T) -> bool,
1710 fn drop(&mut self) {
1711 struct DropGuard<'r, 'a, T, F>(&'r mut DrainFilter<'a, T, F>)
1713 F: FnMut(&mut T) -> bool;
1715 impl<'r, 'a, T, F> Drop for DropGuard<'r, 'a, T, F>
1717 F: FnMut(&mut T) -> bool,
1719 fn drop(&mut self) {
1720 self.0.for_each(drop);
1724 while let Some(item) = self.next() {
1725 let guard = DropGuard(self);
1732 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
1733 impl<T: fmt::Debug, F> fmt::Debug for DrainFilter<'_, T, F>
1735 F: FnMut(&mut T) -> bool,
1737 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1738 f.debug_tuple("DrainFilter").field(&self.list).finish()
1742 #[stable(feature = "rust1", since = "1.0.0")]
1743 impl<T> Iterator for IntoIter<T> {
1747 fn next(&mut self) -> Option<T> {
1748 self.list.pop_front()
1752 fn size_hint(&self) -> (usize, Option<usize>) {
1753 (self.list.len, Some(self.list.len))
1757 #[stable(feature = "rust1", since = "1.0.0")]
1758 impl<T> DoubleEndedIterator for IntoIter<T> {
1760 fn next_back(&mut self) -> Option<T> {
1761 self.list.pop_back()
1765 #[stable(feature = "rust1", since = "1.0.0")]
1766 impl<T> ExactSizeIterator for IntoIter<T> {}
1768 #[stable(feature = "fused", since = "1.26.0")]
1769 impl<T> FusedIterator for IntoIter<T> {}
1771 #[stable(feature = "rust1", since = "1.0.0")]
1772 impl<T> FromIterator<T> for LinkedList<T> {
1773 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
1774 let mut list = Self::new();
1780 #[stable(feature = "rust1", since = "1.0.0")]
1781 impl<T> IntoIterator for LinkedList<T> {
1783 type IntoIter = IntoIter<T>;
1785 /// Consumes the list into an iterator yielding elements by value.
1787 fn into_iter(self) -> IntoIter<T> {
1788 IntoIter { list: self }
1792 #[stable(feature = "rust1", since = "1.0.0")]
1793 impl<'a, T> IntoIterator for &'a LinkedList<T> {
1795 type IntoIter = Iter<'a, T>;
1797 fn into_iter(self) -> Iter<'a, T> {
1802 #[stable(feature = "rust1", since = "1.0.0")]
1803 impl<'a, T> IntoIterator for &'a mut LinkedList<T> {
1804 type Item = &'a mut T;
1805 type IntoIter = IterMut<'a, T>;
1807 fn into_iter(self) -> IterMut<'a, T> {
1812 #[stable(feature = "rust1", since = "1.0.0")]
1813 impl<T> Extend<T> for LinkedList<T> {
1814 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1815 <Self as SpecExtend<I>>::spec_extend(self, iter);
1819 fn extend_one(&mut self, elem: T) {
1820 self.push_back(elem);
1824 impl<I: IntoIterator> SpecExtend<I> for LinkedList<I::Item> {
1825 default fn spec_extend(&mut self, iter: I) {
1826 iter.into_iter().for_each(move |elt| self.push_back(elt));
1830 impl<T> SpecExtend<LinkedList<T>> for LinkedList<T> {
1831 fn spec_extend(&mut self, ref mut other: LinkedList<T>) {
1836 #[stable(feature = "extend_ref", since = "1.2.0")]
1837 impl<'a, T: 'a + Copy> Extend<&'a T> for LinkedList<T> {
1838 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
1839 self.extend(iter.into_iter().cloned());
1843 fn extend_one(&mut self, &elem: &'a T) {
1844 self.push_back(elem);
1848 #[stable(feature = "rust1", since = "1.0.0")]
1849 impl<T: PartialEq> PartialEq for LinkedList<T> {
1850 fn eq(&self, other: &Self) -> bool {
1851 self.len() == other.len() && self.iter().eq(other)
1854 fn ne(&self, other: &Self) -> bool {
1855 self.len() != other.len() || self.iter().ne(other)
1859 #[stable(feature = "rust1", since = "1.0.0")]
1860 impl<T: Eq> Eq for LinkedList<T> {}
1862 #[stable(feature = "rust1", since = "1.0.0")]
1863 impl<T: PartialOrd> PartialOrd for LinkedList<T> {
1864 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1865 self.iter().partial_cmp(other)
1869 #[stable(feature = "rust1", since = "1.0.0")]
1870 impl<T: Ord> Ord for LinkedList<T> {
1872 fn cmp(&self, other: &Self) -> Ordering {
1873 self.iter().cmp(other)
1877 #[stable(feature = "rust1", since = "1.0.0")]
1878 impl<T: Clone> Clone for LinkedList<T> {
1879 fn clone(&self) -> Self {
1880 self.iter().cloned().collect()
1883 fn clone_from(&mut self, other: &Self) {
1884 let mut iter_other = other.iter();
1885 if self.len() > other.len() {
1886 self.split_off(other.len());
1888 for (elem, elem_other) in self.iter_mut().zip(&mut iter_other) {
1889 elem.clone_from(elem_other);
1891 if !iter_other.is_empty() {
1892 self.extend(iter_other.cloned());
1897 #[stable(feature = "rust1", since = "1.0.0")]
1898 impl<T: fmt::Debug> fmt::Debug for LinkedList<T> {
1899 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1900 f.debug_list().entries(self).finish()
1904 #[stable(feature = "rust1", since = "1.0.0")]
1905 impl<T: Hash> Hash for LinkedList<T> {
1906 fn hash<H: Hasher>(&self, state: &mut H) {
1907 self.len().hash(state);
1914 #[stable(feature = "std_collections_from_array", since = "1.56.0")]
1915 impl<T, const N: usize> From<[T; N]> for LinkedList<T> {
1917 /// use std::collections::LinkedList;
1919 /// let list1 = LinkedList::from([1, 2, 3, 4]);
1920 /// let list2: LinkedList<_> = [1, 2, 3, 4].into();
1921 /// assert_eq!(list1, list2);
1923 fn from(arr: [T; N]) -> Self {
1924 core::array::IntoIter::new(arr).collect()
1928 // Ensure that `LinkedList` and its read-only iterators are covariant in their type parameters.
1930 fn assert_covariance() {
1931 fn a<'a>(x: LinkedList<&'static str>) -> LinkedList<&'a str> {
1934 fn b<'i, 'a>(x: Iter<'i, &'static str>) -> Iter<'i, &'a str> {
1937 fn c<'a>(x: IntoIter<&'static str>) -> IntoIter<&'a str> {
1942 #[stable(feature = "rust1", since = "1.0.0")]
1943 unsafe impl<T: Send> Send for LinkedList<T> {}
1945 #[stable(feature = "rust1", since = "1.0.0")]
1946 unsafe impl<T: Sync> Sync for LinkedList<T> {}
1948 #[stable(feature = "rust1", since = "1.0.0")]
1949 unsafe impl<T: Sync> Send for Iter<'_, T> {}
1951 #[stable(feature = "rust1", since = "1.0.0")]
1952 unsafe impl<T: Sync> Sync for Iter<'_, T> {}
1954 #[stable(feature = "rust1", since = "1.0.0")]
1955 unsafe impl<T: Send> Send for IterMut<'_, T> {}
1957 #[stable(feature = "rust1", since = "1.0.0")]
1958 unsafe impl<T: Sync> Sync for IterMut<'_, T> {}
1960 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1961 unsafe impl<T: Sync> Send for Cursor<'_, T> {}
1963 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1964 unsafe impl<T: Sync> Sync for Cursor<'_, T> {}
1966 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1967 unsafe impl<T: Send> Send for CursorMut<'_, T> {}
1969 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1970 unsafe impl<T: Sync> Sync for CursorMut<'_, T> {}