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 and is thus
14 //! efficiently usable as a double-ended queue.
16 // DList is constructed like a singly-linked list over the field `next`.
17 // including the last link being None; each Node owns its `next` field.
19 // Backlinks over DList::prev are raw pointers that form a full chain in
20 // the reverse direction.
24 use alloc::boxed::Box;
25 use core::cmp::Ordering;
26 use core::default::Default;
28 use core::hash::{Writer, Hash};
29 use core::iter::{mod, FromIterator};
33 /// A doubly-linked list.
38 list_tail: Rawlink<Node<T>>,
41 type Link<T> = Option<Box<Node<T>>>;
47 impl<T> Copy for Rawlink<T> {}
48 unsafe impl<T:'static+Send> Send for Rawlink<T> {}
49 unsafe impl<T:Send+Sync> Sync for Rawlink<T> {}
53 prev: Rawlink<Node<T>>,
57 /// An iterator over references to the items of a `DList`.
59 pub struct Iter<'a, T:'a> {
61 tail: Rawlink<Node<T>>,
65 // FIXME #19839: deriving is too aggressive on the bounds (T doesn't need to be Clone).
67 impl<'a, T> Clone for Iter<'a, T> {
68 fn clone(&self) -> Iter<'a, T> {
70 head: self.head.clone(),
77 /// An iterator over mutable references to the items of a `DList`.
79 pub struct IterMut<'a, T:'a> {
80 list: &'a mut DList<T>,
81 head: Rawlink<Node<T>>,
82 tail: Rawlink<Node<T>>,
86 /// An iterator over mutable references to the items of a `DList`.
89 pub struct IntoIter<T> {
93 /// Rawlink is a type like Option<T> but for holding a raw pointer
95 /// Like Option::None for Rawlink
96 fn none() -> Rawlink<T> {
97 Rawlink{p: ptr::null_mut()}
100 /// Like Option::Some for Rawlink
101 fn some(n: &mut T) -> Rawlink<T> {
105 /// Convert the `Rawlink` into an Option value
106 fn resolve_immut<'a>(&self) -> Option<&'a T> {
108 mem::transmute(self.p.as_ref())
112 /// Convert the `Rawlink` into an Option value
113 fn resolve<'a>(&mut self) -> Option<&'a mut T> {
114 if self.p.is_null() {
117 Some(unsafe { mem::transmute(self.p) })
121 /// Return the `Rawlink` and replace with `Rawlink::none()`
122 fn take(&mut self) -> Rawlink<T> {
123 mem::replace(self, Rawlink::none())
127 impl<T> Clone for Rawlink<T> {
129 fn clone(&self) -> Rawlink<T> {
135 fn new(v: T) -> Node<T> {
136 Node{value: v, next: None, prev: Rawlink::none()}
140 /// Set the .prev field on `next`, then return `Some(next)`
141 fn link_with_prev<T>(mut next: Box<Node<T>>, prev: Rawlink<Node<T>>)
149 /// Add a Node first in the list
151 fn push_front_node(&mut self, mut new_head: Box<Node<T>>) {
152 match self.list_head {
154 self.list_tail = Rawlink::some(&mut *new_head);
155 self.list_head = link_with_prev(new_head, Rawlink::none());
157 Some(ref mut head) => {
158 new_head.prev = Rawlink::none();
159 head.prev = Rawlink::some(&mut *new_head);
160 mem::swap(head, &mut new_head);
161 head.next = Some(new_head);
167 /// Remove the first Node and return it, or None if the list is empty
169 fn pop_front_node(&mut self) -> Option<Box<Node<T>>> {
170 self.list_head.take().map(|mut front_node| {
172 match front_node.next.take() {
173 Some(node) => self.list_head = link_with_prev(node, Rawlink::none()),
174 None => self.list_tail = Rawlink::none()
180 /// Add a Node last in the list
182 fn push_back_node(&mut self, mut new_tail: Box<Node<T>>) {
183 match self.list_tail.resolve() {
184 None => return self.push_front_node(new_tail),
186 self.list_tail = Rawlink::some(&mut *new_tail);
187 tail.next = link_with_prev(new_tail, Rawlink::some(tail));
193 /// Remove the last Node and return it, or None if the list is empty
195 fn pop_back_node(&mut self) -> Option<Box<Node<T>>> {
196 self.list_tail.resolve().map_or(None, |tail| {
198 self.list_tail = tail.prev;
199 match tail.prev.resolve() {
200 None => self.list_head.take(),
201 Some(tail_prev) => tail_prev.next.take()
208 impl<T> Default for DList<T> {
211 fn default() -> DList<T> { DList::new() }
215 /// Creates an empty `DList`.
218 pub fn new() -> DList<T> {
219 DList{list_head: None, list_tail: Rawlink::none(), length: 0}
222 /// Deprecated: Not clearly useful enough; use split and append when available.
223 #[deprecated = "Not clearly useful enough; use split and append when available"]
224 pub fn rotate_forward(&mut self) {
225 self.pop_back_node().map(|tail| {
226 self.push_front_node(tail)
230 /// Deprecated: Not clearly useful enough; use split and append when available.
231 #[deprecated = "Not clearly useful enough; use split and append when available"]
232 pub fn rotate_backward(&mut self) {
233 self.pop_front_node().map(|head| {
234 self.push_back_node(head)
238 /// Adds all elements from `other` to the end of the list.
240 /// This operation should compute in O(1) time.
245 /// use std::collections::DList;
247 /// let mut a = DList::new();
248 /// let mut b = DList::new();
256 /// for e in a.iter() {
257 /// println!("{}", e); // prints 1, then 2, then 3, then 4
260 #[unstable = "append should be by-mutable-reference"]
261 pub fn append(&mut self, mut other: DList<T>) {
262 match self.list_tail.resolve() {
263 None => *self = other,
265 // Carefully empty `other`.
266 let o_tail = other.list_tail.take();
267 let o_length = other.length;
268 match other.list_head.take() {
271 tail.next = link_with_prev(node, self.list_tail);
272 self.list_tail = o_tail;
273 self.length += o_length;
280 /// Deprecated: Use append and a swap instead.
281 #[deprecated = "Use append and a swap instead"]
282 pub fn prepend(&mut self, mut other: DList<T>) {
283 mem::swap(self, &mut other);
287 /// Deprecated: Use custom methods on IterMut.
288 #[deprecated = "Use custom methods on IterMut"]
289 pub fn insert_when<F>(&mut self, elt: T, mut f: F) where F: FnMut(&T, &T) -> bool {
290 let mut it = self.iter_mut();
292 match it.peek_next() {
294 Some(x) => if f(x, &elt) { break }
301 /// Deprecated: Use custom methods on IterMut.
302 #[deprecated = "Use custom methods on IterMut"]
303 pub fn merge<F>(&mut self, mut other: DList<T>, mut f: F) where F: FnMut(&T, &T) -> bool {
305 let mut it = self.iter_mut();
307 let take_a = match (it.peek_next(), other.front()) {
308 (_ , None) => return,
310 (Some(ref mut x), Some(y)) => f(*x, y),
315 it.insert_next_node(other.pop_front_node().unwrap());
323 /// Provides a forward iterator.
326 pub fn iter(&self) -> Iter<T> {
327 Iter{nelem: self.len(), head: &self.list_head, tail: self.list_tail}
330 /// Provides a forward iterator with mutable references.
333 pub fn iter_mut(&mut self) -> IterMut<T> {
334 let head_raw = match self.list_head {
335 Some(ref mut h) => Rawlink::some(&mut **h),
336 None => Rawlink::none(),
341 tail: self.list_tail,
346 /// Consumes the list into an iterator yielding elements by value.
349 pub fn into_iter(self) -> IntoIter<T> {
353 /// Returns `true` if the `DList` is empty.
355 /// This operation should compute in O(1) time.
358 pub fn is_empty(&self) -> bool {
359 self.list_head.is_none()
362 /// Returns the length of the `DList`.
364 /// This operation should compute in O(1) time.
367 pub fn len(&self) -> uint {
371 /// Removes all elements from the `DList`.
373 /// This operation should compute in O(n) time.
376 pub fn clear(&mut self) {
380 /// Provides a reference to the front element, or `None` if the list is
384 pub fn front(&self) -> Option<&T> {
385 self.list_head.as_ref().map(|head| &head.value)
388 /// Provides a mutable reference to the front element, or `None` if the list
392 pub fn front_mut(&mut self) -> Option<&mut T> {
393 self.list_head.as_mut().map(|head| &mut head.value)
396 /// Provides a reference to the back element, or `None` if the list is
400 pub fn back(&self) -> Option<&T> {
401 self.list_tail.resolve_immut().as_ref().map(|tail| &tail.value)
404 /// Provides a mutable reference to the back element, or `None` if the list
408 pub fn back_mut(&mut self) -> Option<&mut T> {
409 self.list_tail.resolve().map(|tail| &mut tail.value)
412 /// Adds an element first in the list.
414 /// This operation should compute in O(1) time.
416 pub fn push_front(&mut self, elt: T) {
417 self.push_front_node(box Node::new(elt))
420 /// Removes the first element and returns it, or `None` if the list is
423 /// This operation should compute in O(1) time.
425 pub fn pop_front(&mut self) -> Option<T> {
426 self.pop_front_node().map(|box Node{value, ..}| value)
429 /// Deprecated: Renamed to `push_back`.
430 #[deprecated = "Renamed to `push_back`"]
431 pub fn push(&mut self, elt: T) {
435 /// Appends an element to the back of a list
440 /// use std::collections::DList;
442 /// let mut d = DList::new();
445 /// assert_eq!(3, *d.back().unwrap());
448 pub fn push_back(&mut self, elt: T) {
449 self.push_back_node(box Node::new(elt))
452 /// Deprecated: Renamed to `pop_back`.
453 #[deprecated = "Renamed to `pop_back`"]
454 pub fn pop(&mut self) -> Option<T> {
458 /// Removes the last element from a list and returns it, or `None` if
464 /// use std::collections::DList;
466 /// let mut d = DList::new();
467 /// assert_eq!(d.pop_back(), None);
470 /// assert_eq!(d.pop_back(), Some(3));
473 pub fn pop_back(&mut self) -> Option<T> {
474 self.pop_back_node().map(|box Node{value, ..}| value)
478 impl<T: Ord> DList<T> {
479 /// Deprecated: Why are you maintaining a sorted DList?
480 #[deprecated = "Why are you maintaining a sorted DList?"]
482 pub fn insert_ordered(&mut self, elt: T) {
483 self.insert_when(elt, |a, b| a >= b)
489 impl<T> Drop for DList<T> {
491 // Dissolve the dlist in backwards direction
492 // Just dropping the list_head can lead to stack exhaustion
493 // when length is >> 1_000_000
494 let mut tail = self.list_tail;
496 match tail.resolve() {
499 prev.next.take(); // release Box<Node<T>>
505 self.list_head = None;
506 self.list_tail = Rawlink::none();
511 impl<'a, A> Iterator for Iter<'a, A> {
515 fn next(&mut self) -> Option<&'a A> {
519 self.head.as_ref().map(|head| {
521 self.head = &head.next;
527 fn size_hint(&self) -> (uint, Option<uint>) {
528 (self.nelem, Some(self.nelem))
533 impl<'a, A> DoubleEndedIterator for Iter<'a, A> {
535 fn next_back(&mut self) -> Option<&'a A> {
539 self.tail.resolve_immut().as_ref().map(|prev| {
541 self.tail = prev.prev;
548 impl<'a, A> ExactSizeIterator for Iter<'a, A> {}
551 impl<'a, A> Iterator for IterMut<'a, A> {
552 type Item = &'a mut A;
554 fn next(&mut self) -> Option<&'a mut A> {
558 self.head.resolve().map(|next| {
560 self.head = match next.next {
561 Some(ref mut node) => Rawlink::some(&mut **node),
562 None => Rawlink::none(),
569 fn size_hint(&self) -> (uint, Option<uint>) {
570 (self.nelem, Some(self.nelem))
575 impl<'a, A> DoubleEndedIterator for IterMut<'a, A> {
577 fn next_back(&mut self) -> Option<&'a mut A> {
581 self.tail.resolve().map(|prev| {
583 self.tail = prev.prev;
590 impl<'a, A> ExactSizeIterator for IterMut<'a, A> {}
592 /// Allows mutating a `DList` while iterating.
593 #[deprecated = "Trait is deprecated, use inherent methods on the iterator instead"]
594 pub trait ListInsertion<A> {
595 /// Inserts `elt` just after to the element most recently returned by
598 /// The inserted element does not appear in the iteration.
599 fn insert_next(&mut self, elt: A);
601 /// Provides a reference to the next element, without changing the iterator
602 fn peek_next<'a>(&'a mut self) -> Option<&'a mut A>;
605 // private methods for IterMut
606 impl<'a, A> IterMut<'a, A> {
607 fn insert_next_node(&mut self, mut ins_node: Box<Node<A>>) {
608 // Insert before `self.head` so that it is between the
609 // previously yielded element and self.head.
611 // The inserted node will not appear in further iteration.
612 match self.head.resolve() {
613 None => { self.list.push_back_node(ins_node); }
615 let prev_node = match node.prev.resolve() {
616 None => return self.list.push_front_node(ins_node),
619 let node_own = prev_node.next.take().unwrap();
620 ins_node.next = link_with_prev(node_own, Rawlink::some(&mut *ins_node));
621 prev_node.next = link_with_prev(ins_node, Rawlink::some(prev_node));
622 self.list.length += 1;
628 impl<'a, A> IterMut<'a, A> {
629 /// Inserts `elt` just after the element most recently returned by `.next()`.
630 /// The inserted element does not appear in the iteration.
635 /// use std::collections::DList;
637 /// let mut list: DList<int> = vec![1, 3, 4].into_iter().collect();
640 /// let mut it = list.iter_mut();
641 /// assert_eq!(it.next().unwrap(), &1);
642 /// // insert `2` after `1`
643 /// it.insert_next(2);
646 /// let vec: Vec<int> = list.into_iter().collect();
647 /// assert_eq!(vec, vec![1i, 2, 3, 4]);
651 #[unstable = "this is probably better handled by a cursor type -- we'll see"]
652 pub fn insert_next(&mut self, elt: A) {
653 self.insert_next_node(box Node::new(elt))
656 /// Provides a reference to the next element, without changing the iterator.
661 /// use std::collections::DList;
663 /// let mut list: DList<int> = vec![1, 2, 3].into_iter().collect();
665 /// let mut it = list.iter_mut();
666 /// assert_eq!(it.next().unwrap(), &1);
667 /// assert_eq!(it.peek_next().unwrap(), &2);
668 /// // We just peeked at 2, so it was not consumed from the iterator.
669 /// assert_eq!(it.next().unwrap(), &2);
672 #[unstable = "this is probably better handled by a cursor type -- we'll see"]
673 pub fn peek_next(&mut self) -> Option<&mut A> {
677 self.head.resolve().map(|head| &mut head.value)
682 impl<A> Iterator for IntoIter<A> {
686 fn next(&mut self) -> Option<A> { self.list.pop_front() }
689 fn size_hint(&self) -> (uint, Option<uint>) {
690 (self.list.length, Some(self.list.length))
695 impl<A> DoubleEndedIterator for IntoIter<A> {
697 fn next_back(&mut self) -> Option<A> { self.list.pop_back() }
701 impl<A> FromIterator<A> for DList<A> {
702 fn from_iter<T: Iterator<Item=A>>(iterator: T) -> DList<A> {
703 let mut ret = DList::new();
704 ret.extend(iterator);
710 impl<A> Extend<A> for DList<A> {
711 fn extend<T: Iterator<Item=A>>(&mut self, mut iterator: T) {
712 for elt in iterator { self.push_back(elt); }
717 impl<A: PartialEq> PartialEq for DList<A> {
718 fn eq(&self, other: &DList<A>) -> bool {
719 self.len() == other.len() &&
720 iter::order::eq(self.iter(), other.iter())
723 fn ne(&self, other: &DList<A>) -> bool {
724 self.len() != other.len() ||
725 iter::order::ne(self.iter(), other.iter())
730 impl<A: Eq> Eq for DList<A> {}
733 impl<A: PartialOrd> PartialOrd for DList<A> {
734 fn partial_cmp(&self, other: &DList<A>) -> Option<Ordering> {
735 iter::order::partial_cmp(self.iter(), other.iter())
740 impl<A: Ord> Ord for DList<A> {
742 fn cmp(&self, other: &DList<A>) -> Ordering {
743 iter::order::cmp(self.iter(), other.iter())
748 impl<A: Clone> Clone for DList<A> {
749 fn clone(&self) -> DList<A> {
750 self.iter().map(|x| x.clone()).collect()
755 impl<A: fmt::Show> fmt::Show for DList<A> {
756 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
757 try!(write!(f, "["));
759 for (i, e) in self.iter().enumerate() {
760 if i != 0 { try!(write!(f, ", ")); }
761 try!(write!(f, "{}", *e));
769 impl<S: Writer, A: Hash<S>> Hash<S> for DList<A> {
770 fn hash(&self, state: &mut S) {
771 self.len().hash(state);
772 for elt in self.iter() {
783 use std::task::spawn;
787 use super::{DList, Node};
789 pub fn check_links<T>(list: &DList<T>) {
791 let mut last_ptr: Option<&Node<T>> = None;
792 let mut node_ptr: &Node<T>;
793 match list.list_head {
794 None => { assert_eq!(0u, list.length); return }
795 Some(ref node) => node_ptr = &**node,
798 match (last_ptr, node_ptr.prev.resolve_immut()) {
800 (None , _ ) => panic!("prev link for list_head"),
801 (Some(p), Some(pptr)) => {
802 assert_eq!(p as *const Node<T>, pptr as *const Node<T>);
804 _ => panic!("prev link is none, not good"),
806 match node_ptr.next {
808 last_ptr = Some(node_ptr);
818 assert_eq!(len, list.length);
823 let mut m: DList<Box<int>> = DList::new();
824 assert_eq!(m.pop_front(), None);
825 assert_eq!(m.pop_back(), None);
826 assert_eq!(m.pop_front(), None);
828 assert_eq!(m.pop_front(), Some(box 1));
831 assert_eq!(m.len(), 2);
832 assert_eq!(m.pop_front(), Some(box 2));
833 assert_eq!(m.pop_front(), Some(box 3));
834 assert_eq!(m.len(), 0);
835 assert_eq!(m.pop_front(), None);
840 assert_eq!(m.pop_front(), Some(box 1));
842 let mut n = DList::new();
846 assert_eq!(n.front().unwrap(), &3);
847 let x = n.front_mut().unwrap();
852 assert_eq!(n.back().unwrap(), &2);
853 let y = n.back_mut().unwrap();
857 assert_eq!(n.pop_front(), Some(0));
858 assert_eq!(n.pop_front(), Some(1));
862 fn generate_test() -> DList<int> {
863 list_from(&[0i,1,2,3,4,5,6])
867 fn list_from<T: Clone>(v: &[T]) -> DList<T> {
868 v.iter().map(|x| (*x).clone()).collect()
875 let mut m = DList::new();
876 let mut n = DList::new();
879 assert_eq!(m.len(), 1);
880 assert_eq!(m.pop_back(), Some(2));
884 let mut m = DList::new();
885 let n = DList::new();
888 assert_eq!(m.len(), 1);
889 assert_eq!(m.pop_back(), Some(2));
893 let v = vec![1i,2,3,4,5];
894 let u = vec![9i,8,1,2,3,4,5];
895 let mut m = list_from(v.as_slice());
896 m.append(list_from(u.as_slice()));
899 sum.push_all(u.as_slice());
900 assert_eq!(sum.len(), m.len());
901 for elt in sum.into_iter() {
902 assert_eq!(m.pop_front(), Some(elt))
909 let mut m = DList::new();
910 let mut n = DList::new();
913 assert_eq!(m.len(), 1);
914 assert_eq!(m.pop_back(), Some(2));
918 let v = vec![1i,2,3,4,5];
919 let mut u = vec![9i,8,1,2,3,4,5];
920 let mut m = list_from(v.as_slice());
921 m.prepend(list_from(u.as_slice()));
923 u.extend(v.iter().map(|&b| b));
924 assert_eq!(u.len(), m.len());
925 for elt in u.into_iter() {
926 assert_eq!(m.pop_front(), Some(elt))
932 let mut n: DList<int> = DList::new();
933 n.rotate_backward(); check_links(&n);
934 assert_eq!(n.len(), 0);
935 n.rotate_forward(); check_links(&n);
936 assert_eq!(n.len(), 0);
938 let v = vec![1i,2,3,4,5];
939 let mut m = list_from(v.as_slice());
940 m.rotate_backward(); check_links(&m);
941 m.rotate_forward(); check_links(&m);
942 assert_eq!(v.iter().collect::<Vec<&int>>(), m.iter().collect::<Vec<_>>());
943 m.rotate_forward(); check_links(&m);
944 m.rotate_forward(); check_links(&m);
945 m.pop_front(); check_links(&m);
946 m.rotate_forward(); check_links(&m);
947 m.rotate_backward(); check_links(&m);
948 m.push_front(9); check_links(&m);
949 m.rotate_forward(); check_links(&m);
950 assert_eq!(vec![3i,9,5,1,2], m.into_iter().collect::<Vec<_>>());
955 let m = generate_test();
956 for (i, elt) in m.iter().enumerate() {
957 assert_eq!(i as int, *elt);
959 let mut n = DList::new();
960 assert_eq!(n.iter().next(), None);
962 let mut it = n.iter();
963 assert_eq!(it.size_hint(), (1, Some(1)));
964 assert_eq!(it.next().unwrap(), &4);
965 assert_eq!(it.size_hint(), (0, Some(0)));
966 assert_eq!(it.next(), None);
970 fn test_iterator_clone() {
971 let mut n = DList::new();
975 let mut it = n.iter();
977 let mut jt = it.clone();
978 assert_eq!(it.next(), jt.next());
979 assert_eq!(it.next_back(), jt.next_back());
980 assert_eq!(it.next(), jt.next());
984 fn test_iterator_double_end() {
985 let mut n = DList::new();
986 assert_eq!(n.iter().next(), None);
990 let mut it = n.iter();
991 assert_eq!(it.size_hint(), (3, Some(3)));
992 assert_eq!(it.next().unwrap(), &6);
993 assert_eq!(it.size_hint(), (2, Some(2)));
994 assert_eq!(it.next_back().unwrap(), &4);
995 assert_eq!(it.size_hint(), (1, Some(1)));
996 assert_eq!(it.next_back().unwrap(), &5);
997 assert_eq!(it.next_back(), None);
998 assert_eq!(it.next(), None);
1002 fn test_rev_iter() {
1003 let m = generate_test();
1004 for (i, elt) in m.iter().rev().enumerate() {
1005 assert_eq!((6 - i) as int, *elt);
1007 let mut n = DList::new();
1008 assert_eq!(n.iter().rev().next(), None);
1010 let mut it = n.iter().rev();
1011 assert_eq!(it.size_hint(), (1, Some(1)));
1012 assert_eq!(it.next().unwrap(), &4);
1013 assert_eq!(it.size_hint(), (0, Some(0)));
1014 assert_eq!(it.next(), None);
1018 fn test_mut_iter() {
1019 let mut m = generate_test();
1020 let mut len = m.len();
1021 for (i, elt) in m.iter_mut().enumerate() {
1022 assert_eq!(i as int, *elt);
1026 let mut n = DList::new();
1027 assert!(n.iter_mut().next().is_none());
1030 let mut it = n.iter_mut();
1031 assert_eq!(it.size_hint(), (2, Some(2)));
1032 assert!(it.next().is_some());
1033 assert!(it.next().is_some());
1034 assert_eq!(it.size_hint(), (0, Some(0)));
1035 assert!(it.next().is_none());
1039 fn test_iterator_mut_double_end() {
1040 let mut n = DList::new();
1041 assert!(n.iter_mut().next_back().is_none());
1045 let mut it = n.iter_mut();
1046 assert_eq!(it.size_hint(), (3, Some(3)));
1047 assert_eq!(*it.next().unwrap(), 6);
1048 assert_eq!(it.size_hint(), (2, Some(2)));
1049 assert_eq!(*it.next_back().unwrap(), 4);
1050 assert_eq!(it.size_hint(), (1, Some(1)));
1051 assert_eq!(*it.next_back().unwrap(), 5);
1052 assert!(it.next_back().is_none());
1053 assert!(it.next().is_none());
1057 fn test_insert_prev() {
1058 let mut m = list_from(&[0i,2,4,6,8]);
1061 let mut it = m.iter_mut();
1067 it.insert_next(*elt + 1);
1068 match it.peek_next() {
1069 Some(x) => assert_eq!(*x, *elt + 2),
1070 None => assert_eq!(8, *elt),
1079 assert_eq!(m.len(), 3 + len * 2);
1080 assert_eq!(m.into_iter().collect::<Vec<int>>(), vec![-2,0,1,2,3,4,5,6,7,8,9,0,1]);
1085 let mut m = list_from(&[0i, 1, 3, 5, 6, 7, 2]);
1086 let n = list_from(&[-1i, 0, 0, 7, 7, 9]);
1087 let len = m.len() + n.len();
1088 m.merge(n, |a, b| a <= b);
1089 assert_eq!(m.len(), len);
1091 let res = m.into_iter().collect::<Vec<int>>();
1092 assert_eq!(res, vec![-1, 0, 0, 0, 1, 3, 5, 6, 7, 2, 7, 7, 9]);
1096 fn test_insert_ordered() {
1097 let mut n = DList::new();
1098 n.insert_ordered(1i);
1099 assert_eq!(n.len(), 1);
1100 assert_eq!(n.pop_front(), Some(1));
1102 let mut m = DList::new();
1105 m.insert_ordered(3);
1107 assert_eq!(vec![2,3,4], m.into_iter().collect::<Vec<int>>());
1111 fn test_mut_rev_iter() {
1112 let mut m = generate_test();
1113 for (i, elt) in m.iter_mut().rev().enumerate() {
1114 assert_eq!((6-i) as int, *elt);
1116 let mut n = DList::new();
1117 assert!(n.iter_mut().rev().next().is_none());
1119 let mut it = n.iter_mut().rev();
1120 assert!(it.next().is_some());
1121 assert!(it.next().is_none());
1126 let n = list_from(&[1i,2,3]);
1129 let a: &[_] = &[&1,&2,&3];
1130 assert_eq!(a, n.iter().collect::<Vec<&int>>());
1136 let mut n: DList<u8> = list_from(&[]);
1137 let mut m = list_from(&[]);
1144 let n = list_from(&[2i,3,4]);
1145 let m = list_from(&[1i,2,3]);
1151 let mut x = DList::new();
1152 let mut y = DList::new();
1154 assert!(hash::hash(&x) == hash::hash(&y));
1164 assert!(hash::hash(&x) == hash::hash(&y));
1169 let n: DList<int> = list_from(&[]);
1170 let m = list_from(&[1i,2,3]);
1179 let nan = 0.0f64/0.0;
1180 let n = list_from(&[nan]);
1181 let m = list_from(&[nan]);
1187 let n = list_from(&[nan]);
1188 let one = list_from(&[1.0f64]);
1189 assert!(!(n < one));
1190 assert!(!(n > one));
1191 assert!(!(n <= one));
1192 assert!(!(n >= one));
1194 let u = list_from(&[1.0f64,2.0,nan]);
1195 let v = list_from(&[1.0f64,2.0,3.0]);
1201 let s = list_from(&[1.0f64,2.0,4.0,2.0]);
1202 let t = list_from(&[1.0f64,2.0,3.0,2.0]);
1205 assert!(!(s <= one));
1211 for _ in range(0u, 25) {
1220 let list: DList<int> = range(0i, 10).collect();
1221 assert!(list.to_string() == "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]");
1223 let list: DList<&str> = vec!["just", "one", "test", "more"].iter()
1226 assert!(list.to_string() == "[just, one, test, more]");
1230 fn fuzz_test(sz: int) {
1231 let mut m: DList<int> = DList::new();
1233 for i in range(0, sz) {
1235 let r: u8 = rand::random();
1261 for (a, &b) in m.into_iter().zip(v.iter()) {
1265 assert_eq!(i, v.len());
1269 fn bench_collect_into(b: &mut test::Bencher) {
1272 let _: DList<int> = v.iter().map(|x| *x).collect();
1277 fn bench_push_front(b: &mut test::Bencher) {
1278 let mut m: DList<int> = DList::new();
1285 fn bench_push_back(b: &mut test::Bencher) {
1286 let mut m: DList<int> = DList::new();
1293 fn bench_push_back_pop_back(b: &mut test::Bencher) {
1294 let mut m: DList<int> = DList::new();
1302 fn bench_push_front_pop_front(b: &mut test::Bencher) {
1303 let mut m: DList<int> = DList::new();
1311 fn bench_rotate_forward(b: &mut test::Bencher) {
1312 let mut m: DList<int> = DList::new();
1321 fn bench_rotate_backward(b: &mut test::Bencher) {
1322 let mut m: DList<int> = DList::new();
1326 m.rotate_backward();
1331 fn bench_iter(b: &mut test::Bencher) {
1333 let m: DList<int> = v.iter().map(|&x|x).collect();
1335 assert!(m.iter().count() == 128);
1339 fn bench_iter_mut(b: &mut test::Bencher) {
1341 let mut m: DList<int> = v.iter().map(|&x|x).collect();
1343 assert!(m.iter_mut().count() == 128);
1347 fn bench_iter_rev(b: &mut test::Bencher) {
1349 let m: DList<int> = v.iter().map(|&x|x).collect();
1351 assert!(m.iter().rev().count() == 128);
1355 fn bench_iter_mut_rev(b: &mut test::Bencher) {
1357 let mut m: DList<int> = v.iter().map(|&x|x).collect();
1359 assert!(m.iter_mut().rev().count() == 128);