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;
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 None
1205 } else {
1206 self.head.map(|node| unsafe {
1207 // Need an unbound lifetime to get 'a
1208 let node = &*node.as_ptr();
1209 self.len -= 1;
1210 self.head = node.next;
1211 &node.element
1212 })
1213 }
1214 }
1215
1216 #[inline]
1217 fn size_hint(&self) -> (usize, Option<usize>) {
1218 (self.len, Some(self.len))
1219 }
1220
1221 #[inline]
1222 fn last(mut self) -> Option<&'a T> {
1223 self.next_back()
1224 }
1225}
1226
1227#[stable(feature = "rust1", since = "1.0.0")]
1228impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
1229 #[inline]
1230 fn next_back(&mut self) -> Option<&'a T> {
1231 if self.len == 0 {
1232 None
1233 } else {
1234 self.tail.map(|node| unsafe {
1235 // Need an unbound lifetime to get 'a
1236 let node = &*node.as_ptr();
1237 self.len -= 1;
1238 self.tail = node.prev;
1239 &node.element
1240 })
1241 }
1242 }
1243}
1244
1245#[stable(feature = "rust1", since = "1.0.0")]
1246impl<T> ExactSizeIterator for Iter<'_, T> {}
1247
1248#[stable(feature = "fused", since = "1.26.0")]
1249impl<T> FusedIterator for Iter<'_, T> {}
1250
1251#[stable(feature = "default_iters", since = "1.70.0")]
1252impl<T> Default for Iter<'_, T> {
1253 /// Creates an empty `linked_list::Iter`.
1254 ///
1255 /// ```
1256 /// # use std::collections::linked_list;
1257 /// let iter: linked_list::Iter<'_, u8> = Default::default();
1258 /// assert_eq!(iter.len(), 0);
1259 /// ```
1260 fn default() -> Self {
1261 Iter { head: None, tail: None, len: 0, marker: Default::default() }
1262 }
1263}
1264
1265#[stable(feature = "rust1", since = "1.0.0")]
1266impl<'a, T> Iterator for IterMut<'a, T> {
1267 type Item = &'a mut T;
1268
1269 #[inline]
1270 fn next(&mut self) -> Option<&'a mut T> {
1271 if self.len == 0 {
1272 None
1273 } else {
1274 self.head.map(|node| unsafe {
1275 // Need an unbound lifetime to get 'a
1276 let node = &mut *node.as_ptr();
1277 self.len -= 1;
1278 self.head = node.next;
1279 &mut node.element
1280 })
1281 }
1282 }
1283
1284 #[inline]
1285 fn size_hint(&self) -> (usize, Option<usize>) {
1286 (self.len, Some(self.len))
1287 }
1288
1289 #[inline]
1290 fn last(mut self) -> Option<&'a mut T> {
1291 self.next_back()
1292 }
1293}
1294
1295#[stable(feature = "rust1", since = "1.0.0")]
1296impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
1297 #[inline]
1298 fn next_back(&mut self) -> Option<&'a mut T> {
1299 if self.len == 0 {
1300 None
1301 } else {
1302 self.tail.map(|node| unsafe {
1303 // Need an unbound lifetime to get 'a
1304 let node = &mut *node.as_ptr();
1305 self.len -= 1;
1306 self.tail = node.prev;
1307 &mut node.element
1308 })
1309 }
1310 }
1311}
1312
1313#[stable(feature = "rust1", since = "1.0.0")]
1314impl<T> ExactSizeIterator for IterMut<'_, T> {}
1315
1316#[stable(feature = "fused", since = "1.26.0")]
1317impl<T> FusedIterator for IterMut<'_, T> {}
1318
1319#[stable(feature = "default_iters", since = "1.70.0")]
1320impl<T> Default for IterMut<'_, T> {
1321 fn default() -> Self {
1322 IterMut { head: None, tail: None, len: 0, marker: Default::default() }
1323 }
1324}
1325
1326/// A cursor over a `LinkedList`.
1327///
1328/// A `Cursor` is like an iterator, except that it can freely seek back-and-forth.
1329///
1330/// Cursors always rest between two elements in the list, and index in a logically circular way.
1331/// To accommodate this, there is a "ghost" non-element that yields `None` between the head and
1332/// tail of the list.
1333///
1334/// When created, cursors start at the front of the list, or the "ghost" non-element if the list is empty.
1335#[unstable(feature = "linked_list_cursors", issue = "58533")]
1336pub struct Cursor<
1337 'a,
1338 T: 'a,
1339 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
1340> {
1341 index: usize,
1342 current: Option<NonNull<Node<T>>>,
1343 list: &'a LinkedList<T, A>,
1344}
1345
1346#[unstable(feature = "linked_list_cursors", issue = "58533")]
1347impl<T, A: Allocator> Clone for Cursor<'_, T, A> {
1348 fn clone(&self) -> Self {
1349 let Cursor { index, current, list } = *self;
1350 Cursor { index, current, list }
1351 }
1352}
1353
1354#[unstable(feature = "linked_list_cursors", issue = "58533")]
1355impl<T: fmt::Debug, A: Allocator> fmt::Debug for Cursor<'_, T, A> {
1356 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1357 f.debug_tuple("Cursor").field(&self.list).field(&self.index()).finish()
1358 }
1359}
1360
1361/// A cursor over a `LinkedList` with editing operations.
1362///
1363/// A `Cursor` is like an iterator, except that it can freely seek back-and-forth, and can
1364/// safely mutate the list during iteration. This is because the lifetime of its yielded
1365/// references is tied to its own lifetime, instead of just the underlying list. This means
1366/// cursors cannot yield multiple elements at once.
1367///
1368/// Cursors always rest between two elements in the list, and index in a logically circular way.
1369/// To accommodate this, there is a "ghost" non-element that yields `None` between the head and
1370/// tail of the list.
1371#[unstable(feature = "linked_list_cursors", issue = "58533")]
1372pub struct CursorMut<
1373 'a,
1374 T: 'a,
1375 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
1376> {
1377 index: usize,
1378 current: Option<NonNull<Node<T>>>,
1379 list: &'a mut LinkedList<T, A>,
1380}
1381
1382#[unstable(feature = "linked_list_cursors", issue = "58533")]
1383impl<T: fmt::Debug, A: Allocator> fmt::Debug for CursorMut<'_, T, A> {
1384 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1385 f.debug_tuple("CursorMut").field(&self.list).field(&self.index()).finish()
1386 }
1387}
1388
1389impl<'a, T, A: Allocator> Cursor<'a, T, A> {
1390 /// Returns the cursor position index within the `LinkedList`.
1391 ///
1392 /// This returns `None` if the cursor is currently pointing to the
1393 /// "ghost" non-element.
1394 #[must_use]
1395 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1396 pub fn index(&self) -> Option<usize> {
1397 let _ = self.current?;
1398 Some(self.index)
1399 }
1400
1401 /// Moves the cursor to the next element of the `LinkedList`.
1402 ///
1403 /// If the cursor is pointing to the "ghost" non-element then this will move it to
1404 /// the first element of the `LinkedList`. If it is pointing to the last
1405 /// element of the `LinkedList` then this will move it to the "ghost" non-element.
1406 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1407 pub fn move_next(&mut self) {
1408 match self.current.take() {
1409 // We had no current element; the cursor was sitting at the start position
1410 // Next element should be the head of the list
1411 None => {
1412 self.current = self.list.head;
1413 self.index = 0;
1414 }
1415 // We had a previous element, so let's go to its next
1416 Some(current) => unsafe {
1417 self.current = current.as_ref().next;
1418 self.index += 1;
1419 },
1420 }
1421 }
1422
1423 /// Moves the cursor to the previous element of the `LinkedList`.
1424 ///
1425 /// If the cursor is pointing to the "ghost" non-element then this will move it to
1426 /// the last element of the `LinkedList`. If it is pointing to the first
1427 /// element of the `LinkedList` then this will move it to the "ghost" non-element.
1428 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1429 pub fn move_prev(&mut self) {
1430 match self.current.take() {
1431 // No current. We're at the start of the list. Yield None and jump to the end.
1432 None => {
1433 self.current = self.list.tail;
1434 self.index = self.list.len().saturating_sub(1);
1435 }
1436 // Have a prev. Yield it and go to the previous element.
1437 Some(current) => unsafe {
1438 self.current = current.as_ref().prev;
1439 self.index = self.index.checked_sub(1).unwrap_or_else(|| self.list.len());
1440 },
1441 }
1442 }
1443
1444 /// Returns a reference to the element that the cursor is currently
1445 /// pointing to.
1446 ///
1447 /// This returns `None` if the cursor is currently pointing to the
1448 /// "ghost" non-element.
1449 #[must_use]
1450 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1451 pub fn current(&self) -> Option<&'a T> {
1452 unsafe { self.current.map(|current| &(*current.as_ptr()).element) }
1453 }
1454
1455 /// Returns a reference to the next element.
1456 ///
1457 /// If the cursor is pointing to the "ghost" non-element then this returns
1458 /// the first element of the `LinkedList`. If it is pointing to the last
1459 /// element of the `LinkedList` then this returns `None`.
1460 #[must_use]
1461 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1462 pub fn peek_next(&self) -> Option<&'a T> {
1463 unsafe {
1464 let next = match self.current {
1465 None => self.list.head,
1466 Some(current) => current.as_ref().next,
1467 };
1468 next.map(|next| &(*next.as_ptr()).element)
1469 }
1470 }
1471
1472 /// Returns a reference to the previous element.
1473 ///
1474 /// If the cursor is pointing to the "ghost" non-element then this returns
1475 /// the last element of the `LinkedList`. If it is pointing to the first
1476 /// element of the `LinkedList` then this returns `None`.
1477 #[must_use]
1478 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1479 pub fn peek_prev(&self) -> Option<&'a T> {
1480 unsafe {
1481 let prev = match self.current {
1482 None => self.list.tail,
1483 Some(current) => current.as_ref().prev,
1484 };
1485 prev.map(|prev| &(*prev.as_ptr()).element)
1486 }
1487 }
1488
1489 /// Provides a reference to the front element of the cursor's parent list,
1490 /// or None if the list is empty.
1491 #[must_use]
1492 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1493 #[rustc_confusables("first")]
1494 pub fn front(&self) -> Option<&'a T> {
1495 self.list.front()
1496 }
1497
1498 /// Provides a reference to the back element of the cursor's parent list,
1499 /// or None if the list is empty.
1500 #[must_use]
1501 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1502 #[rustc_confusables("last")]
1503 pub fn back(&self) -> Option<&'a T> {
1504 self.list.back()
1505 }
1506
1507 /// Provides a reference to the cursor's parent list.
1508 #[must_use]
1509 #[inline(always)]
1510 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1511 pub fn as_list(&self) -> &'a LinkedList<T, A> {
1512 self.list
1513 }
1514}
1515
1516impl<'a, T, A: Allocator> CursorMut<'a, T, A> {
1517 /// Returns the cursor position index within the `LinkedList`.
1518 ///
1519 /// This returns `None` if the cursor is currently pointing to the
1520 /// "ghost" non-element.
1521 #[must_use]
1522 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1523 pub fn index(&self) -> Option<usize> {
1524 let _ = self.current?;
1525 Some(self.index)
1526 }
1527
1528 /// Moves the cursor to the next element of the `LinkedList`.
1529 ///
1530 /// If the cursor is pointing to the "ghost" non-element then this will move it to
1531 /// the first element of the `LinkedList`. If it is pointing to the last
1532 /// element of the `LinkedList` then this will move it to the "ghost" non-element.
1533 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1534 pub fn move_next(&mut self) {
1535 match self.current.take() {
1536 // We had no current element; the cursor was sitting at the start position
1537 // Next element should be the head of the list
1538 None => {
1539 self.current = self.list.head;
1540 self.index = 0;
1541 }
1542 // We had a previous element, so let's go to its next
1543 Some(current) => unsafe {
1544 self.current = current.as_ref().next;
1545 self.index += 1;
1546 },
1547 }
1548 }
1549
1550 /// Moves the cursor to the previous element of the `LinkedList`.
1551 ///
1552 /// If the cursor is pointing to the "ghost" non-element then this will move it to
1553 /// the last element of the `LinkedList`. If it is pointing to the first
1554 /// element of the `LinkedList` then this will move it to the "ghost" non-element.
1555 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1556 pub fn move_prev(&mut self) {
1557 match self.current.take() {
1558 // No current. We're at the start of the list. Yield None and jump to the end.
1559 None => {
1560 self.current = self.list.tail;
1561 self.index = self.list.len().saturating_sub(1);
1562 }
1563 // Have a prev. Yield it and go to the previous element.
1564 Some(current) => unsafe {
1565 self.current = current.as_ref().prev;
1566 self.index = self.index.checked_sub(1).unwrap_or_else(|| self.list.len());
1567 },
1568 }
1569 }
1570
1571 /// Returns a reference to the element that the cursor is currently
1572 /// pointing to.
1573 ///
1574 /// This returns `None` if the cursor is currently pointing to the
1575 /// "ghost" non-element.
1576 #[must_use]
1577 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1578 pub fn current(&mut self) -> Option<&mut T> {
1579 unsafe { self.current.map(|current| &mut (*current.as_ptr()).element) }
1580 }
1581
1582 /// Returns a reference to the next element.
1583 ///
1584 /// If the cursor is pointing to the "ghost" non-element then this returns
1585 /// the first element of the `LinkedList`. If it is pointing to the last
1586 /// element of the `LinkedList` then this returns `None`.
1587 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1588 pub fn peek_next(&mut self) -> Option<&mut T> {
1589 unsafe {
1590 let next = match self.current {
1591 None => self.list.head,
1592 Some(current) => current.as_ref().next,
1593 };
1594 next.map(|next| &mut (*next.as_ptr()).element)
1595 }
1596 }
1597
1598 /// Returns a reference to the previous element.
1599 ///
1600 /// If the cursor is pointing to the "ghost" non-element then this returns
1601 /// the last element of the `LinkedList`. If it is pointing to the first
1602 /// element of the `LinkedList` then this returns `None`.
1603 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1604 pub fn peek_prev(&mut self) -> Option<&mut T> {
1605 unsafe {
1606 let prev = match self.current {
1607 None => self.list.tail,
1608 Some(current) => current.as_ref().prev,
1609 };
1610 prev.map(|prev| &mut (*prev.as_ptr()).element)
1611 }
1612 }
1613
1614 /// Returns a read-only cursor pointing to the current element.
1615 ///
1616 /// The lifetime of the returned `Cursor` is bound to that of the
1617 /// `CursorMut`, which means it cannot outlive the `CursorMut` and that the
1618 /// `CursorMut` is frozen for the lifetime of the `Cursor`.
1619 #[must_use]
1620 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1621 pub fn as_cursor(&self) -> Cursor<'_, T, A> {
1622 Cursor { list: self.list, current: self.current, index: self.index }
1623 }
1624
1625 /// Provides a read-only reference to the cursor's parent list.
1626 ///
1627 /// The lifetime of the returned reference is bound to that of the
1628 /// `CursorMut`, which means it cannot outlive the `CursorMut` and that the
1629 /// `CursorMut` is frozen for the lifetime of the reference.
1630 #[must_use]
1631 #[inline(always)]
1632 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1633 pub fn as_list(&self) -> &LinkedList<T, A> {
1634 self.list
1635 }
1636}
1637
1638// Now the list editing operations
1639
1640impl<'a, T> CursorMut<'a, T> {
1641 /// Inserts the elements from the given `LinkedList` after the current one.
1642 ///
1643 /// If the cursor is pointing at the "ghost" non-element then the new elements are
1644 /// inserted at the start of the `LinkedList`.
1645 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1646 pub fn splice_after(&mut self, list: LinkedList<T>) {
1647 unsafe {
1648 let Some((splice_head, splice_tail, splice_len)) = list.detach_all_nodes() else {
1649 return;
1650 };
1651 let node_next = match self.current {
1652 None => self.list.head,
1653 Some(node) => node.as_ref().next,
1654 };
1655 self.list.splice_nodes(self.current, node_next, splice_head, splice_tail, splice_len);
1656 if self.current.is_none() {
1657 // The "ghost" non-element's index has changed.
1658 self.index = self.list.len;
1659 }
1660 }
1661 }
1662
1663 /// Inserts the elements from the given `LinkedList` before the current one.
1664 ///
1665 /// If the cursor is pointing at the "ghost" non-element then the new elements are
1666 /// inserted at the end of the `LinkedList`.
1667 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1668 pub fn splice_before(&mut self, list: LinkedList<T>) {
1669 unsafe {
1670 let (splice_head, splice_tail, splice_len) = match list.detach_all_nodes() {
1671 Some(parts) => parts,
1672 _ => return,
1673 };
1674 let node_prev = match self.current {
1675 None => self.list.tail,
1676 Some(node) => node.as_ref().prev,
1677 };
1678 self.list.splice_nodes(node_prev, self.current, splice_head, splice_tail, splice_len);
1679 self.index += splice_len;
1680 }
1681 }
1682}
1683
1684impl<'a, T, A: Allocator> CursorMut<'a, T, A> {
1685 /// Inserts a new element into the `LinkedList` after the current one.
1686 ///
1687 /// If the cursor is pointing at the "ghost" non-element then the new element is
1688 /// inserted at the front of the `LinkedList`.
1689 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1690 pub fn insert_after(&mut self, item: T) {
1691 unsafe {
1692 let spliced_node =
1693 Box::into_non_null_with_allocator(Box::new_in(Node::new(item), &self.list.alloc)).0;
1694 let node_next = match self.current {
1695 None => self.list.head,
1696 Some(node) => node.as_ref().next,
1697 };
1698 self.list.splice_nodes(self.current, node_next, spliced_node, spliced_node, 1);
1699 if self.current.is_none() {
1700 // The "ghost" non-element's index has changed.
1701 self.index = self.list.len;
1702 }
1703 }
1704 }
1705
1706 /// Inserts a new element into the `LinkedList` before the current one.
1707 ///
1708 /// If the cursor is pointing at the "ghost" non-element then the new element is
1709 /// inserted at the end of the `LinkedList`.
1710 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1711 pub fn insert_before(&mut self, item: T) {
1712 unsafe {
1713 let spliced_node =
1714 Box::into_non_null_with_allocator(Box::new_in(Node::new(item), &self.list.alloc)).0;
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, spliced_node, spliced_node, 1);
1720 self.index += 1;
1721 }
1722 }
1723
1724 /// Removes the current element from the `LinkedList`.
1725 ///
1726 /// The element that was removed is returned, and the cursor is
1727 /// moved to point to the next element in the `LinkedList`.
1728 ///
1729 /// If the cursor is currently pointing to the "ghost" non-element then no element
1730 /// is removed and `None` is returned.
1731 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1732 pub fn remove_current(&mut self) -> Option<T> {
1733 let unlinked_node = self.current?;
1734 unsafe {
1735 self.current = unlinked_node.as_ref().next;
1736 self.list.unlink_node(unlinked_node);
1737 let unlinked_node = Box::from_raw_in(unlinked_node.as_ptr(), &self.list.alloc);
1738 Some(unlinked_node.element)
1739 }
1740 }
1741
1742 /// Removes the current element from the `LinkedList` without deallocating the list node.
1743 ///
1744 /// The node that was removed is returned as a new `LinkedList` containing only this node.
1745 /// The cursor is moved to point to the next element in the current `LinkedList`.
1746 ///
1747 /// If the cursor is currently pointing to the "ghost" non-element then no element
1748 /// is removed and `None` is returned.
1749 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1750 pub fn remove_current_as_list(&mut self) -> Option<LinkedList<T, A>>
1751 where
1752 A: AllocatorClone,
1753 {
1754 let mut unlinked_node = self.current?;
1755 unsafe {
1756 self.current = unlinked_node.as_ref().next;
1757 self.list.unlink_node(unlinked_node);
1758
1759 unlinked_node.as_mut().prev = None;
1760 unlinked_node.as_mut().next = None;
1761 Some(LinkedList {
1762 head: Some(unlinked_node),
1763 tail: Some(unlinked_node),
1764 len: 1,
1765 alloc: self.list.alloc.clone(),
1766 marker: PhantomData,
1767 })
1768 }
1769 }
1770
1771 /// Splits the list into two after the current element. This will return a
1772 /// new list consisting of everything after the cursor, with the original
1773 /// list retaining everything before.
1774 ///
1775 /// If the cursor is pointing at the "ghost" non-element then the entire contents
1776 /// of the `LinkedList` are moved.
1777 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1778 pub fn split_after(&mut self) -> LinkedList<T, A>
1779 where
1780 A: AllocatorClone,
1781 {
1782 let split_off_idx = if self.index == self.list.len { 0 } else { self.index + 1 };
1783 if self.index == self.list.len {
1784 // The "ghost" non-element's index has changed to 0.
1785 self.index = 0;
1786 }
1787 unsafe { self.list.split_off_after_node(self.current, split_off_idx) }
1788 }
1789
1790 /// Splits the list into two before the current element. This will return a
1791 /// new list consisting of everything before the cursor, with the original
1792 /// list retaining everything after.
1793 ///
1794 /// If the cursor is pointing at the "ghost" non-element then the entire contents
1795 /// of the `LinkedList` are moved.
1796 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1797 pub fn split_before(&mut self) -> LinkedList<T, A>
1798 where
1799 A: AllocatorClone,
1800 {
1801 let split_off_idx = self.index;
1802 self.index = 0;
1803 unsafe { self.list.split_off_before_node(self.current, split_off_idx) }
1804 }
1805
1806 /// Appends an element to the front of the cursor's parent list. The node
1807 /// that the cursor points to is unchanged, even if it is the "ghost" node.
1808 ///
1809 /// This operation should compute in *O*(1) time.
1810 // `push_front` continues to point to "ghost" when it adds a node to mimic
1811 // the behavior of `insert_before` on an empty list.
1812 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1813 pub fn push_front(&mut self, elt: T) {
1814 // Safety: We know that `push_front` does not change the position in
1815 // memory of other nodes. This ensures that `self.current` remains
1816 // valid.
1817 self.list.push_front(elt);
1818 self.index += 1;
1819 }
1820
1821 /// Appends an element to the back of the cursor's parent list. The node
1822 /// that the cursor points to is unchanged, even if it is the "ghost" node.
1823 ///
1824 /// This operation should compute in *O*(1) time.
1825 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1826 #[rustc_confusables("push", "append")]
1827 pub fn push_back(&mut self, elt: T) {
1828 // Safety: We know that `push_back` does not change the position in
1829 // memory of other nodes. This ensures that `self.current` remains
1830 // valid.
1831 self.list.push_back(elt);
1832 if self.current().is_none() {
1833 // The index of "ghost" is the length of the list, so we just need
1834 // to increment self.index to reflect the new length of the list.
1835 self.index += 1;
1836 }
1837 }
1838
1839 /// Removes the first element from the cursor's parent list and returns it,
1840 /// or None if the list is empty. The element the cursor points to remains
1841 /// unchanged, unless it was pointing to the front element. In that case, it
1842 /// points to the new front element.
1843 ///
1844 /// This operation should compute in *O*(1) time.
1845 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1846 pub fn pop_front(&mut self) -> Option<T> {
1847 // We can't check if current is empty, we must check the list directly.
1848 // It is possible for `self.current == None` and the list to be
1849 // non-empty.
1850 if self.list.is_empty() {
1851 None
1852 } else {
1853 // We can't point to the node that we pop. Copying the behavior of
1854 // `remove_current`, we move on to the next node in the sequence.
1855 // If the list is of length 1 then we end pointing to the "ghost"
1856 // node at index 0, which is expected.
1857 if self.list.head == self.current {
1858 self.move_next();
1859 }
1860 // An element was removed before (or at) our current position, so
1861 // the index must be decremented. `saturating_sub` handles the
1862 // ghost node case where index could be 0.
1863 self.index = self.index.saturating_sub(1);
1864 self.list.pop_front()
1865 }
1866 }
1867
1868 /// Removes the last element from the cursor's parent list and returns it,
1869 /// or None if the list is empty. The element the cursor points to remains
1870 /// unchanged, unless it was pointing to the back element. In that case, it
1871 /// points to the "ghost" element.
1872 ///
1873 /// This operation should compute in *O*(1) time.
1874 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1875 #[rustc_confusables("pop")]
1876 pub fn pop_back(&mut self) -> Option<T> {
1877 if self.list.is_empty() {
1878 None
1879 } else {
1880 if self.list.tail == self.current {
1881 // The index now reflects the length of the list. It was the
1882 // length of the list minus 1, but now the list is 1 smaller. No
1883 // change is needed for `index`.
1884 self.current = None;
1885 } else if self.current.is_none() {
1886 self.index = self.list.len - 1;
1887 }
1888 self.list.pop_back()
1889 }
1890 }
1891
1892 /// Provides a reference to the front element of the cursor's parent list,
1893 /// or None if the list is empty.
1894 #[must_use]
1895 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1896 #[rustc_confusables("first")]
1897 pub fn front(&self) -> Option<&T> {
1898 self.list.front()
1899 }
1900
1901 /// Provides a mutable reference to the front element of the cursor's
1902 /// parent list, or None if the list is empty.
1903 #[must_use]
1904 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1905 pub fn front_mut(&mut self) -> Option<&mut T> {
1906 self.list.front_mut()
1907 }
1908
1909 /// Provides a reference to the back element of the cursor's parent list,
1910 /// or None if the list is empty.
1911 #[must_use]
1912 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1913 #[rustc_confusables("last")]
1914 pub fn back(&self) -> Option<&T> {
1915 self.list.back()
1916 }
1917
1918 /// Provides a mutable reference to back element of the cursor's parent
1919 /// list, or `None` if the list is empty.
1920 ///
1921 /// # Examples
1922 /// Building and mutating a list with a cursor, then getting the back element:
1923 /// ```
1924 /// #![feature(linked_list_cursors)]
1925 /// use std::collections::LinkedList;
1926 /// let mut dl = LinkedList::new();
1927 /// dl.push_front(3);
1928 /// dl.push_front(2);
1929 /// dl.push_front(1);
1930 /// let mut cursor = dl.cursor_front_mut();
1931 /// *cursor.current().unwrap() = 99;
1932 /// *cursor.back_mut().unwrap() = 0;
1933 /// let mut contents = dl.into_iter();
1934 /// assert_eq!(contents.next(), Some(99));
1935 /// assert_eq!(contents.next(), Some(2));
1936 /// assert_eq!(contents.next(), Some(0));
1937 /// assert_eq!(contents.next(), None);
1938 /// ```
1939 #[must_use]
1940 #[unstable(feature = "linked_list_cursors", issue = "58533")]
1941 pub fn back_mut(&mut self) -> Option<&mut T> {
1942 self.list.back_mut()
1943 }
1944}
1945
1946/// This `struct` is created by the [`extract_if`] method on [`LinkedList`].
1947///
1948/// [`extract_if`]: LinkedList::extract_if
1949#[stable(feature = "extract_if", since = "1.87.0")]
1950#[must_use = "iterators are lazy and do nothing unless consumed; \
1951 use `extract_if().for_each(drop)` to remove and discard elements"]
1952pub struct ExtractIf<
1953 'a,
1954 T: 'a,
1955 F: 'a,
1956 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
1957> {
1958 list: &'a mut LinkedList<T, A>,
1959 it: Option<NonNull<Node<T>>>,
1960 pred: F,
1961 idx: usize,
1962 old_len: usize,
1963}
1964
1965#[stable(feature = "extract_if", since = "1.87.0")]
1966impl<T, F, A: Allocator> Iterator for ExtractIf<'_, T, F, A>
1967where
1968 F: FnMut(&mut T) -> bool,
1969{
1970 type Item = T;
1971
1972 fn next(&mut self) -> Option<T> {
1973 while let Some(mut node) = self.it {
1974 unsafe {
1975 self.it = node.as_ref().next;
1976 self.idx += 1;
1977
1978 if (self.pred)(&mut node.as_mut().element) {
1979 // `unlink_node` is okay with aliasing `element` references.
1980 self.list.unlink_node(node);
1981 return Some(Box::from_raw_in(node.as_ptr(), &self.list.alloc).element);
1982 }
1983 }
1984 }
1985
1986 None
1987 }
1988
1989 fn size_hint(&self) -> (usize, Option<usize>) {
1990 (0, Some(self.old_len - self.idx))
1991 }
1992}
1993
1994#[stable(feature = "extract_if", since = "1.87.0")]
1995impl<T, F, A> fmt::Debug for ExtractIf<'_, T, F, A>
1996where
1997 T: fmt::Debug,
1998 A: Allocator,
1999{
2000 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2001 let peek = self.it.map(|node| unsafe { &node.as_ref().element });
2002 f.debug_struct("ExtractIf").field("peek", &peek).finish_non_exhaustive()
2003 }
2004}
2005
2006#[stable(feature = "rust1", since = "1.0.0")]
2007impl<T, A: Allocator> Iterator for IntoIter<T, A> {
2008 type Item = T;
2009
2010 #[inline]
2011 fn next(&mut self) -> Option<T> {
2012 self.list.pop_front()
2013 }
2014
2015 #[inline]
2016 fn size_hint(&self) -> (usize, Option<usize>) {
2017 (self.list.len, Some(self.list.len))
2018 }
2019}
2020
2021#[stable(feature = "rust1", since = "1.0.0")]
2022impl<T, A: Allocator> DoubleEndedIterator for IntoIter<T, A> {
2023 #[inline]
2024 fn next_back(&mut self) -> Option<T> {
2025 self.list.pop_back()
2026 }
2027}
2028
2029#[stable(feature = "rust1", since = "1.0.0")]
2030impl<T, A: Allocator> ExactSizeIterator for IntoIter<T, A> {}
2031
2032#[stable(feature = "fused", since = "1.26.0")]
2033impl<T, A: Allocator> FusedIterator for IntoIter<T, A> {}
2034
2035#[stable(feature = "default_iters", since = "1.70.0")]
2036impl<T> Default for IntoIter<T> {
2037 /// Creates an empty `linked_list::IntoIter`.
2038 ///
2039 /// ```
2040 /// # use std::collections::linked_list;
2041 /// let iter: linked_list::IntoIter<u8> = Default::default();
2042 /// assert_eq!(iter.len(), 0);
2043 /// ```
2044 fn default() -> Self {
2045 LinkedList::new().into_iter()
2046 }
2047}
2048
2049#[stable(feature = "rust1", since = "1.0.0")]
2050impl<T> FromIterator<T> for LinkedList<T> {
2051 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
2052 let mut list = Self::new();
2053 list.extend(iter);
2054 list
2055 }
2056}
2057
2058#[stable(feature = "rust1", since = "1.0.0")]
2059impl<T, A: Allocator> IntoIterator for LinkedList<T, A> {
2060 type Item = T;
2061 type IntoIter = IntoIter<T, A>;
2062
2063 /// Consumes the list into an iterator yielding elements by value.
2064 #[inline]
2065 fn into_iter(self) -> IntoIter<T, A> {
2066 IntoIter { list: self }
2067 }
2068}
2069
2070#[stable(feature = "rust1", since = "1.0.0")]
2071impl<'a, T, A: Allocator> IntoIterator for &'a LinkedList<T, A> {
2072 type Item = &'a T;
2073 type IntoIter = Iter<'a, T>;
2074
2075 fn into_iter(self) -> Iter<'a, T> {
2076 self.iter()
2077 }
2078}
2079
2080#[stable(feature = "rust1", since = "1.0.0")]
2081impl<'a, T, A: Allocator> IntoIterator for &'a mut LinkedList<T, A> {
2082 type Item = &'a mut T;
2083 type IntoIter = IterMut<'a, T>;
2084
2085 fn into_iter(self) -> IterMut<'a, T> {
2086 self.iter_mut()
2087 }
2088}
2089
2090#[stable(feature = "rust1", since = "1.0.0")]
2091impl<T, A: Allocator> Extend<T> for LinkedList<T, A> {
2092 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
2093 <Self as SpecExtend<I>>::spec_extend(self, iter);
2094 }
2095
2096 #[inline]
2097 fn extend_one(&mut self, elem: T) {
2098 self.push_back(elem);
2099 }
2100}
2101
2102impl<I: IntoIterator, A: Allocator> SpecExtend<I> for LinkedList<I::Item, A> {
2103 default fn spec_extend(&mut self, iter: I) {
2104 iter.into_iter().for_each(move |elt| self.push_back(elt));
2105 }
2106}
2107
2108impl<T> SpecExtend<LinkedList<T>> for LinkedList<T> {
2109 fn spec_extend(&mut self, ref mut other: LinkedList<T>) {
2110 self.append(other);
2111 }
2112}
2113
2114#[stable(feature = "extend_ref", since = "1.2.0")]
2115impl<'a, T: 'a + Copy, A: Allocator> Extend<&'a T> for LinkedList<T, A> {
2116 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
2117 self.extend(iter.into_iter().cloned());
2118 }
2119
2120 #[inline]
2121 fn extend_one(&mut self, &elem: &'a T) {
2122 self.push_back(elem);
2123 }
2124}
2125
2126#[stable(feature = "rust1", since = "1.0.0")]
2127impl<T: PartialEq, A: Allocator> PartialEq for LinkedList<T, A> {
2128 fn eq(&self, other: &Self) -> bool {
2129 self.len() == other.len() && self.iter().eq(other)
2130 }
2131
2132 fn ne(&self, other: &Self) -> bool {
2133 self.len() != other.len() || self.iter().ne(other)
2134 }
2135}
2136
2137#[stable(feature = "rust1", since = "1.0.0")]
2138impl<T: Eq, A: Allocator> Eq for LinkedList<T, A> {}
2139
2140#[stable(feature = "rust1", since = "1.0.0")]
2141impl<T: PartialOrd, A: Allocator> PartialOrd for LinkedList<T, A> {
2142 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2143 self.iter().partial_cmp(other)
2144 }
2145}
2146
2147#[stable(feature = "rust1", since = "1.0.0")]
2148impl<T: Ord, A: Allocator> Ord for LinkedList<T, A> {
2149 #[inline]
2150 fn cmp(&self, other: &Self) -> Ordering {
2151 self.iter().cmp(other)
2152 }
2153}
2154
2155#[stable(feature = "rust1", since = "1.0.0")]
2156impl<T: Clone, A: Allocator + Clone> Clone for LinkedList<T, A> {
2157 fn clone(&self) -> Self {
2158 let mut list = Self::new_in(self.alloc.clone());
2159 list.extend(self.iter().cloned());
2160 list
2161 }
2162
2163 /// Overwrites the contents of `self` with a clone of the contents of `source`.
2164 ///
2165 /// This method is preferred over simply assigning `source.clone()` to `self`,
2166 /// as it avoids reallocation of the nodes of the linked list. Additionally,
2167 /// if the element type `T` overrides `clone_from()`, this will reuse the
2168 /// resources of `self`'s elements as well.
2169 fn clone_from(&mut self, source: &Self) {
2170 let mut source_iter = source.iter();
2171 for elem in self.iter_mut() {
2172 let Some(source_elem) = source_iter.next() else {
2173 break;
2174 };
2175 elem.clone_from(source_elem);
2176 }
2177 while self.len() > source.len() {
2178 self.pop_back();
2179 }
2180 if !source_iter.is_empty() {
2181 self.extend(source_iter.cloned());
2182 }
2183 }
2184}
2185
2186#[stable(feature = "rust1", since = "1.0.0")]
2187impl<T: fmt::Debug, A: Allocator> fmt::Debug for LinkedList<T, A> {
2188 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2189 f.debug_list().entries(self).finish()
2190 }
2191}
2192
2193#[stable(feature = "rust1", since = "1.0.0")]
2194impl<T: Hash, A: Allocator> Hash for LinkedList<T, A> {
2195 fn hash<H: Hasher>(&self, state: &mut H) {
2196 state.write_length_prefix(self.len());
2197 for elt in self {
2198 elt.hash(state);
2199 }
2200 }
2201}
2202
2203#[stable(feature = "std_collections_from_array", since = "1.56.0")]
2204impl<T, const N: usize> From<[T; N]> for LinkedList<T> {
2205 /// Converts a `[T; N]` into a `LinkedList<T>`.
2206 ///
2207 /// ```
2208 /// use std::collections::LinkedList;
2209 ///
2210 /// let list1 = LinkedList::from([1, 2, 3, 4]);
2211 /// let list2: LinkedList<_> = [1, 2, 3, 4].into();
2212 /// assert_eq!(list1, list2);
2213 /// ```
2214 fn from(arr: [T; N]) -> Self {
2215 Self::from_iter(arr)
2216 }
2217}
2218
2219// Ensure that `LinkedList` and its read-only iterators are covariant in their type parameters.
2220#[allow(dead_code)]
2221fn assert_covariance() {
2222 fn a<'a>(x: LinkedList<&'static str>) -> LinkedList<&'a str> {
2223 x
2224 }
2225 fn b<'i, 'a>(x: Iter<'i, &'static str>) -> Iter<'i, &'a str> {
2226 x
2227 }
2228 fn c<'a>(x: IntoIter<&'static str>) -> IntoIter<&'a str> {
2229 x
2230 }
2231}
2232
2233#[stable(feature = "rust1", since = "1.0.0")]
2234unsafe impl<T: Send, A: Allocator + Send> Send for LinkedList<T, A> {}
2235
2236#[stable(feature = "rust1", since = "1.0.0")]
2237unsafe impl<T: Sync, A: Allocator + Sync> Sync for LinkedList<T, A> {}
2238
2239#[stable(feature = "rust1", since = "1.0.0")]
2240unsafe impl<T: Sync> Send for Iter<'_, T> {}
2241
2242#[stable(feature = "rust1", since = "1.0.0")]
2243unsafe impl<T: Sync> Sync for Iter<'_, T> {}
2244
2245#[stable(feature = "rust1", since = "1.0.0")]
2246unsafe impl<T: Send> Send for IterMut<'_, T> {}
2247
2248#[stable(feature = "rust1", since = "1.0.0")]
2249unsafe impl<T: Sync> Sync for IterMut<'_, T> {}
2250
2251#[unstable(feature = "linked_list_cursors", issue = "58533")]
2252unsafe impl<T: Sync, A: Allocator + Sync> Send for Cursor<'_, T, A> {}
2253
2254#[unstable(feature = "linked_list_cursors", issue = "58533")]
2255unsafe impl<T: Sync, A: Allocator + Sync> Sync for Cursor<'_, T, A> {}
2256
2257#[unstable(feature = "linked_list_cursors", issue = "58533")]
2258unsafe impl<T: Send, A: Allocator + Send> Send for CursorMut<'_, T, A> {}
2259
2260#[unstable(feature = "linked_list_cursors", issue = "58533")]
2261unsafe impl<T: Sync, A: Allocator + Sync> Sync for CursorMut<'_, T, A> {}