]> git.lizzy.rs Git - rust.git/blob - src/libcollections/dlist.rs
librustc: Don't try to perform the magical
[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(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(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(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(*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(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 lt(&self, other: &DList<A>) -> bool {
599         iter::order::lt(self.iter(), other.iter())
600     }
601     fn le(&self, other: &DList<A>) -> bool {
602         iter::order::le(self.iter(), other.iter())
603     }
604     fn gt(&self, other: &DList<A>) -> bool {
605         iter::order::gt(self.iter(), other.iter())
606     }
607     fn ge(&self, other: &DList<A>) -> bool {
608         iter::order::ge(self.iter(), other.iter())
609     }
610 }
611
612 impl<A: Clone> Clone for DList<A> {
613     fn clone(&self) -> DList<A> {
614         self.iter().map(|x| x.clone()).collect()
615     }
616 }
617
618 impl<A: fmt::Show> fmt::Show for DList<A> {
619     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
620         try!(write!(f, "["));
621
622         for (i, e) in self.iter().enumerate() {
623             if i != 0 { try!(write!(f, ", ")); }
624             try!(write!(f, "{}", *e));
625         }
626
627         write!(f, "]")
628     }
629 }
630
631 #[cfg(test)]
632 mod tests {
633     use std::prelude::*;
634     use std::rand;
635     use test::Bencher;
636     use test;
637
638     use Deque;
639     use super::{DList, Node, ListInsertion};
640     use vec::Vec;
641
642     pub fn check_links<T>(list: &DList<T>) {
643         let mut len = 0u;
644         let mut last_ptr: Option<&Node<T>> = None;
645         let mut node_ptr: &Node<T>;
646         match list.list_head {
647             None => { assert_eq!(0u, list.length); return }
648             Some(ref node) => node_ptr = &**node,
649         }
650         loop {
651             match (last_ptr, node_ptr.prev.resolve_immut()) {
652                 (None   , None      ) => {}
653                 (None   , _         ) => fail!("prev link for list_head"),
654                 (Some(p), Some(pptr)) => {
655                     assert_eq!(p as *Node<T>, pptr as *Node<T>);
656                 }
657                 _ => fail!("prev link is none, not good"),
658             }
659             match node_ptr.next {
660                 Some(ref next) => {
661                     last_ptr = Some(node_ptr);
662                     node_ptr = &**next;
663                     len += 1;
664                 }
665                 None => {
666                     len += 1;
667                     break;
668                 }
669             }
670         }
671         assert_eq!(len, list.length);
672     }
673
674     #[test]
675     fn test_basic() {
676         let mut m: DList<Box<int>> = DList::new();
677         assert_eq!(m.pop_front(), None);
678         assert_eq!(m.pop_back(), None);
679         assert_eq!(m.pop_front(), None);
680         m.push_front(box 1);
681         assert_eq!(m.pop_front(), Some(box 1));
682         m.push_back(box 2);
683         m.push_back(box 3);
684         assert_eq!(m.len(), 2);
685         assert_eq!(m.pop_front(), Some(box 2));
686         assert_eq!(m.pop_front(), Some(box 3));
687         assert_eq!(m.len(), 0);
688         assert_eq!(m.pop_front(), None);
689         m.push_back(box 1);
690         m.push_back(box 3);
691         m.push_back(box 5);
692         m.push_back(box 7);
693         assert_eq!(m.pop_front(), Some(box 1));
694
695         let mut n = DList::new();
696         n.push_front(2i);
697         n.push_front(3);
698         {
699             assert_eq!(n.front().unwrap(), &3);
700             let x = n.front_mut().unwrap();
701             assert_eq!(*x, 3);
702             *x = 0;
703         }
704         {
705             assert_eq!(n.back().unwrap(), &2);
706             let y = n.back_mut().unwrap();
707             assert_eq!(*y, 2);
708             *y = 1;
709         }
710         assert_eq!(n.pop_front(), Some(0));
711         assert_eq!(n.pop_front(), Some(1));
712     }
713
714     #[cfg(test)]
715     fn generate_test() -> DList<int> {
716         list_from(&[0i,1,2,3,4,5,6])
717     }
718
719     #[cfg(test)]
720     fn list_from<T: Clone>(v: &[T]) -> DList<T> {
721         v.iter().map(|x| (*x).clone()).collect()
722     }
723
724     #[test]
725     fn test_append() {
726         {
727             let mut m = DList::new();
728             let mut n = DList::new();
729             n.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 mut m = DList::new();
737             let n = DList::new();
738             m.push_back(2i);
739             m.append(n);
740             assert_eq!(m.len(), 1);
741             assert_eq!(m.pop_back(), Some(2));
742             check_links(&m);
743         }
744
745         let v = vec![1i,2,3,4,5];
746         let u = vec![9i,8,1,2,3,4,5];
747         let mut m = list_from(v.as_slice());
748         m.append(list_from(u.as_slice()));
749         check_links(&m);
750         let sum = v.append(u.as_slice());
751         assert_eq!(sum.len(), m.len());
752         for elt in sum.move_iter() {
753             assert_eq!(m.pop_front(), Some(elt))
754         }
755     }
756
757     #[test]
758     fn test_prepend() {
759         {
760             let mut m = DList::new();
761             let mut n = DList::new();
762             n.push_back(2i);
763             m.prepend(n);
764             assert_eq!(m.len(), 1);
765             assert_eq!(m.pop_back(), Some(2));
766             check_links(&m);
767         }
768
769         let v = vec![1i,2,3,4,5];
770         let u = vec![9i,8,1,2,3,4,5];
771         let mut m = list_from(v.as_slice());
772         m.prepend(list_from(u.as_slice()));
773         check_links(&m);
774         let sum = u.append(v.as_slice());
775         assert_eq!(sum.len(), m.len());
776         for elt in sum.move_iter() {
777             assert_eq!(m.pop_front(), Some(elt))
778         }
779     }
780
781     #[test]
782     fn test_rotate() {
783         let mut n: DList<int> = DList::new();
784         n.rotate_backward(); check_links(&n);
785         assert_eq!(n.len(), 0);
786         n.rotate_forward(); check_links(&n);
787         assert_eq!(n.len(), 0);
788
789         let v = vec![1i,2,3,4,5];
790         let mut m = list_from(v.as_slice());
791         m.rotate_backward(); check_links(&m);
792         m.rotate_forward(); check_links(&m);
793         assert_eq!(v.iter().collect::<Vec<&int>>(), m.iter().collect());
794         m.rotate_forward(); check_links(&m);
795         m.rotate_forward(); check_links(&m);
796         m.pop_front(); check_links(&m);
797         m.rotate_forward(); check_links(&m);
798         m.rotate_backward(); check_links(&m);
799         m.push_front(9); check_links(&m);
800         m.rotate_forward(); check_links(&m);
801         assert_eq!(vec![3i,9,5,1,2], m.move_iter().collect());
802     }
803
804     #[test]
805     fn test_iterator() {
806         let m = generate_test();
807         for (i, elt) in m.iter().enumerate() {
808             assert_eq!(i as int, *elt);
809         }
810         let mut n = DList::new();
811         assert_eq!(n.iter().next(), None);
812         n.push_front(4i);
813         let mut it = n.iter();
814         assert_eq!(it.size_hint(), (1, Some(1)));
815         assert_eq!(it.next().unwrap(), &4);
816         assert_eq!(it.size_hint(), (0, Some(0)));
817         assert_eq!(it.next(), None);
818     }
819
820     #[test]
821     fn test_iterator_clone() {
822         let mut n = DList::new();
823         n.push_back(2i);
824         n.push_back(3);
825         n.push_back(4);
826         let mut it = n.iter();
827         it.next();
828         let mut jt = it.clone();
829         assert_eq!(it.next(), jt.next());
830         assert_eq!(it.next_back(), jt.next_back());
831         assert_eq!(it.next(), jt.next());
832     }
833
834     #[test]
835     fn test_iterator_double_end() {
836         let mut n = DList::new();
837         assert_eq!(n.iter().next(), None);
838         n.push_front(4i);
839         n.push_front(5);
840         n.push_front(6);
841         let mut it = n.iter();
842         assert_eq!(it.size_hint(), (3, Some(3)));
843         assert_eq!(it.next().unwrap(), &6);
844         assert_eq!(it.size_hint(), (2, Some(2)));
845         assert_eq!(it.next_back().unwrap(), &4);
846         assert_eq!(it.size_hint(), (1, Some(1)));
847         assert_eq!(it.next_back().unwrap(), &5);
848         assert_eq!(it.next_back(), None);
849         assert_eq!(it.next(), None);
850     }
851
852     #[test]
853     fn test_rev_iter() {
854         let m = generate_test();
855         for (i, elt) in m.iter().rev().enumerate() {
856             assert_eq!((6 - i) as int, *elt);
857         }
858         let mut n = DList::new();
859         assert_eq!(n.iter().rev().next(), None);
860         n.push_front(4i);
861         let mut it = n.iter().rev();
862         assert_eq!(it.size_hint(), (1, Some(1)));
863         assert_eq!(it.next().unwrap(), &4);
864         assert_eq!(it.size_hint(), (0, Some(0)));
865         assert_eq!(it.next(), None);
866     }
867
868     #[test]
869     fn test_mut_iter() {
870         let mut m = generate_test();
871         let mut len = m.len();
872         for (i, elt) in m.mut_iter().enumerate() {
873             assert_eq!(i as int, *elt);
874             len -= 1;
875         }
876         assert_eq!(len, 0);
877         let mut n = DList::new();
878         assert!(n.mut_iter().next().is_none());
879         n.push_front(4i);
880         n.push_back(5);
881         let mut it = n.mut_iter();
882         assert_eq!(it.size_hint(), (2, Some(2)));
883         assert!(it.next().is_some());
884         assert!(it.next().is_some());
885         assert_eq!(it.size_hint(), (0, Some(0)));
886         assert!(it.next().is_none());
887     }
888
889     #[test]
890     fn test_iterator_mut_double_end() {
891         let mut n = DList::new();
892         assert!(n.mut_iter().next_back().is_none());
893         n.push_front(4i);
894         n.push_front(5);
895         n.push_front(6);
896         let mut it = n.mut_iter();
897         assert_eq!(it.size_hint(), (3, Some(3)));
898         assert_eq!(*it.next().unwrap(), 6);
899         assert_eq!(it.size_hint(), (2, Some(2)));
900         assert_eq!(*it.next_back().unwrap(), 4);
901         assert_eq!(it.size_hint(), (1, Some(1)));
902         assert_eq!(*it.next_back().unwrap(), 5);
903         assert!(it.next_back().is_none());
904         assert!(it.next().is_none());
905     }
906
907     #[test]
908     fn test_insert_prev() {
909         let mut m = list_from(&[0i,2,4,6,8]);
910         let len = m.len();
911         {
912             let mut it = m.mut_iter();
913             it.insert_next(-2);
914             loop {
915                 match it.next() {
916                     None => break,
917                     Some(elt) => {
918                         it.insert_next(*elt + 1);
919                         match it.peek_next() {
920                             Some(x) => assert_eq!(*x, *elt + 2),
921                             None => assert_eq!(8, *elt),
922                         }
923                     }
924                 }
925             }
926             it.insert_next(0);
927             it.insert_next(1);
928         }
929         check_links(&m);
930         assert_eq!(m.len(), 3 + len * 2);
931         assert_eq!(m.move_iter().collect::<Vec<int>>(), vec![-2,0,1,2,3,4,5,6,7,8,9,0,1]);
932     }
933
934     #[test]
935     fn test_merge() {
936         let mut m = list_from([0i, 1, 3, 5, 6, 7, 2]);
937         let n = list_from([-1i, 0, 0, 7, 7, 9]);
938         let len = m.len() + n.len();
939         m.merge(n, |a, b| a <= b);
940         assert_eq!(m.len(), len);
941         check_links(&m);
942         let res = m.move_iter().collect::<Vec<int>>();
943         assert_eq!(res, vec![-1, 0, 0, 0, 1, 3, 5, 6, 7, 2, 7, 7, 9]);
944     }
945
946     #[test]
947     fn test_insert_ordered() {
948         let mut n = DList::new();
949         n.insert_ordered(1i);
950         assert_eq!(n.len(), 1);
951         assert_eq!(n.pop_front(), Some(1));
952
953         let mut m = DList::new();
954         m.push_back(2i);
955         m.push_back(4);
956         m.insert_ordered(3);
957         check_links(&m);
958         assert_eq!(vec![2,3,4], m.move_iter().collect::<Vec<int>>());
959     }
960
961     #[test]
962     fn test_mut_rev_iter() {
963         let mut m = generate_test();
964         for (i, elt) in m.mut_iter().rev().enumerate() {
965             assert_eq!((6-i) as int, *elt);
966         }
967         let mut n = DList::new();
968         assert!(n.mut_iter().rev().next().is_none());
969         n.push_front(4i);
970         let mut it = n.mut_iter().rev();
971         assert!(it.next().is_some());
972         assert!(it.next().is_none());
973     }
974
975     #[test]
976     fn test_send() {
977         let n = list_from([1i,2,3]);
978         spawn(proc() {
979             check_links(&n);
980             assert_eq!(&[&1,&2,&3], n.iter().collect::<Vec<&int>>().as_slice());
981         });
982     }
983
984     #[test]
985     fn test_eq() {
986         let mut n: DList<u8> = list_from([]);
987         let mut m = list_from([]);
988         assert!(n == m);
989         n.push_front(1);
990         assert!(n != m);
991         m.push_back(1);
992         assert!(n == m);
993
994         let n = list_from([2i,3,4]);
995         let m = list_from([1i,2,3]);
996         assert!(n != m);
997     }
998
999     #[test]
1000     fn test_ord() {
1001         let n: DList<int> = list_from([]);
1002         let m = list_from([1i,2,3]);
1003         assert!(n < m);
1004         assert!(m > n);
1005         assert!(n <= n);
1006         assert!(n >= n);
1007     }
1008
1009     #[test]
1010     fn test_ord_nan() {
1011         let nan = 0.0f64/0.0;
1012         let n = list_from([nan]);
1013         let m = list_from([nan]);
1014         assert!(!(n < m));
1015         assert!(!(n > m));
1016         assert!(!(n <= m));
1017         assert!(!(n >= m));
1018
1019         let n = list_from([nan]);
1020         let one = list_from([1.0f64]);
1021         assert!(!(n < one));
1022         assert!(!(n > one));
1023         assert!(!(n <= one));
1024         assert!(!(n >= one));
1025
1026         let u = list_from([1.0f64,2.0,nan]);
1027         let v = list_from([1.0f64,2.0,3.0]);
1028         assert!(!(u < v));
1029         assert!(!(u > v));
1030         assert!(!(u <= v));
1031         assert!(!(u >= v));
1032
1033         let s = list_from([1.0f64,2.0,4.0,2.0]);
1034         let t = list_from([1.0f64,2.0,3.0,2.0]);
1035         assert!(!(s < t));
1036         assert!(s > one);
1037         assert!(!(s <= one));
1038         assert!(s >= one);
1039     }
1040
1041     #[test]
1042     fn test_fuzz() {
1043         for _ in range(0u, 25) {
1044             fuzz_test(3);
1045             fuzz_test(16);
1046             fuzz_test(189);
1047         }
1048     }
1049
1050     #[test]
1051     fn test_show() {
1052         let list: DList<int> = range(0i, 10).collect();
1053         assert!(list.to_str().as_slice() == "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]");
1054
1055         let list: DList<&str> = vec!["just", "one", "test", "more"].iter()
1056                                                                    .map(|&s| s)
1057                                                                    .collect();
1058         assert!(list.to_str().as_slice() == "[just, one, test, more]");
1059     }
1060
1061     #[cfg(test)]
1062     fn fuzz_test(sz: int) {
1063         let mut m: DList<int> = DList::new();
1064         let mut v = vec![];
1065         for i in range(0, sz) {
1066             check_links(&m);
1067             let r: u8 = rand::random();
1068             match r % 6 {
1069                 0 => {
1070                     m.pop_back();
1071                     v.pop();
1072                 }
1073                 1 => {
1074                     m.pop_front();
1075                     v.shift();
1076                 }
1077                 2 | 4 =>  {
1078                     m.push_front(-i);
1079                     v.unshift(-i);
1080                 }
1081                 3 | 5 | _ => {
1082                     m.push_back(i);
1083                     v.push(i);
1084                 }
1085             }
1086         }
1087
1088         check_links(&m);
1089
1090         let mut i = 0u;
1091         for (a, &b) in m.move_iter().zip(v.iter()) {
1092             i += 1;
1093             assert_eq!(a, b);
1094         }
1095         assert_eq!(i, v.len());
1096     }
1097
1098     #[bench]
1099     fn bench_collect_into(b: &mut test::Bencher) {
1100         let v = &[0i, ..64];
1101         b.iter(|| {
1102             let _: DList<int> = v.iter().map(|x| *x).collect();
1103         })
1104     }
1105
1106     #[bench]
1107     fn bench_push_front(b: &mut test::Bencher) {
1108         let mut m: DList<int> = DList::new();
1109         b.iter(|| {
1110             m.push_front(0);
1111         })
1112     }
1113
1114     #[bench]
1115     fn bench_push_back(b: &mut test::Bencher) {
1116         let mut m: DList<int> = DList::new();
1117         b.iter(|| {
1118             m.push_back(0);
1119         })
1120     }
1121
1122     #[bench]
1123     fn bench_push_back_pop_back(b: &mut test::Bencher) {
1124         let mut m: DList<int> = DList::new();
1125         b.iter(|| {
1126             m.push_back(0);
1127             m.pop_back();
1128         })
1129     }
1130
1131     #[bench]
1132     fn bench_push_front_pop_front(b: &mut test::Bencher) {
1133         let mut m: DList<int> = DList::new();
1134         b.iter(|| {
1135             m.push_front(0);
1136             m.pop_front();
1137         })
1138     }
1139
1140     #[bench]
1141     fn bench_rotate_forward(b: &mut test::Bencher) {
1142         let mut m: DList<int> = DList::new();
1143         m.push_front(0i);
1144         m.push_front(1);
1145         b.iter(|| {
1146             m.rotate_forward();
1147         })
1148     }
1149
1150     #[bench]
1151     fn bench_rotate_backward(b: &mut test::Bencher) {
1152         let mut m: DList<int> = DList::new();
1153         m.push_front(0i);
1154         m.push_front(1);
1155         b.iter(|| {
1156             m.rotate_backward();
1157         })
1158     }
1159
1160     #[bench]
1161     fn bench_iter(b: &mut test::Bencher) {
1162         let v = &[0i, ..128];
1163         let m: DList<int> = v.iter().map(|&x|x).collect();
1164         b.iter(|| {
1165             assert!(m.iter().count() == 128);
1166         })
1167     }
1168     #[bench]
1169     fn bench_iter_mut(b: &mut test::Bencher) {
1170         let v = &[0i, ..128];
1171         let mut m: DList<int> = v.iter().map(|&x|x).collect();
1172         b.iter(|| {
1173             assert!(m.mut_iter().count() == 128);
1174         })
1175     }
1176     #[bench]
1177     fn bench_iter_rev(b: &mut test::Bencher) {
1178         let v = &[0i, ..128];
1179         let m: DList<int> = v.iter().map(|&x|x).collect();
1180         b.iter(|| {
1181             assert!(m.iter().rev().count() == 128);
1182         })
1183     }
1184     #[bench]
1185     fn bench_iter_mut_rev(b: &mut test::Bencher) {
1186         let v = &[0i, ..128];
1187         let mut m: DList<int> = v.iter().map(|&x|x).collect();
1188         b.iter(|| {
1189             assert!(m.mut_iter().rev().count() == 128);
1190         })
1191     }
1192 }