]> git.lizzy.rs Git - rust.git/blob - src/libcollections/linked_list.rs
Rollup merge of #31295 - steveklabnik:gh31266, r=alexcrichton
[rust.git] / src / libcollections / linked_list.rs
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.
4 //
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.
10
11 //! A doubly-linked list with owned nodes.
12 //!
13 //! The `LinkedList` allows pushing and popping elements at either end and is thus
14 //! efficiently usable as a double-ended queue.
15
16 // LinkedList is constructed like a singly-linked list over the field `next`.
17 // including the last link being None; each Node owns its `next` field.
18 //
19 // Backlinks over LinkedList::prev are raw pointers that form a full chain in
20 // the reverse direction.
21
22 #![stable(feature = "rust1", since = "1.0.0")]
23
24 use alloc::boxed::Box;
25 use core::cmp::Ordering;
26 use core::fmt;
27 use core::hash::{Hasher, Hash};
28 use core::iter::FromIterator;
29 use core::mem;
30 use core::ptr::Shared;
31
32 /// A doubly-linked list.
33 #[stable(feature = "rust1", since = "1.0.0")]
34 pub struct LinkedList<T> {
35     length: usize,
36     list_head: Link<T>,
37     list_tail: Rawlink<Node<T>>,
38 }
39
40 type Link<T> = Option<Box<Node<T>>>;
41
42 struct Rawlink<T> {
43     p: Option<Shared<T>>,
44 }
45
46 impl<T> Copy for Rawlink<T> {}
47 unsafe impl<T: Send> Send for Rawlink<T> {}
48 unsafe impl<T: Sync> Sync for Rawlink<T> {}
49
50 struct Node<T> {
51     next: Link<T>,
52     prev: Rawlink<Node<T>>,
53     value: T,
54 }
55
56 /// An iterator over references to the items of a `LinkedList`.
57 #[stable(feature = "rust1", since = "1.0.0")]
58 pub struct Iter<'a, T: 'a> {
59     head: &'a Link<T>,
60     tail: Rawlink<Node<T>>,
61     nelem: usize,
62 }
63
64 // FIXME #19839: deriving is too aggressive on the bounds (T doesn't need to be Clone).
65 #[stable(feature = "rust1", since = "1.0.0")]
66 impl<'a, T> Clone for Iter<'a, T> {
67     fn clone(&self) -> Iter<'a, T> {
68         Iter {
69             head: self.head.clone(),
70             tail: self.tail,
71             nelem: self.nelem,
72         }
73     }
74 }
75
76 /// An iterator over mutable references to the items 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: Rawlink<Node<T>>,
81     tail: Rawlink<Node<T>>,
82     nelem: usize,
83 }
84
85 /// An iterator over mutable references to the items of a `LinkedList`.
86 #[derive(Clone)]
87 #[stable(feature = "rust1", since = "1.0.0")]
88 pub struct IntoIter<T> {
89     list: LinkedList<T>,
90 }
91
92 /// Rawlink is a type like Option<T> but for holding a raw pointer
93 impl<T> Rawlink<T> {
94     /// Like Option::None for Rawlink
95     fn none() -> Rawlink<T> {
96         Rawlink { p: None }
97     }
98
99     /// Like Option::Some for Rawlink
100     fn some(n: &mut T) -> Rawlink<T> {
101         unsafe { Rawlink { p: Some(Shared::new(n)) } }
102     }
103
104     /// Convert the `Rawlink` into an Option value
105     ///
106     /// **unsafe** because:
107     ///
108     /// - Dereference of raw pointer.
109     /// - Returns reference of arbitrary lifetime.
110     unsafe fn resolve<'a>(&self) -> Option<&'a T> {
111         self.p.map(|p| &**p)
112     }
113
114     /// Convert the `Rawlink` into an Option value
115     ///
116     /// **unsafe** because:
117     ///
118     /// - Dereference of raw pointer.
119     /// - Returns reference of arbitrary lifetime.
120     unsafe fn resolve_mut<'a>(&mut self) -> Option<&'a mut T> {
121         self.p.map(|p| &mut **p)
122     }
123
124     /// Return the `Rawlink` and replace with `Rawlink::none()`
125     fn take(&mut self) -> Rawlink<T> {
126         mem::replace(self, Rawlink::none())
127     }
128 }
129
130 impl<'a, T> From<&'a mut Link<T>> for Rawlink<Node<T>> {
131     fn from(node: &'a mut Link<T>) -> Self {
132         match node.as_mut() {
133             None => Rawlink::none(),
134             Some(ptr) => Rawlink::some(ptr),
135         }
136     }
137 }
138
139 impl<T> Clone for Rawlink<T> {
140     #[inline]
141     fn clone(&self) -> Rawlink<T> {
142         Rawlink { p: self.p }
143     }
144 }
145
146 impl<T> Node<T> {
147     fn new(v: T) -> Node<T> {
148         Node {
149             value: v,
150             next: None,
151             prev: Rawlink::none(),
152         }
153     }
154
155     /// Update the `prev` link on `next`, then set self's next pointer.
156     ///
157     /// `self.next` should be `None` when you call this
158     /// (otherwise a Node is probably being dropped by mistake).
159     fn set_next(&mut self, mut next: Box<Node<T>>) {
160         debug_assert!(self.next.is_none());
161         next.prev = Rawlink::some(self);
162         self.next = Some(next);
163     }
164 }
165
166 /// Clear the .prev field on `next`, then return `Some(next)`
167 fn link_no_prev<T>(mut next: Box<Node<T>>) -> Link<T> {
168     next.prev = Rawlink::none();
169     Some(next)
170 }
171
172 // private methods
173 impl<T> LinkedList<T> {
174     /// Add a Node first in the list
175     #[inline]
176     fn push_front_node(&mut self, mut new_head: Box<Node<T>>) {
177         match self.list_head {
178             None => {
179                 self.list_head = link_no_prev(new_head);
180                 self.list_tail = Rawlink::from(&mut self.list_head);
181             }
182             Some(ref mut head) => {
183                 new_head.prev = Rawlink::none();
184                 head.prev = Rawlink::some(&mut *new_head);
185                 mem::swap(head, &mut new_head);
186                 head.next = Some(new_head);
187             }
188         }
189         self.length += 1;
190     }
191
192     /// Remove the first Node and return it, or None if the list is empty
193     #[inline]
194     fn pop_front_node(&mut self) -> Option<Box<Node<T>>> {
195         self.list_head.take().map(|mut front_node| {
196             self.length -= 1;
197             match front_node.next.take() {
198                 Some(node) => self.list_head = link_no_prev(node),
199                 None => self.list_tail = Rawlink::none(),
200             }
201             front_node
202         })
203     }
204
205     /// Add a Node last in the list
206     #[inline]
207     fn push_back_node(&mut self, new_tail: Box<Node<T>>) {
208         match unsafe { self.list_tail.resolve_mut() } {
209             None => return self.push_front_node(new_tail),
210             Some(tail) => {
211                 tail.set_next(new_tail);
212                 self.list_tail = Rawlink::from(&mut tail.next);
213             }
214         }
215         self.length += 1;
216     }
217
218     /// Remove the last Node and return it, or None if the list is empty
219     #[inline]
220     fn pop_back_node(&mut self) -> Option<Box<Node<T>>> {
221         unsafe {
222             self.list_tail.resolve_mut().and_then(|tail| {
223                 self.length -= 1;
224                 self.list_tail = tail.prev;
225                 match tail.prev.resolve_mut() {
226                     None => self.list_head.take(),
227                     Some(tail_prev) => tail_prev.next.take(),
228                 }
229             })
230         }
231     }
232 }
233
234 #[stable(feature = "rust1", since = "1.0.0")]
235 impl<T> Default for LinkedList<T> {
236     #[inline]
237     fn default() -> LinkedList<T> {
238         LinkedList::new()
239     }
240 }
241
242 impl<T> LinkedList<T> {
243     /// Creates an empty `LinkedList`.
244     #[inline]
245     #[stable(feature = "rust1", since = "1.0.0")]
246     pub fn new() -> LinkedList<T> {
247         LinkedList {
248             list_head: None,
249             list_tail: Rawlink::none(),
250             length: 0,
251         }
252     }
253
254     /// Moves all elements from `other` to the end of the list.
255     ///
256     /// This reuses all the nodes from `other` and moves them into `self`. After
257     /// this operation, `other` becomes empty.
258     ///
259     /// This operation should compute in O(1) time and O(1) memory.
260     ///
261     /// # Examples
262     ///
263     /// ```
264     /// use std::collections::LinkedList;
265     ///
266     /// let mut a = LinkedList::new();
267     /// let mut b = LinkedList::new();
268     /// a.push_back(1);
269     /// a.push_back(2);
270     /// b.push_back(3);
271     /// b.push_back(4);
272     ///
273     /// a.append(&mut b);
274     ///
275     /// for e in &a {
276     ///     println!("{}", e); // prints 1, then 2, then 3, then 4
277     /// }
278     /// println!("{}", b.len()); // prints 0
279     /// ```
280     #[stable(feature = "rust1", since = "1.0.0")]
281     pub fn append(&mut self, other: &mut LinkedList<T>) {
282         match unsafe { self.list_tail.resolve_mut() } {
283             None => {
284                 self.length = other.length;
285                 self.list_head = other.list_head.take();
286                 self.list_tail = other.list_tail.take();
287             }
288             Some(tail) => {
289                 // Carefully empty `other`.
290                 let o_tail = other.list_tail.take();
291                 let o_length = other.length;
292                 match other.list_head.take() {
293                     None => return,
294                     Some(node) => {
295                         tail.set_next(node);
296                         self.list_tail = o_tail;
297                         self.length += o_length;
298                     }
299                 }
300             }
301         }
302         other.length = 0;
303     }
304
305     /// Provides a forward iterator.
306     #[inline]
307     #[stable(feature = "rust1", since = "1.0.0")]
308     pub fn iter(&self) -> Iter<T> {
309         Iter {
310             nelem: self.len(),
311             head: &self.list_head,
312             tail: self.list_tail,
313         }
314     }
315
316     /// Provides a forward iterator with mutable references.
317     #[inline]
318     #[stable(feature = "rust1", since = "1.0.0")]
319     pub fn iter_mut(&mut self) -> IterMut<T> {
320         IterMut {
321             nelem: self.len(),
322             head: Rawlink::from(&mut self.list_head),
323             tail: self.list_tail,
324             list: self,
325         }
326     }
327
328     /// Returns `true` if the `LinkedList` is empty.
329     ///
330     /// This operation should compute in O(1) time.
331     ///
332     /// # Examples
333     ///
334     /// ```
335     /// use std::collections::LinkedList;
336     ///
337     /// let mut dl = LinkedList::new();
338     /// assert!(dl.is_empty());
339     ///
340     /// dl.push_front("foo");
341     /// assert!(!dl.is_empty());
342     /// ```
343     #[inline]
344     #[stable(feature = "rust1", since = "1.0.0")]
345     pub fn is_empty(&self) -> bool {
346         self.list_head.is_none()
347     }
348
349     /// Returns the length of the `LinkedList`.
350     ///
351     /// This operation should compute in O(1) time.
352     ///
353     /// # Examples
354     ///
355     /// ```
356     /// use std::collections::LinkedList;
357     ///
358     /// let mut dl = LinkedList::new();
359     ///
360     /// dl.push_front(2);
361     /// assert_eq!(dl.len(), 1);
362     ///
363     /// dl.push_front(1);
364     /// assert_eq!(dl.len(), 2);
365     ///
366     /// dl.push_back(3);
367     /// assert_eq!(dl.len(), 3);
368     ///
369     /// ```
370     #[inline]
371     #[stable(feature = "rust1", since = "1.0.0")]
372     pub fn len(&self) -> usize {
373         self.length
374     }
375
376     /// Removes all elements from the `LinkedList`.
377     ///
378     /// This operation should compute in O(n) time.
379     ///
380     /// # Examples
381     ///
382     /// ```
383     /// use std::collections::LinkedList;
384     ///
385     /// let mut dl = LinkedList::new();
386     ///
387     /// dl.push_front(2);
388     /// dl.push_front(1);
389     /// assert_eq!(dl.len(), 2);
390     /// assert_eq!(dl.front(), Some(&1));
391     ///
392     /// dl.clear();
393     /// assert_eq!(dl.len(), 0);
394     /// assert_eq!(dl.front(), None);
395     ///
396     /// ```
397     #[inline]
398     #[stable(feature = "rust1", since = "1.0.0")]
399     pub fn clear(&mut self) {
400         *self = LinkedList::new()
401     }
402
403     /// Provides a reference to the front element, or `None` if the list is
404     /// empty.
405     ///
406     /// # Examples
407     ///
408     /// ```
409     /// use std::collections::LinkedList;
410     ///
411     /// let mut dl = LinkedList::new();
412     /// assert_eq!(dl.front(), None);
413     ///
414     /// dl.push_front(1);
415     /// assert_eq!(dl.front(), Some(&1));
416     ///
417     /// ```
418     #[inline]
419     #[stable(feature = "rust1", since = "1.0.0")]
420     pub fn front(&self) -> Option<&T> {
421         self.list_head.as_ref().map(|head| &head.value)
422     }
423
424     /// Provides a mutable reference to the front element, or `None` if the list
425     /// is empty.
426     ///
427     /// # Examples
428     ///
429     /// ```
430     /// use std::collections::LinkedList;
431     ///
432     /// let mut dl = LinkedList::new();
433     /// assert_eq!(dl.front(), None);
434     ///
435     /// dl.push_front(1);
436     /// assert_eq!(dl.front(), Some(&1));
437     ///
438     /// match dl.front_mut() {
439     ///     None => {},
440     ///     Some(x) => *x = 5,
441     /// }
442     /// assert_eq!(dl.front(), Some(&5));
443     ///
444     /// ```
445     #[inline]
446     #[stable(feature = "rust1", since = "1.0.0")]
447     pub fn front_mut(&mut self) -> Option<&mut T> {
448         self.list_head.as_mut().map(|head| &mut head.value)
449     }
450
451     /// Provides a reference to the back element, or `None` if the list is
452     /// empty.
453     ///
454     /// # Examples
455     ///
456     /// ```
457     /// use std::collections::LinkedList;
458     ///
459     /// let mut dl = LinkedList::new();
460     /// assert_eq!(dl.back(), None);
461     ///
462     /// dl.push_back(1);
463     /// assert_eq!(dl.back(), Some(&1));
464     ///
465     /// ```
466     #[inline]
467     #[stable(feature = "rust1", since = "1.0.0")]
468     pub fn back(&self) -> Option<&T> {
469         unsafe { self.list_tail.resolve().map(|tail| &tail.value) }
470     }
471
472     /// Provides a mutable reference to the back element, or `None` if the list
473     /// is empty.
474     ///
475     /// # Examples
476     ///
477     /// ```
478     /// use std::collections::LinkedList;
479     ///
480     /// let mut dl = LinkedList::new();
481     /// assert_eq!(dl.back(), None);
482     ///
483     /// dl.push_back(1);
484     /// assert_eq!(dl.back(), Some(&1));
485     ///
486     /// match dl.back_mut() {
487     ///     None => {},
488     ///     Some(x) => *x = 5,
489     /// }
490     /// assert_eq!(dl.back(), Some(&5));
491     ///
492     /// ```
493     #[inline]
494     #[stable(feature = "rust1", since = "1.0.0")]
495     pub fn back_mut(&mut self) -> Option<&mut T> {
496         unsafe { self.list_tail.resolve_mut().map(|tail| &mut tail.value) }
497     }
498
499     /// Adds an element first in the list.
500     ///
501     /// This operation should compute in O(1) time.
502     ///
503     /// # Examples
504     ///
505     /// ```
506     /// use std::collections::LinkedList;
507     ///
508     /// let mut dl = LinkedList::new();
509     ///
510     /// dl.push_front(2);
511     /// assert_eq!(dl.front().unwrap(), &2);
512     ///
513     /// dl.push_front(1);
514     /// assert_eq!(dl.front().unwrap(), &1);
515     ///
516     /// ```
517     #[stable(feature = "rust1", since = "1.0.0")]
518     pub fn push_front(&mut self, elt: T) {
519         self.push_front_node(box Node::new(elt))
520     }
521
522     /// Removes the first element and returns it, or `None` if the list is
523     /// empty.
524     ///
525     /// This operation should compute in O(1) time.
526     ///
527     /// # Examples
528     ///
529     /// ```
530     /// use std::collections::LinkedList;
531     ///
532     /// let mut d = LinkedList::new();
533     /// assert_eq!(d.pop_front(), None);
534     ///
535     /// d.push_front(1);
536     /// d.push_front(3);
537     /// assert_eq!(d.pop_front(), Some(3));
538     /// assert_eq!(d.pop_front(), Some(1));
539     /// assert_eq!(d.pop_front(), None);
540     ///
541     /// ```
542     ///
543     #[stable(feature = "rust1", since = "1.0.0")]
544     pub fn pop_front(&mut self) -> Option<T> {
545         self.pop_front_node().map(|box Node { value, .. }| value)
546     }
547
548     /// Appends an element to the back of a list
549     ///
550     /// # Examples
551     ///
552     /// ```
553     /// use std::collections::LinkedList;
554     ///
555     /// let mut d = LinkedList::new();
556     /// d.push_back(1);
557     /// d.push_back(3);
558     /// assert_eq!(3, *d.back().unwrap());
559     /// ```
560     #[stable(feature = "rust1", since = "1.0.0")]
561     pub fn push_back(&mut self, elt: T) {
562         self.push_back_node(box Node::new(elt))
563     }
564
565     /// Removes the last element from a list and returns it, or `None` if
566     /// it is empty.
567     ///
568     /// # Examples
569     ///
570     /// ```
571     /// use std::collections::LinkedList;
572     ///
573     /// let mut d = LinkedList::new();
574     /// assert_eq!(d.pop_back(), None);
575     /// d.push_back(1);
576     /// d.push_back(3);
577     /// assert_eq!(d.pop_back(), Some(3));
578     /// ```
579     #[stable(feature = "rust1", since = "1.0.0")]
580     pub fn pop_back(&mut self) -> Option<T> {
581         self.pop_back_node().map(|box Node { value, .. }| value)
582     }
583
584     /// Splits the list into two at the given index. Returns everything after the given index,
585     /// including the index.
586     ///
587     /// # Panics
588     ///
589     /// Panics if `at > len`.
590     ///
591     /// This operation should compute in O(n) time.
592     ///
593     /// # Examples
594     ///
595     /// ```
596     /// use std::collections::LinkedList;
597     ///
598     /// let mut d = LinkedList::new();
599     ///
600     /// d.push_front(1);
601     /// d.push_front(2);
602     /// d.push_front(3);
603     ///
604     /// let mut splitted = d.split_off(2);
605     ///
606     /// assert_eq!(splitted.pop_front(), Some(1));
607     /// assert_eq!(splitted.pop_front(), None);
608     /// ```
609     #[stable(feature = "rust1", since = "1.0.0")]
610     pub fn split_off(&mut self, at: usize) -> LinkedList<T> {
611         let len = self.len();
612         assert!(at <= len, "Cannot split off at a nonexistent index");
613         if at == 0 {
614             return mem::replace(self, LinkedList::new());
615         } else if at == len {
616             return LinkedList::new();
617         }
618
619         // Below, we iterate towards the `i-1`th node, either from the start or the end,
620         // depending on which would be faster.
621         let mut split_node = if at - 1 <= len - 1 - (at - 1) {
622             let mut iter = self.iter_mut();
623             // instead of skipping using .skip() (which creates a new struct),
624             // we skip manually so we can access the head field without
625             // depending on implementation details of Skip
626             for _ in 0..at - 1 {
627                 iter.next();
628             }
629             iter.head
630         } else {
631             // better off starting from the end
632             let mut iter = self.iter_mut();
633             for _ in 0..len - 1 - (at - 1) {
634                 iter.next_back();
635             }
636             iter.tail
637         };
638
639         // The split node is the new tail node of the first part and owns
640         // the head of the second part.
641         let mut second_part_head;
642
643         unsafe {
644             second_part_head = split_node.resolve_mut().unwrap().next.take();
645             match second_part_head {
646                 None => {}
647                 Some(ref mut head) => head.prev = Rawlink::none(),
648             }
649         }
650
651         let second_part = LinkedList {
652             list_head: second_part_head,
653             list_tail: self.list_tail,
654             length: len - at,
655         };
656
657         // Fix the tail ptr of the first part
658         self.list_tail = split_node;
659         self.length = at;
660
661         second_part
662     }
663 }
664
665 #[stable(feature = "rust1", since = "1.0.0")]
666 impl<T> Drop for LinkedList<T> {
667     #[unsafe_destructor_blind_to_params]
668     fn drop(&mut self) {
669         // Dissolve the linked_list in a loop.
670         // Just dropping the list_head can lead to stack exhaustion
671         // when length is >> 1_000_000
672         while let Some(mut head_) = self.list_head.take() {
673             self.list_head = head_.next.take();
674         }
675         self.length = 0;
676         self.list_tail = Rawlink::none();
677     }
678 }
679
680 #[stable(feature = "rust1", since = "1.0.0")]
681 impl<'a, A> Iterator for Iter<'a, A> {
682     type Item = &'a A;
683
684     #[inline]
685     fn next(&mut self) -> Option<&'a A> {
686         if self.nelem == 0 {
687             return None;
688         }
689         self.head.as_ref().map(|head| {
690             self.nelem -= 1;
691             self.head = &head.next;
692             &head.value
693         })
694     }
695
696     #[inline]
697     fn size_hint(&self) -> (usize, Option<usize>) {
698         (self.nelem, Some(self.nelem))
699     }
700 }
701
702 #[stable(feature = "rust1", since = "1.0.0")]
703 impl<'a, A> DoubleEndedIterator for Iter<'a, A> {
704     #[inline]
705     fn next_back(&mut self) -> Option<&'a A> {
706         if self.nelem == 0 {
707             return None;
708         }
709         unsafe {
710             self.tail.resolve().map(|prev| {
711                 self.nelem -= 1;
712                 self.tail = prev.prev;
713                 &prev.value
714             })
715         }
716     }
717 }
718
719 #[stable(feature = "rust1", since = "1.0.0")]
720 impl<'a, A> ExactSizeIterator for Iter<'a, A> {}
721
722 #[stable(feature = "rust1", since = "1.0.0")]
723 impl<'a, A> Iterator for IterMut<'a, A> {
724     type Item = &'a mut A;
725     #[inline]
726     fn next(&mut self) -> Option<&'a mut A> {
727         if self.nelem == 0 {
728             return None;
729         }
730         unsafe {
731             self.head.resolve_mut().map(|next| {
732                 self.nelem -= 1;
733                 self.head = Rawlink::from(&mut next.next);
734                 &mut next.value
735             })
736         }
737     }
738
739     #[inline]
740     fn size_hint(&self) -> (usize, Option<usize>) {
741         (self.nelem, Some(self.nelem))
742     }
743 }
744
745 #[stable(feature = "rust1", since = "1.0.0")]
746 impl<'a, A> DoubleEndedIterator for IterMut<'a, A> {
747     #[inline]
748     fn next_back(&mut self) -> Option<&'a mut A> {
749         if self.nelem == 0 {
750             return None;
751         }
752         unsafe {
753             self.tail.resolve_mut().map(|prev| {
754                 self.nelem -= 1;
755                 self.tail = prev.prev;
756                 &mut prev.value
757             })
758         }
759     }
760 }
761
762 #[stable(feature = "rust1", since = "1.0.0")]
763 impl<'a, A> ExactSizeIterator for IterMut<'a, A> {}
764
765 // private methods for IterMut
766 impl<'a, A> IterMut<'a, A> {
767     fn insert_next_node(&mut self, mut ins_node: Box<Node<A>>) {
768         // Insert before `self.head` so that it is between the
769         // previously yielded element and self.head.
770         //
771         // The inserted node will not appear in further iteration.
772         match unsafe { self.head.resolve_mut() } {
773             None => {
774                 self.list.push_back_node(ins_node);
775             }
776             Some(node) => {
777                 let prev_node = match unsafe { node.prev.resolve_mut() } {
778                     None => return self.list.push_front_node(ins_node),
779                     Some(prev) => prev,
780                 };
781                 let node_own = prev_node.next.take().unwrap();
782                 ins_node.set_next(node_own);
783                 prev_node.set_next(ins_node);
784                 self.list.length += 1;
785             }
786         }
787     }
788 }
789
790 impl<'a, A> IterMut<'a, A> {
791     /// Inserts `elt` just after the element most recently returned by `.next()`.
792     /// The inserted element does not appear in the iteration.
793     ///
794     /// # Examples
795     ///
796     /// ```
797     /// #![feature(linked_list_extras)]
798     ///
799     /// use std::collections::LinkedList;
800     ///
801     /// let mut list: LinkedList<_> = vec![1, 3, 4].into_iter().collect();
802     ///
803     /// {
804     ///     let mut it = list.iter_mut();
805     ///     assert_eq!(it.next().unwrap(), &1);
806     ///     // insert `2` after `1`
807     ///     it.insert_next(2);
808     /// }
809     /// {
810     ///     let vec: Vec<_> = list.into_iter().collect();
811     ///     assert_eq!(vec, [1, 2, 3, 4]);
812     /// }
813     /// ```
814     #[inline]
815     #[unstable(feature = "linked_list_extras",
816                reason = "this is probably better handled by a cursor type -- we'll see",
817                issue = "27794")]
818     pub fn insert_next(&mut self, elt: A) {
819         self.insert_next_node(box Node::new(elt))
820     }
821
822     /// Provides a reference to the next element, without changing the iterator.
823     ///
824     /// # Examples
825     ///
826     /// ```
827     /// #![feature(linked_list_extras)]
828     ///
829     /// use std::collections::LinkedList;
830     ///
831     /// let mut list: LinkedList<_> = vec![1, 2, 3].into_iter().collect();
832     ///
833     /// let mut it = list.iter_mut();
834     /// assert_eq!(it.next().unwrap(), &1);
835     /// assert_eq!(it.peek_next().unwrap(), &2);
836     /// // We just peeked at 2, so it was not consumed from the iterator.
837     /// assert_eq!(it.next().unwrap(), &2);
838     /// ```
839     #[inline]
840     #[unstable(feature = "linked_list_extras",
841                reason = "this is probably better handled by a cursor type -- we'll see",
842                issue = "27794")]
843     pub fn peek_next(&mut self) -> Option<&mut A> {
844         if self.nelem == 0 {
845             return None;
846         }
847         unsafe { self.head.resolve_mut().map(|head| &mut head.value) }
848     }
849 }
850
851 #[stable(feature = "rust1", since = "1.0.0")]
852 impl<A> Iterator for IntoIter<A> {
853     type Item = A;
854
855     #[inline]
856     fn next(&mut self) -> Option<A> {
857         self.list.pop_front()
858     }
859
860     #[inline]
861     fn size_hint(&self) -> (usize, Option<usize>) {
862         (self.list.length, Some(self.list.length))
863     }
864 }
865
866 #[stable(feature = "rust1", since = "1.0.0")]
867 impl<A> DoubleEndedIterator for IntoIter<A> {
868     #[inline]
869     fn next_back(&mut self) -> Option<A> {
870         self.list.pop_back()
871     }
872 }
873
874 #[stable(feature = "rust1", since = "1.0.0")]
875 impl<A> ExactSizeIterator for IntoIter<A> {}
876
877 #[stable(feature = "rust1", since = "1.0.0")]
878 impl<A> FromIterator<A> for LinkedList<A> {
879     fn from_iter<T: IntoIterator<Item = A>>(iter: T) -> LinkedList<A> {
880         let mut ret = LinkedList::new();
881         ret.extend(iter);
882         ret
883     }
884 }
885
886 #[stable(feature = "rust1", since = "1.0.0")]
887 impl<T> IntoIterator for LinkedList<T> {
888     type Item = T;
889     type IntoIter = IntoIter<T>;
890
891     /// Consumes the list into an iterator yielding elements by value.
892     #[inline]
893     fn into_iter(self) -> IntoIter<T> {
894         IntoIter { list: self }
895     }
896 }
897
898 #[stable(feature = "rust1", since = "1.0.0")]
899 impl<'a, T> IntoIterator for &'a LinkedList<T> {
900     type Item = &'a T;
901     type IntoIter = Iter<'a, T>;
902
903     fn into_iter(self) -> Iter<'a, T> {
904         self.iter()
905     }
906 }
907
908 #[stable(feature = "rust1", since = "1.0.0")]
909 impl<'a, T> IntoIterator for &'a mut LinkedList<T> {
910     type Item = &'a mut T;
911     type IntoIter = IterMut<'a, T>;
912
913     fn into_iter(mut self) -> IterMut<'a, T> {
914         self.iter_mut()
915     }
916 }
917
918 #[stable(feature = "rust1", since = "1.0.0")]
919 impl<A> Extend<A> for LinkedList<A> {
920     fn extend<T: IntoIterator<Item = A>>(&mut self, iter: T) {
921         for elt in iter {
922             self.push_back(elt);
923         }
924     }
925 }
926
927 #[stable(feature = "extend_ref", since = "1.2.0")]
928 impl<'a, T: 'a + Copy> Extend<&'a T> for LinkedList<T> {
929     fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
930         self.extend(iter.into_iter().cloned());
931     }
932 }
933
934 #[stable(feature = "rust1", since = "1.0.0")]
935 impl<A: PartialEq> PartialEq for LinkedList<A> {
936     fn eq(&self, other: &LinkedList<A>) -> bool {
937         self.len() == other.len() && self.iter().eq(other.iter())
938     }
939
940     fn ne(&self, other: &LinkedList<A>) -> bool {
941         self.len() != other.len() || self.iter().ne(other.iter())
942     }
943 }
944
945 #[stable(feature = "rust1", since = "1.0.0")]
946 impl<A: Eq> Eq for LinkedList<A> {}
947
948 #[stable(feature = "rust1", since = "1.0.0")]
949 impl<A: PartialOrd> PartialOrd for LinkedList<A> {
950     fn partial_cmp(&self, other: &LinkedList<A>) -> Option<Ordering> {
951         self.iter().partial_cmp(other.iter())
952     }
953 }
954
955 #[stable(feature = "rust1", since = "1.0.0")]
956 impl<A: Ord> Ord for LinkedList<A> {
957     #[inline]
958     fn cmp(&self, other: &LinkedList<A>) -> Ordering {
959         self.iter().cmp(other.iter())
960     }
961 }
962
963 #[stable(feature = "rust1", since = "1.0.0")]
964 impl<A: Clone> Clone for LinkedList<A> {
965     fn clone(&self) -> LinkedList<A> {
966         self.iter().cloned().collect()
967     }
968 }
969
970 #[stable(feature = "rust1", since = "1.0.0")]
971 impl<A: fmt::Debug> fmt::Debug for LinkedList<A> {
972     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
973         f.debug_list().entries(self.iter()).finish()
974     }
975 }
976
977 #[stable(feature = "rust1", since = "1.0.0")]
978 impl<A: Hash> Hash for LinkedList<A> {
979     fn hash<H: Hasher>(&self, state: &mut H) {
980         self.len().hash(state);
981         for elt in self {
982             elt.hash(state);
983         }
984     }
985 }
986
987 // Ensure that `LinkedList` and its read-only iterators are covariant in their type parameters.
988 #[allow(dead_code)]
989 fn assert_covariance() {
990     fn a<'a>(x: LinkedList<&'static str>) -> LinkedList<&'a str> { x }
991     fn b<'i, 'a>(x: Iter<'i, &'static str>) -> Iter<'i, &'a str> { x }
992     fn c<'a>(x: IntoIter<&'static str>) -> IntoIter<&'a str> { x }
993 }
994
995 #[cfg(test)]
996 mod tests {
997     use std::clone::Clone;
998     use std::iter::{Iterator, IntoIterator, Extend};
999     use std::option::Option::{self, Some, None};
1000     use std::__rand::{thread_rng, Rng};
1001     use std::thread;
1002     use std::vec::Vec;
1003
1004     use super::{LinkedList, Node};
1005
1006     #[cfg(test)]
1007     fn list_from<T: Clone>(v: &[T]) -> LinkedList<T> {
1008         v.iter().cloned().collect()
1009     }
1010
1011     pub fn check_links<T>(list: &LinkedList<T>) {
1012         let mut len = 0;
1013         let mut last_ptr: Option<&Node<T>> = None;
1014         let mut node_ptr: &Node<T>;
1015         match list.list_head {
1016             None => {
1017                 assert_eq!(0, list.length);
1018                 return;
1019             }
1020             Some(ref node) => node_ptr = &**node,
1021         }
1022         loop {
1023             match unsafe { (last_ptr, node_ptr.prev.resolve()) } {
1024                 (None, None) => {}
1025                 (None, _) => panic!("prev link for list_head"),
1026                 (Some(p), Some(pptr)) => {
1027                     assert_eq!(p as *const Node<T>, pptr as *const Node<T>);
1028                 }
1029                 _ => panic!("prev link is none, not good"),
1030             }
1031             match node_ptr.next {
1032                 Some(ref next) => {
1033                     last_ptr = Some(node_ptr);
1034                     node_ptr = &**next;
1035                     len += 1;
1036                 }
1037                 None => {
1038                     len += 1;
1039                     break;
1040                 }
1041             }
1042         }
1043         assert_eq!(len, list.length);
1044     }
1045
1046     #[test]
1047     fn test_append() {
1048         // Empty to empty
1049         {
1050             let mut m = LinkedList::<i32>::new();
1051             let mut n = LinkedList::new();
1052             m.append(&mut n);
1053             check_links(&m);
1054             assert_eq!(m.len(), 0);
1055             assert_eq!(n.len(), 0);
1056         }
1057         // Non-empty to empty
1058         {
1059             let mut m = LinkedList::new();
1060             let mut n = LinkedList::new();
1061             n.push_back(2);
1062             m.append(&mut n);
1063             check_links(&m);
1064             assert_eq!(m.len(), 1);
1065             assert_eq!(m.pop_back(), Some(2));
1066             assert_eq!(n.len(), 0);
1067             check_links(&m);
1068         }
1069         // Empty to non-empty
1070         {
1071             let mut m = LinkedList::new();
1072             let mut n = LinkedList::new();
1073             m.push_back(2);
1074             m.append(&mut n);
1075             check_links(&m);
1076             assert_eq!(m.len(), 1);
1077             assert_eq!(m.pop_back(), Some(2));
1078             check_links(&m);
1079         }
1080
1081         // Non-empty to non-empty
1082         let v = vec![1, 2, 3, 4, 5];
1083         let u = vec![9, 8, 1, 2, 3, 4, 5];
1084         let mut m = list_from(&v);
1085         let mut n = list_from(&u);
1086         m.append(&mut n);
1087         check_links(&m);
1088         let mut sum = v;
1089         sum.push_all(&u);
1090         assert_eq!(sum.len(), m.len());
1091         for elt in sum {
1092             assert_eq!(m.pop_front(), Some(elt))
1093         }
1094         assert_eq!(n.len(), 0);
1095         // let's make sure it's working properly, since we
1096         // did some direct changes to private members
1097         n.push_back(3);
1098         assert_eq!(n.len(), 1);
1099         assert_eq!(n.pop_front(), Some(3));
1100         check_links(&n);
1101     }
1102
1103     #[test]
1104     fn test_insert_prev() {
1105         let mut m = list_from(&[0, 2, 4, 6, 8]);
1106         let len = m.len();
1107         {
1108             let mut it = m.iter_mut();
1109             it.insert_next(-2);
1110             loop {
1111                 match it.next() {
1112                     None => break,
1113                     Some(elt) => {
1114                         it.insert_next(*elt + 1);
1115                         match it.peek_next() {
1116                             Some(x) => assert_eq!(*x, *elt + 2),
1117                             None => assert_eq!(8, *elt),
1118                         }
1119                     }
1120                 }
1121             }
1122             it.insert_next(0);
1123             it.insert_next(1);
1124         }
1125         check_links(&m);
1126         assert_eq!(m.len(), 3 + len * 2);
1127         assert_eq!(m.into_iter().collect::<Vec<_>>(),
1128                    [-2, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1]);
1129     }
1130
1131     #[test]
1132     fn test_send() {
1133         let n = list_from(&[1, 2, 3]);
1134         thread::spawn(move || {
1135             check_links(&n);
1136             let a: &[_] = &[&1, &2, &3];
1137             assert_eq!(a, &n.iter().collect::<Vec<_>>()[..]);
1138         })
1139             .join()
1140             .ok()
1141             .unwrap();
1142     }
1143
1144     #[test]
1145     fn test_fuzz() {
1146         for _ in 0..25 {
1147             fuzz_test(3);
1148             fuzz_test(16);
1149             fuzz_test(189);
1150         }
1151     }
1152
1153     #[test]
1154     fn test_26021() {
1155         use std::iter::ExactSizeIterator;
1156         // There was a bug in split_off that failed to null out the RHS's head's prev ptr.
1157         // This caused the RHS's dtor to walk up into the LHS at drop and delete all of
1158         // its nodes.
1159         //
1160         // https://github.com/rust-lang/rust/issues/26021
1161         let mut v1 = LinkedList::new();
1162         v1.push_front(1u8);
1163         v1.push_front(1u8);
1164         v1.push_front(1u8);
1165         v1.push_front(1u8);
1166         let _ = v1.split_off(3); // Dropping this now should not cause laundry consumption
1167         assert_eq!(v1.len(), 3);
1168
1169         assert_eq!(v1.iter().len(), 3);
1170         assert_eq!(v1.iter().collect::<Vec<_>>().len(), 3);
1171     }
1172
1173     #[test]
1174     fn test_split_off() {
1175         let mut v1 = LinkedList::new();
1176         v1.push_front(1u8);
1177         v1.push_front(1u8);
1178         v1.push_front(1u8);
1179         v1.push_front(1u8);
1180
1181         // test all splits
1182         for ix in 0..1 + v1.len() {
1183             let mut a = v1.clone();
1184             let b = a.split_off(ix);
1185             check_links(&a);
1186             check_links(&b);
1187             a.extend(b);
1188             assert_eq!(v1, a);
1189         }
1190     }
1191
1192
1193     #[cfg(test)]
1194     fn fuzz_test(sz: i32) {
1195         let mut m: LinkedList<_> = LinkedList::new();
1196         let mut v = vec![];
1197         for i in 0..sz {
1198             check_links(&m);
1199             let r: u8 = thread_rng().next_u32() as u8;
1200             match r % 6 {
1201                 0 => {
1202                     m.pop_back();
1203                     v.pop();
1204                 }
1205                 1 => {
1206                     if !v.is_empty() {
1207                         m.pop_front();
1208                         v.remove(0);
1209                     }
1210                 }
1211                 2 | 4 => {
1212                     m.push_front(-i);
1213                     v.insert(0, -i);
1214                 }
1215                 3 | 5 | _ => {
1216                     m.push_back(i);
1217                     v.push(i);
1218                 }
1219             }
1220         }
1221
1222         check_links(&m);
1223
1224         let mut i = 0;
1225         for (a, &b) in m.into_iter().zip(&v) {
1226             i += 1;
1227             assert_eq!(a, b);
1228         }
1229         assert_eq!(i, v.len());
1230     }
1231 }