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