Skip to main content

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