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` implements the trait `Deque`. It should be imported with
16 //! `use collections::Deque`.
18 // DList is constructed like a singly-linked list over the field `next`.
19 // including the last link being None; each Node owns its `next` field.
21 // Backlinks over DList::prev are raw pointers that form a full chain in
22 // the reverse direction.
26 use alloc::boxed::Box;
27 use core::default::Default;
32 use std::hash::{Writer, Hash};
34 /// A doubly-linked list.
38 list_tail: Rawlink<Node<T>>,
41 type Link<T> = Option<Box<Node<T>>>;
42 struct Rawlink<T> { p: *mut T }
46 prev: Rawlink<Node<T>>,
50 /// An iterator over references to the items of a `DList`.
51 pub struct Items<'a, T:'a> {
53 tail: Rawlink<Node<T>>,
57 // FIXME #11820: the &'a Option<> of the Link stops clone working.
58 impl<'a, T> Clone for Items<'a, T> {
59 fn clone(&self) -> Items<'a, T> { *self }
62 /// An iterator over mutable references to the items of a `DList`.
63 pub struct MutItems<'a, T:'a> {
64 list: &'a mut DList<T>,
65 head: Rawlink<Node<T>>,
66 tail: Rawlink<Node<T>>,
70 /// An iterator over mutable references to the items of a `DList`.
72 pub struct MoveItems<T> {
76 /// Rawlink is a type like Option<T> but for holding a raw pointer
78 /// Like Option::None for Rawlink
79 fn none() -> Rawlink<T> {
80 Rawlink{p: ptr::null_mut()}
83 /// Like Option::Some for Rawlink
84 fn some(n: &mut T) -> Rawlink<T> {
88 /// Convert the `Rawlink` into an Option value
89 fn resolve_immut<'a>(&self) -> Option<&'a T> {
95 /// Convert the `Rawlink` into an Option value
96 fn resolve<'a>(&mut self) -> Option<&'a mut T> {
100 Some(unsafe { mem::transmute(self.p) })
104 /// Return the `Rawlink` and replace with `Rawlink::none()`
105 fn take(&mut self) -> Rawlink<T> {
106 mem::replace(self, Rawlink::none())
110 impl<T> Clone for Rawlink<T> {
112 fn clone(&self) -> Rawlink<T> {
118 fn new(v: T) -> Node<T> {
119 Node{value: v, next: None, prev: Rawlink::none()}
123 /// Set the .prev field on `next`, then return `Some(next)`
124 fn link_with_prev<T>(mut next: Box<Node<T>>, prev: Rawlink<Node<T>>)
132 /// Add a Node first in the list
134 fn push_front_node(&mut self, mut new_head: Box<Node<T>>) {
135 match self.list_head {
137 self.list_tail = Rawlink::some(&mut *new_head);
138 self.list_head = link_with_prev(new_head, Rawlink::none());
140 Some(ref mut head) => {
141 new_head.prev = Rawlink::none();
142 head.prev = Rawlink::some(&mut *new_head);
143 mem::swap(head, &mut new_head);
144 head.next = Some(new_head);
150 /// Remove the first Node and return it, or None if the list is empty
152 fn pop_front_node(&mut self) -> Option<Box<Node<T>>> {
153 self.list_head.take().map(|mut front_node| {
155 match front_node.next.take() {
156 Some(node) => self.list_head = link_with_prev(node, Rawlink::none()),
157 None => self.list_tail = Rawlink::none()
163 /// Add a Node last in the list
165 fn push_back_node(&mut self, mut new_tail: Box<Node<T>>) {
166 match self.list_tail.resolve() {
167 None => return self.push_front_node(new_tail),
169 self.list_tail = Rawlink::some(&mut *new_tail);
170 tail.next = link_with_prev(new_tail, Rawlink::some(tail));
176 /// Remove the last Node and return it, or None if the list is empty
178 fn pop_back_node(&mut self) -> Option<Box<Node<T>>> {
179 self.list_tail.resolve().map_or(None, |tail| {
181 self.list_tail = tail.prev;
182 match tail.prev.resolve() {
183 None => self.list_head.take(),
184 Some(tail_prev) => tail_prev.next.take()
190 impl<T> Default for DList<T> {
192 fn default() -> DList<T> { DList::new() }
196 /// Creates an empty `DList`.
198 #[unstable = "matches collection reform specification, waiting for dust to settle"]
199 pub fn new() -> DList<T> {
200 DList{list_head: None, list_tail: Rawlink::none(), length: 0}
203 /// Moves the last element to the front of the list.
205 /// If the list is empty, does nothing.
210 /// use std::collections::DList;
212 /// let mut dl = DList::new();
213 /// dl.push_back(1i);
217 /// dl.rotate_forward();
219 /// for e in dl.iter() {
220 /// println!("{}", e); // prints 3, then 1, then 2
224 pub fn rotate_forward(&mut self) {
225 self.pop_back_node().map(|tail| {
226 self.push_front_node(tail)
230 /// Moves the first element to the back of the list.
232 /// If the list is empty, does nothing.
237 /// use std::collections::DList;
239 /// let mut dl = DList::new();
240 /// dl.push_back(1i);
244 /// dl.rotate_backward();
246 /// for e in dl.iter() {
247 /// println!("{}", e); // prints 2, then 3, then 1
251 pub fn rotate_backward(&mut self) {
252 self.pop_front_node().map(|head| {
253 self.push_back_node(head)
257 /// Adds all elements from `other` to the end of the list.
259 /// This operation should compute in O(1) time.
264 /// use std::collections::DList;
266 /// let mut a = DList::new();
267 /// let mut b = DList::new();
275 /// for e in a.iter() {
276 /// println!("{}", e); // prints 1, then 2, then 3, then 4
279 pub fn append(&mut self, mut other: DList<T>) {
280 match self.list_tail.resolve() {
281 None => *self = other,
283 // Carefully empty `other`.
284 let o_tail = other.list_tail.take();
285 let o_length = other.length;
286 match other.list_head.take() {
289 tail.next = link_with_prev(node, self.list_tail);
290 self.list_tail = o_tail;
291 self.length += o_length;
298 /// Adds all elements from `other` to the beginning of the list.
300 /// This operation should compute in O(1) time.
305 /// use std::collections::DList;
307 /// let mut a = DList::new();
308 /// let mut b = DList::new();
316 /// for e in a.iter() {
317 /// println!("{}", e); // prints 3, then 4, then 1, then 2
321 pub fn prepend(&mut self, mut other: DList<T>) {
322 mem::swap(self, &mut other);
326 /// Inserts `elt` before the first `x` in the list where `f(x, elt)` is
327 /// true, or at the end.
329 /// This operation should compute in O(N) time.
334 /// use std::collections::DList;
336 /// let mut a: DList<int> = DList::new();
342 /// // insert 11 before the first odd number in the list
343 /// a.insert_when(11, |&e, _| e % 2 == 1);
345 /// for e in a.iter() {
346 /// println!("{}", e); // prints 2, then 4, then 11, then 7, then 8
349 pub fn insert_when(&mut self, elt: T, f: |&T, &T| -> bool) {
351 let mut it = self.iter_mut();
353 match it.peek_next() {
355 Some(x) => if f(x, &elt) { break }
363 /// Merges `other` into this `DList`, using the function `f`.
365 /// Iterates both `DList`s with `a` from self and `b` from `other`, and
366 /// put `a` in the result if `f(a, b)` is true, and otherwise `b`.
368 /// This operation should compute in O(max(N, M)) time.
369 pub fn merge(&mut self, mut other: DList<T>, f: |&T, &T| -> bool) {
371 let mut it = self.iter_mut();
373 let take_a = match (it.peek_next(), other.front()) {
374 (_ , None) => return,
376 (Some(ref mut x), Some(y)) => f(*x, y),
381 it.insert_next_node(other.pop_front_node().unwrap());
389 /// Provides a forward iterator.
391 #[unstable = "matches collection reform specification, waiting for dust to settle"]
392 pub fn iter<'a>(&'a self) -> Items<'a, T> {
393 Items{nelem: self.len(), head: &self.list_head, tail: self.list_tail}
396 /// Provides a forward iterator with mutable references.
398 #[unstable = "matches collection reform specification, waiting for dust to settle"]
399 pub fn iter_mut<'a>(&'a mut self) -> MutItems<'a, T> {
400 let head_raw = match self.list_head {
401 Some(ref mut h) => Rawlink::some(&mut **h),
402 None => Rawlink::none(),
407 tail: self.list_tail,
412 /// Consumes the list into an iterator yielding elements by value.
414 #[unstable = "matches collection reform specification, waiting for dust to settle"]
415 pub fn into_iter(self) -> MoveItems<T> {
416 MoveItems{list: self}
419 /// Returns `true` if the `DList` is empty.
421 /// This operation should compute in O(1) time.
423 #[unstable = "matches collection reform specification, waiting for dust to settle"]
424 pub fn is_empty(&self) -> bool {
425 self.list_head.is_none()
428 /// Returns the length of the `DList`.
430 /// This operation should compute in O(1) time.
432 #[unstable = "matches collection reform specification, waiting for dust to settle"]
433 pub fn len(&self) -> uint {
437 /// Removes all elements from the `DList`.
439 /// This operation should compute in O(n) time.
441 #[unstable = "matches collection reform specification, waiting for dust to settle"]
442 pub fn clear(&mut self) {
446 /// Provides a reference to the front element, or `None` if the list is
449 #[unstable = "matches collection reform specification, waiting for dust to settle"]
450 pub fn front(&self) -> Option<&T> {
451 self.list_head.as_ref().map(|head| &head.value)
454 /// Provides a mutable reference to the front element, or `None` if the list
457 #[unstable = "matches collection reform specification, waiting for dust to settle"]
458 pub fn front_mut(&mut self) -> Option<&mut T> {
459 self.list_head.as_mut().map(|head| &mut head.value)
462 /// Provides a reference to the back element, or `None` if the list is
465 #[unstable = "matches collection reform specification, waiting for dust to settle"]
466 pub fn back(&self) -> Option<&T> {
467 self.list_tail.resolve_immut().as_ref().map(|tail| &tail.value)
470 /// Provides a mutable reference to the back element, or `None` if the list
473 #[unstable = "matches collection reform specification, waiting for dust to settle"]
474 pub fn back_mut(&mut self) -> Option<&mut T> {
475 self.list_tail.resolve().map(|tail| &mut tail.value)
478 /// Adds an element first in the list.
480 /// This operation should compute in O(1) time.
481 #[unstable = "matches collection reform specification, waiting for dust to settle"]
482 pub fn push_front(&mut self, elt: T) {
483 self.push_front_node(box Node::new(elt))
486 /// Removes the first element and returns it, or `None` if the list is
489 /// This operation should compute in O(1) time.
490 #[unstable = "matches collection reform specification, waiting for dust to settle"]
491 pub fn pop_front(&mut self) -> Option<T> {
492 self.pop_front_node().map(|box Node{value, ..}| value)
495 /// Deprecated: Renamed to `push_back`.
496 #[deprecated = "Renamed to `push_back`"]
497 pub fn push(&mut self, elt: T) {
501 /// Appends an element to the back of a list
506 /// use std::collections::DList;
508 /// let mut d = DList::new();
511 /// assert_eq!(3, *d.back().unwrap());
513 #[unstable = "matches collection reform specification, waiting for dust to settle"]
514 pub fn push_back(&mut self, elt: T) {
515 self.push_back_node(box Node::new(elt))
518 /// Deprecated: Renamed to `pop_back`.
519 #[deprecated = "Renamed to `pop_back`"]
520 pub fn pop(&mut self) -> Option<T> {
524 /// Removes the last element from a list and returns it, or `None` if
530 /// use std::collections::DList;
532 /// let mut d = DList::new();
533 /// assert_eq!(d.pop_back(), None);
536 /// assert_eq!(d.pop_back(), Some(3));
538 #[unstable = "matches collection reform specification, waiting for dust to settle"]
539 pub fn pop_back(&mut self) -> Option<T> {
540 self.pop_back_node().map(|box Node{value, ..}| value)
544 impl<T: Ord> DList<T> {
545 /// Inserts `elt` sorted in ascending order.
547 /// This operation should compute in O(N) time.
549 pub fn insert_ordered(&mut self, elt: T) {
550 self.insert_when(elt, |a, b| a >= b)
555 impl<T> Drop for DList<T> {
557 // Dissolve the dlist in backwards direction
558 // Just dropping the list_head can lead to stack exhaustion
559 // when length is >> 1_000_000
560 let mut tail = self.list_tail;
562 match tail.resolve() {
565 prev.next.take(); // release Box<Node<T>>
571 self.list_head = None;
572 self.list_tail = Rawlink::none();
577 impl<'a, A> Iterator<&'a A> for Items<'a, A> {
579 fn next(&mut self) -> Option<&'a A> {
583 self.head.as_ref().map(|head| {
585 self.head = &head.next;
591 fn size_hint(&self) -> (uint, Option<uint>) {
592 (self.nelem, Some(self.nelem))
596 impl<'a, A> DoubleEndedIterator<&'a A> for Items<'a, A> {
598 fn next_back(&mut self) -> Option<&'a A> {
602 self.tail.resolve_immut().as_ref().map(|prev| {
604 self.tail = prev.prev;
610 impl<'a, A> ExactSizeIterator<&'a A> for Items<'a, A> {}
612 impl<'a, A> Iterator<&'a mut A> for MutItems<'a, A> {
614 fn next(&mut self) -> Option<&'a mut A> {
618 self.head.resolve().map(|next| {
620 self.head = match next.next {
621 Some(ref mut node) => Rawlink::some(&mut **node),
622 None => Rawlink::none(),
629 fn size_hint(&self) -> (uint, Option<uint>) {
630 (self.nelem, Some(self.nelem))
634 impl<'a, A> DoubleEndedIterator<&'a mut A> for MutItems<'a, A> {
636 fn next_back(&mut self) -> Option<&'a mut A> {
640 self.tail.resolve().map(|prev| {
642 self.tail = prev.prev;
648 impl<'a, A> ExactSizeIterator<&'a mut A> for MutItems<'a, A> {}
650 /// Allows mutating a `DList` while iterating.
651 pub trait ListInsertion<A> {
652 /// Inserts `elt` just after to the element most recently returned by
655 /// The inserted element does not appear in the iteration.
656 fn insert_next(&mut self, elt: A);
658 /// Provides a reference to the next element, without changing the iterator
659 fn peek_next<'a>(&'a mut self) -> Option<&'a mut A>;
662 // private methods for MutItems
663 impl<'a, A> MutItems<'a, A> {
664 fn insert_next_node(&mut self, mut ins_node: Box<Node<A>>) {
665 // Insert before `self.head` so that it is between the
666 // previously yielded element and self.head.
668 // The inserted node will not appear in further iteration.
669 match self.head.resolve() {
670 None => { self.list.push_back_node(ins_node); }
672 let prev_node = match node.prev.resolve() {
673 None => return self.list.push_front_node(ins_node),
676 let node_own = prev_node.next.take().unwrap();
677 ins_node.next = link_with_prev(node_own, Rawlink::some(&mut *ins_node));
678 prev_node.next = link_with_prev(ins_node, Rawlink::some(prev_node));
679 self.list.length += 1;
685 impl<'a, A> ListInsertion<A> for MutItems<'a, A> {
687 fn insert_next(&mut self, elt: A) {
688 self.insert_next_node(box Node::new(elt))
692 fn peek_next<'a>(&'a mut self) -> Option<&'a mut A> {
696 self.head.resolve().map(|head| &mut head.value)
700 impl<A> Iterator<A> for MoveItems<A> {
702 fn next(&mut self) -> Option<A> { self.list.pop_front() }
705 fn size_hint(&self) -> (uint, Option<uint>) {
706 (self.list.length, Some(self.list.length))
710 impl<A> DoubleEndedIterator<A> for MoveItems<A> {
712 fn next_back(&mut self) -> Option<A> { self.list.pop_back() }
715 impl<A> FromIterator<A> for DList<A> {
716 fn from_iter<T: Iterator<A>>(iterator: T) -> DList<A> {
717 let mut ret = DList::new();
718 ret.extend(iterator);
723 impl<A> Extend<A> for DList<A> {
724 fn extend<T: Iterator<A>>(&mut self, mut iterator: T) {
725 for elt in iterator { self.push_back(elt); }
729 impl<A: PartialEq> PartialEq for DList<A> {
730 fn eq(&self, other: &DList<A>) -> bool {
731 self.len() == other.len() &&
732 iter::order::eq(self.iter(), other.iter())
735 fn ne(&self, other: &DList<A>) -> bool {
736 self.len() != other.len() ||
737 iter::order::ne(self.iter(), other.iter())
741 impl<A: Eq> Eq for DList<A> {}
743 impl<A: PartialOrd> PartialOrd for DList<A> {
744 fn partial_cmp(&self, other: &DList<A>) -> Option<Ordering> {
745 iter::order::partial_cmp(self.iter(), other.iter())
749 impl<A: Ord> Ord for DList<A> {
751 fn cmp(&self, other: &DList<A>) -> Ordering {
752 iter::order::cmp(self.iter(), other.iter())
756 impl<A: Clone> Clone for DList<A> {
757 fn clone(&self) -> DList<A> {
758 self.iter().map(|x| x.clone()).collect()
762 impl<A: fmt::Show> fmt::Show for DList<A> {
763 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
764 try!(write!(f, "["));
766 for (i, e) in self.iter().enumerate() {
767 if i != 0 { try!(write!(f, ", ")); }
768 try!(write!(f, "{}", *e));
775 impl<S: Writer, A: Hash<S>> Hash<S> for DList<A> {
776 fn hash(&self, state: &mut S) {
777 self.len().hash(state);
778 for elt in self.iter() {
792 use super::{DList, Node, ListInsertion};
795 pub fn check_links<T>(list: &DList<T>) {
797 let mut last_ptr: Option<&Node<T>> = None;
798 let mut node_ptr: &Node<T>;
799 match list.list_head {
800 None => { assert_eq!(0u, list.length); return }
801 Some(ref node) => node_ptr = &**node,
804 match (last_ptr, node_ptr.prev.resolve_immut()) {
806 (None , _ ) => panic!("prev link for list_head"),
807 (Some(p), Some(pptr)) => {
808 assert_eq!(p as *const Node<T>, pptr as *const Node<T>);
810 _ => panic!("prev link is none, not good"),
812 match node_ptr.next {
814 last_ptr = Some(node_ptr);
824 assert_eq!(len, list.length);
829 let mut m: DList<Box<int>> = DList::new();
830 assert_eq!(m.pop_front(), None);
831 assert_eq!(m.pop_back(), None);
832 assert_eq!(m.pop_front(), None);
834 assert_eq!(m.pop_front(), Some(box 1));
837 assert_eq!(m.len(), 2);
838 assert_eq!(m.pop_front(), Some(box 2));
839 assert_eq!(m.pop_front(), Some(box 3));
840 assert_eq!(m.len(), 0);
841 assert_eq!(m.pop_front(), None);
846 assert_eq!(m.pop_front(), Some(box 1));
848 let mut n = DList::new();
852 assert_eq!(n.front().unwrap(), &3);
853 let x = n.front_mut().unwrap();
858 assert_eq!(n.back().unwrap(), &2);
859 let y = n.back_mut().unwrap();
863 assert_eq!(n.pop_front(), Some(0));
864 assert_eq!(n.pop_front(), Some(1));
868 fn generate_test() -> DList<int> {
869 list_from(&[0i,1,2,3,4,5,6])
873 fn list_from<T: Clone>(v: &[T]) -> DList<T> {
874 v.iter().map(|x| (*x).clone()).collect()
881 let mut m = DList::new();
882 let mut n = DList::new();
885 assert_eq!(m.len(), 1);
886 assert_eq!(m.pop_back(), Some(2));
890 let mut m = DList::new();
891 let n = DList::new();
894 assert_eq!(m.len(), 1);
895 assert_eq!(m.pop_back(), Some(2));
899 let v = vec![1i,2,3,4,5];
900 let u = vec![9i,8,1,2,3,4,5];
901 let mut m = list_from(v.as_slice());
902 m.append(list_from(u.as_slice()));
905 sum.push_all(u.as_slice());
906 assert_eq!(sum.len(), m.len());
907 for elt in sum.into_iter() {
908 assert_eq!(m.pop_front(), Some(elt))
915 let mut m = DList::new();
916 let mut n = DList::new();
919 assert_eq!(m.len(), 1);
920 assert_eq!(m.pop_back(), Some(2));
924 let v = vec![1i,2,3,4,5];
925 let mut u = vec![9i,8,1,2,3,4,5];
926 let mut m = list_from(v.as_slice());
927 m.prepend(list_from(u.as_slice()));
929 u.extend(v.as_slice().iter().map(|&b| b));
930 assert_eq!(u.len(), m.len());
931 for elt in u.into_iter() {
932 assert_eq!(m.pop_front(), Some(elt))
938 let mut n: DList<int> = DList::new();
939 n.rotate_backward(); check_links(&n);
940 assert_eq!(n.len(), 0);
941 n.rotate_forward(); check_links(&n);
942 assert_eq!(n.len(), 0);
944 let v = vec![1i,2,3,4,5];
945 let mut m = list_from(v.as_slice());
946 m.rotate_backward(); check_links(&m);
947 m.rotate_forward(); check_links(&m);
948 assert_eq!(v.iter().collect::<Vec<&int>>(), m.iter().collect::<Vec<_>>());
949 m.rotate_forward(); check_links(&m);
950 m.rotate_forward(); check_links(&m);
951 m.pop_front(); check_links(&m);
952 m.rotate_forward(); check_links(&m);
953 m.rotate_backward(); check_links(&m);
954 m.push_front(9); check_links(&m);
955 m.rotate_forward(); check_links(&m);
956 assert_eq!(vec![3i,9,5,1,2], m.into_iter().collect::<Vec<_>>());
961 let m = generate_test();
962 for (i, elt) in m.iter().enumerate() {
963 assert_eq!(i as int, *elt);
965 let mut n = DList::new();
966 assert_eq!(n.iter().next(), None);
968 let mut it = n.iter();
969 assert_eq!(it.size_hint(), (1, Some(1)));
970 assert_eq!(it.next().unwrap(), &4);
971 assert_eq!(it.size_hint(), (0, Some(0)));
972 assert_eq!(it.next(), None);
976 fn test_iterator_clone() {
977 let mut n = DList::new();
981 let mut it = n.iter();
983 let mut jt = it.clone();
984 assert_eq!(it.next(), jt.next());
985 assert_eq!(it.next_back(), jt.next_back());
986 assert_eq!(it.next(), jt.next());
990 fn test_iterator_double_end() {
991 let mut n = DList::new();
992 assert_eq!(n.iter().next(), None);
996 let mut it = n.iter();
997 assert_eq!(it.size_hint(), (3, Some(3)));
998 assert_eq!(it.next().unwrap(), &6);
999 assert_eq!(it.size_hint(), (2, Some(2)));
1000 assert_eq!(it.next_back().unwrap(), &4);
1001 assert_eq!(it.size_hint(), (1, Some(1)));
1002 assert_eq!(it.next_back().unwrap(), &5);
1003 assert_eq!(it.next_back(), None);
1004 assert_eq!(it.next(), None);
1008 fn test_rev_iter() {
1009 let m = generate_test();
1010 for (i, elt) in m.iter().rev().enumerate() {
1011 assert_eq!((6 - i) as int, *elt);
1013 let mut n = DList::new();
1014 assert_eq!(n.iter().rev().next(), None);
1016 let mut it = n.iter().rev();
1017 assert_eq!(it.size_hint(), (1, Some(1)));
1018 assert_eq!(it.next().unwrap(), &4);
1019 assert_eq!(it.size_hint(), (0, Some(0)));
1020 assert_eq!(it.next(), None);
1024 fn test_mut_iter() {
1025 let mut m = generate_test();
1026 let mut len = m.len();
1027 for (i, elt) in m.iter_mut().enumerate() {
1028 assert_eq!(i as int, *elt);
1032 let mut n = DList::new();
1033 assert!(n.iter_mut().next().is_none());
1036 let mut it = n.iter_mut();
1037 assert_eq!(it.size_hint(), (2, Some(2)));
1038 assert!(it.next().is_some());
1039 assert!(it.next().is_some());
1040 assert_eq!(it.size_hint(), (0, Some(0)));
1041 assert!(it.next().is_none());
1045 fn test_iterator_mut_double_end() {
1046 let mut n = DList::new();
1047 assert!(n.iter_mut().next_back().is_none());
1051 let mut it = n.iter_mut();
1052 assert_eq!(it.size_hint(), (3, Some(3)));
1053 assert_eq!(*it.next().unwrap(), 6);
1054 assert_eq!(it.size_hint(), (2, Some(2)));
1055 assert_eq!(*it.next_back().unwrap(), 4);
1056 assert_eq!(it.size_hint(), (1, Some(1)));
1057 assert_eq!(*it.next_back().unwrap(), 5);
1058 assert!(it.next_back().is_none());
1059 assert!(it.next().is_none());
1063 fn test_insert_prev() {
1064 let mut m = list_from(&[0i,2,4,6,8]);
1067 let mut it = m.iter_mut();
1073 it.insert_next(*elt + 1);
1074 match it.peek_next() {
1075 Some(x) => assert_eq!(*x, *elt + 2),
1076 None => assert_eq!(8, *elt),
1085 assert_eq!(m.len(), 3 + len * 2);
1086 assert_eq!(m.into_iter().collect::<Vec<int>>(), vec![-2,0,1,2,3,4,5,6,7,8,9,0,1]);
1091 let mut m = list_from(&[0i, 1, 3, 5, 6, 7, 2]);
1092 let n = list_from(&[-1i, 0, 0, 7, 7, 9]);
1093 let len = m.len() + n.len();
1094 m.merge(n, |a, b| a <= b);
1095 assert_eq!(m.len(), len);
1097 let res = m.into_iter().collect::<Vec<int>>();
1098 assert_eq!(res, vec![-1, 0, 0, 0, 1, 3, 5, 6, 7, 2, 7, 7, 9]);
1102 fn test_insert_ordered() {
1103 let mut n = DList::new();
1104 n.insert_ordered(1i);
1105 assert_eq!(n.len(), 1);
1106 assert_eq!(n.pop_front(), Some(1));
1108 let mut m = DList::new();
1111 m.insert_ordered(3);
1113 assert_eq!(vec![2,3,4], m.into_iter().collect::<Vec<int>>());
1117 fn test_mut_rev_iter() {
1118 let mut m = generate_test();
1119 for (i, elt) in m.iter_mut().rev().enumerate() {
1120 assert_eq!((6-i) as int, *elt);
1122 let mut n = DList::new();
1123 assert!(n.iter_mut().rev().next().is_none());
1125 let mut it = n.iter_mut().rev();
1126 assert!(it.next().is_some());
1127 assert!(it.next().is_none());
1132 let n = list_from(&[1i,2,3]);
1135 let a: &[_] = &[&1,&2,&3];
1136 assert_eq!(a, n.iter().collect::<Vec<&int>>().as_slice());
1142 let mut n: DList<u8> = list_from(&[]);
1143 let mut m = list_from(&[]);
1150 let n = list_from(&[2i,3,4]);
1151 let m = list_from(&[1i,2,3]);
1157 let mut x = DList::new();
1158 let mut y = DList::new();
1160 assert!(hash::hash(&x) == hash::hash(&y));
1170 assert!(hash::hash(&x) == hash::hash(&y));
1175 let n: DList<int> = list_from(&[]);
1176 let m = list_from(&[1i,2,3]);
1185 let nan = 0.0f64/0.0;
1186 let n = list_from(&[nan]);
1187 let m = list_from(&[nan]);
1193 let n = list_from(&[nan]);
1194 let one = list_from(&[1.0f64]);
1195 assert!(!(n < one));
1196 assert!(!(n > one));
1197 assert!(!(n <= one));
1198 assert!(!(n >= one));
1200 let u = list_from(&[1.0f64,2.0,nan]);
1201 let v = list_from(&[1.0f64,2.0,3.0]);
1207 let s = list_from(&[1.0f64,2.0,4.0,2.0]);
1208 let t = list_from(&[1.0f64,2.0,3.0,2.0]);
1211 assert!(!(s <= one));
1217 for _ in range(0u, 25) {
1226 let list: DList<int> = range(0i, 10).collect();
1227 assert!(list.to_string().as_slice() == "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]");
1229 let list: DList<&str> = vec!["just", "one", "test", "more"].iter()
1232 assert!(list.to_string().as_slice() == "[just, one, test, more]");
1236 fn fuzz_test(sz: int) {
1237 let mut m: DList<int> = DList::new();
1239 for i in range(0, sz) {
1241 let r: u8 = rand::random();
1265 for (a, &b) in m.into_iter().zip(v.iter()) {
1269 assert_eq!(i, v.len());
1273 fn bench_collect_into(b: &mut test::Bencher) {
1274 let v = &[0i, ..64];
1276 let _: DList<int> = v.iter().map(|x| *x).collect();
1281 fn bench_push_front(b: &mut test::Bencher) {
1282 let mut m: DList<int> = DList::new();
1289 fn bench_push_back(b: &mut test::Bencher) {
1290 let mut m: DList<int> = DList::new();
1297 fn bench_push_back_pop_back(b: &mut test::Bencher) {
1298 let mut m: DList<int> = DList::new();
1306 fn bench_push_front_pop_front(b: &mut test::Bencher) {
1307 let mut m: DList<int> = DList::new();
1315 fn bench_rotate_forward(b: &mut test::Bencher) {
1316 let mut m: DList<int> = DList::new();
1325 fn bench_rotate_backward(b: &mut test::Bencher) {
1326 let mut m: DList<int> = DList::new();
1330 m.rotate_backward();
1335 fn bench_iter(b: &mut test::Bencher) {
1336 let v = &[0i, ..128];
1337 let m: DList<int> = v.iter().map(|&x|x).collect();
1339 assert!(m.iter().count() == 128);
1343 fn bench_iter_mut(b: &mut test::Bencher) {
1344 let v = &[0i, ..128];
1345 let mut m: DList<int> = v.iter().map(|&x|x).collect();
1347 assert!(m.iter_mut().count() == 128);
1351 fn bench_iter_rev(b: &mut test::Bencher) {
1352 let v = &[0i, ..128];
1353 let m: DList<int> = v.iter().map(|&x|x).collect();
1355 assert!(m.iter().rev().count() == 128);
1359 fn bench_iter_mut_rev(b: &mut test::Bencher) {
1360 let v = &[0i, ..128];
1361 let mut m: DList<int> = v.iter().map(|&x|x).collect();
1363 assert!(m.iter_mut().rev().count() == 128);