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 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`]
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::new(Box::into_raw(node)));
163 None => self.tail = node,
164 Some(head) => (*head.as_mut_ptr()).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_mut_ptr());
177 self.head = node.next;
180 None => self.tail = None,
181 Some(head) => (*head.as_mut_ptr()).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::new(Box::into_raw(node)));
198 None => self.head = node,
199 Some(tail) => (*tail.as_mut_ptr()).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_mut_ptr());
212 self.tail = node.prev;
215 None => self.head = None,
216 Some(tail) => (*tail.as_mut_ptr()).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(other_head) = other.head.take() {
291 (*tail.as_mut_ptr()).next = Some(other_head);
292 (*other_head.as_mut_ptr()).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> {
480 self.head.map(|node| unsafe { &(**node).element })
483 /// Provides a mutable reference to the front element, or `None` if the list
489 /// use std::collections::LinkedList;
491 /// let mut dl = LinkedList::new();
492 /// assert_eq!(dl.front(), None);
494 /// dl.push_front(1);
495 /// assert_eq!(dl.front(), Some(&1));
497 /// match dl.front_mut() {
499 /// Some(x) => *x = 5,
501 /// assert_eq!(dl.front(), Some(&5));
504 #[stable(feature = "rust1", since = "1.0.0")]
505 pub fn front_mut(&mut self) -> Option<&mut T> {
506 self.head.map(|node| unsafe { &mut (*node.as_mut_ptr()).element })
509 /// Provides a reference to the back element, or `None` if the list is
515 /// use std::collections::LinkedList;
517 /// let mut dl = LinkedList::new();
518 /// assert_eq!(dl.back(), None);
521 /// assert_eq!(dl.back(), Some(&1));
524 #[stable(feature = "rust1", since = "1.0.0")]
525 pub fn back(&self) -> Option<&T> {
526 self.tail.map(|node| unsafe { &(**node).element })
529 /// Provides a mutable reference to the back element, or `None` if the list
535 /// use std::collections::LinkedList;
537 /// let mut dl = LinkedList::new();
538 /// assert_eq!(dl.back(), None);
541 /// assert_eq!(dl.back(), Some(&1));
543 /// match dl.back_mut() {
545 /// Some(x) => *x = 5,
547 /// assert_eq!(dl.back(), Some(&5));
550 #[stable(feature = "rust1", since = "1.0.0")]
551 pub fn back_mut(&mut self) -> Option<&mut T> {
552 self.tail.map(|node| unsafe { &mut (*node.as_mut_ptr()).element })
555 /// Adds an element first in the list.
557 /// This operation should compute in O(1) time.
562 /// use std::collections::LinkedList;
564 /// let mut dl = LinkedList::new();
566 /// dl.push_front(2);
567 /// assert_eq!(dl.front().unwrap(), &2);
569 /// dl.push_front(1);
570 /// assert_eq!(dl.front().unwrap(), &1);
572 #[stable(feature = "rust1", since = "1.0.0")]
573 pub fn push_front(&mut self, elt: T) {
574 self.push_front_node(box Node::new(elt));
577 /// Removes the first element and returns it, or `None` if the list is
580 /// This operation should compute in O(1) time.
585 /// use std::collections::LinkedList;
587 /// let mut d = LinkedList::new();
588 /// assert_eq!(d.pop_front(), None);
592 /// assert_eq!(d.pop_front(), Some(3));
593 /// assert_eq!(d.pop_front(), Some(1));
594 /// assert_eq!(d.pop_front(), None);
596 #[stable(feature = "rust1", since = "1.0.0")]
597 pub fn pop_front(&mut self) -> Option<T> {
598 self.pop_front_node().map(Node::into_element)
601 /// Appends an element to the back of a list
606 /// use std::collections::LinkedList;
608 /// let mut d = LinkedList::new();
611 /// assert_eq!(3, *d.back().unwrap());
613 #[stable(feature = "rust1", since = "1.0.0")]
614 pub fn push_back(&mut self, elt: T) {
615 self.push_back_node(box Node::new(elt));
618 /// Removes the last element from a list and returns it, or `None` if
624 /// use std::collections::LinkedList;
626 /// let mut d = LinkedList::new();
627 /// assert_eq!(d.pop_back(), None);
630 /// assert_eq!(d.pop_back(), Some(3));
632 #[stable(feature = "rust1", since = "1.0.0")]
633 pub fn pop_back(&mut self) -> Option<T> {
634 self.pop_back_node().map(Node::into_element)
637 /// Splits the list into two at the given index. Returns everything after the given index,
638 /// including the index.
640 /// This operation should compute in O(n) time.
644 /// Panics if `at > len`.
649 /// use std::collections::LinkedList;
651 /// let mut d = LinkedList::new();
657 /// let mut splitted = d.split_off(2);
659 /// assert_eq!(splitted.pop_front(), Some(1));
660 /// assert_eq!(splitted.pop_front(), None);
662 #[stable(feature = "rust1", since = "1.0.0")]
663 pub fn split_off(&mut self, at: usize) -> LinkedList<T> {
664 let len = self.len();
665 assert!(at <= len, "Cannot split off at a nonexistent index");
667 return mem::replace(self, Self::new());
668 } else if at == len {
672 // Below, we iterate towards the `i-1`th node, either from the start or the end,
673 // depending on which would be faster.
674 let split_node = if at - 1 <= len - 1 - (at - 1) {
675 let mut iter = self.iter_mut();
676 // instead of skipping using .skip() (which creates a new struct),
677 // we skip manually so we can access the head field without
678 // depending on implementation details of Skip
684 // better off starting from the end
685 let mut iter = self.iter_mut();
686 for _ in 0..len - 1 - (at - 1) {
692 // The split node is the new tail node of the first part and owns
693 // the head of the second part.
694 let second_part_head;
697 second_part_head = (*split_node.unwrap().as_mut_ptr()).next.take();
698 if let Some(head) = second_part_head {
699 (*head.as_mut_ptr()).prev = None;
703 let second_part = LinkedList {
704 head: second_part_head,
710 // Fix the tail ptr of the first part
711 self.tail = split_node;
717 /// Returns a place for insertion at the front of the list.
719 /// Using this method with placement syntax is equivalent to
720 /// [`push_front`](#method.push_front), but may be more efficient.
725 /// #![feature(collection_placement)]
726 /// #![feature(placement_in_syntax)]
728 /// use std::collections::LinkedList;
730 /// let mut list = LinkedList::new();
731 /// list.front_place() <- 2;
732 /// list.front_place() <- 4;
733 /// assert!(list.iter().eq(&[4, 2]));
735 #[unstable(feature = "collection_placement",
736 reason = "method name and placement protocol are subject to change",
738 pub fn front_place(&mut self) -> FrontPlace<T> {
741 node: IntermediateBox::make_place(),
745 /// Returns a place for insertion at the back of the list.
747 /// Using this method with placement syntax is equivalent to [`push_back`](#method.push_back),
748 /// but may be more efficient.
753 /// #![feature(collection_placement)]
754 /// #![feature(placement_in_syntax)]
756 /// use std::collections::LinkedList;
758 /// let mut list = LinkedList::new();
759 /// list.back_place() <- 2;
760 /// list.back_place() <- 4;
761 /// assert!(list.iter().eq(&[2, 4]));
763 #[unstable(feature = "collection_placement",
764 reason = "method name and placement protocol are subject to change",
766 pub fn back_place(&mut self) -> BackPlace<T> {
769 node: IntermediateBox::make_place(),
774 #[stable(feature = "rust1", since = "1.0.0")]
775 unsafe impl<#[may_dangle] T> Drop for LinkedList<T> {
777 while let Some(_) = self.pop_front_node() {}
781 #[stable(feature = "rust1", since = "1.0.0")]
782 impl<'a, T> Iterator for Iter<'a, T> {
786 fn next(&mut self) -> Option<&'a T> {
790 self.head.map(|node| unsafe {
793 self.head = node.next;
800 fn size_hint(&self) -> (usize, Option<usize>) {
801 (self.len, Some(self.len))
805 #[stable(feature = "rust1", since = "1.0.0")]
806 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
808 fn next_back(&mut self) -> Option<&'a T> {
812 self.tail.map(|node| unsafe {
815 self.tail = node.prev;
822 #[stable(feature = "rust1", since = "1.0.0")]
823 impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
825 #[unstable(feature = "fused", issue = "35602")]
826 impl<'a, T> FusedIterator for Iter<'a, T> {}
828 #[stable(feature = "rust1", since = "1.0.0")]
829 impl<'a, T> Iterator for IterMut<'a, T> {
830 type Item = &'a mut T;
833 fn next(&mut self) -> Option<&'a mut T> {
837 self.head.map(|node| unsafe {
838 let node = &mut *node.as_mut_ptr();
840 self.head = node.next;
847 fn size_hint(&self) -> (usize, Option<usize>) {
848 (self.len, Some(self.len))
852 #[stable(feature = "rust1", since = "1.0.0")]
853 impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
855 fn next_back(&mut self) -> Option<&'a mut T> {
859 self.tail.map(|node| unsafe {
860 let node = &mut *node.as_mut_ptr();
862 self.tail = node.prev;
869 #[stable(feature = "rust1", since = "1.0.0")]
870 impl<'a, T> ExactSizeIterator for IterMut<'a, T> {}
872 #[unstable(feature = "fused", issue = "35602")]
873 impl<'a, T> FusedIterator for IterMut<'a, T> {}
875 impl<'a, T> IterMut<'a, T> {
876 /// Inserts the given element just after the element most recently returned by `.next()`.
877 /// The inserted element does not appear in the iteration.
882 /// #![feature(linked_list_extras)]
884 /// use std::collections::LinkedList;
886 /// let mut list: LinkedList<_> = vec![1, 3, 4].into_iter().collect();
889 /// let mut it = list.iter_mut();
890 /// assert_eq!(it.next().unwrap(), &1);
891 /// // insert `2` after `1`
892 /// it.insert_next(2);
895 /// let vec: Vec<_> = list.into_iter().collect();
896 /// assert_eq!(vec, [1, 2, 3, 4]);
900 #[unstable(feature = "linked_list_extras",
901 reason = "this is probably better handled by a cursor type -- we'll see",
903 pub fn insert_next(&mut self, element: T) {
905 None => self.list.push_back(element),
906 Some(head) => unsafe {
907 let prev = match (**head).prev {
908 None => return self.list.push_front(element),
912 let node = Some(Shared::new(Box::into_raw(box Node {
918 (*prev.as_mut_ptr()).next = node;
919 (*head.as_mut_ptr()).prev = node;
926 /// Provides a reference to the next element, without changing the iterator.
931 /// #![feature(linked_list_extras)]
933 /// use std::collections::LinkedList;
935 /// let mut list: LinkedList<_> = vec![1, 2, 3].into_iter().collect();
937 /// let mut it = list.iter_mut();
938 /// assert_eq!(it.next().unwrap(), &1);
939 /// assert_eq!(it.peek_next().unwrap(), &2);
940 /// // We just peeked at 2, so it was not consumed from the iterator.
941 /// assert_eq!(it.next().unwrap(), &2);
944 #[unstable(feature = "linked_list_extras",
945 reason = "this is probably better handled by a cursor type -- we'll see",
947 pub fn peek_next(&mut self) -> Option<&mut T> {
951 self.head.map(|node| unsafe { &mut (*node.as_mut_ptr()).element })
956 #[stable(feature = "rust1", since = "1.0.0")]
957 impl<T> Iterator for IntoIter<T> {
961 fn next(&mut self) -> Option<T> {
962 self.list.pop_front()
966 fn size_hint(&self) -> (usize, Option<usize>) {
967 (self.list.len, Some(self.list.len))
971 #[stable(feature = "rust1", since = "1.0.0")]
972 impl<T> DoubleEndedIterator for IntoIter<T> {
974 fn next_back(&mut self) -> Option<T> {
979 #[stable(feature = "rust1", since = "1.0.0")]
980 impl<T> ExactSizeIterator for IntoIter<T> {}
982 #[unstable(feature = "fused", issue = "35602")]
983 impl<T> FusedIterator for IntoIter<T> {}
985 #[stable(feature = "rust1", since = "1.0.0")]
986 impl<T> FromIterator<T> for LinkedList<T> {
987 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
988 let mut list = Self::new();
994 #[stable(feature = "rust1", since = "1.0.0")]
995 impl<T> IntoIterator for LinkedList<T> {
997 type IntoIter = IntoIter<T>;
999 /// Consumes the list into an iterator yielding elements by value.
1001 fn into_iter(self) -> IntoIter<T> {
1002 IntoIter { list: self }
1006 #[stable(feature = "rust1", since = "1.0.0")]
1007 impl<'a, T> IntoIterator for &'a LinkedList<T> {
1009 type IntoIter = Iter<'a, T>;
1011 fn into_iter(self) -> Iter<'a, T> {
1016 #[stable(feature = "rust1", since = "1.0.0")]
1017 impl<'a, T> IntoIterator for &'a mut LinkedList<T> {
1018 type Item = &'a mut T;
1019 type IntoIter = IterMut<'a, T>;
1021 fn into_iter(self) -> IterMut<'a, T> {
1026 #[stable(feature = "rust1", since = "1.0.0")]
1027 impl<T> Extend<T> for LinkedList<T> {
1028 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1029 <Self as SpecExtend<I>>::spec_extend(self, iter);
1033 impl<I: IntoIterator> SpecExtend<I> for LinkedList<I::Item> {
1034 default fn spec_extend(&mut self, iter: I) {
1036 self.push_back(elt);
1041 impl<T> SpecExtend<LinkedList<T>> for LinkedList<T> {
1042 fn spec_extend(&mut self, ref mut other: LinkedList<T>) {
1047 #[stable(feature = "extend_ref", since = "1.2.0")]
1048 impl<'a, T: 'a + Copy> Extend<&'a T> for LinkedList<T> {
1049 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
1050 self.extend(iter.into_iter().cloned());
1054 #[stable(feature = "rust1", since = "1.0.0")]
1055 impl<T: PartialEq> PartialEq for LinkedList<T> {
1056 fn eq(&self, other: &Self) -> bool {
1057 self.len() == other.len() && self.iter().eq(other)
1060 fn ne(&self, other: &Self) -> bool {
1061 self.len() != other.len() || self.iter().ne(other)
1065 #[stable(feature = "rust1", since = "1.0.0")]
1066 impl<T: Eq> Eq for LinkedList<T> {}
1068 #[stable(feature = "rust1", since = "1.0.0")]
1069 impl<T: PartialOrd> PartialOrd for LinkedList<T> {
1070 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1071 self.iter().partial_cmp(other)
1075 #[stable(feature = "rust1", since = "1.0.0")]
1076 impl<T: Ord> Ord for LinkedList<T> {
1078 fn cmp(&self, other: &Self) -> Ordering {
1079 self.iter().cmp(other)
1083 #[stable(feature = "rust1", since = "1.0.0")]
1084 impl<T: Clone> Clone for LinkedList<T> {
1085 fn clone(&self) -> Self {
1086 self.iter().cloned().collect()
1090 #[stable(feature = "rust1", since = "1.0.0")]
1091 impl<T: fmt::Debug> fmt::Debug for LinkedList<T> {
1092 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1093 f.debug_list().entries(self).finish()
1097 #[stable(feature = "rust1", since = "1.0.0")]
1098 impl<T: Hash> Hash for LinkedList<T> {
1099 fn hash<H: Hasher>(&self, state: &mut H) {
1100 self.len().hash(state);
1107 unsafe fn finalize<T>(node: IntermediateBox<Node<T>>) -> Box<Node<T>> {
1108 let mut node = node.finalize();
1109 ptr::write(&mut node.next, None);
1110 ptr::write(&mut node.prev, None);
1114 /// A place for insertion at the front of a `LinkedList`.
1116 /// See [`LinkedList::front_place`](struct.LinkedList.html#method.front_place) for details.
1117 #[must_use = "places do nothing unless written to with `<-` syntax"]
1118 #[unstable(feature = "collection_placement",
1119 reason = "struct name and placement protocol are subject to change",
1121 pub struct FrontPlace<'a, T: 'a> {
1122 list: &'a mut LinkedList<T>,
1123 node: IntermediateBox<Node<T>>,
1126 #[unstable(feature = "collection_placement",
1127 reason = "struct name and placement protocol are subject to change",
1129 impl<'a, T: 'a + fmt::Debug> fmt::Debug for FrontPlace<'a, T> {
1130 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1131 f.debug_tuple("FrontPlace")
1137 #[unstable(feature = "collection_placement",
1138 reason = "placement protocol is subject to change",
1140 impl<'a, T> Placer<T> for FrontPlace<'a, T> {
1143 fn make_place(self) -> Self {
1148 #[unstable(feature = "collection_placement",
1149 reason = "placement protocol is subject to change",
1151 impl<'a, T> Place<T> for FrontPlace<'a, T> {
1152 fn pointer(&mut self) -> *mut T {
1153 unsafe { &mut (*self.node.pointer()).element }
1157 #[unstable(feature = "collection_placement",
1158 reason = "placement protocol is subject to change",
1160 impl<'a, T> InPlace<T> for FrontPlace<'a, T> {
1163 unsafe fn finalize(self) {
1164 let FrontPlace { list, node } = self;
1165 list.push_front_node(finalize(node));
1169 /// A place for insertion at the back of a `LinkedList`.
1171 /// See [`LinkedList::back_place`](struct.LinkedList.html#method.back_place) for details.
1172 #[must_use = "places do nothing unless written to with `<-` syntax"]
1173 #[unstable(feature = "collection_placement",
1174 reason = "struct name and placement protocol are subject to change",
1176 pub struct BackPlace<'a, T: 'a> {
1177 list: &'a mut LinkedList<T>,
1178 node: IntermediateBox<Node<T>>,
1181 #[unstable(feature = "collection_placement",
1182 reason = "struct name and placement protocol are subject to change",
1184 impl<'a, T: 'a + fmt::Debug> fmt::Debug for BackPlace<'a, T> {
1185 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1186 f.debug_tuple("BackPlace")
1192 #[unstable(feature = "collection_placement",
1193 reason = "placement protocol is subject to change",
1195 impl<'a, T> Placer<T> for BackPlace<'a, T> {
1198 fn make_place(self) -> Self {
1203 #[unstable(feature = "collection_placement",
1204 reason = "placement protocol is subject to change",
1206 impl<'a, T> Place<T> for BackPlace<'a, T> {
1207 fn pointer(&mut self) -> *mut T {
1208 unsafe { &mut (*self.node.pointer()).element }
1212 #[unstable(feature = "collection_placement",
1213 reason = "placement protocol is subject to change",
1215 impl<'a, T> InPlace<T> for BackPlace<'a, T> {
1218 unsafe fn finalize(self) {
1219 let BackPlace { list, node } = self;
1220 list.push_back_node(finalize(node));
1224 // Ensure that `LinkedList` and its read-only iterators are covariant in their type parameters.
1226 fn assert_covariance() {
1227 fn a<'a>(x: LinkedList<&'static str>) -> LinkedList<&'a str> {
1230 fn b<'i, 'a>(x: Iter<'i, &'static str>) -> Iter<'i, &'a str> {
1233 fn c<'a>(x: IntoIter<&'static str>) -> IntoIter<&'a str> {
1238 #[stable(feature = "rust1", since = "1.0.0")]
1239 unsafe impl<T: Send> Send for LinkedList<T> {}
1241 #[stable(feature = "rust1", since = "1.0.0")]
1242 unsafe impl<T: Sync> Sync for LinkedList<T> {}
1244 #[stable(feature = "rust1", since = "1.0.0")]
1245 unsafe impl<'a, T: Sync> Send for Iter<'a, T> {}
1247 #[stable(feature = "rust1", since = "1.0.0")]
1248 unsafe impl<'a, T: Sync> Sync for Iter<'a, T> {}
1250 #[stable(feature = "rust1", since = "1.0.0")]
1251 unsafe impl<'a, T: Send> Send for IterMut<'a, T> {}
1253 #[stable(feature = "rust1", since = "1.0.0")]
1254 unsafe impl<'a, T: Sync> Sync for IterMut<'a, T> {}
1258 use std::__rand::{thread_rng, Rng};
1262 use super::{LinkedList, Node};
1265 fn list_from<T: Clone>(v: &[T]) -> LinkedList<T> {
1266 v.iter().cloned().collect()
1269 pub fn check_links<T>(list: &LinkedList<T>) {
1272 let mut last_ptr: Option<&Node<T>> = None;
1273 let mut node_ptr: &Node<T>;
1276 assert_eq!(0, list.len);
1279 Some(node) => node_ptr = &**node,
1282 match (last_ptr, node_ptr.prev) {
1284 (None, _) => panic!("prev link for head"),
1285 (Some(p), Some(pptr)) => {
1286 assert_eq!(p as *const Node<T>, *pptr as *const Node<T>);
1288 _ => panic!("prev link is none, not good"),
1290 match node_ptr.next {
1292 last_ptr = Some(node_ptr);
1302 assert_eq!(len, list.len);
1310 let mut m = LinkedList::<i32>::new();
1311 let mut n = LinkedList::new();
1314 assert_eq!(m.len(), 0);
1315 assert_eq!(n.len(), 0);
1317 // Non-empty to empty
1319 let mut m = LinkedList::new();
1320 let mut n = LinkedList::new();
1324 assert_eq!(m.len(), 1);
1325 assert_eq!(m.pop_back(), Some(2));
1326 assert_eq!(n.len(), 0);
1329 // Empty to non-empty
1331 let mut m = LinkedList::new();
1332 let mut n = LinkedList::new();
1336 assert_eq!(m.len(), 1);
1337 assert_eq!(m.pop_back(), Some(2));
1341 // Non-empty to non-empty
1342 let v = vec![1, 2, 3, 4, 5];
1343 let u = vec![9, 8, 1, 2, 3, 4, 5];
1344 let mut m = list_from(&v);
1345 let mut n = list_from(&u);
1349 sum.extend_from_slice(&u);
1350 assert_eq!(sum.len(), m.len());
1352 assert_eq!(m.pop_front(), Some(elt))
1354 assert_eq!(n.len(), 0);
1355 // let's make sure it's working properly, since we
1356 // did some direct changes to private members
1358 assert_eq!(n.len(), 1);
1359 assert_eq!(n.pop_front(), Some(3));
1364 fn test_insert_prev() {
1365 let mut m = list_from(&[0, 2, 4, 6, 8]);
1368 let mut it = m.iter_mut();
1374 it.insert_next(*elt + 1);
1375 match it.peek_next() {
1376 Some(x) => assert_eq!(*x, *elt + 2),
1377 None => assert_eq!(8, *elt),
1386 assert_eq!(m.len(), 3 + len * 2);
1387 assert_eq!(m.into_iter().collect::<Vec<_>>(),
1388 [-2, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1]);
1392 #[cfg_attr(target_os = "emscripten", ignore)]
1394 let n = list_from(&[1, 2, 3]);
1395 thread::spawn(move || {
1397 let a: &[_] = &[&1, &2, &3];
1398 assert_eq!(a, &*n.iter().collect::<Vec<_>>());
1416 // There was a bug in split_off that failed to null out the RHS's head's prev ptr.
1417 // This caused the RHS's dtor to walk up into the LHS at drop and delete all of
1420 // https://github.com/rust-lang/rust/issues/26021
1421 let mut v1 = LinkedList::new();
1426 let _ = v1.split_off(3); // Dropping this now should not cause laundry consumption
1427 assert_eq!(v1.len(), 3);
1429 assert_eq!(v1.iter().len(), 3);
1430 assert_eq!(v1.iter().collect::<Vec<_>>().len(), 3);
1434 fn test_split_off() {
1435 let mut v1 = LinkedList::new();
1442 for ix in 0..1 + v1.len() {
1443 let mut a = v1.clone();
1444 let b = a.split_off(ix);
1453 fn fuzz_test(sz: i32) {
1454 let mut m: LinkedList<_> = LinkedList::new();
1458 let r: u8 = thread_rng().next_u32() as u8;
1484 for (a, &b) in m.into_iter().zip(&v) {
1488 assert_eq!(i, v.len());