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