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