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, Shared};
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<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 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<Shared<Node<T>>>,
69 tail: Option<Shared<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 #19839: deriving is too aggressive on the bounds (T doesn't need to be 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<Shared<Node<T>>>,
102 tail: Option<Shared<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(Shared::from(Box::into_unique(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(Shared::from(Box::into_unique(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,
225 #[stable(feature = "rust1", since = "1.0.0")]
226 impl<T> Default for LinkedList<T> {
227 /// Creates an empty `LinkedList<T>`.
229 fn default() -> Self {
234 impl<T> LinkedList<T> {
235 /// Creates an empty `LinkedList`.
240 /// use std::collections::LinkedList;
242 /// let list: LinkedList<u32> = LinkedList::new();
245 #[stable(feature = "rust1", since = "1.0.0")]
246 pub fn new() -> Self {
255 /// Moves all elements from `other` to the end of the list.
257 /// This reuses all the nodes from `other` and moves them into `self`. After
258 /// this operation, `other` becomes empty.
260 /// This operation should compute in O(1) time and O(1) memory.
265 /// use std::collections::LinkedList;
267 /// let mut list1 = LinkedList::new();
268 /// list1.push_back('a');
270 /// let mut list2 = LinkedList::new();
271 /// list2.push_back('b');
272 /// list2.push_back('c');
274 /// list1.append(&mut list2);
276 /// let mut iter = list1.iter();
277 /// assert_eq!(iter.next(), Some(&'a'));
278 /// assert_eq!(iter.next(), Some(&'b'));
279 /// assert_eq!(iter.next(), Some(&'c'));
280 /// assert!(iter.next().is_none());
282 /// assert!(list2.is_empty());
284 #[stable(feature = "rust1", since = "1.0.0")]
285 pub fn append(&mut self, other: &mut Self) {
287 None => mem::swap(self, other),
289 if let Some(mut other_head) = other.head.take() {
291 tail.as_mut().next = Some(other_head);
292 other_head.as_mut().prev = Some(tail);
295 self.tail = other.tail.take();
296 self.len += mem::replace(&mut other.len, 0);
302 /// Provides a forward iterator.
307 /// use std::collections::LinkedList;
309 /// let mut list: LinkedList<u32> = LinkedList::new();
311 /// list.push_back(0);
312 /// list.push_back(1);
313 /// list.push_back(2);
315 /// let mut iter = list.iter();
316 /// assert_eq!(iter.next(), Some(&0));
317 /// assert_eq!(iter.next(), Some(&1));
318 /// assert_eq!(iter.next(), Some(&2));
319 /// assert_eq!(iter.next(), None);
322 #[stable(feature = "rust1", since = "1.0.0")]
323 pub fn iter(&self) -> Iter<T> {
332 /// Provides a forward iterator with mutable references.
337 /// use std::collections::LinkedList;
339 /// let mut list: LinkedList<u32> = LinkedList::new();
341 /// list.push_back(0);
342 /// list.push_back(1);
343 /// list.push_back(2);
345 /// for element in list.iter_mut() {
349 /// let mut iter = list.iter();
350 /// assert_eq!(iter.next(), Some(&10));
351 /// assert_eq!(iter.next(), Some(&11));
352 /// assert_eq!(iter.next(), Some(&12));
353 /// assert_eq!(iter.next(), None);
356 #[stable(feature = "rust1", since = "1.0.0")]
357 pub fn iter_mut(&mut self) -> IterMut<T> {
366 /// Returns `true` if the `LinkedList` is empty.
368 /// This operation should compute in O(1) time.
373 /// use std::collections::LinkedList;
375 /// let mut dl = LinkedList::new();
376 /// assert!(dl.is_empty());
378 /// dl.push_front("foo");
379 /// assert!(!dl.is_empty());
382 #[stable(feature = "rust1", since = "1.0.0")]
383 pub fn is_empty(&self) -> bool {
387 /// Returns the length of the `LinkedList`.
389 /// This operation should compute in O(1) time.
394 /// use std::collections::LinkedList;
396 /// let mut dl = LinkedList::new();
398 /// dl.push_front(2);
399 /// assert_eq!(dl.len(), 1);
401 /// dl.push_front(1);
402 /// assert_eq!(dl.len(), 2);
405 /// assert_eq!(dl.len(), 3);
408 #[stable(feature = "rust1", since = "1.0.0")]
409 pub fn len(&self) -> usize {
413 /// Removes all elements from the `LinkedList`.
415 /// This operation should compute in O(n) time.
420 /// use std::collections::LinkedList;
422 /// let mut dl = LinkedList::new();
424 /// dl.push_front(2);
425 /// dl.push_front(1);
426 /// assert_eq!(dl.len(), 2);
427 /// assert_eq!(dl.front(), Some(&1));
430 /// assert_eq!(dl.len(), 0);
431 /// assert_eq!(dl.front(), None);
434 #[stable(feature = "rust1", since = "1.0.0")]
435 pub fn clear(&mut self) {
439 /// Returns `true` if the `LinkedList` contains an element equal to the
445 /// use std::collections::LinkedList;
447 /// let mut list: LinkedList<u32> = LinkedList::new();
449 /// list.push_back(0);
450 /// list.push_back(1);
451 /// list.push_back(2);
453 /// assert_eq!(list.contains(&0), true);
454 /// assert_eq!(list.contains(&10), false);
456 #[stable(feature = "linked_list_contains", since = "1.12.0")]
457 pub fn contains(&self, x: &T) -> bool
458 where T: PartialEq<T>
460 self.iter().any(|e| e == x)
463 /// Provides a reference to the front element, or `None` if the list is
469 /// use std::collections::LinkedList;
471 /// let mut dl = LinkedList::new();
472 /// assert_eq!(dl.front(), None);
474 /// dl.push_front(1);
475 /// assert_eq!(dl.front(), Some(&1));
478 #[stable(feature = "rust1", since = "1.0.0")]
479 pub fn front(&self) -> Option<&T> {
481 self.head.as_ref().map(|node| &node.as_ref().element)
485 /// Provides a mutable reference to the front element, or `None` if the list
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));
499 /// match dl.front_mut() {
501 /// Some(x) => *x = 5,
503 /// assert_eq!(dl.front(), Some(&5));
506 #[stable(feature = "rust1", since = "1.0.0")]
507 pub fn front_mut(&mut self) -> Option<&mut T> {
509 self.head.as_mut().map(|node| &mut node.as_mut().element)
513 /// Provides a reference to the back element, or `None` if the list is
519 /// use std::collections::LinkedList;
521 /// let mut dl = LinkedList::new();
522 /// assert_eq!(dl.back(), None);
525 /// assert_eq!(dl.back(), Some(&1));
528 #[stable(feature = "rust1", since = "1.0.0")]
529 pub fn back(&self) -> Option<&T> {
531 self.tail.as_ref().map(|node| &node.as_ref().element)
535 /// Provides a mutable reference to the back element, or `None` if the list
541 /// use std::collections::LinkedList;
543 /// let mut dl = LinkedList::new();
544 /// assert_eq!(dl.back(), None);
547 /// assert_eq!(dl.back(), Some(&1));
549 /// match dl.back_mut() {
551 /// Some(x) => *x = 5,
553 /// assert_eq!(dl.back(), Some(&5));
556 #[stable(feature = "rust1", since = "1.0.0")]
557 pub fn back_mut(&mut self) -> Option<&mut T> {
559 self.tail.as_mut().map(|node| &mut node.as_mut().element)
563 /// Adds an element first in the list.
565 /// This operation should compute in O(1) time.
570 /// use std::collections::LinkedList;
572 /// let mut dl = LinkedList::new();
574 /// dl.push_front(2);
575 /// assert_eq!(dl.front().unwrap(), &2);
577 /// dl.push_front(1);
578 /// assert_eq!(dl.front().unwrap(), &1);
580 #[stable(feature = "rust1", since = "1.0.0")]
581 pub fn push_front(&mut self, elt: T) {
582 self.push_front_node(box Node::new(elt));
585 /// Removes the first element and returns it, or `None` if the list is
588 /// This operation should compute in O(1) time.
593 /// use std::collections::LinkedList;
595 /// let mut d = LinkedList::new();
596 /// assert_eq!(d.pop_front(), None);
600 /// assert_eq!(d.pop_front(), Some(3));
601 /// assert_eq!(d.pop_front(), Some(1));
602 /// assert_eq!(d.pop_front(), None);
604 #[stable(feature = "rust1", since = "1.0.0")]
605 pub fn pop_front(&mut self) -> Option<T> {
606 self.pop_front_node().map(Node::into_element)
609 /// Appends an element to the back of a list
614 /// use std::collections::LinkedList;
616 /// let mut d = LinkedList::new();
619 /// assert_eq!(3, *d.back().unwrap());
621 #[stable(feature = "rust1", since = "1.0.0")]
622 pub fn push_back(&mut self, elt: T) {
623 self.push_back_node(box Node::new(elt));
626 /// Removes the last element from a list and returns it, or `None` if
632 /// use std::collections::LinkedList;
634 /// let mut d = LinkedList::new();
635 /// assert_eq!(d.pop_back(), None);
638 /// assert_eq!(d.pop_back(), Some(3));
640 #[stable(feature = "rust1", since = "1.0.0")]
641 pub fn pop_back(&mut self) -> Option<T> {
642 self.pop_back_node().map(Node::into_element)
645 /// Splits the list into two at the given index. Returns everything after the given index,
646 /// including the index.
648 /// This operation should compute in O(n) time.
652 /// Panics if `at > len`.
657 /// use std::collections::LinkedList;
659 /// let mut d = LinkedList::new();
665 /// let mut splitted = d.split_off(2);
667 /// assert_eq!(splitted.pop_front(), Some(1));
668 /// assert_eq!(splitted.pop_front(), None);
670 #[stable(feature = "rust1", since = "1.0.0")]
671 pub fn split_off(&mut self, at: usize) -> LinkedList<T> {
672 let len = self.len();
673 assert!(at <= len, "Cannot split off at a nonexistent index");
675 return mem::replace(self, Self::new());
676 } else if at == len {
680 // Below, we iterate towards the `i-1`th node, either from the start or the end,
681 // depending on which would be faster.
682 let split_node = if at - 1 <= len - 1 - (at - 1) {
683 let mut iter = self.iter_mut();
684 // instead of skipping using .skip() (which creates a new struct),
685 // we skip manually so we can access the head field without
686 // depending on implementation details of Skip
692 // better off starting from the end
693 let mut iter = self.iter_mut();
694 for _ in 0..len - 1 - (at - 1) {
700 // The split node is the new tail node of the first part and owns
701 // the head of the second part.
702 let second_part_head;
705 second_part_head = split_node.unwrap().as_mut().next.take();
706 if let Some(mut head) = second_part_head {
707 head.as_mut().prev = None;
711 let second_part = LinkedList {
712 head: second_part_head,
718 // Fix the tail ptr of the first part
719 self.tail = split_node;
725 /// Returns a place for insertion at the front of the list.
727 /// Using this method with placement syntax is equivalent to
728 /// [`push_front`](#method.push_front), but may be more efficient.
733 /// #![feature(collection_placement)]
734 /// #![feature(placement_in_syntax)]
736 /// use std::collections::LinkedList;
738 /// let mut list = LinkedList::new();
739 /// list.front_place() <- 2;
740 /// list.front_place() <- 4;
741 /// assert!(list.iter().eq(&[4, 2]));
743 #[unstable(feature = "collection_placement",
744 reason = "method name and placement protocol are subject to change",
746 pub fn front_place(&mut self) -> FrontPlace<T> {
749 node: IntermediateBox::make_place(),
753 /// Returns a place for insertion at the back of the list.
755 /// Using this method with placement syntax is equivalent to [`push_back`](#method.push_back),
756 /// but may be more efficient.
761 /// #![feature(collection_placement)]
762 /// #![feature(placement_in_syntax)]
764 /// use std::collections::LinkedList;
766 /// let mut list = LinkedList::new();
767 /// list.back_place() <- 2;
768 /// list.back_place() <- 4;
769 /// assert!(list.iter().eq(&[2, 4]));
771 #[unstable(feature = "collection_placement",
772 reason = "method name and placement protocol are subject to change",
774 pub fn back_place(&mut self) -> BackPlace<T> {
777 node: IntermediateBox::make_place(),
782 #[stable(feature = "rust1", since = "1.0.0")]
783 unsafe impl<#[may_dangle] T> Drop for LinkedList<T> {
785 while let Some(_) = self.pop_front_node() {}
789 #[stable(feature = "rust1", since = "1.0.0")]
790 impl<'a, T> Iterator for Iter<'a, T> {
794 fn next(&mut self) -> Option<&'a T> {
798 self.head.map(|node| unsafe {
799 // Need an unbound lifetime to get 'a
800 let node = &*node.as_ptr();
802 self.head = node.next;
809 fn size_hint(&self) -> (usize, Option<usize>) {
810 (self.len, Some(self.len))
814 #[stable(feature = "rust1", since = "1.0.0")]
815 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
817 fn next_back(&mut self) -> Option<&'a T> {
821 self.tail.map(|node| unsafe {
822 // Need an unbound lifetime to get 'a
823 let node = &*node.as_ptr();
825 self.tail = node.prev;
832 #[stable(feature = "rust1", since = "1.0.0")]
833 impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
835 #[unstable(feature = "fused", issue = "35602")]
836 impl<'a, T> FusedIterator for Iter<'a, T> {}
838 #[stable(feature = "rust1", since = "1.0.0")]
839 impl<'a, T> Iterator for IterMut<'a, T> {
840 type Item = &'a mut T;
843 fn next(&mut self) -> Option<&'a mut T> {
847 self.head.map(|node| unsafe {
848 // Need an unbound lifetime to get 'a
849 let node = &mut *node.as_ptr();
851 self.head = node.next;
858 fn size_hint(&self) -> (usize, Option<usize>) {
859 (self.len, Some(self.len))
863 #[stable(feature = "rust1", since = "1.0.0")]
864 impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
866 fn next_back(&mut self) -> Option<&'a mut T> {
870 self.tail.map(|node| unsafe {
871 // Need an unbound lifetime to get 'a
872 let node = &mut *node.as_ptr();
874 self.tail = node.prev;
881 #[stable(feature = "rust1", since = "1.0.0")]
882 impl<'a, T> ExactSizeIterator for IterMut<'a, T> {}
884 #[unstable(feature = "fused", issue = "35602")]
885 impl<'a, T> FusedIterator for IterMut<'a, T> {}
887 impl<'a, T> IterMut<'a, T> {
888 /// Inserts the given element just after the element most recently returned by `.next()`.
889 /// The inserted element does not appear in the iteration.
894 /// #![feature(linked_list_extras)]
896 /// use std::collections::LinkedList;
898 /// let mut list: LinkedList<_> = vec![1, 3, 4].into_iter().collect();
901 /// let mut it = list.iter_mut();
902 /// assert_eq!(it.next().unwrap(), &1);
903 /// // insert `2` after `1`
904 /// it.insert_next(2);
907 /// let vec: Vec<_> = list.into_iter().collect();
908 /// assert_eq!(vec, [1, 2, 3, 4]);
912 #[unstable(feature = "linked_list_extras",
913 reason = "this is probably better handled by a cursor type -- we'll see",
915 pub fn insert_next(&mut self, element: T) {
917 None => self.list.push_back(element),
918 Some(mut head) => unsafe {
919 let mut prev = match head.as_ref().prev {
920 None => return self.list.push_front(element),
924 let node = Some(Shared::from(Box::into_unique(box Node {
930 prev.as_mut().next = node;
931 head.as_mut().prev = node;
938 /// Provides a reference to the next element, without changing the iterator.
943 /// #![feature(linked_list_extras)]
945 /// use std::collections::LinkedList;
947 /// let mut list: LinkedList<_> = vec![1, 2, 3].into_iter().collect();
949 /// let mut it = list.iter_mut();
950 /// assert_eq!(it.next().unwrap(), &1);
951 /// assert_eq!(it.peek_next().unwrap(), &2);
952 /// // We just peeked at 2, so it was not consumed from the iterator.
953 /// assert_eq!(it.next().unwrap(), &2);
956 #[unstable(feature = "linked_list_extras",
957 reason = "this is probably better handled by a cursor type -- we'll see",
959 pub fn peek_next(&mut self) -> Option<&mut T> {
964 self.head.as_mut().map(|node| &mut node.as_mut().element)
970 #[stable(feature = "rust1", since = "1.0.0")]
971 impl<T> Iterator for IntoIter<T> {
975 fn next(&mut self) -> Option<T> {
976 self.list.pop_front()
980 fn size_hint(&self) -> (usize, Option<usize>) {
981 (self.list.len, Some(self.list.len))
985 #[stable(feature = "rust1", since = "1.0.0")]
986 impl<T> DoubleEndedIterator for IntoIter<T> {
988 fn next_back(&mut self) -> Option<T> {
993 #[stable(feature = "rust1", since = "1.0.0")]
994 impl<T> ExactSizeIterator for IntoIter<T> {}
996 #[unstable(feature = "fused", issue = "35602")]
997 impl<T> FusedIterator for IntoIter<T> {}
999 #[stable(feature = "rust1", since = "1.0.0")]
1000 impl<T> FromIterator<T> for LinkedList<T> {
1001 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
1002 let mut list = Self::new();
1008 #[stable(feature = "rust1", since = "1.0.0")]
1009 impl<T> IntoIterator for LinkedList<T> {
1011 type IntoIter = IntoIter<T>;
1013 /// Consumes the list into an iterator yielding elements by value.
1015 fn into_iter(self) -> IntoIter<T> {
1016 IntoIter { list: self }
1020 #[stable(feature = "rust1", since = "1.0.0")]
1021 impl<'a, T> IntoIterator for &'a LinkedList<T> {
1023 type IntoIter = Iter<'a, T>;
1025 fn into_iter(self) -> Iter<'a, T> {
1030 #[stable(feature = "rust1", since = "1.0.0")]
1031 impl<'a, T> IntoIterator for &'a mut LinkedList<T> {
1032 type Item = &'a mut T;
1033 type IntoIter = IterMut<'a, T>;
1035 fn into_iter(self) -> IterMut<'a, T> {
1040 #[stable(feature = "rust1", since = "1.0.0")]
1041 impl<T> Extend<T> for LinkedList<T> {
1042 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1043 <Self as SpecExtend<I>>::spec_extend(self, iter);
1047 impl<I: IntoIterator> SpecExtend<I> for LinkedList<I::Item> {
1048 default fn spec_extend(&mut self, iter: I) {
1050 self.push_back(elt);
1055 impl<T> SpecExtend<LinkedList<T>> for LinkedList<T> {
1056 fn spec_extend(&mut self, ref mut other: LinkedList<T>) {
1061 #[stable(feature = "extend_ref", since = "1.2.0")]
1062 impl<'a, T: 'a + Copy> Extend<&'a T> for LinkedList<T> {
1063 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
1064 self.extend(iter.into_iter().cloned());
1068 #[stable(feature = "rust1", since = "1.0.0")]
1069 impl<T: PartialEq> PartialEq for LinkedList<T> {
1070 fn eq(&self, other: &Self) -> bool {
1071 self.len() == other.len() && self.iter().eq(other)
1074 fn ne(&self, other: &Self) -> bool {
1075 self.len() != other.len() || self.iter().ne(other)
1079 #[stable(feature = "rust1", since = "1.0.0")]
1080 impl<T: Eq> Eq for LinkedList<T> {}
1082 #[stable(feature = "rust1", since = "1.0.0")]
1083 impl<T: PartialOrd> PartialOrd for LinkedList<T> {
1084 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1085 self.iter().partial_cmp(other)
1089 #[stable(feature = "rust1", since = "1.0.0")]
1090 impl<T: Ord> Ord for LinkedList<T> {
1092 fn cmp(&self, other: &Self) -> Ordering {
1093 self.iter().cmp(other)
1097 #[stable(feature = "rust1", since = "1.0.0")]
1098 impl<T: Clone> Clone for LinkedList<T> {
1099 fn clone(&self) -> Self {
1100 self.iter().cloned().collect()
1104 #[stable(feature = "rust1", since = "1.0.0")]
1105 impl<T: fmt::Debug> fmt::Debug for LinkedList<T> {
1106 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1107 f.debug_list().entries(self).finish()
1111 #[stable(feature = "rust1", since = "1.0.0")]
1112 impl<T: Hash> Hash for LinkedList<T> {
1113 fn hash<H: Hasher>(&self, state: &mut H) {
1114 self.len().hash(state);
1121 unsafe fn finalize<T>(node: IntermediateBox<Node<T>>) -> Box<Node<T>> {
1122 let mut node = node.finalize();
1123 ptr::write(&mut node.next, None);
1124 ptr::write(&mut node.prev, None);
1128 /// A place for insertion at the front of a `LinkedList`.
1130 /// See [`LinkedList::front_place`](struct.LinkedList.html#method.front_place) for details.
1131 #[must_use = "places do nothing unless written to with `<-` syntax"]
1132 #[unstable(feature = "collection_placement",
1133 reason = "struct name and placement protocol are subject to change",
1135 pub struct FrontPlace<'a, T: 'a> {
1136 list: &'a mut LinkedList<T>,
1137 node: IntermediateBox<Node<T>>,
1140 #[unstable(feature = "collection_placement",
1141 reason = "struct name and placement protocol are subject to change",
1143 impl<'a, T: 'a + fmt::Debug> fmt::Debug for FrontPlace<'a, T> {
1144 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1145 f.debug_tuple("FrontPlace")
1151 #[unstable(feature = "collection_placement",
1152 reason = "placement protocol is subject to change",
1154 impl<'a, T> Placer<T> for FrontPlace<'a, T> {
1157 fn make_place(self) -> Self {
1162 #[unstable(feature = "collection_placement",
1163 reason = "placement protocol is subject to change",
1165 impl<'a, T> Place<T> for FrontPlace<'a, T> {
1166 fn pointer(&mut self) -> *mut T {
1167 unsafe { &mut (*self.node.pointer()).element }
1171 #[unstable(feature = "collection_placement",
1172 reason = "placement protocol is subject to change",
1174 impl<'a, T> InPlace<T> for FrontPlace<'a, T> {
1177 unsafe fn finalize(self) {
1178 let FrontPlace { list, node } = self;
1179 list.push_front_node(finalize(node));
1183 /// A place for insertion at the back of a `LinkedList`.
1185 /// See [`LinkedList::back_place`](struct.LinkedList.html#method.back_place) for details.
1186 #[must_use = "places do nothing unless written to with `<-` syntax"]
1187 #[unstable(feature = "collection_placement",
1188 reason = "struct name and placement protocol are subject to change",
1190 pub struct BackPlace<'a, T: 'a> {
1191 list: &'a mut LinkedList<T>,
1192 node: IntermediateBox<Node<T>>,
1195 #[unstable(feature = "collection_placement",
1196 reason = "struct name and placement protocol are subject to change",
1198 impl<'a, T: 'a + fmt::Debug> fmt::Debug for BackPlace<'a, T> {
1199 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1200 f.debug_tuple("BackPlace")
1206 #[unstable(feature = "collection_placement",
1207 reason = "placement protocol is subject to change",
1209 impl<'a, T> Placer<T> for BackPlace<'a, T> {
1212 fn make_place(self) -> Self {
1217 #[unstable(feature = "collection_placement",
1218 reason = "placement protocol is subject to change",
1220 impl<'a, T> Place<T> for BackPlace<'a, T> {
1221 fn pointer(&mut self) -> *mut T {
1222 unsafe { &mut (*self.node.pointer()).element }
1226 #[unstable(feature = "collection_placement",
1227 reason = "placement protocol is subject to change",
1229 impl<'a, T> InPlace<T> for BackPlace<'a, T> {
1232 unsafe fn finalize(self) {
1233 let BackPlace { list, node } = self;
1234 list.push_back_node(finalize(node));
1238 // Ensure that `LinkedList` and its read-only iterators are covariant in their type parameters.
1240 fn assert_covariance() {
1241 fn a<'a>(x: LinkedList<&'static str>) -> LinkedList<&'a str> {
1244 fn b<'i, 'a>(x: Iter<'i, &'static str>) -> Iter<'i, &'a str> {
1247 fn c<'a>(x: IntoIter<&'static str>) -> IntoIter<&'a str> {
1252 #[stable(feature = "rust1", since = "1.0.0")]
1253 unsafe impl<T: Send> Send for LinkedList<T> {}
1255 #[stable(feature = "rust1", since = "1.0.0")]
1256 unsafe impl<T: Sync> Sync for LinkedList<T> {}
1258 #[stable(feature = "rust1", since = "1.0.0")]
1259 unsafe impl<'a, T: Sync> Send for Iter<'a, T> {}
1261 #[stable(feature = "rust1", since = "1.0.0")]
1262 unsafe impl<'a, T: Sync> Sync for Iter<'a, T> {}
1264 #[stable(feature = "rust1", since = "1.0.0")]
1265 unsafe impl<'a, T: Send> Send for IterMut<'a, T> {}
1267 #[stable(feature = "rust1", since = "1.0.0")]
1268 unsafe impl<'a, T: Sync> Sync for IterMut<'a, T> {}
1272 use std::__rand::{thread_rng, Rng};
1276 use super::{LinkedList, Node};
1279 fn list_from<T: Clone>(v: &[T]) -> LinkedList<T> {
1280 v.iter().cloned().collect()
1283 pub fn check_links<T>(list: &LinkedList<T>) {
1286 let mut last_ptr: Option<&Node<T>> = None;
1287 let mut node_ptr: &Node<T>;
1290 assert_eq!(0, list.len);
1293 Some(node) => node_ptr = &*node.as_ptr(),
1296 match (last_ptr, node_ptr.prev) {
1298 (None, _) => panic!("prev link for head"),
1299 (Some(p), Some(pptr)) => {
1300 assert_eq!(p as *const Node<T>, pptr.as_ptr() as *const Node<T>);
1302 _ => panic!("prev link is none, not good"),
1304 match node_ptr.next {
1306 last_ptr = Some(node_ptr);
1307 node_ptr = &*next.as_ptr();
1316 assert_eq!(len, list.len);
1324 let mut m = LinkedList::<i32>::new();
1325 let mut n = LinkedList::new();
1328 assert_eq!(m.len(), 0);
1329 assert_eq!(n.len(), 0);
1331 // Non-empty to empty
1333 let mut m = LinkedList::new();
1334 let mut n = LinkedList::new();
1338 assert_eq!(m.len(), 1);
1339 assert_eq!(m.pop_back(), Some(2));
1340 assert_eq!(n.len(), 0);
1343 // Empty to non-empty
1345 let mut m = LinkedList::new();
1346 let mut n = LinkedList::new();
1350 assert_eq!(m.len(), 1);
1351 assert_eq!(m.pop_back(), Some(2));
1355 // Non-empty to non-empty
1356 let v = vec![1, 2, 3, 4, 5];
1357 let u = vec![9, 8, 1, 2, 3, 4, 5];
1358 let mut m = list_from(&v);
1359 let mut n = list_from(&u);
1363 sum.extend_from_slice(&u);
1364 assert_eq!(sum.len(), m.len());
1366 assert_eq!(m.pop_front(), Some(elt))
1368 assert_eq!(n.len(), 0);
1369 // let's make sure it's working properly, since we
1370 // did some direct changes to private members
1372 assert_eq!(n.len(), 1);
1373 assert_eq!(n.pop_front(), Some(3));
1378 fn test_insert_prev() {
1379 let mut m = list_from(&[0, 2, 4, 6, 8]);
1382 let mut it = m.iter_mut();
1388 it.insert_next(*elt + 1);
1389 match it.peek_next() {
1390 Some(x) => assert_eq!(*x, *elt + 2),
1391 None => assert_eq!(8, *elt),
1400 assert_eq!(m.len(), 3 + len * 2);
1401 assert_eq!(m.into_iter().collect::<Vec<_>>(),
1402 [-2, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1]);
1406 #[cfg_attr(target_os = "emscripten", ignore)]
1408 let n = list_from(&[1, 2, 3]);
1409 thread::spawn(move || {
1411 let a: &[_] = &[&1, &2, &3];
1412 assert_eq!(a, &*n.iter().collect::<Vec<_>>());
1430 // There was a bug in split_off that failed to null out the RHS's head's prev ptr.
1431 // This caused the RHS's dtor to walk up into the LHS at drop and delete all of
1434 // https://github.com/rust-lang/rust/issues/26021
1435 let mut v1 = LinkedList::new();
1440 let _ = v1.split_off(3); // Dropping this now should not cause laundry consumption
1441 assert_eq!(v1.len(), 3);
1443 assert_eq!(v1.iter().len(), 3);
1444 assert_eq!(v1.iter().collect::<Vec<_>>().len(), 3);
1448 fn test_split_off() {
1449 let mut v1 = LinkedList::new();
1456 for ix in 0..1 + v1.len() {
1457 let mut a = v1.clone();
1458 let b = a.split_off(ix);
1467 fn fuzz_test(sz: i32) {
1468 let mut m: LinkedList<_> = LinkedList::new();
1472 let r: u8 = thread_rng().next_u32() as u8;
1498 for (a, &b) in m.into_iter().zip(&v) {
1502 assert_eq!(i, v.len());