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.
45 /// [`Vec`]: crate::vec::Vec
46 /// [`VecDeque`]: super::vec_deque::VecDeque
47 #[stable(feature = "rust1", since = "1.0.0")]
48 #[cfg_attr(not(test), rustc_diagnostic_item = "LinkedList")]
49 #[rustc_insignificant_dtor]
50 pub struct LinkedList<T> {
51 head: Option<NonNull<Node<T>>>,
52 tail: Option<NonNull<Node<T>>>,
54 marker: PhantomData<Box<Node<T>>>,
58 next: Option<NonNull<Node<T>>>,
59 prev: Option<NonNull<Node<T>>>,
63 /// An iterator over the elements of a `LinkedList`.
65 /// This `struct` is created by [`LinkedList::iter()`]. See its
66 /// documentation for more.
67 #[stable(feature = "rust1", since = "1.0.0")]
68 pub struct Iter<'a, T: 'a> {
69 head: Option<NonNull<Node<T>>>,
70 tail: Option<NonNull<Node<T>>>,
72 marker: PhantomData<&'a Node<T>>,
75 #[stable(feature = "collection_debug", since = "1.17.0")]
76 impl<T: fmt::Debug> fmt::Debug for Iter<'_, T> {
77 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
79 .field(&*mem::ManuallyDrop::new(LinkedList {
90 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
91 #[stable(feature = "rust1", since = "1.0.0")]
92 impl<T> Clone for Iter<'_, T> {
93 fn clone(&self) -> Self {
98 /// A mutable iterator over the elements of a `LinkedList`.
100 /// This `struct` is created by [`LinkedList::iter_mut()`]. See its
101 /// documentation for more.
102 #[stable(feature = "rust1", since = "1.0.0")]
103 pub struct IterMut<'a, T: 'a> {
104 head: Option<NonNull<Node<T>>>,
105 tail: Option<NonNull<Node<T>>>,
107 marker: PhantomData<&'a mut Node<T>>,
110 #[stable(feature = "collection_debug", since = "1.17.0")]
111 impl<T: fmt::Debug> fmt::Debug for IterMut<'_, T> {
112 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
113 f.debug_tuple("IterMut")
114 .field(&*mem::ManuallyDrop::new(LinkedList {
125 /// An owning iterator over the elements of a `LinkedList`.
127 /// This `struct` is created by the [`into_iter`] method on [`LinkedList`]
128 /// (provided by the [`IntoIterator`] trait). See its documentation for more.
130 /// [`into_iter`]: LinkedList::into_iter
131 /// [`IntoIterator`]: core::iter::IntoIterator
133 #[stable(feature = "rust1", since = "1.0.0")]
134 pub struct IntoIter<T> {
138 #[stable(feature = "collection_debug", since = "1.17.0")]
139 impl<T: fmt::Debug> fmt::Debug for IntoIter<T> {
140 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
141 f.debug_tuple("IntoIter").field(&self.list).finish()
146 fn new(element: T) -> Self {
147 Node { next: None, prev: None, element }
150 fn into_element(self: Box<Self>) -> T {
156 impl<T> LinkedList<T> {
157 /// Adds the given node to the front of the list.
159 fn push_front_node(&mut self, mut node: Box<Node<T>>) {
160 // This method takes care not to create mutable references to whole nodes,
161 // to maintain validity of aliasing pointers into `element`.
163 node.next = self.head;
165 let node = Some(Box::leak(node).into());
168 None => self.tail = node,
169 // Not creating new mutable (unique!) references overlapping `element`.
170 Some(head) => (*head.as_ptr()).prev = node,
178 /// Removes and returns the node at the front of the list.
180 fn pop_front_node(&mut self) -> Option<Box<Node<T>>> {
181 // This method takes care not to create mutable references to whole nodes,
182 // to maintain validity of aliasing pointers into `element`.
183 self.head.map(|node| unsafe {
184 let node = Box::from_raw(node.as_ptr());
185 self.head = node.next;
188 None => self.tail = None,
189 // Not creating new mutable (unique!) references overlapping `element`.
190 Some(head) => (*head.as_ptr()).prev = None,
198 /// Adds the given node to the back of the list.
200 fn push_back_node(&mut self, mut node: Box<Node<T>>) {
201 // This method takes care not to create mutable references to whole nodes,
202 // to maintain validity of aliasing pointers into `element`.
205 node.prev = self.tail;
206 let node = Some(Box::leak(node).into());
209 None => self.head = node,
210 // Not creating new mutable (unique!) references overlapping `element`.
211 Some(tail) => (*tail.as_ptr()).next = node,
219 /// Removes and returns the node at the back of the list.
221 fn pop_back_node(&mut self) -> Option<Box<Node<T>>> {
222 // This method takes care not to create mutable references to whole nodes,
223 // to maintain validity of aliasing pointers into `element`.
224 self.tail.map(|node| unsafe {
225 let node = Box::from_raw(node.as_ptr());
226 self.tail = node.prev;
229 None => self.head = None,
230 // Not creating new mutable (unique!) references overlapping `element`.
231 Some(tail) => (*tail.as_ptr()).next = None,
239 /// Unlinks the specified node from the current list.
241 /// Warning: this will not check that the provided node belongs to the current list.
243 /// This method takes care not to create mutable references to `element`, to
244 /// maintain validity of aliasing pointers.
246 unsafe fn unlink_node(&mut self, mut node: NonNull<Node<T>>) {
247 let node = unsafe { node.as_mut() }; // this one is ours now, we can create an &mut.
249 // Not creating new mutable (unique!) references overlapping `element`.
251 Some(prev) => unsafe { (*prev.as_ptr()).next = node.next },
252 // this node is the head node
253 None => self.head = node.next,
257 Some(next) => unsafe { (*next.as_ptr()).prev = node.prev },
258 // this node is the tail node
259 None => self.tail = node.prev,
265 /// Splices a series of nodes between two existing nodes.
267 /// Warning: this will not check that the provided node belongs to the two existing lists.
269 unsafe fn splice_nodes(
271 existing_prev: Option<NonNull<Node<T>>>,
272 existing_next: Option<NonNull<Node<T>>>,
273 mut splice_start: NonNull<Node<T>>,
274 mut splice_end: NonNull<Node<T>>,
275 splice_length: usize,
277 // This method takes care not to create multiple mutable references to whole nodes at the same time,
278 // to maintain validity of aliasing pointers into `element`.
279 if let Some(mut existing_prev) = existing_prev {
281 existing_prev.as_mut().next = Some(splice_start);
284 self.head = Some(splice_start);
286 if let Some(mut existing_next) = existing_next {
288 existing_next.as_mut().prev = Some(splice_end);
291 self.tail = Some(splice_end);
294 splice_start.as_mut().prev = existing_prev;
295 splice_end.as_mut().next = existing_next;
298 self.len += splice_length;
301 /// Detaches all nodes from a linked list as a series of nodes.
303 fn detach_all_nodes(mut self) -> Option<(NonNull<Node<T>>, NonNull<Node<T>>, usize)> {
304 let head = self.head.take();
305 let tail = self.tail.take();
306 let len = mem::replace(&mut self.len, 0);
307 if let Some(head) = head {
308 // SAFETY: In a LinkedList, either both the head and tail are None because
309 // the list is empty, or both head and tail are Some because the list is populated.
310 // Since we have verified the head is Some, we are sure the tail is Some too.
311 let tail = unsafe { tail.unwrap_unchecked() };
312 Some((head, tail, len))
319 unsafe fn split_off_before_node(
321 split_node: Option<NonNull<Node<T>>>,
324 // The split node is the new head node of the second part
325 if let Some(mut split_node) = split_node {
329 first_part_tail = split_node.as_mut().prev.take();
331 if let Some(mut tail) = first_part_tail {
333 tail.as_mut().next = None;
335 first_part_head = self.head;
337 first_part_head = None;
340 let first_part = LinkedList {
341 head: first_part_head,
342 tail: first_part_tail,
347 // Fix the head ptr of the second part
348 self.head = Some(split_node);
349 self.len = self.len - at;
353 mem::replace(self, LinkedList::new())
358 unsafe fn split_off_after_node(
360 split_node: Option<NonNull<Node<T>>>,
363 // The split node is the new tail node of the first part and owns
364 // the head of the second part.
365 if let Some(mut split_node) = split_node {
366 let second_part_head;
367 let second_part_tail;
369 second_part_head = split_node.as_mut().next.take();
371 if let Some(mut head) = second_part_head {
373 head.as_mut().prev = None;
375 second_part_tail = self.tail;
377 second_part_tail = None;
380 let second_part = LinkedList {
381 head: second_part_head,
382 tail: second_part_tail,
387 // Fix the tail ptr of the first part
388 self.tail = Some(split_node);
393 mem::replace(self, LinkedList::new())
398 #[stable(feature = "rust1", since = "1.0.0")]
399 impl<T> Default for LinkedList<T> {
400 /// Creates an empty `LinkedList<T>`.
402 fn default() -> Self {
407 impl<T> LinkedList<T> {
408 /// Creates an empty `LinkedList`.
413 /// use std::collections::LinkedList;
415 /// let list: LinkedList<u32> = LinkedList::new();
418 #[rustc_const_stable(feature = "const_linked_list_new", since = "1.32.0")]
419 #[stable(feature = "rust1", since = "1.0.0")]
420 pub const fn new() -> Self {
421 LinkedList { head: None, tail: None, len: 0, marker: PhantomData }
424 /// Moves all elements from `other` to the end of the list.
426 /// This reuses all the nodes from `other` and moves them into `self`. After
427 /// this operation, `other` becomes empty.
429 /// This operation should compute in *O*(1) time and *O*(1) memory.
434 /// use std::collections::LinkedList;
436 /// let mut list1 = LinkedList::new();
437 /// list1.push_back('a');
439 /// let mut list2 = LinkedList::new();
440 /// list2.push_back('b');
441 /// list2.push_back('c');
443 /// list1.append(&mut list2);
445 /// let mut iter = list1.iter();
446 /// assert_eq!(iter.next(), Some(&'a'));
447 /// assert_eq!(iter.next(), Some(&'b'));
448 /// assert_eq!(iter.next(), Some(&'c'));
449 /// assert!(iter.next().is_none());
451 /// assert!(list2.is_empty());
453 #[stable(feature = "rust1", since = "1.0.0")]
454 pub fn append(&mut self, other: &mut Self) {
456 None => mem::swap(self, other),
458 // `as_mut` is okay here because we have exclusive access to the entirety
460 if let Some(mut other_head) = other.head.take() {
462 tail.as_mut().next = Some(other_head);
463 other_head.as_mut().prev = Some(tail);
466 self.tail = other.tail.take();
467 self.len += mem::replace(&mut other.len, 0);
473 /// Provides a forward iterator.
478 /// use std::collections::LinkedList;
480 /// let mut list: LinkedList<u32> = LinkedList::new();
482 /// list.push_back(0);
483 /// list.push_back(1);
484 /// list.push_back(2);
486 /// let mut iter = list.iter();
487 /// assert_eq!(iter.next(), Some(&0));
488 /// assert_eq!(iter.next(), Some(&1));
489 /// assert_eq!(iter.next(), Some(&2));
490 /// assert_eq!(iter.next(), None);
493 #[stable(feature = "rust1", since = "1.0.0")]
494 pub fn iter(&self) -> Iter<'_, T> {
495 Iter { head: self.head, tail: self.tail, len: self.len, marker: PhantomData }
498 /// Provides a forward iterator with mutable references.
503 /// use std::collections::LinkedList;
505 /// let mut list: LinkedList<u32> = LinkedList::new();
507 /// list.push_back(0);
508 /// list.push_back(1);
509 /// list.push_back(2);
511 /// for element in list.iter_mut() {
515 /// let mut iter = list.iter();
516 /// assert_eq!(iter.next(), Some(&10));
517 /// assert_eq!(iter.next(), Some(&11));
518 /// assert_eq!(iter.next(), Some(&12));
519 /// assert_eq!(iter.next(), None);
522 #[stable(feature = "rust1", since = "1.0.0")]
523 pub fn iter_mut(&mut self) -> IterMut<'_, T> {
524 IterMut { head: self.head, tail: self.tail, len: self.len, marker: PhantomData }
527 /// Provides a cursor at the front element.
529 /// The cursor is pointing to the "ghost" non-element if the list is empty.
531 #[unstable(feature = "linked_list_cursors", issue = "58533")]
532 pub fn cursor_front(&self) -> Cursor<'_, T> {
533 Cursor { index: 0, current: self.head, list: self }
536 /// Provides a cursor with editing operations at the front element.
538 /// The cursor is pointing to the "ghost" non-element if the list is empty.
540 #[unstable(feature = "linked_list_cursors", issue = "58533")]
541 pub fn cursor_front_mut(&mut self) -> CursorMut<'_, T> {
542 CursorMut { index: 0, current: self.head, list: self }
545 /// Provides a cursor at the back element.
547 /// The cursor is pointing to the "ghost" non-element if the list is empty.
549 #[unstable(feature = "linked_list_cursors", issue = "58533")]
550 pub fn cursor_back(&self) -> Cursor<'_, T> {
551 Cursor { index: self.len.checked_sub(1).unwrap_or(0), current: self.tail, list: self }
554 /// Provides a cursor with editing operations at the back element.
556 /// The cursor is pointing to the "ghost" non-element if the list is empty.
558 #[unstable(feature = "linked_list_cursors", issue = "58533")]
559 pub fn cursor_back_mut(&mut self) -> CursorMut<'_, T> {
560 CursorMut { index: self.len.checked_sub(1).unwrap_or(0), current: self.tail, list: self }
563 /// Returns `true` if the `LinkedList` is empty.
565 /// This operation should compute in *O*(1) time.
570 /// use std::collections::LinkedList;
572 /// let mut dl = LinkedList::new();
573 /// assert!(dl.is_empty());
575 /// dl.push_front("foo");
576 /// assert!(!dl.is_empty());
579 #[stable(feature = "rust1", since = "1.0.0")]
580 pub fn is_empty(&self) -> bool {
584 /// Returns the length of the `LinkedList`.
586 /// This operation should compute in *O*(1) time.
591 /// use std::collections::LinkedList;
593 /// let mut dl = LinkedList::new();
595 /// dl.push_front(2);
596 /// assert_eq!(dl.len(), 1);
598 /// dl.push_front(1);
599 /// assert_eq!(dl.len(), 2);
602 /// assert_eq!(dl.len(), 3);
605 #[stable(feature = "rust1", since = "1.0.0")]
606 pub fn len(&self) -> usize {
610 /// Removes all elements from the `LinkedList`.
612 /// This operation should compute in *O*(*n*) time.
617 /// use std::collections::LinkedList;
619 /// let mut dl = LinkedList::new();
621 /// dl.push_front(2);
622 /// dl.push_front(1);
623 /// assert_eq!(dl.len(), 2);
624 /// assert_eq!(dl.front(), Some(&1));
627 /// assert_eq!(dl.len(), 0);
628 /// assert_eq!(dl.front(), None);
631 #[stable(feature = "rust1", since = "1.0.0")]
632 pub fn clear(&mut self) {
636 /// Returns `true` if the `LinkedList` contains an element equal to the
639 /// This operation should compute in *O*(*n*) time.
644 /// use std::collections::LinkedList;
646 /// let mut list: LinkedList<u32> = LinkedList::new();
648 /// list.push_back(0);
649 /// list.push_back(1);
650 /// list.push_back(2);
652 /// assert_eq!(list.contains(&0), true);
653 /// assert_eq!(list.contains(&10), false);
655 #[stable(feature = "linked_list_contains", since = "1.12.0")]
656 pub fn contains(&self, x: &T) -> bool
660 self.iter().any(|e| e == x)
663 /// Provides a reference to the front element, or `None` if the list is
666 /// This operation should compute in *O*(1) time.
671 /// use std::collections::LinkedList;
673 /// let mut dl = LinkedList::new();
674 /// assert_eq!(dl.front(), None);
676 /// dl.push_front(1);
677 /// assert_eq!(dl.front(), Some(&1));
680 #[stable(feature = "rust1", since = "1.0.0")]
681 pub fn front(&self) -> Option<&T> {
682 unsafe { self.head.as_ref().map(|node| &node.as_ref().element) }
685 /// Provides a mutable reference to the front element, or `None` if the list
688 /// This operation should compute in *O*(1) time.
693 /// use std::collections::LinkedList;
695 /// let mut dl = LinkedList::new();
696 /// assert_eq!(dl.front(), None);
698 /// dl.push_front(1);
699 /// assert_eq!(dl.front(), Some(&1));
701 /// match dl.front_mut() {
703 /// Some(x) => *x = 5,
705 /// assert_eq!(dl.front(), Some(&5));
708 #[stable(feature = "rust1", since = "1.0.0")]
709 pub fn front_mut(&mut self) -> Option<&mut T> {
710 unsafe { self.head.as_mut().map(|node| &mut node.as_mut().element) }
713 /// Provides a reference to the back element, or `None` if the list is
716 /// This operation should compute in *O*(1) time.
721 /// use std::collections::LinkedList;
723 /// let mut dl = LinkedList::new();
724 /// assert_eq!(dl.back(), None);
727 /// assert_eq!(dl.back(), Some(&1));
730 #[stable(feature = "rust1", since = "1.0.0")]
731 pub fn back(&self) -> Option<&T> {
732 unsafe { self.tail.as_ref().map(|node| &node.as_ref().element) }
735 /// Provides a mutable reference to the back element, or `None` if the list
738 /// This operation should compute in *O*(1) time.
743 /// use std::collections::LinkedList;
745 /// let mut dl = LinkedList::new();
746 /// assert_eq!(dl.back(), None);
749 /// assert_eq!(dl.back(), Some(&1));
751 /// match dl.back_mut() {
753 /// Some(x) => *x = 5,
755 /// assert_eq!(dl.back(), Some(&5));
758 #[stable(feature = "rust1", since = "1.0.0")]
759 pub fn back_mut(&mut self) -> Option<&mut T> {
760 unsafe { self.tail.as_mut().map(|node| &mut node.as_mut().element) }
763 /// Adds an element first in the list.
765 /// This operation should compute in *O*(1) time.
770 /// use std::collections::LinkedList;
772 /// let mut dl = LinkedList::new();
774 /// dl.push_front(2);
775 /// assert_eq!(dl.front().unwrap(), &2);
777 /// dl.push_front(1);
778 /// assert_eq!(dl.front().unwrap(), &1);
780 #[stable(feature = "rust1", since = "1.0.0")]
781 pub fn push_front(&mut self, elt: T) {
782 self.push_front_node(box Node::new(elt));
785 /// Removes the first element and returns it, or `None` if the list is
788 /// This operation should compute in *O*(1) time.
793 /// use std::collections::LinkedList;
795 /// let mut d = LinkedList::new();
796 /// assert_eq!(d.pop_front(), None);
800 /// assert_eq!(d.pop_front(), Some(3));
801 /// assert_eq!(d.pop_front(), Some(1));
802 /// assert_eq!(d.pop_front(), None);
804 #[stable(feature = "rust1", since = "1.0.0")]
805 pub fn pop_front(&mut self) -> Option<T> {
806 self.pop_front_node().map(Node::into_element)
809 /// Appends an element to the back of a list.
811 /// This operation should compute in *O*(1) time.
816 /// use std::collections::LinkedList;
818 /// let mut d = LinkedList::new();
821 /// assert_eq!(3, *d.back().unwrap());
823 #[stable(feature = "rust1", since = "1.0.0")]
824 pub fn push_back(&mut self, elt: T) {
825 self.push_back_node(box Node::new(elt));
828 /// Removes the last element from a list and returns it, or `None` if
831 /// This operation should compute in *O*(1) time.
836 /// use std::collections::LinkedList;
838 /// let mut d = LinkedList::new();
839 /// assert_eq!(d.pop_back(), None);
842 /// assert_eq!(d.pop_back(), Some(3));
844 #[stable(feature = "rust1", since = "1.0.0")]
845 pub fn pop_back(&mut self) -> Option<T> {
846 self.pop_back_node().map(Node::into_element)
849 /// Splits the list into two at the given index. Returns everything after the given index,
850 /// including the index.
852 /// This operation should compute in *O*(*n*) time.
856 /// Panics if `at > len`.
861 /// use std::collections::LinkedList;
863 /// let mut d = LinkedList::new();
869 /// let mut split = d.split_off(2);
871 /// assert_eq!(split.pop_front(), Some(1));
872 /// assert_eq!(split.pop_front(), None);
874 #[stable(feature = "rust1", since = "1.0.0")]
875 pub fn split_off(&mut self, at: usize) -> LinkedList<T> {
876 let len = self.len();
877 assert!(at <= len, "Cannot split off at a nonexistent index");
879 return mem::take(self);
880 } else if at == len {
884 // Below, we iterate towards the `i-1`th node, either from the start or the end,
885 // depending on which would be faster.
886 let split_node = if at - 1 <= len - 1 - (at - 1) {
887 let mut iter = self.iter_mut();
888 // instead of skipping using .skip() (which creates a new struct),
889 // we skip manually so we can access the head field without
890 // depending on implementation details of Skip
896 // better off starting from the end
897 let mut iter = self.iter_mut();
898 for _ in 0..len - 1 - (at - 1) {
903 unsafe { self.split_off_after_node(split_node, at) }
906 /// Removes the element at the given index and returns it.
908 /// This operation should compute in *O*(*n*) time.
911 /// Panics if at >= len
916 /// #![feature(linked_list_remove)]
917 /// use std::collections::LinkedList;
919 /// let mut d = LinkedList::new();
925 /// assert_eq!(d.remove(1), 2);
926 /// assert_eq!(d.remove(0), 3);
927 /// assert_eq!(d.remove(0), 1);
929 #[unstable(feature = "linked_list_remove", issue = "69210")]
930 pub fn remove(&mut self, at: usize) -> T {
931 let len = self.len();
932 assert!(at < len, "Cannot remove at an index outside of the list bounds");
934 // Below, we iterate towards the node at the given index, either from
935 // the start or the end, depending on which would be faster.
936 let offset_from_end = len - at - 1;
937 if at <= offset_from_end {
938 let mut cursor = self.cursor_front_mut();
942 cursor.remove_current().unwrap()
944 let mut cursor = self.cursor_back_mut();
945 for _ in 0..offset_from_end {
948 cursor.remove_current().unwrap()
952 /// Creates an iterator which uses a closure to determine if an element should be removed.
954 /// If the closure returns true, then the element is removed and yielded.
955 /// If the closure returns false, the element will remain in the list and will not be yielded
958 /// Note that `drain_filter` lets you mutate every element in the filter closure, regardless of
959 /// whether you choose to keep or remove it.
963 /// Splitting a list into evens and odds, reusing the original list:
966 /// #![feature(drain_filter)]
967 /// use std::collections::LinkedList;
969 /// let mut numbers: LinkedList<u32> = LinkedList::new();
970 /// numbers.extend(&[1, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15]);
972 /// let evens = numbers.drain_filter(|x| *x % 2 == 0).collect::<LinkedList<_>>();
973 /// let odds = numbers;
975 /// assert_eq!(evens.into_iter().collect::<Vec<_>>(), vec![2, 4, 6, 8, 14]);
976 /// assert_eq!(odds.into_iter().collect::<Vec<_>>(), vec![1, 3, 5, 9, 11, 13, 15]);
978 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
979 pub fn drain_filter<F>(&mut self, filter: F) -> DrainFilter<'_, T, F>
981 F: FnMut(&mut T) -> bool,
983 // avoid borrow issues.
985 let old_len = self.len;
987 DrainFilter { list: self, it, pred: filter, idx: 0, old_len }
991 #[stable(feature = "rust1", since = "1.0.0")]
992 unsafe impl<#[may_dangle] T> Drop for LinkedList<T> {
994 struct DropGuard<'a, T>(&'a mut LinkedList<T>);
996 impl<'a, T> Drop for DropGuard<'a, T> {
998 // Continue the same loop we do below. This only runs when a destructor has
999 // panicked. If another one panics this will abort.
1000 while self.0.pop_front_node().is_some() {}
1004 while let Some(node) = self.pop_front_node() {
1005 let guard = DropGuard(self);
1012 #[stable(feature = "rust1", since = "1.0.0")]
1013 impl<'a, T> Iterator for Iter<'a, T> {
1017 fn next(&mut self) -> Option<&'a T> {
1021 self.head.map(|node| unsafe {
1022 // Need an unbound lifetime to get 'a
1023 let node = &*node.as_ptr();
1025 self.head = node.next;
1032 fn size_hint(&self) -> (usize, Option<usize>) {
1033 (self.len, Some(self.len))
1037 fn last(mut self) -> Option<&'a T> {
1042 #[stable(feature = "rust1", since = "1.0.0")]
1043 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
1045 fn next_back(&mut self) -> Option<&'a T> {
1049 self.tail.map(|node| unsafe {
1050 // Need an unbound lifetime to get 'a
1051 let node = &*node.as_ptr();
1053 self.tail = node.prev;
1060 #[stable(feature = "rust1", since = "1.0.0")]
1061 impl<T> ExactSizeIterator for Iter<'_, T> {}
1063 #[stable(feature = "fused", since = "1.26.0")]
1064 impl<T> FusedIterator for Iter<'_, T> {}
1066 #[stable(feature = "rust1", since = "1.0.0")]
1067 impl<'a, T> Iterator for IterMut<'a, T> {
1068 type Item = &'a mut T;
1071 fn next(&mut self) -> Option<&'a mut T> {
1075 self.head.map(|node| unsafe {
1076 // Need an unbound lifetime to get 'a
1077 let node = &mut *node.as_ptr();
1079 self.head = node.next;
1086 fn size_hint(&self) -> (usize, Option<usize>) {
1087 (self.len, Some(self.len))
1091 fn last(mut self) -> Option<&'a mut T> {
1096 #[stable(feature = "rust1", since = "1.0.0")]
1097 impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
1099 fn next_back(&mut self) -> Option<&'a mut T> {
1103 self.tail.map(|node| unsafe {
1104 // Need an unbound lifetime to get 'a
1105 let node = &mut *node.as_ptr();
1107 self.tail = node.prev;
1114 #[stable(feature = "rust1", since = "1.0.0")]
1115 impl<T> ExactSizeIterator for IterMut<'_, T> {}
1117 #[stable(feature = "fused", since = "1.26.0")]
1118 impl<T> FusedIterator for IterMut<'_, T> {}
1120 /// A cursor over a `LinkedList`.
1122 /// A `Cursor` is like an iterator, except that it can freely seek back-and-forth.
1124 /// Cursors always rest between two elements in the list, and index in a logically circular way.
1125 /// To accommodate this, there is a "ghost" non-element that yields `None` between the head and
1126 /// tail of the list.
1128 /// When created, cursors start at the front of the list, or the "ghost" non-element if the list is empty.
1129 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1130 pub struct Cursor<'a, T: 'a> {
1132 current: Option<NonNull<Node<T>>>,
1133 list: &'a LinkedList<T>,
1136 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1137 impl<T> Clone for Cursor<'_, T> {
1138 fn clone(&self) -> Self {
1139 let Cursor { index, current, list } = *self;
1140 Cursor { index, current, list }
1144 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1145 impl<T: fmt::Debug> fmt::Debug for Cursor<'_, T> {
1146 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1147 f.debug_tuple("Cursor").field(&self.list).field(&self.index()).finish()
1151 /// A cursor over a `LinkedList` with editing operations.
1153 /// A `Cursor` is like an iterator, except that it can freely seek back-and-forth, and can
1154 /// safely mutate the list during iteration. This is because the lifetime of its yielded
1155 /// references is tied to its own lifetime, instead of just the underlying list. This means
1156 /// cursors cannot yield multiple elements at once.
1158 /// Cursors always rest between two elements in the list, and index in a logically circular way.
1159 /// To accommodate this, there is a "ghost" non-element that yields `None` between the head and
1160 /// tail of the list.
1161 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1162 pub struct CursorMut<'a, T: 'a> {
1164 current: Option<NonNull<Node<T>>>,
1165 list: &'a mut LinkedList<T>,
1168 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1169 impl<T: fmt::Debug> fmt::Debug for CursorMut<'_, T> {
1170 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1171 f.debug_tuple("CursorMut").field(&self.list).field(&self.index()).finish()
1175 impl<'a, T> Cursor<'a, T> {
1176 /// Returns the cursor position index within the `LinkedList`.
1178 /// This returns `None` if the cursor is currently pointing to the
1179 /// "ghost" non-element.
1180 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1181 pub fn index(&self) -> Option<usize> {
1182 let _ = self.current?;
1186 /// Moves the cursor to the next element of the `LinkedList`.
1188 /// If the cursor is pointing to the "ghost" non-element then this will move it to
1189 /// the first element of the `LinkedList`. If it is pointing to the last
1190 /// element of the `LinkedList` then this will move it to the "ghost" non-element.
1191 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1192 pub fn move_next(&mut self) {
1193 match self.current.take() {
1194 // We had no current element; the cursor was sitting at the start position
1195 // Next element should be the head of the list
1197 self.current = self.list.head;
1200 // We had a previous element, so let's go to its next
1201 Some(current) => unsafe {
1202 self.current = current.as_ref().next;
1208 /// Moves the cursor to the previous element of the `LinkedList`.
1210 /// If the cursor is pointing to the "ghost" non-element then this will move it to
1211 /// the last element of the `LinkedList`. If it is pointing to the first
1212 /// element of the `LinkedList` then this will move it to the "ghost" non-element.
1213 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1214 pub fn move_prev(&mut self) {
1215 match self.current.take() {
1216 // No current. We're at the start of the list. Yield None and jump to the end.
1218 self.current = self.list.tail;
1219 self.index = self.list.len().checked_sub(1).unwrap_or(0);
1221 // Have a prev. Yield it and go to the previous element.
1222 Some(current) => unsafe {
1223 self.current = current.as_ref().prev;
1224 self.index = self.index.checked_sub(1).unwrap_or_else(|| self.list.len());
1229 /// Returns a reference to the element that the cursor is currently
1232 /// This returns `None` if the cursor is currently pointing to the
1233 /// "ghost" non-element.
1234 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1235 pub fn current(&self) -> Option<&'a T> {
1236 unsafe { self.current.map(|current| &(*current.as_ptr()).element) }
1239 /// Returns a reference to the next element.
1241 /// If the cursor is pointing to the "ghost" non-element then this returns
1242 /// the first element of the `LinkedList`. If it is pointing to the last
1243 /// element of the `LinkedList` then this returns `None`.
1244 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1245 pub fn peek_next(&self) -> Option<&'a T> {
1247 let next = match self.current {
1248 None => self.list.head,
1249 Some(current) => current.as_ref().next,
1251 next.map(|next| &(*next.as_ptr()).element)
1255 /// Returns a reference to the previous element.
1257 /// If the cursor is pointing to the "ghost" non-element then this returns
1258 /// the last element of the `LinkedList`. If it is pointing to the first
1259 /// element of the `LinkedList` then this returns `None`.
1260 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1261 pub fn peek_prev(&self) -> Option<&'a T> {
1263 let prev = match self.current {
1264 None => self.list.tail,
1265 Some(current) => current.as_ref().prev,
1267 prev.map(|prev| &(*prev.as_ptr()).element)
1271 /// Provides a reference to the front element of the cursor's parent list,
1272 /// or None if the list is empty.
1273 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1274 pub fn front(&self) -> Option<&'a T> {
1278 /// Provides a reference to the back element of the cursor's parent list,
1279 /// or None if the list is empty.
1280 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1281 pub fn back(&self) -> Option<&'a T> {
1286 impl<'a, T> CursorMut<'a, T> {
1287 /// Returns the cursor position index within the `LinkedList`.
1289 /// This returns `None` if the cursor is currently pointing to the
1290 /// "ghost" non-element.
1291 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1292 pub fn index(&self) -> Option<usize> {
1293 let _ = self.current?;
1297 /// Moves the cursor to the next element of the `LinkedList`.
1299 /// If the cursor is pointing to the "ghost" non-element then this will move it to
1300 /// the first element of the `LinkedList`. If it is pointing to the last
1301 /// element of the `LinkedList` then this will move it to the "ghost" non-element.
1302 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1303 pub fn move_next(&mut self) {
1304 match self.current.take() {
1305 // We had no current element; the cursor was sitting at the start position
1306 // Next element should be the head of the list
1308 self.current = self.list.head;
1311 // We had a previous element, so let's go to its next
1312 Some(current) => unsafe {
1313 self.current = current.as_ref().next;
1319 /// Moves the cursor to the previous element of the `LinkedList`.
1321 /// If the cursor is pointing to the "ghost" non-element then this will move it to
1322 /// the last element of the `LinkedList`. If it is pointing to the first
1323 /// element of the `LinkedList` then this will move it to the "ghost" non-element.
1324 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1325 pub fn move_prev(&mut self) {
1326 match self.current.take() {
1327 // No current. We're at the start of the list. Yield None and jump to the end.
1329 self.current = self.list.tail;
1330 self.index = self.list.len().checked_sub(1).unwrap_or(0);
1332 // Have a prev. Yield it and go to the previous element.
1333 Some(current) => unsafe {
1334 self.current = current.as_ref().prev;
1335 self.index = self.index.checked_sub(1).unwrap_or_else(|| self.list.len());
1340 /// Returns a reference to the element that the cursor is currently
1343 /// This returns `None` if the cursor is currently pointing to the
1344 /// "ghost" non-element.
1345 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1346 pub fn current(&mut self) -> Option<&mut T> {
1347 unsafe { self.current.map(|current| &mut (*current.as_ptr()).element) }
1350 /// Returns a reference to the next element.
1352 /// If the cursor is pointing to the "ghost" non-element then this returns
1353 /// the first element of the `LinkedList`. If it is pointing to the last
1354 /// element of the `LinkedList` then this returns `None`.
1355 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1356 pub fn peek_next(&mut self) -> Option<&mut T> {
1358 let next = match self.current {
1359 None => self.list.head,
1360 Some(current) => current.as_ref().next,
1362 next.map(|next| &mut (*next.as_ptr()).element)
1366 /// Returns a reference to the previous element.
1368 /// If the cursor is pointing to the "ghost" non-element then this returns
1369 /// the last element of the `LinkedList`. If it is pointing to the first
1370 /// element of the `LinkedList` then this returns `None`.
1371 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1372 pub fn peek_prev(&mut self) -> Option<&mut T> {
1374 let prev = match self.current {
1375 None => self.list.tail,
1376 Some(current) => current.as_ref().prev,
1378 prev.map(|prev| &mut (*prev.as_ptr()).element)
1382 /// Returns a read-only cursor pointing to the current element.
1384 /// The lifetime of the returned `Cursor` is bound to that of the
1385 /// `CursorMut`, which means it cannot outlive the `CursorMut` and that the
1386 /// `CursorMut` is frozen for the lifetime of the `Cursor`.
1387 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1388 pub fn as_cursor(&self) -> Cursor<'_, T> {
1389 Cursor { list: self.list, current: self.current, index: self.index }
1393 // Now the list editing operations
1395 impl<'a, T> CursorMut<'a, T> {
1396 /// Inserts a new element into the `LinkedList` after the current one.
1398 /// If the cursor is pointing at the "ghost" non-element then the new element is
1399 /// inserted at the front of the `LinkedList`.
1400 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1401 pub fn insert_after(&mut self, item: T) {
1403 let spliced_node = Box::leak(Box::new(Node::new(item))).into();
1404 let node_next = match self.current {
1405 None => self.list.head,
1406 Some(node) => node.as_ref().next,
1408 self.list.splice_nodes(self.current, node_next, spliced_node, spliced_node, 1);
1409 if self.current.is_none() {
1410 // The "ghost" non-element's index has changed.
1411 self.index = self.list.len;
1416 /// Inserts a new element into the `LinkedList` before the current one.
1418 /// If the cursor is pointing at the "ghost" non-element then the new element is
1419 /// inserted at the end of the `LinkedList`.
1420 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1421 pub fn insert_before(&mut self, item: T) {
1423 let spliced_node = Box::leak(Box::new(Node::new(item))).into();
1424 let node_prev = match self.current {
1425 None => self.list.tail,
1426 Some(node) => node.as_ref().prev,
1428 self.list.splice_nodes(node_prev, self.current, spliced_node, spliced_node, 1);
1433 /// Removes the current element from the `LinkedList`.
1435 /// The element that was removed is returned, and the cursor is
1436 /// moved to point to the next element in the `LinkedList`.
1438 /// If the cursor is currently pointing to the "ghost" non-element then no element
1439 /// is removed and `None` is returned.
1440 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1441 pub fn remove_current(&mut self) -> Option<T> {
1442 let unlinked_node = self.current?;
1444 self.current = unlinked_node.as_ref().next;
1445 self.list.unlink_node(unlinked_node);
1446 let unlinked_node = Box::from_raw(unlinked_node.as_ptr());
1447 Some(unlinked_node.element)
1451 /// Removes the current element from the `LinkedList` without deallocating the list node.
1453 /// The node that was removed is returned as a new `LinkedList` containing only this node.
1454 /// The cursor is moved to point to the next element in the current `LinkedList`.
1456 /// If the cursor is currently pointing to the "ghost" non-element then no element
1457 /// is removed and `None` is returned.
1458 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1459 pub fn remove_current_as_list(&mut self) -> Option<LinkedList<T>> {
1460 let mut unlinked_node = self.current?;
1462 self.current = unlinked_node.as_ref().next;
1463 self.list.unlink_node(unlinked_node);
1465 unlinked_node.as_mut().prev = None;
1466 unlinked_node.as_mut().next = None;
1468 head: Some(unlinked_node),
1469 tail: Some(unlinked_node),
1471 marker: PhantomData,
1476 /// Inserts the elements from the given `LinkedList` after the current one.
1478 /// If the cursor is pointing at the "ghost" non-element then the new elements are
1479 /// inserted at the start of the `LinkedList`.
1480 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1481 pub fn splice_after(&mut self, list: LinkedList<T>) {
1483 let (splice_head, splice_tail, splice_len) = match list.detach_all_nodes() {
1484 Some(parts) => parts,
1487 let node_next = match self.current {
1488 None => self.list.head,
1489 Some(node) => node.as_ref().next,
1491 self.list.splice_nodes(self.current, node_next, splice_head, splice_tail, splice_len);
1492 if self.current.is_none() {
1493 // The "ghost" non-element's index has changed.
1494 self.index = self.list.len;
1499 /// Inserts the elements from the given `LinkedList` before the current one.
1501 /// If the cursor is pointing at the "ghost" non-element then the new elements are
1502 /// inserted at the end of the `LinkedList`.
1503 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1504 pub fn splice_before(&mut self, list: LinkedList<T>) {
1506 let (splice_head, splice_tail, splice_len) = match list.detach_all_nodes() {
1507 Some(parts) => parts,
1510 let node_prev = match self.current {
1511 None => self.list.tail,
1512 Some(node) => node.as_ref().prev,
1514 self.list.splice_nodes(node_prev, self.current, splice_head, splice_tail, splice_len);
1515 self.index += splice_len;
1519 /// Splits the list into two after the current element. This will return a
1520 /// new list consisting of everything after the cursor, with the original
1521 /// list retaining everything before.
1523 /// If the cursor is pointing at the "ghost" non-element then the entire contents
1524 /// of the `LinkedList` are moved.
1525 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1526 pub fn split_after(&mut self) -> LinkedList<T> {
1527 let split_off_idx = if self.index == self.list.len { 0 } else { self.index + 1 };
1528 if self.index == self.list.len {
1529 // The "ghost" non-element's index has changed to 0.
1532 unsafe { self.list.split_off_after_node(self.current, split_off_idx) }
1535 /// Splits the list into two before the current element. This will return a
1536 /// new list consisting of everything before the cursor, with the original
1537 /// list retaining everything after.
1539 /// If the cursor is pointing at the "ghost" non-element then the entire contents
1540 /// of the `LinkedList` are moved.
1541 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1542 pub fn split_before(&mut self) -> LinkedList<T> {
1543 let split_off_idx = self.index;
1545 unsafe { self.list.split_off_before_node(self.current, split_off_idx) }
1548 /// Appends an element to the front 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 // `push_front` continues to point to "ghost" when it addes a node to mimic
1553 // the behavior of `insert_before` on an empty list.
1554 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1555 pub fn push_front(&mut self, elt: T) {
1556 // Safety: We know that `push_front` does not change the position in
1557 // memory of other nodes. This ensures that `self.current` remains
1559 self.list.push_front(elt);
1563 /// Appends an element to the back of the cursor's parent list. The node
1564 /// that the cursor points to is unchanged, even if it is the "ghost" node.
1566 /// This operation should compute in O(1) time.
1567 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1568 pub fn push_back(&mut self, elt: T) {
1569 // Safety: We know that `push_back` does not change the position in
1570 // memory of other nodes. This ensures that `self.current` remains
1572 self.list.push_back(elt);
1573 if self.current().is_none() {
1574 // The index of "ghost" is the length of the list, so we just need
1575 // to increment self.index to reflect the new length of the list.
1580 /// Removes the first element from the cursor's parent list and returns it,
1581 /// or None if the list is empty. The element the cursor points to remains
1582 /// unchanged, unless it was pointing to the front element. In that case, it
1583 /// points to the new front element.
1585 /// This operation should compute in O(1) time.
1586 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1587 pub fn pop_front(&mut self) -> Option<T> {
1588 // We can't check if current is empty, we must check the list directly.
1589 // It is possible for `self.current == None` and the list to be
1591 if self.list.is_empty() {
1594 // We can't point to the node that we pop. Copying the behavior of
1595 // `remove_current`, we move on the the next node in the sequence.
1596 // If the list is of length 1 then we end pointing to the "ghost"
1597 // node at index 0, which is expected.
1598 if self.list.head == self.current {
1603 self.list.pop_front()
1607 /// Removes the last element from the cursor's parent list and returns it,
1608 /// or None if the list is empty. The element the cursor points to remains
1609 /// unchanged, unless it was pointing to the back element. In that case, it
1610 /// points to the "ghost" element.
1612 /// This operation should compute in O(1) time.
1613 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1614 pub fn pop_back(&mut self) -> Option<T> {
1615 if self.list.is_empty() {
1618 if self.list.tail == self.current {
1619 // The index now reflects the length of the list. It was the
1620 // length of the list minus 1, but now the list is 1 smaller. No
1621 // change is needed for `index`.
1622 self.current = None;
1623 } else if self.current.is_none() {
1624 self.index = self.list.len - 1;
1626 self.list.pop_back()
1630 /// Provides a reference to the front element of the cursor's parent list,
1631 /// or None if the list is empty.
1632 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1633 pub fn front(&self) -> Option<&T> {
1637 /// Provides a mutable reference to the front element of the cursor's
1638 /// parent list, or None if the list is empty.
1639 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1640 pub fn front_mut(&mut self) -> Option<&mut T> {
1641 self.list.front_mut()
1644 /// Provides a reference to the back element of the cursor's parent list,
1645 /// or None if the list is empty.
1646 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1647 pub fn back(&self) -> Option<&T> {
1651 /// Provides a mutable reference to back element of the cursor's parent
1652 /// list, or `None` if the list is empty.
1655 /// Building and mutating a list with a cursor, then getting the back element:
1657 /// #![feature(linked_list_cursors)]
1658 /// use std::collections::LinkedList;
1659 /// let mut dl = LinkedList::new();
1660 /// dl.push_front(3);
1661 /// dl.push_front(2);
1662 /// dl.push_front(1);
1663 /// let mut cursor = dl.cursor_front_mut();
1664 /// *cursor.current().unwrap() = 99;
1665 /// *cursor.back_mut().unwrap() = 0;
1666 /// let mut contents = dl.into_iter();
1667 /// assert_eq!(contents.next(), Some(99));
1668 /// assert_eq!(contents.next(), Some(2));
1669 /// assert_eq!(contents.next(), Some(0));
1670 /// assert_eq!(contents.next(), None);
1672 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1673 pub fn back_mut(&mut self) -> Option<&mut T> {
1674 self.list.back_mut()
1678 /// An iterator produced by calling `drain_filter` on LinkedList.
1679 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
1680 pub struct DrainFilter<'a, T: 'a, F: 'a>
1682 F: FnMut(&mut T) -> bool,
1684 list: &'a mut LinkedList<T>,
1685 it: Option<NonNull<Node<T>>>,
1691 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
1692 impl<T, F> Iterator for DrainFilter<'_, T, F>
1694 F: FnMut(&mut T) -> bool,
1698 fn next(&mut self) -> Option<T> {
1699 while let Some(mut node) = self.it {
1701 self.it = node.as_ref().next;
1704 if (self.pred)(&mut node.as_mut().element) {
1705 // `unlink_node` is okay with aliasing `element` references.
1706 self.list.unlink_node(node);
1707 return Some(Box::from_raw(node.as_ptr()).element);
1715 fn size_hint(&self) -> (usize, Option<usize>) {
1716 (0, Some(self.old_len - self.idx))
1720 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
1721 impl<T, F> Drop for DrainFilter<'_, T, F>
1723 F: FnMut(&mut T) -> bool,
1725 fn drop(&mut self) {
1726 struct DropGuard<'r, 'a, T, F>(&'r mut DrainFilter<'a, T, F>)
1728 F: FnMut(&mut T) -> bool;
1730 impl<'r, 'a, T, F> Drop for DropGuard<'r, 'a, T, F>
1732 F: FnMut(&mut T) -> bool,
1734 fn drop(&mut self) {
1735 self.0.for_each(drop);
1739 while let Some(item) = self.next() {
1740 let guard = DropGuard(self);
1747 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
1748 impl<T: fmt::Debug, F> fmt::Debug for DrainFilter<'_, T, F>
1750 F: FnMut(&mut T) -> bool,
1752 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1753 f.debug_tuple("DrainFilter").field(&self.list).finish()
1757 #[stable(feature = "rust1", since = "1.0.0")]
1758 impl<T> Iterator for IntoIter<T> {
1762 fn next(&mut self) -> Option<T> {
1763 self.list.pop_front()
1767 fn size_hint(&self) -> (usize, Option<usize>) {
1768 (self.list.len, Some(self.list.len))
1772 #[stable(feature = "rust1", since = "1.0.0")]
1773 impl<T> DoubleEndedIterator for IntoIter<T> {
1775 fn next_back(&mut self) -> Option<T> {
1776 self.list.pop_back()
1780 #[stable(feature = "rust1", since = "1.0.0")]
1781 impl<T> ExactSizeIterator for IntoIter<T> {}
1783 #[stable(feature = "fused", since = "1.26.0")]
1784 impl<T> FusedIterator for IntoIter<T> {}
1786 #[stable(feature = "rust1", since = "1.0.0")]
1787 impl<T> FromIterator<T> for LinkedList<T> {
1788 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
1789 let mut list = Self::new();
1795 #[stable(feature = "rust1", since = "1.0.0")]
1796 impl<T> IntoIterator for LinkedList<T> {
1798 type IntoIter = IntoIter<T>;
1800 /// Consumes the list into an iterator yielding elements by value.
1802 fn into_iter(self) -> IntoIter<T> {
1803 IntoIter { list: self }
1807 #[stable(feature = "rust1", since = "1.0.0")]
1808 impl<'a, T> IntoIterator for &'a LinkedList<T> {
1810 type IntoIter = Iter<'a, T>;
1812 fn into_iter(self) -> Iter<'a, T> {
1817 #[stable(feature = "rust1", since = "1.0.0")]
1818 impl<'a, T> IntoIterator for &'a mut LinkedList<T> {
1819 type Item = &'a mut T;
1820 type IntoIter = IterMut<'a, T>;
1822 fn into_iter(self) -> IterMut<'a, T> {
1827 #[stable(feature = "rust1", since = "1.0.0")]
1828 impl<T> Extend<T> for LinkedList<T> {
1829 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1830 <Self as SpecExtend<I>>::spec_extend(self, iter);
1834 fn extend_one(&mut self, elem: T) {
1835 self.push_back(elem);
1839 impl<I: IntoIterator> SpecExtend<I> for LinkedList<I::Item> {
1840 default fn spec_extend(&mut self, iter: I) {
1841 iter.into_iter().for_each(move |elt| self.push_back(elt));
1845 impl<T> SpecExtend<LinkedList<T>> for LinkedList<T> {
1846 fn spec_extend(&mut self, ref mut other: LinkedList<T>) {
1851 #[stable(feature = "extend_ref", since = "1.2.0")]
1852 impl<'a, T: 'a + Copy> Extend<&'a T> for LinkedList<T> {
1853 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
1854 self.extend(iter.into_iter().cloned());
1858 fn extend_one(&mut self, &elem: &'a T) {
1859 self.push_back(elem);
1863 #[stable(feature = "rust1", since = "1.0.0")]
1864 impl<T: PartialEq> PartialEq for LinkedList<T> {
1865 fn eq(&self, other: &Self) -> bool {
1866 self.len() == other.len() && self.iter().eq(other)
1869 fn ne(&self, other: &Self) -> bool {
1870 self.len() != other.len() || self.iter().ne(other)
1874 #[stable(feature = "rust1", since = "1.0.0")]
1875 impl<T: Eq> Eq for LinkedList<T> {}
1877 #[stable(feature = "rust1", since = "1.0.0")]
1878 impl<T: PartialOrd> PartialOrd for LinkedList<T> {
1879 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1880 self.iter().partial_cmp(other)
1884 #[stable(feature = "rust1", since = "1.0.0")]
1885 impl<T: Ord> Ord for LinkedList<T> {
1887 fn cmp(&self, other: &Self) -> Ordering {
1888 self.iter().cmp(other)
1892 #[stable(feature = "rust1", since = "1.0.0")]
1893 impl<T: Clone> Clone for LinkedList<T> {
1894 fn clone(&self) -> Self {
1895 self.iter().cloned().collect()
1898 fn clone_from(&mut self, other: &Self) {
1899 let mut iter_other = other.iter();
1900 if self.len() > other.len() {
1901 self.split_off(other.len());
1903 for (elem, elem_other) in self.iter_mut().zip(&mut iter_other) {
1904 elem.clone_from(elem_other);
1906 if !iter_other.is_empty() {
1907 self.extend(iter_other.cloned());
1912 #[stable(feature = "rust1", since = "1.0.0")]
1913 impl<T: fmt::Debug> fmt::Debug for LinkedList<T> {
1914 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1915 f.debug_list().entries(self).finish()
1919 #[stable(feature = "rust1", since = "1.0.0")]
1920 impl<T: Hash> Hash for LinkedList<T> {
1921 fn hash<H: Hasher>(&self, state: &mut H) {
1922 self.len().hash(state);
1929 #[stable(feature = "std_collections_from_array", since = "1.56.0")]
1930 impl<T, const N: usize> From<[T; N]> for LinkedList<T> {
1932 /// use std::collections::LinkedList;
1934 /// let list1 = LinkedList::from([1, 2, 3, 4]);
1935 /// let list2: LinkedList<_> = [1, 2, 3, 4].into();
1936 /// assert_eq!(list1, list2);
1938 fn from(arr: [T; N]) -> Self {
1939 core::array::IntoIter::new(arr).collect()
1943 // Ensure that `LinkedList` and its read-only iterators are covariant in their type parameters.
1945 fn assert_covariance() {
1946 fn a<'a>(x: LinkedList<&'static str>) -> LinkedList<&'a str> {
1949 fn b<'i, 'a>(x: Iter<'i, &'static str>) -> Iter<'i, &'a str> {
1952 fn c<'a>(x: IntoIter<&'static str>) -> IntoIter<&'a str> {
1957 #[stable(feature = "rust1", since = "1.0.0")]
1958 unsafe impl<T: Send> Send for LinkedList<T> {}
1960 #[stable(feature = "rust1", since = "1.0.0")]
1961 unsafe impl<T: Sync> Sync for LinkedList<T> {}
1963 #[stable(feature = "rust1", since = "1.0.0")]
1964 unsafe impl<T: Sync> Send for Iter<'_, T> {}
1966 #[stable(feature = "rust1", since = "1.0.0")]
1967 unsafe impl<T: Sync> Sync for Iter<'_, T> {}
1969 #[stable(feature = "rust1", since = "1.0.0")]
1970 unsafe impl<T: Send> Send for IterMut<'_, T> {}
1972 #[stable(feature = "rust1", since = "1.0.0")]
1973 unsafe impl<T: Sync> Sync for IterMut<'_, T> {}
1975 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1976 unsafe impl<T: Sync> Send for Cursor<'_, T> {}
1978 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1979 unsafe impl<T: Sync> Sync for Cursor<'_, T> {}
1981 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1982 unsafe impl<T: Send> Send for CursorMut<'_, T> {}
1984 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1985 unsafe impl<T: Sync> Sync for CursorMut<'_, T> {}