1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
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.
22 #![stable(feature = "rust1", since = "1.0.0")]
26 use alloc::boxed::Box;
27 use core::cmp::Ordering;
28 use core::default::Default;
30 use core::hash::{Writer, Hasher, Hash};
31 use core::iter::{self, FromIterator, IntoIterator};
35 /// A doubly-linked list.
36 #[stable(feature = "rust1", since = "1.0.0")]
40 list_tail: Rawlink<Node<T>>,
43 type Link<T> = Option<Box<Node<T>>>;
49 impl<T> Copy for Rawlink<T> {}
50 unsafe impl<T:'static+Send> Send for Rawlink<T> {}
51 unsafe impl<T:Send+Sync> Sync for Rawlink<T> {}
55 prev: Rawlink<Node<T>>,
59 /// An iterator over references to the items of a `DList`.
60 #[stable(feature = "rust1", since = "1.0.0")]
61 pub struct Iter<'a, T:'a> {
63 tail: Rawlink<Node<T>>,
67 // FIXME #19839: deriving is too aggressive on the bounds (T doesn't need to be Clone).
68 #[stable(feature = "rust1", since = "1.0.0")]
69 impl<'a, T> Clone for Iter<'a, T> {
70 fn clone(&self) -> Iter<'a, T> {
72 head: self.head.clone(),
79 /// An iterator over mutable references to the items of a `DList`.
80 #[stable(feature = "rust1", since = "1.0.0")]
81 pub struct IterMut<'a, T:'a> {
82 list: &'a mut DList<T>,
83 head: Rawlink<Node<T>>,
84 tail: Rawlink<Node<T>>,
88 /// An iterator over mutable references to the items of a `DList`.
90 #[stable(feature = "rust1", since = "1.0.0")]
91 pub struct IntoIter<T> {
95 /// Rawlink is a type like Option<T> but for holding a raw pointer
97 /// Like Option::None for Rawlink
98 fn none() -> Rawlink<T> {
99 Rawlink{p: ptr::null_mut()}
102 /// Like Option::Some for Rawlink
103 fn some(n: &mut T) -> Rawlink<T> {
107 /// Convert the `Rawlink` into an Option value
108 fn resolve_immut<'a>(&self) -> Option<&'a T> {
110 mem::transmute(self.p.as_ref())
114 /// Convert the `Rawlink` into an Option value
115 fn resolve<'a>(&mut self) -> Option<&'a mut T> {
116 if self.p.is_null() {
119 Some(unsafe { mem::transmute(self.p) })
123 /// Return the `Rawlink` and replace with `Rawlink::none()`
124 fn take(&mut self) -> Rawlink<T> {
125 mem::replace(self, Rawlink::none())
129 impl<T> Clone for Rawlink<T> {
131 fn clone(&self) -> Rawlink<T> {
137 fn new(v: T) -> Node<T> {
138 Node{value: v, next: None, prev: Rawlink::none()}
142 /// Set the .prev field on `next`, then return `Some(next)`
143 fn link_with_prev<T>(mut next: Box<Node<T>>, prev: Rawlink<Node<T>>)
151 /// Add a Node first in the list
153 fn push_front_node(&mut self, mut new_head: Box<Node<T>>) {
154 match self.list_head {
156 self.list_tail = Rawlink::some(&mut *new_head);
157 self.list_head = link_with_prev(new_head, Rawlink::none());
159 Some(ref mut head) => {
160 new_head.prev = Rawlink::none();
161 head.prev = Rawlink::some(&mut *new_head);
162 mem::swap(head, &mut new_head);
163 head.next = Some(new_head);
169 /// Remove the first Node and return it, or None if the list is empty
171 fn pop_front_node(&mut self) -> Option<Box<Node<T>>> {
172 self.list_head.take().map(|mut front_node| {
174 match front_node.next.take() {
175 Some(node) => self.list_head = link_with_prev(node, Rawlink::none()),
176 None => self.list_tail = Rawlink::none()
182 /// Add a Node last in the list
184 fn push_back_node(&mut self, mut new_tail: Box<Node<T>>) {
185 match self.list_tail.resolve() {
186 None => return self.push_front_node(new_tail),
188 self.list_tail = Rawlink::some(&mut *new_tail);
189 tail.next = link_with_prev(new_tail, Rawlink::some(tail));
195 /// Remove the last Node and return it, or None if the list is empty
197 fn pop_back_node(&mut self) -> Option<Box<Node<T>>> {
198 self.list_tail.resolve().map_or(None, |tail| {
200 self.list_tail = tail.prev;
201 match tail.prev.resolve() {
202 None => self.list_head.take(),
203 Some(tail_prev) => tail_prev.next.take()
209 #[stable(feature = "rust1", since = "1.0.0")]
210 impl<T> Default for DList<T> {
212 #[stable(feature = "rust1", since = "1.0.0")]
213 fn default() -> DList<T> { DList::new() }
217 /// Creates an empty `DList`.
219 #[stable(feature = "rust1", since = "1.0.0")]
220 pub fn new() -> DList<T> {
221 DList{list_head: None, list_tail: Rawlink::none(), length: 0}
224 /// Moves all elements from `other` to the end of the list.
226 /// This reuses all the nodes from `other` and moves them into `self`. After
227 /// this operation, `other` becomes empty.
229 /// This operation should compute in O(1) time and O(1) memory.
234 /// use std::collections::DList;
236 /// let mut a = DList::new();
237 /// let mut b = DList::new();
243 /// a.append(&mut b);
245 /// for e in a.iter() {
246 /// println!("{}", e); // prints 1, then 2, then 3, then 4
248 /// println!("{}", b.len()); // prints 0
250 pub fn append(&mut self, other: &mut DList<T>) {
251 match self.list_tail.resolve() {
253 self.length = other.length;
254 self.list_head = other.list_head.take();
255 self.list_tail = other.list_tail.take();
258 // Carefully empty `other`.
259 let o_tail = other.list_tail.take();
260 let o_length = other.length;
261 match other.list_head.take() {
264 tail.next = link_with_prev(node, self.list_tail);
265 self.list_tail = o_tail;
266 self.length += o_length;
274 /// Provides a forward iterator.
276 #[stable(feature = "rust1", since = "1.0.0")]
277 pub fn iter(&self) -> Iter<T> {
278 Iter{nelem: self.len(), head: &self.list_head, tail: self.list_tail}
281 /// Provides a forward iterator with mutable references.
283 #[stable(feature = "rust1", since = "1.0.0")]
284 pub fn iter_mut(&mut self) -> IterMut<T> {
285 let head_raw = match self.list_head {
286 Some(ref mut h) => Rawlink::some(&mut **h),
287 None => Rawlink::none(),
292 tail: self.list_tail,
297 /// Consumes the list into an iterator yielding elements by value.
299 #[stable(feature = "rust1", since = "1.0.0")]
300 pub fn into_iter(self) -> IntoIter<T> {
304 /// Returns `true` if the `DList` is empty.
306 /// This operation should compute in O(1) time.
311 /// use std::collections::DList;
313 /// let mut dl = DList::new();
314 /// assert!(dl.is_empty());
316 /// dl.push_front("foo");
317 /// assert!(!dl.is_empty());
320 #[stable(feature = "rust1", since = "1.0.0")]
321 pub fn is_empty(&self) -> bool {
322 self.list_head.is_none()
325 /// Returns the length of the `DList`.
327 /// This operation should compute in O(1) time.
332 /// use std::collections::DList;
334 /// let mut dl = DList::new();
336 /// dl.push_front(2);
337 /// assert_eq!(dl.len(), 1);
339 /// dl.push_front(1);
340 /// assert_eq!(dl.len(), 2);
343 /// assert_eq!(dl.len(), 3);
347 #[stable(feature = "rust1", since = "1.0.0")]
348 pub fn len(&self) -> uint {
352 /// Removes all elements from the `DList`.
354 /// This operation should compute in O(n) time.
359 /// use std::collections::DList;
361 /// let mut dl = DList::new();
363 /// dl.push_front(2);
364 /// dl.push_front(1);
365 /// assert_eq!(dl.len(), 2);
366 /// assert_eq!(dl.front(), Some(&1));
369 /// assert_eq!(dl.len(), 0);
370 /// assert_eq!(dl.front(), None);
374 #[stable(feature = "rust1", since = "1.0.0")]
375 pub fn clear(&mut self) {
379 /// Provides a reference to the front element, or `None` if the list is
385 /// use std::collections::DList;
387 /// let mut dl = DList::new();
388 /// assert_eq!(dl.front(), None);
390 /// dl.push_front(1);
391 /// assert_eq!(dl.front(), Some(&1));
395 #[stable(feature = "rust1", since = "1.0.0")]
396 pub fn front(&self) -> Option<&T> {
397 self.list_head.as_ref().map(|head| &head.value)
400 /// Provides a mutable reference to the front element, or `None` if the list
406 /// use std::collections::DList;
408 /// let mut dl = DList::new();
409 /// assert_eq!(dl.front(), None);
411 /// dl.push_front(1);
412 /// assert_eq!(dl.front(), Some(&1));
414 /// match dl.front_mut() {
416 /// Some(x) => *x = 5,
418 /// assert_eq!(dl.front(), Some(&5));
422 #[stable(feature = "rust1", since = "1.0.0")]
423 pub fn front_mut(&mut self) -> Option<&mut T> {
424 self.list_head.as_mut().map(|head| &mut head.value)
427 /// Provides a reference to the back element, or `None` if the list is
433 /// use std::collections::DList;
435 /// let mut dl = DList::new();
436 /// assert_eq!(dl.back(), None);
439 /// assert_eq!(dl.back(), Some(&1));
443 #[stable(feature = "rust1", since = "1.0.0")]
444 pub fn back(&self) -> Option<&T> {
445 self.list_tail.resolve_immut().as_ref().map(|tail| &tail.value)
448 /// Provides a mutable reference to the back element, or `None` if the list
454 /// use std::collections::DList;
456 /// let mut dl = DList::new();
457 /// assert_eq!(dl.back(), None);
460 /// assert_eq!(dl.back(), Some(&1));
462 /// match dl.back_mut() {
464 /// Some(x) => *x = 5,
466 /// assert_eq!(dl.back(), Some(&5));
470 #[stable(feature = "rust1", since = "1.0.0")]
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.
482 /// use std::collections::DList;
484 /// let mut dl = DList::new();
486 /// dl.push_front(2);
487 /// assert_eq!(dl.front().unwrap(), &2);
489 /// dl.push_front(1);
490 /// assert_eq!(dl.front().unwrap(), &1);
493 #[stable(feature = "rust1", since = "1.0.0")]
494 pub fn push_front(&mut self, elt: T) {
495 self.push_front_node(box Node::new(elt))
498 /// Removes the first element and returns it, or `None` if the list is
501 /// This operation should compute in O(1) time.
506 /// use std::collections::DList;
508 /// let mut d = DList::new();
509 /// assert_eq!(d.pop_front(), None);
513 /// assert_eq!(d.pop_front(), Some(3));
514 /// assert_eq!(d.pop_front(), Some(1));
515 /// assert_eq!(d.pop_front(), None);
519 #[stable(feature = "rust1", since = "1.0.0")]
520 pub fn pop_front(&mut self) -> Option<T> {
521 self.pop_front_node().map(|box Node{value, ..}| value)
524 /// Appends an element to the back of a list
529 /// use std::collections::DList;
531 /// let mut d = DList::new();
534 /// assert_eq!(3, *d.back().unwrap());
536 #[stable(feature = "rust1", since = "1.0.0")]
537 pub fn push_back(&mut self, elt: T) {
538 self.push_back_node(box Node::new(elt))
541 /// Removes the last element from a list and returns it, or `None` if
547 /// use std::collections::DList;
549 /// let mut d = DList::new();
550 /// assert_eq!(d.pop_back(), None);
553 /// assert_eq!(d.pop_back(), Some(3));
555 #[stable(feature = "rust1", since = "1.0.0")]
556 pub fn pop_back(&mut self) -> Option<T> {
557 self.pop_back_node().map(|box Node{value, ..}| value)
560 /// Splits the list into two at the given index. Returns everything after the given index,
561 /// including the index.
563 /// This operation should compute in O(n) time.
567 /// use std::collections::DList;
569 /// let mut d = DList::new();
575 /// let mut splitted = d.split_off(2);
577 /// assert_eq!(splitted.pop_front(), Some(1));
578 /// assert_eq!(splitted.pop_front(), None);
580 #[stable(feature = "rust1", since = "1.0.0")]
581 pub fn split_off(&mut self, at: uint) -> DList<T> {
582 let len = self.len();
583 assert!(at < len, "Cannot split off at a nonexistent index");
585 return mem::replace(self, DList::new());
588 // Below, we iterate towards the `i-1`th node, either from the start or the end,
589 // depending on which would be faster.
590 let mut split_node = if at - 1 <= len - 1 - (at - 1) {
591 let mut iter = self.iter_mut();
592 // instead of skipping using .skip() (which creates a new struct),
593 // we skip manually so we can access the head field without
594 // depending on implementation details of Skip
600 // better off starting from the end
601 let mut iter = self.iter_mut();
602 for _ in 0..len - 1 - (at - 1) {
608 let mut splitted_list = DList {
610 list_tail: self.list_tail,
614 mem::swap(&mut split_node.resolve().unwrap().next, &mut splitted_list.list_head);
615 self.list_tail = split_node;
623 #[stable(feature = "rust1", since = "1.0.0")]
624 impl<T> Drop for DList<T> {
626 // Dissolve the dlist in backwards direction
627 // Just dropping the list_head can lead to stack exhaustion
628 // when length is >> 1_000_000
629 let mut tail = self.list_tail;
631 match tail.resolve() {
634 prev.next.take(); // release Box<Node<T>>
640 self.list_head = None;
641 self.list_tail = Rawlink::none();
645 #[stable(feature = "rust1", since = "1.0.0")]
646 impl<'a, A> Iterator for Iter<'a, A> {
650 fn next(&mut self) -> Option<&'a A> {
654 self.head.as_ref().map(|head| {
656 self.head = &head.next;
662 fn size_hint(&self) -> (uint, Option<uint>) {
663 (self.nelem, Some(self.nelem))
667 #[stable(feature = "rust1", since = "1.0.0")]
668 impl<'a, A> DoubleEndedIterator for Iter<'a, A> {
670 fn next_back(&mut self) -> Option<&'a A> {
674 self.tail.resolve_immut().as_ref().map(|prev| {
676 self.tail = prev.prev;
682 #[stable(feature = "rust1", since = "1.0.0")]
683 impl<'a, A> ExactSizeIterator for Iter<'a, A> {}
685 #[stable(feature = "rust1", since = "1.0.0")]
686 impl<'a, A> Iterator for IterMut<'a, A> {
687 type Item = &'a mut A;
689 fn next(&mut self) -> Option<&'a mut A> {
693 self.head.resolve().map(|next| {
695 self.head = match next.next {
696 Some(ref mut node) => Rawlink::some(&mut **node),
697 None => Rawlink::none(),
704 fn size_hint(&self) -> (uint, Option<uint>) {
705 (self.nelem, Some(self.nelem))
709 #[stable(feature = "rust1", since = "1.0.0")]
710 impl<'a, A> DoubleEndedIterator for IterMut<'a, A> {
712 fn next_back(&mut self) -> Option<&'a mut A> {
716 self.tail.resolve().map(|prev| {
718 self.tail = prev.prev;
724 #[stable(feature = "rust1", since = "1.0.0")]
725 impl<'a, A> ExactSizeIterator for IterMut<'a, A> {}
727 // private methods for IterMut
728 impl<'a, A> IterMut<'a, A> {
729 fn insert_next_node(&mut self, mut ins_node: Box<Node<A>>) {
730 // Insert before `self.head` so that it is between the
731 // previously yielded element and self.head.
733 // The inserted node will not appear in further iteration.
734 match self.head.resolve() {
735 None => { self.list.push_back_node(ins_node); }
737 let prev_node = match node.prev.resolve() {
738 None => return self.list.push_front_node(ins_node),
741 let node_own = prev_node.next.take().unwrap();
742 ins_node.next = link_with_prev(node_own, Rawlink::some(&mut *ins_node));
743 prev_node.next = link_with_prev(ins_node, Rawlink::some(prev_node));
744 self.list.length += 1;
750 impl<'a, A> IterMut<'a, A> {
751 /// Inserts `elt` just after the element most recently returned by `.next()`.
752 /// The inserted element does not appear in the iteration.
757 /// use std::collections::DList;
759 /// let mut list: DList<int> = vec![1, 3, 4].into_iter().collect();
762 /// let mut it = list.iter_mut();
763 /// assert_eq!(it.next().unwrap(), &1);
764 /// // insert `2` after `1`
765 /// it.insert_next(2);
768 /// let vec: Vec<int> = list.into_iter().collect();
769 /// assert_eq!(vec, vec![1, 2, 3, 4]);
773 #[unstable(feature = "collections",
774 reason = "this is probably better handled by a cursor type -- we'll see")]
775 pub fn insert_next(&mut self, elt: A) {
776 self.insert_next_node(box Node::new(elt))
779 /// Provides a reference to the next element, without changing the iterator.
784 /// use std::collections::DList;
786 /// let mut list: DList<int> = vec![1, 2, 3].into_iter().collect();
788 /// let mut it = list.iter_mut();
789 /// assert_eq!(it.next().unwrap(), &1);
790 /// assert_eq!(it.peek_next().unwrap(), &2);
791 /// // We just peeked at 2, so it was not consumed from the iterator.
792 /// assert_eq!(it.next().unwrap(), &2);
795 #[unstable(feature = "collections",
796 reason = "this is probably better handled by a cursor type -- we'll see")]
797 pub fn peek_next(&mut self) -> Option<&mut A> {
801 self.head.resolve().map(|head| &mut head.value)
805 #[stable(feature = "rust1", since = "1.0.0")]
806 impl<A> Iterator for IntoIter<A> {
810 fn next(&mut self) -> Option<A> { self.list.pop_front() }
813 fn size_hint(&self) -> (uint, Option<uint>) {
814 (self.list.length, Some(self.list.length))
818 #[stable(feature = "rust1", since = "1.0.0")]
819 impl<A> DoubleEndedIterator for IntoIter<A> {
821 fn next_back(&mut self) -> Option<A> { self.list.pop_back() }
824 #[stable(feature = "rust1", since = "1.0.0")]
825 impl<A> FromIterator<A> for DList<A> {
826 fn from_iter<T: Iterator<Item=A>>(iterator: T) -> DList<A> {
827 let mut ret = DList::new();
828 ret.extend(iterator);
833 impl<T> IntoIterator for DList<T> {
834 type Iter = IntoIter<T>;
836 fn into_iter(self) -> IntoIter<T> {
841 impl<'a, T> IntoIterator for &'a DList<T> {
842 type Iter = Iter<'a, T>;
844 fn into_iter(self) -> Iter<'a, T> {
849 impl<'a, T> IntoIterator for &'a mut DList<T> {
850 type Iter = IterMut<'a, T>;
852 fn into_iter(mut self) -> IterMut<'a, T> {
857 #[stable(feature = "rust1", since = "1.0.0")]
858 impl<A> Extend<A> for DList<A> {
859 fn extend<T: Iterator<Item=A>>(&mut self, mut iterator: T) {
860 for elt in iterator { self.push_back(elt); }
864 #[stable(feature = "rust1", since = "1.0.0")]
865 impl<A: PartialEq> PartialEq for DList<A> {
866 fn eq(&self, other: &DList<A>) -> bool {
867 self.len() == other.len() &&
868 iter::order::eq(self.iter(), other.iter())
871 fn ne(&self, other: &DList<A>) -> bool {
872 self.len() != other.len() ||
873 iter::order::ne(self.iter(), other.iter())
877 #[stable(feature = "rust1", since = "1.0.0")]
878 impl<A: Eq> Eq for DList<A> {}
880 #[stable(feature = "rust1", since = "1.0.0")]
881 impl<A: PartialOrd> PartialOrd for DList<A> {
882 fn partial_cmp(&self, other: &DList<A>) -> Option<Ordering> {
883 iter::order::partial_cmp(self.iter(), other.iter())
887 #[stable(feature = "rust1", since = "1.0.0")]
888 impl<A: Ord> Ord for DList<A> {
890 fn cmp(&self, other: &DList<A>) -> Ordering {
891 iter::order::cmp(self.iter(), other.iter())
895 #[stable(feature = "rust1", since = "1.0.0")]
896 impl<A: Clone> Clone for DList<A> {
897 fn clone(&self) -> DList<A> {
898 self.iter().map(|x| x.clone()).collect()
902 #[stable(feature = "rust1", since = "1.0.0")]
903 impl<A: fmt::Debug> fmt::Debug for DList<A> {
904 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
905 try!(write!(f, "DList ["));
907 for (i, e) in self.iter().enumerate() {
908 if i != 0 { try!(write!(f, ", ")); }
909 try!(write!(f, "{:?}", *e));
916 #[stable(feature = "rust1", since = "1.0.0")]
917 impl<S: Writer + Hasher, A: Hash<S>> Hash<S> for DList<A> {
918 fn hash(&self, state: &mut S) {
919 self.len().hash(state);
930 use std::hash::{self, SipHasher};
931 use std::thread::Thread;
935 use super::{DList, Node};
937 pub fn check_links<T>(list: &DList<T>) {
939 let mut last_ptr: Option<&Node<T>> = None;
940 let mut node_ptr: &Node<T>;
941 match list.list_head {
942 None => { assert_eq!(0u, list.length); return }
943 Some(ref node) => node_ptr = &**node,
946 match (last_ptr, node_ptr.prev.resolve_immut()) {
948 (None , _ ) => panic!("prev link for list_head"),
949 (Some(p), Some(pptr)) => {
950 assert_eq!(p as *const Node<T>, pptr as *const Node<T>);
952 _ => panic!("prev link is none, not good"),
954 match node_ptr.next {
956 last_ptr = Some(node_ptr);
966 assert_eq!(len, list.length);
971 let mut m: DList<Box<int>> = DList::new();
972 assert_eq!(m.pop_front(), None);
973 assert_eq!(m.pop_back(), None);
974 assert_eq!(m.pop_front(), None);
976 assert_eq!(m.pop_front(), Some(box 1));
979 assert_eq!(m.len(), 2);
980 assert_eq!(m.pop_front(), Some(box 2));
981 assert_eq!(m.pop_front(), Some(box 3));
982 assert_eq!(m.len(), 0);
983 assert_eq!(m.pop_front(), None);
988 assert_eq!(m.pop_front(), Some(box 1));
990 let mut n = DList::new();
994 assert_eq!(n.front().unwrap(), &3);
995 let x = n.front_mut().unwrap();
1000 assert_eq!(n.back().unwrap(), &2);
1001 let y = n.back_mut().unwrap();
1005 assert_eq!(n.pop_front(), Some(0));
1006 assert_eq!(n.pop_front(), Some(1));
1010 fn generate_test() -> DList<int> {
1011 list_from(&[0,1,2,3,4,5,6])
1015 fn list_from<T: Clone>(v: &[T]) -> DList<T> {
1016 v.iter().map(|x| (*x).clone()).collect()
1023 let mut m: DList<int> = DList::new();
1024 let mut n = DList::new();
1027 assert_eq!(m.len(), 0);
1028 assert_eq!(n.len(), 0);
1030 // Non-empty to empty
1032 let mut m = DList::new();
1033 let mut n = DList::new();
1037 assert_eq!(m.len(), 1);
1038 assert_eq!(m.pop_back(), Some(2));
1039 assert_eq!(n.len(), 0);
1042 // Empty to non-empty
1044 let mut m = DList::new();
1045 let mut n = DList::new();
1049 assert_eq!(m.len(), 1);
1050 assert_eq!(m.pop_back(), Some(2));
1054 // Non-empty to non-empty
1055 let v = vec![1,2,3,4,5];
1056 let u = vec![9,8,1,2,3,4,5];
1057 let mut m = list_from(v.as_slice());
1058 let mut n = list_from(u.as_slice());
1062 sum.push_all(u.as_slice());
1063 assert_eq!(sum.len(), m.len());
1065 assert_eq!(m.pop_front(), Some(elt))
1067 assert_eq!(n.len(), 0);
1068 // let's make sure it's working properly, since we
1069 // did some direct changes to private members
1071 assert_eq!(n.len(), 1);
1072 assert_eq!(n.pop_front(), Some(3));
1077 fn test_split_off() {
1080 let mut m = DList::new();
1083 let p = m.split_off(0);
1084 assert_eq!(m.len(), 0);
1085 assert_eq!(p.len(), 1);
1086 assert_eq!(p.back(), Some(&1));
1087 assert_eq!(p.front(), Some(&1));
1090 // not singleton, forwards
1092 let u = vec![1,2,3,4,5];
1093 let mut m = list_from(u.as_slice());
1094 let mut n = m.split_off(2);
1095 assert_eq!(m.len(), 2);
1096 assert_eq!(n.len(), 3);
1098 assert_eq!(m.pop_front(), Some(elt));
1101 assert_eq!(n.pop_front(), Some(elt));
1104 // not singleton, backwards
1106 let u = vec![1,2,3,4,5];
1107 let mut m = list_from(u.as_slice());
1108 let mut n = m.split_off(4);
1109 assert_eq!(m.len(), 4);
1110 assert_eq!(n.len(), 1);
1112 assert_eq!(m.pop_front(), Some(elt));
1115 assert_eq!(n.pop_front(), Some(elt));
1122 fn test_iterator() {
1123 let m = generate_test();
1124 for (i, elt) in m.iter().enumerate() {
1125 assert_eq!(i as int, *elt);
1127 let mut n = DList::new();
1128 assert_eq!(n.iter().next(), None);
1130 let mut it = n.iter();
1131 assert_eq!(it.size_hint(), (1, Some(1)));
1132 assert_eq!(it.next().unwrap(), &4);
1133 assert_eq!(it.size_hint(), (0, Some(0)));
1134 assert_eq!(it.next(), None);
1138 fn test_iterator_clone() {
1139 let mut n = DList::new();
1143 let mut it = n.iter();
1145 let mut jt = it.clone();
1146 assert_eq!(it.next(), jt.next());
1147 assert_eq!(it.next_back(), jt.next_back());
1148 assert_eq!(it.next(), jt.next());
1152 fn test_iterator_double_end() {
1153 let mut n = DList::new();
1154 assert_eq!(n.iter().next(), None);
1158 let mut it = n.iter();
1159 assert_eq!(it.size_hint(), (3, Some(3)));
1160 assert_eq!(it.next().unwrap(), &6);
1161 assert_eq!(it.size_hint(), (2, Some(2)));
1162 assert_eq!(it.next_back().unwrap(), &4);
1163 assert_eq!(it.size_hint(), (1, Some(1)));
1164 assert_eq!(it.next_back().unwrap(), &5);
1165 assert_eq!(it.next_back(), None);
1166 assert_eq!(it.next(), None);
1170 fn test_rev_iter() {
1171 let m = generate_test();
1172 for (i, elt) in m.iter().rev().enumerate() {
1173 assert_eq!((6 - i) as int, *elt);
1175 let mut n = DList::new();
1176 assert_eq!(n.iter().rev().next(), None);
1178 let mut it = n.iter().rev();
1179 assert_eq!(it.size_hint(), (1, Some(1)));
1180 assert_eq!(it.next().unwrap(), &4);
1181 assert_eq!(it.size_hint(), (0, Some(0)));
1182 assert_eq!(it.next(), None);
1186 fn test_mut_iter() {
1187 let mut m = generate_test();
1188 let mut len = m.len();
1189 for (i, elt) in m.iter_mut().enumerate() {
1190 assert_eq!(i as int, *elt);
1194 let mut n = DList::new();
1195 assert!(n.iter_mut().next().is_none());
1198 let mut it = n.iter_mut();
1199 assert_eq!(it.size_hint(), (2, Some(2)));
1200 assert!(it.next().is_some());
1201 assert!(it.next().is_some());
1202 assert_eq!(it.size_hint(), (0, Some(0)));
1203 assert!(it.next().is_none());
1207 fn test_iterator_mut_double_end() {
1208 let mut n = DList::new();
1209 assert!(n.iter_mut().next_back().is_none());
1213 let mut it = n.iter_mut();
1214 assert_eq!(it.size_hint(), (3, Some(3)));
1215 assert_eq!(*it.next().unwrap(), 6);
1216 assert_eq!(it.size_hint(), (2, Some(2)));
1217 assert_eq!(*it.next_back().unwrap(), 4);
1218 assert_eq!(it.size_hint(), (1, Some(1)));
1219 assert_eq!(*it.next_back().unwrap(), 5);
1220 assert!(it.next_back().is_none());
1221 assert!(it.next().is_none());
1225 fn test_insert_prev() {
1226 let mut m = list_from(&[0,2,4,6,8]);
1229 let mut it = m.iter_mut();
1235 it.insert_next(*elt + 1);
1236 match it.peek_next() {
1237 Some(x) => assert_eq!(*x, *elt + 2),
1238 None => assert_eq!(8, *elt),
1247 assert_eq!(m.len(), 3 + len * 2);
1248 assert_eq!(m.into_iter().collect::<Vec<int>>(), vec![-2,0,1,2,3,4,5,6,7,8,9,0,1]);
1252 fn test_mut_rev_iter() {
1253 let mut m = generate_test();
1254 for (i, elt) in m.iter_mut().rev().enumerate() {
1255 assert_eq!((6-i) as int, *elt);
1257 let mut n = DList::new();
1258 assert!(n.iter_mut().rev().next().is_none());
1260 let mut it = n.iter_mut().rev();
1261 assert!(it.next().is_some());
1262 assert!(it.next().is_none());
1267 let n = list_from(&[1,2,3]);
1268 Thread::scoped(move || {
1270 let a: &[_] = &[&1,&2,&3];
1271 assert_eq!(a, n.iter().collect::<Vec<&int>>());
1272 }).join().ok().unwrap();
1277 let mut n: DList<u8> = list_from(&[]);
1278 let mut m = list_from(&[]);
1285 let n = list_from(&[2,3,4]);
1286 let m = list_from(&[1,2,3]);
1292 let mut x = DList::new();
1293 let mut y = DList::new();
1295 assert!(hash::hash::<_, SipHasher>(&x) == hash::hash::<_, SipHasher>(&y));
1305 assert!(hash::hash::<_, SipHasher>(&x) == hash::hash::<_, SipHasher>(&y));
1310 let n: DList<int> = list_from(&[]);
1311 let m = list_from(&[1,2,3]);
1320 let nan = 0.0f64/0.0;
1321 let n = list_from(&[nan]);
1322 let m = list_from(&[nan]);
1328 let n = list_from(&[nan]);
1329 let one = list_from(&[1.0f64]);
1330 assert!(!(n < one));
1331 assert!(!(n > one));
1332 assert!(!(n <= one));
1333 assert!(!(n >= one));
1335 let u = list_from(&[1.0f64,2.0,nan]);
1336 let v = list_from(&[1.0f64,2.0,3.0]);
1342 let s = list_from(&[1.0f64,2.0,4.0,2.0]);
1343 let t = list_from(&[1.0f64,2.0,3.0,2.0]);
1346 assert!(!(s <= one));
1361 let list: DList<i32> = (0..10).collect();
1362 assert_eq!(format!("{:?}", list), "DList [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]");
1364 let list: DList<&str> = vec!["just", "one", "test", "more"].iter()
1367 assert_eq!(format!("{:?}", list), "DList [\"just\", \"one\", \"test\", \"more\"]");
1371 fn fuzz_test(sz: int) {
1372 let mut m: DList<int> = DList::new();
1376 let r: u8 = rand::random();
1402 for (a, &b) in m.into_iter().zip(v.iter()) {
1406 assert_eq!(i, v.len());
1410 fn bench_collect_into(b: &mut test::Bencher) {
1413 let _: DList<int> = v.iter().map(|x| *x).collect();
1418 fn bench_push_front(b: &mut test::Bencher) {
1419 let mut m: DList<int> = DList::new();
1426 fn bench_push_back(b: &mut test::Bencher) {
1427 let mut m: DList<int> = DList::new();
1434 fn bench_push_back_pop_back(b: &mut test::Bencher) {
1435 let mut m: DList<int> = DList::new();
1443 fn bench_push_front_pop_front(b: &mut test::Bencher) {
1444 let mut m: DList<int> = DList::new();
1452 fn bench_iter(b: &mut test::Bencher) {
1454 let m: DList<int> = v.iter().map(|&x|x).collect();
1456 assert!(m.iter().count() == 128);
1460 fn bench_iter_mut(b: &mut test::Bencher) {
1462 let mut m: DList<int> = v.iter().map(|&x|x).collect();
1464 assert!(m.iter_mut().count() == 128);
1468 fn bench_iter_rev(b: &mut test::Bencher) {
1470 let m: DList<int> = v.iter().map(|&x|x).collect();
1472 assert!(m.iter().rev().count() == 128);
1476 fn bench_iter_mut_rev(b: &mut test::Bencher) {
1478 let mut m: DList<int> = v.iter().map(|&x|x).collect();
1480 assert!(m.iter_mut().rev().count() == 128);