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