]> git.lizzy.rs Git - rust.git/blob - src/libcollections/dlist.rs
Rollup merge of #21100 - tstorch:small_readability_update, r=alexcrichton
[rust.git] / src / libcollections / dlist.rs
1 // Copyright 2012-2015 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     /// ```
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     ///
308     /// # Examples
309     ///
310     /// ```
311     /// use std::collections::DList;
312     ///
313     /// let mut dl = DList::new();
314     /// assert!(dl.is_empty());
315     ///
316     /// dl.push_front("foo");
317     /// assert!(!dl.is_empty());
318     /// ```
319     #[inline]
320     #[stable]
321     pub fn is_empty(&self) -> bool {
322         self.list_head.is_none()
323     }
324
325     /// Returns the length of the `DList`.
326     ///
327     /// This operation should compute in O(1) time.
328     ///
329     /// # Examples
330     ///
331     /// ```
332     /// use std::collections::DList;
333     ///
334     /// let mut dl = DList::new();
335     ///
336     /// dl.push_front(2is);
337     /// assert_eq!(dl.len(), 1);
338     ///
339     /// dl.push_front(1);
340     /// assert_eq!(dl.len(), 2);
341     ///
342     /// dl.push_back(3);
343     /// assert_eq!(dl.len(), 3);
344     ///
345     /// ```
346     #[inline]
347     #[stable]
348     pub fn len(&self) -> uint {
349         self.length
350     }
351
352     /// Removes all elements from the `DList`.
353     ///
354     /// This operation should compute in O(n) time.
355     ///
356     /// # Examples
357     ///
358     /// ```
359     /// use std::collections::DList;
360     ///
361     /// let mut dl = DList::new();
362     ///
363     /// dl.push_front(2is);
364     /// dl.push_front(1);
365     /// assert_eq!(dl.len(), 2);
366     /// assert_eq!(dl.front(), Some(&1is));
367     ///
368     /// dl.clear();
369     /// assert_eq!(dl.len(), 0);
370     /// assert_eq!(dl.front(), None);
371     ///
372     /// ```
373     #[inline]
374     #[stable]
375     pub fn clear(&mut self) {
376         *self = DList::new()
377     }
378
379     /// Provides a reference to the front element, or `None` if the list is
380     /// empty.
381     ///
382     /// # Examples
383     ///
384     /// ```
385     /// use std::collections::DList;
386     ///
387     /// let mut dl = DList::new();
388     /// assert_eq!(dl.front(), None);
389     ///
390     /// dl.push_front(1);
391     /// assert_eq!(dl.front(), Some(&1is));
392     ///
393     /// ```
394     #[inline]
395     #[stable]
396     pub fn front(&self) -> Option<&T> {
397         self.list_head.as_ref().map(|head| &head.value)
398     }
399
400     /// Provides a mutable reference to the front element, or `None` if the list
401     /// is empty.
402     ///
403     /// # Examples
404     ///
405     /// ```
406     /// use std::collections::DList;
407     ///
408     /// let mut dl = DList::new();
409     /// assert_eq!(dl.front(), None);
410     ///
411     /// dl.push_front(1);
412     /// assert_eq!(dl.front(), Some(&1is));
413     ///
414     /// match dl.front_mut() {
415     ///     None => {},
416     ///     Some(x) => *x = 5is,
417     /// }
418     /// assert_eq!(dl.front(), Some(&5is));
419     ///
420     /// ```
421     #[inline]
422     #[stable]
423     pub fn front_mut(&mut self) -> Option<&mut T> {
424         self.list_head.as_mut().map(|head| &mut head.value)
425     }
426
427     /// Provides a reference to the back element, or `None` if the list is
428     /// empty.
429     ///
430     /// # Examples
431     ///
432     /// ```
433     /// use std::collections::DList;
434     ///
435     /// let mut dl = DList::new();
436     /// assert_eq!(dl.back(), None);
437     ///
438     /// dl.push_back(1);
439     /// assert_eq!(dl.back(), Some(&1is));
440     ///
441     /// ```
442     #[inline]
443     #[stable]
444     pub fn back(&self) -> Option<&T> {
445         self.list_tail.resolve_immut().as_ref().map(|tail| &tail.value)
446     }
447
448     /// Provides a mutable reference to the back element, or `None` if the list
449     /// is empty.
450     ///
451     /// # Examples
452     ///
453     /// ```
454     /// use std::collections::DList;
455     ///
456     /// let mut dl = DList::new();
457     /// assert_eq!(dl.back(), None);
458     ///
459     /// dl.push_back(1);
460     /// assert_eq!(dl.back(), Some(&1is));
461     ///
462     /// match dl.back_mut() {
463     ///     None => {},
464     ///     Some(x) => *x = 5is,
465     /// }
466     /// assert_eq!(dl.back(), Some(&5is));
467     ///
468     /// ```
469     #[inline]
470     #[stable]
471     pub fn back_mut(&mut self) -> Option<&mut T> {
472         self.list_tail.resolve().map(|tail| &mut tail.value)
473     }
474
475     /// Adds an element first in the list.
476     ///
477     /// This operation should compute in O(1) time.
478     ///
479     /// # Examples
480     ///
481     /// ```
482     /// use std::collections::DList;
483     ///
484     /// let mut dl = DList::new();
485     ///
486     /// dl.push_front(2is);
487     /// assert_eq!(dl.front().unwrap(), &2is);
488     ///
489     /// dl.push_front(1);
490     /// assert_eq!(dl.front().unwrap(), &1);
491     ///
492     /// ```
493     #[stable]
494     pub fn push_front(&mut self, elt: T) {
495         self.push_front_node(box Node::new(elt))
496     }
497
498     /// Removes the first element and returns it, or `None` if the list is
499     /// empty.
500     ///
501     /// This operation should compute in O(1) time.
502     ///
503     /// # Examples
504     ///
505     /// ```
506     /// use std::collections::DList;
507     ///
508     /// let mut d = DList::new();
509     /// assert_eq!(d.pop_front(), None);
510     ///
511     /// d.push_front(1is);
512     /// d.push_front(3);
513     /// assert_eq!(d.pop_front(), Some(3));
514     /// assert_eq!(d.pop_front(), Some(1));
515     /// assert_eq!(d.pop_front(), None);
516     ///
517     /// ```
518     ///
519     #[stable]
520     pub fn pop_front(&mut self) -> Option<T> {
521         self.pop_front_node().map(|box Node{value, ..}| value)
522     }
523
524     /// Appends an element to the back of a list
525     ///
526     /// # Examples
527     ///
528     /// ```
529     /// use std::collections::DList;
530     ///
531     /// let mut d = DList::new();
532     /// d.push_back(1i);
533     /// d.push_back(3);
534     /// assert_eq!(3, *d.back().unwrap());
535     /// ```
536     #[stable]
537     pub fn push_back(&mut self, elt: T) {
538         self.push_back_node(box Node::new(elt))
539     }
540
541     /// Removes the last element from a list and returns it, or `None` if
542     /// it is empty.
543     ///
544     /// # Examples
545     ///
546     /// ```
547     /// use std::collections::DList;
548     ///
549     /// let mut d = DList::new();
550     /// assert_eq!(d.pop_back(), None);
551     /// d.push_back(1i);
552     /// d.push_back(3);
553     /// assert_eq!(d.pop_back(), Some(3));
554     /// ```
555     #[stable]
556     pub fn pop_back(&mut self) -> Option<T> {
557         self.pop_back_node().map(|box Node{value, ..}| value)
558     }
559
560     /// Splits the list into two at the given index. Returns everything after the given index,
561     /// including the index.
562     ///
563     /// This operation should compute in O(n) time.
564     /// # Examples
565     ///
566     /// ```
567     /// use std::collections::DList;
568     ///
569     /// let mut d = DList::new();
570     ///
571     /// d.push_front(1is);
572     /// d.push_front(2);
573     /// d.push_front(3);
574     ///
575     /// let mut splitted = d.split_off(2);
576     ///
577     /// assert_eq!(splitted.pop_front(), Some(1));
578     /// assert_eq!(splitted.pop_front(), None);
579     /// ```
580     #[stable]
581     pub fn split_off(&mut self, at: uint) -> DList<T> {
582         let len = self.len();
583         assert!(at < len, "Cannot split off at a nonexistent index");
584         if at == 0 {
585             return mem::replace(self, DList::new());
586         }
587
588         // Below, we iterate towards the `i-1`th node, either from the start or the end,
589         // depending on which would be faster.
590         let mut split_node = if at - 1 <= len - 1 - (at - 1) {
591             let mut iter = self.iter_mut();
592             // instead of skipping using .skip() (which creates a new struct),
593             // we skip manually so we can access the head field without
594             // depending on implementation details of Skip
595             for _ in range(0, at - 1) {
596                 iter.next();
597             }
598             iter.head
599         }  else {
600             // better off starting from the end
601             let mut iter = self.iter_mut();
602             for _ in range(0, len - 1 - (at - 1)) {
603                 iter.next_back();
604             }
605             iter.tail
606         };
607
608         let mut splitted_list = DList {
609             list_head: None,
610             list_tail: self.list_tail,
611             length: len - at
612         };
613
614         mem::swap(&mut split_node.resolve().unwrap().next, &mut splitted_list.list_head);
615         self.list_tail = split_node;
616         self.length = at;
617
618         splitted_list
619     }
620 }
621
622 #[unsafe_destructor]
623 #[stable]
624 impl<T> Drop for DList<T> {
625     fn drop(&mut self) {
626         // Dissolve the dlist in backwards direction
627         // Just dropping the list_head can lead to stack exhaustion
628         // when length is >> 1_000_000
629         let mut tail = self.list_tail;
630         loop {
631             match tail.resolve() {
632                 None => break,
633                 Some(prev) => {
634                     prev.next.take(); // release Box<Node<T>>
635                     tail = prev.prev;
636                 }
637             }
638         }
639         self.length = 0;
640         self.list_head = None;
641         self.list_tail = Rawlink::none();
642     }
643 }
644
645 #[stable]
646 impl<'a, A> Iterator for Iter<'a, A> {
647     type Item = &'a A;
648
649     #[inline]
650     fn next(&mut self) -> Option<&'a A> {
651         if self.nelem == 0 {
652             return None;
653         }
654         self.head.as_ref().map(|head| {
655             self.nelem -= 1;
656             self.head = &head.next;
657             &head.value
658         })
659     }
660
661     #[inline]
662     fn size_hint(&self) -> (uint, Option<uint>) {
663         (self.nelem, Some(self.nelem))
664     }
665 }
666
667 #[stable]
668 impl<'a, A> DoubleEndedIterator for Iter<'a, A> {
669     #[inline]
670     fn next_back(&mut self) -> Option<&'a A> {
671         if self.nelem == 0 {
672             return None;
673         }
674         self.tail.resolve_immut().as_ref().map(|prev| {
675             self.nelem -= 1;
676             self.tail = prev.prev;
677             &prev.value
678         })
679     }
680 }
681
682 #[stable]
683 impl<'a, A> ExactSizeIterator for Iter<'a, A> {}
684
685 #[stable]
686 impl<'a, A> Iterator for IterMut<'a, A> {
687     type Item = &'a mut A;
688     #[inline]
689     fn next(&mut self) -> Option<&'a mut A> {
690         if self.nelem == 0 {
691             return None;
692         }
693         self.head.resolve().map(|next| {
694             self.nelem -= 1;
695             self.head = match next.next {
696                 Some(ref mut node) => Rawlink::some(&mut **node),
697                 None => Rawlink::none(),
698             };
699             &mut next.value
700         })
701     }
702
703     #[inline]
704     fn size_hint(&self) -> (uint, Option<uint>) {
705         (self.nelem, Some(self.nelem))
706     }
707 }
708
709 #[stable]
710 impl<'a, A> DoubleEndedIterator for IterMut<'a, A> {
711     #[inline]
712     fn next_back(&mut self) -> Option<&'a mut A> {
713         if self.nelem == 0 {
714             return None;
715         }
716         self.tail.resolve().map(|prev| {
717             self.nelem -= 1;
718             self.tail = prev.prev;
719             &mut prev.value
720         })
721     }
722 }
723
724 #[stable]
725 impl<'a, A> ExactSizeIterator for IterMut<'a, A> {}
726
727 // private methods for IterMut
728 impl<'a, A> IterMut<'a, A> {
729     fn insert_next_node(&mut self, mut ins_node: Box<Node<A>>) {
730         // Insert before `self.head` so that it is between the
731         // previously yielded element and self.head.
732         //
733         // The inserted node will not appear in further iteration.
734         match self.head.resolve() {
735             None => { self.list.push_back_node(ins_node); }
736             Some(node) => {
737                 let prev_node = match node.prev.resolve() {
738                     None => return self.list.push_front_node(ins_node),
739                     Some(prev) => prev,
740                 };
741                 let node_own = prev_node.next.take().unwrap();
742                 ins_node.next = link_with_prev(node_own, Rawlink::some(&mut *ins_node));
743                 prev_node.next = link_with_prev(ins_node, Rawlink::some(prev_node));
744                 self.list.length += 1;
745             }
746         }
747     }
748 }
749
750 impl<'a, A> IterMut<'a, A> {
751     /// Inserts `elt` just after the element most recently returned by `.next()`.
752     /// The inserted element does not appear in the iteration.
753     ///
754     /// # Examples
755     ///
756     /// ```
757     /// use std::collections::DList;
758     ///
759     /// let mut list: DList<int> = vec![1, 3, 4].into_iter().collect();
760     ///
761     /// {
762     ///     let mut it = list.iter_mut();
763     ///     assert_eq!(it.next().unwrap(), &1);
764     ///     // insert `2` after `1`
765     ///     it.insert_next(2);
766     /// }
767     /// {
768     ///     let vec: Vec<int> = list.into_iter().collect();
769     ///     assert_eq!(vec, vec![1i, 2, 3, 4]);
770     /// }
771     /// ```
772     #[inline]
773     #[unstable = "this is probably better handled by a cursor type -- we'll see"]
774     pub fn insert_next(&mut self, elt: A) {
775         self.insert_next_node(box Node::new(elt))
776     }
777
778     /// Provides a reference to the next element, without changing the iterator.
779     ///
780     /// # Examples
781     ///
782     /// ```
783     /// use std::collections::DList;
784     ///
785     /// let mut list: DList<int> = vec![1, 2, 3].into_iter().collect();
786     ///
787     /// let mut it = list.iter_mut();
788     /// assert_eq!(it.next().unwrap(), &1);
789     /// assert_eq!(it.peek_next().unwrap(), &2);
790     /// // We just peeked at 2, so it was not consumed from the iterator.
791     /// assert_eq!(it.next().unwrap(), &2);
792     /// ```
793     #[inline]
794     #[unstable = "this is probably better handled by a cursor type -- we'll see"]
795     pub fn peek_next(&mut self) -> Option<&mut A> {
796         if self.nelem == 0 {
797             return None
798         }
799         self.head.resolve().map(|head| &mut head.value)
800     }
801 }
802
803 #[stable]
804 impl<A> Iterator for IntoIter<A> {
805     type Item = A;
806
807     #[inline]
808     fn next(&mut self) -> Option<A> { self.list.pop_front() }
809
810     #[inline]
811     fn size_hint(&self) -> (uint, Option<uint>) {
812         (self.list.length, Some(self.list.length))
813     }
814 }
815
816 #[stable]
817 impl<A> DoubleEndedIterator for IntoIter<A> {
818     #[inline]
819     fn next_back(&mut self) -> Option<A> { self.list.pop_back() }
820 }
821
822 #[stable]
823 impl<A> FromIterator<A> for DList<A> {
824     fn from_iter<T: Iterator<Item=A>>(iterator: T) -> DList<A> {
825         let mut ret = DList::new();
826         ret.extend(iterator);
827         ret
828     }
829 }
830
831 #[stable]
832 impl<A> Extend<A> for DList<A> {
833     fn extend<T: Iterator<Item=A>>(&mut self, mut iterator: T) {
834         for elt in iterator { self.push_back(elt); }
835     }
836 }
837
838 #[stable]
839 impl<A: PartialEq> PartialEq for DList<A> {
840     fn eq(&self, other: &DList<A>) -> bool {
841         self.len() == other.len() &&
842             iter::order::eq(self.iter(), other.iter())
843     }
844
845     fn ne(&self, other: &DList<A>) -> bool {
846         self.len() != other.len() ||
847             iter::order::ne(self.iter(), other.iter())
848     }
849 }
850
851 #[stable]
852 impl<A: Eq> Eq for DList<A> {}
853
854 #[stable]
855 impl<A: PartialOrd> PartialOrd for DList<A> {
856     fn partial_cmp(&self, other: &DList<A>) -> Option<Ordering> {
857         iter::order::partial_cmp(self.iter(), other.iter())
858     }
859 }
860
861 #[stable]
862 impl<A: Ord> Ord for DList<A> {
863     #[inline]
864     fn cmp(&self, other: &DList<A>) -> Ordering {
865         iter::order::cmp(self.iter(), other.iter())
866     }
867 }
868
869 #[stable]
870 impl<A: Clone> Clone for DList<A> {
871     fn clone(&self) -> DList<A> {
872         self.iter().map(|x| x.clone()).collect()
873     }
874 }
875
876 #[stable]
877 impl<A: fmt::Show> fmt::Show for DList<A> {
878     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
879         try!(write!(f, "DList ["));
880
881         for (i, e) in self.iter().enumerate() {
882             if i != 0 { try!(write!(f, ", ")); }
883             try!(write!(f, "{:?}", *e));
884         }
885
886         write!(f, "]")
887     }
888 }
889
890 #[stable]
891 impl<S: Writer + Hasher, A: Hash<S>> Hash<S> for DList<A> {
892     fn hash(&self, state: &mut S) {
893         self.len().hash(state);
894         for elt in self.iter() {
895             elt.hash(state);
896         }
897     }
898 }
899
900 #[cfg(test)]
901 mod tests {
902     use prelude::*;
903     use std::rand;
904     use std::hash::{self, SipHasher};
905     use std::thread::Thread;
906     use test::Bencher;
907     use test;
908
909     use super::{DList, Node};
910
911     pub fn check_links<T>(list: &DList<T>) {
912         let mut len = 0u;
913         let mut last_ptr: Option<&Node<T>> = None;
914         let mut node_ptr: &Node<T>;
915         match list.list_head {
916             None => { assert_eq!(0u, list.length); return }
917             Some(ref node) => node_ptr = &**node,
918         }
919         loop {
920             match (last_ptr, node_ptr.prev.resolve_immut()) {
921                 (None   , None      ) => {}
922                 (None   , _         ) => panic!("prev link for list_head"),
923                 (Some(p), Some(pptr)) => {
924                     assert_eq!(p as *const Node<T>, pptr as *const Node<T>);
925                 }
926                 _ => panic!("prev link is none, not good"),
927             }
928             match node_ptr.next {
929                 Some(ref next) => {
930                     last_ptr = Some(node_ptr);
931                     node_ptr = &**next;
932                     len += 1;
933                 }
934                 None => {
935                     len += 1;
936                     break;
937                 }
938             }
939         }
940         assert_eq!(len, list.length);
941     }
942
943     #[test]
944     fn test_basic() {
945         let mut m: DList<Box<int>> = DList::new();
946         assert_eq!(m.pop_front(), None);
947         assert_eq!(m.pop_back(), None);
948         assert_eq!(m.pop_front(), None);
949         m.push_front(box 1);
950         assert_eq!(m.pop_front(), Some(box 1));
951         m.push_back(box 2);
952         m.push_back(box 3);
953         assert_eq!(m.len(), 2);
954         assert_eq!(m.pop_front(), Some(box 2));
955         assert_eq!(m.pop_front(), Some(box 3));
956         assert_eq!(m.len(), 0);
957         assert_eq!(m.pop_front(), None);
958         m.push_back(box 1);
959         m.push_back(box 3);
960         m.push_back(box 5);
961         m.push_back(box 7);
962         assert_eq!(m.pop_front(), Some(box 1));
963
964         let mut n = DList::new();
965         n.push_front(2i);
966         n.push_front(3);
967         {
968             assert_eq!(n.front().unwrap(), &3);
969             let x = n.front_mut().unwrap();
970             assert_eq!(*x, 3);
971             *x = 0;
972         }
973         {
974             assert_eq!(n.back().unwrap(), &2);
975             let y = n.back_mut().unwrap();
976             assert_eq!(*y, 2);
977             *y = 1;
978         }
979         assert_eq!(n.pop_front(), Some(0));
980         assert_eq!(n.pop_front(), Some(1));
981     }
982
983     #[cfg(test)]
984     fn generate_test() -> DList<int> {
985         list_from(&[0i,1,2,3,4,5,6])
986     }
987
988     #[cfg(test)]
989     fn list_from<T: Clone>(v: &[T]) -> DList<T> {
990         v.iter().map(|x| (*x).clone()).collect()
991     }
992
993     #[test]
994     fn test_append() {
995         // Empty to empty
996         {
997             let mut m: DList<int> = DList::new();
998             let mut n = DList::new();
999             m.append(&mut n);
1000             check_links(&m);
1001             assert_eq!(m.len(), 0);
1002             assert_eq!(n.len(), 0);
1003         }
1004         // Non-empty to empty
1005         {
1006             let mut m = DList::new();
1007             let mut n = DList::new();
1008             n.push_back(2i);
1009             m.append(&mut n);
1010             check_links(&m);
1011             assert_eq!(m.len(), 1);
1012             assert_eq!(m.pop_back(), Some(2));
1013             assert_eq!(n.len(), 0);
1014             check_links(&m);
1015         }
1016         // Empty to non-empty
1017         {
1018             let mut m = DList::new();
1019             let mut n = DList::new();
1020             m.push_back(2i);
1021             m.append(&mut n);
1022             check_links(&m);
1023             assert_eq!(m.len(), 1);
1024             assert_eq!(m.pop_back(), Some(2));
1025             check_links(&m);
1026         }
1027
1028         // Non-empty to non-empty
1029         let v = vec![1i,2,3,4,5];
1030         let u = vec![9i,8,1,2,3,4,5];
1031         let mut m = list_from(v.as_slice());
1032         let mut n = list_from(u.as_slice());
1033         m.append(&mut n);
1034         check_links(&m);
1035         let mut sum = v;
1036         sum.push_all(u.as_slice());
1037         assert_eq!(sum.len(), m.len());
1038         for elt in sum.into_iter() {
1039             assert_eq!(m.pop_front(), Some(elt))
1040         }
1041         assert_eq!(n.len(), 0);
1042         // let's make sure it's working properly, since we
1043         // did some direct changes to private members
1044         n.push_back(3);
1045         assert_eq!(n.len(), 1);
1046         assert_eq!(n.pop_front(), Some(3));
1047         check_links(&n);
1048     }
1049
1050     #[test]
1051     fn test_split_off() {
1052         // singleton
1053         {
1054             let mut m = DList::new();
1055             m.push_back(1i);
1056
1057             let p = m.split_off(0);
1058             assert_eq!(m.len(), 0);
1059             assert_eq!(p.len(), 1);
1060             assert_eq!(p.back(), Some(&1));
1061             assert_eq!(p.front(), Some(&1));
1062         }
1063
1064         // not singleton, forwards
1065         {
1066             let u = vec![1i,2,3,4,5];
1067             let mut m = list_from(u.as_slice());
1068             let mut n = m.split_off(2);
1069             assert_eq!(m.len(), 2);
1070             assert_eq!(n.len(), 3);
1071             for elt in range(1i, 3) {
1072                 assert_eq!(m.pop_front(), Some(elt));
1073             }
1074             for elt in range(3i, 6) {
1075                 assert_eq!(n.pop_front(), Some(elt));
1076             }
1077         }
1078         // not singleton, backwards
1079         {
1080             let u = vec![1i,2,3,4,5];
1081             let mut m = list_from(u.as_slice());
1082             let mut n = m.split_off(4);
1083             assert_eq!(m.len(), 4);
1084             assert_eq!(n.len(), 1);
1085             for elt in range(1i, 5) {
1086                 assert_eq!(m.pop_front(), Some(elt));
1087             }
1088             for elt in range(5i, 6) {
1089                 assert_eq!(n.pop_front(), Some(elt));
1090             }
1091         }
1092
1093     }
1094
1095     #[test]
1096     fn test_iterator() {
1097         let m = generate_test();
1098         for (i, elt) in m.iter().enumerate() {
1099             assert_eq!(i as int, *elt);
1100         }
1101         let mut n = DList::new();
1102         assert_eq!(n.iter().next(), None);
1103         n.push_front(4i);
1104         let mut it = n.iter();
1105         assert_eq!(it.size_hint(), (1, Some(1)));
1106         assert_eq!(it.next().unwrap(), &4);
1107         assert_eq!(it.size_hint(), (0, Some(0)));
1108         assert_eq!(it.next(), None);
1109     }
1110
1111     #[test]
1112     fn test_iterator_clone() {
1113         let mut n = DList::new();
1114         n.push_back(2i);
1115         n.push_back(3);
1116         n.push_back(4);
1117         let mut it = n.iter();
1118         it.next();
1119         let mut jt = it.clone();
1120         assert_eq!(it.next(), jt.next());
1121         assert_eq!(it.next_back(), jt.next_back());
1122         assert_eq!(it.next(), jt.next());
1123     }
1124
1125     #[test]
1126     fn test_iterator_double_end() {
1127         let mut n = DList::new();
1128         assert_eq!(n.iter().next(), None);
1129         n.push_front(4i);
1130         n.push_front(5);
1131         n.push_front(6);
1132         let mut it = n.iter();
1133         assert_eq!(it.size_hint(), (3, Some(3)));
1134         assert_eq!(it.next().unwrap(), &6);
1135         assert_eq!(it.size_hint(), (2, Some(2)));
1136         assert_eq!(it.next_back().unwrap(), &4);
1137         assert_eq!(it.size_hint(), (1, Some(1)));
1138         assert_eq!(it.next_back().unwrap(), &5);
1139         assert_eq!(it.next_back(), None);
1140         assert_eq!(it.next(), None);
1141     }
1142
1143     #[test]
1144     fn test_rev_iter() {
1145         let m = generate_test();
1146         for (i, elt) in m.iter().rev().enumerate() {
1147             assert_eq!((6 - i) as int, *elt);
1148         }
1149         let mut n = DList::new();
1150         assert_eq!(n.iter().rev().next(), None);
1151         n.push_front(4i);
1152         let mut it = n.iter().rev();
1153         assert_eq!(it.size_hint(), (1, Some(1)));
1154         assert_eq!(it.next().unwrap(), &4);
1155         assert_eq!(it.size_hint(), (0, Some(0)));
1156         assert_eq!(it.next(), None);
1157     }
1158
1159     #[test]
1160     fn test_mut_iter() {
1161         let mut m = generate_test();
1162         let mut len = m.len();
1163         for (i, elt) in m.iter_mut().enumerate() {
1164             assert_eq!(i as int, *elt);
1165             len -= 1;
1166         }
1167         assert_eq!(len, 0);
1168         let mut n = DList::new();
1169         assert!(n.iter_mut().next().is_none());
1170         n.push_front(4i);
1171         n.push_back(5);
1172         let mut it = n.iter_mut();
1173         assert_eq!(it.size_hint(), (2, Some(2)));
1174         assert!(it.next().is_some());
1175         assert!(it.next().is_some());
1176         assert_eq!(it.size_hint(), (0, Some(0)));
1177         assert!(it.next().is_none());
1178     }
1179
1180     #[test]
1181     fn test_iterator_mut_double_end() {
1182         let mut n = DList::new();
1183         assert!(n.iter_mut().next_back().is_none());
1184         n.push_front(4i);
1185         n.push_front(5);
1186         n.push_front(6);
1187         let mut it = n.iter_mut();
1188         assert_eq!(it.size_hint(), (3, Some(3)));
1189         assert_eq!(*it.next().unwrap(), 6);
1190         assert_eq!(it.size_hint(), (2, Some(2)));
1191         assert_eq!(*it.next_back().unwrap(), 4);
1192         assert_eq!(it.size_hint(), (1, Some(1)));
1193         assert_eq!(*it.next_back().unwrap(), 5);
1194         assert!(it.next_back().is_none());
1195         assert!(it.next().is_none());
1196     }
1197
1198     #[test]
1199     fn test_insert_prev() {
1200         let mut m = list_from(&[0i,2,4,6,8]);
1201         let len = m.len();
1202         {
1203             let mut it = m.iter_mut();
1204             it.insert_next(-2);
1205             loop {
1206                 match it.next() {
1207                     None => break,
1208                     Some(elt) => {
1209                         it.insert_next(*elt + 1);
1210                         match it.peek_next() {
1211                             Some(x) => assert_eq!(*x, *elt + 2),
1212                             None => assert_eq!(8, *elt),
1213                         }
1214                     }
1215                 }
1216             }
1217             it.insert_next(0);
1218             it.insert_next(1);
1219         }
1220         check_links(&m);
1221         assert_eq!(m.len(), 3 + len * 2);
1222         assert_eq!(m.into_iter().collect::<Vec<int>>(), vec![-2,0,1,2,3,4,5,6,7,8,9,0,1]);
1223     }
1224
1225     #[test]
1226     fn test_mut_rev_iter() {
1227         let mut m = generate_test();
1228         for (i, elt) in m.iter_mut().rev().enumerate() {
1229             assert_eq!((6-i) as int, *elt);
1230         }
1231         let mut n = DList::new();
1232         assert!(n.iter_mut().rev().next().is_none());
1233         n.push_front(4i);
1234         let mut it = n.iter_mut().rev();
1235         assert!(it.next().is_some());
1236         assert!(it.next().is_none());
1237     }
1238
1239     #[test]
1240     fn test_send() {
1241         let n = list_from(&[1i,2,3]);
1242         Thread::scoped(move || {
1243             check_links(&n);
1244             let a: &[_] = &[&1,&2,&3];
1245             assert_eq!(a, n.iter().collect::<Vec<&int>>());
1246         }).join().ok().unwrap();
1247     }
1248
1249     #[test]
1250     fn test_eq() {
1251         let mut n: DList<u8> = list_from(&[]);
1252         let mut m = list_from(&[]);
1253         assert!(n == m);
1254         n.push_front(1);
1255         assert!(n != m);
1256         m.push_back(1);
1257         assert!(n == m);
1258
1259         let n = list_from(&[2i,3,4]);
1260         let m = list_from(&[1i,2,3]);
1261         assert!(n != m);
1262     }
1263
1264     #[test]
1265     fn test_hash() {
1266       let mut x = DList::new();
1267       let mut y = DList::new();
1268
1269       assert!(hash::hash::<_, SipHasher>(&x) == hash::hash::<_, SipHasher>(&y));
1270
1271       x.push_back(1i);
1272       x.push_back(2);
1273       x.push_back(3);
1274
1275       y.push_front(3i);
1276       y.push_front(2);
1277       y.push_front(1);
1278
1279       assert!(hash::hash::<_, SipHasher>(&x) == hash::hash::<_, SipHasher>(&y));
1280     }
1281
1282     #[test]
1283     fn test_ord() {
1284         let n: DList<int> = list_from(&[]);
1285         let m = list_from(&[1i,2,3]);
1286         assert!(n < m);
1287         assert!(m > n);
1288         assert!(n <= n);
1289         assert!(n >= n);
1290     }
1291
1292     #[test]
1293     fn test_ord_nan() {
1294         let nan = 0.0f64/0.0;
1295         let n = list_from(&[nan]);
1296         let m = list_from(&[nan]);
1297         assert!(!(n < m));
1298         assert!(!(n > m));
1299         assert!(!(n <= m));
1300         assert!(!(n >= m));
1301
1302         let n = list_from(&[nan]);
1303         let one = list_from(&[1.0f64]);
1304         assert!(!(n < one));
1305         assert!(!(n > one));
1306         assert!(!(n <= one));
1307         assert!(!(n >= one));
1308
1309         let u = list_from(&[1.0f64,2.0,nan]);
1310         let v = list_from(&[1.0f64,2.0,3.0]);
1311         assert!(!(u < v));
1312         assert!(!(u > v));
1313         assert!(!(u <= v));
1314         assert!(!(u >= v));
1315
1316         let s = list_from(&[1.0f64,2.0,4.0,2.0]);
1317         let t = list_from(&[1.0f64,2.0,3.0,2.0]);
1318         assert!(!(s < t));
1319         assert!(s > one);
1320         assert!(!(s <= one));
1321         assert!(s >= one);
1322     }
1323
1324     #[test]
1325     fn test_fuzz() {
1326         for _ in range(0u, 25) {
1327             fuzz_test(3);
1328             fuzz_test(16);
1329             fuzz_test(189);
1330         }
1331     }
1332
1333     #[test]
1334     fn test_show() {
1335         let list: DList<int> = range(0i, 10).collect();
1336         assert_eq!(format!("{:?}", list), "DList [0i, 1i, 2i, 3i, 4i, 5i, 6i, 7i, 8i, 9i]");
1337
1338         let list: DList<&str> = vec!["just", "one", "test", "more"].iter()
1339                                                                    .map(|&s| s)
1340                                                                    .collect();
1341         assert_eq!(format!("{:?}", list), "DList [\"just\", \"one\", \"test\", \"more\"]");
1342     }
1343
1344     #[cfg(test)]
1345     fn fuzz_test(sz: int) {
1346         let mut m: DList<int> = DList::new();
1347         let mut v = vec![];
1348         for i in range(0, sz) {
1349             check_links(&m);
1350             let r: u8 = rand::random();
1351             match r % 6 {
1352                 0 => {
1353                     m.pop_back();
1354                     v.pop();
1355                 }
1356                 1 => {
1357                     if !v.is_empty() {
1358                         m.pop_front();
1359                         v.remove(0);
1360                     }
1361                 }
1362                 2 | 4 =>  {
1363                     m.push_front(-i);
1364                     v.insert(0, -i);
1365                 }
1366                 3 | 5 | _ => {
1367                     m.push_back(i);
1368                     v.push(i);
1369                 }
1370             }
1371         }
1372
1373         check_links(&m);
1374
1375         let mut i = 0u;
1376         for (a, &b) in m.into_iter().zip(v.iter()) {
1377             i += 1;
1378             assert_eq!(a, b);
1379         }
1380         assert_eq!(i, v.len());
1381     }
1382
1383     #[bench]
1384     fn bench_collect_into(b: &mut test::Bencher) {
1385         let v = &[0i; 64];
1386         b.iter(|| {
1387             let _: DList<int> = v.iter().map(|x| *x).collect();
1388         })
1389     }
1390
1391     #[bench]
1392     fn bench_push_front(b: &mut test::Bencher) {
1393         let mut m: DList<int> = DList::new();
1394         b.iter(|| {
1395             m.push_front(0);
1396         })
1397     }
1398
1399     #[bench]
1400     fn bench_push_back(b: &mut test::Bencher) {
1401         let mut m: DList<int> = DList::new();
1402         b.iter(|| {
1403             m.push_back(0);
1404         })
1405     }
1406
1407     #[bench]
1408     fn bench_push_back_pop_back(b: &mut test::Bencher) {
1409         let mut m: DList<int> = DList::new();
1410         b.iter(|| {
1411             m.push_back(0);
1412             m.pop_back();
1413         })
1414     }
1415
1416     #[bench]
1417     fn bench_push_front_pop_front(b: &mut test::Bencher) {
1418         let mut m: DList<int> = DList::new();
1419         b.iter(|| {
1420             m.push_front(0);
1421             m.pop_front();
1422         })
1423     }
1424
1425     #[bench]
1426     fn bench_iter(b: &mut test::Bencher) {
1427         let v = &[0i; 128];
1428         let m: DList<int> = v.iter().map(|&x|x).collect();
1429         b.iter(|| {
1430             assert!(m.iter().count() == 128);
1431         })
1432     }
1433     #[bench]
1434     fn bench_iter_mut(b: &mut test::Bencher) {
1435         let v = &[0i; 128];
1436         let mut m: DList<int> = v.iter().map(|&x|x).collect();
1437         b.iter(|| {
1438             assert!(m.iter_mut().count() == 128);
1439         })
1440     }
1441     #[bench]
1442     fn bench_iter_rev(b: &mut test::Bencher) {
1443         let v = &[0i; 128];
1444         let m: DList<int> = v.iter().map(|&x|x).collect();
1445         b.iter(|| {
1446             assert!(m.iter().rev().count() == 128);
1447         })
1448     }
1449     #[bench]
1450     fn bench_iter_mut_rev(b: &mut test::Bencher) {
1451         let v = &[0i; 128];
1452         let mut m: DList<int> = v.iter().map(|&x|x).collect();
1453         b.iter(|| {
1454             assert!(m.iter_mut().rev().count() == 128);
1455         })
1456     }
1457 }