]> git.lizzy.rs Git - rust.git/blob - src/libcollections/dlist.rs
ed2d67388766700ebd3b99ddf4ec9d739d05ea88
[rust.git] / src / libcollections / dlist.rs
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.
4 //
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.
10
11 //! A doubly-linked list with owned nodes.
12 //!
13 //! The DList allows pushing and popping elements at either end.
14 //!
15 //! DList implements the trait Deque. It should be imported with `use
16 //! collections::Deque`.
17
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.
20 //
21 // Backlinks over DList::prev are raw pointers that form a full chain in
22 // the reverse direction.
23
24 use core::prelude::*;
25
26 use alloc::owned::Box;
27 use core::default::Default;
28 use core::fmt;
29 use core::iter;
30 use core::mem;
31 use core::ptr;
32
33 use {Collection, Mutable, Deque};
34
35 /// A doubly-linked list.
36 pub struct DList<T> {
37     length: uint,
38     list_head: Link<T>,
39     list_tail: Rawlink<Node<T>>,
40 }
41
42 type Link<T> = Option<Box<Node<T>>>;
43 struct Rawlink<T> { p: *mut T }
44
45 struct Node<T> {
46     next: Link<T>,
47     prev: Rawlink<Node<T>>,
48     value: T,
49 }
50
51 /// Double-ended DList iterator
52 pub struct Items<'a, T> {
53     head: &'a Link<T>,
54     tail: Rawlink<Node<T>>,
55     nelem: uint,
56 }
57
58 // FIXME #11820: the &'a Option<> of the Link stops clone working.
59 impl<'a, T> Clone for Items<'a, T> {
60     fn clone(&self) -> Items<'a, T> { *self }
61 }
62
63 /// Double-ended mutable DList iterator
64 pub struct MutItems<'a, T> {
65     list: &'a mut DList<T>,
66     head: Rawlink<Node<T>>,
67     tail: Rawlink<Node<T>>,
68     nelem: uint,
69 }
70
71 /// DList consuming iterator
72 #[deriving(Clone)]
73 pub struct MoveItems<T> {
74     list: DList<T>
75 }
76
77 /// Rawlink is a type like Option<T> but for holding a raw pointer
78 impl<T> Rawlink<T> {
79     /// Like Option::None for Rawlink
80     fn none() -> Rawlink<T> {
81         Rawlink{p: ptr::mut_null()}
82     }
83
84     /// Like Option::Some for Rawlink
85     fn some(n: &mut T) -> Rawlink<T> {
86         Rawlink{p: n}
87     }
88
89     /// Convert the `Rawlink` into an Option value
90     fn resolve_immut(&self) -> Option<&T> {
91         unsafe { self.p.to_option() }
92     }
93
94     /// Convert the `Rawlink` into an Option value
95     fn resolve(&mut self) -> Option<&mut T> {
96         if self.p.is_null() {
97             None
98         } else {
99             Some(unsafe { mem::transmute(self.p) })
100         }
101     }
102
103     /// Return the `Rawlink` and replace with `Rawlink::none()`
104     fn take(&mut self) -> Rawlink<T> {
105         mem::replace(self, Rawlink::none())
106     }
107 }
108
109 impl<T> Clone for Rawlink<T> {
110     #[inline]
111     fn clone(&self) -> Rawlink<T> {
112         Rawlink{p: self.p}
113     }
114 }
115
116 impl<T> Node<T> {
117     fn new(v: T) -> Node<T> {
118         Node{value: v, next: None, prev: Rawlink::none()}
119     }
120 }
121
122 /// Set the .prev field on `next`, then return `Some(next)`
123 fn link_with_prev<T>(mut next: Box<Node<T>>, prev: Rawlink<Node<T>>)
124                   -> Link<T> {
125     next.prev = prev;
126     Some(next)
127 }
128
129 impl<T> Collection for DList<T> {
130     /// O(1)
131     #[inline]
132     fn is_empty(&self) -> bool {
133         self.list_head.is_none()
134     }
135     /// O(1)
136     #[inline]
137     fn len(&self) -> uint {
138         self.length
139     }
140 }
141
142 impl<T> Mutable for DList<T> {
143     /// Remove all elements from the DList
144     ///
145     /// O(N)
146     #[inline]
147     fn clear(&mut self) {
148         *self = DList::new()
149     }
150 }
151
152 // private methods
153 impl<T> DList<T> {
154     /// Add a Node first in the list
155     #[inline]
156     fn push_front_node(&mut self, mut new_head: Box<Node<T>>) {
157         match self.list_head {
158             None => {
159                 self.list_tail = Rawlink::some(&mut *new_head);
160                 self.list_head = link_with_prev(new_head, Rawlink::none());
161             }
162             Some(ref mut head) => {
163                 new_head.prev = Rawlink::none();
164                 head.prev = Rawlink::some(&mut *new_head);
165                 mem::swap(head, &mut new_head);
166                 head.next = Some(new_head);
167             }
168         }
169         self.length += 1;
170     }
171
172     /// Remove the first Node and return it, or None if the list is empty
173     #[inline]
174     fn pop_front_node(&mut self) -> Option<Box<Node<T>>> {
175         self.list_head.take().map(|mut front_node| {
176             self.length -= 1;
177             match front_node.next.take() {
178                 Some(node) => self.list_head = link_with_prev(node, Rawlink::none()),
179                 None => self.list_tail = Rawlink::none()
180             }
181             front_node
182         })
183     }
184
185     /// Add a Node last in the list
186     #[inline]
187     fn push_back_node(&mut self, mut new_tail: Box<Node<T>>) {
188         match self.list_tail.resolve() {
189             None => return self.push_front_node(new_tail),
190             Some(tail) => {
191                 self.list_tail = Rawlink::some(&mut *new_tail);
192                 tail.next = link_with_prev(new_tail, Rawlink::some(tail));
193             }
194         }
195         self.length += 1;
196     }
197
198     /// Remove the last Node and return it, or None if the list is empty
199     #[inline]
200     fn pop_back_node(&mut self) -> Option<Box<Node<T>>> {
201         self.list_tail.resolve().map_or(None, |tail| {
202             self.length -= 1;
203             self.list_tail = tail.prev;
204             match tail.prev.resolve() {
205                 None => self.list_head.take(),
206                 Some(tail_prev) => tail_prev.next.take()
207             }
208         })
209     }
210 }
211
212 impl<T> Deque<T> for DList<T> {
213     /// Provide a reference to the front element, or None if the list is empty
214     #[inline]
215     fn front<'a>(&'a self) -> Option<&'a T> {
216         self.list_head.as_ref().map(|head| &head.value)
217     }
218
219     /// Provide a mutable reference to the front element, or None if the list is empty
220     #[inline]
221     fn front_mut<'a>(&'a mut self) -> Option<&'a mut T> {
222         self.list_head.as_mut().map(|head| &mut head.value)
223     }
224
225     /// Provide a reference to the back element, or None if the list is empty
226     #[inline]
227     fn back<'a>(&'a self) -> Option<&'a T> {
228         self.list_tail.resolve_immut().as_ref().map(|tail| &tail.value)
229     }
230
231     /// Provide a mutable reference to the back element, or None if the list is empty
232     #[inline]
233     fn back_mut<'a>(&'a mut self) -> Option<&'a mut T> {
234         self.list_tail.resolve().map(|tail| &mut tail.value)
235     }
236
237     /// Add an element first in the list
238     ///
239     /// O(1)
240     fn push_front(&mut self, elt: T) {
241         self.push_front_node(box Node::new(elt))
242     }
243
244     /// Remove the first element and return it, or None if the list is empty
245     ///
246     /// O(1)
247     fn pop_front(&mut self) -> Option<T> {
248         self.pop_front_node().map(|box Node{value, ..}| value)
249     }
250
251     /// Add an element last in the list
252     ///
253     /// O(1)
254     fn push_back(&mut self, elt: T) {
255         self.push_back_node(box Node::new(elt))
256     }
257
258     /// Remove the last element and return it, or None if the list is empty
259     ///
260     /// O(1)
261     fn pop_back(&mut self) -> Option<T> {
262         self.pop_back_node().map(|box Node{value, ..}| value)
263     }
264 }
265
266 impl<T> Default for DList<T> {
267     #[inline]
268     fn default() -> DList<T> { DList::new() }
269 }
270
271 impl<T> DList<T> {
272     /// Create an empty DList
273     #[inline]
274     pub fn new() -> DList<T> {
275         DList{list_head: None, list_tail: Rawlink::none(), length: 0}
276     }
277
278     /// Move the last element to the front of the list.
279     ///
280     /// If the list is empty, do nothing.
281     #[inline]
282     pub fn rotate_forward(&mut self) {
283         self.pop_back_node().map(|tail| {
284             self.push_front_node(tail)
285         });
286     }
287
288     /// Move the first element to the back of the list.
289     ///
290     /// If the list is empty, do nothing.
291     #[inline]
292     pub fn rotate_backward(&mut self) {
293         self.pop_front_node().map(|head| {
294             self.push_back_node(head)
295         });
296     }
297
298     /// Add all elements from `other` to the end of the list
299     ///
300     /// O(1)
301     pub fn append(&mut self, mut other: DList<T>) {
302         match self.list_tail.resolve() {
303             None => *self = other,
304             Some(tail) => {
305                 // Carefully empty `other`.
306                 let o_tail = other.list_tail.take();
307                 let o_length = other.length;
308                 match other.list_head.take() {
309                     None => return,
310                     Some(node) => {
311                         tail.next = link_with_prev(node, self.list_tail);
312                         self.list_tail = o_tail;
313                         self.length += o_length;
314                     }
315                 }
316             }
317         }
318     }
319
320     /// Add all elements from `other` to the beginning of the list
321     ///
322     /// O(1)
323     #[inline]
324     pub fn prepend(&mut self, mut other: DList<T>) {
325         mem::swap(self, &mut other);
326         self.append(other);
327     }
328
329     /// Insert `elt` before the first `x` in the list where `f(x, elt)` is true,
330     /// or at the end.
331     ///
332     /// O(N)
333     pub fn insert_when(&mut self, elt: T, f: |&T, &T| -> bool) {
334         {
335             let mut it = self.mut_iter();
336             loop {
337                 match it.peek_next() {
338                     None => break,
339                     Some(x) => if f(x, &elt) { break }
340                 }
341                 it.next();
342             }
343             it.insert_next(elt);
344         }
345     }
346
347     /// Merge DList `other` into this DList, using the function `f`.
348     /// Iterate the both DList with `a` from self and `b` from `other`, and
349     /// put `a` in the result if `f(a, b)` is true, else `b`.
350     ///
351     /// O(max(N, M))
352     pub fn merge(&mut self, mut other: DList<T>, f: |&T, &T| -> bool) {
353         {
354             let mut it = self.mut_iter();
355             loop {
356                 let take_a = match (it.peek_next(), other.front()) {
357                     (_   , None) => return,
358                     (None, _   ) => break,
359                     (Some(ref mut x), Some(y)) => f(*x, y),
360                 };
361                 if take_a {
362                     it.next();
363                 } else {
364                     it.insert_next_node(other.pop_front_node().unwrap());
365                 }
366             }
367         }
368         self.append(other);
369     }
370
371
372     /// Provide a forward iterator
373     #[inline]
374     pub fn iter<'a>(&'a self) -> Items<'a, T> {
375         Items{nelem: self.len(), head: &self.list_head, tail: self.list_tail}
376     }
377
378     /// Provide a forward iterator with mutable references
379     #[inline]
380     pub fn mut_iter<'a>(&'a mut self) -> MutItems<'a, T> {
381         let head_raw = match self.list_head {
382             Some(ref mut h) => Rawlink::some(&mut **h),
383             None => Rawlink::none(),
384         };
385         MutItems{
386             nelem: self.len(),
387             head: head_raw,
388             tail: self.list_tail,
389             list: self
390         }
391     }
392
393
394     /// Consume the list into an iterator yielding elements by value
395     #[inline]
396     pub fn move_iter(self) -> MoveItems<T> {
397         MoveItems{list: self}
398     }
399 }
400
401 impl<T: Ord> DList<T> {
402     /// Insert `elt` sorted in ascending order
403     ///
404     /// O(N)
405     #[inline]
406     pub fn insert_ordered(&mut self, elt: T) {
407         self.insert_when(elt, |a, b| a >= b)
408     }
409 }
410
411 #[unsafe_destructor]
412 impl<T> Drop for DList<T> {
413     fn drop(&mut self) {
414         // Dissolve the dlist in backwards direction
415         // Just dropping the list_head can lead to stack exhaustion
416         // when length is >> 1_000_000
417         let mut tail = self.list_tail;
418         loop {
419             match tail.resolve() {
420                 None => break,
421                 Some(prev) => {
422                     prev.next.take(); // release Box<Node<T>>
423                     tail = prev.prev;
424                 }
425             }
426         }
427         self.length = 0;
428         self.list_head = None;
429         self.list_tail = Rawlink::none();
430     }
431 }
432
433
434 impl<'a, A> Iterator<&'a A> for Items<'a, A> {
435     #[inline]
436     fn next(&mut self) -> Option<&'a A> {
437         if self.nelem == 0 {
438             return None;
439         }
440         self.head.as_ref().map(|head| {
441             self.nelem -= 1;
442             self.head = &head.next;
443             &head.value
444         })
445     }
446
447     #[inline]
448     fn size_hint(&self) -> (uint, Option<uint>) {
449         (self.nelem, Some(self.nelem))
450     }
451 }
452
453 impl<'a, A> DoubleEndedIterator<&'a A> for Items<'a, A> {
454     #[inline]
455     fn next_back(&mut self) -> Option<&'a A> {
456         if self.nelem == 0 {
457             return None;
458         }
459         self.tail.resolve_immut().as_ref().map(|prev| {
460             self.nelem -= 1;
461             self.tail = prev.prev;
462             &prev.value
463         })
464     }
465 }
466
467 impl<'a, A> ExactSize<&'a A> for Items<'a, A> {}
468
469 impl<'a, A> Iterator<&'a mut A> for MutItems<'a, A> {
470     #[inline]
471     fn next(&mut self) -> Option<&'a mut A> {
472         if self.nelem == 0 {
473             return None;
474         }
475         self.head.resolve().map(|next| {
476             self.nelem -= 1;
477             self.head = match next.next {
478                 Some(ref mut node) => Rawlink::some(&mut **node),
479                 None => Rawlink::none(),
480             };
481             &mut next.value
482         })
483     }
484
485     #[inline]
486     fn size_hint(&self) -> (uint, Option<uint>) {
487         (self.nelem, Some(self.nelem))
488     }
489 }
490
491 impl<'a, A> DoubleEndedIterator<&'a mut A> for MutItems<'a, A> {
492     #[inline]
493     fn next_back(&mut self) -> Option<&'a mut A> {
494         if self.nelem == 0 {
495             return None;
496         }
497         self.tail.resolve().map(|prev| {
498             self.nelem -= 1;
499             self.tail = prev.prev;
500             &mut prev.value
501         })
502     }
503 }
504
505 impl<'a, A> ExactSize<&'a mut A> for MutItems<'a, A> {}
506
507 /// Allow mutating the DList while iterating
508 pub trait ListInsertion<A> {
509     /// Insert `elt` just after to the element most recently returned by `.next()`
510     ///
511     /// The inserted element does not appear in the iteration.
512     fn insert_next(&mut self, elt: A);
513
514     /// Provide a reference to the next element, without changing the iterator
515     fn peek_next<'a>(&'a mut self) -> Option<&'a mut A>;
516 }
517
518 // private methods for MutItems
519 impl<'a, A> MutItems<'a, A> {
520     fn insert_next_node(&mut self, mut ins_node: Box<Node<A>>) {
521         // Insert before `self.head` so that it is between the
522         // previously yielded element and self.head.
523         //
524         // The inserted node will not appear in further iteration.
525         match self.head.resolve() {
526             None => { self.list.push_back_node(ins_node); }
527             Some(node) => {
528                 let prev_node = match node.prev.resolve() {
529                     None => return self.list.push_front_node(ins_node),
530                     Some(prev) => prev,
531                 };
532                 let node_own = prev_node.next.take_unwrap();
533                 ins_node.next = link_with_prev(node_own, Rawlink::some(&mut *ins_node));
534                 prev_node.next = link_with_prev(ins_node, Rawlink::some(prev_node));
535                 self.list.length += 1;
536             }
537         }
538     }
539 }
540
541 impl<'a, A> ListInsertion<A> for MutItems<'a, A> {
542     #[inline]
543     fn insert_next(&mut self, elt: A) {
544         self.insert_next_node(box Node::new(elt))
545     }
546
547     #[inline]
548     fn peek_next<'a>(&'a mut self) -> Option<&'a mut A> {
549         if self.nelem == 0 {
550             return None
551         }
552         self.head.resolve().map(|head| &mut head.value)
553     }
554 }
555
556 impl<A> Iterator<A> for MoveItems<A> {
557     #[inline]
558     fn next(&mut self) -> Option<A> { self.list.pop_front() }
559
560     #[inline]
561     fn size_hint(&self) -> (uint, Option<uint>) {
562         (self.list.length, Some(self.list.length))
563     }
564 }
565
566 impl<A> DoubleEndedIterator<A> for MoveItems<A> {
567     #[inline]
568     fn next_back(&mut self) -> Option<A> { self.list.pop_back() }
569 }
570
571 impl<A> FromIterator<A> for DList<A> {
572     fn from_iter<T: Iterator<A>>(iterator: T) -> DList<A> {
573         let mut ret = DList::new();
574         ret.extend(iterator);
575         ret
576     }
577 }
578
579 impl<A> Extendable<A> for DList<A> {
580     fn extend<T: Iterator<A>>(&mut self, mut iterator: T) {
581         for elt in iterator { self.push_back(elt); }
582     }
583 }
584
585 impl<A: PartialEq> PartialEq for DList<A> {
586     fn eq(&self, other: &DList<A>) -> bool {
587         self.len() == other.len() &&
588             iter::order::eq(self.iter(), other.iter())
589     }
590
591     fn ne(&self, other: &DList<A>) -> bool {
592         self.len() != other.len() ||
593             iter::order::ne(self.iter(), other.iter())
594     }
595 }
596
597 impl<A: PartialOrd> PartialOrd for DList<A> {
598     fn partial_cmp(&self, other: &DList<A>) -> Option<Ordering> {
599         iter::order::partial_cmp(self.iter(), other.iter())
600     }
601 }
602
603 impl<A: Clone> Clone for DList<A> {
604     fn clone(&self) -> DList<A> {
605         self.iter().map(|x| x.clone()).collect()
606     }
607 }
608
609 impl<A: fmt::Show> fmt::Show for DList<A> {
610     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
611         try!(write!(f, "["));
612
613         for (i, e) in self.iter().enumerate() {
614             if i != 0 { try!(write!(f, ", ")); }
615             try!(write!(f, "{}", *e));
616         }
617
618         write!(f, "]")
619     }
620 }
621
622 #[cfg(test)]
623 mod tests {
624     use std::prelude::*;
625     use std::rand;
626     use test::Bencher;
627     use test;
628
629     use Deque;
630     use super::{DList, Node, ListInsertion};
631     use vec::Vec;
632
633     pub fn check_links<T>(list: &DList<T>) {
634         let mut len = 0u;
635         let mut last_ptr: Option<&Node<T>> = None;
636         let mut node_ptr: &Node<T>;
637         match list.list_head {
638             None => { assert_eq!(0u, list.length); return }
639             Some(ref node) => node_ptr = &**node,
640         }
641         loop {
642             match (last_ptr, node_ptr.prev.resolve_immut()) {
643                 (None   , None      ) => {}
644                 (None   , _         ) => fail!("prev link for list_head"),
645                 (Some(p), Some(pptr)) => {
646                     assert_eq!(p as *const Node<T>, pptr as *const Node<T>);
647                 }
648                 _ => fail!("prev link is none, not good"),
649             }
650             match node_ptr.next {
651                 Some(ref next) => {
652                     last_ptr = Some(node_ptr);
653                     node_ptr = &**next;
654                     len += 1;
655                 }
656                 None => {
657                     len += 1;
658                     break;
659                 }
660             }
661         }
662         assert_eq!(len, list.length);
663     }
664
665     #[test]
666     fn test_basic() {
667         let mut m: DList<Box<int>> = DList::new();
668         assert_eq!(m.pop_front(), None);
669         assert_eq!(m.pop_back(), None);
670         assert_eq!(m.pop_front(), None);
671         m.push_front(box 1);
672         assert_eq!(m.pop_front(), Some(box 1));
673         m.push_back(box 2);
674         m.push_back(box 3);
675         assert_eq!(m.len(), 2);
676         assert_eq!(m.pop_front(), Some(box 2));
677         assert_eq!(m.pop_front(), Some(box 3));
678         assert_eq!(m.len(), 0);
679         assert_eq!(m.pop_front(), None);
680         m.push_back(box 1);
681         m.push_back(box 3);
682         m.push_back(box 5);
683         m.push_back(box 7);
684         assert_eq!(m.pop_front(), Some(box 1));
685
686         let mut n = DList::new();
687         n.push_front(2i);
688         n.push_front(3);
689         {
690             assert_eq!(n.front().unwrap(), &3);
691             let x = n.front_mut().unwrap();
692             assert_eq!(*x, 3);
693             *x = 0;
694         }
695         {
696             assert_eq!(n.back().unwrap(), &2);
697             let y = n.back_mut().unwrap();
698             assert_eq!(*y, 2);
699             *y = 1;
700         }
701         assert_eq!(n.pop_front(), Some(0));
702         assert_eq!(n.pop_front(), Some(1));
703     }
704
705     #[cfg(test)]
706     fn generate_test() -> DList<int> {
707         list_from(&[0i,1,2,3,4,5,6])
708     }
709
710     #[cfg(test)]
711     fn list_from<T: Clone>(v: &[T]) -> DList<T> {
712         v.iter().map(|x| (*x).clone()).collect()
713     }
714
715     #[test]
716     fn test_append() {
717         {
718             let mut m = DList::new();
719             let mut n = DList::new();
720             n.push_back(2i);
721             m.append(n);
722             assert_eq!(m.len(), 1);
723             assert_eq!(m.pop_back(), Some(2));
724             check_links(&m);
725         }
726         {
727             let mut m = DList::new();
728             let n = DList::new();
729             m.push_back(2i);
730             m.append(n);
731             assert_eq!(m.len(), 1);
732             assert_eq!(m.pop_back(), Some(2));
733             check_links(&m);
734         }
735
736         let v = vec![1i,2,3,4,5];
737         let u = vec![9i,8,1,2,3,4,5];
738         let mut m = list_from(v.as_slice());
739         m.append(list_from(u.as_slice()));
740         check_links(&m);
741         let sum = v.append(u.as_slice());
742         assert_eq!(sum.len(), m.len());
743         for elt in sum.move_iter() {
744             assert_eq!(m.pop_front(), Some(elt))
745         }
746     }
747
748     #[test]
749     fn test_prepend() {
750         {
751             let mut m = DList::new();
752             let mut n = DList::new();
753             n.push_back(2i);
754             m.prepend(n);
755             assert_eq!(m.len(), 1);
756             assert_eq!(m.pop_back(), Some(2));
757             check_links(&m);
758         }
759
760         let v = vec![1i,2,3,4,5];
761         let u = vec![9i,8,1,2,3,4,5];
762         let mut m = list_from(v.as_slice());
763         m.prepend(list_from(u.as_slice()));
764         check_links(&m);
765         let sum = u.append(v.as_slice());
766         assert_eq!(sum.len(), m.len());
767         for elt in sum.move_iter() {
768             assert_eq!(m.pop_front(), Some(elt))
769         }
770     }
771
772     #[test]
773     fn test_rotate() {
774         let mut n: DList<int> = DList::new();
775         n.rotate_backward(); check_links(&n);
776         assert_eq!(n.len(), 0);
777         n.rotate_forward(); check_links(&n);
778         assert_eq!(n.len(), 0);
779
780         let v = vec![1i,2,3,4,5];
781         let mut m = list_from(v.as_slice());
782         m.rotate_backward(); check_links(&m);
783         m.rotate_forward(); check_links(&m);
784         assert_eq!(v.iter().collect::<Vec<&int>>(), m.iter().collect());
785         m.rotate_forward(); check_links(&m);
786         m.rotate_forward(); check_links(&m);
787         m.pop_front(); check_links(&m);
788         m.rotate_forward(); check_links(&m);
789         m.rotate_backward(); check_links(&m);
790         m.push_front(9); check_links(&m);
791         m.rotate_forward(); check_links(&m);
792         assert_eq!(vec![3i,9,5,1,2], m.move_iter().collect());
793     }
794
795     #[test]
796     fn test_iterator() {
797         let m = generate_test();
798         for (i, elt) in m.iter().enumerate() {
799             assert_eq!(i as int, *elt);
800         }
801         let mut n = DList::new();
802         assert_eq!(n.iter().next(), None);
803         n.push_front(4i);
804         let mut it = n.iter();
805         assert_eq!(it.size_hint(), (1, Some(1)));
806         assert_eq!(it.next().unwrap(), &4);
807         assert_eq!(it.size_hint(), (0, Some(0)));
808         assert_eq!(it.next(), None);
809     }
810
811     #[test]
812     fn test_iterator_clone() {
813         let mut n = DList::new();
814         n.push_back(2i);
815         n.push_back(3);
816         n.push_back(4);
817         let mut it = n.iter();
818         it.next();
819         let mut jt = it.clone();
820         assert_eq!(it.next(), jt.next());
821         assert_eq!(it.next_back(), jt.next_back());
822         assert_eq!(it.next(), jt.next());
823     }
824
825     #[test]
826     fn test_iterator_double_end() {
827         let mut n = DList::new();
828         assert_eq!(n.iter().next(), None);
829         n.push_front(4i);
830         n.push_front(5);
831         n.push_front(6);
832         let mut it = n.iter();
833         assert_eq!(it.size_hint(), (3, Some(3)));
834         assert_eq!(it.next().unwrap(), &6);
835         assert_eq!(it.size_hint(), (2, Some(2)));
836         assert_eq!(it.next_back().unwrap(), &4);
837         assert_eq!(it.size_hint(), (1, Some(1)));
838         assert_eq!(it.next_back().unwrap(), &5);
839         assert_eq!(it.next_back(), None);
840         assert_eq!(it.next(), None);
841     }
842
843     #[test]
844     fn test_rev_iter() {
845         let m = generate_test();
846         for (i, elt) in m.iter().rev().enumerate() {
847             assert_eq!((6 - i) as int, *elt);
848         }
849         let mut n = DList::new();
850         assert_eq!(n.iter().rev().next(), None);
851         n.push_front(4i);
852         let mut it = n.iter().rev();
853         assert_eq!(it.size_hint(), (1, Some(1)));
854         assert_eq!(it.next().unwrap(), &4);
855         assert_eq!(it.size_hint(), (0, Some(0)));
856         assert_eq!(it.next(), None);
857     }
858
859     #[test]
860     fn test_mut_iter() {
861         let mut m = generate_test();
862         let mut len = m.len();
863         for (i, elt) in m.mut_iter().enumerate() {
864             assert_eq!(i as int, *elt);
865             len -= 1;
866         }
867         assert_eq!(len, 0);
868         let mut n = DList::new();
869         assert!(n.mut_iter().next().is_none());
870         n.push_front(4i);
871         n.push_back(5);
872         let mut it = n.mut_iter();
873         assert_eq!(it.size_hint(), (2, Some(2)));
874         assert!(it.next().is_some());
875         assert!(it.next().is_some());
876         assert_eq!(it.size_hint(), (0, Some(0)));
877         assert!(it.next().is_none());
878     }
879
880     #[test]
881     fn test_iterator_mut_double_end() {
882         let mut n = DList::new();
883         assert!(n.mut_iter().next_back().is_none());
884         n.push_front(4i);
885         n.push_front(5);
886         n.push_front(6);
887         let mut it = n.mut_iter();
888         assert_eq!(it.size_hint(), (3, Some(3)));
889         assert_eq!(*it.next().unwrap(), 6);
890         assert_eq!(it.size_hint(), (2, Some(2)));
891         assert_eq!(*it.next_back().unwrap(), 4);
892         assert_eq!(it.size_hint(), (1, Some(1)));
893         assert_eq!(*it.next_back().unwrap(), 5);
894         assert!(it.next_back().is_none());
895         assert!(it.next().is_none());
896     }
897
898     #[test]
899     fn test_insert_prev() {
900         let mut m = list_from(&[0i,2,4,6,8]);
901         let len = m.len();
902         {
903             let mut it = m.mut_iter();
904             it.insert_next(-2);
905             loop {
906                 match it.next() {
907                     None => break,
908                     Some(elt) => {
909                         it.insert_next(*elt + 1);
910                         match it.peek_next() {
911                             Some(x) => assert_eq!(*x, *elt + 2),
912                             None => assert_eq!(8, *elt),
913                         }
914                     }
915                 }
916             }
917             it.insert_next(0);
918             it.insert_next(1);
919         }
920         check_links(&m);
921         assert_eq!(m.len(), 3 + len * 2);
922         assert_eq!(m.move_iter().collect::<Vec<int>>(), vec![-2,0,1,2,3,4,5,6,7,8,9,0,1]);
923     }
924
925     #[test]
926     fn test_merge() {
927         let mut m = list_from([0i, 1, 3, 5, 6, 7, 2]);
928         let n = list_from([-1i, 0, 0, 7, 7, 9]);
929         let len = m.len() + n.len();
930         m.merge(n, |a, b| a <= b);
931         assert_eq!(m.len(), len);
932         check_links(&m);
933         let res = m.move_iter().collect::<Vec<int>>();
934         assert_eq!(res, vec![-1, 0, 0, 0, 1, 3, 5, 6, 7, 2, 7, 7, 9]);
935     }
936
937     #[test]
938     fn test_insert_ordered() {
939         let mut n = DList::new();
940         n.insert_ordered(1i);
941         assert_eq!(n.len(), 1);
942         assert_eq!(n.pop_front(), Some(1));
943
944         let mut m = DList::new();
945         m.push_back(2i);
946         m.push_back(4);
947         m.insert_ordered(3);
948         check_links(&m);
949         assert_eq!(vec![2,3,4], m.move_iter().collect::<Vec<int>>());
950     }
951
952     #[test]
953     fn test_mut_rev_iter() {
954         let mut m = generate_test();
955         for (i, elt) in m.mut_iter().rev().enumerate() {
956             assert_eq!((6-i) as int, *elt);
957         }
958         let mut n = DList::new();
959         assert!(n.mut_iter().rev().next().is_none());
960         n.push_front(4i);
961         let mut it = n.mut_iter().rev();
962         assert!(it.next().is_some());
963         assert!(it.next().is_none());
964     }
965
966     #[test]
967     fn test_send() {
968         let n = list_from([1i,2,3]);
969         spawn(proc() {
970             check_links(&n);
971             assert_eq!(&[&1,&2,&3], n.iter().collect::<Vec<&int>>().as_slice());
972         });
973     }
974
975     #[test]
976     fn test_eq() {
977         let mut n: DList<u8> = list_from([]);
978         let mut m = list_from([]);
979         assert!(n == m);
980         n.push_front(1);
981         assert!(n != m);
982         m.push_back(1);
983         assert!(n == m);
984
985         let n = list_from([2i,3,4]);
986         let m = list_from([1i,2,3]);
987         assert!(n != m);
988     }
989
990     #[test]
991     fn test_ord() {
992         let n: DList<int> = list_from([]);
993         let m = list_from([1i,2,3]);
994         assert!(n < m);
995         assert!(m > n);
996         assert!(n <= n);
997         assert!(n >= n);
998     }
999
1000     #[test]
1001     fn test_ord_nan() {
1002         let nan = 0.0f64/0.0;
1003         let n = list_from([nan]);
1004         let m = list_from([nan]);
1005         assert!(!(n < m));
1006         assert!(!(n > m));
1007         assert!(!(n <= m));
1008         assert!(!(n >= m));
1009
1010         let n = list_from([nan]);
1011         let one = list_from([1.0f64]);
1012         assert!(!(n < one));
1013         assert!(!(n > one));
1014         assert!(!(n <= one));
1015         assert!(!(n >= one));
1016
1017         let u = list_from([1.0f64,2.0,nan]);
1018         let v = list_from([1.0f64,2.0,3.0]);
1019         assert!(!(u < v));
1020         assert!(!(u > v));
1021         assert!(!(u <= v));
1022         assert!(!(u >= v));
1023
1024         let s = list_from([1.0f64,2.0,4.0,2.0]);
1025         let t = list_from([1.0f64,2.0,3.0,2.0]);
1026         assert!(!(s < t));
1027         assert!(s > one);
1028         assert!(!(s <= one));
1029         assert!(s >= one);
1030     }
1031
1032     #[test]
1033     fn test_fuzz() {
1034         for _ in range(0u, 25) {
1035             fuzz_test(3);
1036             fuzz_test(16);
1037             fuzz_test(189);
1038         }
1039     }
1040
1041     #[test]
1042     fn test_show() {
1043         let list: DList<int> = range(0i, 10).collect();
1044         assert!(list.to_string().as_slice() == "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]");
1045
1046         let list: DList<&str> = vec!["just", "one", "test", "more"].iter()
1047                                                                    .map(|&s| s)
1048                                                                    .collect();
1049         assert!(list.to_string().as_slice() == "[just, one, test, more]");
1050     }
1051
1052     #[cfg(test)]
1053     fn fuzz_test(sz: int) {
1054         let mut m: DList<int> = DList::new();
1055         let mut v = vec![];
1056         for i in range(0, sz) {
1057             check_links(&m);
1058             let r: u8 = rand::random();
1059             match r % 6 {
1060                 0 => {
1061                     m.pop_back();
1062                     v.pop();
1063                 }
1064                 1 => {
1065                     m.pop_front();
1066                     v.shift();
1067                 }
1068                 2 | 4 =>  {
1069                     m.push_front(-i);
1070                     v.unshift(-i);
1071                 }
1072                 3 | 5 | _ => {
1073                     m.push_back(i);
1074                     v.push(i);
1075                 }
1076             }
1077         }
1078
1079         check_links(&m);
1080
1081         let mut i = 0u;
1082         for (a, &b) in m.move_iter().zip(v.iter()) {
1083             i += 1;
1084             assert_eq!(a, b);
1085         }
1086         assert_eq!(i, v.len());
1087     }
1088
1089     #[bench]
1090     fn bench_collect_into(b: &mut test::Bencher) {
1091         let v = &[0i, ..64];
1092         b.iter(|| {
1093             let _: DList<int> = v.iter().map(|x| *x).collect();
1094         })
1095     }
1096
1097     #[bench]
1098     fn bench_push_front(b: &mut test::Bencher) {
1099         let mut m: DList<int> = DList::new();
1100         b.iter(|| {
1101             m.push_front(0);
1102         })
1103     }
1104
1105     #[bench]
1106     fn bench_push_back(b: &mut test::Bencher) {
1107         let mut m: DList<int> = DList::new();
1108         b.iter(|| {
1109             m.push_back(0);
1110         })
1111     }
1112
1113     #[bench]
1114     fn bench_push_back_pop_back(b: &mut test::Bencher) {
1115         let mut m: DList<int> = DList::new();
1116         b.iter(|| {
1117             m.push_back(0);
1118             m.pop_back();
1119         })
1120     }
1121
1122     #[bench]
1123     fn bench_push_front_pop_front(b: &mut test::Bencher) {
1124         let mut m: DList<int> = DList::new();
1125         b.iter(|| {
1126             m.push_front(0);
1127             m.pop_front();
1128         })
1129     }
1130
1131     #[bench]
1132     fn bench_rotate_forward(b: &mut test::Bencher) {
1133         let mut m: DList<int> = DList::new();
1134         m.push_front(0i);
1135         m.push_front(1);
1136         b.iter(|| {
1137             m.rotate_forward();
1138         })
1139     }
1140
1141     #[bench]
1142     fn bench_rotate_backward(b: &mut test::Bencher) {
1143         let mut m: DList<int> = DList::new();
1144         m.push_front(0i);
1145         m.push_front(1);
1146         b.iter(|| {
1147             m.rotate_backward();
1148         })
1149     }
1150
1151     #[bench]
1152     fn bench_iter(b: &mut test::Bencher) {
1153         let v = &[0i, ..128];
1154         let m: DList<int> = v.iter().map(|&x|x).collect();
1155         b.iter(|| {
1156             assert!(m.iter().count() == 128);
1157         })
1158     }
1159     #[bench]
1160     fn bench_iter_mut(b: &mut test::Bencher) {
1161         let v = &[0i, ..128];
1162         let mut m: DList<int> = v.iter().map(|&x|x).collect();
1163         b.iter(|| {
1164             assert!(m.mut_iter().count() == 128);
1165         })
1166     }
1167     #[bench]
1168     fn bench_iter_rev(b: &mut test::Bencher) {
1169         let v = &[0i, ..128];
1170         let m: DList<int> = v.iter().map(|&x|x).collect();
1171         b.iter(|| {
1172             assert!(m.iter().rev().count() == 128);
1173         })
1174     }
1175     #[bench]
1176     fn bench_iter_mut_rev(b: &mut test::Bencher) {
1177         let v = &[0i, ..128];
1178         let mut m: DList<int> = v.iter().map(|&x|x).collect();
1179         b.iter(|| {
1180             assert!(m.mut_iter().rev().count() == 128);
1181         })
1182     }
1183 }