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