]> git.lizzy.rs Git - rust.git/blob - src/libcollections/dlist.rs
Auto merge of #22517 - brson:relnotes, r=Gankro
[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(feature = "rust1", since = "1.0.0")]
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, IntoIterator};
32 use core::mem;
33 use core::ptr;
34
35 /// A doubly-linked list.
36 #[stable(feature = "rust1", since = "1.0.0")]
37 pub struct DList<T> {
38     length: usize,
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(feature = "rust1", since = "1.0.0")]
61 pub struct Iter<'a, T:'a> {
62     head: &'a Link<T>,
63     tail: Rawlink<Node<T>>,
64     nelem: usize,
65 }
66
67 // FIXME #19839: deriving is too aggressive on the bounds (T doesn't need to be Clone).
68 #[stable(feature = "rust1", since = "1.0.0")]
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(feature = "rust1", since = "1.0.0")]
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: usize,
86 }
87
88 /// An iterator over mutable references to the items of a `DList`.
89 #[derive(Clone)]
90 #[stable(feature = "rust1", since = "1.0.0")]
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(feature = "rust1", since = "1.0.0")]
210 impl<T> Default for DList<T> {
211     #[inline]
212     #[stable(feature = "rust1", since = "1.0.0")]
213     fn default() -> DList<T> { DList::new() }
214 }
215
216 impl<T> DList<T> {
217     /// Creates an empty `DList`.
218     #[inline]
219     #[stable(feature = "rust1", since = "1.0.0")]
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(1);
239     /// a.push_back(2);
240     /// b.push_back(3);
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(feature = "rust1", since = "1.0.0")]
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(feature = "rust1", since = "1.0.0")]
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(feature = "rust1", since = "1.0.0")]
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(feature = "rust1", since = "1.0.0")]
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(2);
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(feature = "rust1", since = "1.0.0")]
348     pub fn len(&self) -> usize {
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(2);
364     /// dl.push_front(1);
365     /// assert_eq!(dl.len(), 2);
366     /// assert_eq!(dl.front(), Some(&1));
367     ///
368     /// dl.clear();
369     /// assert_eq!(dl.len(), 0);
370     /// assert_eq!(dl.front(), None);
371     ///
372     /// ```
373     #[inline]
374     #[stable(feature = "rust1", since = "1.0.0")]
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(&1));
392     ///
393     /// ```
394     #[inline]
395     #[stable(feature = "rust1", since = "1.0.0")]
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(&1));
413     ///
414     /// match dl.front_mut() {
415     ///     None => {},
416     ///     Some(x) => *x = 5,
417     /// }
418     /// assert_eq!(dl.front(), Some(&5));
419     ///
420     /// ```
421     #[inline]
422     #[stable(feature = "rust1", since = "1.0.0")]
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(&1));
440     ///
441     /// ```
442     #[inline]
443     #[stable(feature = "rust1", since = "1.0.0")]
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(&1));
461     ///
462     /// match dl.back_mut() {
463     ///     None => {},
464     ///     Some(x) => *x = 5,
465     /// }
466     /// assert_eq!(dl.back(), Some(&5));
467     ///
468     /// ```
469     #[inline]
470     #[stable(feature = "rust1", since = "1.0.0")]
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(2);
487     /// assert_eq!(dl.front().unwrap(), &2);
488     ///
489     /// dl.push_front(1);
490     /// assert_eq!(dl.front().unwrap(), &1);
491     ///
492     /// ```
493     #[stable(feature = "rust1", since = "1.0.0")]
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(1);
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(feature = "rust1", since = "1.0.0")]
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(1);
533     /// d.push_back(3);
534     /// assert_eq!(3, *d.back().unwrap());
535     /// ```
536     #[stable(feature = "rust1", since = "1.0.0")]
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(1);
552     /// d.push_back(3);
553     /// assert_eq!(d.pop_back(), Some(3));
554     /// ```
555     #[stable(feature = "rust1", since = "1.0.0")]
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     /// # Panics
564     ///
565     /// Panics if `at > len`.
566     ///
567     /// This operation should compute in O(n) time.
568     ///
569     /// # Examples
570     ///
571     /// ```
572     /// use std::collections::DList;
573     ///
574     /// let mut d = DList::new();
575     ///
576     /// d.push_front(1);
577     /// d.push_front(2);
578     /// d.push_front(3);
579     ///
580     /// let mut splitted = d.split_off(2);
581     ///
582     /// assert_eq!(splitted.pop_front(), Some(1));
583     /// assert_eq!(splitted.pop_front(), None);
584     /// ```
585     #[stable(feature = "rust1", since = "1.0.0")]
586     pub fn split_off(&mut self, at: usize) -> DList<T> {
587         let len = self.len();
588         assert!(at <= len, "Cannot split off at a nonexistent index");
589         if at == 0 {
590             return mem::replace(self, DList::new());
591         } else if at == len {
592             return DList::new();
593         }
594
595         // Below, we iterate towards the `i-1`th node, either from the start or the end,
596         // depending on which would be faster.
597         let mut split_node = if at - 1 <= len - 1 - (at - 1) {
598             let mut iter = self.iter_mut();
599             // instead of skipping using .skip() (which creates a new struct),
600             // we skip manually so we can access the head field without
601             // depending on implementation details of Skip
602             for _ in 0..at - 1 {
603                 iter.next();
604             }
605             iter.head
606         }  else {
607             // better off starting from the end
608             let mut iter = self.iter_mut();
609             for _ in 0..len - 1 - (at - 1) {
610                 iter.next_back();
611             }
612             iter.tail
613         };
614
615         let mut splitted_list = DList {
616             list_head: None,
617             list_tail: self.list_tail,
618             length: len - at
619         };
620
621         mem::swap(&mut split_node.resolve().unwrap().next, &mut splitted_list.list_head);
622         self.list_tail = split_node;
623         self.length = at;
624
625         splitted_list
626     }
627 }
628
629 #[unsafe_destructor]
630 #[stable(feature = "rust1", since = "1.0.0")]
631 impl<T> Drop for DList<T> {
632     fn drop(&mut self) {
633         // Dissolve the dlist in backwards direction
634         // Just dropping the list_head can lead to stack exhaustion
635         // when length is >> 1_000_000
636         let mut tail = self.list_tail;
637         loop {
638             match tail.resolve() {
639                 None => break,
640                 Some(prev) => {
641                     prev.next.take(); // release Box<Node<T>>
642                     tail = prev.prev;
643                 }
644             }
645         }
646         self.length = 0;
647         self.list_head = None;
648         self.list_tail = Rawlink::none();
649     }
650 }
651
652 #[stable(feature = "rust1", since = "1.0.0")]
653 impl<'a, A> Iterator for Iter<'a, A> {
654     type Item = &'a A;
655
656     #[inline]
657     fn next(&mut self) -> Option<&'a A> {
658         if self.nelem == 0 {
659             return None;
660         }
661         self.head.as_ref().map(|head| {
662             self.nelem -= 1;
663             self.head = &head.next;
664             &head.value
665         })
666     }
667
668     #[inline]
669     fn size_hint(&self) -> (usize, Option<usize>) {
670         (self.nelem, Some(self.nelem))
671     }
672 }
673
674 #[stable(feature = "rust1", since = "1.0.0")]
675 impl<'a, A> DoubleEndedIterator for Iter<'a, A> {
676     #[inline]
677     fn next_back(&mut self) -> Option<&'a A> {
678         if self.nelem == 0 {
679             return None;
680         }
681         self.tail.resolve_immut().as_ref().map(|prev| {
682             self.nelem -= 1;
683             self.tail = prev.prev;
684             &prev.value
685         })
686     }
687 }
688
689 #[stable(feature = "rust1", since = "1.0.0")]
690 impl<'a, A> ExactSizeIterator for Iter<'a, A> {}
691
692 #[stable(feature = "rust1", since = "1.0.0")]
693 impl<'a, A> Iterator for IterMut<'a, A> {
694     type Item = &'a mut A;
695     #[inline]
696     fn next(&mut self) -> Option<&'a mut A> {
697         if self.nelem == 0 {
698             return None;
699         }
700         self.head.resolve().map(|next| {
701             self.nelem -= 1;
702             self.head = match next.next {
703                 Some(ref mut node) => Rawlink::some(&mut **node),
704                 None => Rawlink::none(),
705             };
706             &mut next.value
707         })
708     }
709
710     #[inline]
711     fn size_hint(&self) -> (usize, Option<usize>) {
712         (self.nelem, Some(self.nelem))
713     }
714 }
715
716 #[stable(feature = "rust1", since = "1.0.0")]
717 impl<'a, A> DoubleEndedIterator for IterMut<'a, A> {
718     #[inline]
719     fn next_back(&mut self) -> Option<&'a mut A> {
720         if self.nelem == 0 {
721             return None;
722         }
723         self.tail.resolve().map(|prev| {
724             self.nelem -= 1;
725             self.tail = prev.prev;
726             &mut prev.value
727         })
728     }
729 }
730
731 #[stable(feature = "rust1", since = "1.0.0")]
732 impl<'a, A> ExactSizeIterator for IterMut<'a, A> {}
733
734 // private methods for IterMut
735 impl<'a, A> IterMut<'a, A> {
736     fn insert_next_node(&mut self, mut ins_node: Box<Node<A>>) {
737         // Insert before `self.head` so that it is between the
738         // previously yielded element and self.head.
739         //
740         // The inserted node will not appear in further iteration.
741         match self.head.resolve() {
742             None => { self.list.push_back_node(ins_node); }
743             Some(node) => {
744                 let prev_node = match node.prev.resolve() {
745                     None => return self.list.push_front_node(ins_node),
746                     Some(prev) => prev,
747                 };
748                 let node_own = prev_node.next.take().unwrap();
749                 ins_node.next = link_with_prev(node_own, Rawlink::some(&mut *ins_node));
750                 prev_node.next = link_with_prev(ins_node, Rawlink::some(prev_node));
751                 self.list.length += 1;
752             }
753         }
754     }
755 }
756
757 impl<'a, A> IterMut<'a, A> {
758     /// Inserts `elt` just after the element most recently returned by `.next()`.
759     /// The inserted element does not appear in the iteration.
760     ///
761     /// # Examples
762     ///
763     /// ```
764     /// use std::collections::DList;
765     ///
766     /// let mut list: DList<_> = vec![1, 3, 4].into_iter().collect();
767     ///
768     /// {
769     ///     let mut it = list.iter_mut();
770     ///     assert_eq!(it.next().unwrap(), &1);
771     ///     // insert `2` after `1`
772     ///     it.insert_next(2);
773     /// }
774     /// {
775     ///     let vec: Vec<_> = list.into_iter().collect();
776     ///     assert_eq!(vec, vec![1, 2, 3, 4]);
777     /// }
778     /// ```
779     #[inline]
780     #[unstable(feature = "collections",
781                reason = "this is probably better handled by a cursor type -- we'll see")]
782     pub fn insert_next(&mut self, elt: A) {
783         self.insert_next_node(box Node::new(elt))
784     }
785
786     /// Provides a reference to the next element, without changing the iterator.
787     ///
788     /// # Examples
789     ///
790     /// ```
791     /// use std::collections::DList;
792     ///
793     /// let mut list: DList<_> = vec![1, 2, 3].into_iter().collect();
794     ///
795     /// let mut it = list.iter_mut();
796     /// assert_eq!(it.next().unwrap(), &1);
797     /// assert_eq!(it.peek_next().unwrap(), &2);
798     /// // We just peeked at 2, so it was not consumed from the iterator.
799     /// assert_eq!(it.next().unwrap(), &2);
800     /// ```
801     #[inline]
802     #[unstable(feature = "collections",
803                reason = "this is probably better handled by a cursor type -- we'll see")]
804     pub fn peek_next(&mut self) -> Option<&mut A> {
805         if self.nelem == 0 {
806             return None
807         }
808         self.head.resolve().map(|head| &mut head.value)
809     }
810 }
811
812 #[stable(feature = "rust1", since = "1.0.0")]
813 impl<A> Iterator for IntoIter<A> {
814     type Item = A;
815
816     #[inline]
817     fn next(&mut self) -> Option<A> { self.list.pop_front() }
818
819     #[inline]
820     fn size_hint(&self) -> (usize, Option<usize>) {
821         (self.list.length, Some(self.list.length))
822     }
823 }
824
825 #[stable(feature = "rust1", since = "1.0.0")]
826 impl<A> DoubleEndedIterator for IntoIter<A> {
827     #[inline]
828     fn next_back(&mut self) -> Option<A> { self.list.pop_back() }
829 }
830
831 #[stable(feature = "rust1", since = "1.0.0")]
832 impl<A> FromIterator<A> for DList<A> {
833     fn from_iter<T: Iterator<Item=A>>(iterator: T) -> DList<A> {
834         let mut ret = DList::new();
835         ret.extend(iterator);
836         ret
837     }
838 }
839
840 #[stable(feature = "rust1", since = "1.0.0")]
841 impl<T> IntoIterator for DList<T> {
842     type Item = T;
843     type IntoIter = IntoIter<T>;
844
845     fn into_iter(self) -> IntoIter<T> {
846         self.into_iter()
847     }
848 }
849
850 #[stable(feature = "rust1", since = "1.0.0")]
851 impl<'a, T> IntoIterator for &'a DList<T> {
852     type Item = &'a T;
853     type IntoIter = Iter<'a, T>;
854
855     fn into_iter(self) -> Iter<'a, T> {
856         self.iter()
857     }
858 }
859
860 impl<'a, T> IntoIterator for &'a mut DList<T> {
861     type Item = &'a mut T;
862     type IntoIter = IterMut<'a, T>;
863
864     fn into_iter(mut self) -> IterMut<'a, T> {
865         self.iter_mut()
866     }
867 }
868
869 #[stable(feature = "rust1", since = "1.0.0")]
870 impl<A> Extend<A> for DList<A> {
871     fn extend<T: Iterator<Item=A>>(&mut self, iterator: T) {
872         for elt in iterator { self.push_back(elt); }
873     }
874 }
875
876 #[stable(feature = "rust1", since = "1.0.0")]
877 impl<A: PartialEq> PartialEq for DList<A> {
878     fn eq(&self, other: &DList<A>) -> bool {
879         self.len() == other.len() &&
880             iter::order::eq(self.iter(), other.iter())
881     }
882
883     fn ne(&self, other: &DList<A>) -> bool {
884         self.len() != other.len() ||
885             iter::order::ne(self.iter(), other.iter())
886     }
887 }
888
889 #[stable(feature = "rust1", since = "1.0.0")]
890 impl<A: Eq> Eq for DList<A> {}
891
892 #[stable(feature = "rust1", since = "1.0.0")]
893 impl<A: PartialOrd> PartialOrd for DList<A> {
894     fn partial_cmp(&self, other: &DList<A>) -> Option<Ordering> {
895         iter::order::partial_cmp(self.iter(), other.iter())
896     }
897 }
898
899 #[stable(feature = "rust1", since = "1.0.0")]
900 impl<A: Ord> Ord for DList<A> {
901     #[inline]
902     fn cmp(&self, other: &DList<A>) -> Ordering {
903         iter::order::cmp(self.iter(), other.iter())
904     }
905 }
906
907 #[stable(feature = "rust1", since = "1.0.0")]
908 impl<A: Clone> Clone for DList<A> {
909     fn clone(&self) -> DList<A> {
910         self.iter().map(|x| x.clone()).collect()
911     }
912 }
913
914 #[stable(feature = "rust1", since = "1.0.0")]
915 impl<A: fmt::Debug> fmt::Debug for DList<A> {
916     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
917         try!(write!(f, "DList ["));
918
919         for (i, e) in self.iter().enumerate() {
920             if i != 0 { try!(write!(f, ", ")); }
921             try!(write!(f, "{:?}", *e));
922         }
923
924         write!(f, "]")
925     }
926 }
927
928 #[stable(feature = "rust1", since = "1.0.0")]
929 impl<S: Writer + Hasher, A: Hash<S>> Hash<S> for DList<A> {
930     fn hash(&self, state: &mut S) {
931         self.len().hash(state);
932         for elt in self {
933             elt.hash(state);
934         }
935     }
936 }
937
938 #[cfg(test)]
939 mod tests {
940     use prelude::*;
941     use std::rand;
942     use std::hash::{self, SipHasher};
943     use std::thread;
944     use test::Bencher;
945     use test;
946
947     use super::{DList, Node};
948
949     pub fn check_links<T>(list: &DList<T>) {
950         let mut len = 0;
951         let mut last_ptr: Option<&Node<T>> = None;
952         let mut node_ptr: &Node<T>;
953         match list.list_head {
954             None => { assert_eq!(0, list.length); return }
955             Some(ref node) => node_ptr = &**node,
956         }
957         loop {
958             match (last_ptr, node_ptr.prev.resolve_immut()) {
959                 (None   , None      ) => {}
960                 (None   , _         ) => panic!("prev link for list_head"),
961                 (Some(p), Some(pptr)) => {
962                     assert_eq!(p as *const Node<T>, pptr as *const Node<T>);
963                 }
964                 _ => panic!("prev link is none, not good"),
965             }
966             match node_ptr.next {
967                 Some(ref next) => {
968                     last_ptr = Some(node_ptr);
969                     node_ptr = &**next;
970                     len += 1;
971                 }
972                 None => {
973                     len += 1;
974                     break;
975                 }
976             }
977         }
978         assert_eq!(len, list.length);
979     }
980
981     #[test]
982     fn test_basic() {
983         let mut m = DList::new();
984         assert_eq!(m.pop_front(), None);
985         assert_eq!(m.pop_back(), None);
986         assert_eq!(m.pop_front(), None);
987         m.push_front(box 1);
988         assert_eq!(m.pop_front(), Some(box 1));
989         m.push_back(box 2);
990         m.push_back(box 3);
991         assert_eq!(m.len(), 2);
992         assert_eq!(m.pop_front(), Some(box 2));
993         assert_eq!(m.pop_front(), Some(box 3));
994         assert_eq!(m.len(), 0);
995         assert_eq!(m.pop_front(), None);
996         m.push_back(box 1);
997         m.push_back(box 3);
998         m.push_back(box 5);
999         m.push_back(box 7);
1000         assert_eq!(m.pop_front(), Some(box 1));
1001
1002         let mut n = DList::new();
1003         n.push_front(2);
1004         n.push_front(3);
1005         {
1006             assert_eq!(n.front().unwrap(), &3);
1007             let x = n.front_mut().unwrap();
1008             assert_eq!(*x, 3);
1009             *x = 0;
1010         }
1011         {
1012             assert_eq!(n.back().unwrap(), &2);
1013             let y = n.back_mut().unwrap();
1014             assert_eq!(*y, 2);
1015             *y = 1;
1016         }
1017         assert_eq!(n.pop_front(), Some(0));
1018         assert_eq!(n.pop_front(), Some(1));
1019     }
1020
1021     #[cfg(test)]
1022     fn generate_test() -> DList<i32> {
1023         list_from(&[0,1,2,3,4,5,6])
1024     }
1025
1026     #[cfg(test)]
1027     fn list_from<T: Clone>(v: &[T]) -> DList<T> {
1028         v.iter().map(|x| (*x).clone()).collect()
1029     }
1030
1031     #[test]
1032     fn test_append() {
1033         // Empty to empty
1034         {
1035             let mut m = DList::<i32>::new();
1036             let mut n = DList::new();
1037             m.append(&mut n);
1038             check_links(&m);
1039             assert_eq!(m.len(), 0);
1040             assert_eq!(n.len(), 0);
1041         }
1042         // Non-empty to empty
1043         {
1044             let mut m = DList::new();
1045             let mut n = DList::new();
1046             n.push_back(2);
1047             m.append(&mut n);
1048             check_links(&m);
1049             assert_eq!(m.len(), 1);
1050             assert_eq!(m.pop_back(), Some(2));
1051             assert_eq!(n.len(), 0);
1052             check_links(&m);
1053         }
1054         // Empty to non-empty
1055         {
1056             let mut m = DList::new();
1057             let mut n = DList::new();
1058             m.push_back(2);
1059             m.append(&mut n);
1060             check_links(&m);
1061             assert_eq!(m.len(), 1);
1062             assert_eq!(m.pop_back(), Some(2));
1063             check_links(&m);
1064         }
1065
1066         // Non-empty to non-empty
1067         let v = vec![1,2,3,4,5];
1068         let u = vec![9,8,1,2,3,4,5];
1069         let mut m = list_from(&v);
1070         let mut n = list_from(&u);
1071         m.append(&mut n);
1072         check_links(&m);
1073         let mut sum = v;
1074         sum.push_all(&u);
1075         assert_eq!(sum.len(), m.len());
1076         for elt in sum {
1077             assert_eq!(m.pop_front(), Some(elt))
1078         }
1079         assert_eq!(n.len(), 0);
1080         // let's make sure it's working properly, since we
1081         // did some direct changes to private members
1082         n.push_back(3);
1083         assert_eq!(n.len(), 1);
1084         assert_eq!(n.pop_front(), Some(3));
1085         check_links(&n);
1086     }
1087
1088     #[test]
1089     fn test_split_off() {
1090         // singleton
1091         {
1092             let mut m = DList::new();
1093             m.push_back(1);
1094
1095             let p = m.split_off(0);
1096             assert_eq!(m.len(), 0);
1097             assert_eq!(p.len(), 1);
1098             assert_eq!(p.back(), Some(&1));
1099             assert_eq!(p.front(), Some(&1));
1100         }
1101
1102         // not singleton, forwards
1103         {
1104             let u = vec![1,2,3,4,5];
1105             let mut m = list_from(&u);
1106             let mut n = m.split_off(2);
1107             assert_eq!(m.len(), 2);
1108             assert_eq!(n.len(), 3);
1109             for elt in 1..3 {
1110                 assert_eq!(m.pop_front(), Some(elt));
1111             }
1112             for elt in 3..6 {
1113                 assert_eq!(n.pop_front(), Some(elt));
1114             }
1115         }
1116         // not singleton, backwards
1117         {
1118             let u = vec![1,2,3,4,5];
1119             let mut m = list_from(&u);
1120             let mut n = m.split_off(4);
1121             assert_eq!(m.len(), 4);
1122             assert_eq!(n.len(), 1);
1123             for elt in 1..5 {
1124                 assert_eq!(m.pop_front(), Some(elt));
1125             }
1126             for elt in 5..6 {
1127                 assert_eq!(n.pop_front(), Some(elt));
1128             }
1129         }
1130
1131         // no-op on the last index
1132         {
1133             let mut m = DList::new();
1134             m.push_back(1);
1135
1136             let p = m.split_off(1);
1137             assert_eq!(m.len(), 1);
1138             assert_eq!(p.len(), 0);
1139             assert_eq!(m.back(), Some(&1));
1140             assert_eq!(m.front(), Some(&1));
1141         }
1142
1143     }
1144
1145     #[test]
1146     fn test_iterator() {
1147         let m = generate_test();
1148         for (i, elt) in m.iter().enumerate() {
1149             assert_eq!(i as i32, *elt);
1150         }
1151         let mut n = DList::new();
1152         assert_eq!(n.iter().next(), None);
1153         n.push_front(4);
1154         let mut it = n.iter();
1155         assert_eq!(it.size_hint(), (1, Some(1)));
1156         assert_eq!(it.next().unwrap(), &4);
1157         assert_eq!(it.size_hint(), (0, Some(0)));
1158         assert_eq!(it.next(), None);
1159     }
1160
1161     #[test]
1162     fn test_iterator_clone() {
1163         let mut n = DList::new();
1164         n.push_back(2);
1165         n.push_back(3);
1166         n.push_back(4);
1167         let mut it = n.iter();
1168         it.next();
1169         let mut jt = it.clone();
1170         assert_eq!(it.next(), jt.next());
1171         assert_eq!(it.next_back(), jt.next_back());
1172         assert_eq!(it.next(), jt.next());
1173     }
1174
1175     #[test]
1176     fn test_iterator_double_end() {
1177         let mut n = DList::new();
1178         assert_eq!(n.iter().next(), None);
1179         n.push_front(4);
1180         n.push_front(5);
1181         n.push_front(6);
1182         let mut it = n.iter();
1183         assert_eq!(it.size_hint(), (3, Some(3)));
1184         assert_eq!(it.next().unwrap(), &6);
1185         assert_eq!(it.size_hint(), (2, Some(2)));
1186         assert_eq!(it.next_back().unwrap(), &4);
1187         assert_eq!(it.size_hint(), (1, Some(1)));
1188         assert_eq!(it.next_back().unwrap(), &5);
1189         assert_eq!(it.next_back(), None);
1190         assert_eq!(it.next(), None);
1191     }
1192
1193     #[test]
1194     fn test_rev_iter() {
1195         let m = generate_test();
1196         for (i, elt) in m.iter().rev().enumerate() {
1197             assert_eq!((6 - i) as i32, *elt);
1198         }
1199         let mut n = DList::new();
1200         assert_eq!(n.iter().rev().next(), None);
1201         n.push_front(4);
1202         let mut it = n.iter().rev();
1203         assert_eq!(it.size_hint(), (1, Some(1)));
1204         assert_eq!(it.next().unwrap(), &4);
1205         assert_eq!(it.size_hint(), (0, Some(0)));
1206         assert_eq!(it.next(), None);
1207     }
1208
1209     #[test]
1210     fn test_mut_iter() {
1211         let mut m = generate_test();
1212         let mut len = m.len();
1213         for (i, elt) in m.iter_mut().enumerate() {
1214             assert_eq!(i as i32, *elt);
1215             len -= 1;
1216         }
1217         assert_eq!(len, 0);
1218         let mut n = DList::new();
1219         assert!(n.iter_mut().next().is_none());
1220         n.push_front(4);
1221         n.push_back(5);
1222         let mut it = n.iter_mut();
1223         assert_eq!(it.size_hint(), (2, Some(2)));
1224         assert!(it.next().is_some());
1225         assert!(it.next().is_some());
1226         assert_eq!(it.size_hint(), (0, Some(0)));
1227         assert!(it.next().is_none());
1228     }
1229
1230     #[test]
1231     fn test_iterator_mut_double_end() {
1232         let mut n = DList::new();
1233         assert!(n.iter_mut().next_back().is_none());
1234         n.push_front(4);
1235         n.push_front(5);
1236         n.push_front(6);
1237         let mut it = n.iter_mut();
1238         assert_eq!(it.size_hint(), (3, Some(3)));
1239         assert_eq!(*it.next().unwrap(), 6);
1240         assert_eq!(it.size_hint(), (2, Some(2)));
1241         assert_eq!(*it.next_back().unwrap(), 4);
1242         assert_eq!(it.size_hint(), (1, Some(1)));
1243         assert_eq!(*it.next_back().unwrap(), 5);
1244         assert!(it.next_back().is_none());
1245         assert!(it.next().is_none());
1246     }
1247
1248     #[test]
1249     fn test_insert_prev() {
1250         let mut m = list_from(&[0,2,4,6,8]);
1251         let len = m.len();
1252         {
1253             let mut it = m.iter_mut();
1254             it.insert_next(-2);
1255             loop {
1256                 match it.next() {
1257                     None => break,
1258                     Some(elt) => {
1259                         it.insert_next(*elt + 1);
1260                         match it.peek_next() {
1261                             Some(x) => assert_eq!(*x, *elt + 2),
1262                             None => assert_eq!(8, *elt),
1263                         }
1264                     }
1265                 }
1266             }
1267             it.insert_next(0);
1268             it.insert_next(1);
1269         }
1270         check_links(&m);
1271         assert_eq!(m.len(), 3 + len * 2);
1272         assert_eq!(m.into_iter().collect::<Vec<_>>(), vec![-2,0,1,2,3,4,5,6,7,8,9,0,1]);
1273     }
1274
1275     #[test]
1276     fn test_mut_rev_iter() {
1277         let mut m = generate_test();
1278         for (i, elt) in m.iter_mut().rev().enumerate() {
1279             assert_eq!((6 - i) as i32, *elt);
1280         }
1281         let mut n = DList::new();
1282         assert!(n.iter_mut().rev().next().is_none());
1283         n.push_front(4);
1284         let mut it = n.iter_mut().rev();
1285         assert!(it.next().is_some());
1286         assert!(it.next().is_none());
1287     }
1288
1289     #[test]
1290     fn test_send() {
1291         let n = list_from(&[1,2,3]);
1292         thread::spawn(move || {
1293             check_links(&n);
1294             let a: &[_] = &[&1,&2,&3];
1295             assert_eq!(a, n.iter().collect::<Vec<_>>());
1296         }).join().ok().unwrap();
1297     }
1298
1299     #[test]
1300     fn test_eq() {
1301         let mut n = list_from(&[]);
1302         let mut m = list_from(&[]);
1303         assert!(n == m);
1304         n.push_front(1);
1305         assert!(n != m);
1306         m.push_back(1);
1307         assert!(n == m);
1308
1309         let n = list_from(&[2,3,4]);
1310         let m = list_from(&[1,2,3]);
1311         assert!(n != m);
1312     }
1313
1314     #[test]
1315     fn test_hash() {
1316       let mut x = DList::new();
1317       let mut y = DList::new();
1318
1319       assert!(hash::hash::<_, SipHasher>(&x) == hash::hash::<_, SipHasher>(&y));
1320
1321       x.push_back(1);
1322       x.push_back(2);
1323       x.push_back(3);
1324
1325       y.push_front(3);
1326       y.push_front(2);
1327       y.push_front(1);
1328
1329       assert!(hash::hash::<_, SipHasher>(&x) == hash::hash::<_, SipHasher>(&y));
1330     }
1331
1332     #[test]
1333     fn test_ord() {
1334         let n = list_from(&[]);
1335         let m = list_from(&[1,2,3]);
1336         assert!(n < m);
1337         assert!(m > n);
1338         assert!(n <= n);
1339         assert!(n >= n);
1340     }
1341
1342     #[test]
1343     fn test_ord_nan() {
1344         let nan = 0.0f64/0.0;
1345         let n = list_from(&[nan]);
1346         let m = list_from(&[nan]);
1347         assert!(!(n < m));
1348         assert!(!(n > m));
1349         assert!(!(n <= m));
1350         assert!(!(n >= m));
1351
1352         let n = list_from(&[nan]);
1353         let one = list_from(&[1.0f64]);
1354         assert!(!(n < one));
1355         assert!(!(n > one));
1356         assert!(!(n <= one));
1357         assert!(!(n >= one));
1358
1359         let u = list_from(&[1.0f64,2.0,nan]);
1360         let v = list_from(&[1.0f64,2.0,3.0]);
1361         assert!(!(u < v));
1362         assert!(!(u > v));
1363         assert!(!(u <= v));
1364         assert!(!(u >= v));
1365
1366         let s = list_from(&[1.0f64,2.0,4.0,2.0]);
1367         let t = list_from(&[1.0f64,2.0,3.0,2.0]);
1368         assert!(!(s < t));
1369         assert!(s > one);
1370         assert!(!(s <= one));
1371         assert!(s >= one);
1372     }
1373
1374     #[test]
1375     fn test_fuzz() {
1376         for _ in 0..25 {
1377             fuzz_test(3);
1378             fuzz_test(16);
1379             fuzz_test(189);
1380         }
1381     }
1382
1383     #[test]
1384     fn test_show() {
1385         let list: DList<_> = (0..10).collect();
1386         assert_eq!(format!("{:?}", list), "DList [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]");
1387
1388         let list: DList<_> = vec!["just", "one", "test", "more"].iter().cloned().collect();
1389         assert_eq!(format!("{:?}", list), "DList [\"just\", \"one\", \"test\", \"more\"]");
1390     }
1391
1392     #[cfg(test)]
1393     fn fuzz_test(sz: i32) {
1394         let mut m: DList<_> = DList::new();
1395         let mut v = vec![];
1396         for i in 0..sz {
1397             check_links(&m);
1398             let r: u8 = rand::random();
1399             match r % 6 {
1400                 0 => {
1401                     m.pop_back();
1402                     v.pop();
1403                 }
1404                 1 => {
1405                     if !v.is_empty() {
1406                         m.pop_front();
1407                         v.remove(0);
1408                     }
1409                 }
1410                 2 | 4 =>  {
1411                     m.push_front(-i);
1412                     v.insert(0, -i);
1413                 }
1414                 3 | 5 | _ => {
1415                     m.push_back(i);
1416                     v.push(i);
1417                 }
1418             }
1419         }
1420
1421         check_links(&m);
1422
1423         let mut i = 0;
1424         for (a, &b) in m.into_iter().zip(v.iter()) {
1425             i += 1;
1426             assert_eq!(a, b);
1427         }
1428         assert_eq!(i, v.len());
1429     }
1430
1431     #[bench]
1432     fn bench_collect_into(b: &mut test::Bencher) {
1433         let v = &[0; 64];
1434         b.iter(|| {
1435             let _: DList<_> = v.iter().cloned().collect();
1436         })
1437     }
1438
1439     #[bench]
1440     fn bench_push_front(b: &mut test::Bencher) {
1441         let mut m: DList<_> = DList::new();
1442         b.iter(|| {
1443             m.push_front(0);
1444         })
1445     }
1446
1447     #[bench]
1448     fn bench_push_back(b: &mut test::Bencher) {
1449         let mut m: DList<_> = DList::new();
1450         b.iter(|| {
1451             m.push_back(0);
1452         })
1453     }
1454
1455     #[bench]
1456     fn bench_push_back_pop_back(b: &mut test::Bencher) {
1457         let mut m: DList<_> = DList::new();
1458         b.iter(|| {
1459             m.push_back(0);
1460             m.pop_back();
1461         })
1462     }
1463
1464     #[bench]
1465     fn bench_push_front_pop_front(b: &mut test::Bencher) {
1466         let mut m: DList<_> = DList::new();
1467         b.iter(|| {
1468             m.push_front(0);
1469             m.pop_front();
1470         })
1471     }
1472
1473     #[bench]
1474     fn bench_iter(b: &mut test::Bencher) {
1475         let v = &[0; 128];
1476         let m: DList<_> = v.iter().cloned().collect();
1477         b.iter(|| {
1478             assert!(m.iter().count() == 128);
1479         })
1480     }
1481     #[bench]
1482     fn bench_iter_mut(b: &mut test::Bencher) {
1483         let v = &[0; 128];
1484         let mut m: DList<_> = v.iter().cloned().collect();
1485         b.iter(|| {
1486             assert!(m.iter_mut().count() == 128);
1487         })
1488     }
1489     #[bench]
1490     fn bench_iter_rev(b: &mut test::Bencher) {
1491         let v = &[0; 128];
1492         let m: DList<_> = v.iter().cloned().collect();
1493         b.iter(|| {
1494             assert!(m.iter().rev().count() == 128);
1495         })
1496     }
1497     #[bench]
1498     fn bench_iter_mut_rev(b: &mut test::Bencher) {
1499         let v = &[0; 128];
1500         let mut m: DList<_> = v.iter().cloned().collect();
1501         b.iter(|| {
1502             assert!(m.iter_mut().rev().count() == 128);
1503         })
1504     }
1505 }