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