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`]: ../../vec/struct.Vec.html
11 //! [`VecDeque`]: ../vec_deque/struct.VecDeque.html
13 #![stable(feature = "rust1", since = "1.0.0")]
15 use core::cmp::Ordering;
17 use core::hash::{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 /// NOTE: It is almost always better to use `Vec` or `VecDeque` because
35 /// array-based containers are generally faster,
36 /// more memory efficient, and make better use of CPU cache.
37 #[stable(feature = "rust1", since = "1.0.0")]
38 pub struct LinkedList<T> {
39 head: Option<NonNull<Node<T>>>,
40 tail: Option<NonNull<Node<T>>>,
42 marker: PhantomData<Box<Node<T>>>,
46 next: Option<NonNull<Node<T>>>,
47 prev: Option<NonNull<Node<T>>>,
51 /// An iterator over the elements of a `LinkedList`.
53 /// This `struct` is created by the [`iter`] method on [`LinkedList`]. See its
54 /// documentation for more.
56 /// [`iter`]: struct.LinkedList.html#method.iter
57 /// [`LinkedList`]: struct.LinkedList.html
58 #[stable(feature = "rust1", since = "1.0.0")]
59 pub struct Iter<'a, T: 'a> {
60 head: Option<NonNull<Node<T>>>,
61 tail: Option<NonNull<Node<T>>>,
63 marker: PhantomData<&'a Node<T>>,
66 #[stable(feature = "collection_debug", since = "1.17.0")]
67 impl<T: fmt::Debug> fmt::Debug for Iter<'_, T> {
68 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
69 f.debug_tuple("Iter").field(&self.len).finish()
73 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
74 #[stable(feature = "rust1", since = "1.0.0")]
75 impl<T> Clone for Iter<'_, T> {
76 fn clone(&self) -> Self {
81 /// A mutable iterator over the elements of a `LinkedList`.
83 /// This `struct` is created by the [`iter_mut`] method on [`LinkedList`]. See its
84 /// documentation for more.
86 /// [`iter_mut`]: struct.LinkedList.html#method.iter_mut
87 /// [`LinkedList`]: struct.LinkedList.html
88 #[stable(feature = "rust1", since = "1.0.0")]
89 pub struct IterMut<'a, T: 'a> {
90 // We do *not* exclusively own the entire list here, references to node's `element`
91 // have been handed out by the iterator! So be careful when using this; the methods
92 // called must be aware that there can be aliasing pointers to `element`.
93 list: &'a mut LinkedList<T>,
94 head: Option<NonNull<Node<T>>>,
95 tail: Option<NonNull<Node<T>>>,
99 #[stable(feature = "collection_debug", since = "1.17.0")]
100 impl<T: fmt::Debug> fmt::Debug for IterMut<'_, T> {
101 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
102 f.debug_tuple("IterMut").field(&self.list).field(&self.len).finish()
106 /// An owning iterator over the elements of a `LinkedList`.
108 /// This `struct` is created by the [`into_iter`] method on [`LinkedList`]
109 /// (provided by the `IntoIterator` trait). See its documentation for more.
111 /// [`into_iter`]: struct.LinkedList.html#method.into_iter
112 /// [`LinkedList`]: struct.LinkedList.html
114 #[stable(feature = "rust1", since = "1.0.0")]
115 pub struct IntoIter<T> {
119 #[stable(feature = "collection_debug", since = "1.17.0")]
120 impl<T: fmt::Debug> fmt::Debug for IntoIter<T> {
121 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
122 f.debug_tuple("IntoIter").field(&self.list).finish()
127 fn new(element: T) -> Self {
128 Node { next: None, prev: None, element }
131 fn into_element(self: Box<Self>) -> T {
137 impl<T> LinkedList<T> {
138 /// Adds the given node to the front of the list.
140 fn push_front_node(&mut self, mut node: Box<Node<T>>) {
141 // This method takes care not to create mutable references to whole nodes,
142 // to maintain validity of aliasing pointers into `element`.
144 node.next = self.head;
146 let node = Some(Box::into_raw_non_null(node));
149 None => self.tail = node,
150 // Not creating new mutable (unique!) references overlapping `element`.
151 Some(head) => (*head.as_ptr()).prev = node,
159 /// Removes and returns the node at the front of the list.
161 fn pop_front_node(&mut self) -> Option<Box<Node<T>>> {
162 // This method takes care not to create mutable references to whole nodes,
163 // to maintain validity of aliasing pointers into `element`.
164 self.head.map(|node| unsafe {
165 let node = Box::from_raw(node.as_ptr());
166 self.head = node.next;
169 None => self.tail = None,
170 // Not creating new mutable (unique!) references overlapping `element`.
171 Some(head) => (*head.as_ptr()).prev = None,
179 /// Adds the given node to the back of the list.
181 fn push_back_node(&mut self, mut node: Box<Node<T>>) {
182 // This method takes care not to create mutable references to whole nodes,
183 // to maintain validity of aliasing pointers into `element`.
186 node.prev = self.tail;
187 let node = Some(Box::into_raw_non_null(node));
190 None => self.head = node,
191 // Not creating new mutable (unique!) references overlapping `element`.
192 Some(tail) => (*tail.as_ptr()).next = node,
200 /// Removes and returns the node at the back of the list.
202 fn pop_back_node(&mut self) -> Option<Box<Node<T>>> {
203 // This method takes care not to create mutable references to whole nodes,
204 // to maintain validity of aliasing pointers into `element`.
205 self.tail.map(|node| unsafe {
206 let node = Box::from_raw(node.as_ptr());
207 self.tail = node.prev;
210 None => self.head = None,
211 // Not creating new mutable (unique!) references overlapping `element`.
212 Some(tail) => (*tail.as_ptr()).next = None,
220 /// Unlinks the specified node from the current list.
222 /// Warning: this will not check that the provided node belongs to the current list.
224 /// This method takes care not to create mutable references to `element`, to
225 /// maintain validity of aliasing pointers.
227 unsafe fn unlink_node(&mut self, mut node: NonNull<Node<T>>) {
228 let node = node.as_mut(); // this one is ours now, we can create an &mut.
230 // Not creating new mutable (unique!) references overlapping `element`.
232 Some(prev) => (*prev.as_ptr()).next = node.next,
233 // this node is the head node
234 None => self.head = node.next,
238 Some(next) => (*next.as_ptr()).prev = node.prev,
239 // this node is the tail node
240 None => self.tail = node.prev,
247 #[stable(feature = "rust1", since = "1.0.0")]
248 impl<T> Default for LinkedList<T> {
249 /// Creates an empty `LinkedList<T>`.
251 fn default() -> Self {
256 impl<T> LinkedList<T> {
257 /// Creates an empty `LinkedList`.
262 /// use std::collections::LinkedList;
264 /// let list: LinkedList<u32> = LinkedList::new();
267 #[rustc_const_stable(feature = "const_linked_list_new", since = "1.32.0")]
268 #[stable(feature = "rust1", since = "1.0.0")]
269 pub const fn new() -> Self {
270 LinkedList { head: None, tail: None, len: 0, marker: PhantomData }
273 /// Moves all elements from `other` to the end of the list.
275 /// This reuses all the nodes from `other` and moves them into `self`. After
276 /// this operation, `other` becomes empty.
278 /// This operation should compute in O(1) time and O(1) memory.
283 /// use std::collections::LinkedList;
285 /// let mut list1 = LinkedList::new();
286 /// list1.push_back('a');
288 /// let mut list2 = LinkedList::new();
289 /// list2.push_back('b');
290 /// list2.push_back('c');
292 /// list1.append(&mut list2);
294 /// let mut iter = list1.iter();
295 /// assert_eq!(iter.next(), Some(&'a'));
296 /// assert_eq!(iter.next(), Some(&'b'));
297 /// assert_eq!(iter.next(), Some(&'c'));
298 /// assert!(iter.next().is_none());
300 /// assert!(list2.is_empty());
302 #[stable(feature = "rust1", since = "1.0.0")]
303 pub fn append(&mut self, other: &mut Self) {
305 None => mem::swap(self, other),
307 // `as_mut` is okay here because we have exclusive access to the entirety
309 if let Some(mut other_head) = other.head.take() {
311 tail.as_mut().next = Some(other_head);
312 other_head.as_mut().prev = Some(tail);
315 self.tail = other.tail.take();
316 self.len += mem::replace(&mut other.len, 0);
322 /// Provides a forward iterator.
327 /// use std::collections::LinkedList;
329 /// let mut list: LinkedList<u32> = LinkedList::new();
331 /// list.push_back(0);
332 /// list.push_back(1);
333 /// list.push_back(2);
335 /// let mut iter = list.iter();
336 /// assert_eq!(iter.next(), Some(&0));
337 /// assert_eq!(iter.next(), Some(&1));
338 /// assert_eq!(iter.next(), Some(&2));
339 /// assert_eq!(iter.next(), None);
342 #[stable(feature = "rust1", since = "1.0.0")]
343 pub fn iter(&self) -> Iter<'_, T> {
344 Iter { head: self.head, tail: self.tail, len: self.len, marker: PhantomData }
347 /// Provides a forward iterator with mutable references.
352 /// use std::collections::LinkedList;
354 /// let mut list: LinkedList<u32> = LinkedList::new();
356 /// list.push_back(0);
357 /// list.push_back(1);
358 /// list.push_back(2);
360 /// for element in list.iter_mut() {
364 /// let mut iter = list.iter();
365 /// assert_eq!(iter.next(), Some(&10));
366 /// assert_eq!(iter.next(), Some(&11));
367 /// assert_eq!(iter.next(), Some(&12));
368 /// assert_eq!(iter.next(), None);
371 #[stable(feature = "rust1", since = "1.0.0")]
372 pub fn iter_mut(&mut self) -> IterMut<'_, T> {
373 IterMut { head: self.head, tail: self.tail, len: self.len, list: self }
376 /// Returns `true` if the `LinkedList` is empty.
378 /// This operation should compute in O(1) time.
383 /// use std::collections::LinkedList;
385 /// let mut dl = LinkedList::new();
386 /// assert!(dl.is_empty());
388 /// dl.push_front("foo");
389 /// assert!(!dl.is_empty());
392 #[stable(feature = "rust1", since = "1.0.0")]
393 pub fn is_empty(&self) -> bool {
397 /// Returns the length of the `LinkedList`.
399 /// This operation should compute in O(1) time.
404 /// use std::collections::LinkedList;
406 /// let mut dl = LinkedList::new();
408 /// dl.push_front(2);
409 /// assert_eq!(dl.len(), 1);
411 /// dl.push_front(1);
412 /// assert_eq!(dl.len(), 2);
415 /// assert_eq!(dl.len(), 3);
418 #[stable(feature = "rust1", since = "1.0.0")]
419 pub fn len(&self) -> usize {
423 /// Removes all elements from the `LinkedList`.
425 /// This operation should compute in O(n) time.
430 /// use std::collections::LinkedList;
432 /// let mut dl = LinkedList::new();
434 /// dl.push_front(2);
435 /// dl.push_front(1);
436 /// assert_eq!(dl.len(), 2);
437 /// assert_eq!(dl.front(), Some(&1));
440 /// assert_eq!(dl.len(), 0);
441 /// assert_eq!(dl.front(), None);
444 #[stable(feature = "rust1", since = "1.0.0")]
445 pub fn clear(&mut self) {
449 /// Returns `true` if the `LinkedList` contains an element equal to the
455 /// use std::collections::LinkedList;
457 /// let mut list: LinkedList<u32> = LinkedList::new();
459 /// list.push_back(0);
460 /// list.push_back(1);
461 /// list.push_back(2);
463 /// assert_eq!(list.contains(&0), true);
464 /// assert_eq!(list.contains(&10), false);
466 #[stable(feature = "linked_list_contains", since = "1.12.0")]
467 pub fn contains(&self, x: &T) -> bool
471 self.iter().any(|e| e == x)
474 /// Provides a reference to the front element, or `None` if the list is
480 /// use std::collections::LinkedList;
482 /// let mut dl = LinkedList::new();
483 /// assert_eq!(dl.front(), None);
485 /// dl.push_front(1);
486 /// assert_eq!(dl.front(), Some(&1));
489 #[stable(feature = "rust1", since = "1.0.0")]
490 pub fn front(&self) -> Option<&T> {
491 unsafe { self.head.as_ref().map(|node| &node.as_ref().element) }
494 /// Provides a mutable reference to the front element, or `None` if the list
500 /// use std::collections::LinkedList;
502 /// let mut dl = LinkedList::new();
503 /// assert_eq!(dl.front(), None);
505 /// dl.push_front(1);
506 /// assert_eq!(dl.front(), Some(&1));
508 /// match dl.front_mut() {
510 /// Some(x) => *x = 5,
512 /// assert_eq!(dl.front(), Some(&5));
515 #[stable(feature = "rust1", since = "1.0.0")]
516 pub fn front_mut(&mut self) -> Option<&mut T> {
517 unsafe { self.head.as_mut().map(|node| &mut node.as_mut().element) }
520 /// Provides a reference to the back element, or `None` if the list is
526 /// use std::collections::LinkedList;
528 /// let mut dl = LinkedList::new();
529 /// assert_eq!(dl.back(), None);
532 /// assert_eq!(dl.back(), Some(&1));
535 #[stable(feature = "rust1", since = "1.0.0")]
536 pub fn back(&self) -> Option<&T> {
537 unsafe { self.tail.as_ref().map(|node| &node.as_ref().element) }
540 /// Provides a mutable reference to the back element, or `None` if the list
546 /// use std::collections::LinkedList;
548 /// let mut dl = LinkedList::new();
549 /// assert_eq!(dl.back(), None);
552 /// assert_eq!(dl.back(), Some(&1));
554 /// match dl.back_mut() {
556 /// Some(x) => *x = 5,
558 /// assert_eq!(dl.back(), Some(&5));
561 #[stable(feature = "rust1", since = "1.0.0")]
562 pub fn back_mut(&mut self) -> Option<&mut T> {
563 unsafe { self.tail.as_mut().map(|node| &mut node.as_mut().element) }
566 /// Adds an element first in the list.
568 /// This operation should compute in O(1) time.
573 /// use std::collections::LinkedList;
575 /// let mut dl = LinkedList::new();
577 /// dl.push_front(2);
578 /// assert_eq!(dl.front().unwrap(), &2);
580 /// dl.push_front(1);
581 /// assert_eq!(dl.front().unwrap(), &1);
583 #[stable(feature = "rust1", since = "1.0.0")]
584 pub fn push_front(&mut self, elt: T) {
585 self.push_front_node(box Node::new(elt));
588 /// Removes the first element and returns it, or `None` if the list is
591 /// This operation should compute in O(1) time.
596 /// use std::collections::LinkedList;
598 /// let mut d = LinkedList::new();
599 /// assert_eq!(d.pop_front(), None);
603 /// assert_eq!(d.pop_front(), Some(3));
604 /// assert_eq!(d.pop_front(), Some(1));
605 /// assert_eq!(d.pop_front(), None);
607 #[stable(feature = "rust1", since = "1.0.0")]
608 pub fn pop_front(&mut self) -> Option<T> {
609 self.pop_front_node().map(Node::into_element)
612 /// Appends an element to the back of a list.
614 /// This operation should compute in O(1) time.
619 /// use std::collections::LinkedList;
621 /// let mut d = LinkedList::new();
624 /// assert_eq!(3, *d.back().unwrap());
626 #[stable(feature = "rust1", since = "1.0.0")]
627 pub fn push_back(&mut self, elt: T) {
628 self.push_back_node(box Node::new(elt));
631 /// Removes the last element from a list and returns it, or `None` if
634 /// This operation should compute in O(1) time.
639 /// use std::collections::LinkedList;
641 /// let mut d = LinkedList::new();
642 /// assert_eq!(d.pop_back(), None);
645 /// assert_eq!(d.pop_back(), Some(3));
647 #[stable(feature = "rust1", since = "1.0.0")]
648 pub fn pop_back(&mut self) -> Option<T> {
649 self.pop_back_node().map(Node::into_element)
652 /// Splits the list into two at the given index. Returns everything after the given index,
653 /// including the index.
655 /// This operation should compute in O(n) time.
659 /// Panics if `at > len`.
664 /// use std::collections::LinkedList;
666 /// let mut d = LinkedList::new();
672 /// let mut splitted = d.split_off(2);
674 /// assert_eq!(splitted.pop_front(), Some(1));
675 /// assert_eq!(splitted.pop_front(), None);
677 #[stable(feature = "rust1", since = "1.0.0")]
678 pub fn split_off(&mut self, at: usize) -> LinkedList<T> {
679 let len = self.len();
680 assert!(at <= len, "Cannot split off at a nonexistent index");
682 return mem::take(self);
683 } else if at == len {
687 // Below, we iterate towards the `i-1`th node, either from the start or the end,
688 // depending on which would be faster.
689 let split_node = if at - 1 <= len - 1 - (at - 1) {
690 let mut iter = self.iter_mut();
691 // instead of skipping using .skip() (which creates a new struct),
692 // we skip manually so we can access the head field without
693 // depending on implementation details of Skip
699 // better off starting from the end
700 let mut iter = self.iter_mut();
701 for _ in 0..len - 1 - (at - 1) {
707 // The split node is the new tail node of the first part and owns
708 // the head of the second part.
709 let second_part_head;
712 second_part_head = split_node.unwrap().as_mut().next.take();
713 if let Some(mut head) = second_part_head {
714 head.as_mut().prev = None;
718 let second_part = LinkedList {
719 head: second_part_head,
725 // Fix the tail ptr of the first part
726 self.tail = split_node;
732 /// Creates an iterator which uses a closure to determine if an element should be removed.
734 /// If the closure returns true, then the element is removed and yielded.
735 /// If the closure returns false, the element will remain in the list and will not be yielded
738 /// Note that `drain_filter` lets you mutate every element in the filter closure, regardless of
739 /// whether you choose to keep or remove it.
743 /// Splitting a list into evens and odds, reusing the original list:
746 /// #![feature(drain_filter)]
747 /// use std::collections::LinkedList;
749 /// let mut numbers: LinkedList<u32> = LinkedList::new();
750 /// numbers.extend(&[1, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15]);
752 /// let evens = numbers.drain_filter(|x| *x % 2 == 0).collect::<LinkedList<_>>();
753 /// let odds = numbers;
755 /// assert_eq!(evens.into_iter().collect::<Vec<_>>(), vec![2, 4, 6, 8, 14]);
756 /// assert_eq!(odds.into_iter().collect::<Vec<_>>(), vec![1, 3, 5, 9, 11, 13, 15]);
758 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
759 pub fn drain_filter<F>(&mut self, filter: F) -> DrainFilter<'_, T, F>
761 F: FnMut(&mut T) -> bool,
763 // avoid borrow issues.
765 let old_len = self.len;
767 DrainFilter { list: self, it: it, pred: filter, idx: 0, old_len: old_len }
771 #[stable(feature = "rust1", since = "1.0.0")]
772 unsafe impl<#[may_dangle] T> Drop for LinkedList<T> {
774 struct DropGuard<'a, T>(&'a mut LinkedList<T>);
776 impl<'a, T> Drop for DropGuard<'a, T> {
778 // Continue the same loop we do below. This only runs when a destructor has
779 // panicked. If another one panics this will abort.
780 while let Some(_) = self.0.pop_front_node() {}
784 while let Some(node) = self.pop_front_node() {
785 let guard = DropGuard(self);
792 #[stable(feature = "rust1", since = "1.0.0")]
793 impl<'a, T> Iterator for Iter<'a, T> {
797 fn next(&mut self) -> Option<&'a T> {
801 self.head.map(|node| unsafe {
802 // Need an unbound lifetime to get 'a
803 let node = &*node.as_ptr();
805 self.head = node.next;
812 fn size_hint(&self) -> (usize, Option<usize>) {
813 (self.len, Some(self.len))
817 fn last(mut self) -> Option<&'a T> {
822 #[stable(feature = "rust1", since = "1.0.0")]
823 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
825 fn next_back(&mut self) -> Option<&'a T> {
829 self.tail.map(|node| unsafe {
830 // Need an unbound lifetime to get 'a
831 let node = &*node.as_ptr();
833 self.tail = node.prev;
840 #[stable(feature = "rust1", since = "1.0.0")]
841 impl<T> ExactSizeIterator for Iter<'_, T> {}
843 #[stable(feature = "fused", since = "1.26.0")]
844 impl<T> FusedIterator for Iter<'_, T> {}
846 #[stable(feature = "rust1", since = "1.0.0")]
847 impl<'a, T> Iterator for IterMut<'a, T> {
848 type Item = &'a mut T;
851 fn next(&mut self) -> Option<&'a mut T> {
855 self.head.map(|node| unsafe {
856 // Need an unbound lifetime to get 'a
857 let node = &mut *node.as_ptr();
859 self.head = node.next;
866 fn size_hint(&self) -> (usize, Option<usize>) {
867 (self.len, Some(self.len))
871 fn last(mut self) -> Option<&'a mut T> {
876 #[stable(feature = "rust1", since = "1.0.0")]
877 impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
879 fn next_back(&mut self) -> Option<&'a mut T> {
883 self.tail.map(|node| unsafe {
884 // Need an unbound lifetime to get 'a
885 let node = &mut *node.as_ptr();
887 self.tail = node.prev;
894 #[stable(feature = "rust1", since = "1.0.0")]
895 impl<T> ExactSizeIterator for IterMut<'_, T> {}
897 #[stable(feature = "fused", since = "1.26.0")]
898 impl<T> FusedIterator for IterMut<'_, T> {}
900 impl<T> IterMut<'_, T> {
901 /// Inserts the given element just after the element most recently returned by `.next()`.
902 /// The inserted element does not appear in the iteration.
907 /// #![feature(linked_list_extras)]
909 /// use std::collections::LinkedList;
911 /// let mut list: LinkedList<_> = vec![1, 3, 4].into_iter().collect();
914 /// let mut it = list.iter_mut();
915 /// assert_eq!(it.next().unwrap(), &1);
916 /// // insert `2` after `1`
917 /// it.insert_next(2);
920 /// let vec: Vec<_> = list.into_iter().collect();
921 /// assert_eq!(vec, [1, 2, 3, 4]);
926 feature = "linked_list_extras",
927 reason = "this is probably better handled by a cursor type -- we'll see",
930 pub fn insert_next(&mut self, element: T) {
932 // `push_back` is okay with aliasing `element` references
933 None => self.list.push_back(element),
934 Some(head) => unsafe {
935 let prev = match head.as_ref().prev {
936 // `push_front` is okay with aliasing nodes
937 None => return self.list.push_front(element),
941 let node = Some(Box::into_raw_non_null(box Node {
947 // Not creating references to entire nodes to not invalidate the
948 // reference to `element` we handed to the user.
949 (*prev.as_ptr()).next = node;
950 (*head.as_ptr()).prev = node;
957 /// Provides a reference to the next element, without changing the iterator.
962 /// #![feature(linked_list_extras)]
964 /// use std::collections::LinkedList;
966 /// let mut list: LinkedList<_> = vec![1, 2, 3].into_iter().collect();
968 /// let mut it = list.iter_mut();
969 /// assert_eq!(it.next().unwrap(), &1);
970 /// assert_eq!(it.peek_next().unwrap(), &2);
971 /// // We just peeked at 2, so it was not consumed from the iterator.
972 /// assert_eq!(it.next().unwrap(), &2);
976 feature = "linked_list_extras",
977 reason = "this is probably better handled by a cursor type -- we'll see",
980 pub fn peek_next(&mut self) -> Option<&mut T> {
984 unsafe { self.head.as_mut().map(|node| &mut node.as_mut().element) }
989 /// An iterator produced by calling `drain_filter` on LinkedList.
990 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
991 pub struct DrainFilter<'a, T: 'a, F: 'a>
993 F: FnMut(&mut T) -> bool,
995 list: &'a mut LinkedList<T>,
996 it: Option<NonNull<Node<T>>>,
1002 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
1003 impl<T, F> Iterator for DrainFilter<'_, T, F>
1005 F: FnMut(&mut T) -> bool,
1009 fn next(&mut self) -> Option<T> {
1010 while let Some(mut node) = self.it {
1012 self.it = node.as_ref().next;
1015 if (self.pred)(&mut node.as_mut().element) {
1016 // `unlink_node` is okay with aliasing `element` references.
1017 self.list.unlink_node(node);
1018 return Some(Box::from_raw(node.as_ptr()).element);
1026 fn size_hint(&self) -> (usize, Option<usize>) {
1027 (0, Some(self.old_len - self.idx))
1031 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
1032 impl<T, F> Drop for DrainFilter<'_, T, F>
1034 F: FnMut(&mut T) -> bool,
1036 fn drop(&mut self) {
1037 self.for_each(drop);
1041 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
1042 impl<T: fmt::Debug, F> fmt::Debug for DrainFilter<'_, T, F>
1044 F: FnMut(&mut T) -> bool,
1046 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1047 f.debug_tuple("DrainFilter").field(&self.list).finish()
1051 #[stable(feature = "rust1", since = "1.0.0")]
1052 impl<T> Iterator for IntoIter<T> {
1056 fn next(&mut self) -> Option<T> {
1057 self.list.pop_front()
1061 fn size_hint(&self) -> (usize, Option<usize>) {
1062 (self.list.len, Some(self.list.len))
1066 #[stable(feature = "rust1", since = "1.0.0")]
1067 impl<T> DoubleEndedIterator for IntoIter<T> {
1069 fn next_back(&mut self) -> Option<T> {
1070 self.list.pop_back()
1074 #[stable(feature = "rust1", since = "1.0.0")]
1075 impl<T> ExactSizeIterator for IntoIter<T> {}
1077 #[stable(feature = "fused", since = "1.26.0")]
1078 impl<T> FusedIterator for IntoIter<T> {}
1080 #[stable(feature = "rust1", since = "1.0.0")]
1081 impl<T> FromIterator<T> for LinkedList<T> {
1082 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
1083 let mut list = Self::new();
1089 #[stable(feature = "rust1", since = "1.0.0")]
1090 impl<T> IntoIterator for LinkedList<T> {
1092 type IntoIter = IntoIter<T>;
1094 /// Consumes the list into an iterator yielding elements by value.
1096 fn into_iter(self) -> IntoIter<T> {
1097 IntoIter { list: self }
1101 #[stable(feature = "rust1", since = "1.0.0")]
1102 impl<'a, T> IntoIterator for &'a LinkedList<T> {
1104 type IntoIter = Iter<'a, T>;
1106 fn into_iter(self) -> Iter<'a, T> {
1111 #[stable(feature = "rust1", since = "1.0.0")]
1112 impl<'a, T> IntoIterator for &'a mut LinkedList<T> {
1113 type Item = &'a mut T;
1114 type IntoIter = IterMut<'a, T>;
1116 fn into_iter(self) -> IterMut<'a, T> {
1121 #[stable(feature = "rust1", since = "1.0.0")]
1122 impl<T> Extend<T> for LinkedList<T> {
1123 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1124 <Self as SpecExtend<I>>::spec_extend(self, iter);
1128 impl<I: IntoIterator> SpecExtend<I> for LinkedList<I::Item> {
1129 default fn spec_extend(&mut self, iter: I) {
1130 iter.into_iter().for_each(move |elt| self.push_back(elt));
1134 impl<T> SpecExtend<LinkedList<T>> for LinkedList<T> {
1135 fn spec_extend(&mut self, ref mut other: LinkedList<T>) {
1140 #[stable(feature = "extend_ref", since = "1.2.0")]
1141 impl<'a, T: 'a + Copy> Extend<&'a T> for LinkedList<T> {
1142 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
1143 self.extend(iter.into_iter().cloned());
1147 #[stable(feature = "rust1", since = "1.0.0")]
1148 impl<T: PartialEq> PartialEq for LinkedList<T> {
1149 fn eq(&self, other: &Self) -> bool {
1150 self.len() == other.len() && self.iter().eq(other)
1153 fn ne(&self, other: &Self) -> bool {
1154 self.len() != other.len() || self.iter().ne(other)
1158 #[stable(feature = "rust1", since = "1.0.0")]
1159 impl<T: Eq> Eq for LinkedList<T> {}
1161 #[stable(feature = "rust1", since = "1.0.0")]
1162 impl<T: PartialOrd> PartialOrd for LinkedList<T> {
1163 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1164 self.iter().partial_cmp(other)
1168 #[stable(feature = "rust1", since = "1.0.0")]
1169 impl<T: Ord> Ord for LinkedList<T> {
1171 fn cmp(&self, other: &Self) -> Ordering {
1172 self.iter().cmp(other)
1176 #[stable(feature = "rust1", since = "1.0.0")]
1177 impl<T: Clone> Clone for LinkedList<T> {
1178 fn clone(&self) -> Self {
1179 self.iter().cloned().collect()
1182 fn clone_from(&mut self, other: &Self) {
1183 let mut iter_other = other.iter();
1184 if self.len() > other.len() {
1185 self.split_off(other.len());
1187 for (elem, elem_other) in self.iter_mut().zip(&mut iter_other) {
1188 elem.clone_from(elem_other);
1190 if !iter_other.is_empty() {
1191 self.extend(iter_other.cloned());
1196 #[stable(feature = "rust1", since = "1.0.0")]
1197 impl<T: fmt::Debug> fmt::Debug for LinkedList<T> {
1198 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1199 f.debug_list().entries(self).finish()
1203 #[stable(feature = "rust1", since = "1.0.0")]
1204 impl<T: Hash> Hash for LinkedList<T> {
1205 fn hash<H: Hasher>(&self, state: &mut H) {
1206 self.len().hash(state);
1213 // Ensure that `LinkedList` and its read-only iterators are covariant in their type parameters.
1215 fn assert_covariance() {
1216 fn a<'a>(x: LinkedList<&'static str>) -> LinkedList<&'a str> {
1219 fn b<'i, 'a>(x: Iter<'i, &'static str>) -> Iter<'i, &'a str> {
1222 fn c<'a>(x: IntoIter<&'static str>) -> IntoIter<&'a str> {
1227 #[stable(feature = "rust1", since = "1.0.0")]
1228 unsafe impl<T: Send> Send for LinkedList<T> {}
1230 #[stable(feature = "rust1", since = "1.0.0")]
1231 unsafe impl<T: Sync> Sync for LinkedList<T> {}
1233 #[stable(feature = "rust1", since = "1.0.0")]
1234 unsafe impl<T: Sync> Send for Iter<'_, T> {}
1236 #[stable(feature = "rust1", since = "1.0.0")]
1237 unsafe impl<T: Sync> Sync for Iter<'_, T> {}
1239 #[stable(feature = "rust1", since = "1.0.0")]
1240 unsafe impl<T: Send> Send for IterMut<'_, T> {}
1242 #[stable(feature = "rust1", since = "1.0.0")]
1243 unsafe impl<T: Sync> Sync for IterMut<'_, T> {}