]> git.proxmox.com Git - rustc.git/blob - src/libcollections/linked_list.rs
Imported Upstream version 1.1.0+dfsg1
[rustc.git] / src / libcollections / linked_list.rs
1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! A doubly-linked list with owned nodes.
12 //!
13 //! The `LinkedList` allows pushing and popping elements at either end and is thus
14 //! efficiently usable as a double-ended queue.
15
16 // LinkedList is constructed like a singly-linked list over the field `next`.
17 // including the last link being None; each Node owns its `next` field.
18 //
19 // Backlinks over LinkedList::prev are raw pointers that form a full chain in
20 // the reverse direction.
21
22 #![stable(feature = "rust1", since = "1.0.0")]
23
24 use core::prelude::*;
25
26 use alloc::boxed::Box;
27 use core::cmp::Ordering;
28 use core::fmt;
29 use core::hash::{Hasher, Hash};
30 use core::iter::{self, FromIterator};
31 use core::mem;
32 use core::ptr;
33
34 /// A doubly-linked list.
35 #[stable(feature = "rust1", since = "1.0.0")]
36 pub struct LinkedList<T> {
37 length: usize,
38 list_head: Link<T>,
39 list_tail: Rawlink<Node<T>>,
40 }
41
42 type Link<T> = Option<Box<Node<T>>>;
43
44 struct Rawlink<T> {
45 p: *mut T,
46 }
47
48 impl<T> Copy for Rawlink<T> {}
49 unsafe impl<T:Send> Send for Rawlink<T> {}
50 unsafe impl<T:Sync> Sync for Rawlink<T> {}
51
52 struct Node<T> {
53 next: Link<T>,
54 prev: Rawlink<Node<T>>,
55 value: T,
56 }
57
58 /// An iterator over references to the items of a `LinkedList`.
59 #[stable(feature = "rust1", since = "1.0.0")]
60 pub struct Iter<'a, T:'a> {
61 head: &'a Link<T>,
62 tail: Rawlink<Node<T>>,
63 nelem: usize,
64 }
65
66 // FIXME #19839: deriving is too aggressive on the bounds (T doesn't need to be Clone).
67 #[stable(feature = "rust1", since = "1.0.0")]
68 impl<'a, T> Clone for Iter<'a, T> {
69 fn clone(&self) -> Iter<'a, T> {
70 Iter {
71 head: self.head.clone(),
72 tail: self.tail,
73 nelem: self.nelem,
74 }
75 }
76 }
77
78 /// An iterator over mutable references to the items of a `LinkedList`.
79 #[stable(feature = "rust1", since = "1.0.0")]
80 pub struct IterMut<'a, T:'a> {
81 list: &'a mut LinkedList<T>,
82 head: Rawlink<Node<T>>,
83 tail: Rawlink<Node<T>>,
84 nelem: usize,
85 }
86
87 /// An iterator over mutable references to the items of a `LinkedList`.
88 #[derive(Clone)]
89 #[stable(feature = "rust1", since = "1.0.0")]
90 pub struct IntoIter<T> {
91 list: LinkedList<T>
92 }
93
94 /// Rawlink is a type like Option<T> but for holding a raw pointer
95 impl<T> Rawlink<T> {
96 /// Like Option::None for Rawlink
97 fn none() -> Rawlink<T> {
98 Rawlink{p: ptr::null_mut()}
99 }
100
101 /// Like Option::Some for Rawlink
102 fn some(n: &mut T) -> Rawlink<T> {
103 Rawlink{p: n}
104 }
105
106 /// Convert the `Rawlink` into an Option value
107 fn resolve_immut<'a>(&self) -> Option<&'a T> {
108 unsafe {
109 mem::transmute(self.p.as_ref())
110 }
111 }
112
113 /// Convert the `Rawlink` into an Option value
114 fn resolve<'a>(&mut self) -> Option<&'a mut T> {
115 if self.p.is_null() {
116 None
117 } else {
118 Some(unsafe { mem::transmute(self.p) })
119 }
120 }
121
122 /// Return the `Rawlink` and replace with `Rawlink::none()`
123 fn take(&mut self) -> Rawlink<T> {
124 mem::replace(self, Rawlink::none())
125 }
126 }
127
128 impl<T> Clone for Rawlink<T> {
129 #[inline]
130 fn clone(&self) -> Rawlink<T> {
131 Rawlink{p: self.p}
132 }
133 }
134
135 impl<T> Node<T> {
136 fn new(v: T) -> Node<T> {
137 Node{value: v, next: None, prev: Rawlink::none()}
138 }
139 }
140
141 /// Set the .prev field on `next`, then return `Some(next)`
142 fn link_with_prev<T>(mut next: Box<Node<T>>, prev: Rawlink<Node<T>>)
143 -> Link<T> {
144 next.prev = prev;
145 Some(next)
146 }
147
148 // private methods
149 impl<T> LinkedList<T> {
150 /// Add a Node first in the list
151 #[inline]
152 fn push_front_node(&mut self, mut new_head: Box<Node<T>>) {
153 match self.list_head {
154 None => {
155 self.list_tail = Rawlink::some(&mut *new_head);
156 self.list_head = link_with_prev(new_head, Rawlink::none());
157 }
158 Some(ref mut head) => {
159 new_head.prev = Rawlink::none();
160 head.prev = Rawlink::some(&mut *new_head);
161 mem::swap(head, &mut new_head);
162 head.next = Some(new_head);
163 }
164 }
165 self.length += 1;
166 }
167
168 /// Remove the first Node and return it, or None if the list is empty
169 #[inline]
170 fn pop_front_node(&mut self) -> Option<Box<Node<T>>> {
171 self.list_head.take().map(|mut front_node| {
172 self.length -= 1;
173 match front_node.next.take() {
174 Some(node) => self.list_head = link_with_prev(node, Rawlink::none()),
175 None => self.list_tail = Rawlink::none()
176 }
177 front_node
178 })
179 }
180
181 /// Add a Node last in the list
182 #[inline]
183 fn push_back_node(&mut self, mut new_tail: Box<Node<T>>) {
184 match self.list_tail.resolve() {
185 None => return self.push_front_node(new_tail),
186 Some(tail) => {
187 self.list_tail = Rawlink::some(&mut *new_tail);
188 tail.next = link_with_prev(new_tail, Rawlink::some(tail));
189 }
190 }
191 self.length += 1;
192 }
193
194 /// Remove the last Node and return it, or None if the list is empty
195 #[inline]
196 fn pop_back_node(&mut self) -> Option<Box<Node<T>>> {
197 self.list_tail.resolve().map_or(None, |tail| {
198 self.length -= 1;
199 self.list_tail = tail.prev;
200 match tail.prev.resolve() {
201 None => self.list_head.take(),
202 Some(tail_prev) => tail_prev.next.take()
203 }
204 })
205 }
206 }
207
208 #[stable(feature = "rust1", since = "1.0.0")]
209 impl<T> Default for LinkedList<T> {
210 #[inline]
211 #[stable(feature = "rust1", since = "1.0.0")]
212 fn default() -> LinkedList<T> { LinkedList::new() }
213 }
214
215 impl<T> LinkedList<T> {
216 /// Creates an empty `LinkedList`.
217 #[inline]
218 #[stable(feature = "rust1", since = "1.0.0")]
219 pub fn new() -> LinkedList<T> {
220 LinkedList{list_head: None, list_tail: Rawlink::none(), length: 0}
221 }
222
223 /// Moves all elements from `other` to the end of the list.
224 ///
225 /// This reuses all the nodes from `other` and moves them into `self`. After
226 /// this operation, `other` becomes empty.
227 ///
228 /// This operation should compute in O(1) time and O(1) memory.
229 ///
230 /// # Examples
231 ///
232 /// ```
233 /// # #![feature(collections)]
234 /// use std::collections::LinkedList;
235 ///
236 /// let mut a = LinkedList::new();
237 /// let mut b = LinkedList::new();
238 /// a.push_back(1);
239 /// a.push_back(2);
240 /// b.push_back(3);
241 /// b.push_back(4);
242 ///
243 /// a.append(&mut b);
244 ///
245 /// for e in a.iter() {
246 /// println!("{}", e); // prints 1, then 2, then 3, then 4
247 /// }
248 /// println!("{}", b.len()); // prints 0
249 /// ```
250 #[stable(feature = "rust1", since = "1.0.0")]
251 pub fn append(&mut self, other: &mut LinkedList<T>) {
252 match self.list_tail.resolve() {
253 None => {
254 self.length = other.length;
255 self.list_head = other.list_head.take();
256 self.list_tail = other.list_tail.take();
257 },
258 Some(tail) => {
259 // Carefully empty `other`.
260 let o_tail = other.list_tail.take();
261 let o_length = other.length;
262 match other.list_head.take() {
263 None => return,
264 Some(node) => {
265 tail.next = link_with_prev(node, self.list_tail);
266 self.list_tail = o_tail;
267 self.length += o_length;
268 }
269 }
270 }
271 }
272 other.length = 0;
273 }
274
275 /// Provides a forward iterator.
276 #[inline]
277 #[stable(feature = "rust1", since = "1.0.0")]
278 pub fn iter(&self) -> Iter<T> {
279 Iter{nelem: self.len(), head: &self.list_head, tail: self.list_tail}
280 }
281
282 /// Provides a forward iterator with mutable references.
283 #[inline]
284 #[stable(feature = "rust1", since = "1.0.0")]
285 pub fn iter_mut(&mut self) -> IterMut<T> {
286 let head_raw = match self.list_head {
287 Some(ref mut h) => Rawlink::some(&mut **h),
288 None => Rawlink::none(),
289 };
290 IterMut{
291 nelem: self.len(),
292 head: head_raw,
293 tail: self.list_tail,
294 list: self
295 }
296 }
297
298 /// Returns `true` if the `LinkedList` is empty.
299 ///
300 /// This operation should compute in O(1) time.
301 ///
302 /// # Examples
303 ///
304 /// ```
305 /// use std::collections::LinkedList;
306 ///
307 /// let mut dl = LinkedList::new();
308 /// assert!(dl.is_empty());
309 ///
310 /// dl.push_front("foo");
311 /// assert!(!dl.is_empty());
312 /// ```
313 #[inline]
314 #[stable(feature = "rust1", since = "1.0.0")]
315 pub fn is_empty(&self) -> bool {
316 self.list_head.is_none()
317 }
318
319 /// Returns the length of the `LinkedList`.
320 ///
321 /// This operation should compute in O(1) time.
322 ///
323 /// # Examples
324 ///
325 /// ```
326 /// use std::collections::LinkedList;
327 ///
328 /// let mut dl = LinkedList::new();
329 ///
330 /// dl.push_front(2);
331 /// assert_eq!(dl.len(), 1);
332 ///
333 /// dl.push_front(1);
334 /// assert_eq!(dl.len(), 2);
335 ///
336 /// dl.push_back(3);
337 /// assert_eq!(dl.len(), 3);
338 ///
339 /// ```
340 #[inline]
341 #[stable(feature = "rust1", since = "1.0.0")]
342 pub fn len(&self) -> usize {
343 self.length
344 }
345
346 /// Removes all elements from the `LinkedList`.
347 ///
348 /// This operation should compute in O(n) time.
349 ///
350 /// # Examples
351 ///
352 /// ```
353 /// use std::collections::LinkedList;
354 ///
355 /// let mut dl = LinkedList::new();
356 ///
357 /// dl.push_front(2);
358 /// dl.push_front(1);
359 /// assert_eq!(dl.len(), 2);
360 /// assert_eq!(dl.front(), Some(&1));
361 ///
362 /// dl.clear();
363 /// assert_eq!(dl.len(), 0);
364 /// assert_eq!(dl.front(), None);
365 ///
366 /// ```
367 #[inline]
368 #[stable(feature = "rust1", since = "1.0.0")]
369 pub fn clear(&mut self) {
370 *self = LinkedList::new()
371 }
372
373 /// Provides a reference to the front element, or `None` if the list is
374 /// empty.
375 ///
376 /// # Examples
377 ///
378 /// ```
379 /// use std::collections::LinkedList;
380 ///
381 /// let mut dl = LinkedList::new();
382 /// assert_eq!(dl.front(), None);
383 ///
384 /// dl.push_front(1);
385 /// assert_eq!(dl.front(), Some(&1));
386 ///
387 /// ```
388 #[inline]
389 #[stable(feature = "rust1", since = "1.0.0")]
390 pub fn front(&self) -> Option<&T> {
391 self.list_head.as_ref().map(|head| &head.value)
392 }
393
394 /// Provides a mutable reference to the front element, or `None` if the list
395 /// is empty.
396 ///
397 /// # Examples
398 ///
399 /// ```
400 /// use std::collections::LinkedList;
401 ///
402 /// let mut dl = LinkedList::new();
403 /// assert_eq!(dl.front(), None);
404 ///
405 /// dl.push_front(1);
406 /// assert_eq!(dl.front(), Some(&1));
407 ///
408 /// match dl.front_mut() {
409 /// None => {},
410 /// Some(x) => *x = 5,
411 /// }
412 /// assert_eq!(dl.front(), Some(&5));
413 ///
414 /// ```
415 #[inline]
416 #[stable(feature = "rust1", since = "1.0.0")]
417 pub fn front_mut(&mut self) -> Option<&mut T> {
418 self.list_head.as_mut().map(|head| &mut head.value)
419 }
420
421 /// Provides a reference to the back element, or `None` if the list is
422 /// empty.
423 ///
424 /// # Examples
425 ///
426 /// ```
427 /// use std::collections::LinkedList;
428 ///
429 /// let mut dl = LinkedList::new();
430 /// assert_eq!(dl.back(), None);
431 ///
432 /// dl.push_back(1);
433 /// assert_eq!(dl.back(), Some(&1));
434 ///
435 /// ```
436 #[inline]
437 #[stable(feature = "rust1", since = "1.0.0")]
438 pub fn back(&self) -> Option<&T> {
439 self.list_tail.resolve_immut().as_ref().map(|tail| &tail.value)
440 }
441
442 /// Provides a mutable reference to the back element, or `None` if the list
443 /// is empty.
444 ///
445 /// # Examples
446 ///
447 /// ```
448 /// use std::collections::LinkedList;
449 ///
450 /// let mut dl = LinkedList::new();
451 /// assert_eq!(dl.back(), None);
452 ///
453 /// dl.push_back(1);
454 /// assert_eq!(dl.back(), Some(&1));
455 ///
456 /// match dl.back_mut() {
457 /// None => {},
458 /// Some(x) => *x = 5,
459 /// }
460 /// assert_eq!(dl.back(), Some(&5));
461 ///
462 /// ```
463 #[inline]
464 #[stable(feature = "rust1", since = "1.0.0")]
465 pub fn back_mut(&mut self) -> Option<&mut T> {
466 self.list_tail.resolve().map(|tail| &mut tail.value)
467 }
468
469 /// Adds an element first in the list.
470 ///
471 /// This operation should compute in O(1) time.
472 ///
473 /// # Examples
474 ///
475 /// ```
476 /// # #![feature(collections)]
477 /// use std::collections::LinkedList;
478 ///
479 /// let mut dl = LinkedList::new();
480 ///
481 /// dl.push_front(2);
482 /// assert_eq!(dl.front().unwrap(), &2);
483 ///
484 /// dl.push_front(1);
485 /// assert_eq!(dl.front().unwrap(), &1);
486 ///
487 /// ```
488 #[stable(feature = "rust1", since = "1.0.0")]
489 pub fn push_front(&mut self, elt: T) {
490 self.push_front_node(box Node::new(elt))
491 }
492
493 /// Removes the first element and returns it, or `None` if the list is
494 /// empty.
495 ///
496 /// This operation should compute in O(1) time.
497 ///
498 /// # Examples
499 ///
500 /// ```
501 /// use std::collections::LinkedList;
502 ///
503 /// let mut d = LinkedList::new();
504 /// assert_eq!(d.pop_front(), None);
505 ///
506 /// d.push_front(1);
507 /// d.push_front(3);
508 /// assert_eq!(d.pop_front(), Some(3));
509 /// assert_eq!(d.pop_front(), Some(1));
510 /// assert_eq!(d.pop_front(), None);
511 ///
512 /// ```
513 ///
514 #[stable(feature = "rust1", since = "1.0.0")]
515 pub fn pop_front(&mut self) -> Option<T> {
516 self.pop_front_node().map(|box Node{value, ..}| value)
517 }
518
519 /// Appends an element to the back of a list
520 ///
521 /// # Examples
522 ///
523 /// ```
524 /// # #![feature(collections)]
525 /// use std::collections::LinkedList;
526 ///
527 /// let mut d = LinkedList::new();
528 /// d.push_back(1);
529 /// d.push_back(3);
530 /// assert_eq!(3, *d.back().unwrap());
531 /// ```
532 #[stable(feature = "rust1", since = "1.0.0")]
533 pub fn push_back(&mut self, elt: T) {
534 self.push_back_node(box Node::new(elt))
535 }
536
537 /// Removes the last element from a list and returns it, or `None` if
538 /// it is empty.
539 ///
540 /// # Examples
541 ///
542 /// ```
543 /// # #![feature(collections)]
544 /// use std::collections::LinkedList;
545 ///
546 /// let mut d = LinkedList::new();
547 /// assert_eq!(d.pop_back(), None);
548 /// d.push_back(1);
549 /// d.push_back(3);
550 /// assert_eq!(d.pop_back(), Some(3));
551 /// ```
552 #[stable(feature = "rust1", since = "1.0.0")]
553 pub fn pop_back(&mut self) -> Option<T> {
554 self.pop_back_node().map(|box Node{value, ..}| value)
555 }
556
557 /// Splits the list into two at the given index. Returns everything after the given index,
558 /// including the index.
559 ///
560 /// # Panics
561 ///
562 /// Panics if `at > len`.
563 ///
564 /// This operation should compute in O(n) time.
565 ///
566 /// # Examples
567 ///
568 /// ```
569 /// # #![feature(collections)]
570 /// use std::collections::LinkedList;
571 ///
572 /// let mut d = LinkedList::new();
573 ///
574 /// d.push_front(1);
575 /// d.push_front(2);
576 /// d.push_front(3);
577 ///
578 /// let mut splitted = d.split_off(2);
579 ///
580 /// assert_eq!(splitted.pop_front(), Some(1));
581 /// assert_eq!(splitted.pop_front(), None);
582 /// ```
583 #[stable(feature = "rust1", since = "1.0.0")]
584 pub fn split_off(&mut self, at: usize) -> LinkedList<T> {
585 let len = self.len();
586 assert!(at <= len, "Cannot split off at a nonexistent index");
587 if at == 0 {
588 return mem::replace(self, LinkedList::new());
589 } else if at == len {
590 return LinkedList::new();
591 }
592
593 // Below, we iterate towards the `i-1`th node, either from the start or the end,
594 // depending on which would be faster.
595 let mut split_node = if at - 1 <= len - 1 - (at - 1) {
596 let mut iter = self.iter_mut();
597 // instead of skipping using .skip() (which creates a new struct),
598 // we skip manually so we can access the head field without
599 // depending on implementation details of Skip
600 for _ in 0..at - 1 {
601 iter.next();
602 }
603 iter.head
604 } else {
605 // better off starting from the end
606 let mut iter = self.iter_mut();
607 for _ in 0..len - 1 - (at - 1) {
608 iter.next_back();
609 }
610 iter.tail
611 };
612
613 let mut splitted_list = LinkedList {
614 list_head: None,
615 list_tail: self.list_tail,
616 length: len - at
617 };
618
619 // Swap split_node.next with list_head (which is None), nulling out split_node.next,
620 // as it is the new tail.
621 mem::swap(&mut split_node.resolve().unwrap().next, &mut splitted_list.list_head);
622 // Null out list_head.prev. Note this `unwrap` won't fail because if at == len
623 // we already branched out at the top of the fn to return the empty list.
624 splitted_list.list_head.as_mut().unwrap().prev = Rawlink::none();
625 // Fix the tail ptr
626 self.list_tail = split_node;
627 self.length = at;
628
629 splitted_list
630 }
631 }
632
633 #[stable(feature = "rust1", since = "1.0.0")]
634 impl<T> Drop for LinkedList<T> {
635 fn drop(&mut self) {
636 // Dissolve the linked_list in backwards direction
637 // Just dropping the list_head can lead to stack exhaustion
638 // when length is >> 1_000_000
639 let mut tail = self.list_tail;
640 loop {
641 match tail.resolve() {
642 None => break,
643 Some(prev) => {
644 prev.next.take(); // release Box<Node<T>>
645 tail = prev.prev;
646 }
647 }
648 }
649 self.length = 0;
650 self.list_head = None;
651 self.list_tail = Rawlink::none();
652 }
653 }
654
655 #[stable(feature = "rust1", since = "1.0.0")]
656 impl<'a, A> Iterator for Iter<'a, A> {
657 type Item = &'a A;
658
659 #[inline]
660 fn next(&mut self) -> Option<&'a A> {
661 if self.nelem == 0 {
662 return None;
663 }
664 self.head.as_ref().map(|head| {
665 self.nelem -= 1;
666 self.head = &head.next;
667 &head.value
668 })
669 }
670
671 #[inline]
672 fn size_hint(&self) -> (usize, Option<usize>) {
673 (self.nelem, Some(self.nelem))
674 }
675 }
676
677 #[stable(feature = "rust1", since = "1.0.0")]
678 impl<'a, A> DoubleEndedIterator for Iter<'a, A> {
679 #[inline]
680 fn next_back(&mut self) -> Option<&'a A> {
681 if self.nelem == 0 {
682 return None;
683 }
684 self.tail.resolve_immut().as_ref().map(|prev| {
685 self.nelem -= 1;
686 self.tail = prev.prev;
687 &prev.value
688 })
689 }
690 }
691
692 #[stable(feature = "rust1", since = "1.0.0")]
693 impl<'a, A> ExactSizeIterator for Iter<'a, A> {}
694
695 #[stable(feature = "rust1", since = "1.0.0")]
696 impl<'a, A> Iterator for IterMut<'a, A> {
697 type Item = &'a mut A;
698 #[inline]
699 fn next(&mut self) -> Option<&'a mut A> {
700 if self.nelem == 0 {
701 return None;
702 }
703 self.head.resolve().map(|next| {
704 self.nelem -= 1;
705 self.head = match next.next {
706 Some(ref mut node) => Rawlink::some(&mut **node),
707 None => Rawlink::none(),
708 };
709 &mut next.value
710 })
711 }
712
713 #[inline]
714 fn size_hint(&self) -> (usize, Option<usize>) {
715 (self.nelem, Some(self.nelem))
716 }
717 }
718
719 #[stable(feature = "rust1", since = "1.0.0")]
720 impl<'a, A> DoubleEndedIterator for IterMut<'a, A> {
721 #[inline]
722 fn next_back(&mut self) -> Option<&'a mut A> {
723 if self.nelem == 0 {
724 return None;
725 }
726 self.tail.resolve().map(|prev| {
727 self.nelem -= 1;
728 self.tail = prev.prev;
729 &mut prev.value
730 })
731 }
732 }
733
734 #[stable(feature = "rust1", since = "1.0.0")]
735 impl<'a, A> ExactSizeIterator for IterMut<'a, A> {}
736
737 // private methods for IterMut
738 impl<'a, A> IterMut<'a, A> {
739 fn insert_next_node(&mut self, mut ins_node: Box<Node<A>>) {
740 // Insert before `self.head` so that it is between the
741 // previously yielded element and self.head.
742 //
743 // The inserted node will not appear in further iteration.
744 match self.head.resolve() {
745 None => { self.list.push_back_node(ins_node); }
746 Some(node) => {
747 let prev_node = match node.prev.resolve() {
748 None => return self.list.push_front_node(ins_node),
749 Some(prev) => prev,
750 };
751 let node_own = prev_node.next.take().unwrap();
752 ins_node.next = link_with_prev(node_own, Rawlink::some(&mut *ins_node));
753 prev_node.next = link_with_prev(ins_node, Rawlink::some(prev_node));
754 self.list.length += 1;
755 }
756 }
757 }
758 }
759
760 impl<'a, A> IterMut<'a, A> {
761 /// Inserts `elt` just after the element most recently returned by `.next()`.
762 /// The inserted element does not appear in the iteration.
763 ///
764 /// # Examples
765 ///
766 /// ```
767 /// # #![feature(collections)]
768 /// use std::collections::LinkedList;
769 ///
770 /// let mut list: LinkedList<_> = vec![1, 3, 4].into_iter().collect();
771 ///
772 /// {
773 /// let mut it = list.iter_mut();
774 /// assert_eq!(it.next().unwrap(), &1);
775 /// // insert `2` after `1`
776 /// it.insert_next(2);
777 /// }
778 /// {
779 /// let vec: Vec<_> = list.into_iter().collect();
780 /// assert_eq!(vec, [1, 2, 3, 4]);
781 /// }
782 /// ```
783 #[inline]
784 #[unstable(feature = "collections",
785 reason = "this is probably better handled by a cursor type -- we'll see")]
786 pub fn insert_next(&mut self, elt: A) {
787 self.insert_next_node(box Node::new(elt))
788 }
789
790 /// Provides a reference to the next element, without changing the iterator.
791 ///
792 /// # Examples
793 ///
794 /// ```
795 /// # #![feature(collections)]
796 /// use std::collections::LinkedList;
797 ///
798 /// let mut list: LinkedList<_> = vec![1, 2, 3].into_iter().collect();
799 ///
800 /// let mut it = list.iter_mut();
801 /// assert_eq!(it.next().unwrap(), &1);
802 /// assert_eq!(it.peek_next().unwrap(), &2);
803 /// // We just peeked at 2, so it was not consumed from the iterator.
804 /// assert_eq!(it.next().unwrap(), &2);
805 /// ```
806 #[inline]
807 #[unstable(feature = "collections",
808 reason = "this is probably better handled by a cursor type -- we'll see")]
809 pub fn peek_next(&mut self) -> Option<&mut A> {
810 if self.nelem == 0 {
811 return None
812 }
813 self.head.resolve().map(|head| &mut head.value)
814 }
815 }
816
817 #[stable(feature = "rust1", since = "1.0.0")]
818 impl<A> Iterator for IntoIter<A> {
819 type Item = A;
820
821 #[inline]
822 fn next(&mut self) -> Option<A> { self.list.pop_front() }
823
824 #[inline]
825 fn size_hint(&self) -> (usize, Option<usize>) {
826 (self.list.length, Some(self.list.length))
827 }
828 }
829
830 #[stable(feature = "rust1", since = "1.0.0")]
831 impl<A> DoubleEndedIterator for IntoIter<A> {
832 #[inline]
833 fn next_back(&mut self) -> Option<A> { self.list.pop_back() }
834 }
835
836 impl<A> ExactSizeIterator for IntoIter<A> {}
837
838 #[stable(feature = "rust1", since = "1.0.0")]
839 impl<A> FromIterator<A> for LinkedList<A> {
840 fn from_iter<T: IntoIterator<Item=A>>(iter: T) -> LinkedList<A> {
841 let mut ret = LinkedList::new();
842 ret.extend(iter);
843 ret
844 }
845 }
846
847 #[stable(feature = "rust1", since = "1.0.0")]
848 impl<T> IntoIterator for LinkedList<T> {
849 type Item = T;
850 type IntoIter = IntoIter<T>;
851
852 /// Consumes the list into an iterator yielding elements by value.
853 #[inline]
854 fn into_iter(self) -> IntoIter<T> {
855 IntoIter{list: self}
856 }
857 }
858
859 #[stable(feature = "rust1", since = "1.0.0")]
860 impl<'a, T> IntoIterator for &'a LinkedList<T> {
861 type Item = &'a T;
862 type IntoIter = Iter<'a, T>;
863
864 fn into_iter(self) -> Iter<'a, T> {
865 self.iter()
866 }
867 }
868
869 impl<'a, T> IntoIterator for &'a mut LinkedList<T> {
870 type Item = &'a mut T;
871 type IntoIter = IterMut<'a, T>;
872
873 fn into_iter(mut self) -> IterMut<'a, T> {
874 self.iter_mut()
875 }
876 }
877
878 #[stable(feature = "rust1", since = "1.0.0")]
879 impl<A> Extend<A> for LinkedList<A> {
880 fn extend<T: IntoIterator<Item=A>>(&mut self, iter: T) {
881 for elt in iter { self.push_back(elt); }
882 }
883 }
884
885 #[stable(feature = "rust1", since = "1.0.0")]
886 impl<A: PartialEq> PartialEq for LinkedList<A> {
887 fn eq(&self, other: &LinkedList<A>) -> bool {
888 self.len() == other.len() &&
889 iter::order::eq(self.iter(), other.iter())
890 }
891
892 fn ne(&self, other: &LinkedList<A>) -> bool {
893 self.len() != other.len() ||
894 iter::order::ne(self.iter(), other.iter())
895 }
896 }
897
898 #[stable(feature = "rust1", since = "1.0.0")]
899 impl<A: Eq> Eq for LinkedList<A> {}
900
901 #[stable(feature = "rust1", since = "1.0.0")]
902 impl<A: PartialOrd> PartialOrd for LinkedList<A> {
903 fn partial_cmp(&self, other: &LinkedList<A>) -> Option<Ordering> {
904 iter::order::partial_cmp(self.iter(), other.iter())
905 }
906 }
907
908 #[stable(feature = "rust1", since = "1.0.0")]
909 impl<A: Ord> Ord for LinkedList<A> {
910 #[inline]
911 fn cmp(&self, other: &LinkedList<A>) -> Ordering {
912 iter::order::cmp(self.iter(), other.iter())
913 }
914 }
915
916 #[stable(feature = "rust1", since = "1.0.0")]
917 impl<A: Clone> Clone for LinkedList<A> {
918 fn clone(&self) -> LinkedList<A> {
919 self.iter().cloned().collect()
920 }
921 }
922
923 #[stable(feature = "rust1", since = "1.0.0")]
924 impl<A: fmt::Debug> fmt::Debug for LinkedList<A> {
925 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
926 self.iter().fold(f.debug_list(), |b, e| b.entry(e)).finish()
927 }
928 }
929
930 #[stable(feature = "rust1", since = "1.0.0")]
931 impl<A: Hash> Hash for LinkedList<A> {
932 fn hash<H: Hasher>(&self, state: &mut H) {
933 self.len().hash(state);
934 for elt in self {
935 elt.hash(state);
936 }
937 }
938 }
939
940 #[cfg(test)]
941 mod tests {
942 use std::clone::Clone;
943 use std::iter::{Iterator, IntoIterator};
944 use std::option::Option::{Some, None, self};
945 use std::__rand::{thread_rng, Rng};
946 use std::thread;
947 use std::vec::Vec;
948
949 use super::{LinkedList, Node};
950
951 #[cfg(test)]
952 fn list_from<T: Clone>(v: &[T]) -> LinkedList<T> {
953 v.iter().cloned().collect()
954 }
955
956 pub fn check_links<T>(list: &LinkedList<T>) {
957 let mut len = 0;
958 let mut last_ptr: Option<&Node<T>> = None;
959 let mut node_ptr: &Node<T>;
960 match list.list_head {
961 None => { assert_eq!(0, list.length); return }
962 Some(ref node) => node_ptr = &**node,
963 }
964 loop {
965 match (last_ptr, node_ptr.prev.resolve_immut()) {
966 (None , None ) => {}
967 (None , _ ) => panic!("prev link for list_head"),
968 (Some(p), Some(pptr)) => {
969 assert_eq!(p as *const Node<T>, pptr as *const Node<T>);
970 }
971 _ => panic!("prev link is none, not good"),
972 }
973 match node_ptr.next {
974 Some(ref next) => {
975 last_ptr = Some(node_ptr);
976 node_ptr = &**next;
977 len += 1;
978 }
979 None => {
980 len += 1;
981 break;
982 }
983 }
984 }
985 assert_eq!(len, list.length);
986 }
987
988 #[test]
989 fn test_append() {
990 // Empty to empty
991 {
992 let mut m = LinkedList::<i32>::new();
993 let mut n = LinkedList::new();
994 m.append(&mut n);
995 check_links(&m);
996 assert_eq!(m.len(), 0);
997 assert_eq!(n.len(), 0);
998 }
999 // Non-empty to empty
1000 {
1001 let mut m = LinkedList::new();
1002 let mut n = LinkedList::new();
1003 n.push_back(2);
1004 m.append(&mut n);
1005 check_links(&m);
1006 assert_eq!(m.len(), 1);
1007 assert_eq!(m.pop_back(), Some(2));
1008 assert_eq!(n.len(), 0);
1009 check_links(&m);
1010 }
1011 // Empty to non-empty
1012 {
1013 let mut m = LinkedList::new();
1014 let mut n = LinkedList::new();
1015 m.push_back(2);
1016 m.append(&mut n);
1017 check_links(&m);
1018 assert_eq!(m.len(), 1);
1019 assert_eq!(m.pop_back(), Some(2));
1020 check_links(&m);
1021 }
1022
1023 // Non-empty to non-empty
1024 let v = vec![1,2,3,4,5];
1025 let u = vec![9,8,1,2,3,4,5];
1026 let mut m = list_from(&v);
1027 let mut n = list_from(&u);
1028 m.append(&mut n);
1029 check_links(&m);
1030 let mut sum = v;
1031 sum.push_all(&u);
1032 assert_eq!(sum.len(), m.len());
1033 for elt in sum {
1034 assert_eq!(m.pop_front(), Some(elt))
1035 }
1036 assert_eq!(n.len(), 0);
1037 // let's make sure it's working properly, since we
1038 // did some direct changes to private members
1039 n.push_back(3);
1040 assert_eq!(n.len(), 1);
1041 assert_eq!(n.pop_front(), Some(3));
1042 check_links(&n);
1043 }
1044
1045 #[test]
1046 fn test_insert_prev() {
1047 let mut m = list_from(&[0,2,4,6,8]);
1048 let len = m.len();
1049 {
1050 let mut it = m.iter_mut();
1051 it.insert_next(-2);
1052 loop {
1053 match it.next() {
1054 None => break,
1055 Some(elt) => {
1056 it.insert_next(*elt + 1);
1057 match it.peek_next() {
1058 Some(x) => assert_eq!(*x, *elt + 2),
1059 None => assert_eq!(8, *elt),
1060 }
1061 }
1062 }
1063 }
1064 it.insert_next(0);
1065 it.insert_next(1);
1066 }
1067 check_links(&m);
1068 assert_eq!(m.len(), 3 + len * 2);
1069 assert_eq!(m.into_iter().collect::<Vec<_>>(), [-2,0,1,2,3,4,5,6,7,8,9,0,1]);
1070 }
1071
1072 #[test]
1073 fn test_send() {
1074 let n = list_from(&[1,2,3]);
1075 thread::spawn(move || {
1076 check_links(&n);
1077 let a: &[_] = &[&1,&2,&3];
1078 assert_eq!(a, &n.iter().collect::<Vec<_>>()[..]);
1079 }).join().ok().unwrap();
1080 }
1081
1082 #[test]
1083 fn test_fuzz() {
1084 for _ in 0..25 {
1085 fuzz_test(3);
1086 fuzz_test(16);
1087 fuzz_test(189);
1088 }
1089 }
1090
1091 #[test]
1092 fn test_26021() {
1093 use std::iter::ExactSizeIterator;
1094 // There was a bug in split_off that failed to null out the RHS's head's prev ptr.
1095 // This caused the RHS's dtor to walk up into the LHS at drop and delete all of
1096 // its nodes.
1097 //
1098 // https://github.com/rust-lang/rust/issues/26021
1099 let mut v1 = LinkedList::new();
1100 v1.push_front(1u8);
1101 v1.push_front(1u8);
1102 v1.push_front(1u8);
1103 v1.push_front(1u8);
1104 let _ = v1.split_off(3); // Dropping this now should not cause laundry consumption
1105 assert_eq!(v1.len(), 3);
1106
1107 assert_eq!(v1.iter().len(), 3);
1108 assert_eq!(v1.iter().collect::<Vec<_>>().len(), 3);
1109 }
1110
1111 #[cfg(test)]
1112 fn fuzz_test(sz: i32) {
1113 let mut m: LinkedList<_> = LinkedList::new();
1114 let mut v = vec![];
1115 for i in 0..sz {
1116 check_links(&m);
1117 let r: u8 = thread_rng().next_u32() as u8;
1118 match r % 6 {
1119 0 => {
1120 m.pop_back();
1121 v.pop();
1122 }
1123 1 => {
1124 if !v.is_empty() {
1125 m.pop_front();
1126 v.remove(0);
1127 }
1128 }
1129 2 | 4 => {
1130 m.push_front(-i);
1131 v.insert(0, -i);
1132 }
1133 3 | 5 | _ => {
1134 m.push_back(i);
1135 v.push(i);
1136 }
1137 }
1138 }
1139
1140 check_links(&m);
1141
1142 let mut i = 0;
1143 for (a, &b) in m.into_iter().zip(v.iter()) {
1144 i += 1;
1145 assert_eq!(a, b);
1146 }
1147 assert_eq!(i, v.len());
1148 }
1149 }