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