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