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