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 alloc::boxed::{Box, IntermediateBox};
26 use core::cmp::Ordering;
28 use core::hash::{Hasher, Hash};
29 use core::iter::{FromIterator, FusedIterator};
30 use core::marker::PhantomData;
32 use core::ops::{BoxPlace, InPlace, Place, Placer};
33 use core::ptr::{self, Shared};
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<Shared<Node<T>>>,
48 tail: Option<Shared<Node<T>>>,
50 marker: PhantomData<Box<Node<T>>>,
54 next: Option<Shared<Node<T>>>,
55 prev: Option<Shared<Node<T>>>,
59 /// An iterator over references to the elements of a `LinkedList`.
60 #[stable(feature = "rust1", since = "1.0.0")]
61 pub struct Iter<'a, T: 'a> {
62 head: Option<Shared<Node<T>>>,
63 tail: Option<Shared<Node<T>>>,
65 marker: PhantomData<&'a Node<T>>,
68 // FIXME #19839: deriving is too aggressive on the bounds (T doesn't need to be Clone).
69 #[stable(feature = "rust1", since = "1.0.0")]
70 impl<'a, T> Clone for Iter<'a, T> {
71 fn clone(&self) -> Self {
76 /// An iterator over mutable references to the elements of a `LinkedList`.
77 #[stable(feature = "rust1", since = "1.0.0")]
78 pub struct IterMut<'a, T: 'a> {
79 list: &'a mut LinkedList<T>,
80 head: Option<Shared<Node<T>>>,
81 tail: Option<Shared<Node<T>>>,
85 /// An iterator over the elements of a `LinkedList`.
87 #[stable(feature = "rust1", since = "1.0.0")]
88 pub struct IntoIter<T> {
93 fn new(element: T) -> Self {
101 fn into_element(self: Box<Self>) -> T {
107 impl<T> LinkedList<T> {
108 /// Adds the given node to the front of the list.
110 fn push_front_node(&mut self, mut node: Box<Node<T>>) {
112 node.next = self.head;
114 let node = Some(Shared::new(Box::into_raw(node)));
117 None => self.tail = node,
118 Some(head) => (**head).prev = node,
126 /// Removes and returns the node at the front of the list.
128 fn pop_front_node(&mut self) -> Option<Box<Node<T>>> {
129 self.head.map(|node| unsafe {
130 let node = Box::from_raw(*node);
131 self.head = node.next;
134 None => self.tail = None,
135 Some(head) => (**head).prev = None,
143 /// Adds the given node to the back of the list.
145 fn push_back_node(&mut self, mut node: Box<Node<T>>) {
148 node.prev = self.tail;
149 let node = Some(Shared::new(Box::into_raw(node)));
152 None => self.head = node,
153 Some(tail) => (**tail).next = node,
161 /// Removes and returns the node at the back of the list.
163 fn pop_back_node(&mut self) -> Option<Box<Node<T>>> {
164 self.tail.map(|node| unsafe {
165 let node = Box::from_raw(*node);
166 self.tail = node.prev;
169 None => self.head = None,
170 Some(tail) => (**tail).next = None,
179 #[stable(feature = "rust1", since = "1.0.0")]
180 impl<T> Default for LinkedList<T> {
181 /// Creates an empty `LinkedList<T>`.
183 fn default() -> Self {
188 impl<T> LinkedList<T> {
189 /// Creates an empty `LinkedList`.
194 /// use std::collections::LinkedList;
196 /// let list: LinkedList<u32> = LinkedList::new();
199 #[stable(feature = "rust1", since = "1.0.0")]
200 pub fn new() -> Self {
209 /// Moves all elements from `other` to the end of the list.
211 /// This reuses all the nodes from `other` and moves them into `self`. After
212 /// this operation, `other` becomes empty.
214 /// This operation should compute in O(1) time and O(1) memory.
219 /// use std::collections::LinkedList;
221 /// let mut list1 = LinkedList::new();
222 /// list1.push_back('a');
224 /// let mut list2 = LinkedList::new();
225 /// list2.push_back('b');
226 /// list2.push_back('c');
228 /// list1.append(&mut list2);
230 /// let mut iter = list1.iter();
231 /// assert_eq!(iter.next(), Some(&'a'));
232 /// assert_eq!(iter.next(), Some(&'b'));
233 /// assert_eq!(iter.next(), Some(&'c'));
234 /// assert!(iter.next().is_none());
236 /// assert!(list2.is_empty());
238 #[stable(feature = "rust1", since = "1.0.0")]
239 pub fn append(&mut self, other: &mut Self) {
241 None => mem::swap(self, other),
243 if let Some(other_head) = other.head.take() {
245 (**tail).next = Some(other_head);
246 (**other_head).prev = Some(tail);
249 self.tail = other.tail.take();
250 self.len += mem::replace(&mut other.len, 0);
256 /// Provides a forward iterator.
261 /// use std::collections::LinkedList;
263 /// let mut list: LinkedList<u32> = LinkedList::new();
265 /// list.push_back(0);
266 /// list.push_back(1);
267 /// list.push_back(2);
269 /// let mut iter = list.iter();
270 /// assert_eq!(iter.next(), Some(&0));
271 /// assert_eq!(iter.next(), Some(&1));
272 /// assert_eq!(iter.next(), Some(&2));
273 /// assert_eq!(iter.next(), None);
276 #[stable(feature = "rust1", since = "1.0.0")]
277 pub fn iter(&self) -> Iter<T> {
286 /// Provides a forward iterator with mutable references.
291 /// use std::collections::LinkedList;
293 /// let mut list: LinkedList<u32> = LinkedList::new();
295 /// list.push_back(0);
296 /// list.push_back(1);
297 /// list.push_back(2);
299 /// for element in list.iter_mut() {
303 /// let mut iter = list.iter();
304 /// assert_eq!(iter.next(), Some(&10));
305 /// assert_eq!(iter.next(), Some(&11));
306 /// assert_eq!(iter.next(), Some(&12));
307 /// assert_eq!(iter.next(), None);
310 #[stable(feature = "rust1", since = "1.0.0")]
311 pub fn iter_mut(&mut self) -> IterMut<T> {
320 /// Returns `true` if the `LinkedList` is empty.
322 /// This operation should compute in O(1) time.
327 /// use std::collections::LinkedList;
329 /// let mut dl = LinkedList::new();
330 /// assert!(dl.is_empty());
332 /// dl.push_front("foo");
333 /// assert!(!dl.is_empty());
336 #[stable(feature = "rust1", since = "1.0.0")]
337 pub fn is_empty(&self) -> bool {
341 /// Returns the length of the `LinkedList`.
343 /// This operation should compute in O(1) time.
348 /// use std::collections::LinkedList;
350 /// let mut dl = LinkedList::new();
352 /// dl.push_front(2);
353 /// assert_eq!(dl.len(), 1);
355 /// dl.push_front(1);
356 /// assert_eq!(dl.len(), 2);
359 /// assert_eq!(dl.len(), 3);
362 #[stable(feature = "rust1", since = "1.0.0")]
363 pub fn len(&self) -> usize {
367 /// Removes all elements from the `LinkedList`.
369 /// This operation should compute in O(n) time.
374 /// use std::collections::LinkedList;
376 /// let mut dl = LinkedList::new();
378 /// dl.push_front(2);
379 /// dl.push_front(1);
380 /// assert_eq!(dl.len(), 2);
381 /// assert_eq!(dl.front(), Some(&1));
384 /// assert_eq!(dl.len(), 0);
385 /// assert_eq!(dl.front(), None);
388 #[stable(feature = "rust1", since = "1.0.0")]
389 pub fn clear(&mut self) {
393 /// Returns `true` if the `LinkedList` contains an element equal to the
399 /// use std::collections::LinkedList;
401 /// let mut list: LinkedList<u32> = LinkedList::new();
403 /// list.push_back(0);
404 /// list.push_back(1);
405 /// list.push_back(2);
407 /// assert_eq!(list.contains(&0), true);
408 /// assert_eq!(list.contains(&10), false);
410 #[stable(feature = "linked_list_contains", since = "1.12.0")]
411 pub fn contains(&self, x: &T) -> bool
412 where T: PartialEq<T>
414 self.iter().any(|e| e == x)
417 /// Provides a reference to the front element, or `None` if the list is
423 /// use std::collections::LinkedList;
425 /// let mut dl = LinkedList::new();
426 /// assert_eq!(dl.front(), None);
428 /// dl.push_front(1);
429 /// assert_eq!(dl.front(), Some(&1));
432 #[stable(feature = "rust1", since = "1.0.0")]
433 pub fn front(&self) -> Option<&T> {
434 self.head.map(|node| unsafe { &(**node).element })
437 /// Provides a mutable reference to the front element, or `None` if the list
443 /// use std::collections::LinkedList;
445 /// let mut dl = LinkedList::new();
446 /// assert_eq!(dl.front(), None);
448 /// dl.push_front(1);
449 /// assert_eq!(dl.front(), Some(&1));
451 /// match dl.front_mut() {
453 /// Some(x) => *x = 5,
455 /// assert_eq!(dl.front(), Some(&5));
458 #[stable(feature = "rust1", since = "1.0.0")]
459 pub fn front_mut(&mut self) -> Option<&mut T> {
460 self.head.map(|node| unsafe { &mut (**node).element })
463 /// Provides a reference to the back element, or `None` if the list is
469 /// use std::collections::LinkedList;
471 /// let mut dl = LinkedList::new();
472 /// assert_eq!(dl.back(), None);
475 /// assert_eq!(dl.back(), Some(&1));
478 #[stable(feature = "rust1", since = "1.0.0")]
479 pub fn back(&self) -> Option<&T> {
480 self.tail.map(|node| unsafe { &(**node).element })
483 /// Provides a mutable reference to the back element, or `None` if the list
489 /// use std::collections::LinkedList;
491 /// let mut dl = LinkedList::new();
492 /// assert_eq!(dl.back(), None);
495 /// assert_eq!(dl.back(), Some(&1));
497 /// match dl.back_mut() {
499 /// Some(x) => *x = 5,
501 /// assert_eq!(dl.back(), Some(&5));
504 #[stable(feature = "rust1", since = "1.0.0")]
505 pub fn back_mut(&mut self) -> Option<&mut T> {
506 self.tail.map(|node| unsafe { &mut (**node).element })
509 /// Adds an element first in the list.
511 /// This operation should compute in O(1) time.
516 /// use std::collections::LinkedList;
518 /// let mut dl = LinkedList::new();
520 /// dl.push_front(2);
521 /// assert_eq!(dl.front().unwrap(), &2);
523 /// dl.push_front(1);
524 /// assert_eq!(dl.front().unwrap(), &1);
526 #[stable(feature = "rust1", since = "1.0.0")]
527 pub fn push_front(&mut self, elt: T) {
528 self.push_front_node(box Node::new(elt));
531 /// Removes the first element and returns it, or `None` if the list is
534 /// This operation should compute in O(1) time.
539 /// use std::collections::LinkedList;
541 /// let mut d = LinkedList::new();
542 /// assert_eq!(d.pop_front(), None);
546 /// assert_eq!(d.pop_front(), Some(3));
547 /// assert_eq!(d.pop_front(), Some(1));
548 /// assert_eq!(d.pop_front(), None);
550 #[stable(feature = "rust1", since = "1.0.0")]
551 pub fn pop_front(&mut self) -> Option<T> {
552 self.pop_front_node().map(Node::into_element)
555 /// Appends an element to the back of a list
560 /// use std::collections::LinkedList;
562 /// let mut d = LinkedList::new();
565 /// assert_eq!(3, *d.back().unwrap());
567 #[stable(feature = "rust1", since = "1.0.0")]
568 pub fn push_back(&mut self, elt: T) {
569 self.push_back_node(box Node::new(elt));
572 /// Removes the last element from a list and returns it, or `None` if
578 /// use std::collections::LinkedList;
580 /// let mut d = LinkedList::new();
581 /// assert_eq!(d.pop_back(), None);
584 /// assert_eq!(d.pop_back(), Some(3));
586 #[stable(feature = "rust1", since = "1.0.0")]
587 pub fn pop_back(&mut self) -> Option<T> {
588 self.pop_back_node().map(Node::into_element)
591 /// Splits the list into two at the given index. Returns everything after the given index,
592 /// including the index.
596 /// Panics if `at > len`.
598 /// This operation should compute in O(n) time.
603 /// use std::collections::LinkedList;
605 /// let mut d = LinkedList::new();
611 /// let mut splitted = d.split_off(2);
613 /// assert_eq!(splitted.pop_front(), Some(1));
614 /// assert_eq!(splitted.pop_front(), None);
616 #[stable(feature = "rust1", since = "1.0.0")]
617 pub fn split_off(&mut self, at: usize) -> LinkedList<T> {
618 let len = self.len();
619 assert!(at <= len, "Cannot split off at a nonexistent index");
621 return mem::replace(self, Self::new());
622 } else if at == len {
626 // Below, we iterate towards the `i-1`th node, either from the start or the end,
627 // depending on which would be faster.
628 let split_node = if at - 1 <= len - 1 - (at - 1) {
629 let mut iter = self.iter_mut();
630 // instead of skipping using .skip() (which creates a new struct),
631 // we skip manually so we can access the head field without
632 // depending on implementation details of Skip
638 // better off starting from the end
639 let mut iter = self.iter_mut();
640 for _ in 0..len - 1 - (at - 1) {
646 // The split node is the new tail node of the first part and owns
647 // the head of the second part.
648 let second_part_head;
651 second_part_head = (**split_node.unwrap()).next.take();
652 if let Some(head) = second_part_head {
653 (**head).prev = None;
657 let second_part = LinkedList {
658 head: second_part_head,
664 // Fix the tail ptr of the first part
665 self.tail = split_node;
671 /// Returns a place for insertion at the front of the list.
673 /// Using this method with placement syntax is equivalent to [`push_front`]
674 /// (#method.push_front), but may be more efficient.
679 /// #![feature(collection_placement)]
680 /// #![feature(placement_in_syntax)]
682 /// use std::collections::LinkedList;
684 /// let mut list = LinkedList::new();
685 /// list.front_place() <- 2;
686 /// list.front_place() <- 4;
687 /// assert!(list.iter().eq(&[4, 2]));
689 #[unstable(feature = "collection_placement",
690 reason = "method name and placement protocol are subject to change",
692 pub fn front_place(&mut self) -> FrontPlace<T> {
695 node: IntermediateBox::make_place(),
699 /// Returns a place for insertion at the back of the list.
701 /// Using this method with placement syntax is equivalent to [`push_back`](#method.push_back),
702 /// but may be more efficient.
707 /// #![feature(collection_placement)]
708 /// #![feature(placement_in_syntax)]
710 /// use std::collections::LinkedList;
712 /// let mut list = LinkedList::new();
713 /// list.back_place() <- 2;
714 /// list.back_place() <- 4;
715 /// assert!(list.iter().eq(&[2, 4]));
717 #[unstable(feature = "collection_placement",
718 reason = "method name and placement protocol are subject to change",
720 pub fn back_place(&mut self) -> BackPlace<T> {
723 node: IntermediateBox::make_place(),
728 #[stable(feature = "rust1", since = "1.0.0")]
729 unsafe impl<#[may_dangle] T> Drop for LinkedList<T> {
731 while let Some(_) = self.pop_front_node() {}
735 #[stable(feature = "rust1", since = "1.0.0")]
736 impl<'a, T> Iterator for Iter<'a, T> {
740 fn next(&mut self) -> Option<&'a T> {
744 self.head.map(|node| unsafe {
747 self.head = node.next;
754 fn size_hint(&self) -> (usize, Option<usize>) {
755 (self.len, Some(self.len))
759 #[stable(feature = "rust1", since = "1.0.0")]
760 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
762 fn next_back(&mut self) -> Option<&'a T> {
766 self.tail.map(|node| unsafe {
769 self.tail = node.prev;
776 #[stable(feature = "rust1", since = "1.0.0")]
777 impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
779 #[unstable(feature = "fused", issue = "35602")]
780 impl<'a, T> FusedIterator for Iter<'a, T> {}
782 #[stable(feature = "rust1", since = "1.0.0")]
783 impl<'a, T> Iterator for IterMut<'a, T> {
784 type Item = &'a mut T;
787 fn next(&mut self) -> Option<&'a mut T> {
791 self.head.map(|node| unsafe {
792 let node = &mut **node;
794 self.head = node.next;
801 fn size_hint(&self) -> (usize, Option<usize>) {
802 (self.len, Some(self.len))
806 #[stable(feature = "rust1", since = "1.0.0")]
807 impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
809 fn next_back(&mut self) -> Option<&'a mut T> {
813 self.tail.map(|node| unsafe {
814 let node = &mut **node;
816 self.tail = node.prev;
823 #[stable(feature = "rust1", since = "1.0.0")]
824 impl<'a, T> ExactSizeIterator for IterMut<'a, T> {}
826 #[unstable(feature = "fused", issue = "35602")]
827 impl<'a, T> FusedIterator for IterMut<'a, T> {}
829 impl<'a, T> IterMut<'a, T> {
830 /// Inserts the given element just after the element most recently returned by `.next()`.
831 /// The inserted element does not appear in the iteration.
836 /// #![feature(linked_list_extras)]
838 /// use std::collections::LinkedList;
840 /// let mut list: LinkedList<_> = vec![1, 3, 4].into_iter().collect();
843 /// let mut it = list.iter_mut();
844 /// assert_eq!(it.next().unwrap(), &1);
845 /// // insert `2` after `1`
846 /// it.insert_next(2);
849 /// let vec: Vec<_> = list.into_iter().collect();
850 /// assert_eq!(vec, [1, 2, 3, 4]);
854 #[unstable(feature = "linked_list_extras",
855 reason = "this is probably better handled by a cursor type -- we'll see",
857 pub fn insert_next(&mut self, element: T) {
859 None => self.list.push_back(element),
860 Some(head) => unsafe {
861 let prev = match (**head).prev {
862 None => return self.list.push_front(element),
866 let node = Some(Shared::new(Box::into_raw(box Node {
872 (**prev).next = node;
873 (**head).prev = node;
880 /// Provides a reference to the next element, without changing the iterator.
885 /// #![feature(linked_list_extras)]
887 /// use std::collections::LinkedList;
889 /// let mut list: LinkedList<_> = vec![1, 2, 3].into_iter().collect();
891 /// let mut it = list.iter_mut();
892 /// assert_eq!(it.next().unwrap(), &1);
893 /// assert_eq!(it.peek_next().unwrap(), &2);
894 /// // We just peeked at 2, so it was not consumed from the iterator.
895 /// assert_eq!(it.next().unwrap(), &2);
898 #[unstable(feature = "linked_list_extras",
899 reason = "this is probably better handled by a cursor type -- we'll see",
901 pub fn peek_next(&mut self) -> Option<&mut T> {
905 self.head.map(|node| unsafe { &mut (**node).element })
910 #[stable(feature = "rust1", since = "1.0.0")]
911 impl<T> Iterator for IntoIter<T> {
915 fn next(&mut self) -> Option<T> {
916 self.list.pop_front()
920 fn size_hint(&self) -> (usize, Option<usize>) {
921 (self.list.len, Some(self.list.len))
925 #[stable(feature = "rust1", since = "1.0.0")]
926 impl<T> DoubleEndedIterator for IntoIter<T> {
928 fn next_back(&mut self) -> Option<T> {
933 #[stable(feature = "rust1", since = "1.0.0")]
934 impl<T> ExactSizeIterator for IntoIter<T> {}
936 #[unstable(feature = "fused", issue = "35602")]
937 impl<T> FusedIterator for IntoIter<T> {}
939 #[stable(feature = "rust1", since = "1.0.0")]
940 impl<T> FromIterator<T> for LinkedList<T> {
941 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
942 let mut list = Self::new();
948 #[stable(feature = "rust1", since = "1.0.0")]
949 impl<T> IntoIterator for LinkedList<T> {
951 type IntoIter = IntoIter<T>;
953 /// Consumes the list into an iterator yielding elements by value.
955 fn into_iter(self) -> IntoIter<T> {
956 IntoIter { list: self }
960 #[stable(feature = "rust1", since = "1.0.0")]
961 impl<'a, T> IntoIterator for &'a LinkedList<T> {
963 type IntoIter = Iter<'a, T>;
965 fn into_iter(self) -> Iter<'a, T> {
970 #[stable(feature = "rust1", since = "1.0.0")]
971 impl<'a, T> IntoIterator for &'a mut LinkedList<T> {
972 type Item = &'a mut T;
973 type IntoIter = IterMut<'a, T>;
975 fn into_iter(self) -> IterMut<'a, T> {
980 #[stable(feature = "rust1", since = "1.0.0")]
981 impl<T> Extend<T> for LinkedList<T> {
982 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
983 <Self as SpecExtend<I>>::spec_extend(self, iter);
987 impl<I: IntoIterator> SpecExtend<I> for LinkedList<I::Item> {
988 default fn spec_extend(&mut self, iter: I) {
995 impl<T> SpecExtend<LinkedList<T>> for LinkedList<T> {
996 fn spec_extend(&mut self, ref mut other: LinkedList<T>) {
1001 #[stable(feature = "extend_ref", since = "1.2.0")]
1002 impl<'a, T: 'a + Copy> Extend<&'a T> for LinkedList<T> {
1003 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
1004 self.extend(iter.into_iter().cloned());
1008 #[stable(feature = "rust1", since = "1.0.0")]
1009 impl<T: PartialEq> PartialEq for LinkedList<T> {
1010 fn eq(&self, other: &Self) -> bool {
1011 self.len() == other.len() && self.iter().eq(other)
1014 fn ne(&self, other: &Self) -> bool {
1015 self.len() != other.len() || self.iter().ne(other)
1019 #[stable(feature = "rust1", since = "1.0.0")]
1020 impl<T: Eq> Eq for LinkedList<T> {}
1022 #[stable(feature = "rust1", since = "1.0.0")]
1023 impl<T: PartialOrd> PartialOrd for LinkedList<T> {
1024 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1025 self.iter().partial_cmp(other)
1029 #[stable(feature = "rust1", since = "1.0.0")]
1030 impl<T: Ord> Ord for LinkedList<T> {
1032 fn cmp(&self, other: &Self) -> Ordering {
1033 self.iter().cmp(other)
1037 #[stable(feature = "rust1", since = "1.0.0")]
1038 impl<T: Clone> Clone for LinkedList<T> {
1039 fn clone(&self) -> Self {
1040 self.iter().cloned().collect()
1044 #[stable(feature = "rust1", since = "1.0.0")]
1045 impl<T: fmt::Debug> fmt::Debug for LinkedList<T> {
1046 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1047 f.debug_list().entries(self).finish()
1051 #[stable(feature = "rust1", since = "1.0.0")]
1052 impl<T: Hash> Hash for LinkedList<T> {
1053 fn hash<H: Hasher>(&self, state: &mut H) {
1054 self.len().hash(state);
1061 unsafe fn finalize<T>(node: IntermediateBox<Node<T>>) -> Box<Node<T>> {
1062 let mut node = node.finalize();
1063 ptr::write(&mut node.next, None);
1064 ptr::write(&mut node.prev, None);
1068 /// A place for insertion at the front of a `LinkedList`.
1070 /// See [`LinkedList::front_place`](struct.LinkedList.html#method.front_place) for details.
1071 #[must_use = "places do nothing unless written to with `<-` syntax"]
1072 #[unstable(feature = "collection_placement",
1073 reason = "struct name and placement protocol are subject to change",
1075 pub struct FrontPlace<'a, T: 'a> {
1076 list: &'a mut LinkedList<T>,
1077 node: IntermediateBox<Node<T>>,
1080 #[unstable(feature = "collection_placement",
1081 reason = "placement protocol is subject to change",
1083 impl<'a, T> Placer<T> for FrontPlace<'a, T> {
1086 fn make_place(self) -> Self {
1091 #[unstable(feature = "collection_placement",
1092 reason = "placement protocol is subject to change",
1094 impl<'a, T> Place<T> for FrontPlace<'a, T> {
1095 fn pointer(&mut self) -> *mut T {
1096 unsafe { &mut (*self.node.pointer()).element }
1100 #[unstable(feature = "collection_placement",
1101 reason = "placement protocol is subject to change",
1103 impl<'a, T> InPlace<T> for FrontPlace<'a, T> {
1106 unsafe fn finalize(self) {
1107 let FrontPlace { list, node } = self;
1108 list.push_front_node(finalize(node));
1112 /// A place for insertion at the back of a `LinkedList`.
1114 /// See [`LinkedList::back_place`](struct.LinkedList.html#method.back_place) for details.
1115 #[must_use = "places do nothing unless written to with `<-` syntax"]
1116 #[unstable(feature = "collection_placement",
1117 reason = "struct name and placement protocol are subject to change",
1119 pub struct BackPlace<'a, T: 'a> {
1120 list: &'a mut LinkedList<T>,
1121 node: IntermediateBox<Node<T>>,
1124 #[unstable(feature = "collection_placement",
1125 reason = "placement protocol is subject to change",
1127 impl<'a, T> Placer<T> for BackPlace<'a, T> {
1130 fn make_place(self) -> Self {
1135 #[unstable(feature = "collection_placement",
1136 reason = "placement protocol is subject to change",
1138 impl<'a, T> Place<T> for BackPlace<'a, T> {
1139 fn pointer(&mut self) -> *mut T {
1140 unsafe { &mut (*self.node.pointer()).element }
1144 #[unstable(feature = "collection_placement",
1145 reason = "placement protocol is subject to change",
1147 impl<'a, T> InPlace<T> for BackPlace<'a, T> {
1150 unsafe fn finalize(self) {
1151 let BackPlace { list, node } = self;
1152 list.push_back_node(finalize(node));
1156 // Ensure that `LinkedList` and its read-only iterators are covariant in their type parameters.
1158 fn assert_covariance() {
1159 fn a<'a>(x: LinkedList<&'static str>) -> LinkedList<&'a str> {
1162 fn b<'i, 'a>(x: Iter<'i, &'static str>) -> Iter<'i, &'a str> {
1165 fn c<'a>(x: IntoIter<&'static str>) -> IntoIter<&'a str> {
1170 #[stable(feature = "rust1", since = "1.0.0")]
1171 unsafe impl<T: Send> Send for LinkedList<T> {}
1173 #[stable(feature = "rust1", since = "1.0.0")]
1174 unsafe impl<T: Sync> Sync for LinkedList<T> {}
1176 #[stable(feature = "rust1", since = "1.0.0")]
1177 unsafe impl<'a, T: Sync> Send for Iter<'a, T> {}
1179 #[stable(feature = "rust1", since = "1.0.0")]
1180 unsafe impl<'a, T: Sync> Sync for Iter<'a, T> {}
1182 #[stable(feature = "rust1", since = "1.0.0")]
1183 unsafe impl<'a, T: Send> Send for IterMut<'a, T> {}
1185 #[stable(feature = "rust1", since = "1.0.0")]
1186 unsafe impl<'a, T: Sync> Sync for IterMut<'a, T> {}
1190 use std::__rand::{thread_rng, Rng};
1194 use super::{LinkedList, Node};
1197 fn list_from<T: Clone>(v: &[T]) -> LinkedList<T> {
1198 v.iter().cloned().collect()
1201 pub fn check_links<T>(list: &LinkedList<T>) {
1204 let mut last_ptr: Option<&Node<T>> = None;
1205 let mut node_ptr: &Node<T>;
1208 assert_eq!(0, list.len);
1211 Some(node) => node_ptr = &**node,
1214 match (last_ptr, node_ptr.prev) {
1216 (None, _) => panic!("prev link for head"),
1217 (Some(p), Some(pptr)) => {
1218 assert_eq!(p as *const Node<T>, *pptr as *const Node<T>);
1220 _ => panic!("prev link is none, not good"),
1222 match node_ptr.next {
1224 last_ptr = Some(node_ptr);
1234 assert_eq!(len, list.len);
1242 let mut m = LinkedList::<i32>::new();
1243 let mut n = LinkedList::new();
1246 assert_eq!(m.len(), 0);
1247 assert_eq!(n.len(), 0);
1249 // Non-empty to empty
1251 let mut m = LinkedList::new();
1252 let mut n = LinkedList::new();
1256 assert_eq!(m.len(), 1);
1257 assert_eq!(m.pop_back(), Some(2));
1258 assert_eq!(n.len(), 0);
1261 // Empty to non-empty
1263 let mut m = LinkedList::new();
1264 let mut n = LinkedList::new();
1268 assert_eq!(m.len(), 1);
1269 assert_eq!(m.pop_back(), Some(2));
1273 // Non-empty to non-empty
1274 let v = vec![1, 2, 3, 4, 5];
1275 let u = vec![9, 8, 1, 2, 3, 4, 5];
1276 let mut m = list_from(&v);
1277 let mut n = list_from(&u);
1281 sum.extend_from_slice(&u);
1282 assert_eq!(sum.len(), m.len());
1284 assert_eq!(m.pop_front(), Some(elt))
1286 assert_eq!(n.len(), 0);
1287 // let's make sure it's working properly, since we
1288 // did some direct changes to private members
1290 assert_eq!(n.len(), 1);
1291 assert_eq!(n.pop_front(), Some(3));
1296 fn test_insert_prev() {
1297 let mut m = list_from(&[0, 2, 4, 6, 8]);
1300 let mut it = m.iter_mut();
1306 it.insert_next(*elt + 1);
1307 match it.peek_next() {
1308 Some(x) => assert_eq!(*x, *elt + 2),
1309 None => assert_eq!(8, *elt),
1318 assert_eq!(m.len(), 3 + len * 2);
1319 assert_eq!(m.into_iter().collect::<Vec<_>>(),
1320 [-2, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1]);
1324 #[cfg_attr(target_os = "emscripten", ignore)]
1326 let n = list_from(&[1, 2, 3]);
1327 thread::spawn(move || {
1329 let a: &[_] = &[&1, &2, &3];
1330 assert_eq!(a, &n.iter().collect::<Vec<_>>()[..]);
1348 // There was a bug in split_off that failed to null out the RHS's head's prev ptr.
1349 // This caused the RHS's dtor to walk up into the LHS at drop and delete all of
1352 // https://github.com/rust-lang/rust/issues/26021
1353 let mut v1 = LinkedList::new();
1358 let _ = v1.split_off(3); // Dropping this now should not cause laundry consumption
1359 assert_eq!(v1.len(), 3);
1361 assert_eq!(v1.iter().len(), 3);
1362 assert_eq!(v1.iter().collect::<Vec<_>>().len(), 3);
1366 fn test_split_off() {
1367 let mut v1 = LinkedList::new();
1374 for ix in 0..1 + v1.len() {
1375 let mut a = v1.clone();
1376 let b = a.split_off(ix);
1385 fn fuzz_test(sz: i32) {
1386 let mut m: LinkedList<_> = LinkedList::new();
1390 let r: u8 = thread_rng().next_u32() as u8;
1416 for (a, &b) in m.into_iter().zip(&v) {
1420 assert_eq!(i, v.len());