]> git.proxmox.com Git - rustc.git/blob - src/libcollections/linked_list.rs
c142819a5189671bf8400aed0fe5c0fe357a48c6
[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::default::Default;
29 use core::fmt;
30 use core::hash::{Hasher, Hash};
31 #[cfg(stage0)]
32 use core::hash::Writer;
33 use core::iter::{self, FromIterator, IntoIterator};
34 use core::mem;
35 use core::ptr;
36
37 #[deprecated(since = "1.0.0", reason = "renamed to LinkedList")]
38 #[unstable(feature = "collections")]
39 pub use LinkedList as DList;
40
41 /// A doubly-linked list.
42 #[stable(feature = "rust1", since = "1.0.0")]
43 pub struct LinkedList<T> {
44 length: usize,
45 list_head: Link<T>,
46 list_tail: Rawlink<Node<T>>,
47 }
48
49 type Link<T> = Option<Box<Node<T>>>;
50
51 struct Rawlink<T> {
52 p: *mut T,
53 }
54
55 impl<T> Copy for Rawlink<T> {}
56 unsafe impl<T:'static+Send> Send for Rawlink<T> {}
57 unsafe impl<T:Send+Sync> Sync for Rawlink<T> {}
58
59 struct Node<T> {
60 next: Link<T>,
61 prev: Rawlink<Node<T>>,
62 value: T,
63 }
64
65 /// An iterator over references to the items of a `LinkedList`.
66 #[stable(feature = "rust1", since = "1.0.0")]
67 pub struct Iter<'a, T:'a> {
68 head: &'a Link<T>,
69 tail: Rawlink<Node<T>>,
70 nelem: usize,
71 }
72
73 // FIXME #19839: deriving is too aggressive on the bounds (T doesn't need to be Clone).
74 #[stable(feature = "rust1", since = "1.0.0")]
75 impl<'a, T> Clone for Iter<'a, T> {
76 fn clone(&self) -> Iter<'a, T> {
77 Iter {
78 head: self.head.clone(),
79 tail: self.tail,
80 nelem: self.nelem,
81 }
82 }
83 }
84
85 /// An iterator over mutable references to the items of a `LinkedList`.
86 #[stable(feature = "rust1", since = "1.0.0")]
87 pub struct IterMut<'a, T:'a> {
88 list: &'a mut LinkedList<T>,
89 head: Rawlink<Node<T>>,
90 tail: Rawlink<Node<T>>,
91 nelem: usize,
92 }
93
94 /// An iterator over mutable references to the items of a `LinkedList`.
95 #[derive(Clone)]
96 #[stable(feature = "rust1", since = "1.0.0")]
97 pub struct IntoIter<T> {
98 list: LinkedList<T>
99 }
100
101 /// Rawlink is a type like Option<T> but for holding a raw pointer
102 impl<T> Rawlink<T> {
103 /// Like Option::None for Rawlink
104 fn none() -> Rawlink<T> {
105 Rawlink{p: ptr::null_mut()}
106 }
107
108 /// Like Option::Some for Rawlink
109 fn some(n: &mut T) -> Rawlink<T> {
110 Rawlink{p: n}
111 }
112
113 /// Convert the `Rawlink` into an Option value
114 fn resolve_immut<'a>(&self) -> Option<&'a T> {
115 unsafe {
116 mem::transmute(self.p.as_ref())
117 }
118 }
119
120 /// Convert the `Rawlink` into an Option value
121 fn resolve<'a>(&mut self) -> Option<&'a mut T> {
122 if self.p.is_null() {
123 None
124 } else {
125 Some(unsafe { mem::transmute(self.p) })
126 }
127 }
128
129 /// Return the `Rawlink` and replace with `Rawlink::none()`
130 fn take(&mut self) -> Rawlink<T> {
131 mem::replace(self, Rawlink::none())
132 }
133 }
134
135 impl<T> Clone for Rawlink<T> {
136 #[inline]
137 fn clone(&self) -> Rawlink<T> {
138 Rawlink{p: self.p}
139 }
140 }
141
142 impl<T> Node<T> {
143 fn new(v: T) -> Node<T> {
144 Node{value: v, next: None, prev: Rawlink::none()}
145 }
146 }
147
148 /// Set the .prev field on `next`, then return `Some(next)`
149 fn link_with_prev<T>(mut next: Box<Node<T>>, prev: Rawlink<Node<T>>)
150 -> Link<T> {
151 next.prev = prev;
152 Some(next)
153 }
154
155 // private methods
156 impl<T> LinkedList<T> {
157 /// Add a Node first in the list
158 #[inline]
159 fn push_front_node(&mut self, mut new_head: Box<Node<T>>) {
160 match self.list_head {
161 None => {
162 self.list_tail = Rawlink::some(&mut *new_head);
163 self.list_head = link_with_prev(new_head, Rawlink::none());
164 }
165 Some(ref mut head) => {
166 new_head.prev = Rawlink::none();
167 head.prev = Rawlink::some(&mut *new_head);
168 mem::swap(head, &mut new_head);
169 head.next = Some(new_head);
170 }
171 }
172 self.length += 1;
173 }
174
175 /// Remove the first Node and return it, or None if the list is empty
176 #[inline]
177 fn pop_front_node(&mut self) -> Option<Box<Node<T>>> {
178 self.list_head.take().map(|mut front_node| {
179 self.length -= 1;
180 match front_node.next.take() {
181 Some(node) => self.list_head = link_with_prev(node, Rawlink::none()),
182 None => self.list_tail = Rawlink::none()
183 }
184 front_node
185 })
186 }
187
188 /// Add a Node last in the list
189 #[inline]
190 fn push_back_node(&mut self, mut new_tail: Box<Node<T>>) {
191 match self.list_tail.resolve() {
192 None => return self.push_front_node(new_tail),
193 Some(tail) => {
194 self.list_tail = Rawlink::some(&mut *new_tail);
195 tail.next = link_with_prev(new_tail, Rawlink::some(tail));
196 }
197 }
198 self.length += 1;
199 }
200
201 /// Remove the last Node and return it, or None if the list is empty
202 #[inline]
203 fn pop_back_node(&mut self) -> Option<Box<Node<T>>> {
204 self.list_tail.resolve().map_or(None, |tail| {
205 self.length -= 1;
206 self.list_tail = tail.prev;
207 match tail.prev.resolve() {
208 None => self.list_head.take(),
209 Some(tail_prev) => tail_prev.next.take()
210 }
211 })
212 }
213 }
214
215 #[stable(feature = "rust1", since = "1.0.0")]
216 impl<T> Default for LinkedList<T> {
217 #[inline]
218 #[stable(feature = "rust1", since = "1.0.0")]
219 fn default() -> LinkedList<T> { LinkedList::new() }
220 }
221
222 impl<T> LinkedList<T> {
223 /// Creates an empty `LinkedList`.
224 #[inline]
225 #[stable(feature = "rust1", since = "1.0.0")]
226 pub fn new() -> LinkedList<T> {
227 LinkedList{list_head: None, list_tail: Rawlink::none(), length: 0}
228 }
229
230 /// Moves all elements from `other` to the end of the list.
231 ///
232 /// This reuses all the nodes from `other` and moves them into `self`. After
233 /// this operation, `other` becomes empty.
234 ///
235 /// This operation should compute in O(1) time and O(1) memory.
236 ///
237 /// # Examples
238 ///
239 /// ```
240 /// use std::collections::LinkedList;
241 ///
242 /// let mut a = LinkedList::new();
243 /// let mut b = LinkedList::new();
244 /// a.push_back(1);
245 /// a.push_back(2);
246 /// b.push_back(3);
247 /// b.push_back(4);
248 ///
249 /// a.append(&mut b);
250 ///
251 /// for e in a.iter() {
252 /// println!("{}", e); // prints 1, then 2, then 3, then 4
253 /// }
254 /// println!("{}", b.len()); // prints 0
255 /// ```
256 pub fn append(&mut self, other: &mut LinkedList<T>) {
257 match self.list_tail.resolve() {
258 None => {
259 self.length = other.length;
260 self.list_head = other.list_head.take();
261 self.list_tail = other.list_tail.take();
262 },
263 Some(tail) => {
264 // Carefully empty `other`.
265 let o_tail = other.list_tail.take();
266 let o_length = other.length;
267 match other.list_head.take() {
268 None => return,
269 Some(node) => {
270 tail.next = link_with_prev(node, self.list_tail);
271 self.list_tail = o_tail;
272 self.length += o_length;
273 }
274 }
275 }
276 }
277 other.length = 0;
278 }
279
280 /// Provides a forward iterator.
281 #[inline]
282 #[stable(feature = "rust1", since = "1.0.0")]
283 pub fn iter(&self) -> Iter<T> {
284 Iter{nelem: self.len(), head: &self.list_head, tail: self.list_tail}
285 }
286
287 /// Provides a forward iterator with mutable references.
288 #[inline]
289 #[stable(feature = "rust1", since = "1.0.0")]
290 pub fn iter_mut(&mut self) -> IterMut<T> {
291 let head_raw = match self.list_head {
292 Some(ref mut h) => Rawlink::some(&mut **h),
293 None => Rawlink::none(),
294 };
295 IterMut{
296 nelem: self.len(),
297 head: head_raw,
298 tail: self.list_tail,
299 list: self
300 }
301 }
302
303 /// Consumes the list into an iterator yielding elements by value.
304 #[inline]
305 #[stable(feature = "rust1", since = "1.0.0")]
306 pub fn into_iter(self) -> IntoIter<T> {
307 IntoIter{list: self}
308 }
309
310 /// Returns `true` if the `LinkedList` is empty.
311 ///
312 /// This operation should compute in O(1) time.
313 ///
314 /// # Examples
315 ///
316 /// ```
317 /// use std::collections::LinkedList;
318 ///
319 /// let mut dl = LinkedList::new();
320 /// assert!(dl.is_empty());
321 ///
322 /// dl.push_front("foo");
323 /// assert!(!dl.is_empty());
324 /// ```
325 #[inline]
326 #[stable(feature = "rust1", since = "1.0.0")]
327 pub fn is_empty(&self) -> bool {
328 self.list_head.is_none()
329 }
330
331 /// Returns the length of the `LinkedList`.
332 ///
333 /// This operation should compute in O(1) time.
334 ///
335 /// # Examples
336 ///
337 /// ```
338 /// use std::collections::LinkedList;
339 ///
340 /// let mut dl = LinkedList::new();
341 ///
342 /// dl.push_front(2);
343 /// assert_eq!(dl.len(), 1);
344 ///
345 /// dl.push_front(1);
346 /// assert_eq!(dl.len(), 2);
347 ///
348 /// dl.push_back(3);
349 /// assert_eq!(dl.len(), 3);
350 ///
351 /// ```
352 #[inline]
353 #[stable(feature = "rust1", since = "1.0.0")]
354 pub fn len(&self) -> usize {
355 self.length
356 }
357
358 /// Removes all elements from the `LinkedList`.
359 ///
360 /// This operation should compute in O(n) time.
361 ///
362 /// # Examples
363 ///
364 /// ```
365 /// use std::collections::LinkedList;
366 ///
367 /// let mut dl = LinkedList::new();
368 ///
369 /// dl.push_front(2);
370 /// dl.push_front(1);
371 /// assert_eq!(dl.len(), 2);
372 /// assert_eq!(dl.front(), Some(&1));
373 ///
374 /// dl.clear();
375 /// assert_eq!(dl.len(), 0);
376 /// assert_eq!(dl.front(), None);
377 ///
378 /// ```
379 #[inline]
380 #[stable(feature = "rust1", since = "1.0.0")]
381 pub fn clear(&mut self) {
382 *self = LinkedList::new()
383 }
384
385 /// Provides a reference to the front element, or `None` if the list is
386 /// empty.
387 ///
388 /// # Examples
389 ///
390 /// ```
391 /// use std::collections::LinkedList;
392 ///
393 /// let mut dl = LinkedList::new();
394 /// assert_eq!(dl.front(), None);
395 ///
396 /// dl.push_front(1);
397 /// assert_eq!(dl.front(), Some(&1));
398 ///
399 /// ```
400 #[inline]
401 #[stable(feature = "rust1", since = "1.0.0")]
402 pub fn front(&self) -> Option<&T> {
403 self.list_head.as_ref().map(|head| &head.value)
404 }
405
406 /// Provides a mutable reference to the front element, or `None` if the list
407 /// is empty.
408 ///
409 /// # Examples
410 ///
411 /// ```
412 /// use std::collections::LinkedList;
413 ///
414 /// let mut dl = LinkedList::new();
415 /// assert_eq!(dl.front(), None);
416 ///
417 /// dl.push_front(1);
418 /// assert_eq!(dl.front(), Some(&1));
419 ///
420 /// match dl.front_mut() {
421 /// None => {},
422 /// Some(x) => *x = 5,
423 /// }
424 /// assert_eq!(dl.front(), Some(&5));
425 ///
426 /// ```
427 #[inline]
428 #[stable(feature = "rust1", since = "1.0.0")]
429 pub fn front_mut(&mut self) -> Option<&mut T> {
430 self.list_head.as_mut().map(|head| &mut head.value)
431 }
432
433 /// Provides a reference to the back element, or `None` if the list is
434 /// empty.
435 ///
436 /// # Examples
437 ///
438 /// ```
439 /// use std::collections::LinkedList;
440 ///
441 /// let mut dl = LinkedList::new();
442 /// assert_eq!(dl.back(), None);
443 ///
444 /// dl.push_back(1);
445 /// assert_eq!(dl.back(), Some(&1));
446 ///
447 /// ```
448 #[inline]
449 #[stable(feature = "rust1", since = "1.0.0")]
450 pub fn back(&self) -> Option<&T> {
451 self.list_tail.resolve_immut().as_ref().map(|tail| &tail.value)
452 }
453
454 /// Provides a mutable reference to the back element, or `None` if the list
455 /// is empty.
456 ///
457 /// # Examples
458 ///
459 /// ```
460 /// use std::collections::LinkedList;
461 ///
462 /// let mut dl = LinkedList::new();
463 /// assert_eq!(dl.back(), None);
464 ///
465 /// dl.push_back(1);
466 /// assert_eq!(dl.back(), Some(&1));
467 ///
468 /// match dl.back_mut() {
469 /// None => {},
470 /// Some(x) => *x = 5,
471 /// }
472 /// assert_eq!(dl.back(), Some(&5));
473 ///
474 /// ```
475 #[inline]
476 #[stable(feature = "rust1", since = "1.0.0")]
477 pub fn back_mut(&mut self) -> Option<&mut T> {
478 self.list_tail.resolve().map(|tail| &mut tail.value)
479 }
480
481 /// Adds an element first in the list.
482 ///
483 /// This operation should compute in O(1) time.
484 ///
485 /// # Examples
486 ///
487 /// ```
488 /// use std::collections::LinkedList;
489 ///
490 /// let mut dl = LinkedList::new();
491 ///
492 /// dl.push_front(2);
493 /// assert_eq!(dl.front().unwrap(), &2);
494 ///
495 /// dl.push_front(1);
496 /// assert_eq!(dl.front().unwrap(), &1);
497 ///
498 /// ```
499 #[stable(feature = "rust1", since = "1.0.0")]
500 pub fn push_front(&mut self, elt: T) {
501 self.push_front_node(box Node::new(elt))
502 }
503
504 /// Removes the first element and returns it, or `None` if the list is
505 /// empty.
506 ///
507 /// This operation should compute in O(1) time.
508 ///
509 /// # Examples
510 ///
511 /// ```
512 /// use std::collections::LinkedList;
513 ///
514 /// let mut d = LinkedList::new();
515 /// assert_eq!(d.pop_front(), None);
516 ///
517 /// d.push_front(1);
518 /// d.push_front(3);
519 /// assert_eq!(d.pop_front(), Some(3));
520 /// assert_eq!(d.pop_front(), Some(1));
521 /// assert_eq!(d.pop_front(), None);
522 ///
523 /// ```
524 ///
525 #[stable(feature = "rust1", since = "1.0.0")]
526 pub fn pop_front(&mut self) -> Option<T> {
527 self.pop_front_node().map(|box Node{value, ..}| value)
528 }
529
530 /// Appends an element to the back of a list
531 ///
532 /// # Examples
533 ///
534 /// ```
535 /// use std::collections::LinkedList;
536 ///
537 /// let mut d = LinkedList::new();
538 /// d.push_back(1);
539 /// d.push_back(3);
540 /// assert_eq!(3, *d.back().unwrap());
541 /// ```
542 #[stable(feature = "rust1", since = "1.0.0")]
543 pub fn push_back(&mut self, elt: T) {
544 self.push_back_node(box Node::new(elt))
545 }
546
547 /// Removes the last element from a list and returns it, or `None` if
548 /// it is empty.
549 ///
550 /// # Examples
551 ///
552 /// ```
553 /// use std::collections::LinkedList;
554 ///
555 /// let mut d = LinkedList::new();
556 /// assert_eq!(d.pop_back(), None);
557 /// d.push_back(1);
558 /// d.push_back(3);
559 /// assert_eq!(d.pop_back(), Some(3));
560 /// ```
561 #[stable(feature = "rust1", since = "1.0.0")]
562 pub fn pop_back(&mut self) -> Option<T> {
563 self.pop_back_node().map(|box Node{value, ..}| value)
564 }
565
566 /// Splits the list into two at the given index. Returns everything after the given index,
567 /// including the index.
568 ///
569 /// # Panics
570 ///
571 /// Panics if `at > len`.
572 ///
573 /// This operation should compute in O(n) time.
574 ///
575 /// # Examples
576 ///
577 /// ```
578 /// use std::collections::LinkedList;
579 ///
580 /// let mut d = LinkedList::new();
581 ///
582 /// d.push_front(1);
583 /// d.push_front(2);
584 /// d.push_front(3);
585 ///
586 /// let mut splitted = d.split_off(2);
587 ///
588 /// assert_eq!(splitted.pop_front(), Some(1));
589 /// assert_eq!(splitted.pop_front(), None);
590 /// ```
591 #[stable(feature = "rust1", since = "1.0.0")]
592 pub fn split_off(&mut self, at: usize) -> LinkedList<T> {
593 let len = self.len();
594 assert!(at <= len, "Cannot split off at a nonexistent index");
595 if at == 0 {
596 return mem::replace(self, LinkedList::new());
597 } else if at == len {
598 return LinkedList::new();
599 }
600
601 // Below, we iterate towards the `i-1`th node, either from the start or the end,
602 // depending on which would be faster.
603 let mut split_node = if at - 1 <= len - 1 - (at - 1) {
604 let mut iter = self.iter_mut();
605 // instead of skipping using .skip() (which creates a new struct),
606 // we skip manually so we can access the head field without
607 // depending on implementation details of Skip
608 for _ in 0..at - 1 {
609 iter.next();
610 }
611 iter.head
612 } else {
613 // better off starting from the end
614 let mut iter = self.iter_mut();
615 for _ in 0..len - 1 - (at - 1) {
616 iter.next_back();
617 }
618 iter.tail
619 };
620
621 let mut splitted_list = LinkedList {
622 list_head: None,
623 list_tail: self.list_tail,
624 length: len - at
625 };
626
627 mem::swap(&mut split_node.resolve().unwrap().next, &mut splitted_list.list_head);
628 self.list_tail = split_node;
629 self.length = at;
630
631 splitted_list
632 }
633 }
634
635 #[unsafe_destructor]
636 #[stable(feature = "rust1", since = "1.0.0")]
637 impl<T> Drop for LinkedList<T> {
638 fn drop(&mut self) {
639 // Dissolve the linked_list in backwards direction
640 // Just dropping the list_head can lead to stack exhaustion
641 // when length is >> 1_000_000
642 let mut tail = self.list_tail;
643 loop {
644 match tail.resolve() {
645 None => break,
646 Some(prev) => {
647 prev.next.take(); // release Box<Node<T>>
648 tail = prev.prev;
649 }
650 }
651 }
652 self.length = 0;
653 self.list_head = None;
654 self.list_tail = Rawlink::none();
655 }
656 }
657
658 #[stable(feature = "rust1", since = "1.0.0")]
659 impl<'a, A> Iterator for Iter<'a, A> {
660 type Item = &'a A;
661
662 #[inline]
663 fn next(&mut self) -> Option<&'a A> {
664 if self.nelem == 0 {
665 return None;
666 }
667 self.head.as_ref().map(|head| {
668 self.nelem -= 1;
669 self.head = &head.next;
670 &head.value
671 })
672 }
673
674 #[inline]
675 fn size_hint(&self) -> (usize, Option<usize>) {
676 (self.nelem, Some(self.nelem))
677 }
678 }
679
680 #[stable(feature = "rust1", since = "1.0.0")]
681 impl<'a, A> DoubleEndedIterator for Iter<'a, A> {
682 #[inline]
683 fn next_back(&mut self) -> Option<&'a A> {
684 if self.nelem == 0 {
685 return None;
686 }
687 self.tail.resolve_immut().as_ref().map(|prev| {
688 self.nelem -= 1;
689 self.tail = prev.prev;
690 &prev.value
691 })
692 }
693 }
694
695 #[stable(feature = "rust1", since = "1.0.0")]
696 impl<'a, A> ExactSizeIterator for Iter<'a, A> {}
697
698 #[stable(feature = "rust1", since = "1.0.0")]
699 impl<'a, A> Iterator for IterMut<'a, A> {
700 type Item = &'a mut A;
701 #[inline]
702 fn next(&mut self) -> Option<&'a mut A> {
703 if self.nelem == 0 {
704 return None;
705 }
706 self.head.resolve().map(|next| {
707 self.nelem -= 1;
708 self.head = match next.next {
709 Some(ref mut node) => Rawlink::some(&mut **node),
710 None => Rawlink::none(),
711 };
712 &mut next.value
713 })
714 }
715
716 #[inline]
717 fn size_hint(&self) -> (usize, Option<usize>) {
718 (self.nelem, Some(self.nelem))
719 }
720 }
721
722 #[stable(feature = "rust1", since = "1.0.0")]
723 impl<'a, A> DoubleEndedIterator for IterMut<'a, A> {
724 #[inline]
725 fn next_back(&mut self) -> Option<&'a mut A> {
726 if self.nelem == 0 {
727 return None;
728 }
729 self.tail.resolve().map(|prev| {
730 self.nelem -= 1;
731 self.tail = prev.prev;
732 &mut prev.value
733 })
734 }
735 }
736
737 #[stable(feature = "rust1", since = "1.0.0")]
738 impl<'a, A> ExactSizeIterator for IterMut<'a, A> {}
739
740 // private methods for IterMut
741 impl<'a, A> IterMut<'a, A> {
742 fn insert_next_node(&mut self, mut ins_node: Box<Node<A>>) {
743 // Insert before `self.head` so that it is between the
744 // previously yielded element and self.head.
745 //
746 // The inserted node will not appear in further iteration.
747 match self.head.resolve() {
748 None => { self.list.push_back_node(ins_node); }
749 Some(node) => {
750 let prev_node = match node.prev.resolve() {
751 None => return self.list.push_front_node(ins_node),
752 Some(prev) => prev,
753 };
754 let node_own = prev_node.next.take().unwrap();
755 ins_node.next = link_with_prev(node_own, Rawlink::some(&mut *ins_node));
756 prev_node.next = link_with_prev(ins_node, Rawlink::some(prev_node));
757 self.list.length += 1;
758 }
759 }
760 }
761 }
762
763 impl<'a, A> IterMut<'a, A> {
764 /// Inserts `elt` just after the element most recently returned by `.next()`.
765 /// The inserted element does not appear in the iteration.
766 ///
767 /// # Examples
768 ///
769 /// ```
770 /// use std::collections::LinkedList;
771 ///
772 /// let mut list: LinkedList<_> = vec![1, 3, 4].into_iter().collect();
773 ///
774 /// {
775 /// let mut it = list.iter_mut();
776 /// assert_eq!(it.next().unwrap(), &1);
777 /// // insert `2` after `1`
778 /// it.insert_next(2);
779 /// }
780 /// {
781 /// let vec: Vec<_> = list.into_iter().collect();
782 /// assert_eq!(vec, vec![1, 2, 3, 4]);
783 /// }
784 /// ```
785 #[inline]
786 #[unstable(feature = "collections",
787 reason = "this is probably better handled by a cursor type -- we'll see")]
788 pub fn insert_next(&mut self, elt: A) {
789 self.insert_next_node(box Node::new(elt))
790 }
791
792 /// Provides a reference to the next element, without changing the iterator.
793 ///
794 /// # Examples
795 ///
796 /// ```
797 /// use std::collections::LinkedList;
798 ///
799 /// let mut list: LinkedList<_> = vec![1, 2, 3].into_iter().collect();
800 ///
801 /// let mut it = list.iter_mut();
802 /// assert_eq!(it.next().unwrap(), &1);
803 /// assert_eq!(it.peek_next().unwrap(), &2);
804 /// // We just peeked at 2, so it was not consumed from the iterator.
805 /// assert_eq!(it.next().unwrap(), &2);
806 /// ```
807 #[inline]
808 #[unstable(feature = "collections",
809 reason = "this is probably better handled by a cursor type -- we'll see")]
810 pub fn peek_next(&mut self) -> Option<&mut A> {
811 if self.nelem == 0 {
812 return None
813 }
814 self.head.resolve().map(|head| &mut head.value)
815 }
816 }
817
818 #[stable(feature = "rust1", since = "1.0.0")]
819 impl<A> Iterator for IntoIter<A> {
820 type Item = A;
821
822 #[inline]
823 fn next(&mut self) -> Option<A> { self.list.pop_front() }
824
825 #[inline]
826 fn size_hint(&self) -> (usize, Option<usize>) {
827 (self.list.length, Some(self.list.length))
828 }
829 }
830
831 #[stable(feature = "rust1", since = "1.0.0")]
832 impl<A> DoubleEndedIterator for IntoIter<A> {
833 #[inline]
834 fn next_back(&mut self) -> Option<A> { self.list.pop_back() }
835 }
836
837 #[stable(feature = "rust1", since = "1.0.0")]
838 impl<A> FromIterator<A> for LinkedList<A> {
839 fn from_iter<T: IntoIterator<Item=A>>(iter: T) -> LinkedList<A> {
840 let mut ret = DList::new();
841 ret.extend(iter);
842 ret
843 }
844 }
845
846 #[stable(feature = "rust1", since = "1.0.0")]
847 impl<T> IntoIterator for LinkedList<T> {
848 type Item = T;
849 type IntoIter = IntoIter<T>;
850
851 fn into_iter(self) -> IntoIter<T> {
852 self.into_iter()
853 }
854 }
855
856 #[stable(feature = "rust1", since = "1.0.0")]
857 impl<'a, T> IntoIterator for &'a LinkedList<T> {
858 type Item = &'a T;
859 type IntoIter = Iter<'a, T>;
860
861 fn into_iter(self) -> Iter<'a, T> {
862 self.iter()
863 }
864 }
865
866 impl<'a, T> IntoIterator for &'a mut LinkedList<T> {
867 type Item = &'a mut T;
868 type IntoIter = IterMut<'a, T>;
869
870 fn into_iter(mut self) -> IterMut<'a, T> {
871 self.iter_mut()
872 }
873 }
874
875 #[stable(feature = "rust1", since = "1.0.0")]
876 impl<A> Extend<A> for LinkedList<A> {
877 fn extend<T: IntoIterator<Item=A>>(&mut self, iter: T) {
878 for elt in iter { self.push_back(elt); }
879 }
880 }
881
882 #[stable(feature = "rust1", since = "1.0.0")]
883 impl<A: PartialEq> PartialEq for LinkedList<A> {
884 fn eq(&self, other: &LinkedList<A>) -> bool {
885 self.len() == other.len() &&
886 iter::order::eq(self.iter(), other.iter())
887 }
888
889 fn ne(&self, other: &LinkedList<A>) -> bool {
890 self.len() != other.len() ||
891 iter::order::ne(self.iter(), other.iter())
892 }
893 }
894
895 #[stable(feature = "rust1", since = "1.0.0")]
896 impl<A: Eq> Eq for LinkedList<A> {}
897
898 #[stable(feature = "rust1", since = "1.0.0")]
899 impl<A: PartialOrd> PartialOrd for LinkedList<A> {
900 fn partial_cmp(&self, other: &LinkedList<A>) -> Option<Ordering> {
901 iter::order::partial_cmp(self.iter(), other.iter())
902 }
903 }
904
905 #[stable(feature = "rust1", since = "1.0.0")]
906 impl<A: Ord> Ord for LinkedList<A> {
907 #[inline]
908 fn cmp(&self, other: &LinkedList<A>) -> Ordering {
909 iter::order::cmp(self.iter(), other.iter())
910 }
911 }
912
913 #[stable(feature = "rust1", since = "1.0.0")]
914 impl<A: Clone> Clone for LinkedList<A> {
915 fn clone(&self) -> LinkedList<A> {
916 self.iter().cloned().collect()
917 }
918 }
919
920 #[stable(feature = "rust1", since = "1.0.0")]
921 impl<A: fmt::Debug> fmt::Debug for LinkedList<A> {
922 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
923 try!(write!(f, "LinkedList ["));
924
925 for (i, e) in self.iter().enumerate() {
926 if i != 0 { try!(write!(f, ", ")); }
927 try!(write!(f, "{:?}", *e));
928 }
929
930 write!(f, "]")
931 }
932 }
933
934 #[stable(feature = "rust1", since = "1.0.0")]
935 #[cfg(stage0)]
936 impl<S: Writer + Hasher, A: Hash<S>> Hash<S> for LinkedList<A> {
937 fn hash(&self, state: &mut S) {
938 self.len().hash(state);
939 for elt in self {
940 elt.hash(state);
941 }
942 }
943 }
944 #[stable(feature = "rust1", since = "1.0.0")]
945 #[cfg(not(stage0))]
946 impl<A: Hash> Hash for LinkedList<A> {
947 fn hash<H: Hasher>(&self, state: &mut H) {
948 self.len().hash(state);
949 for elt in self {
950 elt.hash(state);
951 }
952 }
953 }
954
955 #[cfg(test)]
956 mod tests {
957 use prelude::*;
958 use std::rand;
959 use std::hash::{self, SipHasher};
960 use std::thread;
961 use test::Bencher;
962 use test;
963
964 use super::{LinkedList, Node};
965
966 pub fn check_links<T>(list: &LinkedList<T>) {
967 let mut len = 0;
968 let mut last_ptr: Option<&Node<T>> = None;
969 let mut node_ptr: &Node<T>;
970 match list.list_head {
971 None => { assert_eq!(0, list.length); return }
972 Some(ref node) => node_ptr = &**node,
973 }
974 loop {
975 match (last_ptr, node_ptr.prev.resolve_immut()) {
976 (None , None ) => {}
977 (None , _ ) => panic!("prev link for list_head"),
978 (Some(p), Some(pptr)) => {
979 assert_eq!(p as *const Node<T>, pptr as *const Node<T>);
980 }
981 _ => panic!("prev link is none, not good"),
982 }
983 match node_ptr.next {
984 Some(ref next) => {
985 last_ptr = Some(node_ptr);
986 node_ptr = &**next;
987 len += 1;
988 }
989 None => {
990 len += 1;
991 break;
992 }
993 }
994 }
995 assert_eq!(len, list.length);
996 }
997
998 #[test]
999 fn test_basic() {
1000 let mut m = LinkedList::new();
1001 assert_eq!(m.pop_front(), None);
1002 assert_eq!(m.pop_back(), None);
1003 assert_eq!(m.pop_front(), None);
1004 m.push_front(box 1);
1005 assert_eq!(m.pop_front(), Some(box 1));
1006 m.push_back(box 2);
1007 m.push_back(box 3);
1008 assert_eq!(m.len(), 2);
1009 assert_eq!(m.pop_front(), Some(box 2));
1010 assert_eq!(m.pop_front(), Some(box 3));
1011 assert_eq!(m.len(), 0);
1012 assert_eq!(m.pop_front(), None);
1013 m.push_back(box 1);
1014 m.push_back(box 3);
1015 m.push_back(box 5);
1016 m.push_back(box 7);
1017 assert_eq!(m.pop_front(), Some(box 1));
1018
1019 let mut n = LinkedList::new();
1020 n.push_front(2);
1021 n.push_front(3);
1022 {
1023 assert_eq!(n.front().unwrap(), &3);
1024 let x = n.front_mut().unwrap();
1025 assert_eq!(*x, 3);
1026 *x = 0;
1027 }
1028 {
1029 assert_eq!(n.back().unwrap(), &2);
1030 let y = n.back_mut().unwrap();
1031 assert_eq!(*y, 2);
1032 *y = 1;
1033 }
1034 assert_eq!(n.pop_front(), Some(0));
1035 assert_eq!(n.pop_front(), Some(1));
1036 }
1037
1038 #[cfg(test)]
1039 fn generate_test() -> LinkedList<i32> {
1040 list_from(&[0,1,2,3,4,5,6])
1041 }
1042
1043 #[cfg(test)]
1044 fn list_from<T: Clone>(v: &[T]) -> LinkedList<T> {
1045 v.iter().cloned().collect()
1046 }
1047
1048 #[test]
1049 fn test_append() {
1050 // Empty to empty
1051 {
1052 let mut m = LinkedList::<i32>::new();
1053 let mut n = LinkedList::new();
1054 m.append(&mut n);
1055 check_links(&m);
1056 assert_eq!(m.len(), 0);
1057 assert_eq!(n.len(), 0);
1058 }
1059 // Non-empty to empty
1060 {
1061 let mut m = LinkedList::new();
1062 let mut n = LinkedList::new();
1063 n.push_back(2);
1064 m.append(&mut n);
1065 check_links(&m);
1066 assert_eq!(m.len(), 1);
1067 assert_eq!(m.pop_back(), Some(2));
1068 assert_eq!(n.len(), 0);
1069 check_links(&m);
1070 }
1071 // Empty to non-empty
1072 {
1073 let mut m = LinkedList::new();
1074 let mut n = LinkedList::new();
1075 m.push_back(2);
1076 m.append(&mut n);
1077 check_links(&m);
1078 assert_eq!(m.len(), 1);
1079 assert_eq!(m.pop_back(), Some(2));
1080 check_links(&m);
1081 }
1082
1083 // Non-empty to non-empty
1084 let v = vec![1,2,3,4,5];
1085 let u = vec![9,8,1,2,3,4,5];
1086 let mut m = list_from(&v);
1087 let mut n = list_from(&u);
1088 m.append(&mut n);
1089 check_links(&m);
1090 let mut sum = v;
1091 sum.push_all(&u);
1092 assert_eq!(sum.len(), m.len());
1093 for elt in sum {
1094 assert_eq!(m.pop_front(), Some(elt))
1095 }
1096 assert_eq!(n.len(), 0);
1097 // let's make sure it's working properly, since we
1098 // did some direct changes to private members
1099 n.push_back(3);
1100 assert_eq!(n.len(), 1);
1101 assert_eq!(n.pop_front(), Some(3));
1102 check_links(&n);
1103 }
1104
1105 #[test]
1106 fn test_split_off() {
1107 // singleton
1108 {
1109 let mut m = LinkedList::new();
1110 m.push_back(1);
1111
1112 let p = m.split_off(0);
1113 assert_eq!(m.len(), 0);
1114 assert_eq!(p.len(), 1);
1115 assert_eq!(p.back(), Some(&1));
1116 assert_eq!(p.front(), Some(&1));
1117 }
1118
1119 // not singleton, forwards
1120 {
1121 let u = vec![1,2,3,4,5];
1122 let mut m = list_from(&u);
1123 let mut n = m.split_off(2);
1124 assert_eq!(m.len(), 2);
1125 assert_eq!(n.len(), 3);
1126 for elt in 1..3 {
1127 assert_eq!(m.pop_front(), Some(elt));
1128 }
1129 for elt in 3..6 {
1130 assert_eq!(n.pop_front(), Some(elt));
1131 }
1132 }
1133 // not singleton, backwards
1134 {
1135 let u = vec![1,2,3,4,5];
1136 let mut m = list_from(&u);
1137 let mut n = m.split_off(4);
1138 assert_eq!(m.len(), 4);
1139 assert_eq!(n.len(), 1);
1140 for elt in 1..5 {
1141 assert_eq!(m.pop_front(), Some(elt));
1142 }
1143 for elt in 5..6 {
1144 assert_eq!(n.pop_front(), Some(elt));
1145 }
1146 }
1147
1148 // no-op on the last index
1149 {
1150 let mut m = LinkedList::new();
1151 m.push_back(1);
1152
1153 let p = m.split_off(1);
1154 assert_eq!(m.len(), 1);
1155 assert_eq!(p.len(), 0);
1156 assert_eq!(m.back(), Some(&1));
1157 assert_eq!(m.front(), Some(&1));
1158 }
1159
1160 }
1161
1162 #[test]
1163 fn test_iterator() {
1164 let m = generate_test();
1165 for (i, elt) in m.iter().enumerate() {
1166 assert_eq!(i as i32, *elt);
1167 }
1168 let mut n = LinkedList::new();
1169 assert_eq!(n.iter().next(), None);
1170 n.push_front(4);
1171 let mut it = n.iter();
1172 assert_eq!(it.size_hint(), (1, Some(1)));
1173 assert_eq!(it.next().unwrap(), &4);
1174 assert_eq!(it.size_hint(), (0, Some(0)));
1175 assert_eq!(it.next(), None);
1176 }
1177
1178 #[test]
1179 fn test_iterator_clone() {
1180 let mut n = LinkedList::new();
1181 n.push_back(2);
1182 n.push_back(3);
1183 n.push_back(4);
1184 let mut it = n.iter();
1185 it.next();
1186 let mut jt = it.clone();
1187 assert_eq!(it.next(), jt.next());
1188 assert_eq!(it.next_back(), jt.next_back());
1189 assert_eq!(it.next(), jt.next());
1190 }
1191
1192 #[test]
1193 fn test_iterator_double_end() {
1194 let mut n = LinkedList::new();
1195 assert_eq!(n.iter().next(), None);
1196 n.push_front(4);
1197 n.push_front(5);
1198 n.push_front(6);
1199 let mut it = n.iter();
1200 assert_eq!(it.size_hint(), (3, Some(3)));
1201 assert_eq!(it.next().unwrap(), &6);
1202 assert_eq!(it.size_hint(), (2, Some(2)));
1203 assert_eq!(it.next_back().unwrap(), &4);
1204 assert_eq!(it.size_hint(), (1, Some(1)));
1205 assert_eq!(it.next_back().unwrap(), &5);
1206 assert_eq!(it.next_back(), None);
1207 assert_eq!(it.next(), None);
1208 }
1209
1210 #[test]
1211 fn test_rev_iter() {
1212 let m = generate_test();
1213 for (i, elt) in m.iter().rev().enumerate() {
1214 assert_eq!((6 - i) as i32, *elt);
1215 }
1216 let mut n = LinkedList::new();
1217 assert_eq!(n.iter().rev().next(), None);
1218 n.push_front(4);
1219 let mut it = n.iter().rev();
1220 assert_eq!(it.size_hint(), (1, Some(1)));
1221 assert_eq!(it.next().unwrap(), &4);
1222 assert_eq!(it.size_hint(), (0, Some(0)));
1223 assert_eq!(it.next(), None);
1224 }
1225
1226 #[test]
1227 fn test_mut_iter() {
1228 let mut m = generate_test();
1229 let mut len = m.len();
1230 for (i, elt) in m.iter_mut().enumerate() {
1231 assert_eq!(i as i32, *elt);
1232 len -= 1;
1233 }
1234 assert_eq!(len, 0);
1235 let mut n = LinkedList::new();
1236 assert!(n.iter_mut().next().is_none());
1237 n.push_front(4);
1238 n.push_back(5);
1239 let mut it = n.iter_mut();
1240 assert_eq!(it.size_hint(), (2, Some(2)));
1241 assert!(it.next().is_some());
1242 assert!(it.next().is_some());
1243 assert_eq!(it.size_hint(), (0, Some(0)));
1244 assert!(it.next().is_none());
1245 }
1246
1247 #[test]
1248 fn test_iterator_mut_double_end() {
1249 let mut n = LinkedList::new();
1250 assert!(n.iter_mut().next_back().is_none());
1251 n.push_front(4);
1252 n.push_front(5);
1253 n.push_front(6);
1254 let mut it = n.iter_mut();
1255 assert_eq!(it.size_hint(), (3, Some(3)));
1256 assert_eq!(*it.next().unwrap(), 6);
1257 assert_eq!(it.size_hint(), (2, Some(2)));
1258 assert_eq!(*it.next_back().unwrap(), 4);
1259 assert_eq!(it.size_hint(), (1, Some(1)));
1260 assert_eq!(*it.next_back().unwrap(), 5);
1261 assert!(it.next_back().is_none());
1262 assert!(it.next().is_none());
1263 }
1264
1265 #[test]
1266 fn test_insert_prev() {
1267 let mut m = list_from(&[0,2,4,6,8]);
1268 let len = m.len();
1269 {
1270 let mut it = m.iter_mut();
1271 it.insert_next(-2);
1272 loop {
1273 match it.next() {
1274 None => break,
1275 Some(elt) => {
1276 it.insert_next(*elt + 1);
1277 match it.peek_next() {
1278 Some(x) => assert_eq!(*x, *elt + 2),
1279 None => assert_eq!(8, *elt),
1280 }
1281 }
1282 }
1283 }
1284 it.insert_next(0);
1285 it.insert_next(1);
1286 }
1287 check_links(&m);
1288 assert_eq!(m.len(), 3 + len * 2);
1289 assert_eq!(m.into_iter().collect::<Vec<_>>(), vec![-2,0,1,2,3,4,5,6,7,8,9,0,1]);
1290 }
1291
1292 #[test]
1293 fn test_mut_rev_iter() {
1294 let mut m = generate_test();
1295 for (i, elt) in m.iter_mut().rev().enumerate() {
1296 assert_eq!((6 - i) as i32, *elt);
1297 }
1298 let mut n = LinkedList::new();
1299 assert!(n.iter_mut().rev().next().is_none());
1300 n.push_front(4);
1301 let mut it = n.iter_mut().rev();
1302 assert!(it.next().is_some());
1303 assert!(it.next().is_none());
1304 }
1305
1306 #[test]
1307 fn test_send() {
1308 let n = list_from(&[1,2,3]);
1309 thread::spawn(move || {
1310 check_links(&n);
1311 let a: &[_] = &[&1,&2,&3];
1312 assert_eq!(a, n.iter().collect::<Vec<_>>());
1313 }).join().ok().unwrap();
1314 }
1315
1316 #[test]
1317 fn test_eq() {
1318 let mut n = list_from(&[]);
1319 let mut m = list_from(&[]);
1320 assert!(n == m);
1321 n.push_front(1);
1322 assert!(n != m);
1323 m.push_back(1);
1324 assert!(n == m);
1325
1326 let n = list_from(&[2,3,4]);
1327 let m = list_from(&[1,2,3]);
1328 assert!(n != m);
1329 }
1330
1331 #[test]
1332 fn test_hash() {
1333 let mut x = LinkedList::new();
1334 let mut y = LinkedList::new();
1335
1336 assert!(hash::hash::<_, SipHasher>(&x) == hash::hash::<_, SipHasher>(&y));
1337
1338 x.push_back(1);
1339 x.push_back(2);
1340 x.push_back(3);
1341
1342 y.push_front(3);
1343 y.push_front(2);
1344 y.push_front(1);
1345
1346 assert!(hash::hash::<_, SipHasher>(&x) == hash::hash::<_, SipHasher>(&y));
1347 }
1348
1349 #[test]
1350 fn test_ord() {
1351 let n = list_from(&[]);
1352 let m = list_from(&[1,2,3]);
1353 assert!(n < m);
1354 assert!(m > n);
1355 assert!(n <= n);
1356 assert!(n >= n);
1357 }
1358
1359 #[test]
1360 fn test_ord_nan() {
1361 let nan = 0.0f64/0.0;
1362 let n = list_from(&[nan]);
1363 let m = list_from(&[nan]);
1364 assert!(!(n < m));
1365 assert!(!(n > m));
1366 assert!(!(n <= m));
1367 assert!(!(n >= m));
1368
1369 let n = list_from(&[nan]);
1370 let one = list_from(&[1.0f64]);
1371 assert!(!(n < one));
1372 assert!(!(n > one));
1373 assert!(!(n <= one));
1374 assert!(!(n >= one));
1375
1376 let u = list_from(&[1.0f64,2.0,nan]);
1377 let v = list_from(&[1.0f64,2.0,3.0]);
1378 assert!(!(u < v));
1379 assert!(!(u > v));
1380 assert!(!(u <= v));
1381 assert!(!(u >= v));
1382
1383 let s = list_from(&[1.0f64,2.0,4.0,2.0]);
1384 let t = list_from(&[1.0f64,2.0,3.0,2.0]);
1385 assert!(!(s < t));
1386 assert!(s > one);
1387 assert!(!(s <= one));
1388 assert!(s >= one);
1389 }
1390
1391 #[test]
1392 fn test_fuzz() {
1393 for _ in 0..25 {
1394 fuzz_test(3);
1395 fuzz_test(16);
1396 fuzz_test(189);
1397 }
1398 }
1399
1400 #[test]
1401 fn test_show() {
1402 let list: LinkedList<_> = (0..10).collect();
1403 assert_eq!(format!("{:?}", list), "LinkedList [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]");
1404
1405 let list: LinkedList<_> = vec!["just", "one", "test", "more"].iter().cloned().collect();
1406 assert_eq!(format!("{:?}", list), "LinkedList [\"just\", \"one\", \"test\", \"more\"]");
1407 }
1408
1409 #[cfg(test)]
1410 fn fuzz_test(sz: i32) {
1411 let mut m: LinkedList<_> = LinkedList::new();
1412 let mut v = vec![];
1413 for i in 0..sz {
1414 check_links(&m);
1415 let r: u8 = rand::random();
1416 match r % 6 {
1417 0 => {
1418 m.pop_back();
1419 v.pop();
1420 }
1421 1 => {
1422 if !v.is_empty() {
1423 m.pop_front();
1424 v.remove(0);
1425 }
1426 }
1427 2 | 4 => {
1428 m.push_front(-i);
1429 v.insert(0, -i);
1430 }
1431 3 | 5 | _ => {
1432 m.push_back(i);
1433 v.push(i);
1434 }
1435 }
1436 }
1437
1438 check_links(&m);
1439
1440 let mut i = 0;
1441 for (a, &b) in m.into_iter().zip(v.iter()) {
1442 i += 1;
1443 assert_eq!(a, b);
1444 }
1445 assert_eq!(i, v.len());
1446 }
1447
1448 #[bench]
1449 fn bench_collect_into(b: &mut test::Bencher) {
1450 let v = &[0; 64];
1451 b.iter(|| {
1452 let _: LinkedList<_> = v.iter().cloned().collect();
1453 })
1454 }
1455
1456 #[bench]
1457 fn bench_push_front(b: &mut test::Bencher) {
1458 let mut m: LinkedList<_> = LinkedList::new();
1459 b.iter(|| {
1460 m.push_front(0);
1461 })
1462 }
1463
1464 #[bench]
1465 fn bench_push_back(b: &mut test::Bencher) {
1466 let mut m: LinkedList<_> = LinkedList::new();
1467 b.iter(|| {
1468 m.push_back(0);
1469 })
1470 }
1471
1472 #[bench]
1473 fn bench_push_back_pop_back(b: &mut test::Bencher) {
1474 let mut m: LinkedList<_> = LinkedList::new();
1475 b.iter(|| {
1476 m.push_back(0);
1477 m.pop_back();
1478 })
1479 }
1480
1481 #[bench]
1482 fn bench_push_front_pop_front(b: &mut test::Bencher) {
1483 let mut m: LinkedList<_> = LinkedList::new();
1484 b.iter(|| {
1485 m.push_front(0);
1486 m.pop_front();
1487 })
1488 }
1489
1490 #[bench]
1491 fn bench_iter(b: &mut test::Bencher) {
1492 let v = &[0; 128];
1493 let m: LinkedList<_> = v.iter().cloned().collect();
1494 b.iter(|| {
1495 assert!(m.iter().count() == 128);
1496 })
1497 }
1498 #[bench]
1499 fn bench_iter_mut(b: &mut test::Bencher) {
1500 let v = &[0; 128];
1501 let mut m: LinkedList<_> = v.iter().cloned().collect();
1502 b.iter(|| {
1503 assert!(m.iter_mut().count() == 128);
1504 })
1505 }
1506 #[bench]
1507 fn bench_iter_rev(b: &mut test::Bencher) {
1508 let v = &[0; 128];
1509 let m: LinkedList<_> = v.iter().cloned().collect();
1510 b.iter(|| {
1511 assert!(m.iter().rev().count() == 128);
1512 })
1513 }
1514 #[bench]
1515 fn bench_iter_mut_rev(b: &mut test::Bencher) {
1516 let v = &[0; 128];
1517 let mut m: LinkedList<_> = v.iter().cloned().collect();
1518 b.iter(|| {
1519 assert!(m.iter_mut().rev().count() == 128);
1520 })
1521 }
1522 }