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::default::Default;
30 use std::hash::{Writer, Hash};
32 /// A doubly-linked list.
36 list_tail: Rawlink<Node<T>>,
39 type Link<T> = Option<Box<Node<T>>>;
45 impl<T> Copy for Rawlink<T> {}
46 unsafe impl<T:'static+Send> Send for Rawlink<T> {}
47 unsafe impl<T:Send+Sync> Sync for Rawlink<T> {}
51 prev: Rawlink<Node<T>>,
55 /// An iterator over references to the items of a `DList`.
56 pub struct Iter<'a, T:'a> {
58 tail: Rawlink<Node<T>>,
62 // FIXME #11820: the &'a Option<> of the Link stops clone working.
63 impl<'a, T> Clone for Iter<'a, T> {
64 fn clone(&self) -> Iter<'a, T> { *self }
67 impl<'a,T> Copy for Iter<'a,T> {}
69 /// An iterator over mutable references to the items of a `DList`.
70 pub struct IterMut<'a, T:'a> {
71 list: &'a mut DList<T>,
72 head: Rawlink<Node<T>>,
73 tail: Rawlink<Node<T>>,
77 /// An iterator over mutable references to the items of a `DList`.
79 pub struct IntoIter<T> {
83 /// Rawlink is a type like Option<T> but for holding a raw pointer
85 /// Like Option::None for Rawlink
86 fn none() -> Rawlink<T> {
87 Rawlink{p: ptr::null_mut()}
90 /// Like Option::Some for Rawlink
91 fn some(n: &mut T) -> Rawlink<T> {
95 /// Convert the `Rawlink` into an Option value
96 fn resolve_immut<'a>(&self) -> Option<&'a T> {
98 mem::transmute(self.p.as_ref())
102 /// Convert the `Rawlink` into an Option value
103 fn resolve<'a>(&mut self) -> Option<&'a mut T> {
104 if self.p.is_null() {
107 Some(unsafe { mem::transmute(self.p) })
111 /// Return the `Rawlink` and replace with `Rawlink::none()`
112 fn take(&mut self) -> Rawlink<T> {
113 mem::replace(self, Rawlink::none())
117 impl<T> Clone for Rawlink<T> {
119 fn clone(&self) -> Rawlink<T> {
125 fn new(v: T) -> Node<T> {
126 Node{value: v, next: None, prev: Rawlink::none()}
130 /// Set the .prev field on `next`, then return `Some(next)`
131 fn link_with_prev<T>(mut next: Box<Node<T>>, prev: Rawlink<Node<T>>)
139 /// Add a Node first in the list
141 fn push_front_node(&mut self, mut new_head: Box<Node<T>>) {
142 match self.list_head {
144 self.list_tail = Rawlink::some(&mut *new_head);
145 self.list_head = link_with_prev(new_head, Rawlink::none());
147 Some(ref mut head) => {
148 new_head.prev = Rawlink::none();
149 head.prev = Rawlink::some(&mut *new_head);
150 mem::swap(head, &mut new_head);
151 head.next = Some(new_head);
157 /// Remove the first Node and return it, or None if the list is empty
159 fn pop_front_node(&mut self) -> Option<Box<Node<T>>> {
160 self.list_head.take().map(|mut front_node| {
162 match front_node.next.take() {
163 Some(node) => self.list_head = link_with_prev(node, Rawlink::none()),
164 None => self.list_tail = Rawlink::none()
170 /// Add a Node last in the list
172 fn push_back_node(&mut self, mut new_tail: Box<Node<T>>) {
173 match self.list_tail.resolve() {
174 None => return self.push_front_node(new_tail),
176 self.list_tail = Rawlink::some(&mut *new_tail);
177 tail.next = link_with_prev(new_tail, Rawlink::some(tail));
183 /// Remove the last Node and return it, or None if the list is empty
185 fn pop_back_node(&mut self) -> Option<Box<Node<T>>> {
186 self.list_tail.resolve().map_or(None, |tail| {
188 self.list_tail = tail.prev;
189 match tail.prev.resolve() {
190 None => self.list_head.take(),
191 Some(tail_prev) => tail_prev.next.take()
198 impl<T> Default for DList<T> {
201 fn default() -> DList<T> { DList::new() }
205 /// Creates an empty `DList`.
207 #[unstable = "matches collection reform specification, waiting for dust to settle"]
208 pub fn new() -> DList<T> {
209 DList{list_head: None, list_tail: Rawlink::none(), length: 0}
212 /// Moves the last element to the front of the list.
214 /// If the list is empty, does nothing.
219 /// use std::collections::DList;
221 /// let mut dl = DList::new();
222 /// dl.push_back(1i);
226 /// dl.rotate_forward();
228 /// for e in dl.iter() {
229 /// println!("{}", e); // prints 3, then 1, then 2
233 pub fn rotate_forward(&mut self) {
234 self.pop_back_node().map(|tail| {
235 self.push_front_node(tail)
239 /// Moves the first element to the back of the list.
241 /// If the list is empty, does nothing.
246 /// use std::collections::DList;
248 /// let mut dl = DList::new();
249 /// dl.push_back(1i);
253 /// dl.rotate_backward();
255 /// for e in dl.iter() {
256 /// println!("{}", e); // prints 2, then 3, then 1
260 pub fn rotate_backward(&mut self) {
261 self.pop_front_node().map(|head| {
262 self.push_back_node(head)
266 /// Adds all elements from `other` to the end of the list.
268 /// This operation should compute in O(1) time.
273 /// use std::collections::DList;
275 /// let mut a = DList::new();
276 /// let mut b = DList::new();
284 /// for e in a.iter() {
285 /// println!("{}", e); // prints 1, then 2, then 3, then 4
288 pub fn append(&mut self, mut other: DList<T>) {
289 match self.list_tail.resolve() {
290 None => *self = other,
292 // Carefully empty `other`.
293 let o_tail = other.list_tail.take();
294 let o_length = other.length;
295 match other.list_head.take() {
298 tail.next = link_with_prev(node, self.list_tail);
299 self.list_tail = o_tail;
300 self.length += o_length;
307 /// Adds all elements from `other` to the beginning of the list.
309 /// This operation should compute in O(1) time.
314 /// use std::collections::DList;
316 /// let mut a = DList::new();
317 /// let mut b = DList::new();
325 /// for e in a.iter() {
326 /// println!("{}", e); // prints 3, then 4, then 1, then 2
330 pub fn prepend(&mut self, mut other: DList<T>) {
331 mem::swap(self, &mut other);
335 /// Inserts `elt` before the first `x` in the list where `f(x, elt)` is
336 /// true, or at the end.
338 /// This operation should compute in O(N) time.
343 /// use std::collections::DList;
345 /// let mut a: DList<int> = DList::new();
351 /// // insert 11 before the first odd number in the list
352 /// a.insert_when(11, |&e, _| e % 2 == 1);
354 /// for e in a.iter() {
355 /// println!("{}", e); // prints 2, then 4, then 11, then 7, then 8
358 pub fn insert_when<F>(&mut self, elt: T, mut f: F) where F: FnMut(&T, &T) -> bool {
359 let mut it = self.iter_mut();
361 match it.peek_next() {
363 Some(x) => if f(x, &elt) { break }
370 /// Merges `other` into this `DList`, using the function `f`.
372 /// Iterates both `DList`s with `a` from self and `b` from `other`, and
373 /// put `a` in the result if `f(a, b)` is true, and otherwise `b`.
375 /// This operation should compute in O(max(N, M)) time.
376 pub fn merge<F>(&mut self, mut other: DList<T>, mut f: F) where F: FnMut(&T, &T) -> bool {
378 let mut it = self.iter_mut();
380 let take_a = match (it.peek_next(), other.front()) {
381 (_ , None) => return,
383 (Some(ref mut x), Some(y)) => f(*x, y),
388 it.insert_next_node(other.pop_front_node().unwrap());
396 /// Provides a forward iterator.
398 #[unstable = "matches collection reform specification, waiting for dust to settle"]
399 pub fn iter<'a>(&'a self) -> Iter<'a, T> {
400 Iter{nelem: self.len(), head: &self.list_head, tail: self.list_tail}
403 /// Provides a forward iterator with mutable references.
405 #[unstable = "matches collection reform specification, waiting for dust to settle"]
406 pub fn iter_mut<'a>(&'a mut self) -> IterMut<'a, T> {
407 let head_raw = match self.list_head {
408 Some(ref mut h) => Rawlink::some(&mut **h),
409 None => Rawlink::none(),
414 tail: self.list_tail,
419 /// Consumes the list into an iterator yielding elements by value.
421 #[unstable = "matches collection reform specification, waiting for dust to settle"]
422 pub fn into_iter(self) -> IntoIter<T> {
426 /// Returns `true` if the `DList` is empty.
428 /// This operation should compute in O(1) time.
430 #[unstable = "matches collection reform specification, waiting for dust to settle"]
431 pub fn is_empty(&self) -> bool {
432 self.list_head.is_none()
435 /// Returns the length of the `DList`.
437 /// This operation should compute in O(1) time.
439 #[unstable = "matches collection reform specification, waiting for dust to settle"]
440 pub fn len(&self) -> uint {
444 /// Removes all elements from the `DList`.
446 /// This operation should compute in O(n) time.
448 #[unstable = "matches collection reform specification, waiting for dust to settle"]
449 pub fn clear(&mut self) {
453 /// Provides a reference to the front element, or `None` if the list is
457 pub fn front(&self) -> Option<&T> {
458 self.list_head.as_ref().map(|head| &head.value)
461 /// Provides a mutable reference to the front element, or `None` if the list
465 pub fn front_mut(&mut self) -> Option<&mut T> {
466 self.list_head.as_mut().map(|head| &mut head.value)
469 /// Provides a reference to the back element, or `None` if the list is
473 pub fn back(&self) -> Option<&T> {
474 self.list_tail.resolve_immut().as_ref().map(|tail| &tail.value)
477 /// Provides a mutable reference to the back element, or `None` if the list
481 pub fn back_mut(&mut self) -> Option<&mut T> {
482 self.list_tail.resolve().map(|tail| &mut tail.value)
485 /// Adds an element first in the list.
487 /// This operation should compute in O(1) time.
488 #[unstable = "matches collection reform specification, waiting for dust to settle"]
489 pub fn push_front(&mut self, elt: T) {
490 self.push_front_node(box Node::new(elt))
493 /// Removes the first element and returns it, or `None` if the list is
496 /// This operation should compute in O(1) time.
497 #[unstable = "matches collection reform specification, waiting for dust to settle"]
498 pub fn pop_front(&mut self) -> Option<T> {
499 self.pop_front_node().map(|box Node{value, ..}| value)
502 /// Deprecated: Renamed to `push_back`.
503 #[deprecated = "Renamed to `push_back`"]
504 pub fn push(&mut self, elt: T) {
508 /// Appends an element to the back of a list
513 /// use std::collections::DList;
515 /// let mut d = DList::new();
518 /// assert_eq!(3, *d.back().unwrap());
520 #[unstable = "matches collection reform specification, waiting for dust to settle"]
521 pub fn push_back(&mut self, elt: T) {
522 self.push_back_node(box Node::new(elt))
525 /// Deprecated: Renamed to `pop_back`.
526 #[deprecated = "Renamed to `pop_back`"]
527 pub fn pop(&mut self) -> Option<T> {
531 /// Removes the last element from a list and returns it, or `None` if
537 /// use std::collections::DList;
539 /// let mut d = DList::new();
540 /// assert_eq!(d.pop_back(), None);
543 /// assert_eq!(d.pop_back(), Some(3));
545 #[unstable = "matches collection reform specification, waiting for dust to settle"]
546 pub fn pop_back(&mut self) -> Option<T> {
547 self.pop_back_node().map(|box Node{value, ..}| value)
551 impl<T: Ord> DList<T> {
552 /// Inserts `elt` sorted in ascending order.
554 /// This operation should compute in O(N) time.
556 pub fn insert_ordered(&mut self, elt: T) {
557 self.insert_when(elt, |a, b| a >= b)
562 impl<T> Drop for DList<T> {
564 // Dissolve the dlist in backwards direction
565 // Just dropping the list_head can lead to stack exhaustion
566 // when length is >> 1_000_000
567 let mut tail = self.list_tail;
569 match tail.resolve() {
572 prev.next.take(); // release Box<Node<T>>
578 self.list_head = None;
579 self.list_tail = Rawlink::none();
584 impl<'a, A> Iterator<&'a A> for Iter<'a, A> {
586 fn next(&mut self) -> Option<&'a A> {
590 self.head.as_ref().map(|head| {
592 self.head = &head.next;
598 fn size_hint(&self) -> (uint, Option<uint>) {
599 (self.nelem, Some(self.nelem))
603 impl<'a, A> DoubleEndedIterator<&'a A> for Iter<'a, A> {
605 fn next_back(&mut self) -> Option<&'a A> {
609 self.tail.resolve_immut().as_ref().map(|prev| {
611 self.tail = prev.prev;
617 impl<'a, A> ExactSizeIterator<&'a A> for Iter<'a, A> {}
619 impl<'a, A> Iterator<&'a mut A> for IterMut<'a, A> {
621 fn next(&mut self) -> Option<&'a mut A> {
625 self.head.resolve().map(|next| {
627 self.head = match next.next {
628 Some(ref mut node) => Rawlink::some(&mut **node),
629 None => Rawlink::none(),
636 fn size_hint(&self) -> (uint, Option<uint>) {
637 (self.nelem, Some(self.nelem))
641 impl<'a, A> DoubleEndedIterator<&'a mut A> for IterMut<'a, A> {
643 fn next_back(&mut self) -> Option<&'a mut A> {
647 self.tail.resolve().map(|prev| {
649 self.tail = prev.prev;
655 impl<'a, A> ExactSizeIterator<&'a mut A> for IterMut<'a, A> {}
657 /// Allows mutating a `DList` while iterating.
658 #[deprecated = "Trait is deprecated, use inherent methods on the iterator instead"]
659 pub trait ListInsertion<A> {
660 /// Inserts `elt` just after to the element most recently returned by
663 /// The inserted element does not appear in the iteration.
664 fn insert_next(&mut self, elt: A);
666 /// Provides a reference to the next element, without changing the iterator
667 fn peek_next<'a>(&'a mut self) -> Option<&'a mut A>;
670 // private methods for IterMut
671 impl<'a, A> IterMut<'a, A> {
672 fn insert_next_node(&mut self, mut ins_node: Box<Node<A>>) {
673 // Insert before `self.head` so that it is between the
674 // previously yielded element and self.head.
676 // The inserted node will not appear in further iteration.
677 match self.head.resolve() {
678 None => { self.list.push_back_node(ins_node); }
680 let prev_node = match node.prev.resolve() {
681 None => return self.list.push_front_node(ins_node),
684 let node_own = prev_node.next.take().unwrap();
685 ins_node.next = link_with_prev(node_own, Rawlink::some(&mut *ins_node));
686 prev_node.next = link_with_prev(ins_node, Rawlink::some(prev_node));
687 self.list.length += 1;
693 impl<'a, A> IterMut<'a, A> {
694 /// Inserts `elt` just after the element most recently returned by `.next()`.
695 /// The inserted element does not appear in the iteration.
700 /// use std::collections::DList;
702 /// let mut list: DList<int> = vec![1, 3, 4].into_iter().collect();
705 /// let mut it = list.iter_mut();
706 /// assert_eq!(it.next().unwrap(), &1);
707 /// // insert `2` after `1`
708 /// it.insert_next(2);
711 /// let vec: Vec<int> = list.into_iter().collect();
712 /// assert_eq!(vec, vec![1i, 2, 3, 4]);
716 pub fn insert_next(&mut self, elt: A) {
717 self.insert_next_node(box Node::new(elt))
720 /// Provides a reference to the next element, without changing the iterator.
725 /// use std::collections::DList;
727 /// let mut list: DList<int> = vec![1, 2, 3].into_iter().collect();
729 /// let mut it = list.iter_mut();
730 /// assert_eq!(it.next().unwrap(), &1);
731 /// assert_eq!(it.peek_next().unwrap(), &2);
732 /// // We just peeked at 2, so it was not consumed from the iterator.
733 /// assert_eq!(it.next().unwrap(), &2);
736 pub fn peek_next(&mut self) -> Option<&mut A> {
740 self.head.resolve().map(|head| &mut head.value)
744 impl<A> Iterator<A> for IntoIter<A> {
746 fn next(&mut self) -> Option<A> { self.list.pop_front() }
749 fn size_hint(&self) -> (uint, Option<uint>) {
750 (self.list.length, Some(self.list.length))
754 impl<A> DoubleEndedIterator<A> for IntoIter<A> {
756 fn next_back(&mut self) -> Option<A> { self.list.pop_back() }
759 impl<A> FromIterator<A> for DList<A> {
760 fn from_iter<T: Iterator<A>>(iterator: T) -> DList<A> {
761 let mut ret = DList::new();
762 ret.extend(iterator);
767 impl<A> Extend<A> for DList<A> {
768 fn extend<T: Iterator<A>>(&mut self, mut iterator: T) {
769 for elt in iterator { self.push_back(elt); }
773 impl<A: PartialEq> PartialEq for DList<A> {
774 fn eq(&self, other: &DList<A>) -> bool {
775 self.len() == other.len() &&
776 iter::order::eq(self.iter(), other.iter())
779 fn ne(&self, other: &DList<A>) -> bool {
780 self.len() != other.len() ||
781 iter::order::ne(self.iter(), other.iter())
785 impl<A: Eq> Eq for DList<A> {}
787 impl<A: PartialOrd> PartialOrd for DList<A> {
788 fn partial_cmp(&self, other: &DList<A>) -> Option<Ordering> {
789 iter::order::partial_cmp(self.iter(), other.iter())
793 impl<A: Ord> Ord for DList<A> {
795 fn cmp(&self, other: &DList<A>) -> Ordering {
796 iter::order::cmp(self.iter(), other.iter())
801 impl<A: Clone> Clone for DList<A> {
802 fn clone(&self) -> DList<A> {
803 self.iter().map(|x| x.clone()).collect()
807 impl<A: fmt::Show> fmt::Show for DList<A> {
808 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
809 try!(write!(f, "["));
811 for (i, e) in self.iter().enumerate() {
812 if i != 0 { try!(write!(f, ", ")); }
813 try!(write!(f, "{}", *e));
820 impl<S: Writer, A: Hash<S>> Hash<S> for DList<A> {
821 fn hash(&self, state: &mut S) {
822 self.len().hash(state);
823 for elt in self.iter() {
834 use std::task::spawn;
838 use super::{DList, Node};
840 pub fn check_links<T>(list: &DList<T>) {
842 let mut last_ptr: Option<&Node<T>> = None;
843 let mut node_ptr: &Node<T>;
844 match list.list_head {
845 None => { assert_eq!(0u, list.length); return }
846 Some(ref node) => node_ptr = &**node,
849 match (last_ptr, node_ptr.prev.resolve_immut()) {
851 (None , _ ) => panic!("prev link for list_head"),
852 (Some(p), Some(pptr)) => {
853 assert_eq!(p as *const Node<T>, pptr as *const Node<T>);
855 _ => panic!("prev link is none, not good"),
857 match node_ptr.next {
859 last_ptr = Some(node_ptr);
869 assert_eq!(len, list.length);
874 let mut m: DList<Box<int>> = DList::new();
875 assert_eq!(m.pop_front(), None);
876 assert_eq!(m.pop_back(), None);
877 assert_eq!(m.pop_front(), None);
879 assert_eq!(m.pop_front(), Some(box 1));
882 assert_eq!(m.len(), 2);
883 assert_eq!(m.pop_front(), Some(box 2));
884 assert_eq!(m.pop_front(), Some(box 3));
885 assert_eq!(m.len(), 0);
886 assert_eq!(m.pop_front(), None);
891 assert_eq!(m.pop_front(), Some(box 1));
893 let mut n = DList::new();
897 assert_eq!(n.front().unwrap(), &3);
898 let x = n.front_mut().unwrap();
903 assert_eq!(n.back().unwrap(), &2);
904 let y = n.back_mut().unwrap();
908 assert_eq!(n.pop_front(), Some(0));
909 assert_eq!(n.pop_front(), Some(1));
913 fn generate_test() -> DList<int> {
914 list_from(&[0i,1,2,3,4,5,6])
918 fn list_from<T: Clone>(v: &[T]) -> DList<T> {
919 v.iter().map(|x| (*x).clone()).collect()
926 let mut m = DList::new();
927 let mut n = DList::new();
930 assert_eq!(m.len(), 1);
931 assert_eq!(m.pop_back(), Some(2));
935 let mut m = DList::new();
936 let n = DList::new();
939 assert_eq!(m.len(), 1);
940 assert_eq!(m.pop_back(), Some(2));
944 let v = vec![1i,2,3,4,5];
945 let u = vec![9i,8,1,2,3,4,5];
946 let mut m = list_from(v.as_slice());
947 m.append(list_from(u.as_slice()));
950 sum.push_all(u.as_slice());
951 assert_eq!(sum.len(), m.len());
952 for elt in sum.into_iter() {
953 assert_eq!(m.pop_front(), Some(elt))
960 let mut m = DList::new();
961 let mut n = DList::new();
964 assert_eq!(m.len(), 1);
965 assert_eq!(m.pop_back(), Some(2));
969 let v = vec![1i,2,3,4,5];
970 let mut u = vec![9i,8,1,2,3,4,5];
971 let mut m = list_from(v.as_slice());
972 m.prepend(list_from(u.as_slice()));
974 u.extend(v.iter().map(|&b| b));
975 assert_eq!(u.len(), m.len());
976 for elt in u.into_iter() {
977 assert_eq!(m.pop_front(), Some(elt))
983 let mut n: DList<int> = DList::new();
984 n.rotate_backward(); check_links(&n);
985 assert_eq!(n.len(), 0);
986 n.rotate_forward(); check_links(&n);
987 assert_eq!(n.len(), 0);
989 let v = vec![1i,2,3,4,5];
990 let mut m = list_from(v.as_slice());
991 m.rotate_backward(); check_links(&m);
992 m.rotate_forward(); check_links(&m);
993 assert_eq!(v.iter().collect::<Vec<&int>>(), m.iter().collect::<Vec<_>>());
994 m.rotate_forward(); check_links(&m);
995 m.rotate_forward(); check_links(&m);
996 m.pop_front(); check_links(&m);
997 m.rotate_forward(); check_links(&m);
998 m.rotate_backward(); check_links(&m);
999 m.push_front(9); check_links(&m);
1000 m.rotate_forward(); check_links(&m);
1001 assert_eq!(vec![3i,9,5,1,2], m.into_iter().collect::<Vec<_>>());
1005 fn test_iterator() {
1006 let m = generate_test();
1007 for (i, elt) in m.iter().enumerate() {
1008 assert_eq!(i as int, *elt);
1010 let mut n = DList::new();
1011 assert_eq!(n.iter().next(), None);
1013 let mut it = n.iter();
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_iterator_clone() {
1022 let mut n = DList::new();
1026 let mut it = n.iter();
1028 let mut jt = it.clone();
1029 assert_eq!(it.next(), jt.next());
1030 assert_eq!(it.next_back(), jt.next_back());
1031 assert_eq!(it.next(), jt.next());
1035 fn test_iterator_double_end() {
1036 let mut n = DList::new();
1037 assert_eq!(n.iter().next(), None);
1041 let mut it = n.iter();
1042 assert_eq!(it.size_hint(), (3, Some(3)));
1043 assert_eq!(it.next().unwrap(), &6);
1044 assert_eq!(it.size_hint(), (2, Some(2)));
1045 assert_eq!(it.next_back().unwrap(), &4);
1046 assert_eq!(it.size_hint(), (1, Some(1)));
1047 assert_eq!(it.next_back().unwrap(), &5);
1048 assert_eq!(it.next_back(), None);
1049 assert_eq!(it.next(), None);
1053 fn test_rev_iter() {
1054 let m = generate_test();
1055 for (i, elt) in m.iter().rev().enumerate() {
1056 assert_eq!((6 - i) as int, *elt);
1058 let mut n = DList::new();
1059 assert_eq!(n.iter().rev().next(), None);
1061 let mut it = n.iter().rev();
1062 assert_eq!(it.size_hint(), (1, Some(1)));
1063 assert_eq!(it.next().unwrap(), &4);
1064 assert_eq!(it.size_hint(), (0, Some(0)));
1065 assert_eq!(it.next(), None);
1069 fn test_mut_iter() {
1070 let mut m = generate_test();
1071 let mut len = m.len();
1072 for (i, elt) in m.iter_mut().enumerate() {
1073 assert_eq!(i as int, *elt);
1077 let mut n = DList::new();
1078 assert!(n.iter_mut().next().is_none());
1081 let mut it = n.iter_mut();
1082 assert_eq!(it.size_hint(), (2, Some(2)));
1083 assert!(it.next().is_some());
1084 assert!(it.next().is_some());
1085 assert_eq!(it.size_hint(), (0, Some(0)));
1086 assert!(it.next().is_none());
1090 fn test_iterator_mut_double_end() {
1091 let mut n = DList::new();
1092 assert!(n.iter_mut().next_back().is_none());
1096 let mut it = n.iter_mut();
1097 assert_eq!(it.size_hint(), (3, Some(3)));
1098 assert_eq!(*it.next().unwrap(), 6);
1099 assert_eq!(it.size_hint(), (2, Some(2)));
1100 assert_eq!(*it.next_back().unwrap(), 4);
1101 assert_eq!(it.size_hint(), (1, Some(1)));
1102 assert_eq!(*it.next_back().unwrap(), 5);
1103 assert!(it.next_back().is_none());
1104 assert!(it.next().is_none());
1108 fn test_insert_prev() {
1109 let mut m = list_from(&[0i,2,4,6,8]);
1112 let mut it = m.iter_mut();
1118 it.insert_next(*elt + 1);
1119 match it.peek_next() {
1120 Some(x) => assert_eq!(*x, *elt + 2),
1121 None => assert_eq!(8, *elt),
1130 assert_eq!(m.len(), 3 + len * 2);
1131 assert_eq!(m.into_iter().collect::<Vec<int>>(), vec![-2,0,1,2,3,4,5,6,7,8,9,0,1]);
1136 let mut m = list_from(&[0i, 1, 3, 5, 6, 7, 2]);
1137 let n = list_from(&[-1i, 0, 0, 7, 7, 9]);
1138 let len = m.len() + n.len();
1139 m.merge(n, |a, b| a <= b);
1140 assert_eq!(m.len(), len);
1142 let res = m.into_iter().collect::<Vec<int>>();
1143 assert_eq!(res, vec![-1, 0, 0, 0, 1, 3, 5, 6, 7, 2, 7, 7, 9]);
1147 fn test_insert_ordered() {
1148 let mut n = DList::new();
1149 n.insert_ordered(1i);
1150 assert_eq!(n.len(), 1);
1151 assert_eq!(n.pop_front(), Some(1));
1153 let mut m = DList::new();
1156 m.insert_ordered(3);
1158 assert_eq!(vec![2,3,4], m.into_iter().collect::<Vec<int>>());
1162 fn test_mut_rev_iter() {
1163 let mut m = generate_test();
1164 for (i, elt) in m.iter_mut().rev().enumerate() {
1165 assert_eq!((6-i) as int, *elt);
1167 let mut n = DList::new();
1168 assert!(n.iter_mut().rev().next().is_none());
1170 let mut it = n.iter_mut().rev();
1171 assert!(it.next().is_some());
1172 assert!(it.next().is_none());
1177 let n = list_from(&[1i,2,3]);
1180 let a: &[_] = &[&1,&2,&3];
1181 assert_eq!(a, n.iter().collect::<Vec<&int>>());
1187 let mut n: DList<u8> = list_from(&[]);
1188 let mut m = list_from(&[]);
1195 let n = list_from(&[2i,3,4]);
1196 let m = list_from(&[1i,2,3]);
1202 let mut x = DList::new();
1203 let mut y = DList::new();
1205 assert!(hash::hash(&x) == hash::hash(&y));
1215 assert!(hash::hash(&x) == hash::hash(&y));
1220 let n: DList<int> = list_from(&[]);
1221 let m = list_from(&[1i,2,3]);
1230 let nan = 0.0f64/0.0;
1231 let n = list_from(&[nan]);
1232 let m = list_from(&[nan]);
1238 let n = list_from(&[nan]);
1239 let one = list_from(&[1.0f64]);
1240 assert!(!(n < one));
1241 assert!(!(n > one));
1242 assert!(!(n <= one));
1243 assert!(!(n >= one));
1245 let u = list_from(&[1.0f64,2.0,nan]);
1246 let v = list_from(&[1.0f64,2.0,3.0]);
1252 let s = list_from(&[1.0f64,2.0,4.0,2.0]);
1253 let t = list_from(&[1.0f64,2.0,3.0,2.0]);
1256 assert!(!(s <= one));
1262 for _ in range(0u, 25) {
1271 let list: DList<int> = range(0i, 10).collect();
1272 assert!(list.to_string() == "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]");
1274 let list: DList<&str> = vec!["just", "one", "test", "more"].iter()
1277 assert!(list.to_string() == "[just, one, test, more]");
1281 fn fuzz_test(sz: int) {
1282 let mut m: DList<int> = DList::new();
1284 for i in range(0, sz) {
1286 let r: u8 = rand::random();
1310 for (a, &b) in m.into_iter().zip(v.iter()) {
1314 assert_eq!(i, v.len());
1318 fn bench_collect_into(b: &mut test::Bencher) {
1319 let v = &[0i, ..64];
1321 let _: DList<int> = v.iter().map(|x| *x).collect();
1326 fn bench_push_front(b: &mut test::Bencher) {
1327 let mut m: DList<int> = DList::new();
1334 fn bench_push_back(b: &mut test::Bencher) {
1335 let mut m: DList<int> = DList::new();
1342 fn bench_push_back_pop_back(b: &mut test::Bencher) {
1343 let mut m: DList<int> = DList::new();
1351 fn bench_push_front_pop_front(b: &mut test::Bencher) {
1352 let mut m: DList<int> = DList::new();
1360 fn bench_rotate_forward(b: &mut test::Bencher) {
1361 let mut m: DList<int> = DList::new();
1370 fn bench_rotate_backward(b: &mut test::Bencher) {
1371 let mut m: DList<int> = DList::new();
1375 m.rotate_backward();
1380 fn bench_iter(b: &mut test::Bencher) {
1381 let v = &[0i, ..128];
1382 let m: DList<int> = v.iter().map(|&x|x).collect();
1384 assert!(m.iter().count() == 128);
1388 fn bench_iter_mut(b: &mut test::Bencher) {
1389 let v = &[0i, ..128];
1390 let mut m: DList<int> = v.iter().map(|&x|x).collect();
1392 assert!(m.iter_mut().count() == 128);
1396 fn bench_iter_rev(b: &mut test::Bencher) {
1397 let v = &[0i, ..128];
1398 let m: DList<int> = v.iter().map(|&x|x).collect();
1400 assert!(m.iter().rev().count() == 128);
1404 fn bench_iter_mut_rev(b: &mut test::Bencher) {
1405 let v = &[0i, ..128];
1406 let mut m: DList<int> = v.iter().map(|&x|x).collect();
1408 assert!(m.iter_mut().rev().count() == 128);