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,
246 /// Splices a series of nodes between two existing nodes.
248 /// Warning: this will not check that the provided node belongs to the two existing lists.
250 unsafe fn splice_nodes(
252 existing_prev: Option<NonNull<Node<T>>>,
253 existing_next: Option<NonNull<Node<T>>>,
254 mut splice_start: NonNull<Node<T>>,
255 mut splice_end: NonNull<Node<T>>,
256 splice_length: usize,
258 // This method takes care not to create multiple mutable references to whole nodes at the same time,
259 // to maintain validity of aliasing pointers into `element`.
260 if let Some(mut existing_prev) = existing_prev {
261 existing_prev.as_mut().next = Some(splice_start);
263 self.head = Some(splice_start);
265 if let Some(mut existing_next) = existing_next {
266 existing_next.as_mut().prev = Some(splice_end);
268 self.tail = Some(splice_end);
270 splice_start.as_mut().prev = existing_prev;
271 splice_end.as_mut().next = existing_next;
273 self.len += splice_length;
276 /// Detaches all nodes from a linked list as a series of nodes.
278 fn detach_all_nodes(mut self) -> Option<(NonNull<Node<T>>, NonNull<Node<T>>, usize)> {
279 let head = self.head.take();
280 let tail = self.tail.take();
281 let len = mem::replace(&mut self.len, 0);
282 if let Some(head) = head {
283 let tail = tail.unwrap_or_else(|| unsafe { core::hint::unreachable_unchecked() });
284 Some((head, tail, len))
291 unsafe fn split_off_before_node(
293 split_node: Option<NonNull<Node<T>>>,
296 // The split node is the new head node of the second part
297 if let Some(mut split_node) = split_node {
300 first_part_tail = split_node.as_mut().prev.take();
301 if let Some(mut tail) = first_part_tail {
302 tail.as_mut().next = None;
303 first_part_head = self.head;
305 first_part_head = None;
308 let first_part = LinkedList {
309 head: first_part_head,
310 tail: first_part_tail,
315 // Fix the head ptr of the second part
316 self.head = Some(split_node);
317 self.len = self.len - at;
321 mem::replace(self, LinkedList::new())
326 unsafe fn split_off_after_node(
328 split_node: Option<NonNull<Node<T>>>,
331 // The split node is the new tail node of the first part and owns
332 // the head of the second part.
333 if let Some(mut split_node) = split_node {
334 let second_part_head;
335 let second_part_tail;
336 second_part_head = split_node.as_mut().next.take();
337 if let Some(mut head) = second_part_head {
338 head.as_mut().prev = None;
339 second_part_tail = self.tail;
341 second_part_tail = None;
344 let second_part = LinkedList {
345 head: second_part_head,
346 tail: second_part_tail,
351 // Fix the tail ptr of the first part
352 self.tail = Some(split_node);
357 mem::replace(self, LinkedList::new())
362 #[stable(feature = "rust1", since = "1.0.0")]
363 impl<T> Default for LinkedList<T> {
364 /// Creates an empty `LinkedList<T>`.
366 fn default() -> Self {
371 impl<T> LinkedList<T> {
372 /// Creates an empty `LinkedList`.
377 /// use std::collections::LinkedList;
379 /// let list: LinkedList<u32> = LinkedList::new();
382 #[rustc_const_stable(feature = "const_linked_list_new", since = "1.32.0")]
383 #[stable(feature = "rust1", since = "1.0.0")]
384 pub const fn new() -> Self {
385 LinkedList { head: None, tail: None, len: 0, marker: PhantomData }
388 /// Moves all elements from `other` to the end of the list.
390 /// This reuses all the nodes from `other` and moves them into `self`. After
391 /// this operation, `other` becomes empty.
393 /// This operation should compute in O(1) time and O(1) memory.
398 /// use std::collections::LinkedList;
400 /// let mut list1 = LinkedList::new();
401 /// list1.push_back('a');
403 /// let mut list2 = LinkedList::new();
404 /// list2.push_back('b');
405 /// list2.push_back('c');
407 /// list1.append(&mut list2);
409 /// let mut iter = list1.iter();
410 /// assert_eq!(iter.next(), Some(&'a'));
411 /// assert_eq!(iter.next(), Some(&'b'));
412 /// assert_eq!(iter.next(), Some(&'c'));
413 /// assert!(iter.next().is_none());
415 /// assert!(list2.is_empty());
417 #[stable(feature = "rust1", since = "1.0.0")]
418 pub fn append(&mut self, other: &mut Self) {
420 None => mem::swap(self, other),
422 // `as_mut` is okay here because we have exclusive access to the entirety
424 if let Some(mut other_head) = other.head.take() {
426 tail.as_mut().next = Some(other_head);
427 other_head.as_mut().prev = Some(tail);
430 self.tail = other.tail.take();
431 self.len += mem::replace(&mut other.len, 0);
437 /// Moves all elements from `other` to the begin of the list.
438 #[unstable(feature = "linked_list_prepend", issue = "none")]
439 pub fn prepend(&mut self, other: &mut Self) {
441 None => mem::swap(self, other),
443 // `as_mut` is okay here because we have exclusive access to the entirety
445 if let Some(mut other_tail) = other.tail.take() {
447 head.as_mut().prev = Some(other_tail);
448 other_tail.as_mut().next = Some(head);
451 self.head = other.head.take();
452 self.len += mem::replace(&mut other.len, 0);
458 /// Provides a forward iterator.
463 /// use std::collections::LinkedList;
465 /// let mut list: LinkedList<u32> = LinkedList::new();
467 /// list.push_back(0);
468 /// list.push_back(1);
469 /// list.push_back(2);
471 /// let mut iter = list.iter();
472 /// assert_eq!(iter.next(), Some(&0));
473 /// assert_eq!(iter.next(), Some(&1));
474 /// assert_eq!(iter.next(), Some(&2));
475 /// assert_eq!(iter.next(), None);
478 #[stable(feature = "rust1", since = "1.0.0")]
479 pub fn iter(&self) -> Iter<'_, T> {
480 Iter { head: self.head, tail: self.tail, len: self.len, marker: PhantomData }
483 /// Provides a forward iterator with mutable references.
488 /// use std::collections::LinkedList;
490 /// let mut list: LinkedList<u32> = LinkedList::new();
492 /// list.push_back(0);
493 /// list.push_back(1);
494 /// list.push_back(2);
496 /// for element in list.iter_mut() {
500 /// let mut iter = list.iter();
501 /// assert_eq!(iter.next(), Some(&10));
502 /// assert_eq!(iter.next(), Some(&11));
503 /// assert_eq!(iter.next(), Some(&12));
504 /// assert_eq!(iter.next(), None);
507 #[stable(feature = "rust1", since = "1.0.0")]
508 pub fn iter_mut(&mut self) -> IterMut<'_, T> {
509 IterMut { head: self.head, tail: self.tail, len: self.len, list: self }
512 /// Provides a cursor at the front element.
514 /// The cursor is pointing to the "ghost" non-element if the list is empty.
516 #[unstable(feature = "linked_list_cursors", issue = "58533")]
517 pub fn cursor_front(&self) -> Cursor<'_, T> {
518 Cursor { index: 0, current: self.head, list: self }
521 /// Provides a cursor with editing operations at the front element.
523 /// The cursor is pointing to the "ghost" non-element if the list is empty.
525 #[unstable(feature = "linked_list_cursors", issue = "58533")]
526 pub fn cursor_front_mut(&mut self) -> CursorMut<'_, T> {
527 CursorMut { index: 0, current: self.head, list: self }
530 /// Provides a cursor at the back element.
532 /// The cursor is pointing to the "ghost" non-element if the list is empty.
534 #[unstable(feature = "linked_list_cursors", issue = "58533")]
535 pub fn cursor_back(&self) -> Cursor<'_, T> {
536 Cursor { index: self.len.checked_sub(1).unwrap_or(0), current: self.tail, list: self }
539 /// Provides a cursor with editing operations at the back element.
541 /// The cursor is pointing to the "ghost" non-element if the list is empty.
543 #[unstable(feature = "linked_list_cursors", issue = "58533")]
544 pub fn cursor_back_mut(&mut self) -> CursorMut<'_, T> {
545 CursorMut { index: self.len.checked_sub(1).unwrap_or(0), current: self.tail, list: self }
548 /// Returns `true` if the `LinkedList` is empty.
550 /// This operation should compute in O(1) time.
555 /// use std::collections::LinkedList;
557 /// let mut dl = LinkedList::new();
558 /// assert!(dl.is_empty());
560 /// dl.push_front("foo");
561 /// assert!(!dl.is_empty());
564 #[stable(feature = "rust1", since = "1.0.0")]
565 pub fn is_empty(&self) -> bool {
569 /// Returns the length of the `LinkedList`.
571 /// This operation should compute in O(1) time.
576 /// use std::collections::LinkedList;
578 /// let mut dl = LinkedList::new();
580 /// dl.push_front(2);
581 /// assert_eq!(dl.len(), 1);
583 /// dl.push_front(1);
584 /// assert_eq!(dl.len(), 2);
587 /// assert_eq!(dl.len(), 3);
590 #[stable(feature = "rust1", since = "1.0.0")]
591 pub fn len(&self) -> usize {
595 /// Removes all elements from the `LinkedList`.
597 /// This operation should compute in O(n) time.
602 /// use std::collections::LinkedList;
604 /// let mut dl = LinkedList::new();
606 /// dl.push_front(2);
607 /// dl.push_front(1);
608 /// assert_eq!(dl.len(), 2);
609 /// assert_eq!(dl.front(), Some(&1));
612 /// assert_eq!(dl.len(), 0);
613 /// assert_eq!(dl.front(), None);
616 #[stable(feature = "rust1", since = "1.0.0")]
617 pub fn clear(&mut self) {
621 /// Returns `true` if the `LinkedList` contains an element equal to the
627 /// use std::collections::LinkedList;
629 /// let mut list: LinkedList<u32> = LinkedList::new();
631 /// list.push_back(0);
632 /// list.push_back(1);
633 /// list.push_back(2);
635 /// assert_eq!(list.contains(&0), true);
636 /// assert_eq!(list.contains(&10), false);
638 #[stable(feature = "linked_list_contains", since = "1.12.0")]
639 pub fn contains(&self, x: &T) -> bool
643 self.iter().any(|e| e == x)
646 /// Provides a reference to the front element, or `None` if the list is
652 /// use std::collections::LinkedList;
654 /// let mut dl = LinkedList::new();
655 /// assert_eq!(dl.front(), None);
657 /// dl.push_front(1);
658 /// assert_eq!(dl.front(), Some(&1));
661 #[stable(feature = "rust1", since = "1.0.0")]
662 pub fn front(&self) -> Option<&T> {
663 unsafe { self.head.as_ref().map(|node| &node.as_ref().element) }
666 /// Provides a mutable reference to the front element, or `None` if the list
672 /// use std::collections::LinkedList;
674 /// let mut dl = LinkedList::new();
675 /// assert_eq!(dl.front(), None);
677 /// dl.push_front(1);
678 /// assert_eq!(dl.front(), Some(&1));
680 /// match dl.front_mut() {
682 /// Some(x) => *x = 5,
684 /// assert_eq!(dl.front(), Some(&5));
687 #[stable(feature = "rust1", since = "1.0.0")]
688 pub fn front_mut(&mut self) -> Option<&mut T> {
689 unsafe { self.head.as_mut().map(|node| &mut node.as_mut().element) }
692 /// Provides a reference to the back element, or `None` if the list is
698 /// use std::collections::LinkedList;
700 /// let mut dl = LinkedList::new();
701 /// assert_eq!(dl.back(), None);
704 /// assert_eq!(dl.back(), Some(&1));
707 #[stable(feature = "rust1", since = "1.0.0")]
708 pub fn back(&self) -> Option<&T> {
709 unsafe { self.tail.as_ref().map(|node| &node.as_ref().element) }
712 /// Provides a mutable reference to the back element, or `None` if the list
718 /// use std::collections::LinkedList;
720 /// let mut dl = LinkedList::new();
721 /// assert_eq!(dl.back(), None);
724 /// assert_eq!(dl.back(), Some(&1));
726 /// match dl.back_mut() {
728 /// Some(x) => *x = 5,
730 /// assert_eq!(dl.back(), Some(&5));
733 #[stable(feature = "rust1", since = "1.0.0")]
734 pub fn back_mut(&mut self) -> Option<&mut T> {
735 unsafe { self.tail.as_mut().map(|node| &mut node.as_mut().element) }
738 /// Adds an element first in the list.
740 /// This operation should compute in O(1) time.
745 /// use std::collections::LinkedList;
747 /// let mut dl = LinkedList::new();
749 /// dl.push_front(2);
750 /// assert_eq!(dl.front().unwrap(), &2);
752 /// dl.push_front(1);
753 /// assert_eq!(dl.front().unwrap(), &1);
755 #[stable(feature = "rust1", since = "1.0.0")]
756 pub fn push_front(&mut self, elt: T) {
757 self.push_front_node(box Node::new(elt));
760 /// Removes the first element and returns it, or `None` if the list is
763 /// This operation should compute in O(1) time.
768 /// use std::collections::LinkedList;
770 /// let mut d = LinkedList::new();
771 /// assert_eq!(d.pop_front(), None);
775 /// assert_eq!(d.pop_front(), Some(3));
776 /// assert_eq!(d.pop_front(), Some(1));
777 /// assert_eq!(d.pop_front(), None);
779 #[stable(feature = "rust1", since = "1.0.0")]
780 pub fn pop_front(&mut self) -> Option<T> {
781 self.pop_front_node().map(Node::into_element)
784 /// Appends an element to the back of a list.
786 /// This operation should compute in O(1) time.
791 /// use std::collections::LinkedList;
793 /// let mut d = LinkedList::new();
796 /// assert_eq!(3, *d.back().unwrap());
798 #[stable(feature = "rust1", since = "1.0.0")]
799 pub fn push_back(&mut self, elt: T) {
800 self.push_back_node(box Node::new(elt));
803 /// Removes the last element from a list and returns it, or `None` if
806 /// This operation should compute in O(1) time.
811 /// use std::collections::LinkedList;
813 /// let mut d = LinkedList::new();
814 /// assert_eq!(d.pop_back(), None);
817 /// assert_eq!(d.pop_back(), Some(3));
819 #[stable(feature = "rust1", since = "1.0.0")]
820 pub fn pop_back(&mut self) -> Option<T> {
821 self.pop_back_node().map(Node::into_element)
824 /// Splits the list into two at the given index. Returns everything after the given index,
825 /// including the index.
827 /// This operation should compute in O(n) time.
831 /// Panics if `at > len`.
836 /// use std::collections::LinkedList;
838 /// let mut d = LinkedList::new();
844 /// let mut split = d.split_off(2);
846 /// assert_eq!(split.pop_front(), Some(1));
847 /// assert_eq!(split.pop_front(), None);
849 #[stable(feature = "rust1", since = "1.0.0")]
850 pub fn split_off(&mut self, at: usize) -> LinkedList<T> {
851 let len = self.len();
852 assert!(at <= len, "Cannot split off at a nonexistent index");
854 return mem::take(self);
855 } else if at == len {
859 // Below, we iterate towards the `i-1`th node, either from the start or the end,
860 // depending on which would be faster.
861 let split_node = if at - 1 <= len - 1 - (at - 1) {
862 let mut iter = self.iter_mut();
863 // instead of skipping using .skip() (which creates a new struct),
864 // we skip manually so we can access the head field without
865 // depending on implementation details of Skip
871 // better off starting from the end
872 let mut iter = self.iter_mut();
873 for _ in 0..len - 1 - (at - 1) {
878 unsafe { self.split_off_after_node(split_node, at) }
881 /// Removes the element at the given index and returns it.
883 /// This operation should compute in O(n) time.
886 /// Panics if at >= len
891 /// #![feature(linked_list_remove)]
892 /// use std::collections::LinkedList;
894 /// let mut d = LinkedList::new();
900 /// assert_eq!(d.remove(1), 2);
901 /// assert_eq!(d.remove(0), 3);
902 /// assert_eq!(d.remove(0), 1);
904 #[unstable(feature = "linked_list_remove", issue = "69210")]
905 pub fn remove(&mut self, at: usize) -> T {
906 let len = self.len();
907 assert!(at < len, "Cannot remove at an index outside of the list bounds");
909 // Below, we iterate towards the node at the given index, either from
910 // the start or the end, depending on which would be faster.
911 let offset_from_end = len - at - 1;
912 if at <= offset_from_end {
913 let mut cursor = self.cursor_front_mut();
917 cursor.remove_current().unwrap()
919 let mut cursor = self.cursor_back_mut();
920 for _ in 0..offset_from_end {
923 cursor.remove_current().unwrap()
927 /// Creates an iterator which uses a closure to determine if an element should be removed.
929 /// If the closure returns true, then the element is removed and yielded.
930 /// If the closure returns false, the element will remain in the list and will not be yielded
933 /// Note that `drain_filter` lets you mutate every element in the filter closure, regardless of
934 /// whether you choose to keep or remove it.
938 /// Splitting a list into evens and odds, reusing the original list:
941 /// #![feature(drain_filter)]
942 /// use std::collections::LinkedList;
944 /// let mut numbers: LinkedList<u32> = LinkedList::new();
945 /// numbers.extend(&[1, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15]);
947 /// let evens = numbers.drain_filter(|x| *x % 2 == 0).collect::<LinkedList<_>>();
948 /// let odds = numbers;
950 /// assert_eq!(evens.into_iter().collect::<Vec<_>>(), vec![2, 4, 6, 8, 14]);
951 /// assert_eq!(odds.into_iter().collect::<Vec<_>>(), vec![1, 3, 5, 9, 11, 13, 15]);
953 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
954 pub fn drain_filter<F>(&mut self, filter: F) -> DrainFilter<'_, T, F>
956 F: FnMut(&mut T) -> bool,
958 // avoid borrow issues.
960 let old_len = self.len;
962 DrainFilter { list: self, it, pred: filter, idx: 0, old_len }
966 #[stable(feature = "rust1", since = "1.0.0")]
967 unsafe impl<#[may_dangle] T> Drop for LinkedList<T> {
969 struct DropGuard<'a, T>(&'a mut LinkedList<T>);
971 impl<'a, T> Drop for DropGuard<'a, T> {
973 // Continue the same loop we do below. This only runs when a destructor has
974 // panicked. If another one panics this will abort.
975 while let Some(_) = self.0.pop_front_node() {}
979 while let Some(node) = self.pop_front_node() {
980 let guard = DropGuard(self);
987 #[stable(feature = "rust1", since = "1.0.0")]
988 impl<'a, T> Iterator for Iter<'a, T> {
992 fn next(&mut self) -> Option<&'a T> {
996 self.head.map(|node| unsafe {
997 // Need an unbound lifetime to get 'a
998 let node = &*node.as_ptr();
1000 self.head = node.next;
1007 fn size_hint(&self) -> (usize, Option<usize>) {
1008 (self.len, Some(self.len))
1012 fn last(mut self) -> Option<&'a T> {
1017 #[stable(feature = "rust1", since = "1.0.0")]
1018 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
1020 fn next_back(&mut self) -> Option<&'a T> {
1024 self.tail.map(|node| unsafe {
1025 // Need an unbound lifetime to get 'a
1026 let node = &*node.as_ptr();
1028 self.tail = node.prev;
1035 #[stable(feature = "rust1", since = "1.0.0")]
1036 impl<T> ExactSizeIterator for Iter<'_, T> {}
1038 #[stable(feature = "fused", since = "1.26.0")]
1039 impl<T> FusedIterator for Iter<'_, T> {}
1041 #[stable(feature = "rust1", since = "1.0.0")]
1042 impl<'a, T> Iterator for IterMut<'a, T> {
1043 type Item = &'a mut T;
1046 fn next(&mut self) -> Option<&'a mut T> {
1050 self.head.map(|node| unsafe {
1051 // Need an unbound lifetime to get 'a
1052 let node = &mut *node.as_ptr();
1054 self.head = node.next;
1061 fn size_hint(&self) -> (usize, Option<usize>) {
1062 (self.len, Some(self.len))
1066 fn last(mut self) -> Option<&'a mut T> {
1071 #[stable(feature = "rust1", since = "1.0.0")]
1072 impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
1074 fn next_back(&mut self) -> Option<&'a mut T> {
1078 self.tail.map(|node| unsafe {
1079 // Need an unbound lifetime to get 'a
1080 let node = &mut *node.as_ptr();
1082 self.tail = node.prev;
1089 #[stable(feature = "rust1", since = "1.0.0")]
1090 impl<T> ExactSizeIterator for IterMut<'_, T> {}
1092 #[stable(feature = "fused", since = "1.26.0")]
1093 impl<T> FusedIterator for IterMut<'_, T> {}
1095 impl<T> IterMut<'_, T> {
1096 /// Inserts the given element just after the element most recently returned by `.next()`.
1097 /// The inserted element does not appear in the iteration.
1102 /// #![feature(linked_list_extras)]
1104 /// use std::collections::LinkedList;
1106 /// let mut list: LinkedList<_> = vec![1, 3, 4].into_iter().collect();
1109 /// let mut it = list.iter_mut();
1110 /// assert_eq!(it.next().unwrap(), &1);
1111 /// // insert `2` after `1`
1112 /// it.insert_next(2);
1115 /// let vec: Vec<_> = list.into_iter().collect();
1116 /// assert_eq!(vec, [1, 2, 3, 4]);
1121 feature = "linked_list_extras",
1122 reason = "this is probably better handled by a cursor type -- we'll see",
1125 pub fn insert_next(&mut self, element: T) {
1127 // `push_back` is okay with aliasing `element` references
1128 None => self.list.push_back(element),
1129 Some(head) => unsafe {
1130 let prev = match head.as_ref().prev {
1131 // `push_front` is okay with aliasing nodes
1132 None => return self.list.push_front(element),
1136 let node = Some(Box::into_raw_non_null(box Node {
1142 // Not creating references to entire nodes to not invalidate the
1143 // reference to `element` we handed to the user.
1144 (*prev.as_ptr()).next = node;
1145 (*head.as_ptr()).prev = node;
1152 /// Provides a reference to the next element, without changing the iterator.
1157 /// #![feature(linked_list_extras)]
1159 /// use std::collections::LinkedList;
1161 /// let mut list: LinkedList<_> = vec![1, 2, 3].into_iter().collect();
1163 /// let mut it = list.iter_mut();
1164 /// assert_eq!(it.next().unwrap(), &1);
1165 /// assert_eq!(it.peek_next().unwrap(), &2);
1166 /// // We just peeked at 2, so it was not consumed from the iterator.
1167 /// assert_eq!(it.next().unwrap(), &2);
1171 feature = "linked_list_extras",
1172 reason = "this is probably better handled by a cursor type -- we'll see",
1175 pub fn peek_next(&mut self) -> Option<&mut T> {
1179 unsafe { self.head.as_mut().map(|node| &mut node.as_mut().element) }
1184 /// A cursor over a `LinkedList`.
1186 /// A `Cursor` is like an iterator, except that it can freely seek back-and-forth.
1188 /// Cursors always rest between two elements in the list, and index in a logically circular way.
1189 /// To accommodate this, there is a "ghost" non-element that yields `None` between the head and
1190 /// tail of the list.
1192 /// When created, cursors start at the front of the list, or the "ghost" non-element if the list is empty.
1193 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1194 pub struct Cursor<'a, T: 'a> {
1196 current: Option<NonNull<Node<T>>>,
1197 list: &'a LinkedList<T>,
1200 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1201 impl<T: fmt::Debug> fmt::Debug for Cursor<'_, T> {
1202 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1203 f.debug_tuple("Cursor").field(&self.list).field(&self.index()).finish()
1207 /// A cursor over a `LinkedList` with editing operations.
1209 /// A `Cursor` is like an iterator, except that it can freely seek back-and-forth, and can
1210 /// safely mutate the list during iteration. This is because the lifetime of its yielded
1211 /// references is tied to its own lifetime, instead of just the underlying list. This means
1212 /// cursors cannot yield multiple elements at once.
1214 /// Cursors always rest between two elements in the list, and index in a logically circular way.
1215 /// To accommodate this, there is a "ghost" non-element that yields `None` between the head and
1216 /// tail of the list.
1217 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1218 pub struct CursorMut<'a, T: 'a> {
1220 current: Option<NonNull<Node<T>>>,
1221 list: &'a mut LinkedList<T>,
1224 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1225 impl<T: fmt::Debug> fmt::Debug for CursorMut<'_, T> {
1226 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1227 f.debug_tuple("CursorMut").field(&self.list).field(&self.index()).finish()
1231 impl<'a, T> Cursor<'a, T> {
1232 /// Returns the cursor position index within the `LinkedList`.
1234 /// This returns `None` if the cursor is currently pointing to the
1235 /// "ghost" non-element.
1236 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1237 pub fn index(&self) -> Option<usize> {
1238 let _ = self.current?;
1242 /// Moves the cursor to the next element of the `LinkedList`.
1244 /// If the cursor is pointing to the "ghost" non-element then this will move it to
1245 /// the first element of the `LinkedList`. If it is pointing to the last
1246 /// element of the `LinkedList` then this will move it to the "ghost" non-element.
1247 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1248 pub fn move_next(&mut self) {
1249 match self.current.take() {
1250 // We had no current element; the cursor was sitting at the start position
1251 // Next element should be the head of the list
1253 self.current = self.list.head;
1256 // We had a previous element, so let's go to its next
1257 Some(current) => unsafe {
1258 self.current = current.as_ref().next;
1264 /// Moves the cursor to the previous element of the `LinkedList`.
1266 /// If the cursor is pointing to the "ghost" non-element then this will move it to
1267 /// the last element of the `LinkedList`. If it is pointing to the first
1268 /// element of the `LinkedList` then this will move it to the "ghost" non-element.
1269 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1270 pub fn move_prev(&mut self) {
1271 match self.current.take() {
1272 // No current. We're at the start of the list. Yield None and jump to the end.
1274 self.current = self.list.tail;
1275 self.index = self.list.len().checked_sub(1).unwrap_or(0);
1277 // Have a prev. Yield it and go to the previous element.
1278 Some(current) => unsafe {
1279 self.current = current.as_ref().prev;
1280 self.index = self.index.checked_sub(1).unwrap_or_else(|| self.list.len());
1285 /// Returns a reference to the element that the cursor is currently
1288 /// This returns `None` if the cursor is currently pointing to the
1289 /// "ghost" non-element.
1290 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1291 pub fn current(&self) -> Option<&'a T> {
1292 unsafe { self.current.map(|current| &(*current.as_ptr()).element) }
1295 /// Returns a reference to the next element.
1297 /// If the cursor is pointing to the "ghost" non-element then this returns
1298 /// the first element of the `LinkedList`. If it is pointing to the last
1299 /// element of the `LinkedList` then this returns `None`.
1300 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1301 pub fn peek_next(&self) -> Option<&'a T> {
1303 let next = match self.current {
1304 None => self.list.head,
1305 Some(current) => current.as_ref().next,
1307 next.map(|next| &(*next.as_ptr()).element)
1311 /// Returns a reference to the previous element.
1313 /// If the cursor is pointing to the "ghost" non-element then this returns
1314 /// the last element of the `LinkedList`. If it is pointing to the first
1315 /// element of the `LinkedList` then this returns `None`.
1316 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1317 pub fn peek_prev(&self) -> Option<&'a T> {
1319 let prev = match self.current {
1320 None => self.list.tail,
1321 Some(current) => current.as_ref().prev,
1323 prev.map(|prev| &(*prev.as_ptr()).element)
1328 impl<'a, T> CursorMut<'a, T> {
1329 /// Returns the cursor position index within the `LinkedList`.
1331 /// This returns `None` if the cursor is currently pointing to the
1332 /// "ghost" non-element.
1333 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1334 pub fn index(&self) -> Option<usize> {
1335 let _ = self.current?;
1339 /// Moves the cursor to the next element of the `LinkedList`.
1341 /// If the cursor is pointing to the "ghost" non-element then this will move it to
1342 /// the first element of the `LinkedList`. If it is pointing to the last
1343 /// element of the `LinkedList` then this will move it to the "ghost" non-element.
1344 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1345 pub fn move_next(&mut self) {
1346 match self.current.take() {
1347 // We had no current element; the cursor was sitting at the start position
1348 // Next element should be the head of the list
1350 self.current = self.list.head;
1353 // We had a previous element, so let's go to its next
1354 Some(current) => unsafe {
1355 self.current = current.as_ref().next;
1361 /// Moves the cursor to the previous element of the `LinkedList`.
1363 /// If the cursor is pointing to the "ghost" non-element then this will move it to
1364 /// the last element of the `LinkedList`. If it is pointing to the first
1365 /// element of the `LinkedList` then this will move it to the "ghost" non-element.
1366 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1367 pub fn move_prev(&mut self) {
1368 match self.current.take() {
1369 // No current. We're at the start of the list. Yield None and jump to the end.
1371 self.current = self.list.tail;
1372 self.index = self.list.len().checked_sub(1).unwrap_or(0);
1374 // Have a prev. Yield it and go to the previous element.
1375 Some(current) => unsafe {
1376 self.current = current.as_ref().prev;
1377 self.index = self.index.checked_sub(1).unwrap_or_else(|| self.list.len());
1382 /// Returns a reference to the element that the cursor is currently
1385 /// This returns `None` if the cursor is currently pointing to the
1386 /// "ghost" non-element.
1387 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1388 pub fn current(&mut self) -> Option<&mut T> {
1389 unsafe { self.current.map(|current| &mut (*current.as_ptr()).element) }
1392 /// Returns a reference to the next element.
1394 /// If the cursor is pointing to the "ghost" non-element then this returns
1395 /// the first element of the `LinkedList`. If it is pointing to the last
1396 /// element of the `LinkedList` then this returns `None`.
1397 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1398 pub fn peek_next(&mut self) -> Option<&mut T> {
1400 let next = match self.current {
1401 None => self.list.head,
1402 Some(current) => current.as_ref().next,
1404 next.map(|next| &mut (*next.as_ptr()).element)
1408 /// Returns a reference to the previous element.
1410 /// If the cursor is pointing to the "ghost" non-element then this returns
1411 /// the last element of the `LinkedList`. If it is pointing to the first
1412 /// element of the `LinkedList` then this returns `None`.
1413 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1414 pub fn peek_prev(&mut self) -> Option<&mut T> {
1416 let prev = match self.current {
1417 None => self.list.tail,
1418 Some(current) => current.as_ref().prev,
1420 prev.map(|prev| &mut (*prev.as_ptr()).element)
1424 /// Returns a read-only cursor pointing to the current element.
1426 /// The lifetime of the returned `Cursor` is bound to that of the
1427 /// `CursorMut`, which means it cannot outlive the `CursorMut` and that the
1428 /// `CursorMut` is frozen for the lifetime of the `Cursor`.
1429 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1430 pub fn as_cursor(&self) -> Cursor<'_, T> {
1431 Cursor { list: self.list, current: self.current, index: self.index }
1435 // Now the list editing operations
1437 impl<'a, T> CursorMut<'a, T> {
1438 /// Inserts a new element into the `LinkedList` after the current one.
1440 /// If the cursor is pointing at the "ghost" non-element then the new element is
1441 /// inserted at the front of the `LinkedList`.
1442 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1443 pub fn insert_after(&mut self, item: T) {
1445 let spliced_node = Box::into_raw_non_null(Box::new(Node::new(item)));
1446 let node_next = match self.current {
1447 None => self.list.head,
1448 Some(node) => node.as_ref().next,
1450 self.list.splice_nodes(self.current, node_next, spliced_node, spliced_node, 1);
1451 if self.current.is_none() {
1452 // The "ghost" non-element's index has changed.
1453 self.index = self.list.len;
1458 /// Inserts a new element into the `LinkedList` before the current one.
1460 /// If the cursor is pointing at the "ghost" non-element then the new element is
1461 /// inserted at the end of the `LinkedList`.
1462 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1463 pub fn insert_before(&mut self, item: T) {
1465 let spliced_node = Box::into_raw_non_null(Box::new(Node::new(item)));
1466 let node_prev = match self.current {
1467 None => self.list.tail,
1468 Some(node) => node.as_ref().prev,
1470 self.list.splice_nodes(node_prev, self.current, spliced_node, spliced_node, 1);
1475 /// Removes the current element from the `LinkedList`.
1477 /// The element that was removed is returned, and the cursor is
1478 /// moved to point to the next element in the `LinkedList`.
1480 /// If the cursor is currently pointing to the "ghost" non-element then no element
1481 /// is removed and `None` is returned.
1482 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1483 pub fn remove_current(&mut self) -> Option<T> {
1484 let unlinked_node = self.current?;
1486 self.current = unlinked_node.as_ref().next;
1487 self.list.unlink_node(unlinked_node);
1488 let unlinked_node = Box::from_raw(unlinked_node.as_ptr());
1489 Some(unlinked_node.element)
1493 /// Inserts the elements from the given `LinkedList` after the current one.
1495 /// If the cursor is pointing at the "ghost" non-element then the new elements are
1496 /// inserted at the start of the `LinkedList`.
1497 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1498 pub fn splice_after(&mut self, list: LinkedList<T>) {
1500 let (splice_head, splice_tail, splice_len) = match list.detach_all_nodes() {
1501 Some(parts) => parts,
1504 let node_next = match self.current {
1505 None => self.list.head,
1506 Some(node) => node.as_ref().next,
1508 self.list.splice_nodes(self.current, node_next, splice_head, splice_tail, splice_len);
1509 if self.current.is_none() {
1510 // The "ghost" non-element's index has changed.
1511 self.index = self.list.len;
1516 /// Inserts the elements from the given `LinkedList` before the current one.
1518 /// If the cursor is pointing at the "ghost" non-element then the new elements are
1519 /// inserted at the end of the `LinkedList`.
1520 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1521 pub fn splice_before(&mut self, list: LinkedList<T>) {
1523 let (splice_head, splice_tail, splice_len) = match list.detach_all_nodes() {
1524 Some(parts) => parts,
1527 let node_prev = match self.current {
1528 None => self.list.tail,
1529 Some(node) => node.as_ref().prev,
1531 self.list.splice_nodes(node_prev, self.current, splice_head, splice_tail, splice_len);
1532 self.index += splice_len;
1536 /// Splits the list into two after the current element. This will return a
1537 /// new list consisting of everything after the cursor, with the original
1538 /// list retaining everything before.
1540 /// If the cursor is pointing at the "ghost" non-element then the entire contents
1541 /// of the `LinkedList` are moved.
1542 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1543 pub fn split_after(&mut self) -> LinkedList<T> {
1544 let split_off_idx = if self.index == self.list.len { 0 } else { self.index + 1 };
1545 if self.index == self.list.len {
1546 // The "ghost" non-element's index has changed to 0.
1549 unsafe { self.list.split_off_after_node(self.current, split_off_idx) }
1552 /// Splits the list into two before the current element. This will return a
1553 /// new list consisting of everything before the cursor, with the original
1554 /// list retaining everything after.
1556 /// If the cursor is pointing at the "ghost" non-element then the entire contents
1557 /// of the `LinkedList` are moved.
1558 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1559 pub fn split_before(&mut self) -> LinkedList<T> {
1560 let split_off_idx = self.index;
1562 unsafe { self.list.split_off_before_node(self.current, split_off_idx) }
1566 /// An iterator produced by calling `drain_filter` on LinkedList.
1567 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
1568 pub struct DrainFilter<'a, T: 'a, F: 'a>
1570 F: FnMut(&mut T) -> bool,
1572 list: &'a mut LinkedList<T>,
1573 it: Option<NonNull<Node<T>>>,
1579 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
1580 impl<T, F> Iterator for DrainFilter<'_, T, F>
1582 F: FnMut(&mut T) -> bool,
1586 fn next(&mut self) -> Option<T> {
1587 while let Some(mut node) = self.it {
1589 self.it = node.as_ref().next;
1592 if (self.pred)(&mut node.as_mut().element) {
1593 // `unlink_node` is okay with aliasing `element` references.
1594 self.list.unlink_node(node);
1595 return Some(Box::from_raw(node.as_ptr()).element);
1603 fn size_hint(&self) -> (usize, Option<usize>) {
1604 (0, Some(self.old_len - self.idx))
1608 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
1609 impl<T, F> Drop for DrainFilter<'_, T, F>
1611 F: FnMut(&mut T) -> bool,
1613 fn drop(&mut self) {
1614 struct DropGuard<'r, 'a, T, F>(&'r mut DrainFilter<'a, T, F>)
1616 F: FnMut(&mut T) -> bool;
1618 impl<'r, 'a, T, F> Drop for DropGuard<'r, 'a, T, F>
1620 F: FnMut(&mut T) -> bool,
1622 fn drop(&mut self) {
1623 self.0.for_each(drop);
1627 while let Some(item) = self.next() {
1628 let guard = DropGuard(self);
1635 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
1636 impl<T: fmt::Debug, F> fmt::Debug for DrainFilter<'_, T, F>
1638 F: FnMut(&mut T) -> bool,
1640 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1641 f.debug_tuple("DrainFilter").field(&self.list).finish()
1645 #[stable(feature = "rust1", since = "1.0.0")]
1646 impl<T> Iterator for IntoIter<T> {
1650 fn next(&mut self) -> Option<T> {
1651 self.list.pop_front()
1655 fn size_hint(&self) -> (usize, Option<usize>) {
1656 (self.list.len, Some(self.list.len))
1660 #[stable(feature = "rust1", since = "1.0.0")]
1661 impl<T> DoubleEndedIterator for IntoIter<T> {
1663 fn next_back(&mut self) -> Option<T> {
1664 self.list.pop_back()
1668 #[stable(feature = "rust1", since = "1.0.0")]
1669 impl<T> ExactSizeIterator for IntoIter<T> {}
1671 #[stable(feature = "fused", since = "1.26.0")]
1672 impl<T> FusedIterator for IntoIter<T> {}
1674 #[stable(feature = "rust1", since = "1.0.0")]
1675 impl<T> FromIterator<T> for LinkedList<T> {
1676 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
1677 let mut list = Self::new();
1683 #[stable(feature = "rust1", since = "1.0.0")]
1684 impl<T> IntoIterator for LinkedList<T> {
1686 type IntoIter = IntoIter<T>;
1688 /// Consumes the list into an iterator yielding elements by value.
1690 fn into_iter(self) -> IntoIter<T> {
1691 IntoIter { list: self }
1695 #[stable(feature = "rust1", since = "1.0.0")]
1696 impl<'a, T> IntoIterator for &'a LinkedList<T> {
1698 type IntoIter = Iter<'a, T>;
1700 fn into_iter(self) -> Iter<'a, T> {
1705 #[stable(feature = "rust1", since = "1.0.0")]
1706 impl<'a, T> IntoIterator for &'a mut LinkedList<T> {
1707 type Item = &'a mut T;
1708 type IntoIter = IterMut<'a, T>;
1710 fn into_iter(self) -> IterMut<'a, T> {
1715 #[stable(feature = "rust1", since = "1.0.0")]
1716 impl<T> Extend<T> for LinkedList<T> {
1717 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1718 <Self as SpecExtend<I>>::spec_extend(self, iter);
1722 impl<I: IntoIterator> SpecExtend<I> for LinkedList<I::Item> {
1723 default fn spec_extend(&mut self, iter: I) {
1724 iter.into_iter().for_each(move |elt| self.push_back(elt));
1728 impl<T> SpecExtend<LinkedList<T>> for LinkedList<T> {
1729 fn spec_extend(&mut self, ref mut other: LinkedList<T>) {
1734 #[stable(feature = "extend_ref", since = "1.2.0")]
1735 impl<'a, T: 'a + Copy> Extend<&'a T> for LinkedList<T> {
1736 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
1737 self.extend(iter.into_iter().cloned());
1741 #[stable(feature = "rust1", since = "1.0.0")]
1742 impl<T: PartialEq> PartialEq for LinkedList<T> {
1743 fn eq(&self, other: &Self) -> bool {
1744 self.len() == other.len() && self.iter().eq(other)
1747 fn ne(&self, other: &Self) -> bool {
1748 self.len() != other.len() || self.iter().ne(other)
1752 #[stable(feature = "rust1", since = "1.0.0")]
1753 impl<T: Eq> Eq for LinkedList<T> {}
1755 #[stable(feature = "rust1", since = "1.0.0")]
1756 impl<T: PartialOrd> PartialOrd for LinkedList<T> {
1757 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1758 self.iter().partial_cmp(other)
1762 #[stable(feature = "rust1", since = "1.0.0")]
1763 impl<T: Ord> Ord for LinkedList<T> {
1765 fn cmp(&self, other: &Self) -> Ordering {
1766 self.iter().cmp(other)
1770 #[stable(feature = "rust1", since = "1.0.0")]
1771 impl<T: Clone> Clone for LinkedList<T> {
1772 fn clone(&self) -> Self {
1773 self.iter().cloned().collect()
1776 fn clone_from(&mut self, other: &Self) {
1777 let mut iter_other = other.iter();
1778 if self.len() > other.len() {
1779 self.split_off(other.len());
1781 for (elem, elem_other) in self.iter_mut().zip(&mut iter_other) {
1782 elem.clone_from(elem_other);
1784 if !iter_other.is_empty() {
1785 self.extend(iter_other.cloned());
1790 #[stable(feature = "rust1", since = "1.0.0")]
1791 impl<T: fmt::Debug> fmt::Debug for LinkedList<T> {
1792 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1793 f.debug_list().entries(self).finish()
1797 #[stable(feature = "rust1", since = "1.0.0")]
1798 impl<T: Hash> Hash for LinkedList<T> {
1799 fn hash<H: Hasher>(&self, state: &mut H) {
1800 self.len().hash(state);
1807 // Ensure that `LinkedList` and its read-only iterators are covariant in their type parameters.
1809 fn assert_covariance() {
1810 fn a<'a>(x: LinkedList<&'static str>) -> LinkedList<&'a str> {
1813 fn b<'i, 'a>(x: Iter<'i, &'static str>) -> Iter<'i, &'a str> {
1816 fn c<'a>(x: IntoIter<&'static str>) -> IntoIter<&'a str> {
1821 #[stable(feature = "rust1", since = "1.0.0")]
1822 unsafe impl<T: Send> Send for LinkedList<T> {}
1824 #[stable(feature = "rust1", since = "1.0.0")]
1825 unsafe impl<T: Sync> Sync for LinkedList<T> {}
1827 #[stable(feature = "rust1", since = "1.0.0")]
1828 unsafe impl<T: Sync> Send for Iter<'_, T> {}
1830 #[stable(feature = "rust1", since = "1.0.0")]
1831 unsafe impl<T: Sync> Sync for Iter<'_, T> {}
1833 #[stable(feature = "rust1", since = "1.0.0")]
1834 unsafe impl<T: Send> Send for IterMut<'_, T> {}
1836 #[stable(feature = "rust1", since = "1.0.0")]
1837 unsafe impl<T: Sync> Sync for IterMut<'_, T> {}