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::ops::{BoxPlace, InPlace, Place, Placer};
32 use core::ptr::{self, NonNull};
34 use boxed::{Box, IntermediateBox};
35 use super::SpecExtend;
37 /// A doubly-linked list with owned nodes.
39 /// The `LinkedList` allows pushing and popping elements at either end
42 /// Almost always it is better to use `Vec` or `VecDeque` instead of
43 /// `LinkedList`. In general, array-based containers are faster,
44 /// more memory efficient and make better use of CPU cache.
45 #[stable(feature = "rust1", since = "1.0.0")]
46 pub struct LinkedList<T> {
47 head: Option<NonNull<Node<T>>>,
48 tail: Option<NonNull<Node<T>>>,
50 marker: PhantomData<Box<Node<T>>>,
54 next: Option<NonNull<Node<T>>>,
55 prev: Option<NonNull<Node<T>>>,
59 /// An iterator over the elements of a `LinkedList`.
61 /// This `struct` is created by the [`iter`] method on [`LinkedList`]. See its
62 /// documentation for more.
64 /// [`iter`]: struct.LinkedList.html#method.iter
65 /// [`LinkedList`]: struct.LinkedList.html
66 #[stable(feature = "rust1", since = "1.0.0")]
67 pub struct Iter<'a, T: 'a> {
68 head: Option<NonNull<Node<T>>>,
69 tail: Option<NonNull<Node<T>>>,
71 marker: PhantomData<&'a Node<T>>,
74 #[stable(feature = "collection_debug", since = "1.17.0")]
75 impl<'a, T: 'a + fmt::Debug> fmt::Debug for Iter<'a, T> {
76 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
83 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
84 #[stable(feature = "rust1", since = "1.0.0")]
85 impl<'a, T> Clone for Iter<'a, T> {
86 fn clone(&self) -> Self {
91 /// A mutable iterator over the elements of a `LinkedList`.
93 /// This `struct` is created by the [`iter_mut`] method on [`LinkedList`]. See its
94 /// documentation for more.
96 /// [`iter_mut`]: struct.LinkedList.html#method.iter_mut
97 /// [`LinkedList`]: struct.LinkedList.html
98 #[stable(feature = "rust1", since = "1.0.0")]
99 pub struct IterMut<'a, T: 'a> {
100 list: &'a mut LinkedList<T>,
101 head: Option<NonNull<Node<T>>>,
102 tail: Option<NonNull<Node<T>>>,
106 #[stable(feature = "collection_debug", since = "1.17.0")]
107 impl<'a, T: 'a + fmt::Debug> fmt::Debug for IterMut<'a, T> {
108 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
109 f.debug_tuple("IterMut")
116 /// An owning iterator over the elements of a `LinkedList`.
118 /// This `struct` is created by the [`into_iter`] method on [`LinkedList`][`LinkedList`]
119 /// (provided by the `IntoIterator` trait). See its documentation for more.
121 /// [`into_iter`]: struct.LinkedList.html#method.into_iter
122 /// [`LinkedList`]: struct.LinkedList.html
124 #[stable(feature = "rust1", since = "1.0.0")]
125 pub struct IntoIter<T> {
129 #[stable(feature = "collection_debug", since = "1.17.0")]
130 impl<T: fmt::Debug> fmt::Debug for IntoIter<T> {
131 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
132 f.debug_tuple("IntoIter")
139 fn new(element: T) -> Self {
147 fn into_element(self: Box<Self>) -> T {
153 impl<T> LinkedList<T> {
154 /// Adds the given node to the front of the list.
156 fn push_front_node(&mut self, mut node: Box<Node<T>>) {
158 node.next = self.head;
160 let node = Some(Box::into_raw_non_null(node));
163 None => self.tail = node,
164 Some(mut head) => head.as_mut().prev = node,
172 /// Removes and returns the node at the front of the list.
174 fn pop_front_node(&mut self) -> Option<Box<Node<T>>> {
175 self.head.map(|node| unsafe {
176 let node = Box::from_raw(node.as_ptr());
177 self.head = node.next;
180 None => self.tail = None,
181 Some(mut head) => head.as_mut().prev = None,
189 /// Adds the given node to the back of the list.
191 fn push_back_node(&mut self, mut node: Box<Node<T>>) {
194 node.prev = self.tail;
195 let node = Some(Box::into_raw_non_null(node));
198 None => self.head = node,
199 Some(mut tail) => tail.as_mut().next = node,
207 /// Removes and returns the node at the back of the list.
209 fn pop_back_node(&mut self) -> Option<Box<Node<T>>> {
210 self.tail.map(|node| unsafe {
211 let node = Box::from_raw(node.as_ptr());
212 self.tail = node.prev;
215 None => self.head = None,
216 Some(mut tail) => tail.as_mut().next = None,
224 /// Unlinks the specified node from the current list.
226 /// Warning: this will not check that the provided node belongs to the current list.
228 unsafe fn unlink_node(&mut self, mut node: NonNull<Node<T>>) {
229 let node = node.as_mut();
232 Some(mut prev) => prev.as_mut().next = node.next.clone(),
233 // this node is the head node
234 None => self.head = node.next.clone(),
238 Some(mut next) => next.as_mut().prev = node.prev.clone(),
239 // this node is the tail node
240 None => self.tail = node.prev.clone(),
247 #[stable(feature = "rust1", since = "1.0.0")]
248 impl<T> Default for LinkedList<T> {
249 /// Creates an empty `LinkedList<T>`.
251 fn default() -> Self {
256 impl<T> LinkedList<T> {
257 /// Creates an empty `LinkedList`.
262 /// use std::collections::LinkedList;
264 /// let list: LinkedList<u32> = LinkedList::new();
267 #[stable(feature = "rust1", since = "1.0.0")]
268 pub fn new() -> Self {
277 /// Moves all elements from `other` to the end of the list.
279 /// This reuses all the nodes from `other` and moves them into `self`. After
280 /// this operation, `other` becomes empty.
282 /// This operation should compute in O(1) time and O(1) memory.
287 /// use std::collections::LinkedList;
289 /// let mut list1 = LinkedList::new();
290 /// list1.push_back('a');
292 /// let mut list2 = LinkedList::new();
293 /// list2.push_back('b');
294 /// list2.push_back('c');
296 /// list1.append(&mut list2);
298 /// let mut iter = list1.iter();
299 /// assert_eq!(iter.next(), Some(&'a'));
300 /// assert_eq!(iter.next(), Some(&'b'));
301 /// assert_eq!(iter.next(), Some(&'c'));
302 /// assert!(iter.next().is_none());
304 /// assert!(list2.is_empty());
306 #[stable(feature = "rust1", since = "1.0.0")]
307 pub fn append(&mut self, other: &mut Self) {
309 None => mem::swap(self, other),
311 if let Some(mut other_head) = other.head.take() {
313 tail.as_mut().next = Some(other_head);
314 other_head.as_mut().prev = Some(tail);
317 self.tail = other.tail.take();
318 self.len += mem::replace(&mut other.len, 0);
324 /// Provides a forward iterator.
329 /// use std::collections::LinkedList;
331 /// let mut list: LinkedList<u32> = LinkedList::new();
333 /// list.push_back(0);
334 /// list.push_back(1);
335 /// list.push_back(2);
337 /// let mut iter = list.iter();
338 /// assert_eq!(iter.next(), Some(&0));
339 /// assert_eq!(iter.next(), Some(&1));
340 /// assert_eq!(iter.next(), Some(&2));
341 /// assert_eq!(iter.next(), None);
344 #[stable(feature = "rust1", since = "1.0.0")]
345 pub fn iter(&self) -> Iter<T> {
354 /// Provides a forward iterator with mutable references.
359 /// use std::collections::LinkedList;
361 /// let mut list: LinkedList<u32> = LinkedList::new();
363 /// list.push_back(0);
364 /// list.push_back(1);
365 /// list.push_back(2);
367 /// for element in list.iter_mut() {
371 /// let mut iter = list.iter();
372 /// assert_eq!(iter.next(), Some(&10));
373 /// assert_eq!(iter.next(), Some(&11));
374 /// assert_eq!(iter.next(), Some(&12));
375 /// assert_eq!(iter.next(), None);
378 #[stable(feature = "rust1", since = "1.0.0")]
379 pub fn iter_mut(&mut self) -> IterMut<T> {
388 /// Returns `true` if the `LinkedList` is empty.
390 /// This operation should compute in O(1) time.
395 /// use std::collections::LinkedList;
397 /// let mut dl = LinkedList::new();
398 /// assert!(dl.is_empty());
400 /// dl.push_front("foo");
401 /// assert!(!dl.is_empty());
404 #[stable(feature = "rust1", since = "1.0.0")]
405 pub fn is_empty(&self) -> bool {
409 /// Returns the length of the `LinkedList`.
411 /// This operation should compute in O(1) time.
416 /// use std::collections::LinkedList;
418 /// let mut dl = LinkedList::new();
420 /// dl.push_front(2);
421 /// assert_eq!(dl.len(), 1);
423 /// dl.push_front(1);
424 /// assert_eq!(dl.len(), 2);
427 /// assert_eq!(dl.len(), 3);
430 #[stable(feature = "rust1", since = "1.0.0")]
431 pub fn len(&self) -> usize {
435 /// Removes all elements from the `LinkedList`.
437 /// This operation should compute in O(n) time.
442 /// use std::collections::LinkedList;
444 /// let mut dl = LinkedList::new();
446 /// dl.push_front(2);
447 /// dl.push_front(1);
448 /// assert_eq!(dl.len(), 2);
449 /// assert_eq!(dl.front(), Some(&1));
452 /// assert_eq!(dl.len(), 0);
453 /// assert_eq!(dl.front(), None);
456 #[stable(feature = "rust1", since = "1.0.0")]
457 pub fn clear(&mut self) {
461 /// Returns `true` if the `LinkedList` contains an element equal to the
467 /// use std::collections::LinkedList;
469 /// let mut list: LinkedList<u32> = LinkedList::new();
471 /// list.push_back(0);
472 /// list.push_back(1);
473 /// list.push_back(2);
475 /// assert_eq!(list.contains(&0), true);
476 /// assert_eq!(list.contains(&10), false);
478 #[stable(feature = "linked_list_contains", since = "1.12.0")]
479 pub fn contains(&self, x: &T) -> bool
480 where T: PartialEq<T>
482 self.iter().any(|e| e == x)
485 /// Provides a reference to the front element, or `None` if the list is
491 /// use std::collections::LinkedList;
493 /// let mut dl = LinkedList::new();
494 /// assert_eq!(dl.front(), None);
496 /// dl.push_front(1);
497 /// assert_eq!(dl.front(), Some(&1));
500 #[stable(feature = "rust1", since = "1.0.0")]
501 pub fn front(&self) -> Option<&T> {
503 self.head.as_ref().map(|node| &node.as_ref().element)
507 /// Provides a mutable reference to the front element, or `None` if the list
513 /// use std::collections::LinkedList;
515 /// let mut dl = LinkedList::new();
516 /// assert_eq!(dl.front(), None);
518 /// dl.push_front(1);
519 /// assert_eq!(dl.front(), Some(&1));
521 /// match dl.front_mut() {
523 /// Some(x) => *x = 5,
525 /// assert_eq!(dl.front(), Some(&5));
528 #[stable(feature = "rust1", since = "1.0.0")]
529 pub fn front_mut(&mut self) -> Option<&mut T> {
531 self.head.as_mut().map(|node| &mut node.as_mut().element)
535 /// Provides a reference to the back element, or `None` if the list is
541 /// use std::collections::LinkedList;
543 /// let mut dl = LinkedList::new();
544 /// assert_eq!(dl.back(), None);
547 /// assert_eq!(dl.back(), Some(&1));
550 #[stable(feature = "rust1", since = "1.0.0")]
551 pub fn back(&self) -> Option<&T> {
553 self.tail.as_ref().map(|node| &node.as_ref().element)
557 /// Provides a mutable reference to the back element, or `None` if the list
563 /// use std::collections::LinkedList;
565 /// let mut dl = LinkedList::new();
566 /// assert_eq!(dl.back(), None);
569 /// assert_eq!(dl.back(), Some(&1));
571 /// match dl.back_mut() {
573 /// Some(x) => *x = 5,
575 /// assert_eq!(dl.back(), Some(&5));
578 #[stable(feature = "rust1", since = "1.0.0")]
579 pub fn back_mut(&mut self) -> Option<&mut T> {
581 self.tail.as_mut().map(|node| &mut node.as_mut().element)
585 /// Adds an element first in the list.
587 /// This operation should compute in O(1) time.
592 /// use std::collections::LinkedList;
594 /// let mut dl = LinkedList::new();
596 /// dl.push_front(2);
597 /// assert_eq!(dl.front().unwrap(), &2);
599 /// dl.push_front(1);
600 /// assert_eq!(dl.front().unwrap(), &1);
602 #[stable(feature = "rust1", since = "1.0.0")]
603 pub fn push_front(&mut self, elt: T) {
604 self.push_front_node(box Node::new(elt));
607 /// Removes the first element and returns it, or `None` if the list is
610 /// This operation should compute in O(1) time.
615 /// use std::collections::LinkedList;
617 /// let mut d = LinkedList::new();
618 /// assert_eq!(d.pop_front(), None);
622 /// assert_eq!(d.pop_front(), Some(3));
623 /// assert_eq!(d.pop_front(), Some(1));
624 /// assert_eq!(d.pop_front(), None);
626 #[stable(feature = "rust1", since = "1.0.0")]
627 pub fn pop_front(&mut self) -> Option<T> {
628 self.pop_front_node().map(Node::into_element)
631 /// Appends an element to the back of a list
636 /// use std::collections::LinkedList;
638 /// let mut d = LinkedList::new();
641 /// assert_eq!(3, *d.back().unwrap());
643 #[stable(feature = "rust1", since = "1.0.0")]
644 pub fn push_back(&mut self, elt: T) {
645 self.push_back_node(box Node::new(elt));
648 /// Removes the last element from a list and returns it, or `None` if
654 /// use std::collections::LinkedList;
656 /// let mut d = LinkedList::new();
657 /// assert_eq!(d.pop_back(), None);
660 /// assert_eq!(d.pop_back(), Some(3));
662 #[stable(feature = "rust1", since = "1.0.0")]
663 pub fn pop_back(&mut self) -> Option<T> {
664 self.pop_back_node().map(Node::into_element)
667 /// Splits the list into two at the given index. Returns everything after the given index,
668 /// including the index.
670 /// This operation should compute in O(n) time.
674 /// Panics if `at > len`.
679 /// use std::collections::LinkedList;
681 /// let mut d = LinkedList::new();
687 /// let mut splitted = d.split_off(2);
689 /// assert_eq!(splitted.pop_front(), Some(1));
690 /// assert_eq!(splitted.pop_front(), None);
692 #[stable(feature = "rust1", since = "1.0.0")]
693 pub fn split_off(&mut self, at: usize) -> LinkedList<T> {
694 let len = self.len();
695 assert!(at <= len, "Cannot split off at a nonexistent index");
697 return mem::replace(self, Self::new());
698 } else if at == len {
702 // Below, we iterate towards the `i-1`th node, either from the start or the end,
703 // depending on which would be faster.
704 let split_node = if at - 1 <= len - 1 - (at - 1) {
705 let mut iter = self.iter_mut();
706 // instead of skipping using .skip() (which creates a new struct),
707 // we skip manually so we can access the head field without
708 // depending on implementation details of Skip
714 // better off starting from the end
715 let mut iter = self.iter_mut();
716 for _ in 0..len - 1 - (at - 1) {
722 // The split node is the new tail node of the first part and owns
723 // the head of the second part.
724 let second_part_head;
727 second_part_head = split_node.unwrap().as_mut().next.take();
728 if let Some(mut head) = second_part_head {
729 head.as_mut().prev = None;
733 let second_part = LinkedList {
734 head: second_part_head,
740 // Fix the tail ptr of the first part
741 self.tail = split_node;
747 /// Creates an iterator which uses a closure to determine if an element should be removed.
749 /// If the closure returns true, then the element is removed and yielded.
750 /// If the closure returns false, the element will remain in the list and will not be yielded
753 /// Note that `drain_filter` lets you mutate every element in the filter closure, regardless of
754 /// whether you choose to keep or remove it.
758 /// Splitting a list into evens and odds, reusing the original list:
761 /// #![feature(drain_filter)]
762 /// use std::collections::LinkedList;
764 /// let mut numbers: LinkedList<u32> = LinkedList::new();
765 /// numbers.extend(&[1, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15]);
767 /// let evens = numbers.drain_filter(|x| *x % 2 == 0).collect::<LinkedList<_>>();
768 /// let odds = numbers;
770 /// assert_eq!(evens.into_iter().collect::<Vec<_>>(), vec![2, 4, 6, 8, 14]);
771 /// assert_eq!(odds.into_iter().collect::<Vec<_>>(), vec![1, 3, 5, 9, 11, 13, 15]);
773 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
774 pub fn drain_filter<F>(&mut self, filter: F) -> DrainFilter<T, F>
775 where F: FnMut(&mut T) -> bool
777 // avoid borrow issues.
779 let old_len = self.len;
790 /// Returns a place for insertion at the front of the list.
792 /// Using this method with placement syntax is equivalent to
793 /// [`push_front`](#method.push_front), but may be more efficient.
798 /// #![feature(collection_placement)]
799 /// #![feature(placement_in_syntax)]
801 /// use std::collections::LinkedList;
803 /// let mut list = LinkedList::new();
804 /// list.front_place() <- 2;
805 /// list.front_place() <- 4;
806 /// assert!(list.iter().eq(&[4, 2]));
808 #[unstable(feature = "collection_placement",
809 reason = "method name and placement protocol are subject to change",
811 pub fn front_place(&mut self) -> FrontPlace<T> {
814 node: IntermediateBox::make_place(),
818 /// Returns a place for insertion at the back of the list.
820 /// Using this method with placement syntax is equivalent to [`push_back`](#method.push_back),
821 /// but may be more efficient.
826 /// #![feature(collection_placement)]
827 /// #![feature(placement_in_syntax)]
829 /// use std::collections::LinkedList;
831 /// let mut list = LinkedList::new();
832 /// list.back_place() <- 2;
833 /// list.back_place() <- 4;
834 /// assert!(list.iter().eq(&[2, 4]));
836 #[unstable(feature = "collection_placement",
837 reason = "method name and placement protocol are subject to change",
839 pub fn back_place(&mut self) -> BackPlace<T> {
842 node: IntermediateBox::make_place(),
847 #[stable(feature = "rust1", since = "1.0.0")]
848 unsafe impl<#[may_dangle] T> Drop for LinkedList<T> {
850 while let Some(_) = self.pop_front_node() {}
854 #[stable(feature = "rust1", since = "1.0.0")]
855 impl<'a, T> Iterator for Iter<'a, T> {
859 fn next(&mut self) -> Option<&'a T> {
863 self.head.map(|node| unsafe {
864 // Need an unbound lifetime to get 'a
865 let node = &*node.as_ptr();
867 self.head = node.next;
874 fn size_hint(&self) -> (usize, Option<usize>) {
875 (self.len, Some(self.len))
879 #[stable(feature = "rust1", since = "1.0.0")]
880 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
882 fn next_back(&mut self) -> Option<&'a T> {
886 self.tail.map(|node| unsafe {
887 // Need an unbound lifetime to get 'a
888 let node = &*node.as_ptr();
890 self.tail = node.prev;
897 #[stable(feature = "rust1", since = "1.0.0")]
898 impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
900 #[stable(feature = "fused", since = "1.26.0")]
901 impl<'a, T> FusedIterator for Iter<'a, T> {}
903 #[stable(feature = "rust1", since = "1.0.0")]
904 impl<'a, T> Iterator for IterMut<'a, T> {
905 type Item = &'a mut T;
908 fn next(&mut self) -> Option<&'a mut T> {
912 self.head.map(|node| unsafe {
913 // Need an unbound lifetime to get 'a
914 let node = &mut *node.as_ptr();
916 self.head = node.next;
923 fn size_hint(&self) -> (usize, Option<usize>) {
924 (self.len, Some(self.len))
928 #[stable(feature = "rust1", since = "1.0.0")]
929 impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
931 fn next_back(&mut self) -> Option<&'a mut T> {
935 self.tail.map(|node| unsafe {
936 // Need an unbound lifetime to get 'a
937 let node = &mut *node.as_ptr();
939 self.tail = node.prev;
946 #[stable(feature = "rust1", since = "1.0.0")]
947 impl<'a, T> ExactSizeIterator for IterMut<'a, T> {}
949 #[stable(feature = "fused", since = "1.26.0")]
950 impl<'a, T> FusedIterator for IterMut<'a, T> {}
952 impl<'a, T> IterMut<'a, T> {
953 /// Inserts the given element just after the element most recently returned by `.next()`.
954 /// The inserted element does not appear in the iteration.
959 /// #![feature(linked_list_extras)]
961 /// use std::collections::LinkedList;
963 /// let mut list: LinkedList<_> = vec![1, 3, 4].into_iter().collect();
966 /// let mut it = list.iter_mut();
967 /// assert_eq!(it.next().unwrap(), &1);
968 /// // insert `2` after `1`
969 /// it.insert_next(2);
972 /// let vec: Vec<_> = list.into_iter().collect();
973 /// assert_eq!(vec, [1, 2, 3, 4]);
977 #[unstable(feature = "linked_list_extras",
978 reason = "this is probably better handled by a cursor type -- we'll see",
980 pub fn insert_next(&mut self, element: T) {
982 None => self.list.push_back(element),
983 Some(mut head) => unsafe {
984 let mut prev = match head.as_ref().prev {
985 None => return self.list.push_front(element),
989 let node = Some(Box::into_raw_non_null(box Node {
995 prev.as_mut().next = node;
996 head.as_mut().prev = node;
1003 /// Provides a reference to the next element, without changing the iterator.
1008 /// #![feature(linked_list_extras)]
1010 /// use std::collections::LinkedList;
1012 /// let mut list: LinkedList<_> = vec![1, 2, 3].into_iter().collect();
1014 /// let mut it = list.iter_mut();
1015 /// assert_eq!(it.next().unwrap(), &1);
1016 /// assert_eq!(it.peek_next().unwrap(), &2);
1017 /// // We just peeked at 2, so it was not consumed from the iterator.
1018 /// assert_eq!(it.next().unwrap(), &2);
1021 #[unstable(feature = "linked_list_extras",
1022 reason = "this is probably better handled by a cursor type -- we'll see",
1024 pub fn peek_next(&mut self) -> Option<&mut T> {
1029 self.head.as_mut().map(|node| &mut node.as_mut().element)
1035 /// An iterator produced by calling `drain_filter` on LinkedList.
1036 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
1037 pub struct DrainFilter<'a, T: 'a, F: 'a>
1038 where F: FnMut(&mut T) -> bool,
1040 list: &'a mut LinkedList<T>,
1041 it: Option<NonNull<Node<T>>>,
1047 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
1048 impl<'a, T, F> Iterator for DrainFilter<'a, T, F>
1049 where F: FnMut(&mut T) -> bool,
1053 fn next(&mut self) -> Option<T> {
1054 while let Some(mut node) = self.it {
1056 self.it = node.as_ref().next;
1059 if (self.pred)(&mut node.as_mut().element) {
1060 self.list.unlink_node(node);
1061 return Some(Box::from_raw(node.as_ptr()).element);
1069 fn size_hint(&self) -> (usize, Option<usize>) {
1070 (0, Some(self.old_len - self.idx))
1074 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
1075 impl<'a, T, F> Drop for DrainFilter<'a, T, F>
1076 where F: FnMut(&mut T) -> bool,
1078 fn drop(&mut self) {
1083 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
1084 impl<'a, T: 'a + fmt::Debug, F> fmt::Debug for DrainFilter<'a, T, F>
1085 where F: FnMut(&mut T) -> bool
1087 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1088 f.debug_tuple("DrainFilter")
1094 #[stable(feature = "rust1", since = "1.0.0")]
1095 impl<T> Iterator for IntoIter<T> {
1099 fn next(&mut self) -> Option<T> {
1100 self.list.pop_front()
1104 fn size_hint(&self) -> (usize, Option<usize>) {
1105 (self.list.len, Some(self.list.len))
1109 #[stable(feature = "rust1", since = "1.0.0")]
1110 impl<T> DoubleEndedIterator for IntoIter<T> {
1112 fn next_back(&mut self) -> Option<T> {
1113 self.list.pop_back()
1117 #[stable(feature = "rust1", since = "1.0.0")]
1118 impl<T> ExactSizeIterator for IntoIter<T> {}
1120 #[stable(feature = "fused", since = "1.26.0")]
1121 impl<T> FusedIterator for IntoIter<T> {}
1123 #[stable(feature = "rust1", since = "1.0.0")]
1124 impl<T> FromIterator<T> for LinkedList<T> {
1125 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
1126 let mut list = Self::new();
1132 #[stable(feature = "rust1", since = "1.0.0")]
1133 impl<T> IntoIterator for LinkedList<T> {
1135 type IntoIter = IntoIter<T>;
1137 /// Consumes the list into an iterator yielding elements by value.
1139 fn into_iter(self) -> IntoIter<T> {
1140 IntoIter { list: self }
1144 #[stable(feature = "rust1", since = "1.0.0")]
1145 impl<'a, T> IntoIterator for &'a LinkedList<T> {
1147 type IntoIter = Iter<'a, T>;
1149 fn into_iter(self) -> Iter<'a, T> {
1154 #[stable(feature = "rust1", since = "1.0.0")]
1155 impl<'a, T> IntoIterator for &'a mut LinkedList<T> {
1156 type Item = &'a mut T;
1157 type IntoIter = IterMut<'a, T>;
1159 fn into_iter(self) -> IterMut<'a, T> {
1164 #[stable(feature = "rust1", since = "1.0.0")]
1165 impl<T> Extend<T> for LinkedList<T> {
1166 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1167 <Self as SpecExtend<I>>::spec_extend(self, iter);
1171 impl<I: IntoIterator> SpecExtend<I> for LinkedList<I::Item> {
1172 default fn spec_extend(&mut self, iter: I) {
1174 self.push_back(elt);
1179 impl<T> SpecExtend<LinkedList<T>> for LinkedList<T> {
1180 fn spec_extend(&mut self, ref mut other: LinkedList<T>) {
1185 #[stable(feature = "extend_ref", since = "1.2.0")]
1186 impl<'a, T: 'a + Copy> Extend<&'a T> for LinkedList<T> {
1187 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
1188 self.extend(iter.into_iter().cloned());
1192 #[stable(feature = "rust1", since = "1.0.0")]
1193 impl<T: PartialEq> PartialEq for LinkedList<T> {
1194 fn eq(&self, other: &Self) -> bool {
1195 self.len() == other.len() && self.iter().eq(other)
1198 fn ne(&self, other: &Self) -> bool {
1199 self.len() != other.len() || self.iter().ne(other)
1203 #[stable(feature = "rust1", since = "1.0.0")]
1204 impl<T: Eq> Eq for LinkedList<T> {}
1206 #[stable(feature = "rust1", since = "1.0.0")]
1207 impl<T: PartialOrd> PartialOrd for LinkedList<T> {
1208 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1209 self.iter().partial_cmp(other)
1213 #[stable(feature = "rust1", since = "1.0.0")]
1214 impl<T: Ord> Ord for LinkedList<T> {
1216 fn cmp(&self, other: &Self) -> Ordering {
1217 self.iter().cmp(other)
1221 #[stable(feature = "rust1", since = "1.0.0")]
1222 impl<T: Clone> Clone for LinkedList<T> {
1223 fn clone(&self) -> Self {
1224 self.iter().cloned().collect()
1228 #[stable(feature = "rust1", since = "1.0.0")]
1229 impl<T: fmt::Debug> fmt::Debug for LinkedList<T> {
1230 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1231 f.debug_list().entries(self).finish()
1235 #[stable(feature = "rust1", since = "1.0.0")]
1236 impl<T: Hash> Hash for LinkedList<T> {
1237 fn hash<H: Hasher>(&self, state: &mut H) {
1238 self.len().hash(state);
1245 unsafe fn finalize<T>(node: IntermediateBox<Node<T>>) -> Box<Node<T>> {
1246 let mut node = node.finalize();
1247 ptr::write(&mut node.next, None);
1248 ptr::write(&mut node.prev, None);
1252 /// A place for insertion at the front of a `LinkedList`.
1254 /// See [`LinkedList::front_place`](struct.LinkedList.html#method.front_place) for details.
1255 #[must_use = "places do nothing unless written to with `<-` syntax"]
1256 #[unstable(feature = "collection_placement",
1257 reason = "struct name and placement protocol are subject to change",
1259 pub struct FrontPlace<'a, T: 'a> {
1260 list: &'a mut LinkedList<T>,
1261 node: IntermediateBox<Node<T>>,
1264 #[unstable(feature = "collection_placement",
1265 reason = "struct name and placement protocol are subject to change",
1267 impl<'a, T: 'a + fmt::Debug> fmt::Debug for FrontPlace<'a, T> {
1268 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1269 f.debug_tuple("FrontPlace")
1275 #[unstable(feature = "collection_placement",
1276 reason = "placement protocol is subject to change",
1278 impl<'a, T> Placer<T> for FrontPlace<'a, T> {
1281 fn make_place(self) -> Self {
1286 #[unstable(feature = "collection_placement",
1287 reason = "placement protocol is subject to change",
1289 unsafe impl<'a, T> Place<T> for FrontPlace<'a, T> {
1290 fn pointer(&mut self) -> *mut T {
1291 unsafe { &mut (*self.node.pointer()).element }
1295 #[unstable(feature = "collection_placement",
1296 reason = "placement protocol is subject to change",
1298 impl<'a, T> InPlace<T> for FrontPlace<'a, T> {
1301 unsafe fn finalize(self) {
1302 let FrontPlace { list, node } = self;
1303 list.push_front_node(finalize(node));
1307 /// A place for insertion at the back of a `LinkedList`.
1309 /// See [`LinkedList::back_place`](struct.LinkedList.html#method.back_place) for details.
1310 #[must_use = "places do nothing unless written to with `<-` syntax"]
1311 #[unstable(feature = "collection_placement",
1312 reason = "struct name and placement protocol are subject to change",
1314 pub struct BackPlace<'a, T: 'a> {
1315 list: &'a mut LinkedList<T>,
1316 node: IntermediateBox<Node<T>>,
1319 #[unstable(feature = "collection_placement",
1320 reason = "struct name and placement protocol are subject to change",
1322 impl<'a, T: 'a + fmt::Debug> fmt::Debug for BackPlace<'a, T> {
1323 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1324 f.debug_tuple("BackPlace")
1330 #[unstable(feature = "collection_placement",
1331 reason = "placement protocol is subject to change",
1333 impl<'a, T> Placer<T> for BackPlace<'a, T> {
1336 fn make_place(self) -> Self {
1341 #[unstable(feature = "collection_placement",
1342 reason = "placement protocol is subject to change",
1344 unsafe impl<'a, T> Place<T> for BackPlace<'a, T> {
1345 fn pointer(&mut self) -> *mut T {
1346 unsafe { &mut (*self.node.pointer()).element }
1350 #[unstable(feature = "collection_placement",
1351 reason = "placement protocol is subject to change",
1353 impl<'a, T> InPlace<T> for BackPlace<'a, T> {
1356 unsafe fn finalize(self) {
1357 let BackPlace { list, node } = self;
1358 list.push_back_node(finalize(node));
1362 // Ensure that `LinkedList` and its read-only iterators are covariant in their type parameters.
1364 fn assert_covariance() {
1365 fn a<'a>(x: LinkedList<&'static str>) -> LinkedList<&'a str> {
1368 fn b<'i, 'a>(x: Iter<'i, &'static str>) -> Iter<'i, &'a str> {
1371 fn c<'a>(x: IntoIter<&'static str>) -> IntoIter<&'a str> {
1376 #[stable(feature = "rust1", since = "1.0.0")]
1377 unsafe impl<T: Send> Send for LinkedList<T> {}
1379 #[stable(feature = "rust1", since = "1.0.0")]
1380 unsafe impl<T: Sync> Sync for LinkedList<T> {}
1382 #[stable(feature = "rust1", since = "1.0.0")]
1383 unsafe impl<'a, T: Sync> Send for Iter<'a, T> {}
1385 #[stable(feature = "rust1", since = "1.0.0")]
1386 unsafe impl<'a, T: Sync> Sync for Iter<'a, T> {}
1388 #[stable(feature = "rust1", since = "1.0.0")]
1389 unsafe impl<'a, T: Send> Send for IterMut<'a, T> {}
1391 #[stable(feature = "rust1", since = "1.0.0")]
1392 unsafe impl<'a, T: Sync> Sync for IterMut<'a, T> {}
1399 use rand::{thread_rng, Rng};
1401 use super::{LinkedList, Node};
1404 fn list_from<T: Clone>(v: &[T]) -> LinkedList<T> {
1405 v.iter().cloned().collect()
1408 pub fn check_links<T>(list: &LinkedList<T>) {
1411 let mut last_ptr: Option<&Node<T>> = None;
1412 let mut node_ptr: &Node<T>;
1415 // tail node should also be None.
1416 assert!(list.tail.is_none());
1417 assert_eq!(0, list.len);
1420 Some(node) => node_ptr = &*node.as_ptr(),
1423 match (last_ptr, node_ptr.prev) {
1425 (None, _) => panic!("prev link for head"),
1426 (Some(p), Some(pptr)) => {
1427 assert_eq!(p as *const Node<T>, pptr.as_ptr() as *const Node<T>);
1429 _ => panic!("prev link is none, not good"),
1431 match node_ptr.next {
1433 last_ptr = Some(node_ptr);
1434 node_ptr = &*next.as_ptr();
1444 // verify that the tail node points to the last node.
1445 let tail = list.tail.as_ref().expect("some tail node").as_ref();
1446 assert_eq!(tail as *const Node<T>, node_ptr as *const Node<T>);
1447 // check that len matches interior links.
1448 assert_eq!(len, list.len);
1456 let mut m = LinkedList::<i32>::new();
1457 let mut n = LinkedList::new();
1460 assert_eq!(m.len(), 0);
1461 assert_eq!(n.len(), 0);
1463 // Non-empty to empty
1465 let mut m = LinkedList::new();
1466 let mut n = LinkedList::new();
1470 assert_eq!(m.len(), 1);
1471 assert_eq!(m.pop_back(), Some(2));
1472 assert_eq!(n.len(), 0);
1475 // Empty to non-empty
1477 let mut m = LinkedList::new();
1478 let mut n = LinkedList::new();
1482 assert_eq!(m.len(), 1);
1483 assert_eq!(m.pop_back(), Some(2));
1487 // Non-empty to non-empty
1488 let v = vec![1, 2, 3, 4, 5];
1489 let u = vec![9, 8, 1, 2, 3, 4, 5];
1490 let mut m = list_from(&v);
1491 let mut n = list_from(&u);
1495 sum.extend_from_slice(&u);
1496 assert_eq!(sum.len(), m.len());
1498 assert_eq!(m.pop_front(), Some(elt))
1500 assert_eq!(n.len(), 0);
1501 // let's make sure it's working properly, since we
1502 // did some direct changes to private members
1504 assert_eq!(n.len(), 1);
1505 assert_eq!(n.pop_front(), Some(3));
1510 fn test_insert_prev() {
1511 let mut m = list_from(&[0, 2, 4, 6, 8]);
1514 let mut it = m.iter_mut();
1520 it.insert_next(*elt + 1);
1521 match it.peek_next() {
1522 Some(x) => assert_eq!(*x, *elt + 2),
1523 None => assert_eq!(8, *elt),
1532 assert_eq!(m.len(), 3 + len * 2);
1533 assert_eq!(m.into_iter().collect::<Vec<_>>(),
1534 [-2, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1]);
1538 #[cfg_attr(target_os = "emscripten", ignore)]
1540 let n = list_from(&[1, 2, 3]);
1541 thread::spawn(move || {
1543 let a: &[_] = &[&1, &2, &3];
1544 assert_eq!(a, &*n.iter().collect::<Vec<_>>());
1562 // There was a bug in split_off that failed to null out the RHS's head's prev ptr.
1563 // This caused the RHS's dtor to walk up into the LHS at drop and delete all of
1566 // https://github.com/rust-lang/rust/issues/26021
1567 let mut v1 = LinkedList::new();
1572 let _ = v1.split_off(3); // Dropping this now should not cause laundry consumption
1573 assert_eq!(v1.len(), 3);
1575 assert_eq!(v1.iter().len(), 3);
1576 assert_eq!(v1.iter().collect::<Vec<_>>().len(), 3);
1580 fn test_split_off() {
1581 let mut v1 = LinkedList::new();
1588 for ix in 0..1 + v1.len() {
1589 let mut a = v1.clone();
1590 let b = a.split_off(ix);
1599 fn fuzz_test(sz: i32) {
1600 let mut m: LinkedList<_> = LinkedList::new();
1604 let r: u8 = thread_rng().next_u32() as u8;
1630 for (a, &b) in m.into_iter().zip(&v) {
1634 assert_eq!(i, v.len());
1638 fn drain_filter_test() {
1639 let mut m: LinkedList<u32> = LinkedList::new();
1640 m.extend(&[1, 2, 3, 4, 5, 6]);
1641 let deleted = m.drain_filter(|v| *v < 4).collect::<Vec<_>>();
1645 assert_eq!(deleted, &[1, 2, 3]);
1646 assert_eq!(m.into_iter().collect::<Vec<_>>(), &[4, 5, 6]);
1650 fn drain_to_empty_test() {
1651 let mut m: LinkedList<u32> = LinkedList::new();
1652 m.extend(&[1, 2, 3, 4, 5, 6]);
1653 let deleted = m.drain_filter(|_| true).collect::<Vec<_>>();
1657 assert_eq!(deleted, &[1, 2, 3, 4, 5, 6]);
1658 assert_eq!(m.into_iter().collect::<Vec<_>>(), &[]);