1 // Copyright 2012-2014 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.
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.
11 //! A doubly-linked list with owned nodes.
13 //! The `DList` allows pushing and popping elements at either end.
15 // DList is constructed like a singly-linked list over the field `next`.
16 // including the last link being None; each Node owns its `next` field.
18 // Backlinks over DList::prev are raw pointers that form a full chain in
19 // the reverse direction.
23 use alloc::boxed::Box;
24 use core::default::Default;
29 use std::hash::{Writer, Hash};
31 /// A doubly-linked list.
35 list_tail: Rawlink<Node<T>>,
38 type Link<T> = Option<Box<Node<T>>>;
39 struct Rawlink<T> { p: *mut T }
43 prev: Rawlink<Node<T>>,
47 /// An iterator over references to the items of a `DList`.
48 pub struct Items<'a, T:'a> {
50 tail: Rawlink<Node<T>>,
54 // FIXME #11820: the &'a Option<> of the Link stops clone working.
55 impl<'a, T> Clone for Items<'a, T> {
56 fn clone(&self) -> Items<'a, T> { *self }
59 /// An iterator over mutable references to the items of a `DList`.
60 pub struct MutItems<'a, T:'a> {
61 list: &'a mut DList<T>,
62 head: Rawlink<Node<T>>,
63 tail: Rawlink<Node<T>>,
67 /// An iterator over mutable references to the items of a `DList`.
69 pub struct MoveItems<T> {
73 /// Rawlink is a type like Option<T> but for holding a raw pointer
75 /// Like Option::None for Rawlink
76 fn none() -> Rawlink<T> {
77 Rawlink{p: ptr::null_mut()}
80 /// Like Option::Some for Rawlink
81 fn some(n: &mut T) -> Rawlink<T> {
85 /// Convert the `Rawlink` into an Option value
86 fn resolve_immut<'a>(&self) -> Option<&'a T> {
92 /// Convert the `Rawlink` into an Option value
93 fn resolve<'a>(&mut self) -> Option<&'a mut T> {
97 Some(unsafe { mem::transmute(self.p) })
101 /// Return the `Rawlink` and replace with `Rawlink::none()`
102 fn take(&mut self) -> Rawlink<T> {
103 mem::replace(self, Rawlink::none())
107 impl<T> Clone for Rawlink<T> {
109 fn clone(&self) -> Rawlink<T> {
115 fn new(v: T) -> Node<T> {
116 Node{value: v, next: None, prev: Rawlink::none()}
120 /// Set the .prev field on `next`, then return `Some(next)`
121 fn link_with_prev<T>(mut next: Box<Node<T>>, prev: Rawlink<Node<T>>)
129 /// Add a Node first in the list
131 fn push_front_node(&mut self, mut new_head: Box<Node<T>>) {
132 match self.list_head {
134 self.list_tail = Rawlink::some(&mut *new_head);
135 self.list_head = link_with_prev(new_head, Rawlink::none());
137 Some(ref mut head) => {
138 new_head.prev = Rawlink::none();
139 head.prev = Rawlink::some(&mut *new_head);
140 mem::swap(head, &mut new_head);
141 head.next = Some(new_head);
147 /// Remove the first Node and return it, or None if the list is empty
149 fn pop_front_node(&mut self) -> Option<Box<Node<T>>> {
150 self.list_head.take().map(|mut front_node| {
152 match front_node.next.take() {
153 Some(node) => self.list_head = link_with_prev(node, Rawlink::none()),
154 None => self.list_tail = Rawlink::none()
160 /// Add a Node last in the list
162 fn push_back_node(&mut self, mut new_tail: Box<Node<T>>) {
163 match self.list_tail.resolve() {
164 None => return self.push_front_node(new_tail),
166 self.list_tail = Rawlink::some(&mut *new_tail);
167 tail.next = link_with_prev(new_tail, Rawlink::some(tail));
173 /// Remove the last Node and return it, or None if the list is empty
175 fn pop_back_node(&mut self) -> Option<Box<Node<T>>> {
176 self.list_tail.resolve().map_or(None, |tail| {
178 self.list_tail = tail.prev;
179 match tail.prev.resolve() {
180 None => self.list_head.take(),
181 Some(tail_prev) => tail_prev.next.take()
187 impl<T> Default for DList<T> {
189 fn default() -> DList<T> { DList::new() }
193 /// Creates an empty `DList`.
195 #[unstable = "matches collection reform specification, waiting for dust to settle"]
196 pub fn new() -> DList<T> {
197 DList{list_head: None, list_tail: Rawlink::none(), length: 0}
200 /// Moves the last element to the front of the list.
202 /// If the list is empty, does nothing.
207 /// use std::collections::DList;
209 /// let mut dl = DList::new();
210 /// dl.push_back(1i);
214 /// dl.rotate_forward();
216 /// for e in dl.iter() {
217 /// println!("{}", e); // prints 3, then 1, then 2
221 pub fn rotate_forward(&mut self) {
222 self.pop_back_node().map(|tail| {
223 self.push_front_node(tail)
227 /// Moves the first element to the back of the list.
229 /// If the list is empty, does nothing.
234 /// use std::collections::DList;
236 /// let mut dl = DList::new();
237 /// dl.push_back(1i);
241 /// dl.rotate_backward();
243 /// for e in dl.iter() {
244 /// println!("{}", e); // prints 2, then 3, then 1
248 pub fn rotate_backward(&mut self) {
249 self.pop_front_node().map(|head| {
250 self.push_back_node(head)
254 /// Adds all elements from `other` to the end of the list.
256 /// This operation should compute in O(1) time.
261 /// use std::collections::DList;
263 /// let mut a = DList::new();
264 /// let mut b = DList::new();
272 /// for e in a.iter() {
273 /// println!("{}", e); // prints 1, then 2, then 3, then 4
276 pub fn append(&mut self, mut other: DList<T>) {
277 match self.list_tail.resolve() {
278 None => *self = other,
280 // Carefully empty `other`.
281 let o_tail = other.list_tail.take();
282 let o_length = other.length;
283 match other.list_head.take() {
286 tail.next = link_with_prev(node, self.list_tail);
287 self.list_tail = o_tail;
288 self.length += o_length;
295 /// Adds all elements from `other` to the beginning of the list.
297 /// This operation should compute in O(1) time.
302 /// use std::collections::DList;
304 /// let mut a = DList::new();
305 /// let mut b = DList::new();
313 /// for e in a.iter() {
314 /// println!("{}", e); // prints 3, then 4, then 1, then 2
318 pub fn prepend(&mut self, mut other: DList<T>) {
319 mem::swap(self, &mut other);
323 /// Inserts `elt` before the first `x` in the list where `f(x, elt)` is
324 /// true, or at the end.
326 /// This operation should compute in O(N) time.
331 /// use std::collections::DList;
333 /// let mut a: DList<int> = DList::new();
339 /// // insert 11 before the first odd number in the list
340 /// a.insert_when(11, |&e, _| e % 2 == 1);
342 /// for e in a.iter() {
343 /// println!("{}", e); // prints 2, then 4, then 11, then 7, then 8
346 pub fn insert_when(&mut self, elt: T, f: |&T, &T| -> bool) {
348 let mut it = self.iter_mut();
350 match it.peek_next() {
352 Some(x) => if f(x, &elt) { break }
360 /// Merges `other` into this `DList`, using the function `f`.
362 /// Iterates both `DList`s with `a` from self and `b` from `other`, and
363 /// put `a` in the result if `f(a, b)` is true, and otherwise `b`.
365 /// This operation should compute in O(max(N, M)) time.
366 pub fn merge(&mut self, mut other: DList<T>, f: |&T, &T| -> bool) {
368 let mut it = self.iter_mut();
370 let take_a = match (it.peek_next(), other.front()) {
371 (_ , None) => return,
373 (Some(ref mut x), Some(y)) => f(*x, y),
378 it.insert_next_node(other.pop_front_node().unwrap());
386 /// Provides a forward iterator.
388 #[unstable = "matches collection reform specification, waiting for dust to settle"]
389 pub fn iter<'a>(&'a self) -> Items<'a, T> {
390 Items{nelem: self.len(), head: &self.list_head, tail: self.list_tail}
393 /// Provides a forward iterator with mutable references.
395 #[unstable = "matches collection reform specification, waiting for dust to settle"]
396 pub fn iter_mut<'a>(&'a mut self) -> MutItems<'a, T> {
397 let head_raw = match self.list_head {
398 Some(ref mut h) => Rawlink::some(&mut **h),
399 None => Rawlink::none(),
404 tail: self.list_tail,
409 /// Consumes the list into an iterator yielding elements by value.
411 #[unstable = "matches collection reform specification, waiting for dust to settle"]
412 pub fn into_iter(self) -> MoveItems<T> {
413 MoveItems{list: self}
416 /// Returns `true` if the `DList` is empty.
418 /// This operation should compute in O(1) time.
420 #[unstable = "matches collection reform specification, waiting for dust to settle"]
421 pub fn is_empty(&self) -> bool {
422 self.list_head.is_none()
425 /// Returns the length of the `DList`.
427 /// This operation should compute in O(1) time.
429 #[unstable = "matches collection reform specification, waiting for dust to settle"]
430 pub fn len(&self) -> uint {
434 /// Removes all elements from the `DList`.
436 /// This operation should compute in O(n) time.
438 #[unstable = "matches collection reform specification, waiting for dust to settle"]
439 pub fn clear(&mut self) {
443 /// Provides a reference to the front element, or `None` if the list is
446 #[unstable = "matches collection reform specification, waiting for dust to settle"]
447 pub fn front(&self) -> Option<&T> {
448 self.list_head.as_ref().map(|head| &head.value)
451 /// Provides a mutable reference to the front element, or `None` if the list
454 #[unstable = "matches collection reform specification, waiting for dust to settle"]
455 pub fn front_mut(&mut self) -> Option<&mut T> {
456 self.list_head.as_mut().map(|head| &mut head.value)
459 /// Provides a reference to the back element, or `None` if the list is
462 #[unstable = "matches collection reform specification, waiting for dust to settle"]
463 pub fn back(&self) -> Option<&T> {
464 self.list_tail.resolve_immut().as_ref().map(|tail| &tail.value)
467 /// Provides a mutable reference to the back element, or `None` if the list
470 #[unstable = "matches collection reform specification, waiting for dust to settle"]
471 pub fn back_mut(&mut self) -> Option<&mut T> {
472 self.list_tail.resolve().map(|tail| &mut tail.value)
475 /// Adds an element first in the list.
477 /// This operation should compute in O(1) time.
478 #[unstable = "matches collection reform specification, waiting for dust to settle"]
479 pub fn push_front(&mut self, elt: T) {
480 self.push_front_node(box Node::new(elt))
483 /// Removes the first element and returns it, or `None` if the list is
486 /// This operation should compute in O(1) time.
487 #[unstable = "matches collection reform specification, waiting for dust to settle"]
488 pub fn pop_front(&mut self) -> Option<T> {
489 self.pop_front_node().map(|box Node{value, ..}| value)
492 /// Deprecated: Renamed to `push_back`.
493 #[deprecated = "Renamed to `push_back`"]
494 pub fn push(&mut self, elt: T) {
498 /// Appends an element to the back of a list
503 /// use std::collections::DList;
505 /// let mut d = DList::new();
508 /// assert_eq!(3, *d.back().unwrap());
510 #[unstable = "matches collection reform specification, waiting for dust to settle"]
511 pub fn push_back(&mut self, elt: T) {
512 self.push_back_node(box Node::new(elt))
515 /// Deprecated: Renamed to `pop_back`.
516 #[deprecated = "Renamed to `pop_back`"]
517 pub fn pop(&mut self) -> Option<T> {
521 /// Removes the last element from a list and returns it, or `None` if
527 /// use std::collections::DList;
529 /// let mut d = DList::new();
530 /// assert_eq!(d.pop_back(), None);
533 /// assert_eq!(d.pop_back(), Some(3));
535 #[unstable = "matches collection reform specification, waiting for dust to settle"]
536 pub fn pop_back(&mut self) -> Option<T> {
537 self.pop_back_node().map(|box Node{value, ..}| value)
541 impl<T: Ord> DList<T> {
542 /// Inserts `elt` sorted in ascending order.
544 /// This operation should compute in O(N) time.
546 pub fn insert_ordered(&mut self, elt: T) {
547 self.insert_when(elt, |a, b| a >= b)
552 impl<T> Drop for DList<T> {
554 // Dissolve the dlist in backwards direction
555 // Just dropping the list_head can lead to stack exhaustion
556 // when length is >> 1_000_000
557 let mut tail = self.list_tail;
559 match tail.resolve() {
562 prev.next.take(); // release Box<Node<T>>
568 self.list_head = None;
569 self.list_tail = Rawlink::none();
574 impl<'a, A> Iterator<&'a A> for Items<'a, A> {
576 fn next(&mut self) -> Option<&'a A> {
580 self.head.as_ref().map(|head| {
582 self.head = &head.next;
588 fn size_hint(&self) -> (uint, Option<uint>) {
589 (self.nelem, Some(self.nelem))
593 impl<'a, A> DoubleEndedIterator<&'a A> for Items<'a, A> {
595 fn next_back(&mut self) -> Option<&'a A> {
599 self.tail.resolve_immut().as_ref().map(|prev| {
601 self.tail = prev.prev;
607 impl<'a, A> ExactSizeIterator<&'a A> for Items<'a, A> {}
609 impl<'a, A> Iterator<&'a mut A> for MutItems<'a, A> {
611 fn next(&mut self) -> Option<&'a mut A> {
615 self.head.resolve().map(|next| {
617 self.head = match next.next {
618 Some(ref mut node) => Rawlink::some(&mut **node),
619 None => Rawlink::none(),
626 fn size_hint(&self) -> (uint, Option<uint>) {
627 (self.nelem, Some(self.nelem))
631 impl<'a, A> DoubleEndedIterator<&'a mut A> for MutItems<'a, A> {
633 fn next_back(&mut self) -> Option<&'a mut A> {
637 self.tail.resolve().map(|prev| {
639 self.tail = prev.prev;
645 impl<'a, A> ExactSizeIterator<&'a mut A> for MutItems<'a, A> {}
647 /// Allows mutating a `DList` while iterating.
648 pub trait ListInsertion<A> {
649 /// Inserts `elt` just after to the element most recently returned by
652 /// The inserted element does not appear in the iteration.
653 fn insert_next(&mut self, elt: A);
655 /// Provides a reference to the next element, without changing the iterator
656 fn peek_next<'a>(&'a mut self) -> Option<&'a mut A>;
659 // private methods for MutItems
660 impl<'a, A> MutItems<'a, A> {
661 fn insert_next_node(&mut self, mut ins_node: Box<Node<A>>) {
662 // Insert before `self.head` so that it is between the
663 // previously yielded element and self.head.
665 // The inserted node will not appear in further iteration.
666 match self.head.resolve() {
667 None => { self.list.push_back_node(ins_node); }
669 let prev_node = match node.prev.resolve() {
670 None => return self.list.push_front_node(ins_node),
673 let node_own = prev_node.next.take().unwrap();
674 ins_node.next = link_with_prev(node_own, Rawlink::some(&mut *ins_node));
675 prev_node.next = link_with_prev(ins_node, Rawlink::some(prev_node));
676 self.list.length += 1;
682 impl<'a, A> ListInsertion<A> for MutItems<'a, A> {
684 fn insert_next(&mut self, elt: A) {
685 self.insert_next_node(box Node::new(elt))
689 fn peek_next<'a>(&'a mut self) -> Option<&'a mut A> {
693 self.head.resolve().map(|head| &mut head.value)
697 impl<A> Iterator<A> for MoveItems<A> {
699 fn next(&mut self) -> Option<A> { self.list.pop_front() }
702 fn size_hint(&self) -> (uint, Option<uint>) {
703 (self.list.length, Some(self.list.length))
707 impl<A> DoubleEndedIterator<A> for MoveItems<A> {
709 fn next_back(&mut self) -> Option<A> { self.list.pop_back() }
712 impl<A> FromIterator<A> for DList<A> {
713 fn from_iter<T: Iterator<A>>(iterator: T) -> DList<A> {
714 let mut ret = DList::new();
715 ret.extend(iterator);
720 impl<A> Extend<A> for DList<A> {
721 fn extend<T: Iterator<A>>(&mut self, mut iterator: T) {
722 for elt in iterator { self.push_back(elt); }
726 impl<A: PartialEq> PartialEq for DList<A> {
727 fn eq(&self, other: &DList<A>) -> bool {
728 self.len() == other.len() &&
729 iter::order::eq(self.iter(), other.iter())
732 fn ne(&self, other: &DList<A>) -> bool {
733 self.len() != other.len() ||
734 iter::order::ne(self.iter(), other.iter())
738 impl<A: Eq> Eq for DList<A> {}
740 impl<A: PartialOrd> PartialOrd for DList<A> {
741 fn partial_cmp(&self, other: &DList<A>) -> Option<Ordering> {
742 iter::order::partial_cmp(self.iter(), other.iter())
746 impl<A: Ord> Ord for DList<A> {
748 fn cmp(&self, other: &DList<A>) -> Ordering {
749 iter::order::cmp(self.iter(), other.iter())
753 impl<A: Clone> Clone for DList<A> {
754 fn clone(&self) -> DList<A> {
755 self.iter().map(|x| x.clone()).collect()
759 impl<A: fmt::Show> fmt::Show for DList<A> {
760 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
761 try!(write!(f, "["));
763 for (i, e) in self.iter().enumerate() {
764 if i != 0 { try!(write!(f, ", ")); }
765 try!(write!(f, "{}", *e));
772 impl<S: Writer, A: Hash<S>> Hash<S> for DList<A> {
773 fn hash(&self, state: &mut S) {
774 self.len().hash(state);
775 for elt in self.iter() {
789 use super::{DList, Node, ListInsertion};
792 pub fn check_links<T>(list: &DList<T>) {
794 let mut last_ptr: Option<&Node<T>> = None;
795 let mut node_ptr: &Node<T>;
796 match list.list_head {
797 None => { assert_eq!(0u, list.length); return }
798 Some(ref node) => node_ptr = &**node,
801 match (last_ptr, node_ptr.prev.resolve_immut()) {
803 (None , _ ) => panic!("prev link for list_head"),
804 (Some(p), Some(pptr)) => {
805 assert_eq!(p as *const Node<T>, pptr as *const Node<T>);
807 _ => panic!("prev link is none, not good"),
809 match node_ptr.next {
811 last_ptr = Some(node_ptr);
821 assert_eq!(len, list.length);
826 let mut m: DList<Box<int>> = DList::new();
827 assert_eq!(m.pop_front(), None);
828 assert_eq!(m.pop_back(), None);
829 assert_eq!(m.pop_front(), None);
831 assert_eq!(m.pop_front(), Some(box 1));
834 assert_eq!(m.len(), 2);
835 assert_eq!(m.pop_front(), Some(box 2));
836 assert_eq!(m.pop_front(), Some(box 3));
837 assert_eq!(m.len(), 0);
838 assert_eq!(m.pop_front(), None);
843 assert_eq!(m.pop_front(), Some(box 1));
845 let mut n = DList::new();
849 assert_eq!(n.front().unwrap(), &3);
850 let x = n.front_mut().unwrap();
855 assert_eq!(n.back().unwrap(), &2);
856 let y = n.back_mut().unwrap();
860 assert_eq!(n.pop_front(), Some(0));
861 assert_eq!(n.pop_front(), Some(1));
865 fn generate_test() -> DList<int> {
866 list_from(&[0i,1,2,3,4,5,6])
870 fn list_from<T: Clone>(v: &[T]) -> DList<T> {
871 v.iter().map(|x| (*x).clone()).collect()
878 let mut m = DList::new();
879 let mut n = DList::new();
882 assert_eq!(m.len(), 1);
883 assert_eq!(m.pop_back(), Some(2));
887 let mut m = DList::new();
888 let n = DList::new();
891 assert_eq!(m.len(), 1);
892 assert_eq!(m.pop_back(), Some(2));
896 let v = vec![1i,2,3,4,5];
897 let u = vec![9i,8,1,2,3,4,5];
898 let mut m = list_from(v.as_slice());
899 m.append(list_from(u.as_slice()));
902 sum.push_all(u.as_slice());
903 assert_eq!(sum.len(), m.len());
904 for elt in sum.into_iter() {
905 assert_eq!(m.pop_front(), Some(elt))
912 let mut m = DList::new();
913 let mut n = DList::new();
916 assert_eq!(m.len(), 1);
917 assert_eq!(m.pop_back(), Some(2));
921 let v = vec![1i,2,3,4,5];
922 let mut u = vec![9i,8,1,2,3,4,5];
923 let mut m = list_from(v.as_slice());
924 m.prepend(list_from(u.as_slice()));
926 u.extend(v.as_slice().iter().map(|&b| b));
927 assert_eq!(u.len(), m.len());
928 for elt in u.into_iter() {
929 assert_eq!(m.pop_front(), Some(elt))
935 let mut n: DList<int> = DList::new();
936 n.rotate_backward(); check_links(&n);
937 assert_eq!(n.len(), 0);
938 n.rotate_forward(); check_links(&n);
939 assert_eq!(n.len(), 0);
941 let v = vec![1i,2,3,4,5];
942 let mut m = list_from(v.as_slice());
943 m.rotate_backward(); check_links(&m);
944 m.rotate_forward(); check_links(&m);
945 assert_eq!(v.iter().collect::<Vec<&int>>(), m.iter().collect::<Vec<_>>());
946 m.rotate_forward(); check_links(&m);
947 m.rotate_forward(); check_links(&m);
948 m.pop_front(); check_links(&m);
949 m.rotate_forward(); check_links(&m);
950 m.rotate_backward(); check_links(&m);
951 m.push_front(9); check_links(&m);
952 m.rotate_forward(); check_links(&m);
953 assert_eq!(vec![3i,9,5,1,2], m.into_iter().collect::<Vec<_>>());
958 let m = generate_test();
959 for (i, elt) in m.iter().enumerate() {
960 assert_eq!(i as int, *elt);
962 let mut n = DList::new();
963 assert_eq!(n.iter().next(), None);
965 let mut it = n.iter();
966 assert_eq!(it.size_hint(), (1, Some(1)));
967 assert_eq!(it.next().unwrap(), &4);
968 assert_eq!(it.size_hint(), (0, Some(0)));
969 assert_eq!(it.next(), None);
973 fn test_iterator_clone() {
974 let mut n = DList::new();
978 let mut it = n.iter();
980 let mut jt = it.clone();
981 assert_eq!(it.next(), jt.next());
982 assert_eq!(it.next_back(), jt.next_back());
983 assert_eq!(it.next(), jt.next());
987 fn test_iterator_double_end() {
988 let mut n = DList::new();
989 assert_eq!(n.iter().next(), None);
993 let mut it = n.iter();
994 assert_eq!(it.size_hint(), (3, Some(3)));
995 assert_eq!(it.next().unwrap(), &6);
996 assert_eq!(it.size_hint(), (2, Some(2)));
997 assert_eq!(it.next_back().unwrap(), &4);
998 assert_eq!(it.size_hint(), (1, Some(1)));
999 assert_eq!(it.next_back().unwrap(), &5);
1000 assert_eq!(it.next_back(), None);
1001 assert_eq!(it.next(), None);
1005 fn test_rev_iter() {
1006 let m = generate_test();
1007 for (i, elt) in m.iter().rev().enumerate() {
1008 assert_eq!((6 - i) as int, *elt);
1010 let mut n = DList::new();
1011 assert_eq!(n.iter().rev().next(), None);
1013 let mut it = n.iter().rev();
1014 assert_eq!(it.size_hint(), (1, Some(1)));
1015 assert_eq!(it.next().unwrap(), &4);
1016 assert_eq!(it.size_hint(), (0, Some(0)));
1017 assert_eq!(it.next(), None);
1021 fn test_mut_iter() {
1022 let mut m = generate_test();
1023 let mut len = m.len();
1024 for (i, elt) in m.iter_mut().enumerate() {
1025 assert_eq!(i as int, *elt);
1029 let mut n = DList::new();
1030 assert!(n.iter_mut().next().is_none());
1033 let mut it = n.iter_mut();
1034 assert_eq!(it.size_hint(), (2, Some(2)));
1035 assert!(it.next().is_some());
1036 assert!(it.next().is_some());
1037 assert_eq!(it.size_hint(), (0, Some(0)));
1038 assert!(it.next().is_none());
1042 fn test_iterator_mut_double_end() {
1043 let mut n = DList::new();
1044 assert!(n.iter_mut().next_back().is_none());
1048 let mut it = n.iter_mut();
1049 assert_eq!(it.size_hint(), (3, Some(3)));
1050 assert_eq!(*it.next().unwrap(), 6);
1051 assert_eq!(it.size_hint(), (2, Some(2)));
1052 assert_eq!(*it.next_back().unwrap(), 4);
1053 assert_eq!(it.size_hint(), (1, Some(1)));
1054 assert_eq!(*it.next_back().unwrap(), 5);
1055 assert!(it.next_back().is_none());
1056 assert!(it.next().is_none());
1060 fn test_insert_prev() {
1061 let mut m = list_from(&[0i,2,4,6,8]);
1064 let mut it = m.iter_mut();
1070 it.insert_next(*elt + 1);
1071 match it.peek_next() {
1072 Some(x) => assert_eq!(*x, *elt + 2),
1073 None => assert_eq!(8, *elt),
1082 assert_eq!(m.len(), 3 + len * 2);
1083 assert_eq!(m.into_iter().collect::<Vec<int>>(), vec![-2,0,1,2,3,4,5,6,7,8,9,0,1]);
1088 let mut m = list_from(&[0i, 1, 3, 5, 6, 7, 2]);
1089 let n = list_from(&[-1i, 0, 0, 7, 7, 9]);
1090 let len = m.len() + n.len();
1091 m.merge(n, |a, b| a <= b);
1092 assert_eq!(m.len(), len);
1094 let res = m.into_iter().collect::<Vec<int>>();
1095 assert_eq!(res, vec![-1, 0, 0, 0, 1, 3, 5, 6, 7, 2, 7, 7, 9]);
1099 fn test_insert_ordered() {
1100 let mut n = DList::new();
1101 n.insert_ordered(1i);
1102 assert_eq!(n.len(), 1);
1103 assert_eq!(n.pop_front(), Some(1));
1105 let mut m = DList::new();
1108 m.insert_ordered(3);
1110 assert_eq!(vec![2,3,4], m.into_iter().collect::<Vec<int>>());
1114 fn test_mut_rev_iter() {
1115 let mut m = generate_test();
1116 for (i, elt) in m.iter_mut().rev().enumerate() {
1117 assert_eq!((6-i) as int, *elt);
1119 let mut n = DList::new();
1120 assert!(n.iter_mut().rev().next().is_none());
1122 let mut it = n.iter_mut().rev();
1123 assert!(it.next().is_some());
1124 assert!(it.next().is_none());
1129 let n = list_from(&[1i,2,3]);
1132 let a: &[_] = &[&1,&2,&3];
1133 assert_eq!(a, n.iter().collect::<Vec<&int>>().as_slice());
1139 let mut n: DList<u8> = list_from(&[]);
1140 let mut m = list_from(&[]);
1147 let n = list_from(&[2i,3,4]);
1148 let m = list_from(&[1i,2,3]);
1154 let mut x = DList::new();
1155 let mut y = DList::new();
1157 assert!(hash::hash(&x) == hash::hash(&y));
1167 assert!(hash::hash(&x) == hash::hash(&y));
1172 let n: DList<int> = list_from(&[]);
1173 let m = list_from(&[1i,2,3]);
1182 let nan = 0.0f64/0.0;
1183 let n = list_from(&[nan]);
1184 let m = list_from(&[nan]);
1190 let n = list_from(&[nan]);
1191 let one = list_from(&[1.0f64]);
1192 assert!(!(n < one));
1193 assert!(!(n > one));
1194 assert!(!(n <= one));
1195 assert!(!(n >= one));
1197 let u = list_from(&[1.0f64,2.0,nan]);
1198 let v = list_from(&[1.0f64,2.0,3.0]);
1204 let s = list_from(&[1.0f64,2.0,4.0,2.0]);
1205 let t = list_from(&[1.0f64,2.0,3.0,2.0]);
1208 assert!(!(s <= one));
1214 for _ in range(0u, 25) {
1223 let list: DList<int> = range(0i, 10).collect();
1224 assert!(list.to_string().as_slice() == "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]");
1226 let list: DList<&str> = vec!["just", "one", "test", "more"].iter()
1229 assert!(list.to_string().as_slice() == "[just, one, test, more]");
1233 fn fuzz_test(sz: int) {
1234 let mut m: DList<int> = DList::new();
1236 for i in range(0, sz) {
1238 let r: u8 = rand::random();
1262 for (a, &b) in m.into_iter().zip(v.iter()) {
1266 assert_eq!(i, v.len());
1270 fn bench_collect_into(b: &mut test::Bencher) {
1271 let v = &[0i, ..64];
1273 let _: DList<int> = v.iter().map(|x| *x).collect();
1278 fn bench_push_front(b: &mut test::Bencher) {
1279 let mut m: DList<int> = DList::new();
1286 fn bench_push_back(b: &mut test::Bencher) {
1287 let mut m: DList<int> = DList::new();
1294 fn bench_push_back_pop_back(b: &mut test::Bencher) {
1295 let mut m: DList<int> = DList::new();
1303 fn bench_push_front_pop_front(b: &mut test::Bencher) {
1304 let mut m: DList<int> = DList::new();
1312 fn bench_rotate_forward(b: &mut test::Bencher) {
1313 let mut m: DList<int> = DList::new();
1322 fn bench_rotate_backward(b: &mut test::Bencher) {
1323 let mut m: DList<int> = DList::new();
1327 m.rotate_backward();
1332 fn bench_iter(b: &mut test::Bencher) {
1333 let v = &[0i, ..128];
1334 let m: DList<int> = v.iter().map(|&x|x).collect();
1336 assert!(m.iter().count() == 128);
1340 fn bench_iter_mut(b: &mut test::Bencher) {
1341 let v = &[0i, ..128];
1342 let mut m: DList<int> = v.iter().map(|&x|x).collect();
1344 assert!(m.iter_mut().count() == 128);
1348 fn bench_iter_rev(b: &mut test::Bencher) {
1349 let v = &[0i, ..128];
1350 let m: DList<int> = v.iter().map(|&x|x).collect();
1352 assert!(m.iter().rev().count() == 128);
1356 fn bench_iter_mut_rev(b: &mut test::Bencher) {
1357 let v = &[0i, ..128];
1358 let mut m: DList<int> = v.iter().map(|&x|x).collect();
1360 assert!(m.iter_mut().rev().count() == 128);