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