1 //! A doubly-linked list with owned nodes.
3 //! The `LinkedList` allows pushing and popping elements at either end
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.
10 //! [`Vec`]: crate::vec::Vec
11 //! [`VecDeque`]: super::vec_deque::VecDeque
13 #![stable(feature = "rust1", since = "1.0.0")]
15 use core
::cmp
::Ordering
;
17 use core
::hash
::{Hash, Hasher}
;
18 use core
::iter
::{FromIterator, FusedIterator}
;
19 use core
::marker
::PhantomData
;
21 use core
::ptr
::NonNull
;
23 use super::SpecExtend
;
24 use crate::boxed
::Box
;
29 /// A doubly-linked list with owned nodes.
31 /// The `LinkedList` allows pushing and popping elements at either end
34 /// A `LinkedList` with a known list of items can be initialized from an array:
36 /// use std::collections::LinkedList;
38 /// let list = LinkedList::from([1, 2, 3]);
41 /// NOTE: It is almost always better to use [`Vec`] or [`VecDeque`] because
42 /// array-based containers are generally faster,
43 /// more memory efficient, and make better use of CPU cache.
45 /// [`Vec`]: crate::vec::Vec
46 /// [`VecDeque`]: super::vec_deque::VecDeque
47 #[stable(feature = "rust1", since = "1.0.0")]
48 #[cfg_attr(not(test), rustc_diagnostic_item = "LinkedList")]
49 #[rustc_insignificant_dtor]
50 pub struct LinkedList
<T
> {
51 head
: Option
<NonNull
<Node
<T
>>>,
52 tail
: Option
<NonNull
<Node
<T
>>>,
54 marker
: PhantomData
<Box
<Node
<T
>>>,
58 next
: Option
<NonNull
<Node
<T
>>>,
59 prev
: Option
<NonNull
<Node
<T
>>>,
63 /// An iterator over the elements of a `LinkedList`.
65 /// This `struct` is created by [`LinkedList::iter()`]. See its
66 /// documentation for more.
67 #[must_use = "iterators are lazy and do nothing unless consumed"]
68 #[stable(feature = "rust1", since = "1.0.0")]
69 pub struct Iter
<'a
, T
: 'a
> {
70 head
: Option
<NonNull
<Node
<T
>>>,
71 tail
: Option
<NonNull
<Node
<T
>>>,
73 marker
: PhantomData
<&'a Node
<T
>>,
76 #[stable(feature = "collection_debug", since = "1.17.0")]
77 impl<T
: fmt
::Debug
> fmt
::Debug
for Iter
<'_
, T
> {
78 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
80 .field(&*mem
::ManuallyDrop
::new(LinkedList
{
91 // FIXME(#26925) Remove in favor of `#[derive(Clone)]`
92 #[stable(feature = "rust1", since = "1.0.0")]
93 impl<T
> Clone
for Iter
<'_
, T
> {
94 fn clone(&self) -> Self {
99 /// A mutable iterator over the elements of a `LinkedList`.
101 /// This `struct` is created by [`LinkedList::iter_mut()`]. See its
102 /// documentation for more.
103 #[must_use = "iterators are lazy and do nothing unless consumed"]
104 #[stable(feature = "rust1", since = "1.0.0")]
105 pub struct IterMut
<'a
, T
: 'a
> {
106 head
: Option
<NonNull
<Node
<T
>>>,
107 tail
: Option
<NonNull
<Node
<T
>>>,
109 marker
: PhantomData
<&'a
mut Node
<T
>>,
112 #[stable(feature = "collection_debug", since = "1.17.0")]
113 impl<T
: fmt
::Debug
> fmt
::Debug
for IterMut
<'_
, T
> {
114 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
115 f
.debug_tuple("IterMut")
116 .field(&*mem
::ManuallyDrop
::new(LinkedList
{
127 /// An owning iterator over the elements of a `LinkedList`.
129 /// This `struct` is created by the [`into_iter`] method on [`LinkedList`]
130 /// (provided by the [`IntoIterator`] trait). See its documentation for more.
132 /// [`into_iter`]: LinkedList::into_iter
133 /// [`IntoIterator`]: core::iter::IntoIterator
135 #[stable(feature = "rust1", since = "1.0.0")]
136 pub struct IntoIter
<T
> {
140 #[stable(feature = "collection_debug", since = "1.17.0")]
141 impl<T
: fmt
::Debug
> fmt
::Debug
for IntoIter
<T
> {
142 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
143 f
.debug_tuple("IntoIter").field(&self.list
).finish()
148 fn new(element
: T
) -> Self {
149 Node { next: None, prev: None, element }
152 fn into_element(self: Box
<Self>) -> T
{
158 impl<T
> LinkedList
<T
> {
159 /// Adds the given node to the front of the list.
161 fn push_front_node(&mut self, mut node
: Box
<Node
<T
>>) {
162 // This method takes care not to create mutable references to whole nodes,
163 // to maintain validity of aliasing pointers into `element`.
165 node
.next
= self.head
;
167 let node
= Some(Box
::leak(node
).into());
170 None
=> self.tail
= node
,
171 // Not creating new mutable (unique!) references overlapping `element`.
172 Some(head
) => (*head
.as_ptr()).prev
= node
,
180 /// Removes and returns the node at the front of the list.
182 fn pop_front_node(&mut self) -> Option
<Box
<Node
<T
>>> {
183 // This method takes care not to create mutable references to whole nodes,
184 // to maintain validity of aliasing pointers into `element`.
185 self.head
.map(|node
| unsafe {
186 let node
= Box
::from_raw(node
.as_ptr());
187 self.head
= node
.next
;
190 None
=> self.tail
= None
,
191 // Not creating new mutable (unique!) references overlapping `element`.
192 Some(head
) => (*head
.as_ptr()).prev
= None
,
200 /// Adds the given node to the back of the list.
202 fn push_back_node(&mut self, mut node
: Box
<Node
<T
>>) {
203 // This method takes care not to create mutable references to whole nodes,
204 // to maintain validity of aliasing pointers into `element`.
207 node
.prev
= self.tail
;
208 let node
= Some(Box
::leak(node
).into());
211 None
=> self.head
= node
,
212 // Not creating new mutable (unique!) references overlapping `element`.
213 Some(tail
) => (*tail
.as_ptr()).next
= node
,
221 /// Removes and returns the node at the back of the list.
223 fn pop_back_node(&mut self) -> Option
<Box
<Node
<T
>>> {
224 // This method takes care not to create mutable references to whole nodes,
225 // to maintain validity of aliasing pointers into `element`.
226 self.tail
.map(|node
| unsafe {
227 let node
= Box
::from_raw(node
.as_ptr());
228 self.tail
= node
.prev
;
231 None
=> self.head
= None
,
232 // Not creating new mutable (unique!) references overlapping `element`.
233 Some(tail
) => (*tail
.as_ptr()).next
= None
,
241 /// Unlinks the specified node from the current list.
243 /// Warning: this will not check that the provided node belongs to the current list.
245 /// This method takes care not to create mutable references to `element`, to
246 /// maintain validity of aliasing pointers.
248 unsafe fn unlink_node(&mut self, mut node
: NonNull
<Node
<T
>>) {
249 let node
= unsafe { node.as_mut() }
; // this one is ours now, we can create an &mut.
251 // Not creating new mutable (unique!) references overlapping `element`.
253 Some(prev
) => unsafe { (*prev.as_ptr()).next = node.next }
,
254 // this node is the head node
255 None
=> self.head
= node
.next
,
259 Some(next
) => unsafe { (*next.as_ptr()).prev = node.prev }
,
260 // this node is the tail node
261 None
=> self.tail
= node
.prev
,
267 /// Splices a series of nodes between two existing nodes.
269 /// Warning: this will not check that the provided node belongs to the two existing lists.
271 unsafe fn splice_nodes(
273 existing_prev
: Option
<NonNull
<Node
<T
>>>,
274 existing_next
: Option
<NonNull
<Node
<T
>>>,
275 mut splice_start
: NonNull
<Node
<T
>>,
276 mut splice_end
: NonNull
<Node
<T
>>,
277 splice_length
: usize,
279 // This method takes care not to create multiple mutable references to whole nodes at the same time,
280 // to maintain validity of aliasing pointers into `element`.
281 if let Some(mut existing_prev
) = existing_prev
{
283 existing_prev
.as_mut().next
= Some(splice_start
);
286 self.head
= Some(splice_start
);
288 if let Some(mut existing_next
) = existing_next
{
290 existing_next
.as_mut().prev
= Some(splice_end
);
293 self.tail
= Some(splice_end
);
296 splice_start
.as_mut().prev
= existing_prev
;
297 splice_end
.as_mut().next
= existing_next
;
300 self.len
+= splice_length
;
303 /// Detaches all nodes from a linked list as a series of nodes.
305 fn detach_all_nodes(mut self) -> Option
<(NonNull
<Node
<T
>>, NonNull
<Node
<T
>>, usize)> {
306 let head
= self.head
.take();
307 let tail
= self.tail
.take();
308 let len
= mem
::replace(&mut self.len
, 0);
309 if let Some(head
) = head
{
310 // SAFETY: In a LinkedList, either both the head and tail are None because
311 // the list is empty, or both head and tail are Some because the list is populated.
312 // Since we have verified the head is Some, we are sure the tail is Some too.
313 let tail
= unsafe { tail.unwrap_unchecked() }
;
314 Some((head
, tail
, len
))
321 unsafe fn split_off_before_node(
323 split_node
: Option
<NonNull
<Node
<T
>>>,
326 // The split node is the new head node of the second part
327 if let Some(mut split_node
) = split_node
{
331 first_part_tail
= split_node
.as_mut().prev
.take();
333 if let Some(mut tail
) = first_part_tail
{
335 tail
.as_mut().next
= None
;
337 first_part_head
= self.head
;
339 first_part_head
= None
;
342 let first_part
= LinkedList
{
343 head
: first_part_head
,
344 tail
: first_part_tail
,
349 // Fix the head ptr of the second part
350 self.head
= Some(split_node
);
351 self.len
= self.len
- at
;
355 mem
::replace(self, LinkedList
::new())
360 unsafe fn split_off_after_node(
362 split_node
: Option
<NonNull
<Node
<T
>>>,
365 // The split node is the new tail node of the first part and owns
366 // the head of the second part.
367 if let Some(mut split_node
) = split_node
{
368 let second_part_head
;
369 let second_part_tail
;
371 second_part_head
= split_node
.as_mut().next
.take();
373 if let Some(mut head
) = second_part_head
{
375 head
.as_mut().prev
= None
;
377 second_part_tail
= self.tail
;
379 second_part_tail
= None
;
382 let second_part
= LinkedList
{
383 head
: second_part_head
,
384 tail
: second_part_tail
,
389 // Fix the tail ptr of the first part
390 self.tail
= Some(split_node
);
395 mem
::replace(self, LinkedList
::new())
400 #[stable(feature = "rust1", since = "1.0.0")]
401 impl<T
> Default
for LinkedList
<T
> {
402 /// Creates an empty `LinkedList<T>`.
404 fn default() -> Self {
409 impl<T
> LinkedList
<T
> {
410 /// Creates an empty `LinkedList`.
415 /// use std::collections::LinkedList;
417 /// let list: LinkedList<u32> = LinkedList::new();
420 #[rustc_const_stable(feature = "const_linked_list_new", since = "1.39.0")]
421 #[stable(feature = "rust1", since = "1.0.0")]
423 pub const fn new() -> Self {
424 LinkedList { head: None, tail: None, len: 0, marker: PhantomData }
427 /// Moves all elements from `other` to the end of the list.
429 /// This reuses all the nodes from `other` and moves them into `self`. After
430 /// this operation, `other` becomes empty.
432 /// This operation should compute in *O*(1) time and *O*(1) memory.
437 /// use std::collections::LinkedList;
439 /// let mut list1 = LinkedList::new();
440 /// list1.push_back('a');
442 /// let mut list2 = LinkedList::new();
443 /// list2.push_back('b');
444 /// list2.push_back('c');
446 /// list1.append(&mut list2);
448 /// let mut iter = list1.iter();
449 /// assert_eq!(iter.next(), Some(&'a'));
450 /// assert_eq!(iter.next(), Some(&'b'));
451 /// assert_eq!(iter.next(), Some(&'c'));
452 /// assert!(iter.next().is_none());
454 /// assert!(list2.is_empty());
456 #[stable(feature = "rust1", since = "1.0.0")]
457 pub fn append(&mut self, other
: &mut Self) {
459 None
=> mem
::swap(self, other
),
461 // `as_mut` is okay here because we have exclusive access to the entirety
463 if let Some(mut other_head
) = other
.head
.take() {
465 tail
.as_mut().next
= Some(other_head
);
466 other_head
.as_mut().prev
= Some(tail
);
469 self.tail
= other
.tail
.take();
470 self.len
+= mem
::replace(&mut other
.len
, 0);
476 /// Provides a forward iterator.
481 /// use std::collections::LinkedList;
483 /// let mut list: LinkedList<u32> = LinkedList::new();
485 /// list.push_back(0);
486 /// list.push_back(1);
487 /// list.push_back(2);
489 /// let mut iter = list.iter();
490 /// assert_eq!(iter.next(), Some(&0));
491 /// assert_eq!(iter.next(), Some(&1));
492 /// assert_eq!(iter.next(), Some(&2));
493 /// assert_eq!(iter.next(), None);
496 #[stable(feature = "rust1", since = "1.0.0")]
497 pub fn iter(&self) -> Iter
<'_
, T
> {
498 Iter { head: self.head, tail: self.tail, len: self.len, marker: PhantomData }
501 /// Provides a forward iterator with mutable references.
506 /// use std::collections::LinkedList;
508 /// let mut list: LinkedList<u32> = LinkedList::new();
510 /// list.push_back(0);
511 /// list.push_back(1);
512 /// list.push_back(2);
514 /// for element in list.iter_mut() {
518 /// let mut iter = list.iter();
519 /// assert_eq!(iter.next(), Some(&10));
520 /// assert_eq!(iter.next(), Some(&11));
521 /// assert_eq!(iter.next(), Some(&12));
522 /// assert_eq!(iter.next(), None);
525 #[stable(feature = "rust1", since = "1.0.0")]
526 pub fn iter_mut(&mut self) -> IterMut
<'_
, T
> {
527 IterMut { head: self.head, tail: self.tail, len: self.len, marker: PhantomData }
530 /// Provides a cursor at the front element.
532 /// The cursor is pointing to the "ghost" non-element if the list is empty.
535 #[unstable(feature = "linked_list_cursors", issue = "58533")]
536 pub fn cursor_front(&self) -> Cursor
<'_
, T
> {
537 Cursor { index: 0, current: self.head, list: self }
540 /// Provides a cursor with editing operations at the front element.
542 /// The cursor is pointing to the "ghost" non-element if the list is empty.
545 #[unstable(feature = "linked_list_cursors", issue = "58533")]
546 pub fn cursor_front_mut(&mut self) -> CursorMut
<'_
, T
> {
547 CursorMut { index: 0, current: self.head, list: self }
550 /// Provides a cursor at the back element.
552 /// The cursor is pointing to the "ghost" non-element if the list is empty.
555 #[unstable(feature = "linked_list_cursors", issue = "58533")]
556 pub fn cursor_back(&self) -> Cursor
<'_
, T
> {
557 Cursor { index: self.len.checked_sub(1).unwrap_or(0), current: self.tail, list: self }
560 /// Provides a cursor with editing operations at the back element.
562 /// The cursor is pointing to the "ghost" non-element if the list is empty.
565 #[unstable(feature = "linked_list_cursors", issue = "58533")]
566 pub fn cursor_back_mut(&mut self) -> CursorMut
<'_
, T
> {
567 CursorMut { index: self.len.checked_sub(1).unwrap_or(0), current: self.tail, list: self }
570 /// Returns `true` if the `LinkedList` is empty.
572 /// This operation should compute in *O*(1) time.
577 /// use std::collections::LinkedList;
579 /// let mut dl = LinkedList::new();
580 /// assert!(dl.is_empty());
582 /// dl.push_front("foo");
583 /// assert!(!dl.is_empty());
587 #[stable(feature = "rust1", since = "1.0.0")]
588 pub fn is_empty(&self) -> bool
{
592 /// Returns the length of the `LinkedList`.
594 /// This operation should compute in *O*(1) time.
599 /// use std::collections::LinkedList;
601 /// let mut dl = LinkedList::new();
603 /// dl.push_front(2);
604 /// assert_eq!(dl.len(), 1);
606 /// dl.push_front(1);
607 /// assert_eq!(dl.len(), 2);
610 /// assert_eq!(dl.len(), 3);
614 #[stable(feature = "rust1", since = "1.0.0")]
615 pub fn len(&self) -> usize {
619 /// Removes all elements from the `LinkedList`.
621 /// This operation should compute in *O*(*n*) time.
626 /// use std::collections::LinkedList;
628 /// let mut dl = LinkedList::new();
630 /// dl.push_front(2);
631 /// dl.push_front(1);
632 /// assert_eq!(dl.len(), 2);
633 /// assert_eq!(dl.front(), Some(&1));
636 /// assert_eq!(dl.len(), 0);
637 /// assert_eq!(dl.front(), None);
640 #[stable(feature = "rust1", since = "1.0.0")]
641 pub fn clear(&mut self) {
645 /// Returns `true` if the `LinkedList` contains an element equal to the
648 /// This operation should compute linearly in *O*(*n*) time.
653 /// use std::collections::LinkedList;
655 /// let mut list: LinkedList<u32> = LinkedList::new();
657 /// list.push_back(0);
658 /// list.push_back(1);
659 /// list.push_back(2);
661 /// assert_eq!(list.contains(&0), true);
662 /// assert_eq!(list.contains(&10), false);
664 #[stable(feature = "linked_list_contains", since = "1.12.0")]
665 pub fn contains(&self, x
: &T
) -> bool
669 self.iter().any(|e
| e
== x
)
672 /// Provides a reference to the front element, or `None` if the list is
675 /// This operation should compute in *O*(1) time.
680 /// use std::collections::LinkedList;
682 /// let mut dl = LinkedList::new();
683 /// assert_eq!(dl.front(), None);
685 /// dl.push_front(1);
686 /// assert_eq!(dl.front(), Some(&1));
690 #[stable(feature = "rust1", since = "1.0.0")]
691 pub fn front(&self) -> Option
<&T
> {
692 unsafe { self.head.as_ref().map(|node| &node.as_ref().element) }
695 /// Provides a mutable reference to the front element, or `None` if the list
698 /// This operation should compute in *O*(1) time.
703 /// use std::collections::LinkedList;
705 /// let mut dl = LinkedList::new();
706 /// assert_eq!(dl.front(), None);
708 /// dl.push_front(1);
709 /// assert_eq!(dl.front(), Some(&1));
711 /// match dl.front_mut() {
713 /// Some(x) => *x = 5,
715 /// assert_eq!(dl.front(), Some(&5));
719 #[stable(feature = "rust1", since = "1.0.0")]
720 pub fn front_mut(&mut self) -> Option
<&mut T
> {
721 unsafe { self.head.as_mut().map(|node| &mut node.as_mut().element) }
724 /// Provides a reference to the back element, or `None` if the list is
727 /// This operation should compute in *O*(1) time.
732 /// use std::collections::LinkedList;
734 /// let mut dl = LinkedList::new();
735 /// assert_eq!(dl.back(), None);
738 /// assert_eq!(dl.back(), Some(&1));
742 #[stable(feature = "rust1", since = "1.0.0")]
743 pub fn back(&self) -> Option
<&T
> {
744 unsafe { self.tail.as_ref().map(|node| &node.as_ref().element) }
747 /// Provides a mutable reference to the back element, or `None` if the list
750 /// This operation should compute in *O*(1) time.
755 /// use std::collections::LinkedList;
757 /// let mut dl = LinkedList::new();
758 /// assert_eq!(dl.back(), None);
761 /// assert_eq!(dl.back(), Some(&1));
763 /// match dl.back_mut() {
765 /// Some(x) => *x = 5,
767 /// assert_eq!(dl.back(), Some(&5));
770 #[stable(feature = "rust1", since = "1.0.0")]
771 pub fn back_mut(&mut self) -> Option
<&mut T
> {
772 unsafe { self.tail.as_mut().map(|node| &mut node.as_mut().element) }
775 /// Adds an element first in the list.
777 /// This operation should compute in *O*(1) time.
782 /// use std::collections::LinkedList;
784 /// let mut dl = LinkedList::new();
786 /// dl.push_front(2);
787 /// assert_eq!(dl.front().unwrap(), &2);
789 /// dl.push_front(1);
790 /// assert_eq!(dl.front().unwrap(), &1);
792 #[stable(feature = "rust1", since = "1.0.0")]
793 pub fn push_front(&mut self, elt
: T
) {
794 self.push_front_node(Box
::new(Node
::new(elt
)));
797 /// Removes the first element and returns it, or `None` if the list is
800 /// This operation should compute in *O*(1) time.
805 /// use std::collections::LinkedList;
807 /// let mut d = LinkedList::new();
808 /// assert_eq!(d.pop_front(), None);
812 /// assert_eq!(d.pop_front(), Some(3));
813 /// assert_eq!(d.pop_front(), Some(1));
814 /// assert_eq!(d.pop_front(), None);
816 #[stable(feature = "rust1", since = "1.0.0")]
817 pub fn pop_front(&mut self) -> Option
<T
> {
818 self.pop_front_node().map(Node
::into_element
)
821 /// Appends an element to the back of a list.
823 /// This operation should compute in *O*(1) time.
828 /// use std::collections::LinkedList;
830 /// let mut d = LinkedList::new();
833 /// assert_eq!(3, *d.back().unwrap());
835 #[stable(feature = "rust1", since = "1.0.0")]
836 pub fn push_back(&mut self, elt
: T
) {
837 self.push_back_node(Box
::new(Node
::new(elt
)));
840 /// Removes the last element from a list and returns it, or `None` if
843 /// This operation should compute in *O*(1) time.
848 /// use std::collections::LinkedList;
850 /// let mut d = LinkedList::new();
851 /// assert_eq!(d.pop_back(), None);
854 /// assert_eq!(d.pop_back(), Some(3));
856 #[stable(feature = "rust1", since = "1.0.0")]
857 pub fn pop_back(&mut self) -> Option
<T
> {
858 self.pop_back_node().map(Node
::into_element
)
861 /// Splits the list into two at the given index. Returns everything after the given index,
862 /// including the index.
864 /// This operation should compute in *O*(*n*) time.
868 /// Panics if `at > len`.
873 /// use std::collections::LinkedList;
875 /// let mut d = LinkedList::new();
881 /// let mut split = d.split_off(2);
883 /// assert_eq!(split.pop_front(), Some(1));
884 /// assert_eq!(split.pop_front(), None);
886 #[stable(feature = "rust1", since = "1.0.0")]
887 pub fn split_off(&mut self, at
: usize) -> LinkedList
<T
> {
888 let len
= self.len();
889 assert
!(at
<= len
, "Cannot split off at a nonexistent index");
891 return mem
::take(self);
892 } else if at
== len
{
896 // Below, we iterate towards the `i-1`th node, either from the start or the end,
897 // depending on which would be faster.
898 let split_node
= if at
- 1 <= len
- 1 - (at
- 1) {
899 let mut iter
= self.iter_mut();
900 // instead of skipping using .skip() (which creates a new struct),
901 // we skip manually so we can access the head field without
902 // depending on implementation details of Skip
908 // better off starting from the end
909 let mut iter
= self.iter_mut();
910 for _
in 0..len
- 1 - (at
- 1) {
915 unsafe { self.split_off_after_node(split_node, at) }
918 /// Removes the element at the given index and returns it.
920 /// This operation should compute in *O*(*n*) time.
923 /// Panics if at >= len
928 /// #![feature(linked_list_remove)]
929 /// use std::collections::LinkedList;
931 /// let mut d = LinkedList::new();
937 /// assert_eq!(d.remove(1), 2);
938 /// assert_eq!(d.remove(0), 3);
939 /// assert_eq!(d.remove(0), 1);
941 #[unstable(feature = "linked_list_remove", issue = "69210")]
942 pub fn remove(&mut self, at
: usize) -> T
{
943 let len
= self.len();
944 assert
!(at
< len
, "Cannot remove at an index outside of the list bounds");
946 // Below, we iterate towards the node at the given index, either from
947 // the start or the end, depending on which would be faster.
948 let offset_from_end
= len
- at
- 1;
949 if at
<= offset_from_end
{
950 let mut cursor
= self.cursor_front_mut();
954 cursor
.remove_current().unwrap()
956 let mut cursor
= self.cursor_back_mut();
957 for _
in 0..offset_from_end
{
960 cursor
.remove_current().unwrap()
964 /// Creates an iterator which uses a closure to determine if an element should be removed.
966 /// If the closure returns true, then the element is removed and yielded.
967 /// If the closure returns false, the element will remain in the list and will not be yielded
970 /// Note that `drain_filter` lets you mutate every element in the filter closure, regardless of
971 /// whether you choose to keep or remove it.
975 /// Splitting a list into evens and odds, reusing the original list:
978 /// #![feature(drain_filter)]
979 /// use std::collections::LinkedList;
981 /// let mut numbers: LinkedList<u32> = LinkedList::new();
982 /// numbers.extend(&[1, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15]);
984 /// let evens = numbers.drain_filter(|x| *x % 2 == 0).collect::<LinkedList<_>>();
985 /// let odds = numbers;
987 /// assert_eq!(evens.into_iter().collect::<Vec<_>>(), vec![2, 4, 6, 8, 14]);
988 /// assert_eq!(odds.into_iter().collect::<Vec<_>>(), vec![1, 3, 5, 9, 11, 13, 15]);
990 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
991 pub fn drain_filter
<F
>(&mut self, filter
: F
) -> DrainFilter
<'_
, T
, F
>
993 F
: FnMut(&mut T
) -> bool
,
995 // avoid borrow issues.
997 let old_len
= self.len
;
999 DrainFilter { list: self, it, pred: filter, idx: 0, old_len }
1003 #[stable(feature = "rust1", since = "1.0.0")]
1004 unsafe impl<#[may_dangle] T> Drop for LinkedList<T> {
1005 fn drop(&mut self) {
1006 struct DropGuard
<'a
, T
>(&'a
mut LinkedList
<T
>);
1008 impl<'a
, T
> Drop
for DropGuard
<'a
, T
> {
1009 fn drop(&mut self) {
1010 // Continue the same loop we do below. This only runs when a destructor has
1011 // panicked. If another one panics this will abort.
1012 while self.0.pop_front_node().is_some() {}
1016 while let Some(node
) = self.pop_front_node() {
1017 let guard
= DropGuard(self);
1024 #[stable(feature = "rust1", since = "1.0.0")]
1025 impl<'a
, T
> Iterator
for Iter
<'a
, T
> {
1029 fn next(&mut self) -> Option
<&'a T
> {
1033 self.head
.map(|node
| unsafe {
1034 // Need an unbound lifetime to get 'a
1035 let node
= &*node
.as_ptr();
1037 self.head
= node
.next
;
1044 fn size_hint(&self) -> (usize, Option
<usize>) {
1045 (self.len
, Some(self.len
))
1049 fn last(mut self) -> Option
<&'a T
> {
1054 #[stable(feature = "rust1", since = "1.0.0")]
1055 impl<'a
, T
> DoubleEndedIterator
for Iter
<'a
, T
> {
1057 fn next_back(&mut self) -> Option
<&'a T
> {
1061 self.tail
.map(|node
| unsafe {
1062 // Need an unbound lifetime to get 'a
1063 let node
= &*node
.as_ptr();
1065 self.tail
= node
.prev
;
1072 #[stable(feature = "rust1", since = "1.0.0")]
1073 impl<T
> ExactSizeIterator
for Iter
<'_
, T
> {}
1075 #[stable(feature = "fused", since = "1.26.0")]
1076 impl<T
> FusedIterator
for Iter
<'_
, T
> {}
1078 #[stable(feature = "rust1", since = "1.0.0")]
1079 impl<'a
, T
> Iterator
for IterMut
<'a
, T
> {
1080 type Item
= &'a
mut T
;
1083 fn next(&mut self) -> Option
<&'a
mut T
> {
1087 self.head
.map(|node
| unsafe {
1088 // Need an unbound lifetime to get 'a
1089 let node
= &mut *node
.as_ptr();
1091 self.head
= node
.next
;
1098 fn size_hint(&self) -> (usize, Option
<usize>) {
1099 (self.len
, Some(self.len
))
1103 fn last(mut self) -> Option
<&'a
mut T
> {
1108 #[stable(feature = "rust1", since = "1.0.0")]
1109 impl<'a
, T
> DoubleEndedIterator
for IterMut
<'a
, T
> {
1111 fn next_back(&mut self) -> Option
<&'a
mut T
> {
1115 self.tail
.map(|node
| unsafe {
1116 // Need an unbound lifetime to get 'a
1117 let node
= &mut *node
.as_ptr();
1119 self.tail
= node
.prev
;
1126 #[stable(feature = "rust1", since = "1.0.0")]
1127 impl<T
> ExactSizeIterator
for IterMut
<'_
, T
> {}
1129 #[stable(feature = "fused", since = "1.26.0")]
1130 impl<T
> FusedIterator
for IterMut
<'_
, T
> {}
1132 /// A cursor over a `LinkedList`.
1134 /// A `Cursor` is like an iterator, except that it can freely seek back-and-forth.
1136 /// Cursors always rest between two elements in the list, and index in a logically circular way.
1137 /// To accommodate this, there is a "ghost" non-element that yields `None` between the head and
1138 /// tail of the list.
1140 /// When created, cursors start at the front of the list, or the "ghost" non-element if the list is empty.
1141 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1142 pub struct Cursor
<'a
, T
: 'a
> {
1144 current
: Option
<NonNull
<Node
<T
>>>,
1145 list
: &'a LinkedList
<T
>,
1148 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1149 impl<T
> Clone
for Cursor
<'_
, T
> {
1150 fn clone(&self) -> Self {
1151 let Cursor { index, current, list }
= *self;
1152 Cursor { index, current, list }
1156 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1157 impl<T
: fmt
::Debug
> fmt
::Debug
for Cursor
<'_
, T
> {
1158 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1159 f
.debug_tuple("Cursor").field(&self.list
).field(&self.index()).finish()
1163 /// A cursor over a `LinkedList` with editing operations.
1165 /// A `Cursor` is like an iterator, except that it can freely seek back-and-forth, and can
1166 /// safely mutate the list during iteration. This is because the lifetime of its yielded
1167 /// references is tied to its own lifetime, instead of just the underlying list. This means
1168 /// cursors cannot yield multiple elements at once.
1170 /// Cursors always rest between two elements in the list, and index in a logically circular way.
1171 /// To accommodate this, there is a "ghost" non-element that yields `None` between the head and
1172 /// tail of the list.
1173 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1174 pub struct CursorMut
<'a
, T
: 'a
> {
1176 current
: Option
<NonNull
<Node
<T
>>>,
1177 list
: &'a
mut LinkedList
<T
>,
1180 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1181 impl<T
: fmt
::Debug
> fmt
::Debug
for CursorMut
<'_
, T
> {
1182 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1183 f
.debug_tuple("CursorMut").field(&self.list
).field(&self.index()).finish()
1187 impl<'a
, T
> Cursor
<'a
, T
> {
1188 /// Returns the cursor position index within the `LinkedList`.
1190 /// This returns `None` if the cursor is currently pointing to the
1191 /// "ghost" non-element.
1193 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1194 pub fn index(&self) -> Option
<usize> {
1195 let _
= self.current?
;
1199 /// Moves the cursor to the next element of the `LinkedList`.
1201 /// If the cursor is pointing to the "ghost" non-element then this will move it to
1202 /// the first element of the `LinkedList`. If it is pointing to the last
1203 /// element of the `LinkedList` then this will move it to the "ghost" non-element.
1204 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1205 pub fn move_next(&mut self) {
1206 match self.current
.take() {
1207 // We had no current element; the cursor was sitting at the start position
1208 // Next element should be the head of the list
1210 self.current
= self.list
.head
;
1213 // We had a previous element, so let's go to its next
1214 Some(current
) => unsafe {
1215 self.current
= current
.as_ref().next
;
1221 /// Moves the cursor to the previous element of the `LinkedList`.
1223 /// If the cursor is pointing to the "ghost" non-element then this will move it to
1224 /// the last element of the `LinkedList`. If it is pointing to the first
1225 /// element of the `LinkedList` then this will move it to the "ghost" non-element.
1226 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1227 pub fn move_prev(&mut self) {
1228 match self.current
.take() {
1229 // No current. We're at the start of the list. Yield None and jump to the end.
1231 self.current
= self.list
.tail
;
1232 self.index
= self.list
.len().checked_sub(1).unwrap_or(0);
1234 // Have a prev. Yield it and go to the previous element.
1235 Some(current
) => unsafe {
1236 self.current
= current
.as_ref().prev
;
1237 self.index
= self.index
.checked_sub(1).unwrap_or_else(|| self.list
.len());
1242 /// Returns a reference to the element that the cursor is currently
1245 /// This returns `None` if the cursor is currently pointing to the
1246 /// "ghost" non-element.
1248 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1249 pub fn current(&self) -> Option
<&'a T
> {
1250 unsafe { self.current.map(|current| &(*current.as_ptr()).element) }
1253 /// Returns a reference to the next element.
1255 /// If the cursor is pointing to the "ghost" non-element then this returns
1256 /// the first element of the `LinkedList`. If it is pointing to the last
1257 /// element of the `LinkedList` then this returns `None`.
1259 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1260 pub fn peek_next(&self) -> Option
<&'a T
> {
1262 let next
= match self.current
{
1263 None
=> self.list
.head
,
1264 Some(current
) => current
.as_ref().next
,
1266 next
.map(|next
| &(*next
.as_ptr()).element
)
1270 /// Returns a reference to the previous element.
1272 /// If the cursor is pointing to the "ghost" non-element then this returns
1273 /// the last element of the `LinkedList`. If it is pointing to the first
1274 /// element of the `LinkedList` then this returns `None`.
1276 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1277 pub fn peek_prev(&self) -> Option
<&'a T
> {
1279 let prev
= match self.current
{
1280 None
=> self.list
.tail
,
1281 Some(current
) => current
.as_ref().prev
,
1283 prev
.map(|prev
| &(*prev
.as_ptr()).element
)
1287 /// Provides a reference to the front element of the cursor's parent list,
1288 /// or None if the list is empty.
1290 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1291 pub fn front(&self) -> Option
<&'a T
> {
1295 /// Provides a reference to the back element of the cursor's parent list,
1296 /// or None if the list is empty.
1298 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1299 pub fn back(&self) -> Option
<&'a T
> {
1304 impl<'a
, T
> CursorMut
<'a
, T
> {
1305 /// Returns the cursor position index within the `LinkedList`.
1307 /// This returns `None` if the cursor is currently pointing to the
1308 /// "ghost" non-element.
1310 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1311 pub fn index(&self) -> Option
<usize> {
1312 let _
= self.current?
;
1316 /// Moves the cursor to the next element of the `LinkedList`.
1318 /// If the cursor is pointing to the "ghost" non-element then this will move it to
1319 /// the first element of the `LinkedList`. If it is pointing to the last
1320 /// element of the `LinkedList` then this will move it to the "ghost" non-element.
1321 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1322 pub fn move_next(&mut self) {
1323 match self.current
.take() {
1324 // We had no current element; the cursor was sitting at the start position
1325 // Next element should be the head of the list
1327 self.current
= self.list
.head
;
1330 // We had a previous element, so let's go to its next
1331 Some(current
) => unsafe {
1332 self.current
= current
.as_ref().next
;
1338 /// Moves the cursor to the previous element of the `LinkedList`.
1340 /// If the cursor is pointing to the "ghost" non-element then this will move it to
1341 /// the last element of the `LinkedList`. If it is pointing to the first
1342 /// element of the `LinkedList` then this will move it to the "ghost" non-element.
1343 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1344 pub fn move_prev(&mut self) {
1345 match self.current
.take() {
1346 // No current. We're at the start of the list. Yield None and jump to the end.
1348 self.current
= self.list
.tail
;
1349 self.index
= self.list
.len().checked_sub(1).unwrap_or(0);
1351 // Have a prev. Yield it and go to the previous element.
1352 Some(current
) => unsafe {
1353 self.current
= current
.as_ref().prev
;
1354 self.index
= self.index
.checked_sub(1).unwrap_or_else(|| self.list
.len());
1359 /// Returns a reference to the element that the cursor is currently
1362 /// This returns `None` if the cursor is currently pointing to the
1363 /// "ghost" non-element.
1365 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1366 pub fn current(&mut self) -> Option
<&mut T
> {
1367 unsafe { self.current.map(|current| &mut (*current.as_ptr()).element) }
1370 /// Returns a reference to the next element.
1372 /// If the cursor is pointing to the "ghost" non-element then this returns
1373 /// the first element of the `LinkedList`. If it is pointing to the last
1374 /// element of the `LinkedList` then this returns `None`.
1375 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1376 pub fn peek_next(&mut self) -> Option
<&mut T
> {
1378 let next
= match self.current
{
1379 None
=> self.list
.head
,
1380 Some(current
) => current
.as_ref().next
,
1382 next
.map(|next
| &mut (*next
.as_ptr()).element
)
1386 /// Returns a reference to the previous element.
1388 /// If the cursor is pointing to the "ghost" non-element then this returns
1389 /// the last element of the `LinkedList`. If it is pointing to the first
1390 /// element of the `LinkedList` then this returns `None`.
1391 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1392 pub fn peek_prev(&mut self) -> Option
<&mut T
> {
1394 let prev
= match self.current
{
1395 None
=> self.list
.tail
,
1396 Some(current
) => current
.as_ref().prev
,
1398 prev
.map(|prev
| &mut (*prev
.as_ptr()).element
)
1402 /// Returns a read-only cursor pointing to the current element.
1404 /// The lifetime of the returned `Cursor` is bound to that of the
1405 /// `CursorMut`, which means it cannot outlive the `CursorMut` and that the
1406 /// `CursorMut` is frozen for the lifetime of the `Cursor`.
1408 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1409 pub fn as_cursor(&self) -> Cursor
<'_
, T
> {
1410 Cursor { list: self.list, current: self.current, index: self.index }
1414 // Now the list editing operations
1416 impl<'a
, T
> CursorMut
<'a
, T
> {
1417 /// Inserts a new element into the `LinkedList` after the current one.
1419 /// If the cursor is pointing at the "ghost" non-element then the new element is
1420 /// inserted at the front of the `LinkedList`.
1421 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1422 pub fn insert_after(&mut self, item
: T
) {
1424 let spliced_node
= Box
::leak(Box
::new(Node
::new(item
))).into();
1425 let node_next
= match self.current
{
1426 None
=> self.list
.head
,
1427 Some(node
) => node
.as_ref().next
,
1429 self.list
.splice_nodes(self.current
, node_next
, spliced_node
, spliced_node
, 1);
1430 if self.current
.is_none() {
1431 // The "ghost" non-element's index has changed.
1432 self.index
= self.list
.len
;
1437 /// Inserts a new element into the `LinkedList` before the current one.
1439 /// If the cursor is pointing at the "ghost" non-element then the new element is
1440 /// inserted at the end of the `LinkedList`.
1441 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1442 pub fn insert_before(&mut self, item
: T
) {
1444 let spliced_node
= Box
::leak(Box
::new(Node
::new(item
))).into();
1445 let node_prev
= match self.current
{
1446 None
=> self.list
.tail
,
1447 Some(node
) => node
.as_ref().prev
,
1449 self.list
.splice_nodes(node_prev
, self.current
, spliced_node
, spliced_node
, 1);
1454 /// Removes the current element from the `LinkedList`.
1456 /// The element that was removed is returned, and the cursor is
1457 /// moved to point to the next element in the `LinkedList`.
1459 /// If the cursor is currently pointing to the "ghost" non-element then no element
1460 /// is removed and `None` is returned.
1461 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1462 pub fn remove_current(&mut self) -> Option
<T
> {
1463 let unlinked_node
= self.current?
;
1465 self.current
= unlinked_node
.as_ref().next
;
1466 self.list
.unlink_node(unlinked_node
);
1467 let unlinked_node
= Box
::from_raw(unlinked_node
.as_ptr());
1468 Some(unlinked_node
.element
)
1472 /// Removes the current element from the `LinkedList` without deallocating the list node.
1474 /// The node that was removed is returned as a new `LinkedList` containing only this node.
1475 /// The cursor is moved to point to the next element in the current `LinkedList`.
1477 /// If the cursor is currently pointing to the "ghost" non-element then no element
1478 /// is removed and `None` is returned.
1479 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1480 pub fn remove_current_as_list(&mut self) -> Option
<LinkedList
<T
>> {
1481 let mut unlinked_node
= self.current?
;
1483 self.current
= unlinked_node
.as_ref().next
;
1484 self.list
.unlink_node(unlinked_node
);
1486 unlinked_node
.as_mut().prev
= None
;
1487 unlinked_node
.as_mut().next
= None
;
1489 head
: Some(unlinked_node
),
1490 tail
: Some(unlinked_node
),
1492 marker
: PhantomData
,
1497 /// Inserts the elements from the given `LinkedList` after the current one.
1499 /// If the cursor is pointing at the "ghost" non-element then the new elements are
1500 /// inserted at the start of the `LinkedList`.
1501 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1502 pub fn splice_after(&mut self, list
: LinkedList
<T
>) {
1504 let (splice_head
, splice_tail
, splice_len
) = match list
.detach_all_nodes() {
1505 Some(parts
) => parts
,
1508 let node_next
= match self.current
{
1509 None
=> self.list
.head
,
1510 Some(node
) => node
.as_ref().next
,
1512 self.list
.splice_nodes(self.current
, node_next
, splice_head
, splice_tail
, splice_len
);
1513 if self.current
.is_none() {
1514 // The "ghost" non-element's index has changed.
1515 self.index
= self.list
.len
;
1520 /// Inserts the elements from the given `LinkedList` before the current one.
1522 /// If the cursor is pointing at the "ghost" non-element then the new elements are
1523 /// inserted at the end of the `LinkedList`.
1524 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1525 pub fn splice_before(&mut self, list
: LinkedList
<T
>) {
1527 let (splice_head
, splice_tail
, splice_len
) = match list
.detach_all_nodes() {
1528 Some(parts
) => parts
,
1531 let node_prev
= match self.current
{
1532 None
=> self.list
.tail
,
1533 Some(node
) => node
.as_ref().prev
,
1535 self.list
.splice_nodes(node_prev
, self.current
, splice_head
, splice_tail
, splice_len
);
1536 self.index
+= splice_len
;
1540 /// Splits the list into two after the current element. This will return a
1541 /// new list consisting of everything after the cursor, with the original
1542 /// list retaining everything before.
1544 /// If the cursor is pointing at the "ghost" non-element then the entire contents
1545 /// of the `LinkedList` are moved.
1546 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1547 pub fn split_after(&mut self) -> LinkedList
<T
> {
1548 let split_off_idx
= if self.index
== self.list
.len { 0 }
else { self.index + 1 }
;
1549 if self.index
== self.list
.len
{
1550 // The "ghost" non-element's index has changed to 0.
1553 unsafe { self.list.split_off_after_node(self.current, split_off_idx) }
1556 /// Splits the list into two before the current element. This will return a
1557 /// new list consisting of everything before the cursor, with the original
1558 /// list retaining everything after.
1560 /// If the cursor is pointing at the "ghost" non-element then the entire contents
1561 /// of the `LinkedList` are moved.
1562 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1563 pub fn split_before(&mut self) -> LinkedList
<T
> {
1564 let split_off_idx
= self.index
;
1566 unsafe { self.list.split_off_before_node(self.current, split_off_idx) }
1569 /// Appends an element to the front of the cursor's parent list. The node
1570 /// that the cursor points to is unchanged, even if it is the "ghost" node.
1572 /// This operation should compute in *O*(1) time.
1573 // `push_front` continues to point to "ghost" when it addes a node to mimic
1574 // the behavior of `insert_before` on an empty list.
1575 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1576 pub fn push_front(&mut self, elt
: T
) {
1577 // Safety: We know that `push_front` does not change the position in
1578 // memory of other nodes. This ensures that `self.current` remains
1580 self.list
.push_front(elt
);
1584 /// Appends an element to the back of the cursor's parent list. The node
1585 /// that the cursor points to is unchanged, even if it is the "ghost" node.
1587 /// This operation should compute in *O*(1) time.
1588 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1589 pub fn push_back(&mut self, elt
: T
) {
1590 // Safety: We know that `push_back` does not change the position in
1591 // memory of other nodes. This ensures that `self.current` remains
1593 self.list
.push_back(elt
);
1594 if self.current().is_none() {
1595 // The index of "ghost" is the length of the list, so we just need
1596 // to increment self.index to reflect the new length of the list.
1601 /// Removes the first element from the cursor's parent list and returns it,
1602 /// or None if the list is empty. The element the cursor points to remains
1603 /// unchanged, unless it was pointing to the front element. In that case, it
1604 /// points to the new front element.
1606 /// This operation should compute in *O*(1) time.
1607 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1608 pub fn pop_front(&mut self) -> Option
<T
> {
1609 // We can't check if current is empty, we must check the list directly.
1610 // It is possible for `self.current == None` and the list to be
1612 if self.list
.is_empty() {
1615 // We can't point to the node that we pop. Copying the behavior of
1616 // `remove_current`, we move on the the next node in the sequence.
1617 // If the list is of length 1 then we end pointing to the "ghost"
1618 // node at index 0, which is expected.
1619 if self.list
.head
== self.current
{
1624 self.list
.pop_front()
1628 /// Removes the last element from the cursor's parent list and returns it,
1629 /// or None if the list is empty. The element the cursor points to remains
1630 /// unchanged, unless it was pointing to the back element. In that case, it
1631 /// points to the "ghost" element.
1633 /// This operation should compute in *O*(1) time.
1634 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1635 pub fn pop_back(&mut self) -> Option
<T
> {
1636 if self.list
.is_empty() {
1639 if self.list
.tail
== self.current
{
1640 // The index now reflects the length of the list. It was the
1641 // length of the list minus 1, but now the list is 1 smaller. No
1642 // change is needed for `index`.
1643 self.current
= None
;
1644 } else if self.current
.is_none() {
1645 self.index
= self.list
.len
- 1;
1647 self.list
.pop_back()
1651 /// Provides a reference to the front element of the cursor's parent list,
1652 /// or None if the list is empty.
1654 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1655 pub fn front(&self) -> Option
<&T
> {
1659 /// Provides a mutable reference to the front element of the cursor's
1660 /// parent list, or None if the list is empty.
1662 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1663 pub fn front_mut(&mut self) -> Option
<&mut T
> {
1664 self.list
.front_mut()
1667 /// Provides a reference to the back element of the cursor's parent list,
1668 /// or None if the list is empty.
1670 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1671 pub fn back(&self) -> Option
<&T
> {
1675 /// Provides a mutable reference to back element of the cursor's parent
1676 /// list, or `None` if the list is empty.
1679 /// Building and mutating a list with a cursor, then getting the back element:
1681 /// #![feature(linked_list_cursors)]
1682 /// use std::collections::LinkedList;
1683 /// let mut dl = LinkedList::new();
1684 /// dl.push_front(3);
1685 /// dl.push_front(2);
1686 /// dl.push_front(1);
1687 /// let mut cursor = dl.cursor_front_mut();
1688 /// *cursor.current().unwrap() = 99;
1689 /// *cursor.back_mut().unwrap() = 0;
1690 /// let mut contents = dl.into_iter();
1691 /// assert_eq!(contents.next(), Some(99));
1692 /// assert_eq!(contents.next(), Some(2));
1693 /// assert_eq!(contents.next(), Some(0));
1694 /// assert_eq!(contents.next(), None);
1697 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1698 pub fn back_mut(&mut self) -> Option
<&mut T
> {
1699 self.list
.back_mut()
1703 /// An iterator produced by calling `drain_filter` on LinkedList.
1704 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
1705 pub struct DrainFilter
<'a
, T
: 'a
, F
: 'a
>
1707 F
: FnMut(&mut T
) -> bool
,
1709 list
: &'a
mut LinkedList
<T
>,
1710 it
: Option
<NonNull
<Node
<T
>>>,
1716 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
1717 impl<T
, F
> Iterator
for DrainFilter
<'_
, T
, F
>
1719 F
: FnMut(&mut T
) -> bool
,
1723 fn next(&mut self) -> Option
<T
> {
1724 while let Some(mut node
) = self.it
{
1726 self.it
= node
.as_ref().next
;
1729 if (self.pred
)(&mut node
.as_mut().element
) {
1730 // `unlink_node` is okay with aliasing `element` references.
1731 self.list
.unlink_node(node
);
1732 return Some(Box
::from_raw(node
.as_ptr()).element
);
1740 fn size_hint(&self) -> (usize, Option
<usize>) {
1741 (0, Some(self.old_len
- self.idx
))
1745 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
1746 impl<T
, F
> Drop
for DrainFilter
<'_
, T
, F
>
1748 F
: FnMut(&mut T
) -> bool
,
1750 fn drop(&mut self) {
1751 struct DropGuard
<'r
, 'a
, T
, F
>(&'r
mut DrainFilter
<'a
, T
, F
>)
1753 F
: FnMut(&mut T
) -> bool
;
1755 impl<'r
, 'a
, T
, F
> Drop
for DropGuard
<'r
, 'a
, T
, F
>
1757 F
: FnMut(&mut T
) -> bool
,
1759 fn drop(&mut self) {
1760 self.0.for_each
(drop
);
1764 while let Some(item
) = self.next() {
1765 let guard
= DropGuard(self);
1772 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
1773 impl<T
: fmt
::Debug
, F
> fmt
::Debug
for DrainFilter
<'_
, T
, F
>
1775 F
: FnMut(&mut T
) -> bool
,
1777 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1778 f
.debug_tuple("DrainFilter").field(&self.list
).finish()
1782 #[stable(feature = "rust1", since = "1.0.0")]
1783 impl<T
> Iterator
for IntoIter
<T
> {
1787 fn next(&mut self) -> Option
<T
> {
1788 self.list
.pop_front()
1792 fn size_hint(&self) -> (usize, Option
<usize>) {
1793 (self.list
.len
, Some(self.list
.len
))
1797 #[stable(feature = "rust1", since = "1.0.0")]
1798 impl<T
> DoubleEndedIterator
for IntoIter
<T
> {
1800 fn next_back(&mut self) -> Option
<T
> {
1801 self.list
.pop_back()
1805 #[stable(feature = "rust1", since = "1.0.0")]
1806 impl<T
> ExactSizeIterator
for IntoIter
<T
> {}
1808 #[stable(feature = "fused", since = "1.26.0")]
1809 impl<T
> FusedIterator
for IntoIter
<T
> {}
1811 #[stable(feature = "rust1", since = "1.0.0")]
1812 impl<T
> FromIterator
<T
> for LinkedList
<T
> {
1813 fn from_iter
<I
: IntoIterator
<Item
= T
>>(iter
: I
) -> Self {
1814 let mut list
= Self::new();
1820 #[stable(feature = "rust1", since = "1.0.0")]
1821 impl<T
> IntoIterator
for LinkedList
<T
> {
1823 type IntoIter
= IntoIter
<T
>;
1825 /// Consumes the list into an iterator yielding elements by value.
1827 fn into_iter(self) -> IntoIter
<T
> {
1828 IntoIter { list: self }
1832 #[stable(feature = "rust1", since = "1.0.0")]
1833 impl<'a
, T
> IntoIterator
for &'a LinkedList
<T
> {
1835 type IntoIter
= Iter
<'a
, T
>;
1837 fn into_iter(self) -> Iter
<'a
, T
> {
1842 #[stable(feature = "rust1", since = "1.0.0")]
1843 impl<'a
, T
> IntoIterator
for &'a
mut LinkedList
<T
> {
1844 type Item
= &'a
mut T
;
1845 type IntoIter
= IterMut
<'a
, T
>;
1847 fn into_iter(self) -> IterMut
<'a
, T
> {
1852 #[stable(feature = "rust1", since = "1.0.0")]
1853 impl<T
> Extend
<T
> for LinkedList
<T
> {
1854 fn extend
<I
: IntoIterator
<Item
= T
>>(&mut self, iter
: I
) {
1855 <Self as SpecExtend
<I
>>::spec_extend(self, iter
);
1859 fn extend_one(&mut self, elem
: T
) {
1860 self.push_back(elem
);
1864 impl<I
: IntoIterator
> SpecExtend
<I
> for LinkedList
<I
::Item
> {
1865 default fn spec_extend(&mut self, iter
: I
) {
1866 iter
.into_iter().for_each(move |elt
| self.push_back(elt
));
1870 impl<T
> SpecExtend
<LinkedList
<T
>> for LinkedList
<T
> {
1871 fn spec_extend(&mut self, ref mut other
: LinkedList
<T
>) {
1876 #[stable(feature = "extend_ref", since = "1.2.0")]
1877 impl<'a
, T
: 'a
+ Copy
> Extend
<&'a T
> for LinkedList
<T
> {
1878 fn extend
<I
: IntoIterator
<Item
= &'a T
>>(&mut self, iter
: I
) {
1879 self.extend(iter
.into_iter().cloned());
1883 fn extend_one(&mut self, &elem
: &'a T
) {
1884 self.push_back(elem
);
1888 #[stable(feature = "rust1", since = "1.0.0")]
1889 impl<T
: PartialEq
> PartialEq
for LinkedList
<T
> {
1890 fn eq(&self, other
: &Self) -> bool
{
1891 self.len() == other
.len() && self.iter().eq(other
)
1894 fn ne(&self, other
: &Self) -> bool
{
1895 self.len() != other
.len() || self.iter().ne(other
)
1899 #[stable(feature = "rust1", since = "1.0.0")]
1900 impl<T
: Eq
> Eq
for LinkedList
<T
> {}
1902 #[stable(feature = "rust1", since = "1.0.0")]
1903 impl<T
: PartialOrd
> PartialOrd
for LinkedList
<T
> {
1904 fn partial_cmp(&self, other
: &Self) -> Option
<Ordering
> {
1905 self.iter().partial_cmp(other
)
1909 #[stable(feature = "rust1", since = "1.0.0")]
1910 impl<T
: Ord
> Ord
for LinkedList
<T
> {
1912 fn cmp(&self, other
: &Self) -> Ordering
{
1913 self.iter().cmp(other
)
1917 #[stable(feature = "rust1", since = "1.0.0")]
1918 impl<T
: Clone
> Clone
for LinkedList
<T
> {
1919 fn clone(&self) -> Self {
1920 self.iter().cloned().collect()
1923 fn clone_from(&mut self, other
: &Self) {
1924 let mut iter_other
= other
.iter();
1925 if self.len() > other
.len() {
1926 self.split_off(other
.len());
1928 for (elem
, elem_other
) in self.iter_mut().zip(&mut iter_other
) {
1929 elem
.clone_from(elem_other
);
1931 if !iter_other
.is_empty() {
1932 self.extend(iter_other
.cloned());
1937 #[stable(feature = "rust1", since = "1.0.0")]
1938 impl<T
: fmt
::Debug
> fmt
::Debug
for LinkedList
<T
> {
1939 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
1940 f
.debug_list().entries(self).finish()
1944 #[stable(feature = "rust1", since = "1.0.0")]
1945 impl<T
: Hash
> Hash
for LinkedList
<T
> {
1946 fn hash
<H
: Hasher
>(&self, state
: &mut H
) {
1947 state
.write_length_prefix(self.len());
1954 #[stable(feature = "std_collections_from_array", since = "1.56.0")]
1955 impl<T
, const N
: usize> From
<[T
; N
]> for LinkedList
<T
> {
1956 /// Converts a `[T; N]` into a `LinkedList<T>`.
1959 /// use std::collections::LinkedList;
1961 /// let list1 = LinkedList::from([1, 2, 3, 4]);
1962 /// let list2: LinkedList<_> = [1, 2, 3, 4].into();
1963 /// assert_eq!(list1, list2);
1965 fn from(arr
: [T
; N
]) -> Self {
1966 Self::from_iter(arr
)
1970 // Ensure that `LinkedList` and its read-only iterators are covariant in their type parameters.
1972 fn assert_covariance() {
1973 fn a
<'a
>(x
: LinkedList
<&'
static str>) -> LinkedList
<&'a
str> {
1976 fn b
<'i
, 'a
>(x
: Iter
<'i
, &'
static str>) -> Iter
<'i
, &'a
str> {
1979 fn c
<'a
>(x
: IntoIter
<&'
static str>) -> IntoIter
<&'a
str> {
1984 #[stable(feature = "rust1", since = "1.0.0")]
1985 unsafe impl<T
: Send
> Send
for LinkedList
<T
> {}
1987 #[stable(feature = "rust1", since = "1.0.0")]
1988 unsafe impl<T
: Sync
> Sync
for LinkedList
<T
> {}
1990 #[stable(feature = "rust1", since = "1.0.0")]
1991 unsafe impl<T
: Sync
> Send
for Iter
<'_
, T
> {}
1993 #[stable(feature = "rust1", since = "1.0.0")]
1994 unsafe impl<T
: Sync
> Sync
for Iter
<'_
, T
> {}
1996 #[stable(feature = "rust1", since = "1.0.0")]
1997 unsafe impl<T
: Send
> Send
for IterMut
<'_
, T
> {}
1999 #[stable(feature = "rust1", since = "1.0.0")]
2000 unsafe impl<T
: Sync
> Sync
for IterMut
<'_
, T
> {}
2002 #[unstable(feature = "linked_list_cursors", issue = "58533")]
2003 unsafe impl<T
: Sync
> Send
for Cursor
<'_
, T
> {}
2005 #[unstable(feature = "linked_list_cursors", issue = "58533")]
2006 unsafe impl<T
: Sync
> Sync
for Cursor
<'_
, T
> {}
2008 #[unstable(feature = "linked_list_cursors", issue = "58533")]
2009 unsafe impl<T
: Send
> Send
for CursorMut
<'_
, T
> {}
2011 #[unstable(feature = "linked_list_cursors", issue = "58533")]
2012 unsafe impl<T
: Sync
> Sync
for CursorMut
<'_
, T
> {}