1 // Copyright 2012-2013 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.
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.
11 //! A doubly-linked list with owned nodes.
13 //! The DList allows pushing and popping elements at either end.
15 //! DList implements the trait Deque. It should be imported with `use
16 //! extra::container::Deque`.
19 // DList is constructed like a singly-linked list over the field `next`.
20 // including the last link being None; each Node owns its `next` field.
22 // Backlinks over DList::prev are raw pointers that form a full chain in
23 // the reverse direction.
28 use std::iterator::{FromIterator, InvertIterator};
32 /// A doubly-linked list.
35 priv list_head: Link<T>,
36 priv list_tail: Rawlink<Node<T>>,
39 type Link<T> = Option<~Node<T>>;
40 struct Rawlink<T> { priv p: *mut T }
44 priv prev: Rawlink<Node<T>>,
48 /// Double-ended DList iterator
50 pub struct DListIterator<'self, T> {
51 priv head: &'self Link<T>,
52 priv tail: Rawlink<Node<T>>,
56 /// Double-ended mutable DList iterator
57 pub struct MutDListIterator<'self, T> {
58 priv list: &'self mut DList<T>,
59 priv head: Rawlink<Node<T>>,
60 priv tail: Rawlink<Node<T>>,
64 /// DList consuming iterator
66 pub struct ConsumeIterator<T> {
70 /// Rawlink is a type like Option<T> but for holding a raw pointer
72 /// Like Option::None for Rawlink
73 fn none() -> Rawlink<T> {
74 Rawlink{p: ptr::mut_null()}
77 /// Like Option::Some for Rawlink
78 fn some(n: &mut T) -> Rawlink<T> {
79 Rawlink{p: ptr::to_mut_unsafe_ptr(n)}
82 /// Convert the `Rawlink` into an Option value
83 fn resolve_immut(&self) -> Option<&T> {
84 unsafe { self.p.to_option() }
87 /// Convert the `Rawlink` into an Option value
88 fn resolve(&mut self) -> Option<&mut T> {
92 Some(unsafe { cast::transmute(self.p) })
97 impl<T> Clone for Rawlink<T> {
99 fn clone(&self) -> Rawlink<T> {
105 fn new(v: T) -> Node<T> {
106 Node{value: v, next: None, prev: Rawlink::none()}
110 /// Set the .prev field on `next`, then return `Some(next)`
111 fn link_with_prev<T>(mut next: ~Node<T>, prev: Rawlink<Node<T>>) -> Link<T> {
116 impl<T> Container for DList<T> {
119 fn is_empty(&self) -> bool {
120 self.list_head.is_none()
124 fn len(&self) -> uint {
129 impl<T> Mutable for DList<T> {
130 /// Remove all elements from the DList
134 fn clear(&mut self) {
141 /// Add a Node first in the list
143 fn push_front_node(&mut self, mut new_head: ~Node<T>) {
144 match self.list_head {
146 self.list_tail = Rawlink::some(new_head);
147 self.list_head = link_with_prev(new_head, Rawlink::none());
149 Some(ref mut head) => {
150 new_head.prev = Rawlink::none();
151 head.prev = Rawlink::some(new_head);
152 util::swap(head, &mut new_head);
153 head.next = Some(new_head);
159 /// Remove the first Node and return it, or None if the list is empty
161 fn pop_front_node(&mut self) -> Option<~Node<T>> {
162 do self.list_head.take().map_consume |mut front_node| {
164 match front_node.next.take() {
165 Some(node) => self.list_head = link_with_prev(node, Rawlink::none()),
166 None => self.list_tail = Rawlink::none()
172 /// Add a Node last in the list
174 fn push_back_node(&mut self, mut new_tail: ~Node<T>) {
175 match self.list_tail.resolve() {
176 None => return self.push_front_node(new_tail),
178 self.list_tail = Rawlink::some(new_tail);
179 tail.next = link_with_prev(new_tail, Rawlink::some(tail));
185 /// Remove the last Node and return it, or None if the list is empty
187 fn pop_back_node(&mut self) -> Option<~Node<T>> {
188 do self.list_tail.resolve().map_consume_default(None) |tail| {
190 self.list_tail = tail.prev;
191 match tail.prev.resolve() {
192 None => self.list_head.take(),
193 Some(tail_prev) => tail_prev.next.take()
199 impl<T> Deque<T> for DList<T> {
200 /// Provide a reference to the front element, or None if the list is empty
202 fn front<'a>(&'a self) -> Option<&'a T> {
203 self.list_head.map(|head| &head.value)
206 /// Provide a mutable reference to the front element, or None if the list is empty
208 fn front_mut<'a>(&'a mut self) -> Option<&'a mut T> {
209 self.list_head.map_mut(|head| &mut head.value)
212 /// Provide a reference to the back element, or None if the list is empty
214 fn back<'a>(&'a self) -> Option<&'a T> {
215 self.list_tail.resolve_immut().map(|tail| &tail.value)
218 /// Provide a mutable reference to the back element, or None if the list is empty
220 fn back_mut<'a>(&'a mut self) -> Option<&'a mut T> {
221 self.list_tail.resolve().map_mut(|tail| &mut tail.value)
224 /// Add an element first in the list
227 fn push_front(&mut self, elt: T) {
228 self.push_front_node(~Node::new(elt))
231 /// Remove the first element and return it, or None if the list is empty
234 fn pop_front(&mut self) -> Option<T> {
235 self.pop_front_node().map_consume(|~Node{value, _}| value)
238 /// Add an element last in the list
241 fn push_back(&mut self, elt: T) {
242 self.push_back_node(~Node::new(elt))
245 /// Remove the last element and return it, or None if the list is empty
248 fn pop_back(&mut self) -> Option<T> {
249 self.pop_back_node().map_consume(|~Node{value, _}| value)
254 /// Create an empty DList
256 pub fn new() -> DList<T> {
257 DList{list_head: None, list_tail: Rawlink::none(), length: 0}
260 /// Move the last element to the front of the list.
262 /// If the list is empty, do nothing.
264 pub fn rotate_to_front(&mut self) {
265 do self.pop_back_node().map_consume |tail| {
266 self.push_front_node(tail)
270 /// Move the first element to the back of the list.
272 /// If the list is empty, do nothing.
274 pub fn rotate_to_back(&mut self) {
275 do self.pop_front_node().map_consume |head| {
276 self.push_back_node(head)
280 /// Add all elements from `other` to the end of the list
283 pub fn append(&mut self, other: DList<T>) {
284 match self.list_tail.resolve() {
285 None => *self = other,
288 DList{list_head: None, _} => return,
289 DList{list_head: Some(node), list_tail: o_tail, length: o_length} => {
290 tail.next = link_with_prev(node, self.list_tail);
291 self.list_tail = o_tail;
292 self.length += o_length;
299 /// Add all elements from `other` to the beginning of the list
303 pub fn prepend(&mut self, mut other: DList<T>) {
304 util::swap(self, &mut other);
308 /// Insert `elt` before the first `x` in the list where `f(x, elt)` is true,
312 pub fn insert_when(&mut self, elt: T, f: &fn(&T, &T) -> bool) {
314 let mut it = self.mut_iter();
316 match it.peek_next() {
318 Some(x) => if f(x, &elt) { break }
326 /// Merge DList `other` into this DList, using the function `f`.
327 /// Iterate the both DList with `a` from self and `b` from `other`, and
328 /// put `a` in the result if `f(a, b)` is true, else `b`.
331 pub fn merge(&mut self, mut other: DList<T>, f: &fn(&T, &T) -> bool) {
333 let mut it = self.mut_iter();
335 let take_a = match (it.peek_next(), other.front()) {
336 (_ , None) => return,
338 (Some(ref mut x), Some(y)) => f(*x, y),
343 it.insert_next_node(other.pop_front_node().unwrap());
351 /// Provide a forward iterator
353 pub fn iter<'a>(&'a self) -> DListIterator<'a, T> {
354 DListIterator{nelem: self.len(), head: &self.list_head, tail: self.list_tail}
357 /// Provide a reverse iterator
359 pub fn rev_iter<'a>(&'a self) -> InvertIterator<&'a T, DListIterator<'a, T>> {
363 /// Provide a forward iterator with mutable references
365 pub fn mut_iter<'a>(&'a mut self) -> MutDListIterator<'a, T> {
366 let head_raw = match self.list_head {
367 Some(ref mut h) => Rawlink::some(*h),
368 None => Rawlink::none(),
373 tail: self.list_tail,
377 /// Provide a reverse iterator with mutable references
379 pub fn mut_rev_iter<'a>(&'a mut self) -> InvertIterator<&'a mut T,
380 MutDListIterator<'a, T>> {
381 self.mut_iter().invert()
385 /// Consume the list into an iterator yielding elements by value
387 pub fn consume_iter(self) -> ConsumeIterator<T> {
388 ConsumeIterator{list: self}
391 /// Consume the list into an iterator yielding elements by value, in reverse
393 pub fn consume_rev_iter(self) -> InvertIterator<T, ConsumeIterator<T>> {
394 self.consume_iter().invert()
398 impl<T: Ord> DList<T> {
399 /// Insert `elt` sorted in ascending order
403 pub fn insert_ordered(&mut self, elt: T) {
404 self.insert_when(elt, |a, b| a >= b)
408 impl<'self, A> Iterator<&'self A> for DListIterator<'self, A> {
410 fn next(&mut self) -> Option<&'self A> {
414 do self.head.map |head| {
416 self.head = &head.next;
422 fn size_hint(&self) -> (uint, Option<uint>) {
423 (self.nelem, Some(self.nelem))
427 impl<'self, A> DoubleEndedIterator<&'self A> for DListIterator<'self, A> {
429 fn next_back(&mut self) -> Option<&'self A> {
433 do self.tail.resolve().map_consume |prev| {
435 self.tail = prev.prev;
441 impl<'self, A> Iterator<&'self mut A> for MutDListIterator<'self, A> {
443 fn next(&mut self) -> Option<&'self mut A> {
447 do self.head.resolve().map_consume |next| {
449 self.head = match next.next {
450 Some(ref mut node) => Rawlink::some(&mut **node),
451 None => Rawlink::none(),
458 fn size_hint(&self) -> (uint, Option<uint>) {
459 (self.nelem, Some(self.nelem))
463 impl<'self, A> DoubleEndedIterator<&'self mut A> for MutDListIterator<'self, A> {
465 fn next_back(&mut self) -> Option<&'self mut A> {
469 do self.tail.resolve().map_consume |prev| {
471 self.tail = prev.prev;
478 /// Allow mutating the DList while iterating
479 pub trait ListInsertion<A> {
480 /// Insert `elt` just after to the element most recently returned by `.next()`
482 /// The inserted element does not appear in the iteration.
483 fn insert_next(&mut self, elt: A);
485 /// Provide a reference to the next element, without changing the iterator
486 fn peek_next<'a>(&'a mut self) -> Option<&'a mut A>;
489 // private methods for MutDListIterator
490 impl<'self, A> MutDListIterator<'self, A> {
491 fn insert_next_node(&mut self, mut ins_node: ~Node<A>) {
492 // Insert before `self.head` so that it is between the
493 // previously yielded element and self.head.
495 // The inserted node will not appear in further iteration.
496 match self.head.resolve() {
497 None => { self.list.push_back_node(ins_node); }
499 let prev_node = match node.prev.resolve() {
500 None => return self.list.push_front_node(ins_node),
503 let node_own = prev_node.next.take_unwrap();
504 ins_node.next = link_with_prev(node_own, Rawlink::some(ins_node));
505 prev_node.next = link_with_prev(ins_node, Rawlink::some(prev_node));
506 self.list.length += 1;
512 impl<'self, A> ListInsertion<A> for MutDListIterator<'self, A> {
514 fn insert_next(&mut self, elt: A) {
515 self.insert_next_node(~Node::new(elt))
519 fn peek_next<'a>(&'a mut self) -> Option<&'a mut A> {
523 self.head.resolve().map_consume(|head| &mut head.value)
527 impl<A> Iterator<A> for ConsumeIterator<A> {
529 fn next(&mut self) -> Option<A> { self.list.pop_front() }
532 fn size_hint(&self) -> (uint, Option<uint>) {
533 (self.list.length, Some(self.list.length))
537 impl<A> DoubleEndedIterator<A> for ConsumeIterator<A> {
539 fn next_back(&mut self) -> Option<A> { self.list.pop_back() }
542 impl<A, T: Iterator<A>> FromIterator<A, T> for DList<A> {
543 fn from_iterator(iterator: &mut T) -> DList<A> {
544 let mut ret = DList::new();
545 for iterator.advance |elt| { ret.push_back(elt); }
550 impl<A: Eq> Eq for DList<A> {
551 fn eq(&self, other: &DList<A>) -> bool {
552 self.len() == other.len() &&
553 self.iter().zip(other.iter()).all(|(a, b)| a.eq(b))
557 fn ne(&self, other: &DList<A>) -> bool {
562 impl<A: Clone> Clone for DList<A> {
563 fn clone(&self) -> DList<A> {
564 self.iter().transform(|x| x.clone()).collect()
569 pub fn check_links<T>(list: &DList<T>) {
571 let mut last_ptr: Option<&Node<T>> = None;
572 let mut node_ptr: &Node<T>;
573 match list.list_head {
574 None => { assert_eq!(0u, list.length); return }
575 Some(ref node) => node_ptr = &**node,
578 match (last_ptr, node_ptr.prev.resolve_immut()) {
580 (None , _ ) => fail!("prev link for list_head"),
581 (Some(p), Some(pptr)) => {
582 assert_eq!(p as *Node<T>, pptr as *Node<T>);
584 _ => fail!("prev link is none, not good"),
586 match node_ptr.next {
588 last_ptr = Some(node_ptr);
598 assert_eq!(len, list.length);
610 let mut m = DList::new::<~int>();
611 assert_eq!(m.pop_front(), None);
612 assert_eq!(m.pop_back(), None);
613 assert_eq!(m.pop_front(), None);
615 assert_eq!(m.pop_front(), Some(~1));
618 assert_eq!(m.len(), 2);
619 assert_eq!(m.pop_front(), Some(~2));
620 assert_eq!(m.pop_front(), Some(~3));
621 assert_eq!(m.len(), 0);
622 assert_eq!(m.pop_front(), None);
627 assert_eq!(m.pop_front(), Some(~1));
629 let mut n = DList::new();
633 assert_eq!(n.front().unwrap(), &3);
634 let x = n.front_mut().unwrap();
639 assert_eq!(n.back().unwrap(), &2);
640 let y = n.back_mut().unwrap();
644 assert_eq!(n.pop_front(), Some(0));
645 assert_eq!(n.pop_front(), Some(1));
649 fn generate_test() -> DList<int> {
650 list_from(&[0,1,2,3,4,5,6])
654 fn list_from<T: Clone>(v: &[T]) -> DList<T> {
655 v.iter().transform(|x| (*x).clone()).collect()
661 let mut m = DList::new();
662 let mut n = DList::new();
665 assert_eq!(m.len(), 1);
666 assert_eq!(m.pop_back(), Some(2));
670 let mut m = DList::new();
671 let n = DList::new();
674 assert_eq!(m.len(), 1);
675 assert_eq!(m.pop_back(), Some(2));
679 let v = ~[1,2,3,4,5];
680 let u = ~[9,8,1,2,3,4,5];
681 let mut m = list_from(v);
682 m.append(list_from(u));
685 assert_eq!(sum.len(), m.len());
686 for sum.consume_iter().advance |elt| {
687 assert_eq!(m.pop_front(), Some(elt))
694 let mut m = DList::new();
695 let mut n = DList::new();
698 assert_eq!(m.len(), 1);
699 assert_eq!(m.pop_back(), Some(2));
703 let v = ~[1,2,3,4,5];
704 let u = ~[9,8,1,2,3,4,5];
705 let mut m = list_from(v);
706 m.prepend(list_from(u));
709 assert_eq!(sum.len(), m.len());
710 for sum.consume_iter().advance |elt| {
711 assert_eq!(m.pop_front(), Some(elt))
717 let mut n = DList::new::<int>();
718 n.rotate_to_back(); check_links(&n);
719 assert_eq!(n.len(), 0);
720 n.rotate_to_front(); check_links(&n);
721 assert_eq!(n.len(), 0);
723 let v = ~[1,2,3,4,5];
724 let mut m = list_from(v);
725 m.rotate_to_back(); check_links(&m);
726 m.rotate_to_front(); check_links(&m);
727 assert_eq!(v.iter().collect::<~[&int]>(), m.iter().collect());
728 m.rotate_to_front(); check_links(&m);
729 m.rotate_to_front(); check_links(&m);
730 m.pop_front(); check_links(&m);
731 m.rotate_to_front(); check_links(&m);
732 m.rotate_to_back(); check_links(&m);
733 m.push_front(9); check_links(&m);
734 m.rotate_to_front(); check_links(&m);
735 assert_eq!(~[3,9,5,1,2], m.consume_iter().collect());
740 let m = generate_test();
741 for m.iter().enumerate().advance |(i, elt)| {
742 assert_eq!(i as int, *elt);
744 let mut n = DList::new();
745 assert_eq!(n.iter().next(), None);
747 let mut it = n.iter();
748 assert_eq!(it.size_hint(), (1, Some(1)));
749 assert_eq!(it.next().unwrap(), &4);
750 assert_eq!(it.size_hint(), (0, Some(0)));
751 assert_eq!(it.next(), None);
755 fn test_iterator_clone() {
756 let mut n = DList::new();
760 let mut it = n.iter();
762 let mut jt = it.clone();
763 assert_eq!(it.next(), jt.next());
764 assert_eq!(it.next_back(), jt.next_back());
765 assert_eq!(it.next(), jt.next());
769 fn test_iterator_double_end() {
770 let mut n = DList::new();
771 assert_eq!(n.iter().next(), None);
775 let mut it = n.iter();
776 assert_eq!(it.size_hint(), (3, Some(3)));
777 assert_eq!(it.next().unwrap(), &6);
778 assert_eq!(it.size_hint(), (2, Some(2)));
779 assert_eq!(it.next_back().unwrap(), &4);
780 assert_eq!(it.size_hint(), (1, Some(1)));
781 assert_eq!(it.next_back().unwrap(), &5);
782 assert_eq!(it.next_back(), None);
783 assert_eq!(it.next(), None);
788 let m = generate_test();
789 for m.rev_iter().enumerate().advance |(i, elt)| {
790 assert_eq!((6 - i) as int, *elt);
792 let mut n = DList::new();
793 assert_eq!(n.rev_iter().next(), None);
795 let mut it = n.rev_iter();
796 assert_eq!(it.size_hint(), (1, Some(1)));
797 assert_eq!(it.next().unwrap(), &4);
798 assert_eq!(it.size_hint(), (0, Some(0)));
799 assert_eq!(it.next(), None);
804 let mut m = generate_test();
805 let mut len = m.len();
806 for m.mut_iter().enumerate().advance |(i, elt)| {
807 assert_eq!(i as int, *elt);
811 let mut n = DList::new();
812 assert!(n.mut_iter().next().is_none());
815 let mut it = n.mut_iter();
816 assert_eq!(it.size_hint(), (2, Some(2)));
817 assert!(it.next().is_some());
818 assert!(it.next().is_some());
819 assert_eq!(it.size_hint(), (0, Some(0)));
820 assert!(it.next().is_none());
824 fn test_iterator_mut_double_end() {
825 let mut n = DList::new();
826 assert!(n.mut_iter().next_back().is_none());
830 let mut it = n.mut_iter();
831 assert_eq!(it.size_hint(), (3, Some(3)));
832 assert_eq!(*it.next().unwrap(), 6);
833 assert_eq!(it.size_hint(), (2, Some(2)));
834 assert_eq!(*it.next_back().unwrap(), 4);
835 assert_eq!(it.size_hint(), (1, Some(1)));
836 assert_eq!(*it.next_back().unwrap(), 5);
837 assert!(it.next_back().is_none());
838 assert!(it.next().is_none());
842 fn test_insert_prev() {
843 let mut m = list_from(&[0,2,4,6,8]);
846 let mut it = m.mut_iter();
852 it.insert_next(*elt + 1);
853 match it.peek_next() {
854 Some(x) => assert_eq!(*x, *elt + 2),
855 None => assert_eq!(8, *elt),
864 assert_eq!(m.len(), 3 + len * 2);
865 assert_eq!(m.consume_iter().collect::<~[int]>(), ~[-2,0,1,2,3,4,5,6,7,8,9,0,1]);
870 let mut m = list_from([0, 1, 3, 5, 6, 7, 2]);
871 let n = list_from([-1, 0, 0, 7, 7, 9]);
872 let len = m.len() + n.len();
873 m.merge(n, |a, b| a <= b);
874 assert_eq!(m.len(), len);
876 let res = m.consume_iter().collect::<~[int]>();
877 assert_eq!(res, ~[-1, 0, 0, 0, 1, 3, 5, 6, 7, 2, 7, 7, 9]);
881 fn test_insert_ordered() {
882 let mut n = DList::new();
884 assert_eq!(n.len(), 1);
885 assert_eq!(n.pop_front(), Some(1));
887 let mut m = DList::new();
892 assert_eq!(~[2,3,4], m.consume_iter().collect::<~[int]>());
896 fn test_mut_rev_iter() {
897 let mut m = generate_test();
898 for m.mut_rev_iter().enumerate().advance |(i, elt)| {
899 assert_eq!((6-i) as int, *elt);
901 let mut n = DList::new();
902 assert!(n.mut_rev_iter().next().is_none());
904 let mut it = n.mut_rev_iter();
905 assert!(it.next().is_some());
906 assert!(it.next().is_none());
911 let n = list_from([1,2,3]);
914 assert_eq!(~[&1,&2,&3], n.iter().collect::<~[&int]>());
920 let mut n: DList<u8> = list_from([]);
921 let mut m = list_from([]);
939 fn fuzz_test(sz: int) {
940 let mut m = DList::new::<int>();
942 for int::range(0i, sz) |i| {
944 let r: u8 = rand::random();
948 if v.len() > 0 { v.pop(); }
952 if v.len() > 0 { v.shift(); }
968 for m.consume_iter().zip(v.iter()).advance |(a, &b)| {
972 assert_eq!(i, v.len());
976 fn bench_collect_into(b: &mut test::BenchHarness) {
979 let _: DList<int> = v.iter().transform(|x| *x).collect();
984 fn bench_push_front(b: &mut test::BenchHarness) {
985 let mut m = DList::new::<int>();
992 fn bench_push_back(b: &mut test::BenchHarness) {
993 let mut m = DList::new::<int>();
1000 fn bench_push_back_pop_back(b: &mut test::BenchHarness) {
1001 let mut m = DList::new::<int>();
1009 fn bench_push_front_pop_front(b: &mut test::BenchHarness) {
1010 let mut m = DList::new::<int>();
1018 fn bench_rotate_to_front(b: &mut test::BenchHarness) {
1019 let mut m = DList::new::<int>();
1023 m.rotate_to_front();
1028 fn bench_rotate_to_back(b: &mut test::BenchHarness) {
1029 let mut m = DList::new::<int>();
1038 fn bench_iter(b: &mut test::BenchHarness) {
1039 let v = &[0, ..128];
1040 let m: DList<int> = v.iter().transform(|&x|x).collect();
1042 assert!(m.iter().len_() == 128);
1046 fn bench_iter_mut(b: &mut test::BenchHarness) {
1047 let v = &[0, ..128];
1048 let mut m: DList<int> = v.iter().transform(|&x|x).collect();
1050 assert!(m.mut_iter().len_() == 128);
1054 fn bench_iter_rev(b: &mut test::BenchHarness) {
1055 let v = &[0, ..128];
1056 let m: DList<int> = v.iter().transform(|&x|x).collect();
1058 assert!(m.rev_iter().len_() == 128);
1062 fn bench_iter_mut_rev(b: &mut test::BenchHarness) {
1063 let v = &[0, ..128];
1064 let mut m: DList<int> = v.iter().transform(|&x|x).collect();
1066 assert!(m.mut_rev_iter().len_() == 128);