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 /// 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 [`LinkedList::iter()`]. See its
54 /// documentation for more.
55 #[stable(feature = "rust1", since = "1.0.0")]
56 pub struct Iter<'a, T: 'a> {
57 head: Option<NonNull<Node<T>>>,
58 tail: Option<NonNull<Node<T>>>,
60 marker: PhantomData<&'a Node<T>>,
63 #[stable(feature = "collection_debug", since = "1.17.0")]
64 impl<T: fmt::Debug> fmt::Debug for Iter<'_, T> {
65 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
66 f.debug_tuple("Iter").field(&self.len).finish()
70 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
71 #[stable(feature = "rust1", since = "1.0.0")]
72 impl<T> Clone for Iter<'_, T> {
73 fn clone(&self) -> Self {
78 /// A mutable iterator over the elements of a `LinkedList`.
80 /// This `struct` is created by [`LinkedList::iter_mut()`]. See its
81 /// documentation for more.
82 #[stable(feature = "rust1", since = "1.0.0")]
83 pub struct IterMut<'a, T: 'a> {
84 // We do *not* exclusively own the entire list here, references to node's `element`
85 // have been handed out by the iterator! So be careful when using this; the methods
86 // called must be aware that there can be aliasing pointers to `element`.
87 list: &'a mut LinkedList<T>,
88 head: Option<NonNull<Node<T>>>,
89 tail: Option<NonNull<Node<T>>>,
93 #[stable(feature = "collection_debug", since = "1.17.0")]
94 impl<T: fmt::Debug> fmt::Debug for IterMut<'_, T> {
95 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
96 f.debug_tuple("IterMut").field(&self.list).field(&self.len).finish()
100 /// An owning iterator over the elements of a `LinkedList`.
102 /// This `struct` is created by the [`into_iter`] method on [`LinkedList`]
103 /// (provided by the `IntoIterator` trait). See its documentation for more.
105 /// [`into_iter`]: LinkedList::into_iter
107 #[stable(feature = "rust1", since = "1.0.0")]
108 pub struct IntoIter<T> {
112 #[stable(feature = "collection_debug", since = "1.17.0")]
113 impl<T: fmt::Debug> fmt::Debug for IntoIter<T> {
114 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
115 f.debug_tuple("IntoIter").field(&self.list).finish()
120 fn new(element: T) -> Self {
121 Node { next: None, prev: None, element }
124 fn into_element(self: Box<Self>) -> T {
130 impl<T> LinkedList<T> {
131 /// Adds the given node to the front of the list.
133 fn push_front_node(&mut self, mut node: Box<Node<T>>) {
134 // This method takes care not to create mutable references to whole nodes,
135 // to maintain validity of aliasing pointers into `element`.
137 node.next = self.head;
139 let node = Some(Box::leak(node).into());
142 None => self.tail = node,
143 // Not creating new mutable (unique!) references overlapping `element`.
144 Some(head) => (*head.as_ptr()).prev = node,
152 /// Removes and returns the node at the front of the list.
154 fn pop_front_node(&mut self) -> Option<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`.
157 self.head.map(|node| unsafe {
158 let node = Box::from_raw(node.as_ptr());
159 self.head = node.next;
162 None => self.tail = None,
163 // Not creating new mutable (unique!) references overlapping `element`.
164 Some(head) => (*head.as_ptr()).prev = None,
172 /// Adds the given node to the back of the list.
174 fn push_back_node(&mut self, mut node: Box<Node<T>>) {
175 // This method takes care not to create mutable references to whole nodes,
176 // to maintain validity of aliasing pointers into `element`.
179 node.prev = self.tail;
180 let node = Some(Box::leak(node).into());
183 None => self.head = node,
184 // Not creating new mutable (unique!) references overlapping `element`.
185 Some(tail) => (*tail.as_ptr()).next = node,
193 /// Removes and returns the node at the back of the list.
195 fn pop_back_node(&mut self) -> Option<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`.
198 self.tail.map(|node| unsafe {
199 let node = Box::from_raw(node.as_ptr());
200 self.tail = node.prev;
203 None => self.head = None,
204 // Not creating new mutable (unique!) references overlapping `element`.
205 Some(tail) => (*tail.as_ptr()).next = None,
213 /// Unlinks the specified node from the current list.
215 /// Warning: this will not check that the provided node belongs to the current list.
217 /// This method takes care not to create mutable references to `element`, to
218 /// maintain validity of aliasing pointers.
220 unsafe fn unlink_node(&mut self, mut node: NonNull<Node<T>>) {
221 let node = unsafe { node.as_mut() }; // this one is ours now, we can create an &mut.
223 // Not creating new mutable (unique!) references overlapping `element`.
225 Some(prev) => unsafe { (*prev.as_ptr()).next = node.next },
226 // this node is the head node
227 None => self.head = node.next,
231 Some(next) => unsafe { (*next.as_ptr()).prev = node.prev },
232 // this node is the tail node
233 None => self.tail = node.prev,
239 /// Splices a series of nodes between two existing nodes.
241 /// Warning: this will not check that the provided node belongs to the two existing lists.
243 unsafe fn splice_nodes(
245 existing_prev: Option<NonNull<Node<T>>>,
246 existing_next: Option<NonNull<Node<T>>>,
247 mut splice_start: NonNull<Node<T>>,
248 mut splice_end: NonNull<Node<T>>,
249 splice_length: usize,
251 // This method takes care not to create multiple mutable references to whole nodes at the same time,
252 // to maintain validity of aliasing pointers into `element`.
253 if let Some(mut existing_prev) = existing_prev {
255 existing_prev.as_mut().next = Some(splice_start);
258 self.head = Some(splice_start);
260 if let Some(mut existing_next) = existing_next {
262 existing_next.as_mut().prev = Some(splice_end);
265 self.tail = Some(splice_end);
268 splice_start.as_mut().prev = existing_prev;
269 splice_end.as_mut().next = existing_next;
272 self.len += splice_length;
275 /// Detaches all nodes from a linked list as a series of nodes.
277 fn detach_all_nodes(mut self) -> Option<(NonNull<Node<T>>, NonNull<Node<T>>, usize)> {
278 let head = self.head.take();
279 let tail = self.tail.take();
280 let len = mem::replace(&mut self.len, 0);
281 if let Some(head) = head {
282 let tail = tail.unwrap_or_else(|| unsafe { core::hint::unreachable_unchecked() });
283 Some((head, tail, len))
290 unsafe fn split_off_before_node(
292 split_node: Option<NonNull<Node<T>>>,
295 // The split node is the new head node of the second part
296 if let Some(mut split_node) = split_node {
300 first_part_tail = split_node.as_mut().prev.take();
302 if let Some(mut tail) = first_part_tail {
304 tail.as_mut().next = None;
306 first_part_head = self.head;
308 first_part_head = None;
311 let first_part = LinkedList {
312 head: first_part_head,
313 tail: first_part_tail,
318 // Fix the head ptr of the second part
319 self.head = Some(split_node);
320 self.len = self.len - at;
324 mem::replace(self, LinkedList::new())
329 unsafe fn split_off_after_node(
331 split_node: Option<NonNull<Node<T>>>,
334 // The split node is the new tail node of the first part and owns
335 // the head of the second part.
336 if let Some(mut split_node) = split_node {
337 let second_part_head;
338 let second_part_tail;
340 second_part_head = split_node.as_mut().next.take();
342 if let Some(mut head) = second_part_head {
344 head.as_mut().prev = None;
346 second_part_tail = self.tail;
348 second_part_tail = None;
351 let second_part = LinkedList {
352 head: second_part_head,
353 tail: second_part_tail,
358 // Fix the tail ptr of the first part
359 self.tail = Some(split_node);
364 mem::replace(self, LinkedList::new())
369 #[stable(feature = "rust1", since = "1.0.0")]
370 impl<T> Default for LinkedList<T> {
371 /// Creates an empty `LinkedList<T>`.
373 fn default() -> Self {
378 impl<T> LinkedList<T> {
379 /// Creates an empty `LinkedList`.
384 /// use std::collections::LinkedList;
386 /// let list: LinkedList<u32> = LinkedList::new();
389 #[rustc_const_stable(feature = "const_linked_list_new", since = "1.32.0")]
390 #[stable(feature = "rust1", since = "1.0.0")]
391 pub const fn new() -> Self {
392 LinkedList { head: None, tail: None, len: 0, marker: PhantomData }
395 /// Moves all elements from `other` to the end of the list.
397 /// This reuses all the nodes from `other` and moves them into `self`. After
398 /// this operation, `other` becomes empty.
400 /// This operation should compute in *O*(1) time and *O*(1) memory.
405 /// use std::collections::LinkedList;
407 /// let mut list1 = LinkedList::new();
408 /// list1.push_back('a');
410 /// let mut list2 = LinkedList::new();
411 /// list2.push_back('b');
412 /// list2.push_back('c');
414 /// list1.append(&mut list2);
416 /// let mut iter = list1.iter();
417 /// assert_eq!(iter.next(), Some(&'a'));
418 /// assert_eq!(iter.next(), Some(&'b'));
419 /// assert_eq!(iter.next(), Some(&'c'));
420 /// assert!(iter.next().is_none());
422 /// assert!(list2.is_empty());
424 #[stable(feature = "rust1", since = "1.0.0")]
425 pub fn append(&mut self, other: &mut Self) {
427 None => mem::swap(self, other),
429 // `as_mut` is okay here because we have exclusive access to the entirety
431 if let Some(mut other_head) = other.head.take() {
433 tail.as_mut().next = Some(other_head);
434 other_head.as_mut().prev = Some(tail);
437 self.tail = other.tail.take();
438 self.len += mem::replace(&mut other.len, 0);
444 /// Moves all elements from `other` to the begin of the list.
445 #[unstable(feature = "linked_list_prepend", issue = "none")]
446 pub fn prepend(&mut self, other: &mut Self) {
448 None => mem::swap(self, other),
450 // `as_mut` is okay here because we have exclusive access to the entirety
452 if let Some(mut other_tail) = other.tail.take() {
454 head.as_mut().prev = Some(other_tail);
455 other_tail.as_mut().next = Some(head);
458 self.head = other.head.take();
459 self.len += mem::replace(&mut other.len, 0);
465 /// Provides a forward iterator.
470 /// use std::collections::LinkedList;
472 /// let mut list: LinkedList<u32> = LinkedList::new();
474 /// list.push_back(0);
475 /// list.push_back(1);
476 /// list.push_back(2);
478 /// let mut iter = list.iter();
479 /// assert_eq!(iter.next(), Some(&0));
480 /// assert_eq!(iter.next(), Some(&1));
481 /// assert_eq!(iter.next(), Some(&2));
482 /// assert_eq!(iter.next(), None);
485 #[stable(feature = "rust1", since = "1.0.0")]
486 pub fn iter(&self) -> Iter<'_, T> {
487 Iter { head: self.head, tail: self.tail, len: self.len, marker: PhantomData }
490 /// Provides a forward iterator with mutable references.
495 /// use std::collections::LinkedList;
497 /// let mut list: LinkedList<u32> = LinkedList::new();
499 /// list.push_back(0);
500 /// list.push_back(1);
501 /// list.push_back(2);
503 /// for element in list.iter_mut() {
507 /// let mut iter = list.iter();
508 /// assert_eq!(iter.next(), Some(&10));
509 /// assert_eq!(iter.next(), Some(&11));
510 /// assert_eq!(iter.next(), Some(&12));
511 /// assert_eq!(iter.next(), None);
514 #[stable(feature = "rust1", since = "1.0.0")]
515 pub fn iter_mut(&mut self) -> IterMut<'_, T> {
516 IterMut { head: self.head, tail: self.tail, len: self.len, list: self }
519 /// Provides a cursor at the front element.
521 /// The cursor is pointing to the "ghost" non-element if the list is empty.
523 #[unstable(feature = "linked_list_cursors", issue = "58533")]
524 pub fn cursor_front(&self) -> Cursor<'_, T> {
525 Cursor { index: 0, current: self.head, list: self }
528 /// Provides a cursor with editing operations at the front element.
530 /// The cursor is pointing to the "ghost" non-element if the list is empty.
532 #[unstable(feature = "linked_list_cursors", issue = "58533")]
533 pub fn cursor_front_mut(&mut self) -> CursorMut<'_, T> {
534 CursorMut { index: 0, current: self.head, list: self }
537 /// Provides a cursor at the back element.
539 /// The cursor is pointing to the "ghost" non-element if the list is empty.
541 #[unstable(feature = "linked_list_cursors", issue = "58533")]
542 pub fn cursor_back(&self) -> Cursor<'_, T> {
543 Cursor { index: self.len.checked_sub(1).unwrap_or(0), current: self.tail, list: self }
546 /// Provides a cursor with editing operations at the back element.
548 /// The cursor is pointing to the "ghost" non-element if the list is empty.
550 #[unstable(feature = "linked_list_cursors", issue = "58533")]
551 pub fn cursor_back_mut(&mut self) -> CursorMut<'_, T> {
552 CursorMut { index: self.len.checked_sub(1).unwrap_or(0), current: self.tail, list: self }
555 /// Returns `true` if the `LinkedList` is empty.
557 /// This operation should compute in *O*(1) time.
562 /// use std::collections::LinkedList;
564 /// let mut dl = LinkedList::new();
565 /// assert!(dl.is_empty());
567 /// dl.push_front("foo");
568 /// assert!(!dl.is_empty());
571 #[stable(feature = "rust1", since = "1.0.0")]
572 pub fn is_empty(&self) -> bool {
576 /// Returns the length of the `LinkedList`.
578 /// This operation should compute in *O*(1) time.
583 /// use std::collections::LinkedList;
585 /// let mut dl = LinkedList::new();
587 /// dl.push_front(2);
588 /// assert_eq!(dl.len(), 1);
590 /// dl.push_front(1);
591 /// assert_eq!(dl.len(), 2);
594 /// assert_eq!(dl.len(), 3);
597 #[stable(feature = "rust1", since = "1.0.0")]
598 pub fn len(&self) -> usize {
602 /// Removes all elements from the `LinkedList`.
604 /// This operation should compute in *O*(*n*) time.
609 /// use std::collections::LinkedList;
611 /// let mut dl = LinkedList::new();
613 /// dl.push_front(2);
614 /// dl.push_front(1);
615 /// assert_eq!(dl.len(), 2);
616 /// assert_eq!(dl.front(), Some(&1));
619 /// assert_eq!(dl.len(), 0);
620 /// assert_eq!(dl.front(), None);
623 #[stable(feature = "rust1", since = "1.0.0")]
624 pub fn clear(&mut self) {
628 /// Returns `true` if the `LinkedList` contains an element equal to the
634 /// use std::collections::LinkedList;
636 /// let mut list: LinkedList<u32> = LinkedList::new();
638 /// list.push_back(0);
639 /// list.push_back(1);
640 /// list.push_back(2);
642 /// assert_eq!(list.contains(&0), true);
643 /// assert_eq!(list.contains(&10), false);
645 #[stable(feature = "linked_list_contains", since = "1.12.0")]
646 pub fn contains(&self, x: &T) -> bool
650 self.iter().any(|e| e == x)
653 /// Provides a reference to the front element, or `None` if the list is
659 /// use std::collections::LinkedList;
661 /// let mut dl = LinkedList::new();
662 /// assert_eq!(dl.front(), None);
664 /// dl.push_front(1);
665 /// assert_eq!(dl.front(), Some(&1));
668 #[stable(feature = "rust1", since = "1.0.0")]
669 pub fn front(&self) -> Option<&T> {
670 unsafe { self.head.as_ref().map(|node| &node.as_ref().element) }
673 /// Provides a mutable reference to the front element, or `None` if the list
679 /// use std::collections::LinkedList;
681 /// let mut dl = LinkedList::new();
682 /// assert_eq!(dl.front(), None);
684 /// dl.push_front(1);
685 /// assert_eq!(dl.front(), Some(&1));
687 /// match dl.front_mut() {
689 /// Some(x) => *x = 5,
691 /// assert_eq!(dl.front(), Some(&5));
694 #[stable(feature = "rust1", since = "1.0.0")]
695 pub fn front_mut(&mut self) -> Option<&mut T> {
696 unsafe { self.head.as_mut().map(|node| &mut node.as_mut().element) }
699 /// Provides a reference to the back element, or `None` if the list is
705 /// use std::collections::LinkedList;
707 /// let mut dl = LinkedList::new();
708 /// assert_eq!(dl.back(), None);
711 /// assert_eq!(dl.back(), Some(&1));
714 #[stable(feature = "rust1", since = "1.0.0")]
715 pub fn back(&self) -> Option<&T> {
716 unsafe { self.tail.as_ref().map(|node| &node.as_ref().element) }
719 /// Provides a mutable reference to the back element, or `None` if the list
725 /// use std::collections::LinkedList;
727 /// let mut dl = LinkedList::new();
728 /// assert_eq!(dl.back(), None);
731 /// assert_eq!(dl.back(), Some(&1));
733 /// match dl.back_mut() {
735 /// Some(x) => *x = 5,
737 /// assert_eq!(dl.back(), Some(&5));
740 #[stable(feature = "rust1", since = "1.0.0")]
741 pub fn back_mut(&mut self) -> Option<&mut T> {
742 unsafe { self.tail.as_mut().map(|node| &mut node.as_mut().element) }
745 /// Adds an element first in the list.
747 /// This operation should compute in *O*(1) time.
752 /// use std::collections::LinkedList;
754 /// let mut dl = LinkedList::new();
756 /// dl.push_front(2);
757 /// assert_eq!(dl.front().unwrap(), &2);
759 /// dl.push_front(1);
760 /// assert_eq!(dl.front().unwrap(), &1);
762 #[stable(feature = "rust1", since = "1.0.0")]
763 pub fn push_front(&mut self, elt: T) {
764 self.push_front_node(box Node::new(elt));
767 /// Removes the first element and returns it, or `None` if the list is
770 /// This operation should compute in *O*(1) time.
775 /// use std::collections::LinkedList;
777 /// let mut d = LinkedList::new();
778 /// assert_eq!(d.pop_front(), None);
782 /// assert_eq!(d.pop_front(), Some(3));
783 /// assert_eq!(d.pop_front(), Some(1));
784 /// assert_eq!(d.pop_front(), None);
786 #[stable(feature = "rust1", since = "1.0.0")]
787 pub fn pop_front(&mut self) -> Option<T> {
788 self.pop_front_node().map(Node::into_element)
791 /// Appends an element to the back of a list.
793 /// This operation should compute in *O*(1) time.
798 /// use std::collections::LinkedList;
800 /// let mut d = LinkedList::new();
803 /// assert_eq!(3, *d.back().unwrap());
805 #[stable(feature = "rust1", since = "1.0.0")]
806 pub fn push_back(&mut self, elt: T) {
807 self.push_back_node(box Node::new(elt));
810 /// Removes the last element from a list and returns it, or `None` if
813 /// This operation should compute in *O*(1) time.
818 /// use std::collections::LinkedList;
820 /// let mut d = LinkedList::new();
821 /// assert_eq!(d.pop_back(), None);
824 /// assert_eq!(d.pop_back(), Some(3));
826 #[stable(feature = "rust1", since = "1.0.0")]
827 pub fn pop_back(&mut self) -> Option<T> {
828 self.pop_back_node().map(Node::into_element)
831 /// Splits the list into two at the given index. Returns everything after the given index,
832 /// including the index.
834 /// This operation should compute in *O*(*n*) time.
838 /// Panics if `at > len`.
843 /// use std::collections::LinkedList;
845 /// let mut d = LinkedList::new();
851 /// let mut split = d.split_off(2);
853 /// assert_eq!(split.pop_front(), Some(1));
854 /// assert_eq!(split.pop_front(), None);
856 #[stable(feature = "rust1", since = "1.0.0")]
857 pub fn split_off(&mut self, at: usize) -> LinkedList<T> {
858 let len = self.len();
859 assert!(at <= len, "Cannot split off at a nonexistent index");
861 return mem::take(self);
862 } else if at == len {
866 // Below, we iterate towards the `i-1`th node, either from the start or the end,
867 // depending on which would be faster.
868 let split_node = if at - 1 <= len - 1 - (at - 1) {
869 let mut iter = self.iter_mut();
870 // instead of skipping using .skip() (which creates a new struct),
871 // we skip manually so we can access the head field without
872 // depending on implementation details of Skip
878 // better off starting from the end
879 let mut iter = self.iter_mut();
880 for _ in 0..len - 1 - (at - 1) {
885 unsafe { self.split_off_after_node(split_node, at) }
888 /// Removes the element at the given index and returns it.
890 /// This operation should compute in *O*(*n*) time.
893 /// Panics if at >= len
898 /// #![feature(linked_list_remove)]
899 /// use std::collections::LinkedList;
901 /// let mut d = LinkedList::new();
907 /// assert_eq!(d.remove(1), 2);
908 /// assert_eq!(d.remove(0), 3);
909 /// assert_eq!(d.remove(0), 1);
911 #[unstable(feature = "linked_list_remove", issue = "69210")]
912 pub fn remove(&mut self, at: usize) -> T {
913 let len = self.len();
914 assert!(at < len, "Cannot remove at an index outside of the list bounds");
916 // Below, we iterate towards the node at the given index, either from
917 // the start or the end, depending on which would be faster.
918 let offset_from_end = len - at - 1;
919 if at <= offset_from_end {
920 let mut cursor = self.cursor_front_mut();
924 cursor.remove_current().unwrap()
926 let mut cursor = self.cursor_back_mut();
927 for _ in 0..offset_from_end {
930 cursor.remove_current().unwrap()
934 /// Creates an iterator which uses a closure to determine if an element should be removed.
936 /// If the closure returns true, then the element is removed and yielded.
937 /// If the closure returns false, the element will remain in the list and will not be yielded
940 /// Note that `drain_filter` lets you mutate every element in the filter closure, regardless of
941 /// whether you choose to keep or remove it.
945 /// Splitting a list into evens and odds, reusing the original list:
948 /// #![feature(drain_filter)]
949 /// use std::collections::LinkedList;
951 /// let mut numbers: LinkedList<u32> = LinkedList::new();
952 /// numbers.extend(&[1, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15]);
954 /// let evens = numbers.drain_filter(|x| *x % 2 == 0).collect::<LinkedList<_>>();
955 /// let odds = numbers;
957 /// assert_eq!(evens.into_iter().collect::<Vec<_>>(), vec![2, 4, 6, 8, 14]);
958 /// assert_eq!(odds.into_iter().collect::<Vec<_>>(), vec![1, 3, 5, 9, 11, 13, 15]);
960 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
961 pub fn drain_filter<F>(&mut self, filter: F) -> DrainFilter<'_, T, F>
963 F: FnMut(&mut T) -> bool,
965 // avoid borrow issues.
967 let old_len = self.len;
969 DrainFilter { list: self, it, pred: filter, idx: 0, old_len }
973 #[stable(feature = "rust1", since = "1.0.0")]
974 unsafe impl<#[may_dangle] T> Drop for LinkedList<T> {
976 struct DropGuard<'a, T>(&'a mut LinkedList<T>);
978 impl<'a, T> Drop for DropGuard<'a, T> {
980 // Continue the same loop we do below. This only runs when a destructor has
981 // panicked. If another one panics this will abort.
982 while self.0.pop_front_node().is_some() {}
986 while let Some(node) = self.pop_front_node() {
987 let guard = DropGuard(self);
994 #[stable(feature = "rust1", since = "1.0.0")]
995 impl<'a, T> Iterator for Iter<'a, T> {
999 fn next(&mut self) -> Option<&'a T> {
1003 self.head.map(|node| unsafe {
1004 // Need an unbound lifetime to get 'a
1005 let node = &*node.as_ptr();
1007 self.head = node.next;
1014 fn size_hint(&self) -> (usize, Option<usize>) {
1015 (self.len, Some(self.len))
1019 fn last(mut self) -> Option<&'a T> {
1024 #[stable(feature = "rust1", since = "1.0.0")]
1025 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
1027 fn next_back(&mut self) -> Option<&'a T> {
1031 self.tail.map(|node| unsafe {
1032 // Need an unbound lifetime to get 'a
1033 let node = &*node.as_ptr();
1035 self.tail = node.prev;
1042 #[stable(feature = "rust1", since = "1.0.0")]
1043 impl<T> ExactSizeIterator for Iter<'_, T> {}
1045 #[stable(feature = "fused", since = "1.26.0")]
1046 impl<T> FusedIterator for Iter<'_, T> {}
1048 #[stable(feature = "rust1", since = "1.0.0")]
1049 impl<'a, T> Iterator for IterMut<'a, T> {
1050 type Item = &'a mut T;
1053 fn next(&mut self) -> Option<&'a mut T> {
1057 self.head.map(|node| unsafe {
1058 // Need an unbound lifetime to get 'a
1059 let node = &mut *node.as_ptr();
1061 self.head = node.next;
1068 fn size_hint(&self) -> (usize, Option<usize>) {
1069 (self.len, Some(self.len))
1073 fn last(mut self) -> Option<&'a mut T> {
1078 #[stable(feature = "rust1", since = "1.0.0")]
1079 impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
1081 fn next_back(&mut self) -> Option<&'a mut T> {
1085 self.tail.map(|node| unsafe {
1086 // Need an unbound lifetime to get 'a
1087 let node = &mut *node.as_ptr();
1089 self.tail = node.prev;
1096 #[stable(feature = "rust1", since = "1.0.0")]
1097 impl<T> ExactSizeIterator for IterMut<'_, T> {}
1099 #[stable(feature = "fused", since = "1.26.0")]
1100 impl<T> FusedIterator for IterMut<'_, T> {}
1102 impl<T> IterMut<'_, T> {
1103 /// Inserts the given element just after the element most recently returned by `.next()`.
1104 /// The inserted element does not appear in the iteration.
1106 /// This method will be removed soon.
1109 feature = "linked_list_extras",
1110 reason = "this is probably better handled by a cursor type -- we'll see",
1114 reason = "Deprecated in favor of CursorMut methods. This method will be removed soon.",
1117 pub fn insert_next(&mut self, element: T) {
1119 // `push_back` is okay with aliasing `element` references
1120 None => self.list.push_back(element),
1121 Some(head) => unsafe {
1122 let prev = match head.as_ref().prev {
1123 // `push_front` is okay with aliasing nodes
1124 None => return self.list.push_front(element),
1129 Box::leak(box Node { next: Some(head), prev: Some(prev), element }).into(),
1132 // Not creating references to entire nodes to not invalidate the
1133 // reference to `element` we handed to the user.
1134 (*prev.as_ptr()).next = node;
1135 (*head.as_ptr()).prev = node;
1142 /// Provides a reference to the next element, without changing the iterator.
1144 /// This method will be removed soon.
1147 feature = "linked_list_extras",
1148 reason = "this is probably better handled by a cursor type -- we'll see",
1152 reason = "Deprecated in favor of CursorMut methods. This method will be removed soon.",
1155 pub fn peek_next(&mut self) -> Option<&mut T> {
1159 unsafe { self.head.as_mut().map(|node| &mut node.as_mut().element) }
1164 /// A cursor over a `LinkedList`.
1166 /// A `Cursor` is like an iterator, except that it can freely seek back-and-forth.
1168 /// Cursors always rest between two elements in the list, and index in a logically circular way.
1169 /// To accommodate this, there is a "ghost" non-element that yields `None` between the head and
1170 /// tail of the list.
1172 /// When created, cursors start at the front of the list, or the "ghost" non-element if the list is empty.
1173 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1174 pub struct Cursor<'a, T: 'a> {
1176 current: Option<NonNull<Node<T>>>,
1177 list: &'a LinkedList<T>,
1180 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1181 impl<T> Clone for Cursor<'_, T> {
1182 fn clone(&self) -> Self {
1183 let Cursor { index, current, list } = *self;
1184 Cursor { index, current, list }
1188 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1189 impl<T: fmt::Debug> fmt::Debug for Cursor<'_, T> {
1190 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1191 f.debug_tuple("Cursor").field(&self.list).field(&self.index()).finish()
1195 /// A cursor over a `LinkedList` with editing operations.
1197 /// A `Cursor` is like an iterator, except that it can freely seek back-and-forth, and can
1198 /// safely mutate the list during iteration. This is because the lifetime of its yielded
1199 /// references is tied to its own lifetime, instead of just the underlying list. This means
1200 /// cursors cannot yield multiple elements at once.
1202 /// Cursors always rest between two elements in the list, and index in a logically circular way.
1203 /// To accommodate this, there is a "ghost" non-element that yields `None` between the head and
1204 /// tail of the list.
1205 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1206 pub struct CursorMut<'a, T: 'a> {
1208 current: Option<NonNull<Node<T>>>,
1209 list: &'a mut LinkedList<T>,
1212 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1213 impl<T: fmt::Debug> fmt::Debug for CursorMut<'_, T> {
1214 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1215 f.debug_tuple("CursorMut").field(&self.list).field(&self.index()).finish()
1219 impl<'a, T> Cursor<'a, T> {
1220 /// Returns the cursor position index within the `LinkedList`.
1222 /// This returns `None` if the cursor is currently pointing to the
1223 /// "ghost" non-element.
1224 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1225 pub fn index(&self) -> Option<usize> {
1226 let _ = self.current?;
1230 /// Moves the cursor to the next element of the `LinkedList`.
1232 /// If the cursor is pointing to the "ghost" non-element then this will move it to
1233 /// the first element of the `LinkedList`. If it is pointing to the last
1234 /// element of the `LinkedList` then this will move it to the "ghost" non-element.
1235 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1236 pub fn move_next(&mut self) {
1237 match self.current.take() {
1238 // We had no current element; the cursor was sitting at the start position
1239 // Next element should be the head of the list
1241 self.current = self.list.head;
1244 // We had a previous element, so let's go to its next
1245 Some(current) => unsafe {
1246 self.current = current.as_ref().next;
1252 /// Moves the cursor to the previous element of the `LinkedList`.
1254 /// If the cursor is pointing to the "ghost" non-element then this will move it to
1255 /// the last element of the `LinkedList`. If it is pointing to the first
1256 /// element of the `LinkedList` then this will move it to the "ghost" non-element.
1257 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1258 pub fn move_prev(&mut self) {
1259 match self.current.take() {
1260 // No current. We're at the start of the list. Yield None and jump to the end.
1262 self.current = self.list.tail;
1263 self.index = self.list.len().checked_sub(1).unwrap_or(0);
1265 // Have a prev. Yield it and go to the previous element.
1266 Some(current) => unsafe {
1267 self.current = current.as_ref().prev;
1268 self.index = self.index.checked_sub(1).unwrap_or_else(|| self.list.len());
1273 /// Returns a reference to the element that the cursor is currently
1276 /// This returns `None` if the cursor is currently pointing to the
1277 /// "ghost" non-element.
1278 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1279 pub fn current(&self) -> Option<&'a T> {
1280 unsafe { self.current.map(|current| &(*current.as_ptr()).element) }
1283 /// Returns a reference to the next element.
1285 /// If the cursor is pointing to the "ghost" non-element then this returns
1286 /// the first element of the `LinkedList`. If it is pointing to the last
1287 /// element of the `LinkedList` then this returns `None`.
1288 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1289 pub fn peek_next(&self) -> Option<&'a T> {
1291 let next = match self.current {
1292 None => self.list.head,
1293 Some(current) => current.as_ref().next,
1295 next.map(|next| &(*next.as_ptr()).element)
1299 /// Returns a reference to the previous element.
1301 /// If the cursor is pointing to the "ghost" non-element then this returns
1302 /// the last element of the `LinkedList`. If it is pointing to the first
1303 /// element of the `LinkedList` then this returns `None`.
1304 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1305 pub fn peek_prev(&self) -> Option<&'a T> {
1307 let prev = match self.current {
1308 None => self.list.tail,
1309 Some(current) => current.as_ref().prev,
1311 prev.map(|prev| &(*prev.as_ptr()).element)
1316 impl<'a, T> CursorMut<'a, T> {
1317 /// Returns the cursor position index within the `LinkedList`.
1319 /// This returns `None` if the cursor is currently pointing to the
1320 /// "ghost" non-element.
1321 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1322 pub fn index(&self) -> Option<usize> {
1323 let _ = self.current?;
1327 /// Moves the cursor to the next element of the `LinkedList`.
1329 /// If the cursor is pointing to the "ghost" non-element then this will move it to
1330 /// the first element of the `LinkedList`. If it is pointing to the last
1331 /// element of the `LinkedList` then this will move it to the "ghost" non-element.
1332 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1333 pub fn move_next(&mut self) {
1334 match self.current.take() {
1335 // We had no current element; the cursor was sitting at the start position
1336 // Next element should be the head of the list
1338 self.current = self.list.head;
1341 // We had a previous element, so let's go to its next
1342 Some(current) => unsafe {
1343 self.current = current.as_ref().next;
1349 /// Moves the cursor to the previous element of the `LinkedList`.
1351 /// If the cursor is pointing to the "ghost" non-element then this will move it to
1352 /// the last element of the `LinkedList`. If it is pointing to the first
1353 /// element of the `LinkedList` then this will move it to the "ghost" non-element.
1354 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1355 pub fn move_prev(&mut self) {
1356 match self.current.take() {
1357 // No current. We're at the start of the list. Yield None and jump to the end.
1359 self.current = self.list.tail;
1360 self.index = self.list.len().checked_sub(1).unwrap_or(0);
1362 // Have a prev. Yield it and go to the previous element.
1363 Some(current) => unsafe {
1364 self.current = current.as_ref().prev;
1365 self.index = self.index.checked_sub(1).unwrap_or_else(|| self.list.len());
1370 /// Returns a reference to the element that the cursor is currently
1373 /// This returns `None` if the cursor is currently pointing to the
1374 /// "ghost" non-element.
1375 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1376 pub fn current(&mut self) -> Option<&mut T> {
1377 unsafe { self.current.map(|current| &mut (*current.as_ptr()).element) }
1380 /// Returns a reference to the next element.
1382 /// If the cursor is pointing to the "ghost" non-element then this returns
1383 /// the first element of the `LinkedList`. If it is pointing to the last
1384 /// element of the `LinkedList` then this returns `None`.
1385 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1386 pub fn peek_next(&mut self) -> Option<&mut T> {
1388 let next = match self.current {
1389 None => self.list.head,
1390 Some(current) => current.as_ref().next,
1392 next.map(|next| &mut (*next.as_ptr()).element)
1396 /// Returns a reference to the previous element.
1398 /// If the cursor is pointing to the "ghost" non-element then this returns
1399 /// the last element of the `LinkedList`. If it is pointing to the first
1400 /// element of the `LinkedList` then this returns `None`.
1401 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1402 pub fn peek_prev(&mut self) -> Option<&mut T> {
1404 let prev = match self.current {
1405 None => self.list.tail,
1406 Some(current) => current.as_ref().prev,
1408 prev.map(|prev| &mut (*prev.as_ptr()).element)
1412 /// Returns a read-only cursor pointing to the current element.
1414 /// The lifetime of the returned `Cursor` is bound to that of the
1415 /// `CursorMut`, which means it cannot outlive the `CursorMut` and that the
1416 /// `CursorMut` is frozen for the lifetime of the `Cursor`.
1417 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1418 pub fn as_cursor(&self) -> Cursor<'_, T> {
1419 Cursor { list: self.list, current: self.current, index: self.index }
1423 // Now the list editing operations
1425 impl<'a, T> CursorMut<'a, T> {
1426 /// Inserts a new element into the `LinkedList` after the current one.
1428 /// If the cursor is pointing at the "ghost" non-element then the new element is
1429 /// inserted at the front of the `LinkedList`.
1430 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1431 pub fn insert_after(&mut self, item: T) {
1433 let spliced_node = Box::leak(Box::new(Node::new(item))).into();
1434 let node_next = match self.current {
1435 None => self.list.head,
1436 Some(node) => node.as_ref().next,
1438 self.list.splice_nodes(self.current, node_next, spliced_node, spliced_node, 1);
1439 if self.current.is_none() {
1440 // The "ghost" non-element's index has changed.
1441 self.index = self.list.len;
1446 /// Inserts a new element into the `LinkedList` before the current one.
1448 /// If the cursor is pointing at the "ghost" non-element then the new element is
1449 /// inserted at the end of the `LinkedList`.
1450 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1451 pub fn insert_before(&mut self, item: T) {
1453 let spliced_node = Box::leak(Box::new(Node::new(item))).into();
1454 let node_prev = match self.current {
1455 None => self.list.tail,
1456 Some(node) => node.as_ref().prev,
1458 self.list.splice_nodes(node_prev, self.current, spliced_node, spliced_node, 1);
1463 /// Removes the current element from the `LinkedList`.
1465 /// The element that was removed is returned, and the cursor is
1466 /// moved to point to the next element in the `LinkedList`.
1468 /// If the cursor is currently pointing to the "ghost" non-element then no element
1469 /// is removed and `None` is returned.
1470 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1471 pub fn remove_current(&mut self) -> Option<T> {
1472 let unlinked_node = self.current?;
1474 self.current = unlinked_node.as_ref().next;
1475 self.list.unlink_node(unlinked_node);
1476 let unlinked_node = Box::from_raw(unlinked_node.as_ptr());
1477 Some(unlinked_node.element)
1481 /// Removes the current element from the `LinkedList` without deallocating the list node.
1483 /// The node that was removed is returned as a new `LinkedList` containing only this node.
1484 /// The cursor is moved to point to the next element in the current `LinkedList`.
1486 /// If the cursor is currently pointing to the "ghost" non-element then no element
1487 /// is removed and `None` is returned.
1488 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1489 pub fn remove_current_as_list(&mut self) -> Option<LinkedList<T>> {
1490 let mut unlinked_node = self.current?;
1492 self.current = unlinked_node.as_ref().next;
1493 self.list.unlink_node(unlinked_node);
1495 unlinked_node.as_mut().prev = None;
1496 unlinked_node.as_mut().next = None;
1498 head: Some(unlinked_node),
1499 tail: Some(unlinked_node),
1501 marker: PhantomData,
1506 /// Inserts the elements from the given `LinkedList` after the current one.
1508 /// If the cursor is pointing at the "ghost" non-element then the new elements are
1509 /// inserted at the start of the `LinkedList`.
1510 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1511 pub fn splice_after(&mut self, list: LinkedList<T>) {
1513 let (splice_head, splice_tail, splice_len) = match list.detach_all_nodes() {
1514 Some(parts) => parts,
1517 let node_next = match self.current {
1518 None => self.list.head,
1519 Some(node) => node.as_ref().next,
1521 self.list.splice_nodes(self.current, node_next, splice_head, splice_tail, splice_len);
1522 if self.current.is_none() {
1523 // The "ghost" non-element's index has changed.
1524 self.index = self.list.len;
1529 /// Inserts the elements from the given `LinkedList` before the current one.
1531 /// If the cursor is pointing at the "ghost" non-element then the new elements are
1532 /// inserted at the end of the `LinkedList`.
1533 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1534 pub fn splice_before(&mut self, list: LinkedList<T>) {
1536 let (splice_head, splice_tail, splice_len) = match list.detach_all_nodes() {
1537 Some(parts) => parts,
1540 let node_prev = match self.current {
1541 None => self.list.tail,
1542 Some(node) => node.as_ref().prev,
1544 self.list.splice_nodes(node_prev, self.current, splice_head, splice_tail, splice_len);
1545 self.index += splice_len;
1549 /// Splits the list into two after the current element. This will return a
1550 /// new list consisting of everything after the cursor, with the original
1551 /// list retaining everything before.
1553 /// If the cursor is pointing at the "ghost" non-element then the entire contents
1554 /// of the `LinkedList` are moved.
1555 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1556 pub fn split_after(&mut self) -> LinkedList<T> {
1557 let split_off_idx = if self.index == self.list.len { 0 } else { self.index + 1 };
1558 if self.index == self.list.len {
1559 // The "ghost" non-element's index has changed to 0.
1562 unsafe { self.list.split_off_after_node(self.current, split_off_idx) }
1565 /// Splits the list into two before the current element. This will return a
1566 /// new list consisting of everything before the cursor, with the original
1567 /// list retaining everything after.
1569 /// If the cursor is pointing at the "ghost" non-element then the entire contents
1570 /// of the `LinkedList` are moved.
1571 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1572 pub fn split_before(&mut self) -> LinkedList<T> {
1573 let split_off_idx = self.index;
1575 unsafe { self.list.split_off_before_node(self.current, split_off_idx) }
1579 /// An iterator produced by calling `drain_filter` on LinkedList.
1580 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
1581 pub struct DrainFilter<'a, T: 'a, F: 'a>
1583 F: FnMut(&mut T) -> bool,
1585 list: &'a mut LinkedList<T>,
1586 it: Option<NonNull<Node<T>>>,
1592 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
1593 impl<T, F> Iterator for DrainFilter<'_, T, F>
1595 F: FnMut(&mut T) -> bool,
1599 fn next(&mut self) -> Option<T> {
1600 while let Some(mut node) = self.it {
1602 self.it = node.as_ref().next;
1605 if (self.pred)(&mut node.as_mut().element) {
1606 // `unlink_node` is okay with aliasing `element` references.
1607 self.list.unlink_node(node);
1608 return Some(Box::from_raw(node.as_ptr()).element);
1616 fn size_hint(&self) -> (usize, Option<usize>) {
1617 (0, Some(self.old_len - self.idx))
1621 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
1622 impl<T, F> Drop for DrainFilter<'_, T, F>
1624 F: FnMut(&mut T) -> bool,
1626 fn drop(&mut self) {
1627 struct DropGuard<'r, 'a, T, F>(&'r mut DrainFilter<'a, T, F>)
1629 F: FnMut(&mut T) -> bool;
1631 impl<'r, 'a, T, F> Drop for DropGuard<'r, 'a, T, F>
1633 F: FnMut(&mut T) -> bool,
1635 fn drop(&mut self) {
1636 self.0.for_each(drop);
1640 while let Some(item) = self.next() {
1641 let guard = DropGuard(self);
1648 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
1649 impl<T: fmt::Debug, F> fmt::Debug for DrainFilter<'_, T, F>
1651 F: FnMut(&mut T) -> bool,
1653 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1654 f.debug_tuple("DrainFilter").field(&self.list).finish()
1658 #[stable(feature = "rust1", since = "1.0.0")]
1659 impl<T> Iterator for IntoIter<T> {
1663 fn next(&mut self) -> Option<T> {
1664 self.list.pop_front()
1668 fn size_hint(&self) -> (usize, Option<usize>) {
1669 (self.list.len, Some(self.list.len))
1673 #[stable(feature = "rust1", since = "1.0.0")]
1674 impl<T> DoubleEndedIterator for IntoIter<T> {
1676 fn next_back(&mut self) -> Option<T> {
1677 self.list.pop_back()
1681 #[stable(feature = "rust1", since = "1.0.0")]
1682 impl<T> ExactSizeIterator for IntoIter<T> {}
1684 #[stable(feature = "fused", since = "1.26.0")]
1685 impl<T> FusedIterator for IntoIter<T> {}
1687 #[stable(feature = "rust1", since = "1.0.0")]
1688 impl<T> FromIterator<T> for LinkedList<T> {
1689 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
1690 let mut list = Self::new();
1696 #[stable(feature = "rust1", since = "1.0.0")]
1697 impl<T> IntoIterator for LinkedList<T> {
1699 type IntoIter = IntoIter<T>;
1701 /// Consumes the list into an iterator yielding elements by value.
1703 fn into_iter(self) -> IntoIter<T> {
1704 IntoIter { list: self }
1708 #[stable(feature = "rust1", since = "1.0.0")]
1709 impl<'a, T> IntoIterator for &'a LinkedList<T> {
1711 type IntoIter = Iter<'a, T>;
1713 fn into_iter(self) -> Iter<'a, T> {
1718 #[stable(feature = "rust1", since = "1.0.0")]
1719 impl<'a, T> IntoIterator for &'a mut LinkedList<T> {
1720 type Item = &'a mut T;
1721 type IntoIter = IterMut<'a, T>;
1723 fn into_iter(self) -> IterMut<'a, T> {
1728 #[stable(feature = "rust1", since = "1.0.0")]
1729 impl<T> Extend<T> for LinkedList<T> {
1730 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1731 <Self as SpecExtend<I>>::spec_extend(self, iter);
1735 fn extend_one(&mut self, elem: T) {
1736 self.push_back(elem);
1740 impl<I: IntoIterator> SpecExtend<I> for LinkedList<I::Item> {
1741 default fn spec_extend(&mut self, iter: I) {
1742 iter.into_iter().for_each(move |elt| self.push_back(elt));
1746 impl<T> SpecExtend<LinkedList<T>> for LinkedList<T> {
1747 fn spec_extend(&mut self, ref mut other: LinkedList<T>) {
1752 #[stable(feature = "extend_ref", since = "1.2.0")]
1753 impl<'a, T: 'a + Copy> Extend<&'a T> for LinkedList<T> {
1754 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
1755 self.extend(iter.into_iter().cloned());
1759 fn extend_one(&mut self, &elem: &'a T) {
1760 self.push_back(elem);
1764 #[stable(feature = "rust1", since = "1.0.0")]
1765 impl<T: PartialEq> PartialEq for LinkedList<T> {
1766 fn eq(&self, other: &Self) -> bool {
1767 self.len() == other.len() && self.iter().eq(other)
1770 fn ne(&self, other: &Self) -> bool {
1771 self.len() != other.len() || self.iter().ne(other)
1775 #[stable(feature = "rust1", since = "1.0.0")]
1776 impl<T: Eq> Eq for LinkedList<T> {}
1778 #[stable(feature = "rust1", since = "1.0.0")]
1779 impl<T: PartialOrd> PartialOrd for LinkedList<T> {
1780 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1781 self.iter().partial_cmp(other)
1785 #[stable(feature = "rust1", since = "1.0.0")]
1786 impl<T: Ord> Ord for LinkedList<T> {
1788 fn cmp(&self, other: &Self) -> Ordering {
1789 self.iter().cmp(other)
1793 #[stable(feature = "rust1", since = "1.0.0")]
1794 impl<T: Clone> Clone for LinkedList<T> {
1795 fn clone(&self) -> Self {
1796 self.iter().cloned().collect()
1799 fn clone_from(&mut self, other: &Self) {
1800 let mut iter_other = other.iter();
1801 if self.len() > other.len() {
1802 self.split_off(other.len());
1804 for (elem, elem_other) in self.iter_mut().zip(&mut iter_other) {
1805 elem.clone_from(elem_other);
1807 if !iter_other.is_empty() {
1808 self.extend(iter_other.cloned());
1813 #[stable(feature = "rust1", since = "1.0.0")]
1814 impl<T: fmt::Debug> fmt::Debug for LinkedList<T> {
1815 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1816 f.debug_list().entries(self).finish()
1820 #[stable(feature = "rust1", since = "1.0.0")]
1821 impl<T: Hash> Hash for LinkedList<T> {
1822 fn hash<H: Hasher>(&self, state: &mut H) {
1823 self.len().hash(state);
1830 // Ensure that `LinkedList` and its read-only iterators are covariant in their type parameters.
1832 fn assert_covariance() {
1833 fn a<'a>(x: LinkedList<&'static str>) -> LinkedList<&'a str> {
1836 fn b<'i, 'a>(x: Iter<'i, &'static str>) -> Iter<'i, &'a str> {
1839 fn c<'a>(x: IntoIter<&'static str>) -> IntoIter<&'a str> {
1844 #[stable(feature = "rust1", since = "1.0.0")]
1845 unsafe impl<T: Send> Send for LinkedList<T> {}
1847 #[stable(feature = "rust1", since = "1.0.0")]
1848 unsafe impl<T: Sync> Sync for LinkedList<T> {}
1850 #[stable(feature = "rust1", since = "1.0.0")]
1851 unsafe impl<T: Sync> Send for Iter<'_, T> {}
1853 #[stable(feature = "rust1", since = "1.0.0")]
1854 unsafe impl<T: Sync> Sync for Iter<'_, T> {}
1856 #[stable(feature = "rust1", since = "1.0.0")]
1857 unsafe impl<T: Send> Send for IterMut<'_, T> {}
1859 #[stable(feature = "rust1", since = "1.0.0")]
1860 unsafe impl<T: Sync> Sync for IterMut<'_, T> {}
1862 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1863 unsafe impl<T: Sync> Send for Cursor<'_, T> {}
1865 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1866 unsafe impl<T: Sync> Sync for Cursor<'_, T> {}
1868 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1869 unsafe impl<T: Send> Send for CursorMut<'_, T> {}
1871 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1872 unsafe impl<T: Sync> Sync for CursorMut<'_, T> {}