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