]> git.lizzy.rs Git - rust.git/blob - library/alloc/src/collections/linked_list.rs
Apply suggestions from code review
[rust.git] / library / alloc / src / collections / linked_list.rs
1 //! A doubly-linked list with owned nodes.
2 //!
3 //! The `LinkedList` allows pushing and popping elements at either end
4 //! in constant time.
5 //!
6 //! NOTE: It is almost always better to use [`Vec`] or [`VecDeque`] because
7 //! array-based containers are generally faster,
8 //! more memory efficient, and make better use of CPU cache.
9 //!
10 //! [`Vec`]: crate::vec::Vec
11 //! [`VecDeque`]: super::vec_deque::VecDeque
12
13 #![stable(feature = "rust1", since = "1.0.0")]
14
15 use core::cmp::Ordering;
16 use core::fmt;
17 use core::hash::{Hash, Hasher};
18 use core::iter::{FromIterator, FusedIterator};
19 use core::marker::PhantomData;
20 use core::mem;
21 use core::ptr::NonNull;
22
23 use super::SpecExtend;
24 use crate::boxed::Box;
25
26 #[cfg(test)]
27 mod tests;
28
29 /// A doubly-linked list with owned nodes.
30 ///
31 /// The `LinkedList` allows pushing and popping elements at either end
32 /// in constant time.
33 ///
34 /// A `LinkedList` with a known list of items can be initialized from an array:
35 /// ```
36 /// use std::collections::LinkedList;
37 ///
38 /// let list = LinkedList::from([1, 2, 3]);
39 /// ```
40 ///
41 /// NOTE: It is almost always better to use `Vec` or `VecDeque` because
42 /// array-based containers are generally faster,
43 /// more memory efficient, and make better use of CPU cache.
44 #[stable(feature = "rust1", since = "1.0.0")]
45 #[cfg_attr(not(test), rustc_diagnostic_item = "LinkedList")]
46 pub struct LinkedList<T> {
47     head: Option<NonNull<Node<T>>>,
48     tail: Option<NonNull<Node<T>>>,
49     len: usize,
50     marker: PhantomData<Box<Node<T>>>,
51 }
52
53 struct Node<T> {
54     next: Option<NonNull<Node<T>>>,
55     prev: Option<NonNull<Node<T>>>,
56     element: T,
57 }
58
59 /// An iterator over the elements of a `LinkedList`.
60 ///
61 /// This `struct` is created by [`LinkedList::iter()`]. See its
62 /// documentation for more.
63 #[stable(feature = "rust1", since = "1.0.0")]
64 pub struct Iter<'a, T: 'a> {
65     head: Option<NonNull<Node<T>>>,
66     tail: Option<NonNull<Node<T>>>,
67     len: usize,
68     marker: PhantomData<&'a Node<T>>,
69 }
70
71 #[stable(feature = "collection_debug", since = "1.17.0")]
72 impl<T: fmt::Debug> fmt::Debug for Iter<'_, T> {
73     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
74         f.debug_tuple("Iter")
75             .field(&*mem::ManuallyDrop::new(LinkedList {
76                 head: self.head,
77                 tail: self.tail,
78                 len: self.len,
79                 marker: PhantomData,
80             }))
81             .field(&self.len)
82             .finish()
83     }
84 }
85
86 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
87 #[stable(feature = "rust1", since = "1.0.0")]
88 impl<T> Clone for Iter<'_, T> {
89     fn clone(&self) -> Self {
90         Iter { ..*self }
91     }
92 }
93
94 /// A mutable iterator over the elements of a `LinkedList`.
95 ///
96 /// This `struct` is created by [`LinkedList::iter_mut()`]. See its
97 /// documentation for more.
98 #[stable(feature = "rust1", since = "1.0.0")]
99 pub struct IterMut<'a, T: 'a> {
100     head: Option<NonNull<Node<T>>>,
101     tail: Option<NonNull<Node<T>>>,
102     len: usize,
103     marker: PhantomData<&'a mut Node<T>>,
104 }
105
106 #[stable(feature = "collection_debug", since = "1.17.0")]
107 impl<T: fmt::Debug> fmt::Debug for IterMut<'_, T> {
108     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
109         f.debug_tuple("IterMut")
110             .field(&*mem::ManuallyDrop::new(LinkedList {
111                 head: self.head,
112                 tail: self.tail,
113                 len: self.len,
114                 marker: PhantomData,
115             }))
116             .field(&self.len)
117             .finish()
118     }
119 }
120
121 /// An owning iterator over the elements of a `LinkedList`.
122 ///
123 /// This `struct` is created by the [`into_iter`] method on [`LinkedList`]
124 /// (provided by the `IntoIterator` trait). See its documentation for more.
125 ///
126 /// [`into_iter`]: LinkedList::into_iter
127 #[derive(Clone)]
128 #[stable(feature = "rust1", since = "1.0.0")]
129 pub struct IntoIter<T> {
130     list: LinkedList<T>,
131 }
132
133 #[stable(feature = "collection_debug", since = "1.17.0")]
134 impl<T: fmt::Debug> fmt::Debug for IntoIter<T> {
135     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
136         f.debug_tuple("IntoIter").field(&self.list).finish()
137     }
138 }
139
140 impl<T> Node<T> {
141     fn new(element: T) -> Self {
142         Node { next: None, prev: None, element }
143     }
144
145     fn into_element(self: Box<Self>) -> T {
146         self.element
147     }
148 }
149
150 // private methods
151 impl<T> LinkedList<T> {
152     /// Adds the given node to the front of the list.
153     #[inline]
154     fn push_front_node(&mut self, mut node: Box<Node<T>>) {
155         // This method takes care not to create mutable references to whole nodes,
156         // to maintain validity of aliasing pointers into `element`.
157         unsafe {
158             node.next = self.head;
159             node.prev = None;
160             let node = Some(Box::leak(node).into());
161
162             match self.head {
163                 None => self.tail = node,
164                 // Not creating new mutable (unique!) references overlapping `element`.
165                 Some(head) => (*head.as_ptr()).prev = node,
166             }
167
168             self.head = node;
169             self.len += 1;
170         }
171     }
172
173     /// Removes and returns the node at the front of the list.
174     #[inline]
175     fn pop_front_node(&mut self) -> Option<Box<Node<T>>> {
176         // This method takes care not to create mutable references to whole nodes,
177         // to maintain validity of aliasing pointers into `element`.
178         self.head.map(|node| unsafe {
179             let node = Box::from_raw(node.as_ptr());
180             self.head = node.next;
181
182             match self.head {
183                 None => self.tail = None,
184                 // Not creating new mutable (unique!) references overlapping `element`.
185                 Some(head) => (*head.as_ptr()).prev = None,
186             }
187
188             self.len -= 1;
189             node
190         })
191     }
192
193     /// Adds the given node to the back of the list.
194     #[inline]
195     fn push_back_node(&mut self, mut node: Box<Node<T>>) {
196         // This method takes care not to create mutable references to whole nodes,
197         // to maintain validity of aliasing pointers into `element`.
198         unsafe {
199             node.next = None;
200             node.prev = self.tail;
201             let node = Some(Box::leak(node).into());
202
203             match self.tail {
204                 None => self.head = node,
205                 // Not creating new mutable (unique!) references overlapping `element`.
206                 Some(tail) => (*tail.as_ptr()).next = node,
207             }
208
209             self.tail = node;
210             self.len += 1;
211         }
212     }
213
214     /// Removes and returns the node at the back of the list.
215     #[inline]
216     fn pop_back_node(&mut self) -> Option<Box<Node<T>>> {
217         // This method takes care not to create mutable references to whole nodes,
218         // to maintain validity of aliasing pointers into `element`.
219         self.tail.map(|node| unsafe {
220             let node = Box::from_raw(node.as_ptr());
221             self.tail = node.prev;
222
223             match self.tail {
224                 None => self.head = None,
225                 // Not creating new mutable (unique!) references overlapping `element`.
226                 Some(tail) => (*tail.as_ptr()).next = None,
227             }
228
229             self.len -= 1;
230             node
231         })
232     }
233
234     /// Unlinks the specified node from the current list.
235     ///
236     /// Warning: this will not check that the provided node belongs to the current list.
237     ///
238     /// This method takes care not to create mutable references to `element`, to
239     /// maintain validity of aliasing pointers.
240     #[inline]
241     unsafe fn unlink_node(&mut self, mut node: NonNull<Node<T>>) {
242         let node = unsafe { node.as_mut() }; // this one is ours now, we can create an &mut.
243
244         // Not creating new mutable (unique!) references overlapping `element`.
245         match node.prev {
246             Some(prev) => unsafe { (*prev.as_ptr()).next = node.next },
247             // this node is the head node
248             None => self.head = node.next,
249         };
250
251         match node.next {
252             Some(next) => unsafe { (*next.as_ptr()).prev = node.prev },
253             // this node is the tail node
254             None => self.tail = node.prev,
255         };
256
257         self.len -= 1;
258     }
259
260     /// Splices a series of nodes between two existing nodes.
261     ///
262     /// Warning: this will not check that the provided node belongs to the two existing lists.
263     #[inline]
264     unsafe fn splice_nodes(
265         &mut self,
266         existing_prev: Option<NonNull<Node<T>>>,
267         existing_next: Option<NonNull<Node<T>>>,
268         mut splice_start: NonNull<Node<T>>,
269         mut splice_end: NonNull<Node<T>>,
270         splice_length: usize,
271     ) {
272         // This method takes care not to create multiple mutable references to whole nodes at the same time,
273         // to maintain validity of aliasing pointers into `element`.
274         if let Some(mut existing_prev) = existing_prev {
275             unsafe {
276                 existing_prev.as_mut().next = Some(splice_start);
277             }
278         } else {
279             self.head = Some(splice_start);
280         }
281         if let Some(mut existing_next) = existing_next {
282             unsafe {
283                 existing_next.as_mut().prev = Some(splice_end);
284             }
285         } else {
286             self.tail = Some(splice_end);
287         }
288         unsafe {
289             splice_start.as_mut().prev = existing_prev;
290             splice_end.as_mut().next = existing_next;
291         }
292
293         self.len += splice_length;
294     }
295
296     /// Detaches all nodes from a linked list as a series of nodes.
297     #[inline]
298     fn detach_all_nodes(mut self) -> Option<(NonNull<Node<T>>, NonNull<Node<T>>, usize)> {
299         let head = self.head.take();
300         let tail = self.tail.take();
301         let len = mem::replace(&mut self.len, 0);
302         if let Some(head) = head {
303             // SAFETY: In a LinkedList, either both the head and tail are None because
304             // the list is empty, or both head and tail are Some because the list is populated.
305             // Since we have verified the head is Some, we are sure the tail is Some too.
306             let tail = unsafe { tail.unwrap_unchecked() };
307             Some((head, tail, len))
308         } else {
309             None
310         }
311     }
312
313     #[inline]
314     unsafe fn split_off_before_node(
315         &mut self,
316         split_node: Option<NonNull<Node<T>>>,
317         at: usize,
318     ) -> Self {
319         // The split node is the new head node of the second part
320         if let Some(mut split_node) = split_node {
321             let first_part_head;
322             let first_part_tail;
323             unsafe {
324                 first_part_tail = split_node.as_mut().prev.take();
325             }
326             if let Some(mut tail) = first_part_tail {
327                 unsafe {
328                     tail.as_mut().next = None;
329                 }
330                 first_part_head = self.head;
331             } else {
332                 first_part_head = None;
333             }
334
335             let first_part = LinkedList {
336                 head: first_part_head,
337                 tail: first_part_tail,
338                 len: at,
339                 marker: PhantomData,
340             };
341
342             // Fix the head ptr of the second part
343             self.head = Some(split_node);
344             self.len = self.len - at;
345
346             first_part
347         } else {
348             mem::replace(self, LinkedList::new())
349         }
350     }
351
352     #[inline]
353     unsafe fn split_off_after_node(
354         &mut self,
355         split_node: Option<NonNull<Node<T>>>,
356         at: usize,
357     ) -> Self {
358         // The split node is the new tail node of the first part and owns
359         // the head of the second part.
360         if let Some(mut split_node) = split_node {
361             let second_part_head;
362             let second_part_tail;
363             unsafe {
364                 second_part_head = split_node.as_mut().next.take();
365             }
366             if let Some(mut head) = second_part_head {
367                 unsafe {
368                     head.as_mut().prev = None;
369                 }
370                 second_part_tail = self.tail;
371             } else {
372                 second_part_tail = None;
373             }
374
375             let second_part = LinkedList {
376                 head: second_part_head,
377                 tail: second_part_tail,
378                 len: self.len - at,
379                 marker: PhantomData,
380             };
381
382             // Fix the tail ptr of the first part
383             self.tail = Some(split_node);
384             self.len = at;
385
386             second_part
387         } else {
388             mem::replace(self, LinkedList::new())
389         }
390     }
391 }
392
393 #[stable(feature = "rust1", since = "1.0.0")]
394 impl<T> Default for LinkedList<T> {
395     /// Creates an empty `LinkedList<T>`.
396     #[inline]
397     fn default() -> Self {
398         Self::new()
399     }
400 }
401
402 impl<T> LinkedList<T> {
403     /// Creates an empty `LinkedList`.
404     ///
405     /// # Examples
406     ///
407     /// ```
408     /// use std::collections::LinkedList;
409     ///
410     /// let list: LinkedList<u32> = LinkedList::new();
411     /// ```
412     #[inline]
413     #[rustc_const_stable(feature = "const_linked_list_new", since = "1.32.0")]
414     #[stable(feature = "rust1", since = "1.0.0")]
415     pub const fn new() -> Self {
416         LinkedList { head: None, tail: None, len: 0, marker: PhantomData }
417     }
418
419     /// Moves all elements from `other` to the end of the list.
420     ///
421     /// This reuses all the nodes from `other` and moves them into `self`. After
422     /// this operation, `other` becomes empty.
423     ///
424     /// This operation should compute in *O*(1) time and *O*(1) memory.
425     ///
426     /// # Examples
427     ///
428     /// ```
429     /// use std::collections::LinkedList;
430     ///
431     /// let mut list1 = LinkedList::new();
432     /// list1.push_back('a');
433     ///
434     /// let mut list2 = LinkedList::new();
435     /// list2.push_back('b');
436     /// list2.push_back('c');
437     ///
438     /// list1.append(&mut list2);
439     ///
440     /// let mut iter = list1.iter();
441     /// assert_eq!(iter.next(), Some(&'a'));
442     /// assert_eq!(iter.next(), Some(&'b'));
443     /// assert_eq!(iter.next(), Some(&'c'));
444     /// assert!(iter.next().is_none());
445     ///
446     /// assert!(list2.is_empty());
447     /// ```
448     #[stable(feature = "rust1", since = "1.0.0")]
449     pub fn append(&mut self, other: &mut Self) {
450         match self.tail {
451             None => mem::swap(self, other),
452             Some(mut tail) => {
453                 // `as_mut` is okay here because we have exclusive access to the entirety
454                 // of both lists.
455                 if let Some(mut other_head) = other.head.take() {
456                     unsafe {
457                         tail.as_mut().next = Some(other_head);
458                         other_head.as_mut().prev = Some(tail);
459                     }
460
461                     self.tail = other.tail.take();
462                     self.len += mem::replace(&mut other.len, 0);
463                 }
464             }
465         }
466     }
467
468     /// Provides a forward iterator.
469     ///
470     /// # Examples
471     ///
472     /// ```
473     /// use std::collections::LinkedList;
474     ///
475     /// let mut list: LinkedList<u32> = LinkedList::new();
476     ///
477     /// list.push_back(0);
478     /// list.push_back(1);
479     /// list.push_back(2);
480     ///
481     /// let mut iter = list.iter();
482     /// assert_eq!(iter.next(), Some(&0));
483     /// assert_eq!(iter.next(), Some(&1));
484     /// assert_eq!(iter.next(), Some(&2));
485     /// assert_eq!(iter.next(), None);
486     /// ```
487     #[inline]
488     #[stable(feature = "rust1", since = "1.0.0")]
489     pub fn iter(&self) -> Iter<'_, T> {
490         Iter { head: self.head, tail: self.tail, len: self.len, marker: PhantomData }
491     }
492
493     /// Provides a forward iterator with mutable references.
494     ///
495     /// # Examples
496     ///
497     /// ```
498     /// use std::collections::LinkedList;
499     ///
500     /// let mut list: LinkedList<u32> = LinkedList::new();
501     ///
502     /// list.push_back(0);
503     /// list.push_back(1);
504     /// list.push_back(2);
505     ///
506     /// for element in list.iter_mut() {
507     ///     *element += 10;
508     /// }
509     ///
510     /// let mut iter = list.iter();
511     /// assert_eq!(iter.next(), Some(&10));
512     /// assert_eq!(iter.next(), Some(&11));
513     /// assert_eq!(iter.next(), Some(&12));
514     /// assert_eq!(iter.next(), None);
515     /// ```
516     #[inline]
517     #[stable(feature = "rust1", since = "1.0.0")]
518     pub fn iter_mut(&mut self) -> IterMut<'_, T> {
519         IterMut { head: self.head, tail: self.tail, len: self.len, marker: PhantomData }
520     }
521
522     /// Provides a cursor at the front element.
523     ///
524     /// The cursor is pointing to the "ghost" non-element if the list is empty.
525     #[inline]
526     #[unstable(feature = "linked_list_cursors", issue = "58533")]
527     pub fn cursor_front(&self) -> Cursor<'_, T> {
528         Cursor { index: 0, current: self.head, list: self }
529     }
530
531     /// Provides a cursor with editing operations at the front element.
532     ///
533     /// The cursor is pointing to the "ghost" non-element if the list is empty.
534     #[inline]
535     #[unstable(feature = "linked_list_cursors", issue = "58533")]
536     pub fn cursor_front_mut(&mut self) -> CursorMut<'_, T> {
537         CursorMut { index: 0, current: self.head, list: self }
538     }
539
540     /// Provides a cursor at the back element.
541     ///
542     /// The cursor is pointing to the "ghost" non-element if the list is empty.
543     #[inline]
544     #[unstable(feature = "linked_list_cursors", issue = "58533")]
545     pub fn cursor_back(&self) -> Cursor<'_, T> {
546         Cursor { index: self.len.checked_sub(1).unwrap_or(0), current: self.tail, list: self }
547     }
548
549     /// Provides a cursor with editing operations at the back element.
550     ///
551     /// The cursor is pointing to the "ghost" non-element if the list is empty.
552     #[inline]
553     #[unstable(feature = "linked_list_cursors", issue = "58533")]
554     pub fn cursor_back_mut(&mut self) -> CursorMut<'_, T> {
555         CursorMut { index: self.len.checked_sub(1).unwrap_or(0), current: self.tail, list: self }
556     }
557
558     /// Returns `true` if the `LinkedList` is empty.
559     ///
560     /// This operation should compute in *O*(1) time.
561     ///
562     /// # Examples
563     ///
564     /// ```
565     /// use std::collections::LinkedList;
566     ///
567     /// let mut dl = LinkedList::new();
568     /// assert!(dl.is_empty());
569     ///
570     /// dl.push_front("foo");
571     /// assert!(!dl.is_empty());
572     /// ```
573     #[inline]
574     #[stable(feature = "rust1", since = "1.0.0")]
575     pub fn is_empty(&self) -> bool {
576         self.head.is_none()
577     }
578
579     /// Returns the length of the `LinkedList`.
580     ///
581     /// This operation should compute in *O*(1) time.
582     ///
583     /// # Examples
584     ///
585     /// ```
586     /// use std::collections::LinkedList;
587     ///
588     /// let mut dl = LinkedList::new();
589     ///
590     /// dl.push_front(2);
591     /// assert_eq!(dl.len(), 1);
592     ///
593     /// dl.push_front(1);
594     /// assert_eq!(dl.len(), 2);
595     ///
596     /// dl.push_back(3);
597     /// assert_eq!(dl.len(), 3);
598     /// ```
599     #[inline]
600     #[stable(feature = "rust1", since = "1.0.0")]
601     pub fn len(&self) -> usize {
602         self.len
603     }
604
605     /// Removes all elements from the `LinkedList`.
606     ///
607     /// This operation should compute in *O*(*n*) time.
608     ///
609     /// # Examples
610     ///
611     /// ```
612     /// use std::collections::LinkedList;
613     ///
614     /// let mut dl = LinkedList::new();
615     ///
616     /// dl.push_front(2);
617     /// dl.push_front(1);
618     /// assert_eq!(dl.len(), 2);
619     /// assert_eq!(dl.front(), Some(&1));
620     ///
621     /// dl.clear();
622     /// assert_eq!(dl.len(), 0);
623     /// assert_eq!(dl.front(), None);
624     /// ```
625     #[inline]
626     #[stable(feature = "rust1", since = "1.0.0")]
627     pub fn clear(&mut self) {
628         *self = Self::new();
629     }
630
631     /// Returns `true` if the `LinkedList` contains an element equal to the
632     /// given value.
633     ///
634     /// # Examples
635     ///
636     /// ```
637     /// use std::collections::LinkedList;
638     ///
639     /// let mut list: LinkedList<u32> = LinkedList::new();
640     ///
641     /// list.push_back(0);
642     /// list.push_back(1);
643     /// list.push_back(2);
644     ///
645     /// assert_eq!(list.contains(&0), true);
646     /// assert_eq!(list.contains(&10), false);
647     /// ```
648     #[stable(feature = "linked_list_contains", since = "1.12.0")]
649     pub fn contains(&self, x: &T) -> bool
650     where
651         T: PartialEq<T>,
652     {
653         self.iter().any(|e| e == x)
654     }
655
656     /// Provides a reference to the front element, or `None` if the list is
657     /// empty.
658     ///
659     /// # Examples
660     ///
661     /// ```
662     /// use std::collections::LinkedList;
663     ///
664     /// let mut dl = LinkedList::new();
665     /// assert_eq!(dl.front(), None);
666     ///
667     /// dl.push_front(1);
668     /// assert_eq!(dl.front(), Some(&1));
669     /// ```
670     #[inline]
671     #[stable(feature = "rust1", since = "1.0.0")]
672     pub fn front(&self) -> Option<&T> {
673         unsafe { self.head.as_ref().map(|node| &node.as_ref().element) }
674     }
675
676     /// Provides a mutable reference to the front element, or `None` if the list
677     /// is empty.
678     ///
679     /// # Examples
680     ///
681     /// ```
682     /// use std::collections::LinkedList;
683     ///
684     /// let mut dl = LinkedList::new();
685     /// assert_eq!(dl.front(), None);
686     ///
687     /// dl.push_front(1);
688     /// assert_eq!(dl.front(), Some(&1));
689     ///
690     /// match dl.front_mut() {
691     ///     None => {},
692     ///     Some(x) => *x = 5,
693     /// }
694     /// assert_eq!(dl.front(), Some(&5));
695     /// ```
696     #[inline]
697     #[stable(feature = "rust1", since = "1.0.0")]
698     pub fn front_mut(&mut self) -> Option<&mut T> {
699         unsafe { self.head.as_mut().map(|node| &mut node.as_mut().element) }
700     }
701
702     /// Provides a reference to the back element, or `None` if the list is
703     /// empty.
704     ///
705     /// # Examples
706     ///
707     /// ```
708     /// use std::collections::LinkedList;
709     ///
710     /// let mut dl = LinkedList::new();
711     /// assert_eq!(dl.back(), None);
712     ///
713     /// dl.push_back(1);
714     /// assert_eq!(dl.back(), Some(&1));
715     /// ```
716     #[inline]
717     #[stable(feature = "rust1", since = "1.0.0")]
718     pub fn back(&self) -> Option<&T> {
719         unsafe { self.tail.as_ref().map(|node| &node.as_ref().element) }
720     }
721
722     /// Provides a mutable reference to the back element, or `None` if the list
723     /// is empty.
724     ///
725     /// # Examples
726     ///
727     /// ```
728     /// use std::collections::LinkedList;
729     ///
730     /// let mut dl = LinkedList::new();
731     /// assert_eq!(dl.back(), None);
732     ///
733     /// dl.push_back(1);
734     /// assert_eq!(dl.back(), Some(&1));
735     ///
736     /// match dl.back_mut() {
737     ///     None => {},
738     ///     Some(x) => *x = 5,
739     /// }
740     /// assert_eq!(dl.back(), Some(&5));
741     /// ```
742     #[inline]
743     #[stable(feature = "rust1", since = "1.0.0")]
744     pub fn back_mut(&mut self) -> Option<&mut T> {
745         unsafe { self.tail.as_mut().map(|node| &mut node.as_mut().element) }
746     }
747
748     /// Adds an element first in the list.
749     ///
750     /// This operation should compute in *O*(1) time.
751     ///
752     /// # Examples
753     ///
754     /// ```
755     /// use std::collections::LinkedList;
756     ///
757     /// let mut dl = LinkedList::new();
758     ///
759     /// dl.push_front(2);
760     /// assert_eq!(dl.front().unwrap(), &2);
761     ///
762     /// dl.push_front(1);
763     /// assert_eq!(dl.front().unwrap(), &1);
764     /// ```
765     #[stable(feature = "rust1", since = "1.0.0")]
766     pub fn push_front(&mut self, elt: T) {
767         self.push_front_node(box Node::new(elt));
768     }
769
770     /// Removes the first element and returns it, or `None` if the list is
771     /// empty.
772     ///
773     /// This operation should compute in *O*(1) time.
774     ///
775     /// # Examples
776     ///
777     /// ```
778     /// use std::collections::LinkedList;
779     ///
780     /// let mut d = LinkedList::new();
781     /// assert_eq!(d.pop_front(), None);
782     ///
783     /// d.push_front(1);
784     /// d.push_front(3);
785     /// assert_eq!(d.pop_front(), Some(3));
786     /// assert_eq!(d.pop_front(), Some(1));
787     /// assert_eq!(d.pop_front(), None);
788     /// ```
789     #[stable(feature = "rust1", since = "1.0.0")]
790     pub fn pop_front(&mut self) -> Option<T> {
791         self.pop_front_node().map(Node::into_element)
792     }
793
794     /// Appends an element to the back of a list.
795     ///
796     /// This operation should compute in *O*(1) time.
797     ///
798     /// # Examples
799     ///
800     /// ```
801     /// use std::collections::LinkedList;
802     ///
803     /// let mut d = LinkedList::new();
804     /// d.push_back(1);
805     /// d.push_back(3);
806     /// assert_eq!(3, *d.back().unwrap());
807     /// ```
808     #[stable(feature = "rust1", since = "1.0.0")]
809     pub fn push_back(&mut self, elt: T) {
810         self.push_back_node(box Node::new(elt));
811     }
812
813     /// Removes the last element from a list and returns it, or `None` if
814     /// it is empty.
815     ///
816     /// This operation should compute in *O*(1) time.
817     ///
818     /// # Examples
819     ///
820     /// ```
821     /// use std::collections::LinkedList;
822     ///
823     /// let mut d = LinkedList::new();
824     /// assert_eq!(d.pop_back(), None);
825     /// d.push_back(1);
826     /// d.push_back(3);
827     /// assert_eq!(d.pop_back(), Some(3));
828     /// ```
829     #[stable(feature = "rust1", since = "1.0.0")]
830     pub fn pop_back(&mut self) -> Option<T> {
831         self.pop_back_node().map(Node::into_element)
832     }
833
834     /// Splits the list into two at the given index. Returns everything after the given index,
835     /// including the index.
836     ///
837     /// This operation should compute in *O*(*n*) time.
838     ///
839     /// # Panics
840     ///
841     /// Panics if `at > len`.
842     ///
843     /// # Examples
844     ///
845     /// ```
846     /// use std::collections::LinkedList;
847     ///
848     /// let mut d = LinkedList::new();
849     ///
850     /// d.push_front(1);
851     /// d.push_front(2);
852     /// d.push_front(3);
853     ///
854     /// let mut split = d.split_off(2);
855     ///
856     /// assert_eq!(split.pop_front(), Some(1));
857     /// assert_eq!(split.pop_front(), None);
858     /// ```
859     #[stable(feature = "rust1", since = "1.0.0")]
860     pub fn split_off(&mut self, at: usize) -> LinkedList<T> {
861         let len = self.len();
862         assert!(at <= len, "Cannot split off at a nonexistent index");
863         if at == 0 {
864             return mem::take(self);
865         } else if at == len {
866             return Self::new();
867         }
868
869         // Below, we iterate towards the `i-1`th node, either from the start or the end,
870         // depending on which would be faster.
871         let split_node = if at - 1 <= len - 1 - (at - 1) {
872             let mut iter = self.iter_mut();
873             // instead of skipping using .skip() (which creates a new struct),
874             // we skip manually so we can access the head field without
875             // depending on implementation details of Skip
876             for _ in 0..at - 1 {
877                 iter.next();
878             }
879             iter.head
880         } else {
881             // better off starting from the end
882             let mut iter = self.iter_mut();
883             for _ in 0..len - 1 - (at - 1) {
884                 iter.next_back();
885             }
886             iter.tail
887         };
888         unsafe { self.split_off_after_node(split_node, at) }
889     }
890
891     /// Removes the element at the given index and returns it.
892     ///
893     /// This operation should compute in *O*(*n*) time.
894     ///
895     /// # Panics
896     /// Panics if at >= len
897     ///
898     /// # Examples
899     ///
900     /// ```
901     /// #![feature(linked_list_remove)]
902     /// use std::collections::LinkedList;
903     ///
904     /// let mut d = LinkedList::new();
905     ///
906     /// d.push_front(1);
907     /// d.push_front(2);
908     /// d.push_front(3);
909     ///
910     /// assert_eq!(d.remove(1), 2);
911     /// assert_eq!(d.remove(0), 3);
912     /// assert_eq!(d.remove(0), 1);
913     /// ```
914     #[unstable(feature = "linked_list_remove", issue = "69210")]
915     pub fn remove(&mut self, at: usize) -> T {
916         let len = self.len();
917         assert!(at < len, "Cannot remove at an index outside of the list bounds");
918
919         // Below, we iterate towards the node at the given index, either from
920         // the start or the end, depending on which would be faster.
921         let offset_from_end = len - at - 1;
922         if at <= offset_from_end {
923             let mut cursor = self.cursor_front_mut();
924             for _ in 0..at {
925                 cursor.move_next();
926             }
927             cursor.remove_current().unwrap()
928         } else {
929             let mut cursor = self.cursor_back_mut();
930             for _ in 0..offset_from_end {
931                 cursor.move_prev();
932             }
933             cursor.remove_current().unwrap()
934         }
935     }
936
937     /// Creates an iterator which uses a closure to determine if an element should be removed.
938     ///
939     /// If the closure returns true, then the element is removed and yielded.
940     /// If the closure returns false, the element will remain in the list and will not be yielded
941     /// by the iterator.
942     ///
943     /// Note that `drain_filter` lets you mutate every element in the filter closure, regardless of
944     /// whether you choose to keep or remove it.
945     ///
946     /// # Examples
947     ///
948     /// Splitting a list into evens and odds, reusing the original list:
949     ///
950     /// ```
951     /// #![feature(drain_filter)]
952     /// use std::collections::LinkedList;
953     ///
954     /// let mut numbers: LinkedList<u32> = LinkedList::new();
955     /// numbers.extend(&[1, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15]);
956     ///
957     /// let evens = numbers.drain_filter(|x| *x % 2 == 0).collect::<LinkedList<_>>();
958     /// let odds = numbers;
959     ///
960     /// assert_eq!(evens.into_iter().collect::<Vec<_>>(), vec![2, 4, 6, 8, 14]);
961     /// assert_eq!(odds.into_iter().collect::<Vec<_>>(), vec![1, 3, 5, 9, 11, 13, 15]);
962     /// ```
963     #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
964     pub fn drain_filter<F>(&mut self, filter: F) -> DrainFilter<'_, T, F>
965     where
966         F: FnMut(&mut T) -> bool,
967     {
968         // avoid borrow issues.
969         let it = self.head;
970         let old_len = self.len;
971
972         DrainFilter { list: self, it, pred: filter, idx: 0, old_len }
973     }
974 }
975
976 #[stable(feature = "rust1", since = "1.0.0")]
977 unsafe impl<#[may_dangle] T> Drop for LinkedList<T> {
978     fn drop(&mut self) {
979         struct DropGuard<'a, T>(&'a mut LinkedList<T>);
980
981         impl<'a, T> Drop for DropGuard<'a, T> {
982             fn drop(&mut self) {
983                 // Continue the same loop we do below. This only runs when a destructor has
984                 // panicked. If another one panics this will abort.
985                 while self.0.pop_front_node().is_some() {}
986             }
987         }
988
989         while let Some(node) = self.pop_front_node() {
990             let guard = DropGuard(self);
991             drop(node);
992             mem::forget(guard);
993         }
994     }
995 }
996
997 #[stable(feature = "rust1", since = "1.0.0")]
998 impl<'a, T> Iterator for Iter<'a, T> {
999     type Item = &'a T;
1000
1001     #[inline]
1002     fn next(&mut self) -> Option<&'a T> {
1003         if self.len == 0 {
1004             None
1005         } else {
1006             self.head.map(|node| unsafe {
1007                 // Need an unbound lifetime to get 'a
1008                 let node = &*node.as_ptr();
1009                 self.len -= 1;
1010                 self.head = node.next;
1011                 &node.element
1012             })
1013         }
1014     }
1015
1016     #[inline]
1017     fn size_hint(&self) -> (usize, Option<usize>) {
1018         (self.len, Some(self.len))
1019     }
1020
1021     #[inline]
1022     fn last(mut self) -> Option<&'a T> {
1023         self.next_back()
1024     }
1025 }
1026
1027 #[stable(feature = "rust1", since = "1.0.0")]
1028 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
1029     #[inline]
1030     fn next_back(&mut self) -> Option<&'a T> {
1031         if self.len == 0 {
1032             None
1033         } else {
1034             self.tail.map(|node| unsafe {
1035                 // Need an unbound lifetime to get 'a
1036                 let node = &*node.as_ptr();
1037                 self.len -= 1;
1038                 self.tail = node.prev;
1039                 &node.element
1040             })
1041         }
1042     }
1043 }
1044
1045 #[stable(feature = "rust1", since = "1.0.0")]
1046 impl<T> ExactSizeIterator for Iter<'_, T> {}
1047
1048 #[stable(feature = "fused", since = "1.26.0")]
1049 impl<T> FusedIterator for Iter<'_, T> {}
1050
1051 #[stable(feature = "rust1", since = "1.0.0")]
1052 impl<'a, T> Iterator for IterMut<'a, T> {
1053     type Item = &'a mut T;
1054
1055     #[inline]
1056     fn next(&mut self) -> Option<&'a mut T> {
1057         if self.len == 0 {
1058             None
1059         } else {
1060             self.head.map(|node| unsafe {
1061                 // Need an unbound lifetime to get 'a
1062                 let node = &mut *node.as_ptr();
1063                 self.len -= 1;
1064                 self.head = node.next;
1065                 &mut node.element
1066             })
1067         }
1068     }
1069
1070     #[inline]
1071     fn size_hint(&self) -> (usize, Option<usize>) {
1072         (self.len, Some(self.len))
1073     }
1074
1075     #[inline]
1076     fn last(mut self) -> Option<&'a mut T> {
1077         self.next_back()
1078     }
1079 }
1080
1081 #[stable(feature = "rust1", since = "1.0.0")]
1082 impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
1083     #[inline]
1084     fn next_back(&mut self) -> Option<&'a mut T> {
1085         if self.len == 0 {
1086             None
1087         } else {
1088             self.tail.map(|node| unsafe {
1089                 // Need an unbound lifetime to get 'a
1090                 let node = &mut *node.as_ptr();
1091                 self.len -= 1;
1092                 self.tail = node.prev;
1093                 &mut node.element
1094             })
1095         }
1096     }
1097 }
1098
1099 #[stable(feature = "rust1", since = "1.0.0")]
1100 impl<T> ExactSizeIterator for IterMut<'_, T> {}
1101
1102 #[stable(feature = "fused", since = "1.26.0")]
1103 impl<T> FusedIterator for IterMut<'_, T> {}
1104
1105 /// A cursor over a `LinkedList`.
1106 ///
1107 /// A `Cursor` is like an iterator, except that it can freely seek back-and-forth.
1108 ///
1109 /// Cursors always rest between two elements in the list, and index in a logically circular way.
1110 /// To accommodate this, there is a "ghost" non-element that yields `None` between the head and
1111 /// tail of the list.
1112 ///
1113 /// When created, cursors start at the front of the list, or the "ghost" non-element if the list is empty.
1114 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1115 pub struct Cursor<'a, T: 'a> {
1116     index: usize,
1117     current: Option<NonNull<Node<T>>>,
1118     list: &'a LinkedList<T>,
1119 }
1120
1121 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1122 impl<T> Clone for Cursor<'_, T> {
1123     fn clone(&self) -> Self {
1124         let Cursor { index, current, list } = *self;
1125         Cursor { index, current, list }
1126     }
1127 }
1128
1129 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1130 impl<T: fmt::Debug> fmt::Debug for Cursor<'_, T> {
1131     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1132         f.debug_tuple("Cursor").field(&self.list).field(&self.index()).finish()
1133     }
1134 }
1135
1136 /// A cursor over a `LinkedList` with editing operations.
1137 ///
1138 /// A `Cursor` is like an iterator, except that it can freely seek back-and-forth, and can
1139 /// safely mutate the list during iteration. This is because the lifetime of its yielded
1140 /// references is tied to its own lifetime, instead of just the underlying list. This means
1141 /// cursors cannot yield multiple elements at once.
1142 ///
1143 /// Cursors always rest between two elements in the list, and index in a logically circular way.
1144 /// To accommodate this, there is a "ghost" non-element that yields `None` between the head and
1145 /// tail of the list.
1146 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1147 pub struct CursorMut<'a, T: 'a> {
1148     index: usize,
1149     current: Option<NonNull<Node<T>>>,
1150     list: &'a mut LinkedList<T>,
1151 }
1152
1153 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1154 impl<T: fmt::Debug> fmt::Debug for CursorMut<'_, T> {
1155     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1156         f.debug_tuple("CursorMut").field(&self.list).field(&self.index()).finish()
1157     }
1158 }
1159
1160 impl<'a, T> Cursor<'a, T> {
1161     /// Returns the cursor position index within the `LinkedList`.
1162     ///
1163     /// This returns `None` if the cursor is currently pointing to the
1164     /// "ghost" non-element.
1165     #[unstable(feature = "linked_list_cursors", issue = "58533")]
1166     pub fn index(&self) -> Option<usize> {
1167         let _ = self.current?;
1168         Some(self.index)
1169     }
1170
1171     /// Moves the cursor to the next element of the `LinkedList`.
1172     ///
1173     /// If the cursor is pointing to the "ghost" non-element then this will move it to
1174     /// the first element of the `LinkedList`. If it is pointing to the last
1175     /// element of the `LinkedList` then this will move it to the "ghost" non-element.
1176     #[unstable(feature = "linked_list_cursors", issue = "58533")]
1177     pub fn move_next(&mut self) {
1178         match self.current.take() {
1179             // We had no current element; the cursor was sitting at the start position
1180             // Next element should be the head of the list
1181             None => {
1182                 self.current = self.list.head;
1183                 self.index = 0;
1184             }
1185             // We had a previous element, so let's go to its next
1186             Some(current) => unsafe {
1187                 self.current = current.as_ref().next;
1188                 self.index += 1;
1189             },
1190         }
1191     }
1192
1193     /// Moves the cursor to the previous element of the `LinkedList`.
1194     ///
1195     /// If the cursor is pointing to the "ghost" non-element then this will move it to
1196     /// the last element of the `LinkedList`. If it is pointing to the first
1197     /// element of the `LinkedList` then this will move it to the "ghost" non-element.
1198     #[unstable(feature = "linked_list_cursors", issue = "58533")]
1199     pub fn move_prev(&mut self) {
1200         match self.current.take() {
1201             // No current. We're at the start of the list. Yield None and jump to the end.
1202             None => {
1203                 self.current = self.list.tail;
1204                 self.index = self.list.len().checked_sub(1).unwrap_or(0);
1205             }
1206             // Have a prev. Yield it and go to the previous element.
1207             Some(current) => unsafe {
1208                 self.current = current.as_ref().prev;
1209                 self.index = self.index.checked_sub(1).unwrap_or_else(|| self.list.len());
1210             },
1211         }
1212     }
1213
1214     /// Returns a reference to the element that the cursor is currently
1215     /// pointing to.
1216     ///
1217     /// This returns `None` if the cursor is currently pointing to the
1218     /// "ghost" non-element.
1219     #[unstable(feature = "linked_list_cursors", issue = "58533")]
1220     pub fn current(&self) -> Option<&'a T> {
1221         unsafe { self.current.map(|current| &(*current.as_ptr()).element) }
1222     }
1223
1224     /// Returns a reference to the next element.
1225     ///
1226     /// If the cursor is pointing to the "ghost" non-element then this returns
1227     /// the first element of the `LinkedList`. If it is pointing to the last
1228     /// element of the `LinkedList` then this returns `None`.
1229     #[unstable(feature = "linked_list_cursors", issue = "58533")]
1230     pub fn peek_next(&self) -> Option<&'a T> {
1231         unsafe {
1232             let next = match self.current {
1233                 None => self.list.head,
1234                 Some(current) => current.as_ref().next,
1235             };
1236             next.map(|next| &(*next.as_ptr()).element)
1237         }
1238     }
1239
1240     /// Returns a reference to the previous element.
1241     ///
1242     /// If the cursor is pointing to the "ghost" non-element then this returns
1243     /// the last element of the `LinkedList`. If it is pointing to the first
1244     /// element of the `LinkedList` then this returns `None`.
1245     #[unstable(feature = "linked_list_cursors", issue = "58533")]
1246     pub fn peek_prev(&self) -> Option<&'a T> {
1247         unsafe {
1248             let prev = match self.current {
1249                 None => self.list.tail,
1250                 Some(current) => current.as_ref().prev,
1251             };
1252             prev.map(|prev| &(*prev.as_ptr()).element)
1253         }
1254     }
1255
1256     /// Provides a reference to the front element of the cursor's parent list,
1257     /// or None if the list is empty.
1258     #[unstable(feature = "linked_list_cursors", issue = "58533")]
1259     pub fn front(&self) -> Option<&'a T> {
1260         self.list.front()
1261     }
1262
1263     /// Provides a reference to the back element of the cursor's parent list,
1264     /// or None if the list is empty.
1265     #[unstable(feature = "linked_list_cursors", issue = "58533")]
1266     pub fn back(&self) -> Option<&'a T> {
1267         self.list.back()
1268     }
1269 }
1270
1271 impl<'a, T> CursorMut<'a, T> {
1272     /// Returns the cursor position index within the `LinkedList`.
1273     ///
1274     /// This returns `None` if the cursor is currently pointing to the
1275     /// "ghost" non-element.
1276     #[unstable(feature = "linked_list_cursors", issue = "58533")]
1277     pub fn index(&self) -> Option<usize> {
1278         let _ = self.current?;
1279         Some(self.index)
1280     }
1281
1282     /// Moves the cursor to the next element of the `LinkedList`.
1283     ///
1284     /// If the cursor is pointing to the "ghost" non-element then this will move it to
1285     /// the first element of the `LinkedList`. If it is pointing to the last
1286     /// element of the `LinkedList` then this will move it to the "ghost" non-element.
1287     #[unstable(feature = "linked_list_cursors", issue = "58533")]
1288     pub fn move_next(&mut self) {
1289         match self.current.take() {
1290             // We had no current element; the cursor was sitting at the start position
1291             // Next element should be the head of the list
1292             None => {
1293                 self.current = self.list.head;
1294                 self.index = 0;
1295             }
1296             // We had a previous element, so let's go to its next
1297             Some(current) => unsafe {
1298                 self.current = current.as_ref().next;
1299                 self.index += 1;
1300             },
1301         }
1302     }
1303
1304     /// Moves the cursor to the previous element of the `LinkedList`.
1305     ///
1306     /// If the cursor is pointing to the "ghost" non-element then this will move it to
1307     /// the last element of the `LinkedList`. If it is pointing to the first
1308     /// element of the `LinkedList` then this will move it to the "ghost" non-element.
1309     #[unstable(feature = "linked_list_cursors", issue = "58533")]
1310     pub fn move_prev(&mut self) {
1311         match self.current.take() {
1312             // No current. We're at the start of the list. Yield None and jump to the end.
1313             None => {
1314                 self.current = self.list.tail;
1315                 self.index = self.list.len().checked_sub(1).unwrap_or(0);
1316             }
1317             // Have a prev. Yield it and go to the previous element.
1318             Some(current) => unsafe {
1319                 self.current = current.as_ref().prev;
1320                 self.index = self.index.checked_sub(1).unwrap_or_else(|| self.list.len());
1321             },
1322         }
1323     }
1324
1325     /// Returns a reference to the element that the cursor is currently
1326     /// pointing to.
1327     ///
1328     /// This returns `None` if the cursor is currently pointing to the
1329     /// "ghost" non-element.
1330     #[unstable(feature = "linked_list_cursors", issue = "58533")]
1331     pub fn current(&mut self) -> Option<&mut T> {
1332         unsafe { self.current.map(|current| &mut (*current.as_ptr()).element) }
1333     }
1334
1335     /// Returns a reference to the next element.
1336     ///
1337     /// If the cursor is pointing to the "ghost" non-element then this returns
1338     /// the first element of the `LinkedList`. If it is pointing to the last
1339     /// element of the `LinkedList` then this returns `None`.
1340     #[unstable(feature = "linked_list_cursors", issue = "58533")]
1341     pub fn peek_next(&mut self) -> Option<&mut T> {
1342         unsafe {
1343             let next = match self.current {
1344                 None => self.list.head,
1345                 Some(current) => current.as_ref().next,
1346             };
1347             next.map(|next| &mut (*next.as_ptr()).element)
1348         }
1349     }
1350
1351     /// Returns a reference to the previous element.
1352     ///
1353     /// If the cursor is pointing to the "ghost" non-element then this returns
1354     /// the last element of the `LinkedList`. If it is pointing to the first
1355     /// element of the `LinkedList` then this returns `None`.
1356     #[unstable(feature = "linked_list_cursors", issue = "58533")]
1357     pub fn peek_prev(&mut self) -> Option<&mut T> {
1358         unsafe {
1359             let prev = match self.current {
1360                 None => self.list.tail,
1361                 Some(current) => current.as_ref().prev,
1362             };
1363             prev.map(|prev| &mut (*prev.as_ptr()).element)
1364         }
1365     }
1366
1367     /// Returns a read-only cursor pointing to the current element.
1368     ///
1369     /// The lifetime of the returned `Cursor` is bound to that of the
1370     /// `CursorMut`, which means it cannot outlive the `CursorMut` and that the
1371     /// `CursorMut` is frozen for the lifetime of the `Cursor`.
1372     #[unstable(feature = "linked_list_cursors", issue = "58533")]
1373     pub fn as_cursor(&self) -> Cursor<'_, T> {
1374         Cursor { list: self.list, current: self.current, index: self.index }
1375     }
1376 }
1377
1378 // Now the list editing operations
1379
1380 impl<'a, T> CursorMut<'a, T> {
1381     /// Inserts a new element into the `LinkedList` after the current one.
1382     ///
1383     /// If the cursor is pointing at the "ghost" non-element then the new element is
1384     /// inserted at the front of the `LinkedList`.
1385     #[unstable(feature = "linked_list_cursors", issue = "58533")]
1386     pub fn insert_after(&mut self, item: T) {
1387         unsafe {
1388             let spliced_node = Box::leak(Box::new(Node::new(item))).into();
1389             let node_next = match self.current {
1390                 None => self.list.head,
1391                 Some(node) => node.as_ref().next,
1392             };
1393             self.list.splice_nodes(self.current, node_next, spliced_node, spliced_node, 1);
1394             if self.current.is_none() {
1395                 // The "ghost" non-element's index has changed.
1396                 self.index = self.list.len;
1397             }
1398         }
1399     }
1400
1401     /// Inserts a new element into the `LinkedList` before the current one.
1402     ///
1403     /// If the cursor is pointing at the "ghost" non-element then the new element is
1404     /// inserted at the end of the `LinkedList`.
1405     #[unstable(feature = "linked_list_cursors", issue = "58533")]
1406     pub fn insert_before(&mut self, item: T) {
1407         unsafe {
1408             let spliced_node = Box::leak(Box::new(Node::new(item))).into();
1409             let node_prev = match self.current {
1410                 None => self.list.tail,
1411                 Some(node) => node.as_ref().prev,
1412             };
1413             self.list.splice_nodes(node_prev, self.current, spliced_node, spliced_node, 1);
1414             self.index += 1;
1415         }
1416     }
1417
1418     /// Removes the current element from the `LinkedList`.
1419     ///
1420     /// The element that was removed is returned, and the cursor is
1421     /// moved to point to the next element in the `LinkedList`.
1422     ///
1423     /// If the cursor is currently pointing to the "ghost" non-element then no element
1424     /// is removed and `None` is returned.
1425     #[unstable(feature = "linked_list_cursors", issue = "58533")]
1426     pub fn remove_current(&mut self) -> Option<T> {
1427         let unlinked_node = self.current?;
1428         unsafe {
1429             self.current = unlinked_node.as_ref().next;
1430             self.list.unlink_node(unlinked_node);
1431             let unlinked_node = Box::from_raw(unlinked_node.as_ptr());
1432             Some(unlinked_node.element)
1433         }
1434     }
1435
1436     /// Removes the current element from the `LinkedList` without deallocating the list node.
1437     ///
1438     /// The node that was removed is returned as a new `LinkedList` containing only this node.
1439     /// The cursor is moved to point to the next element in the current `LinkedList`.
1440     ///
1441     /// If the cursor is currently pointing to the "ghost" non-element then no element
1442     /// is removed and `None` is returned.
1443     #[unstable(feature = "linked_list_cursors", issue = "58533")]
1444     pub fn remove_current_as_list(&mut self) -> Option<LinkedList<T>> {
1445         let mut unlinked_node = self.current?;
1446         unsafe {
1447             self.current = unlinked_node.as_ref().next;
1448             self.list.unlink_node(unlinked_node);
1449
1450             unlinked_node.as_mut().prev = None;
1451             unlinked_node.as_mut().next = None;
1452             Some(LinkedList {
1453                 head: Some(unlinked_node),
1454                 tail: Some(unlinked_node),
1455                 len: 1,
1456                 marker: PhantomData,
1457             })
1458         }
1459     }
1460
1461     /// Inserts the elements from the given `LinkedList` after the current one.
1462     ///
1463     /// If the cursor is pointing at the "ghost" non-element then the new elements are
1464     /// inserted at the start of the `LinkedList`.
1465     #[unstable(feature = "linked_list_cursors", issue = "58533")]
1466     pub fn splice_after(&mut self, list: LinkedList<T>) {
1467         unsafe {
1468             let (splice_head, splice_tail, splice_len) = match list.detach_all_nodes() {
1469                 Some(parts) => parts,
1470                 _ => return,
1471             };
1472             let node_next = match self.current {
1473                 None => self.list.head,
1474                 Some(node) => node.as_ref().next,
1475             };
1476             self.list.splice_nodes(self.current, node_next, splice_head, splice_tail, splice_len);
1477             if self.current.is_none() {
1478                 // The "ghost" non-element's index has changed.
1479                 self.index = self.list.len;
1480             }
1481         }
1482     }
1483
1484     /// Inserts the elements from the given `LinkedList` before the current one.
1485     ///
1486     /// If the cursor is pointing at the "ghost" non-element then the new elements are
1487     /// inserted at the end of the `LinkedList`.
1488     #[unstable(feature = "linked_list_cursors", issue = "58533")]
1489     pub fn splice_before(&mut self, list: LinkedList<T>) {
1490         unsafe {
1491             let (splice_head, splice_tail, splice_len) = match list.detach_all_nodes() {
1492                 Some(parts) => parts,
1493                 _ => return,
1494             };
1495             let node_prev = match self.current {
1496                 None => self.list.tail,
1497                 Some(node) => node.as_ref().prev,
1498             };
1499             self.list.splice_nodes(node_prev, self.current, splice_head, splice_tail, splice_len);
1500             self.index += splice_len;
1501         }
1502     }
1503
1504     /// Splits the list into two after the current element. This will return a
1505     /// new list consisting of everything after the cursor, with the original
1506     /// list retaining everything before.
1507     ///
1508     /// If the cursor is pointing at the "ghost" non-element then the entire contents
1509     /// of the `LinkedList` are moved.
1510     #[unstable(feature = "linked_list_cursors", issue = "58533")]
1511     pub fn split_after(&mut self) -> LinkedList<T> {
1512         let split_off_idx = if self.index == self.list.len { 0 } else { self.index + 1 };
1513         if self.index == self.list.len {
1514             // The "ghost" non-element's index has changed to 0.
1515             self.index = 0;
1516         }
1517         unsafe { self.list.split_off_after_node(self.current, split_off_idx) }
1518     }
1519
1520     /// Splits the list into two before the current element. This will return a
1521     /// new list consisting of everything before the cursor, with the original
1522     /// list retaining everything after.
1523     ///
1524     /// If the cursor is pointing at the "ghost" non-element then the entire contents
1525     /// of the `LinkedList` are moved.
1526     #[unstable(feature = "linked_list_cursors", issue = "58533")]
1527     pub fn split_before(&mut self) -> LinkedList<T> {
1528         let split_off_idx = self.index;
1529         self.index = 0;
1530         unsafe { self.list.split_off_before_node(self.current, split_off_idx) }
1531     }
1532
1533     /// Appends an element to the front of the cursor's parent list. The node
1534     /// that the cursor points to is unchanged, even if it is the "ghost" node.
1535     ///
1536     /// This operation should compute in O(1) time.
1537     // `push_front` continues to point to "ghost" when it addes a node to mimic
1538     // the behavior of `insert_before` on an empty list.
1539     #[unstable(feature = "linked_list_cursors", issue = "58533")]
1540     pub fn push_front(&mut self, elt: T) {
1541         // Safety: We know that `push_front` does not change the position in
1542         // memory of other nodes. This ensures that `self.current` remains
1543         // valid.
1544         self.list.push_front(elt);
1545         self.index += 1;
1546     }
1547
1548     /// Appends an element to the back of the cursor's parent list. The node
1549     /// that the cursor points to is unchanged, even if it is the "ghost" node.
1550     ///
1551     /// This operation should compute in O(1) time.
1552     #[unstable(feature = "linked_list_cursors", issue = "58533")]
1553     pub fn push_back(&mut self, elt: T) {
1554         // Safety: We know that `push_back` does not change the position in
1555         // memory of other nodes. This ensures that `self.current` remains
1556         // valid.
1557         self.list.push_back(elt);
1558         if self.current().is_none() {
1559             // The index of "ghost" is the length of the list, so we just need
1560             // to increment self.index to reflect the new length of the list.
1561             self.index += 1;
1562         }
1563     }
1564
1565     /// Removes the first element from the cursor's parent list and returns it,
1566     /// or None if the list is empty. The element the cursor points to remains
1567     /// unchanged, unless it was pointing to the front element. In that case, it
1568     /// points to the new front element.
1569     ///
1570     /// This operation should compute in O(1) time.
1571     #[unstable(feature = "linked_list_cursors", issue = "58533")]
1572     pub fn pop_front(&mut self) -> Option<T> {
1573         // We can't check if current is empty, we must check the list directly.
1574         // It is possible for `self.current == None` and the list to be
1575         // non-empty.
1576         if self.list.is_empty() {
1577             None
1578         } else {
1579             // We can't point to the node that we pop. Copying the behavior of
1580             // `remove_current`, we move on the the next node in the sequence.
1581             // If the list is of length 1 then we end pointing to the "ghost"
1582             // node at index 0, which is expected.
1583             if self.list.head == self.current {
1584                 self.move_next();
1585             } else {
1586                 self.index -= 1;
1587             }
1588             self.list.pop_front()
1589         }
1590     }
1591
1592     /// Removes the last element from the cursor's parent list and returns it,
1593     /// or None if the list is empty. The element the cursor points to remains
1594     /// unchanged, unless it was pointing to the back element. In that case, it
1595     /// points to the "ghost" element.
1596     ///
1597     /// This operation should compute in O(1) time.
1598     #[unstable(feature = "linked_list_cursors", issue = "58533")]
1599     pub fn pop_back(&mut self) -> Option<T> {
1600         if self.list.is_empty() {
1601             None
1602         } else {
1603             if self.list.tail == self.current {
1604                 // The index now reflects the length of the list. It was the
1605                 // length of the list minus 1, but now the list is 1 smaller. No
1606                 // change is needed for `index`.
1607                 self.current = None;
1608             } else if self.current.is_none() {
1609                 self.index = self.list.len - 1;
1610             }
1611             self.list.pop_back()
1612         }
1613     }
1614
1615     /// Provides a reference to the front element of the cursor's parent list,
1616     /// or None if the list is empty.
1617     #[unstable(feature = "linked_list_cursors", issue = "58533")]
1618     pub fn front(&self) -> Option<&T> {
1619         self.list.front()
1620     }
1621
1622     /// Provides a mutable reference to the front element of the cursor's
1623     /// parent list, or None if the list is empty.
1624     #[unstable(feature = "linked_list_cursors", issue = "58533")]
1625     pub fn front_mut(&mut self) -> Option<&mut T> {
1626         self.list.front_mut()
1627     }
1628
1629     /// Provides a reference to the back element of the cursor's parent list,
1630     /// or None if the list is empty.
1631     #[unstable(feature = "linked_list_cursors", issue = "58533")]
1632     pub fn back(&self) -> Option<&T> {
1633         self.list.back()
1634     }
1635
1636     /// Provides a mutable reference to back element of the cursor's parent
1637     /// list, or `None` if the list is empty.
1638     ///
1639     /// # Examples
1640     /// Building and mutating a list with a cursor, then getting the back element:
1641     /// ```
1642     /// #![feature(linked_list_cursors)]
1643     /// use std::collections::LinkedList;
1644     /// let mut dl = LinkedList::new();
1645     /// dl.push_front(3);
1646     /// dl.push_front(2);
1647     /// dl.push_front(1);
1648     /// let mut cursor = dl.cursor_front_mut();
1649     /// *cursor.current().unwrap() = 99;
1650     /// *cursor.back_mut().unwrap() = 0;
1651     /// let mut contents = dl.into_iter();
1652     /// assert_eq!(contents.next(), Some(99));
1653     /// assert_eq!(contents.next(), Some(2));
1654     /// assert_eq!(contents.next(), Some(0));
1655     /// assert_eq!(contents.next(), None);
1656     /// ```
1657     #[unstable(feature = "linked_list_cursors", issue = "58533")]
1658     pub fn back_mut(&mut self) -> Option<&mut T> {
1659         self.list.back_mut()
1660     }
1661 }
1662
1663 /// An iterator produced by calling `drain_filter` on LinkedList.
1664 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
1665 pub struct DrainFilter<'a, T: 'a, F: 'a>
1666 where
1667     F: FnMut(&mut T) -> bool,
1668 {
1669     list: &'a mut LinkedList<T>,
1670     it: Option<NonNull<Node<T>>>,
1671     pred: F,
1672     idx: usize,
1673     old_len: usize,
1674 }
1675
1676 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
1677 impl<T, F> Iterator for DrainFilter<'_, T, F>
1678 where
1679     F: FnMut(&mut T) -> bool,
1680 {
1681     type Item = T;
1682
1683     fn next(&mut self) -> Option<T> {
1684         while let Some(mut node) = self.it {
1685             unsafe {
1686                 self.it = node.as_ref().next;
1687                 self.idx += 1;
1688
1689                 if (self.pred)(&mut node.as_mut().element) {
1690                     // `unlink_node` is okay with aliasing `element` references.
1691                     self.list.unlink_node(node);
1692                     return Some(Box::from_raw(node.as_ptr()).element);
1693                 }
1694             }
1695         }
1696
1697         None
1698     }
1699
1700     fn size_hint(&self) -> (usize, Option<usize>) {
1701         (0, Some(self.old_len - self.idx))
1702     }
1703 }
1704
1705 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
1706 impl<T, F> Drop for DrainFilter<'_, T, F>
1707 where
1708     F: FnMut(&mut T) -> bool,
1709 {
1710     fn drop(&mut self) {
1711         struct DropGuard<'r, 'a, T, F>(&'r mut DrainFilter<'a, T, F>)
1712         where
1713             F: FnMut(&mut T) -> bool;
1714
1715         impl<'r, 'a, T, F> Drop for DropGuard<'r, 'a, T, F>
1716         where
1717             F: FnMut(&mut T) -> bool,
1718         {
1719             fn drop(&mut self) {
1720                 self.0.for_each(drop);
1721             }
1722         }
1723
1724         while let Some(item) = self.next() {
1725             let guard = DropGuard(self);
1726             drop(item);
1727             mem::forget(guard);
1728         }
1729     }
1730 }
1731
1732 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
1733 impl<T: fmt::Debug, F> fmt::Debug for DrainFilter<'_, T, F>
1734 where
1735     F: FnMut(&mut T) -> bool,
1736 {
1737     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1738         f.debug_tuple("DrainFilter").field(&self.list).finish()
1739     }
1740 }
1741
1742 #[stable(feature = "rust1", since = "1.0.0")]
1743 impl<T> Iterator for IntoIter<T> {
1744     type Item = T;
1745
1746     #[inline]
1747     fn next(&mut self) -> Option<T> {
1748         self.list.pop_front()
1749     }
1750
1751     #[inline]
1752     fn size_hint(&self) -> (usize, Option<usize>) {
1753         (self.list.len, Some(self.list.len))
1754     }
1755 }
1756
1757 #[stable(feature = "rust1", since = "1.0.0")]
1758 impl<T> DoubleEndedIterator for IntoIter<T> {
1759     #[inline]
1760     fn next_back(&mut self) -> Option<T> {
1761         self.list.pop_back()
1762     }
1763 }
1764
1765 #[stable(feature = "rust1", since = "1.0.0")]
1766 impl<T> ExactSizeIterator for IntoIter<T> {}
1767
1768 #[stable(feature = "fused", since = "1.26.0")]
1769 impl<T> FusedIterator for IntoIter<T> {}
1770
1771 #[stable(feature = "rust1", since = "1.0.0")]
1772 impl<T> FromIterator<T> for LinkedList<T> {
1773     fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
1774         let mut list = Self::new();
1775         list.extend(iter);
1776         list
1777     }
1778 }
1779
1780 #[stable(feature = "rust1", since = "1.0.0")]
1781 impl<T> IntoIterator for LinkedList<T> {
1782     type Item = T;
1783     type IntoIter = IntoIter<T>;
1784
1785     /// Consumes the list into an iterator yielding elements by value.
1786     #[inline]
1787     fn into_iter(self) -> IntoIter<T> {
1788         IntoIter { list: self }
1789     }
1790 }
1791
1792 #[stable(feature = "rust1", since = "1.0.0")]
1793 impl<'a, T> IntoIterator for &'a LinkedList<T> {
1794     type Item = &'a T;
1795     type IntoIter = Iter<'a, T>;
1796
1797     fn into_iter(self) -> Iter<'a, T> {
1798         self.iter()
1799     }
1800 }
1801
1802 #[stable(feature = "rust1", since = "1.0.0")]
1803 impl<'a, T> IntoIterator for &'a mut LinkedList<T> {
1804     type Item = &'a mut T;
1805     type IntoIter = IterMut<'a, T>;
1806
1807     fn into_iter(self) -> IterMut<'a, T> {
1808         self.iter_mut()
1809     }
1810 }
1811
1812 #[stable(feature = "rust1", since = "1.0.0")]
1813 impl<T> Extend<T> for LinkedList<T> {
1814     fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1815         <Self as SpecExtend<I>>::spec_extend(self, iter);
1816     }
1817
1818     #[inline]
1819     fn extend_one(&mut self, elem: T) {
1820         self.push_back(elem);
1821     }
1822 }
1823
1824 impl<I: IntoIterator> SpecExtend<I> for LinkedList<I::Item> {
1825     default fn spec_extend(&mut self, iter: I) {
1826         iter.into_iter().for_each(move |elt| self.push_back(elt));
1827     }
1828 }
1829
1830 impl<T> SpecExtend<LinkedList<T>> for LinkedList<T> {
1831     fn spec_extend(&mut self, ref mut other: LinkedList<T>) {
1832         self.append(other);
1833     }
1834 }
1835
1836 #[stable(feature = "extend_ref", since = "1.2.0")]
1837 impl<'a, T: 'a + Copy> Extend<&'a T> for LinkedList<T> {
1838     fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
1839         self.extend(iter.into_iter().cloned());
1840     }
1841
1842     #[inline]
1843     fn extend_one(&mut self, &elem: &'a T) {
1844         self.push_back(elem);
1845     }
1846 }
1847
1848 #[stable(feature = "rust1", since = "1.0.0")]
1849 impl<T: PartialEq> PartialEq for LinkedList<T> {
1850     fn eq(&self, other: &Self) -> bool {
1851         self.len() == other.len() && self.iter().eq(other)
1852     }
1853
1854     fn ne(&self, other: &Self) -> bool {
1855         self.len() != other.len() || self.iter().ne(other)
1856     }
1857 }
1858
1859 #[stable(feature = "rust1", since = "1.0.0")]
1860 impl<T: Eq> Eq for LinkedList<T> {}
1861
1862 #[stable(feature = "rust1", since = "1.0.0")]
1863 impl<T: PartialOrd> PartialOrd for LinkedList<T> {
1864     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1865         self.iter().partial_cmp(other)
1866     }
1867 }
1868
1869 #[stable(feature = "rust1", since = "1.0.0")]
1870 impl<T: Ord> Ord for LinkedList<T> {
1871     #[inline]
1872     fn cmp(&self, other: &Self) -> Ordering {
1873         self.iter().cmp(other)
1874     }
1875 }
1876
1877 #[stable(feature = "rust1", since = "1.0.0")]
1878 impl<T: Clone> Clone for LinkedList<T> {
1879     fn clone(&self) -> Self {
1880         self.iter().cloned().collect()
1881     }
1882
1883     fn clone_from(&mut self, other: &Self) {
1884         let mut iter_other = other.iter();
1885         if self.len() > other.len() {
1886             self.split_off(other.len());
1887         }
1888         for (elem, elem_other) in self.iter_mut().zip(&mut iter_other) {
1889             elem.clone_from(elem_other);
1890         }
1891         if !iter_other.is_empty() {
1892             self.extend(iter_other.cloned());
1893         }
1894     }
1895 }
1896
1897 #[stable(feature = "rust1", since = "1.0.0")]
1898 impl<T: fmt::Debug> fmt::Debug for LinkedList<T> {
1899     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1900         f.debug_list().entries(self).finish()
1901     }
1902 }
1903
1904 #[stable(feature = "rust1", since = "1.0.0")]
1905 impl<T: Hash> Hash for LinkedList<T> {
1906     fn hash<H: Hasher>(&self, state: &mut H) {
1907         self.len().hash(state);
1908         for elt in self {
1909             elt.hash(state);
1910         }
1911     }
1912 }
1913
1914 #[stable(feature = "std_collections_from_array", since = "1.56.0")]
1915 impl<T, const N: usize> From<[T; N]> for LinkedList<T> {
1916     /// ```
1917     /// use std::collections::LinkedList;
1918     ///
1919     /// let list1 = LinkedList::from([1, 2, 3, 4]);
1920     /// let list2: LinkedList<_> = [1, 2, 3, 4].into();
1921     /// assert_eq!(list1, list2);
1922     /// ```
1923     fn from(arr: [T; N]) -> Self {
1924         core::array::IntoIter::new(arr).collect()
1925     }
1926 }
1927
1928 // Ensure that `LinkedList` and its read-only iterators are covariant in their type parameters.
1929 #[allow(dead_code)]
1930 fn assert_covariance() {
1931     fn a<'a>(x: LinkedList<&'static str>) -> LinkedList<&'a str> {
1932         x
1933     }
1934     fn b<'i, 'a>(x: Iter<'i, &'static str>) -> Iter<'i, &'a str> {
1935         x
1936     }
1937     fn c<'a>(x: IntoIter<&'static str>) -> IntoIter<&'a str> {
1938         x
1939     }
1940 }
1941
1942 #[stable(feature = "rust1", since = "1.0.0")]
1943 unsafe impl<T: Send> Send for LinkedList<T> {}
1944
1945 #[stable(feature = "rust1", since = "1.0.0")]
1946 unsafe impl<T: Sync> Sync for LinkedList<T> {}
1947
1948 #[stable(feature = "rust1", since = "1.0.0")]
1949 unsafe impl<T: Sync> Send for Iter<'_, T> {}
1950
1951 #[stable(feature = "rust1", since = "1.0.0")]
1952 unsafe impl<T: Sync> Sync for Iter<'_, T> {}
1953
1954 #[stable(feature = "rust1", since = "1.0.0")]
1955 unsafe impl<T: Send> Send for IterMut<'_, T> {}
1956
1957 #[stable(feature = "rust1", since = "1.0.0")]
1958 unsafe impl<T: Sync> Sync for IterMut<'_, T> {}
1959
1960 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1961 unsafe impl<T: Sync> Send for Cursor<'_, T> {}
1962
1963 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1964 unsafe impl<T: Sync> Sync for Cursor<'_, T> {}
1965
1966 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1967 unsafe impl<T: Send> Send for CursorMut<'_, T> {}
1968
1969 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1970 unsafe impl<T: Sync> Sync for CursorMut<'_, T> {}