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 #[stable(feature = "collection_debug", since = "1.17.0")]
69 impl<'a, T: 'a + fmt::Debug> fmt::Debug for Iter<'a, T> {
70 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
77 // FIXME #19839: deriving is too aggressive on the bounds (T doesn't need to be Clone).
78 #[stable(feature = "rust1", since = "1.0.0")]
79 impl<'a, T> Clone for Iter<'a, T> {
80 fn clone(&self) -> Self {
85 /// An iterator over mutable references to the elements of a `LinkedList`.
86 #[stable(feature = "rust1", since = "1.0.0")]
87 pub struct IterMut<'a, T: 'a> {
88 list: &'a mut LinkedList<T>,
89 head: Option<Shared<Node<T>>>,
90 tail: Option<Shared<Node<T>>>,
94 #[stable(feature = "collection_debug", since = "1.17.0")]
95 impl<'a, T: 'a + fmt::Debug> fmt::Debug for IterMut<'a, T> {
96 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
97 f.debug_tuple("IterMut")
103 /// An iterator over the elements of a `LinkedList`.
105 #[stable(feature = "rust1", since = "1.0.0")]
106 pub struct IntoIter<T> {
110 #[stable(feature = "collection_debug", since = "1.17.0")]
111 impl<T: fmt::Debug> fmt::Debug for IntoIter<T> {
112 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
113 f.debug_tuple("IntoIter")
120 fn new(element: T) -> Self {
128 fn into_element(self: Box<Self>) -> T {
134 impl<T> LinkedList<T> {
135 /// Adds the given node to the front of the list.
137 fn push_front_node(&mut self, mut node: Box<Node<T>>) {
139 node.next = self.head;
141 let node = Some(Shared::new(Box::into_raw(node)));
144 None => self.tail = node,
145 Some(head) => (**head).prev = node,
153 /// Removes and returns the node at the front of the list.
155 fn pop_front_node(&mut self) -> Option<Box<Node<T>>> {
156 self.head.map(|node| unsafe {
157 let node = Box::from_raw(*node);
158 self.head = node.next;
161 None => self.tail = None,
162 Some(head) => (**head).prev = None,
170 /// Adds the given node to the back of the list.
172 fn push_back_node(&mut self, mut node: Box<Node<T>>) {
175 node.prev = self.tail;
176 let node = Some(Shared::new(Box::into_raw(node)));
179 None => self.head = node,
180 Some(tail) => (**tail).next = node,
188 /// Removes and returns the node at the back of the list.
190 fn pop_back_node(&mut self) -> Option<Box<Node<T>>> {
191 self.tail.map(|node| unsafe {
192 let node = Box::from_raw(*node);
193 self.tail = node.prev;
196 None => self.head = None,
197 Some(tail) => (**tail).next = None,
206 #[stable(feature = "rust1", since = "1.0.0")]
207 impl<T> Default for LinkedList<T> {
208 /// Creates an empty `LinkedList<T>`.
210 fn default() -> Self {
215 impl<T> LinkedList<T> {
216 /// Creates an empty `LinkedList`.
221 /// use std::collections::LinkedList;
223 /// let list: LinkedList<u32> = LinkedList::new();
226 #[stable(feature = "rust1", since = "1.0.0")]
227 pub fn new() -> Self {
236 /// Moves all elements from `other` to the end of the list.
238 /// This reuses all the nodes from `other` and moves them into `self`. After
239 /// this operation, `other` becomes empty.
241 /// This operation should compute in O(1) time and O(1) memory.
246 /// use std::collections::LinkedList;
248 /// let mut list1 = LinkedList::new();
249 /// list1.push_back('a');
251 /// let mut list2 = LinkedList::new();
252 /// list2.push_back('b');
253 /// list2.push_back('c');
255 /// list1.append(&mut list2);
257 /// let mut iter = list1.iter();
258 /// assert_eq!(iter.next(), Some(&'a'));
259 /// assert_eq!(iter.next(), Some(&'b'));
260 /// assert_eq!(iter.next(), Some(&'c'));
261 /// assert!(iter.next().is_none());
263 /// assert!(list2.is_empty());
265 #[stable(feature = "rust1", since = "1.0.0")]
266 pub fn append(&mut self, other: &mut Self) {
268 None => mem::swap(self, other),
270 if let Some(other_head) = other.head.take() {
272 (**tail).next = Some(other_head);
273 (**other_head).prev = Some(tail);
276 self.tail = other.tail.take();
277 self.len += mem::replace(&mut other.len, 0);
283 /// Provides a forward iterator.
288 /// use std::collections::LinkedList;
290 /// let mut list: LinkedList<u32> = LinkedList::new();
292 /// list.push_back(0);
293 /// list.push_back(1);
294 /// list.push_back(2);
296 /// let mut iter = list.iter();
297 /// assert_eq!(iter.next(), Some(&0));
298 /// assert_eq!(iter.next(), Some(&1));
299 /// assert_eq!(iter.next(), Some(&2));
300 /// assert_eq!(iter.next(), None);
303 #[stable(feature = "rust1", since = "1.0.0")]
304 pub fn iter(&self) -> Iter<T> {
313 /// Provides a forward iterator with mutable references.
318 /// use std::collections::LinkedList;
320 /// let mut list: LinkedList<u32> = LinkedList::new();
322 /// list.push_back(0);
323 /// list.push_back(1);
324 /// list.push_back(2);
326 /// for element in list.iter_mut() {
330 /// let mut iter = list.iter();
331 /// assert_eq!(iter.next(), Some(&10));
332 /// assert_eq!(iter.next(), Some(&11));
333 /// assert_eq!(iter.next(), Some(&12));
334 /// assert_eq!(iter.next(), None);
337 #[stable(feature = "rust1", since = "1.0.0")]
338 pub fn iter_mut(&mut self) -> IterMut<T> {
347 /// Returns `true` if the `LinkedList` is empty.
349 /// This operation should compute in O(1) time.
354 /// use std::collections::LinkedList;
356 /// let mut dl = LinkedList::new();
357 /// assert!(dl.is_empty());
359 /// dl.push_front("foo");
360 /// assert!(!dl.is_empty());
363 #[stable(feature = "rust1", since = "1.0.0")]
364 pub fn is_empty(&self) -> bool {
368 /// Returns the length of the `LinkedList`.
370 /// This operation should compute in O(1) time.
375 /// use std::collections::LinkedList;
377 /// let mut dl = LinkedList::new();
379 /// dl.push_front(2);
380 /// assert_eq!(dl.len(), 1);
382 /// dl.push_front(1);
383 /// assert_eq!(dl.len(), 2);
386 /// assert_eq!(dl.len(), 3);
389 #[stable(feature = "rust1", since = "1.0.0")]
390 pub fn len(&self) -> usize {
394 /// Removes all elements from the `LinkedList`.
396 /// This operation should compute in O(n) time.
401 /// use std::collections::LinkedList;
403 /// let mut dl = LinkedList::new();
405 /// dl.push_front(2);
406 /// dl.push_front(1);
407 /// assert_eq!(dl.len(), 2);
408 /// assert_eq!(dl.front(), Some(&1));
411 /// assert_eq!(dl.len(), 0);
412 /// assert_eq!(dl.front(), None);
415 #[stable(feature = "rust1", since = "1.0.0")]
416 pub fn clear(&mut self) {
420 /// Returns `true` if the `LinkedList` contains an element equal to the
426 /// use std::collections::LinkedList;
428 /// let mut list: LinkedList<u32> = LinkedList::new();
430 /// list.push_back(0);
431 /// list.push_back(1);
432 /// list.push_back(2);
434 /// assert_eq!(list.contains(&0), true);
435 /// assert_eq!(list.contains(&10), false);
437 #[stable(feature = "linked_list_contains", since = "1.12.0")]
438 pub fn contains(&self, x: &T) -> bool
439 where T: PartialEq<T>
441 self.iter().any(|e| e == x)
444 /// Provides a reference to the front element, or `None` if the list is
450 /// use std::collections::LinkedList;
452 /// let mut dl = LinkedList::new();
453 /// assert_eq!(dl.front(), None);
455 /// dl.push_front(1);
456 /// assert_eq!(dl.front(), Some(&1));
459 #[stable(feature = "rust1", since = "1.0.0")]
460 pub fn front(&self) -> Option<&T> {
461 self.head.map(|node| unsafe { &(**node).element })
464 /// Provides a mutable reference to the front element, or `None` if the list
470 /// use std::collections::LinkedList;
472 /// let mut dl = LinkedList::new();
473 /// assert_eq!(dl.front(), None);
475 /// dl.push_front(1);
476 /// assert_eq!(dl.front(), Some(&1));
478 /// match dl.front_mut() {
480 /// Some(x) => *x = 5,
482 /// assert_eq!(dl.front(), Some(&5));
485 #[stable(feature = "rust1", since = "1.0.0")]
486 pub fn front_mut(&mut self) -> Option<&mut T> {
487 self.head.map(|node| unsafe { &mut (**node).element })
490 /// Provides a reference to the back element, or `None` if the list is
496 /// use std::collections::LinkedList;
498 /// let mut dl = LinkedList::new();
499 /// assert_eq!(dl.back(), None);
502 /// assert_eq!(dl.back(), Some(&1));
505 #[stable(feature = "rust1", since = "1.0.0")]
506 pub fn back(&self) -> Option<&T> {
507 self.tail.map(|node| unsafe { &(**node).element })
510 /// Provides a mutable reference to the back element, or `None` if the list
516 /// use std::collections::LinkedList;
518 /// let mut dl = LinkedList::new();
519 /// assert_eq!(dl.back(), None);
522 /// assert_eq!(dl.back(), Some(&1));
524 /// match dl.back_mut() {
526 /// Some(x) => *x = 5,
528 /// assert_eq!(dl.back(), Some(&5));
531 #[stable(feature = "rust1", since = "1.0.0")]
532 pub fn back_mut(&mut self) -> Option<&mut T> {
533 self.tail.map(|node| unsafe { &mut (**node).element })
536 /// Adds an element first in the list.
538 /// This operation should compute in O(1) time.
543 /// use std::collections::LinkedList;
545 /// let mut dl = LinkedList::new();
547 /// dl.push_front(2);
548 /// assert_eq!(dl.front().unwrap(), &2);
550 /// dl.push_front(1);
551 /// assert_eq!(dl.front().unwrap(), &1);
553 #[stable(feature = "rust1", since = "1.0.0")]
554 pub fn push_front(&mut self, elt: T) {
555 self.push_front_node(box Node::new(elt));
558 /// Removes the first element and returns it, or `None` if the list is
561 /// This operation should compute in O(1) time.
566 /// use std::collections::LinkedList;
568 /// let mut d = LinkedList::new();
569 /// assert_eq!(d.pop_front(), None);
573 /// assert_eq!(d.pop_front(), Some(3));
574 /// assert_eq!(d.pop_front(), Some(1));
575 /// assert_eq!(d.pop_front(), None);
577 #[stable(feature = "rust1", since = "1.0.0")]
578 pub fn pop_front(&mut self) -> Option<T> {
579 self.pop_front_node().map(Node::into_element)
582 /// Appends an element to the back of a list
587 /// use std::collections::LinkedList;
589 /// let mut d = LinkedList::new();
592 /// assert_eq!(3, *d.back().unwrap());
594 #[stable(feature = "rust1", since = "1.0.0")]
595 pub fn push_back(&mut self, elt: T) {
596 self.push_back_node(box Node::new(elt));
599 /// Removes the last element from a list and returns it, or `None` if
605 /// use std::collections::LinkedList;
607 /// let mut d = LinkedList::new();
608 /// assert_eq!(d.pop_back(), None);
611 /// assert_eq!(d.pop_back(), Some(3));
613 #[stable(feature = "rust1", since = "1.0.0")]
614 pub fn pop_back(&mut self) -> Option<T> {
615 self.pop_back_node().map(Node::into_element)
618 /// Splits the list into two at the given index. Returns everything after the given index,
619 /// including the index.
623 /// Panics if `at > len`.
625 /// This operation should compute in O(n) time.
630 /// use std::collections::LinkedList;
632 /// let mut d = LinkedList::new();
638 /// let mut splitted = d.split_off(2);
640 /// assert_eq!(splitted.pop_front(), Some(1));
641 /// assert_eq!(splitted.pop_front(), None);
643 #[stable(feature = "rust1", since = "1.0.0")]
644 pub fn split_off(&mut self, at: usize) -> LinkedList<T> {
645 let len = self.len();
646 assert!(at <= len, "Cannot split off at a nonexistent index");
648 return mem::replace(self, Self::new());
649 } else if at == len {
653 // Below, we iterate towards the `i-1`th node, either from the start or the end,
654 // depending on which would be faster.
655 let split_node = if at - 1 <= len - 1 - (at - 1) {
656 let mut iter = self.iter_mut();
657 // instead of skipping using .skip() (which creates a new struct),
658 // we skip manually so we can access the head field without
659 // depending on implementation details of Skip
665 // better off starting from the end
666 let mut iter = self.iter_mut();
667 for _ in 0..len - 1 - (at - 1) {
673 // The split node is the new tail node of the first part and owns
674 // the head of the second part.
675 let second_part_head;
678 second_part_head = (**split_node.unwrap()).next.take();
679 if let Some(head) = second_part_head {
680 (**head).prev = None;
684 let second_part = LinkedList {
685 head: second_part_head,
691 // Fix the tail ptr of the first part
692 self.tail = split_node;
698 /// Returns a place for insertion at the front of the list.
700 /// Using this method with placement syntax is equivalent to [`push_front`]
701 /// (#method.push_front), but may be more efficient.
706 /// #![feature(collection_placement)]
707 /// #![feature(placement_in_syntax)]
709 /// use std::collections::LinkedList;
711 /// let mut list = LinkedList::new();
712 /// list.front_place() <- 2;
713 /// list.front_place() <- 4;
714 /// assert!(list.iter().eq(&[4, 2]));
716 #[unstable(feature = "collection_placement",
717 reason = "method name and placement protocol are subject to change",
719 pub fn front_place(&mut self) -> FrontPlace<T> {
722 node: IntermediateBox::make_place(),
726 /// Returns a place for insertion at the back of the list.
728 /// Using this method with placement syntax is equivalent to [`push_back`](#method.push_back),
729 /// but may be more efficient.
734 /// #![feature(collection_placement)]
735 /// #![feature(placement_in_syntax)]
737 /// use std::collections::LinkedList;
739 /// let mut list = LinkedList::new();
740 /// list.back_place() <- 2;
741 /// list.back_place() <- 4;
742 /// assert!(list.iter().eq(&[2, 4]));
744 #[unstable(feature = "collection_placement",
745 reason = "method name and placement protocol are subject to change",
747 pub fn back_place(&mut self) -> BackPlace<T> {
750 node: IntermediateBox::make_place(),
755 #[stable(feature = "rust1", since = "1.0.0")]
756 unsafe impl<#[may_dangle] T> Drop for LinkedList<T> {
758 while let Some(_) = self.pop_front_node() {}
762 #[stable(feature = "rust1", since = "1.0.0")]
763 impl<'a, T> Iterator for Iter<'a, T> {
767 fn next(&mut self) -> Option<&'a T> {
771 self.head.map(|node| unsafe {
774 self.head = node.next;
781 fn size_hint(&self) -> (usize, Option<usize>) {
782 (self.len, Some(self.len))
786 #[stable(feature = "rust1", since = "1.0.0")]
787 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
789 fn next_back(&mut self) -> Option<&'a T> {
793 self.tail.map(|node| unsafe {
796 self.tail = node.prev;
803 #[stable(feature = "rust1", since = "1.0.0")]
804 impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
806 #[unstable(feature = "fused", issue = "35602")]
807 impl<'a, T> FusedIterator for Iter<'a, T> {}
809 #[stable(feature = "rust1", since = "1.0.0")]
810 impl<'a, T> Iterator for IterMut<'a, T> {
811 type Item = &'a mut T;
814 fn next(&mut self) -> Option<&'a mut T> {
818 self.head.map(|node| unsafe {
819 let node = &mut **node;
821 self.head = node.next;
828 fn size_hint(&self) -> (usize, Option<usize>) {
829 (self.len, Some(self.len))
833 #[stable(feature = "rust1", since = "1.0.0")]
834 impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
836 fn next_back(&mut self) -> Option<&'a mut T> {
840 self.tail.map(|node| unsafe {
841 let node = &mut **node;
843 self.tail = node.prev;
850 #[stable(feature = "rust1", since = "1.0.0")]
851 impl<'a, T> ExactSizeIterator for IterMut<'a, T> {}
853 #[unstable(feature = "fused", issue = "35602")]
854 impl<'a, T> FusedIterator for IterMut<'a, T> {}
856 impl<'a, T> IterMut<'a, T> {
857 /// Inserts the given element just after the element most recently returned by `.next()`.
858 /// The inserted element does not appear in the iteration.
863 /// #![feature(linked_list_extras)]
865 /// use std::collections::LinkedList;
867 /// let mut list: LinkedList<_> = vec![1, 3, 4].into_iter().collect();
870 /// let mut it = list.iter_mut();
871 /// assert_eq!(it.next().unwrap(), &1);
872 /// // insert `2` after `1`
873 /// it.insert_next(2);
876 /// let vec: Vec<_> = list.into_iter().collect();
877 /// assert_eq!(vec, [1, 2, 3, 4]);
881 #[unstable(feature = "linked_list_extras",
882 reason = "this is probably better handled by a cursor type -- we'll see",
884 pub fn insert_next(&mut self, element: T) {
886 None => self.list.push_back(element),
887 Some(head) => unsafe {
888 let prev = match (**head).prev {
889 None => return self.list.push_front(element),
893 let node = Some(Shared::new(Box::into_raw(box Node {
899 (**prev).next = node;
900 (**head).prev = node;
907 /// Provides a reference to the next element, without changing the iterator.
912 /// #![feature(linked_list_extras)]
914 /// use std::collections::LinkedList;
916 /// let mut list: LinkedList<_> = vec![1, 2, 3].into_iter().collect();
918 /// let mut it = list.iter_mut();
919 /// assert_eq!(it.next().unwrap(), &1);
920 /// assert_eq!(it.peek_next().unwrap(), &2);
921 /// // We just peeked at 2, so it was not consumed from the iterator.
922 /// assert_eq!(it.next().unwrap(), &2);
925 #[unstable(feature = "linked_list_extras",
926 reason = "this is probably better handled by a cursor type -- we'll see",
928 pub fn peek_next(&mut self) -> Option<&mut T> {
932 self.head.map(|node| unsafe { &mut (**node).element })
937 #[stable(feature = "rust1", since = "1.0.0")]
938 impl<T> Iterator for IntoIter<T> {
942 fn next(&mut self) -> Option<T> {
943 self.list.pop_front()
947 fn size_hint(&self) -> (usize, Option<usize>) {
948 (self.list.len, Some(self.list.len))
952 #[stable(feature = "rust1", since = "1.0.0")]
953 impl<T> DoubleEndedIterator for IntoIter<T> {
955 fn next_back(&mut self) -> Option<T> {
960 #[stable(feature = "rust1", since = "1.0.0")]
961 impl<T> ExactSizeIterator for IntoIter<T> {}
963 #[unstable(feature = "fused", issue = "35602")]
964 impl<T> FusedIterator for IntoIter<T> {}
966 #[stable(feature = "rust1", since = "1.0.0")]
967 impl<T> FromIterator<T> for LinkedList<T> {
968 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
969 let mut list = Self::new();
975 #[stable(feature = "rust1", since = "1.0.0")]
976 impl<T> IntoIterator for LinkedList<T> {
978 type IntoIter = IntoIter<T>;
980 /// Consumes the list into an iterator yielding elements by value.
982 fn into_iter(self) -> IntoIter<T> {
983 IntoIter { list: self }
987 #[stable(feature = "rust1", since = "1.0.0")]
988 impl<'a, T> IntoIterator for &'a LinkedList<T> {
990 type IntoIter = Iter<'a, T>;
992 fn into_iter(self) -> Iter<'a, T> {
997 #[stable(feature = "rust1", since = "1.0.0")]
998 impl<'a, T> IntoIterator for &'a mut LinkedList<T> {
999 type Item = &'a mut T;
1000 type IntoIter = IterMut<'a, T>;
1002 fn into_iter(self) -> IterMut<'a, T> {
1007 #[stable(feature = "rust1", since = "1.0.0")]
1008 impl<T> Extend<T> for LinkedList<T> {
1009 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1010 <Self as SpecExtend<I>>::spec_extend(self, iter);
1014 impl<I: IntoIterator> SpecExtend<I> for LinkedList<I::Item> {
1015 default fn spec_extend(&mut self, iter: I) {
1017 self.push_back(elt);
1022 impl<T> SpecExtend<LinkedList<T>> for LinkedList<T> {
1023 fn spec_extend(&mut self, ref mut other: LinkedList<T>) {
1028 #[stable(feature = "extend_ref", since = "1.2.0")]
1029 impl<'a, T: 'a + Copy> Extend<&'a T> for LinkedList<T> {
1030 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
1031 self.extend(iter.into_iter().cloned());
1035 #[stable(feature = "rust1", since = "1.0.0")]
1036 impl<T: PartialEq> PartialEq for LinkedList<T> {
1037 fn eq(&self, other: &Self) -> bool {
1038 self.len() == other.len() && self.iter().eq(other)
1041 fn ne(&self, other: &Self) -> bool {
1042 self.len() != other.len() || self.iter().ne(other)
1046 #[stable(feature = "rust1", since = "1.0.0")]
1047 impl<T: Eq> Eq for LinkedList<T> {}
1049 #[stable(feature = "rust1", since = "1.0.0")]
1050 impl<T: PartialOrd> PartialOrd for LinkedList<T> {
1051 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1052 self.iter().partial_cmp(other)
1056 #[stable(feature = "rust1", since = "1.0.0")]
1057 impl<T: Ord> Ord for LinkedList<T> {
1059 fn cmp(&self, other: &Self) -> Ordering {
1060 self.iter().cmp(other)
1064 #[stable(feature = "rust1", since = "1.0.0")]
1065 impl<T: Clone> Clone for LinkedList<T> {
1066 fn clone(&self) -> Self {
1067 self.iter().cloned().collect()
1071 #[stable(feature = "rust1", since = "1.0.0")]
1072 impl<T: fmt::Debug> fmt::Debug for LinkedList<T> {
1073 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1074 f.debug_list().entries(self).finish()
1078 #[stable(feature = "rust1", since = "1.0.0")]
1079 impl<T: Hash> Hash for LinkedList<T> {
1080 fn hash<H: Hasher>(&self, state: &mut H) {
1081 self.len().hash(state);
1088 unsafe fn finalize<T>(node: IntermediateBox<Node<T>>) -> Box<Node<T>> {
1089 let mut node = node.finalize();
1090 ptr::write(&mut node.next, None);
1091 ptr::write(&mut node.prev, None);
1095 /// A place for insertion at the front of a `LinkedList`.
1097 /// See [`LinkedList::front_place`](struct.LinkedList.html#method.front_place) for details.
1098 #[must_use = "places do nothing unless written to with `<-` syntax"]
1099 #[unstable(feature = "collection_placement",
1100 reason = "struct name and placement protocol are subject to change",
1102 pub struct FrontPlace<'a, T: 'a> {
1103 list: &'a mut LinkedList<T>,
1104 node: IntermediateBox<Node<T>>,
1107 #[unstable(feature = "collection_placement",
1108 reason = "struct name and placement protocol are subject to change",
1110 impl<'a, T: 'a + fmt::Debug> fmt::Debug for FrontPlace<'a, T> {
1111 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1112 f.debug_tuple("FrontPlace")
1113 .field(self.clone())
1118 #[unstable(feature = "collection_placement",
1119 reason = "placement protocol is subject to change",
1121 impl<'a, T> Placer<T> for FrontPlace<'a, T> {
1124 fn make_place(self) -> Self {
1129 #[unstable(feature = "collection_placement",
1130 reason = "placement protocol is subject to change",
1132 impl<'a, T> Place<T> for FrontPlace<'a, T> {
1133 fn pointer(&mut self) -> *mut T {
1134 unsafe { &mut (*self.node.pointer()).element }
1138 #[unstable(feature = "collection_placement",
1139 reason = "placement protocol is subject to change",
1141 impl<'a, T> InPlace<T> for FrontPlace<'a, T> {
1144 unsafe fn finalize(self) {
1145 let FrontPlace { list, node } = self;
1146 list.push_front_node(finalize(node));
1150 /// A place for insertion at the back of a `LinkedList`.
1152 /// See [`LinkedList::back_place`](struct.LinkedList.html#method.back_place) for details.
1153 #[must_use = "places do nothing unless written to with `<-` syntax"]
1154 #[unstable(feature = "collection_placement",
1155 reason = "struct name and placement protocol are subject to change",
1157 pub struct BackPlace<'a, T: 'a> {
1158 list: &'a mut LinkedList<T>,
1159 node: IntermediateBox<Node<T>>,
1162 #[unstable(feature = "collection_placement",
1163 reason = "struct name and placement protocol are subject to change",
1165 impl<'a, T: 'a + fmt::Debug> fmt::Debug for BackPlace<'a, T> {
1166 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1167 f.debug_tuple("BackPlace")
1168 .field(self.clone())
1173 #[unstable(feature = "collection_placement",
1174 reason = "placement protocol is subject to change",
1176 impl<'a, T> Placer<T> for BackPlace<'a, T> {
1179 fn make_place(self) -> Self {
1184 #[unstable(feature = "collection_placement",
1185 reason = "placement protocol is subject to change",
1187 impl<'a, T> Place<T> for BackPlace<'a, T> {
1188 fn pointer(&mut self) -> *mut T {
1189 unsafe { &mut (*self.node.pointer()).element }
1193 #[unstable(feature = "collection_placement",
1194 reason = "placement protocol is subject to change",
1196 impl<'a, T> InPlace<T> for BackPlace<'a, T> {
1199 unsafe fn finalize(self) {
1200 let BackPlace { list, node } = self;
1201 list.push_back_node(finalize(node));
1205 // Ensure that `LinkedList` and its read-only iterators are covariant in their type parameters.
1207 fn assert_covariance() {
1208 fn a<'a>(x: LinkedList<&'static str>) -> LinkedList<&'a str> {
1211 fn b<'i, 'a>(x: Iter<'i, &'static str>) -> Iter<'i, &'a str> {
1214 fn c<'a>(x: IntoIter<&'static str>) -> IntoIter<&'a str> {
1219 #[stable(feature = "rust1", since = "1.0.0")]
1220 unsafe impl<T: Send> Send for LinkedList<T> {}
1222 #[stable(feature = "rust1", since = "1.0.0")]
1223 unsafe impl<T: Sync> Sync for LinkedList<T> {}
1225 #[stable(feature = "rust1", since = "1.0.0")]
1226 unsafe impl<'a, T: Sync> Send for Iter<'a, T> {}
1228 #[stable(feature = "rust1", since = "1.0.0")]
1229 unsafe impl<'a, T: Sync> Sync for Iter<'a, T> {}
1231 #[stable(feature = "rust1", since = "1.0.0")]
1232 unsafe impl<'a, T: Send> Send for IterMut<'a, T> {}
1234 #[stable(feature = "rust1", since = "1.0.0")]
1235 unsafe impl<'a, T: Sync> Sync for IterMut<'a, T> {}
1239 use std::__rand::{thread_rng, Rng};
1243 use super::{LinkedList, Node};
1246 fn list_from<T: Clone>(v: &[T]) -> LinkedList<T> {
1247 v.iter().cloned().collect()
1250 pub fn check_links<T>(list: &LinkedList<T>) {
1253 let mut last_ptr: Option<&Node<T>> = None;
1254 let mut node_ptr: &Node<T>;
1257 assert_eq!(0, list.len);
1260 Some(node) => node_ptr = &**node,
1263 match (last_ptr, node_ptr.prev) {
1265 (None, _) => panic!("prev link for head"),
1266 (Some(p), Some(pptr)) => {
1267 assert_eq!(p as *const Node<T>, *pptr as *const Node<T>);
1269 _ => panic!("prev link is none, not good"),
1271 match node_ptr.next {
1273 last_ptr = Some(node_ptr);
1283 assert_eq!(len, list.len);
1291 let mut m = LinkedList::<i32>::new();
1292 let mut n = LinkedList::new();
1295 assert_eq!(m.len(), 0);
1296 assert_eq!(n.len(), 0);
1298 // Non-empty to empty
1300 let mut m = LinkedList::new();
1301 let mut n = LinkedList::new();
1305 assert_eq!(m.len(), 1);
1306 assert_eq!(m.pop_back(), Some(2));
1307 assert_eq!(n.len(), 0);
1310 // Empty to non-empty
1312 let mut m = LinkedList::new();
1313 let mut n = LinkedList::new();
1317 assert_eq!(m.len(), 1);
1318 assert_eq!(m.pop_back(), Some(2));
1322 // Non-empty to non-empty
1323 let v = vec![1, 2, 3, 4, 5];
1324 let u = vec![9, 8, 1, 2, 3, 4, 5];
1325 let mut m = list_from(&v);
1326 let mut n = list_from(&u);
1330 sum.extend_from_slice(&u);
1331 assert_eq!(sum.len(), m.len());
1333 assert_eq!(m.pop_front(), Some(elt))
1335 assert_eq!(n.len(), 0);
1336 // let's make sure it's working properly, since we
1337 // did some direct changes to private members
1339 assert_eq!(n.len(), 1);
1340 assert_eq!(n.pop_front(), Some(3));
1345 fn test_insert_prev() {
1346 let mut m = list_from(&[0, 2, 4, 6, 8]);
1349 let mut it = m.iter_mut();
1355 it.insert_next(*elt + 1);
1356 match it.peek_next() {
1357 Some(x) => assert_eq!(*x, *elt + 2),
1358 None => assert_eq!(8, *elt),
1367 assert_eq!(m.len(), 3 + len * 2);
1368 assert_eq!(m.into_iter().collect::<Vec<_>>(),
1369 [-2, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1]);
1373 #[cfg_attr(target_os = "emscripten", ignore)]
1375 let n = list_from(&[1, 2, 3]);
1376 thread::spawn(move || {
1378 let a: &[_] = &[&1, &2, &3];
1379 assert_eq!(a, &n.iter().collect::<Vec<_>>()[..]);
1397 // There was a bug in split_off that failed to null out the RHS's head's prev ptr.
1398 // This caused the RHS's dtor to walk up into the LHS at drop and delete all of
1401 // https://github.com/rust-lang/rust/issues/26021
1402 let mut v1 = LinkedList::new();
1407 let _ = v1.split_off(3); // Dropping this now should not cause laundry consumption
1408 assert_eq!(v1.len(), 3);
1410 assert_eq!(v1.iter().len(), 3);
1411 assert_eq!(v1.iter().collect::<Vec<_>>().len(), 3);
1415 fn test_split_off() {
1416 let mut v1 = LinkedList::new();
1423 for ix in 0..1 + v1.len() {
1424 let mut a = v1.clone();
1425 let b = a.split_off(ix);
1434 fn fuzz_test(sz: i32) {
1435 let mut m: LinkedList<_> = LinkedList::new();
1439 let r: u8 = thread_rng().next_u32() as u8;
1465 for (a, &b) in m.into_iter().zip(&v) {
1469 assert_eq!(i, v.len());