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