1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! A doubly-linked list with owned nodes.
13 //! The `LinkedList` allows pushing and popping elements at either end
16 //! Almost always it is better to use `Vec` or [`VecDeque`] instead of
17 //! [`LinkedList`]. In general, array-based containers are faster,
18 //! more memory efficient and make better use of CPU cache.
20 //! [`LinkedList`]: ../linked_list/struct.LinkedList.html
21 //! [`VecDeque`]: ../vec_deque/struct.VecDeque.html
23 #![stable(feature = "rust1", since = "1.0.0")]
25 use core::cmp::Ordering;
27 use core::hash::{Hasher, Hash};
28 use core::iter::{FromIterator, FusedIterator};
29 use core::marker::PhantomData;
31 use core::ptr::NonNull;
34 use super::SpecExtend;
36 /// A doubly-linked list with owned nodes.
38 /// The `LinkedList` allows pushing and popping elements at either end
41 /// Almost always it is better to use `Vec` or `VecDeque` instead of
42 /// `LinkedList`. In general, array-based containers are faster,
43 /// more memory efficient and make better use of CPU cache.
44 #[stable(feature = "rust1", since = "1.0.0")]
45 pub struct LinkedList<T> {
46 head: Option<NonNull<Node<T>>>,
47 tail: Option<NonNull<Node<T>>>,
49 marker: PhantomData<Box<Node<T>>>,
53 next: Option<NonNull<Node<T>>>,
54 prev: Option<NonNull<Node<T>>>,
58 /// An iterator over the elements of a `LinkedList`.
60 /// This `struct` is created by the [`iter`] method on [`LinkedList`]. See its
61 /// documentation for more.
63 /// [`iter`]: struct.LinkedList.html#method.iter
64 /// [`LinkedList`]: struct.LinkedList.html
65 #[stable(feature = "rust1", since = "1.0.0")]
66 pub struct Iter<'a, T: 'a> {
67 head: Option<NonNull<Node<T>>>,
68 tail: Option<NonNull<Node<T>>>,
70 marker: PhantomData<&'a Node<T>>,
73 #[stable(feature = "collection_debug", since = "1.17.0")]
74 impl<'a, T: 'a + fmt::Debug> fmt::Debug for Iter<'a, T> {
75 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
82 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
83 #[stable(feature = "rust1", since = "1.0.0")]
84 impl<'a, T> Clone for Iter<'a, T> {
85 fn clone(&self) -> Self {
90 /// A mutable iterator over the elements of a `LinkedList`.
92 /// This `struct` is created by the [`iter_mut`] method on [`LinkedList`]. See its
93 /// documentation for more.
95 /// [`iter_mut`]: struct.LinkedList.html#method.iter_mut
96 /// [`LinkedList`]: struct.LinkedList.html
97 #[stable(feature = "rust1", since = "1.0.0")]
98 pub struct IterMut<'a, T: 'a> {
99 list: &'a mut LinkedList<T>,
100 head: Option<NonNull<Node<T>>>,
101 tail: Option<NonNull<Node<T>>>,
105 #[stable(feature = "collection_debug", since = "1.17.0")]
106 impl<'a, T: 'a + fmt::Debug> fmt::Debug for IterMut<'a, T> {
107 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
108 f.debug_tuple("IterMut")
115 /// An owning iterator over the elements of a `LinkedList`.
117 /// This `struct` is created by the [`into_iter`] method on [`LinkedList`][`LinkedList`]
118 /// (provided by the `IntoIterator` trait). See its documentation for more.
120 /// [`into_iter`]: struct.LinkedList.html#method.into_iter
121 /// [`LinkedList`]: struct.LinkedList.html
123 #[stable(feature = "rust1", since = "1.0.0")]
124 pub struct IntoIter<T> {
128 #[stable(feature = "collection_debug", since = "1.17.0")]
129 impl<T: fmt::Debug> fmt::Debug for IntoIter<T> {
130 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
131 f.debug_tuple("IntoIter")
138 fn new(element: T) -> Self {
146 fn into_element(self: Box<Self>) -> T {
152 impl<T> LinkedList<T> {
153 /// Adds the given node to the front of the list.
155 fn push_front_node(&mut self, mut node: Box<Node<T>>) {
157 node.next = self.head;
159 let node = Some(Box::into_raw_non_null(node));
162 None => self.tail = node,
163 Some(mut head) => head.as_mut().prev = node,
171 /// Removes and returns the node at the front of the list.
173 fn pop_front_node(&mut self) -> Option<Box<Node<T>>> {
174 self.head.map(|node| unsafe {
175 let node = Box::from_raw(node.as_ptr());
176 self.head = node.next;
179 None => self.tail = None,
180 Some(mut head) => head.as_mut().prev = None,
188 /// Adds the given node to the back of the list.
190 fn push_back_node(&mut self, mut node: Box<Node<T>>) {
193 node.prev = self.tail;
194 let node = Some(Box::into_raw_non_null(node));
197 None => self.head = node,
198 Some(mut tail) => tail.as_mut().next = node,
206 /// Removes and returns the node at the back of the list.
208 fn pop_back_node(&mut self) -> Option<Box<Node<T>>> {
209 self.tail.map(|node| unsafe {
210 let node = Box::from_raw(node.as_ptr());
211 self.tail = node.prev;
214 None => self.head = None,
215 Some(mut tail) => tail.as_mut().next = None,
223 /// Unlinks the specified node from the current list.
225 /// Warning: this will not check that the provided node belongs to the current list.
227 unsafe fn unlink_node(&mut self, mut node: NonNull<Node<T>>) {
228 let node = node.as_mut();
231 Some(mut prev) => prev.as_mut().next = node.next.clone(),
232 // this node is the head node
233 None => self.head = node.next.clone(),
237 Some(mut next) => next.as_mut().prev = node.prev.clone(),
238 // this node is the tail node
239 None => self.tail = node.prev.clone(),
246 #[stable(feature = "rust1", since = "1.0.0")]
247 impl<T> Default for LinkedList<T> {
248 /// Creates an empty `LinkedList<T>`.
250 fn default() -> Self {
255 impl<T> LinkedList<T> {
256 /// Creates an empty `LinkedList`.
261 /// use std::collections::LinkedList;
263 /// let list: LinkedList<u32> = LinkedList::new();
266 #[stable(feature = "rust1", since = "1.0.0")]
267 pub fn new() -> Self {
276 /// Moves all elements from `other` to the end of the list.
278 /// This reuses all the nodes from `other` and moves them into `self`. After
279 /// this operation, `other` becomes empty.
281 /// This operation should compute in O(1) time and O(1) memory.
286 /// use std::collections::LinkedList;
288 /// let mut list1 = LinkedList::new();
289 /// list1.push_back('a');
291 /// let mut list2 = LinkedList::new();
292 /// list2.push_back('b');
293 /// list2.push_back('c');
295 /// list1.append(&mut list2);
297 /// let mut iter = list1.iter();
298 /// assert_eq!(iter.next(), Some(&'a'));
299 /// assert_eq!(iter.next(), Some(&'b'));
300 /// assert_eq!(iter.next(), Some(&'c'));
301 /// assert!(iter.next().is_none());
303 /// assert!(list2.is_empty());
305 #[stable(feature = "rust1", since = "1.0.0")]
306 pub fn append(&mut self, other: &mut Self) {
308 None => mem::swap(self, other),
310 if let Some(mut other_head) = other.head.take() {
312 tail.as_mut().next = Some(other_head);
313 other_head.as_mut().prev = Some(tail);
316 self.tail = other.tail.take();
317 self.len += mem::replace(&mut other.len, 0);
323 /// Provides a forward iterator.
328 /// use std::collections::LinkedList;
330 /// let mut list: LinkedList<u32> = LinkedList::new();
332 /// list.push_back(0);
333 /// list.push_back(1);
334 /// list.push_back(2);
336 /// let mut iter = list.iter();
337 /// assert_eq!(iter.next(), Some(&0));
338 /// assert_eq!(iter.next(), Some(&1));
339 /// assert_eq!(iter.next(), Some(&2));
340 /// assert_eq!(iter.next(), None);
343 #[stable(feature = "rust1", since = "1.0.0")]
344 pub fn iter(&self) -> Iter<T> {
353 /// Provides a forward iterator with mutable references.
358 /// use std::collections::LinkedList;
360 /// let mut list: LinkedList<u32> = LinkedList::new();
362 /// list.push_back(0);
363 /// list.push_back(1);
364 /// list.push_back(2);
366 /// for element in list.iter_mut() {
370 /// let mut iter = list.iter();
371 /// assert_eq!(iter.next(), Some(&10));
372 /// assert_eq!(iter.next(), Some(&11));
373 /// assert_eq!(iter.next(), Some(&12));
374 /// assert_eq!(iter.next(), None);
377 #[stable(feature = "rust1", since = "1.0.0")]
378 pub fn iter_mut(&mut self) -> IterMut<T> {
387 /// Returns `true` if the `LinkedList` is empty.
389 /// This operation should compute in O(1) time.
394 /// use std::collections::LinkedList;
396 /// let mut dl = LinkedList::new();
397 /// assert!(dl.is_empty());
399 /// dl.push_front("foo");
400 /// assert!(!dl.is_empty());
403 #[stable(feature = "rust1", since = "1.0.0")]
404 pub fn is_empty(&self) -> bool {
408 /// Returns the length of the `LinkedList`.
410 /// This operation should compute in O(1) time.
415 /// use std::collections::LinkedList;
417 /// let mut dl = LinkedList::new();
419 /// dl.push_front(2);
420 /// assert_eq!(dl.len(), 1);
422 /// dl.push_front(1);
423 /// assert_eq!(dl.len(), 2);
426 /// assert_eq!(dl.len(), 3);
429 #[stable(feature = "rust1", since = "1.0.0")]
430 pub fn len(&self) -> usize {
434 /// Removes all elements from the `LinkedList`.
436 /// This operation should compute in O(n) time.
441 /// use std::collections::LinkedList;
443 /// let mut dl = LinkedList::new();
445 /// dl.push_front(2);
446 /// dl.push_front(1);
447 /// assert_eq!(dl.len(), 2);
448 /// assert_eq!(dl.front(), Some(&1));
451 /// assert_eq!(dl.len(), 0);
452 /// assert_eq!(dl.front(), None);
455 #[stable(feature = "rust1", since = "1.0.0")]
456 pub fn clear(&mut self) {
460 /// Returns `true` if the `LinkedList` contains an element equal to the
466 /// use std::collections::LinkedList;
468 /// let mut list: LinkedList<u32> = LinkedList::new();
470 /// list.push_back(0);
471 /// list.push_back(1);
472 /// list.push_back(2);
474 /// assert_eq!(list.contains(&0), true);
475 /// assert_eq!(list.contains(&10), false);
477 #[stable(feature = "linked_list_contains", since = "1.12.0")]
478 pub fn contains(&self, x: &T) -> bool
479 where T: PartialEq<T>
481 self.iter().any(|e| e == x)
484 /// Provides a reference to the front element, or `None` if the list is
490 /// use std::collections::LinkedList;
492 /// let mut dl = LinkedList::new();
493 /// assert_eq!(dl.front(), None);
495 /// dl.push_front(1);
496 /// assert_eq!(dl.front(), Some(&1));
499 #[stable(feature = "rust1", since = "1.0.0")]
500 pub fn front(&self) -> Option<&T> {
502 self.head.as_ref().map(|node| &node.as_ref().element)
506 /// Provides a mutable reference to the front element, or `None` if the list
512 /// use std::collections::LinkedList;
514 /// let mut dl = LinkedList::new();
515 /// assert_eq!(dl.front(), None);
517 /// dl.push_front(1);
518 /// assert_eq!(dl.front(), Some(&1));
520 /// match dl.front_mut() {
522 /// Some(x) => *x = 5,
524 /// assert_eq!(dl.front(), Some(&5));
527 #[stable(feature = "rust1", since = "1.0.0")]
528 pub fn front_mut(&mut self) -> Option<&mut T> {
530 self.head.as_mut().map(|node| &mut node.as_mut().element)
534 /// Provides a reference to the back element, or `None` if the list is
540 /// use std::collections::LinkedList;
542 /// let mut dl = LinkedList::new();
543 /// assert_eq!(dl.back(), None);
546 /// assert_eq!(dl.back(), Some(&1));
549 #[stable(feature = "rust1", since = "1.0.0")]
550 pub fn back(&self) -> Option<&T> {
552 self.tail.as_ref().map(|node| &node.as_ref().element)
556 /// Provides a mutable reference to the back element, or `None` if the list
562 /// use std::collections::LinkedList;
564 /// let mut dl = LinkedList::new();
565 /// assert_eq!(dl.back(), None);
568 /// assert_eq!(dl.back(), Some(&1));
570 /// match dl.back_mut() {
572 /// Some(x) => *x = 5,
574 /// assert_eq!(dl.back(), Some(&5));
577 #[stable(feature = "rust1", since = "1.0.0")]
578 pub fn back_mut(&mut self) -> Option<&mut T> {
580 self.tail.as_mut().map(|node| &mut node.as_mut().element)
584 /// Adds an element first in the list.
586 /// This operation should compute in O(1) time.
591 /// use std::collections::LinkedList;
593 /// let mut dl = LinkedList::new();
595 /// dl.push_front(2);
596 /// assert_eq!(dl.front().unwrap(), &2);
598 /// dl.push_front(1);
599 /// assert_eq!(dl.front().unwrap(), &1);
601 #[stable(feature = "rust1", since = "1.0.0")]
602 pub fn push_front(&mut self, elt: T) {
603 self.push_front_node(box Node::new(elt));
606 /// Removes the first element and returns it, or `None` if the list is
609 /// This operation should compute in O(1) time.
614 /// use std::collections::LinkedList;
616 /// let mut d = LinkedList::new();
617 /// assert_eq!(d.pop_front(), None);
621 /// assert_eq!(d.pop_front(), Some(3));
622 /// assert_eq!(d.pop_front(), Some(1));
623 /// assert_eq!(d.pop_front(), None);
625 #[stable(feature = "rust1", since = "1.0.0")]
626 pub fn pop_front(&mut self) -> Option<T> {
627 self.pop_front_node().map(Node::into_element)
630 /// Appends an element to the back of a list
635 /// use std::collections::LinkedList;
637 /// let mut d = LinkedList::new();
640 /// assert_eq!(3, *d.back().unwrap());
642 #[stable(feature = "rust1", since = "1.0.0")]
643 pub fn push_back(&mut self, elt: T) {
644 self.push_back_node(box Node::new(elt));
647 /// Removes the last element from a list and returns it, or `None` if
653 /// use std::collections::LinkedList;
655 /// let mut d = LinkedList::new();
656 /// assert_eq!(d.pop_back(), None);
659 /// assert_eq!(d.pop_back(), Some(3));
661 #[stable(feature = "rust1", since = "1.0.0")]
662 pub fn pop_back(&mut self) -> Option<T> {
663 self.pop_back_node().map(Node::into_element)
666 /// Splits the list into two at the given index. Returns everything after the given index,
667 /// including the index.
669 /// This operation should compute in O(n) time.
673 /// Panics if `at > len`.
678 /// use std::collections::LinkedList;
680 /// let mut d = LinkedList::new();
686 /// let mut splitted = d.split_off(2);
688 /// assert_eq!(splitted.pop_front(), Some(1));
689 /// assert_eq!(splitted.pop_front(), None);
691 #[stable(feature = "rust1", since = "1.0.0")]
692 pub fn split_off(&mut self, at: usize) -> LinkedList<T> {
693 let len = self.len();
694 assert!(at <= len, "Cannot split off at a nonexistent index");
696 return mem::replace(self, Self::new());
697 } else if at == len {
701 // Below, we iterate towards the `i-1`th node, either from the start or the end,
702 // depending on which would be faster.
703 let split_node = if at - 1 <= len - 1 - (at - 1) {
704 let mut iter = self.iter_mut();
705 // instead of skipping using .skip() (which creates a new struct),
706 // we skip manually so we can access the head field without
707 // depending on implementation details of Skip
713 // better off starting from the end
714 let mut iter = self.iter_mut();
715 for _ in 0..len - 1 - (at - 1) {
721 // The split node is the new tail node of the first part and owns
722 // the head of the second part.
723 let second_part_head;
726 second_part_head = split_node.unwrap().as_mut().next.take();
727 if let Some(mut head) = second_part_head {
728 head.as_mut().prev = None;
732 let second_part = LinkedList {
733 head: second_part_head,
739 // Fix the tail ptr of the first part
740 self.tail = split_node;
746 /// Creates an iterator which uses a closure to determine if an element should be removed.
748 /// If the closure returns true, then the element is removed and yielded.
749 /// If the closure returns false, the element will remain in the list and will not be yielded
752 /// Note that `drain_filter` lets you mutate every element in the filter closure, regardless of
753 /// whether you choose to keep or remove it.
757 /// Splitting a list into evens and odds, reusing the original list:
760 /// #![feature(drain_filter)]
761 /// use std::collections::LinkedList;
763 /// let mut numbers: LinkedList<u32> = LinkedList::new();
764 /// numbers.extend(&[1, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15]);
766 /// let evens = numbers.drain_filter(|x| *x % 2 == 0).collect::<LinkedList<_>>();
767 /// let odds = numbers;
769 /// assert_eq!(evens.into_iter().collect::<Vec<_>>(), vec![2, 4, 6, 8, 14]);
770 /// assert_eq!(odds.into_iter().collect::<Vec<_>>(), vec![1, 3, 5, 9, 11, 13, 15]);
772 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
773 pub fn drain_filter<F>(&mut self, filter: F) -> DrainFilter<T, F>
774 where F: FnMut(&mut T) -> bool
776 // avoid borrow issues.
778 let old_len = self.len;
790 #[stable(feature = "rust1", since = "1.0.0")]
791 unsafe impl<#[may_dangle] T> Drop for LinkedList<T> {
793 while let Some(_) = self.pop_front_node() {}
797 #[stable(feature = "rust1", since = "1.0.0")]
798 impl<'a, T> Iterator for Iter<'a, T> {
802 fn next(&mut self) -> Option<&'a T> {
806 self.head.map(|node| unsafe {
807 // Need an unbound lifetime to get 'a
808 let node = &*node.as_ptr();
810 self.head = node.next;
817 fn size_hint(&self) -> (usize, Option<usize>) {
818 (self.len, Some(self.len))
822 #[stable(feature = "rust1", since = "1.0.0")]
823 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
825 fn next_back(&mut self) -> Option<&'a T> {
829 self.tail.map(|node| unsafe {
830 // Need an unbound lifetime to get 'a
831 let node = &*node.as_ptr();
833 self.tail = node.prev;
840 #[stable(feature = "rust1", since = "1.0.0")]
841 impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
843 #[stable(feature = "fused", since = "1.26.0")]
844 impl<'a, T> FusedIterator for Iter<'a, T> {}
846 #[stable(feature = "rust1", since = "1.0.0")]
847 impl<'a, T> Iterator for IterMut<'a, T> {
848 type Item = &'a mut T;
851 fn next(&mut self) -> Option<&'a mut T> {
855 self.head.map(|node| unsafe {
856 // Need an unbound lifetime to get 'a
857 let node = &mut *node.as_ptr();
859 self.head = node.next;
866 fn size_hint(&self) -> (usize, Option<usize>) {
867 (self.len, Some(self.len))
871 #[stable(feature = "rust1", since = "1.0.0")]
872 impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
874 fn next_back(&mut self) -> Option<&'a mut T> {
878 self.tail.map(|node| unsafe {
879 // Need an unbound lifetime to get 'a
880 let node = &mut *node.as_ptr();
882 self.tail = node.prev;
889 #[stable(feature = "rust1", since = "1.0.0")]
890 impl<'a, T> ExactSizeIterator for IterMut<'a, T> {}
892 #[stable(feature = "fused", since = "1.26.0")]
893 impl<'a, T> FusedIterator for IterMut<'a, T> {}
895 impl<'a, T> IterMut<'a, T> {
896 /// Inserts the given element just after the element most recently returned by `.next()`.
897 /// The inserted element does not appear in the iteration.
902 /// #![feature(linked_list_extras)]
904 /// use std::collections::LinkedList;
906 /// let mut list: LinkedList<_> = vec![1, 3, 4].into_iter().collect();
909 /// let mut it = list.iter_mut();
910 /// assert_eq!(it.next().unwrap(), &1);
911 /// // insert `2` after `1`
912 /// it.insert_next(2);
915 /// let vec: Vec<_> = list.into_iter().collect();
916 /// assert_eq!(vec, [1, 2, 3, 4]);
920 #[unstable(feature = "linked_list_extras",
921 reason = "this is probably better handled by a cursor type -- we'll see",
923 pub fn insert_next(&mut self, element: T) {
925 None => self.list.push_back(element),
926 Some(mut head) => unsafe {
927 let mut prev = match head.as_ref().prev {
928 None => return self.list.push_front(element),
932 let node = Some(Box::into_raw_non_null(box Node {
938 prev.as_mut().next = node;
939 head.as_mut().prev = node;
946 /// Provides a reference to the next element, without changing the iterator.
951 /// #![feature(linked_list_extras)]
953 /// use std::collections::LinkedList;
955 /// let mut list: LinkedList<_> = vec![1, 2, 3].into_iter().collect();
957 /// let mut it = list.iter_mut();
958 /// assert_eq!(it.next().unwrap(), &1);
959 /// assert_eq!(it.peek_next().unwrap(), &2);
960 /// // We just peeked at 2, so it was not consumed from the iterator.
961 /// assert_eq!(it.next().unwrap(), &2);
964 #[unstable(feature = "linked_list_extras",
965 reason = "this is probably better handled by a cursor type -- we'll see",
967 pub fn peek_next(&mut self) -> Option<&mut T> {
972 self.head.as_mut().map(|node| &mut node.as_mut().element)
978 /// An iterator produced by calling `drain_filter` on LinkedList.
979 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
980 pub struct DrainFilter<'a, T: 'a, F: 'a>
981 where F: FnMut(&mut T) -> bool,
983 list: &'a mut LinkedList<T>,
984 it: Option<NonNull<Node<T>>>,
990 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
991 impl<'a, T, F> Iterator for DrainFilter<'a, T, F>
992 where F: FnMut(&mut T) -> bool,
996 fn next(&mut self) -> Option<T> {
997 while let Some(mut node) = self.it {
999 self.it = node.as_ref().next;
1002 if (self.pred)(&mut node.as_mut().element) {
1003 self.list.unlink_node(node);
1004 return Some(Box::from_raw(node.as_ptr()).element);
1012 fn size_hint(&self) -> (usize, Option<usize>) {
1013 (0, Some(self.old_len - self.idx))
1017 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
1018 impl<'a, T, F> Drop for DrainFilter<'a, T, F>
1019 where F: FnMut(&mut T) -> bool,
1021 fn drop(&mut self) {
1022 self.for_each(drop);
1026 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
1027 impl<'a, T: 'a + fmt::Debug, F> fmt::Debug for DrainFilter<'a, T, F>
1028 where F: FnMut(&mut T) -> bool
1030 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1031 f.debug_tuple("DrainFilter")
1037 #[stable(feature = "rust1", since = "1.0.0")]
1038 impl<T> Iterator for IntoIter<T> {
1042 fn next(&mut self) -> Option<T> {
1043 self.list.pop_front()
1047 fn size_hint(&self) -> (usize, Option<usize>) {
1048 (self.list.len, Some(self.list.len))
1052 #[stable(feature = "rust1", since = "1.0.0")]
1053 impl<T> DoubleEndedIterator for IntoIter<T> {
1055 fn next_back(&mut self) -> Option<T> {
1056 self.list.pop_back()
1060 #[stable(feature = "rust1", since = "1.0.0")]
1061 impl<T> ExactSizeIterator for IntoIter<T> {}
1063 #[stable(feature = "fused", since = "1.26.0")]
1064 impl<T> FusedIterator for IntoIter<T> {}
1066 #[stable(feature = "rust1", since = "1.0.0")]
1067 impl<T> FromIterator<T> for LinkedList<T> {
1068 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
1069 let mut list = Self::new();
1075 #[stable(feature = "rust1", since = "1.0.0")]
1076 impl<T> IntoIterator for LinkedList<T> {
1078 type IntoIter = IntoIter<T>;
1080 /// Consumes the list into an iterator yielding elements by value.
1082 fn into_iter(self) -> IntoIter<T> {
1083 IntoIter { list: self }
1087 #[stable(feature = "rust1", since = "1.0.0")]
1088 impl<'a, T> IntoIterator for &'a LinkedList<T> {
1090 type IntoIter = Iter<'a, T>;
1092 fn into_iter(self) -> Iter<'a, T> {
1097 #[stable(feature = "rust1", since = "1.0.0")]
1098 impl<'a, T> IntoIterator for &'a mut LinkedList<T> {
1099 type Item = &'a mut T;
1100 type IntoIter = IterMut<'a, T>;
1102 fn into_iter(self) -> IterMut<'a, T> {
1107 #[stable(feature = "rust1", since = "1.0.0")]
1108 impl<T> Extend<T> for LinkedList<T> {
1109 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1110 <Self as SpecExtend<I>>::spec_extend(self, iter);
1114 impl<I: IntoIterator> SpecExtend<I> for LinkedList<I::Item> {
1115 default fn spec_extend(&mut self, iter: I) {
1117 self.push_back(elt);
1122 impl<T> SpecExtend<LinkedList<T>> for LinkedList<T> {
1123 fn spec_extend(&mut self, ref mut other: LinkedList<T>) {
1128 #[stable(feature = "extend_ref", since = "1.2.0")]
1129 impl<'a, T: 'a + Copy> Extend<&'a T> for LinkedList<T> {
1130 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
1131 self.extend(iter.into_iter().cloned());
1135 #[stable(feature = "rust1", since = "1.0.0")]
1136 impl<T: PartialEq> PartialEq for LinkedList<T> {
1137 fn eq(&self, other: &Self) -> bool {
1138 self.len() == other.len() && self.iter().eq(other)
1141 fn ne(&self, other: &Self) -> bool {
1142 self.len() != other.len() || self.iter().ne(other)
1146 #[stable(feature = "rust1", since = "1.0.0")]
1147 impl<T: Eq> Eq for LinkedList<T> {}
1149 #[stable(feature = "rust1", since = "1.0.0")]
1150 impl<T: PartialOrd> PartialOrd for LinkedList<T> {
1151 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1152 self.iter().partial_cmp(other)
1156 #[stable(feature = "rust1", since = "1.0.0")]
1157 impl<T: Ord> Ord for LinkedList<T> {
1159 fn cmp(&self, other: &Self) -> Ordering {
1160 self.iter().cmp(other)
1164 #[stable(feature = "rust1", since = "1.0.0")]
1165 impl<T: Clone> Clone for LinkedList<T> {
1166 fn clone(&self) -> Self {
1167 self.iter().cloned().collect()
1171 #[stable(feature = "rust1", since = "1.0.0")]
1172 impl<T: fmt::Debug> fmt::Debug for LinkedList<T> {
1173 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1174 f.debug_list().entries(self).finish()
1178 #[stable(feature = "rust1", since = "1.0.0")]
1179 impl<T: Hash> Hash for LinkedList<T> {
1180 fn hash<H: Hasher>(&self, state: &mut H) {
1181 self.len().hash(state);
1188 // Ensure that `LinkedList` and its read-only iterators are covariant in their type parameters.
1190 fn assert_covariance() {
1191 fn a<'a>(x: LinkedList<&'static str>) -> LinkedList<&'a str> {
1194 fn b<'i, 'a>(x: Iter<'i, &'static str>) -> Iter<'i, &'a str> {
1197 fn c<'a>(x: IntoIter<&'static str>) -> IntoIter<&'a str> {
1202 #[stable(feature = "rust1", since = "1.0.0")]
1203 unsafe impl<T: Send> Send for LinkedList<T> {}
1205 #[stable(feature = "rust1", since = "1.0.0")]
1206 unsafe impl<T: Sync> Sync for LinkedList<T> {}
1208 #[stable(feature = "rust1", since = "1.0.0")]
1209 unsafe impl<'a, T: Sync> Send for Iter<'a, T> {}
1211 #[stable(feature = "rust1", since = "1.0.0")]
1212 unsafe impl<'a, T: Sync> Sync for Iter<'a, T> {}
1214 #[stable(feature = "rust1", since = "1.0.0")]
1215 unsafe impl<'a, T: Send> Send for IterMut<'a, T> {}
1217 #[stable(feature = "rust1", since = "1.0.0")]
1218 unsafe impl<'a, T: Sync> Sync for IterMut<'a, T> {}
1225 use rand::{thread_rng, RngCore};
1227 use super::{LinkedList, Node};
1230 fn list_from<T: Clone>(v: &[T]) -> LinkedList<T> {
1231 v.iter().cloned().collect()
1234 pub fn check_links<T>(list: &LinkedList<T>) {
1237 let mut last_ptr: Option<&Node<T>> = None;
1238 let mut node_ptr: &Node<T>;
1241 // tail node should also be None.
1242 assert!(list.tail.is_none());
1243 assert_eq!(0, list.len);
1246 Some(node) => node_ptr = &*node.as_ptr(),
1249 match (last_ptr, node_ptr.prev) {
1251 (None, _) => panic!("prev link for head"),
1252 (Some(p), Some(pptr)) => {
1253 assert_eq!(p as *const Node<T>, pptr.as_ptr() as *const Node<T>);
1255 _ => panic!("prev link is none, not good"),
1257 match node_ptr.next {
1259 last_ptr = Some(node_ptr);
1260 node_ptr = &*next.as_ptr();
1270 // verify that the tail node points to the last node.
1271 let tail = list.tail.as_ref().expect("some tail node").as_ref();
1272 assert_eq!(tail as *const Node<T>, node_ptr as *const Node<T>);
1273 // check that len matches interior links.
1274 assert_eq!(len, list.len);
1282 let mut m = LinkedList::<i32>::new();
1283 let mut n = LinkedList::new();
1286 assert_eq!(m.len(), 0);
1287 assert_eq!(n.len(), 0);
1289 // Non-empty to empty
1291 let mut m = LinkedList::new();
1292 let mut n = LinkedList::new();
1296 assert_eq!(m.len(), 1);
1297 assert_eq!(m.pop_back(), Some(2));
1298 assert_eq!(n.len(), 0);
1301 // Empty to non-empty
1303 let mut m = LinkedList::new();
1304 let mut n = LinkedList::new();
1308 assert_eq!(m.len(), 1);
1309 assert_eq!(m.pop_back(), Some(2));
1313 // Non-empty to non-empty
1314 let v = vec![1, 2, 3, 4, 5];
1315 let u = vec![9, 8, 1, 2, 3, 4, 5];
1316 let mut m = list_from(&v);
1317 let mut n = list_from(&u);
1321 sum.extend_from_slice(&u);
1322 assert_eq!(sum.len(), m.len());
1324 assert_eq!(m.pop_front(), Some(elt))
1326 assert_eq!(n.len(), 0);
1327 // let's make sure it's working properly, since we
1328 // did some direct changes to private members
1330 assert_eq!(n.len(), 1);
1331 assert_eq!(n.pop_front(), Some(3));
1336 fn test_insert_prev() {
1337 let mut m = list_from(&[0, 2, 4, 6, 8]);
1340 let mut it = m.iter_mut();
1346 it.insert_next(*elt + 1);
1347 match it.peek_next() {
1348 Some(x) => assert_eq!(*x, *elt + 2),
1349 None => assert_eq!(8, *elt),
1358 assert_eq!(m.len(), 3 + len * 2);
1359 assert_eq!(m.into_iter().collect::<Vec<_>>(),
1360 [-2, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1]);
1364 #[cfg_attr(target_os = "emscripten", ignore)]
1366 let n = list_from(&[1, 2, 3]);
1367 thread::spawn(move || {
1369 let a: &[_] = &[&1, &2, &3];
1370 assert_eq!(a, &*n.iter().collect::<Vec<_>>());
1388 // There was a bug in split_off that failed to null out the RHS's head's prev ptr.
1389 // This caused the RHS's dtor to walk up into the LHS at drop and delete all of
1392 // https://github.com/rust-lang/rust/issues/26021
1393 let mut v1 = LinkedList::new();
1398 let _ = v1.split_off(3); // Dropping this now should not cause laundry consumption
1399 assert_eq!(v1.len(), 3);
1401 assert_eq!(v1.iter().len(), 3);
1402 assert_eq!(v1.iter().collect::<Vec<_>>().len(), 3);
1406 fn test_split_off() {
1407 let mut v1 = LinkedList::new();
1414 for ix in 0..1 + v1.len() {
1415 let mut a = v1.clone();
1416 let b = a.split_off(ix);
1425 fn fuzz_test(sz: i32) {
1426 let mut m: LinkedList<_> = LinkedList::new();
1430 let r: u8 = thread_rng().next_u32() as u8;
1456 for (a, &b) in m.into_iter().zip(&v) {
1460 assert_eq!(i, v.len());
1464 fn drain_filter_test() {
1465 let mut m: LinkedList<u32> = LinkedList::new();
1466 m.extend(&[1, 2, 3, 4, 5, 6]);
1467 let deleted = m.drain_filter(|v| *v < 4).collect::<Vec<_>>();
1471 assert_eq!(deleted, &[1, 2, 3]);
1472 assert_eq!(m.into_iter().collect::<Vec<_>>(), &[4, 5, 6]);
1476 fn drain_to_empty_test() {
1477 let mut m: LinkedList<u32> = LinkedList::new();
1478 m.extend(&[1, 2, 3, 4, 5, 6]);
1479 let deleted = m.drain_filter(|_| true).collect::<Vec<_>>();
1483 assert_eq!(deleted, &[1, 2, 3, 4, 5, 6]);
1484 assert_eq!(m.into_iter().collect::<Vec<_>>(), &[]);