1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
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 //! This crate implements a double-ended queue with `O(1)` amortized inserts and removals from both
12 //! ends of the container. It also has `O(1)` indexing like a vector. The contained elements are
13 //! not required to be copyable, and the queue will be sendable if the contained type is sendable.
14 //! Its interface `Deque` is defined in `collections`.
18 use core::default::Default;
21 use core::raw::Slice as RawSlice;
23 use core::kinds::marker;
25 use core::num::{Int, UnsignedInt};
27 use std::hash::{Writer, Hash};
32 static INITIAL_CAPACITY: uint = 8u; // 2^3
33 static MINIMUM_CAPACITY: uint = 2u;
35 // FIXME(conventions): implement shrink_to_fit. Awkward with the current design, but it should
36 // be scrapped anyway. Defer to rewrite?
38 /// `RingBuf` is a circular buffer that implements `Deque`.
39 pub struct RingBuf<T> {
40 // tail and head are pointers into the buffer. Tail always points
41 // to the first element that could be read, Head always points
42 // to where data should be written.
43 // If tail == head the buffer is empty. The length of the ringbuf
44 // is defined as the distance between the two.
52 impl<T: Clone> Clone for RingBuf<T> {
53 fn clone(&self) -> RingBuf<T> {
54 self.iter().map(|t| t.clone()).collect()
59 impl<T> Drop for RingBuf<T> {
63 if mem::size_of::<T>() != 0 {
64 heap::deallocate(self.ptr as *mut u8,
65 self.cap * mem::size_of::<T>(),
66 mem::min_align_of::<T>())
72 impl<T> Default for RingBuf<T> {
74 fn default() -> RingBuf<T> { RingBuf::new() }
78 /// Turn ptr into a slice
80 unsafe fn buffer_as_slice(&self) -> &[T] {
81 mem::transmute(RawSlice { data: self.ptr as *const T, len: self.cap })
84 /// Moves an element out of the buffer
86 unsafe fn buffer_read(&mut self, off: uint) -> T {
87 ptr::read(self.ptr.offset(off as int) as *const T)
90 /// Writes an element into the buffer, moving it.
92 unsafe fn buffer_write(&mut self, off: uint, t: T) {
93 ptr::write(self.ptr.offset(off as int), t);
96 /// Returns true iff the buffer is at capacity
98 fn is_full(&self) -> bool { self.cap - self.len() == 1 }
100 /// Returns the index in the underlying buffer for a given logical element index.
102 fn wrap_index(&self, idx: uint) -> uint { wrap_index(idx, self.cap) }
106 /// Creates an empty `RingBuf`.
107 #[unstable = "matches collection reform specification, waiting for dust to settle"]
108 pub fn new() -> RingBuf<T> {
109 RingBuf::with_capacity(INITIAL_CAPACITY)
112 /// Creates an empty `RingBuf` with space for at least `n` elements.
113 #[unstable = "matches collection reform specification, waiting for dust to settle"]
114 pub fn with_capacity(n: uint) -> RingBuf<T> {
115 // +1 since the ringbuffer always leaves one space empty
116 let cap = cmp::max(n + 1, MINIMUM_CAPACITY).next_power_of_two();
117 let size = cap.checked_mul(mem::size_of::<T>())
118 .expect("capacity overflow");
120 let ptr = if mem::size_of::<T>() != 0 {
122 let ptr = heap::allocate(size, mem::min_align_of::<T>()) as *mut T;;
123 if ptr.is_null() { ::alloc::oom() }
127 heap::EMPTY as *mut T
138 /// Retrieves an element in the `RingBuf` by index.
143 /// use std::collections::RingBuf;
145 /// let mut buf = RingBuf::new();
146 /// buf.push_back(3i);
147 /// buf.push_back(4);
148 /// buf.push_back(5);
149 /// assert_eq!(buf.get(1).unwrap(), &4);
151 #[unstable = "matches collection reform specification, waiting for dust to settle"]
152 pub fn get(&self, i: uint) -> Option<&T> {
154 let idx = self.wrap_index(self.tail + i);
155 unsafe { Some(&*self.ptr.offset(idx as int)) }
161 /// Retrieves an element in the `RingBuf` mutably by index.
166 /// use std::collections::RingBuf;
168 /// let mut buf = RingBuf::new();
169 /// buf.push_back(3i);
170 /// buf.push_back(4);
171 /// buf.push_back(5);
172 /// match buf.get_mut(1) {
179 /// assert_eq!(buf[1], 7);
181 #[unstable = "matches collection reform specification, waiting for dust to settle"]
182 pub fn get_mut(&mut self, i: uint) -> Option<&mut T> {
184 let idx = self.wrap_index(self.tail + i);
185 unsafe { Some(&mut *self.ptr.offset(idx as int)) }
191 /// Swaps elements at indices `i` and `j`.
193 /// `i` and `j` may be equal.
195 /// Fails if there is no element with either index.
200 /// use std::collections::RingBuf;
202 /// let mut buf = RingBuf::new();
203 /// buf.push_back(3i);
204 /// buf.push_back(4);
205 /// buf.push_back(5);
207 /// assert_eq!(buf[0], 5);
208 /// assert_eq!(buf[2], 3);
210 pub fn swap(&mut self, i: uint, j: uint) {
211 assert!(i < self.len());
212 assert!(j < self.len());
213 let ri = self.wrap_index(self.tail + i);
214 let rj = self.wrap_index(self.tail + j);
216 ptr::swap(self.ptr.offset(ri as int), self.ptr.offset(rj as int))
220 /// Returns the number of elements the `RingBuf` can hold without
226 /// use std::collections::RingBuf;
228 /// let buf: RingBuf<int> = RingBuf::with_capacity(10);
229 /// assert!(buf.capacity() >= 10);
232 #[unstable = "matches collection reform specification, waiting for dust to settle"]
233 pub fn capacity(&self) -> uint { self.cap - 1 }
235 /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the
236 /// given `RingBuf`. Does nothing if the capacity is already sufficient.
238 /// Note that the allocator may give the collection more space than it requests. Therefore
239 /// capacity can not be relied upon to be precisely minimal. Prefer `reserve` if future
240 /// insertions are expected.
244 /// Panics if the new capacity overflows `uint`.
249 /// use std::collections::RingBuf;
251 /// let mut buf: RingBuf<int> = vec![1].into_iter().collect();
252 /// buf.reserve_exact(10);
253 /// assert!(buf.capacity() >= 11);
255 #[unstable = "matches collection reform specification, waiting for dust to settle"]
256 pub fn reserve_exact(&mut self, additional: uint) {
257 self.reserve(additional);
260 /// Reserves capacity for at least `additional` more elements to be inserted in the given
261 /// `Ringbuf`. The collection may reserve more space to avoid frequent reallocations.
265 /// Panics if the new capacity overflows `uint`.
270 /// use std::collections::RingBuf;
272 /// let mut buf: RingBuf<int> = vec![1].into_iter().collect();
274 /// assert!(buf.capacity() >= 11);
276 #[unstable = "matches collection reform specification, waiting for dust to settle"]
277 pub fn reserve(&mut self, additional: uint) {
278 let new_len = self.len() + additional;
279 assert!(new_len + 1 > self.len(), "capacity overflow");
280 if new_len > self.capacity() {
281 let count = (new_len + 1).next_power_of_two();
282 assert!(count >= new_len + 1);
284 if mem::size_of::<T>() != 0 {
285 let old = self.cap * mem::size_of::<T>();
286 let new = count.checked_mul(mem::size_of::<T>())
287 .expect("capacity overflow");
289 self.ptr = heap::reallocate(self.ptr as *mut u8,
292 mem::min_align_of::<T>()) as *mut T;
293 if self.ptr.is_null() { ::alloc::oom() }
297 // Move the shortest contiguous section of the ring buffer
299 // [o o o o o o o . ]
301 // A [o o o o o o o . . . . . . . . . ]
303 // [o o . o o o o o ]
305 // B [. . . o o o o o o o . . . . . . ]
307 // [o o o o o . o o ]
309 // C [o o o o o . . . . . . . . . o o ]
311 let oldcap = self.cap;
314 if self.tail <= self.head { // A
316 } else if self.head < oldcap - self.tail { // B
318 ptr::copy_nonoverlapping_memory(
319 self.ptr.offset(oldcap as int),
320 self.ptr as *const T,
325 debug_assert!(self.head > self.tail);
328 ptr::copy_nonoverlapping_memory(
329 self.ptr.offset((count - (oldcap - self.tail)) as int),
330 self.ptr.offset(self.tail as int) as *const T,
334 self.tail = count - (oldcap - self.tail);
335 debug_assert!(self.head < self.tail);
337 debug_assert!(self.head < self.cap);
338 debug_assert!(self.tail < self.cap);
339 debug_assert!(self.cap.count_ones() == 1);
343 /// Returns a front-to-back iterator.
348 /// use std::collections::RingBuf;
350 /// let mut buf = RingBuf::new();
351 /// buf.push_back(5i);
352 /// buf.push_back(3);
353 /// buf.push_back(4);
354 /// let b: &[_] = &[&5, &3, &4];
355 /// assert_eq!(buf.iter().collect::<Vec<&int>>().as_slice(), b);
357 #[unstable = "matches collection reform specification, waiting for dust to settle"]
358 pub fn iter(&self) -> Items<T> {
362 ring: unsafe { self.buffer_as_slice() }
366 /// Returns a front-to-back iterator which returns mutable references.
371 /// use std::collections::RingBuf;
373 /// let mut buf = RingBuf::new();
374 /// buf.push_back(5i);
375 /// buf.push_back(3);
376 /// buf.push_back(4);
377 /// for num in buf.iter_mut() {
380 /// let b: &[_] = &[&mut 3, &mut 1, &mut 2];
381 /// assert_eq!(buf.iter_mut().collect::<Vec<&mut int>>()[], b);
383 #[unstable = "matches collection reform specification, waiting for dust to settle"]
384 pub fn iter_mut<'a>(&'a mut self) -> MutItems<'a, T> {
390 marker: marker::ContravariantLifetime::<'a>,
391 marker2: marker::NoCopy
395 /// Consumes the list into an iterator yielding elements by value.
396 #[unstable = "matches collection reform specification, waiting for dust to settle"]
397 pub fn into_iter(self) -> MoveItems<T> {
403 /// Returns the number of elements in the `RingBuf`.
408 /// use std::collections::RingBuf;
410 /// let mut v = RingBuf::new();
411 /// assert_eq!(v.len(), 0);
413 /// assert_eq!(v.len(), 1);
415 #[unstable = "matches collection reform specification, waiting for dust to settle"]
416 pub fn len(&self) -> uint { count(self.tail, self.head, self.cap) }
418 /// Returns true if the buffer contains no elements
423 /// use std::collections::RingBuf;
425 /// let mut v = RingBuf::new();
426 /// assert!(v.is_empty());
427 /// v.push_front(1i);
428 /// assert!(!v.is_empty());
430 #[unstable = "matches collection reform specification, waiting for dust to settle"]
431 pub fn is_empty(&self) -> bool { self.len() == 0 }
433 /// Clears the buffer, removing all values.
438 /// use std::collections::RingBuf;
440 /// let mut v = RingBuf::new();
443 /// assert!(v.is_empty());
445 #[unstable = "matches collection reform specification, waiting for dust to settle"]
446 pub fn clear(&mut self) {
447 while self.pop_front().is_some() {}
452 /// Provides a reference to the front element, or `None` if the sequence is
458 /// use std::collections::RingBuf;
460 /// let mut d = RingBuf::new();
461 /// assert_eq!(d.front(), None);
465 /// assert_eq!(d.front(), Some(&1i));
467 #[unstable = "matches collection reform specification, waiting for dust to settle"]
468 pub fn front(&self) -> Option<&T> {
469 if !self.is_empty() { Some(&self[0]) } else { None }
472 /// Provides a mutable reference to the front element, or `None` if the
473 /// sequence is empty.
478 /// use std::collections::RingBuf;
480 /// let mut d = RingBuf::new();
481 /// assert_eq!(d.front_mut(), None);
485 /// match d.front_mut() {
486 /// Some(x) => *x = 9i,
489 /// assert_eq!(d.front(), Some(&9i));
491 #[unstable = "matches collection reform specification, waiting for dust to settle"]
492 pub fn front_mut(&mut self) -> Option<&mut T> {
493 if !self.is_empty() { Some(&mut self[0]) } else { None }
496 /// Provides a reference to the back element, or `None` if the sequence is
502 /// use std::collections::RingBuf;
504 /// let mut d = RingBuf::new();
505 /// assert_eq!(d.back(), None);
509 /// assert_eq!(d.back(), Some(&2i));
511 #[unstable = "matches collection reform specification, waiting for dust to settle"]
512 pub fn back(&self) -> Option<&T> {
513 if !self.is_empty() { Some(&self[self.len() - 1]) } else { None }
516 /// Provides a mutable reference to the back element, or `None` if the
517 /// sequence is empty.
522 /// use std::collections::RingBuf;
524 /// let mut d = RingBuf::new();
525 /// assert_eq!(d.back(), None);
529 /// match d.back_mut() {
530 /// Some(x) => *x = 9i,
533 /// assert_eq!(d.back(), Some(&9i));
535 #[unstable = "matches collection reform specification, waiting for dust to settle"]
536 pub fn back_mut(&mut self) -> Option<&mut T> {
537 let len = self.len();
538 if !self.is_empty() { Some(&mut self[len - 1]) } else { None }
541 /// Removes the first element and returns it, or `None` if the sequence is
547 /// use std::collections::RingBuf;
549 /// let mut d = RingBuf::new();
553 /// assert_eq!(d.pop_front(), Some(1i));
554 /// assert_eq!(d.pop_front(), Some(2i));
555 /// assert_eq!(d.pop_front(), None);
557 #[unstable = "matches collection reform specification, waiting for dust to settle"]
558 pub fn pop_front(&mut self) -> Option<T> {
562 let tail = self.tail;
563 self.tail = self.wrap_index(self.tail + 1);
564 unsafe { Some(self.buffer_read(tail)) }
568 /// Inserts an element first in the sequence.
573 /// use std::collections::RingBuf;
575 /// let mut d = RingBuf::new();
576 /// d.push_front(1i);
577 /// d.push_front(2i);
578 /// assert_eq!(d.front(), Some(&2i));
580 #[unstable = "matches collection reform specification, waiting for dust to settle"]
581 pub fn push_front(&mut self, t: T) {
584 debug_assert!(!self.is_full());
587 self.tail = self.wrap_index(self.tail - 1);
588 let tail = self.tail;
589 unsafe { self.buffer_write(tail, t); }
592 /// Deprecated: Renamed to `push_back`.
593 #[deprecated = "Renamed to `push_back`"]
594 pub fn push(&mut self, t: T) {
598 /// Appends an element to the back of a buffer
603 /// use std::collections::RingBuf;
605 /// let mut buf = RingBuf::new();
606 /// buf.push_back(1i);
607 /// buf.push_back(3);
608 /// assert_eq!(3, *buf.back().unwrap());
610 #[unstable = "matches collection reform specification, waiting for dust to settle"]
611 pub fn push_back(&mut self, t: T) {
614 debug_assert!(!self.is_full());
617 let head = self.head;
618 self.head = self.wrap_index(self.head + 1);
619 unsafe { self.buffer_write(head, t) }
622 /// Deprecated: Renamed to `pop_back`.
623 #[deprecated = "Renamed to `pop_back`"]
624 pub fn pop(&mut self) -> Option<T> {
628 /// Removes the last element from a buffer and returns it, or `None` if
634 /// use std::collections::RingBuf;
636 /// let mut buf = RingBuf::new();
637 /// assert_eq!(buf.pop_back(), None);
638 /// buf.push_back(1i);
639 /// buf.push_back(3);
640 /// assert_eq!(buf.pop_back(), Some(3));
642 #[unstable = "matches collection reform specification, waiting for dust to settle"]
643 pub fn pop_back(&mut self) -> Option<T> {
647 self.head = self.wrap_index(self.head - 1);
648 let head = self.head;
649 unsafe { Some(self.buffer_read(head)) }
654 /// Returns the index in the underlying buffer for a given logical element index.
656 fn wrap_index(index: uint, size: uint) -> uint {
657 // size is always a power of 2
661 /// Calculate the number of elements left to be read in the buffer
663 fn count(tail: uint, head: uint, size: uint) -> uint {
664 // size is always a power of 2
665 (head - tail) & (size - 1)
668 /// `RingBuf` iterator.
669 pub struct Items<'a, T:'a> {
675 impl<'a, T> Iterator<&'a T> for Items<'a, T> {
677 fn next(&mut self) -> Option<&'a T> {
678 if self.tail == self.head {
681 let tail = self.tail;
682 self.tail = wrap_index(self.tail + 1, self.ring.len());
683 unsafe { Some(self.ring.unsafe_get(tail)) }
687 fn size_hint(&self) -> (uint, Option<uint>) {
688 let len = count(self.tail, self.head, self.ring.len());
693 impl<'a, T> DoubleEndedIterator<&'a T> for Items<'a, T> {
695 fn next_back(&mut self) -> Option<&'a T> {
696 if self.tail == self.head {
699 self.head = wrap_index(self.head - 1, self.ring.len());
700 unsafe { Some(self.ring.unsafe_get(self.head)) }
704 impl<'a, T> ExactSizeIterator<&'a T> for Items<'a, T> {}
706 impl<'a, T> RandomAccessIterator<&'a T> for Items<'a, T> {
708 fn indexable(&self) -> uint {
709 let (len, _) = self.size_hint();
714 fn idx(&mut self, j: uint) -> Option<&'a T> {
715 if j >= self.indexable() {
718 let idx = wrap_index(self.tail + j, self.ring.len());
719 unsafe { Some(self.ring.unsafe_get(idx)) }
724 // FIXME This was implemented differently from Items because of a problem
725 // with returning the mutable reference. I couldn't find a way to
726 // make the lifetime checker happy so, but there should be a way.
727 /// `RingBuf` mutable iterator.
728 pub struct MutItems<'a, T:'a> {
733 marker: marker::ContravariantLifetime<'a>,
734 marker2: marker::NoCopy
737 impl<'a, T> Iterator<&'a mut T> for MutItems<'a, T> {
739 fn next(&mut self) -> Option<&'a mut T> {
740 if self.tail == self.head {
743 let tail = self.tail;
744 self.tail = wrap_index(self.tail + 1, self.cap);
747 Some(&mut *self.ptr.offset(tail as int))
752 fn size_hint(&self) -> (uint, Option<uint>) {
753 let len = count(self.tail, self.head, self.cap);
758 impl<'a, T> DoubleEndedIterator<&'a mut T> for MutItems<'a, T> {
760 fn next_back(&mut self) -> Option<&'a mut T> {
761 if self.tail == self.head {
764 self.head = wrap_index(self.head - 1, self.cap);
767 Some(&mut *self.ptr.offset(self.head as int))
772 impl<'a, T> ExactSizeIterator<&'a mut T> for MutItems<'a, T> {}
774 // A by-value RingBuf iterator
775 pub struct MoveItems<T> {
779 impl<T> Iterator<T> for MoveItems<T> {
781 fn next(&mut self) -> Option<T> {
782 self.inner.pop_front()
786 fn size_hint(&self) -> (uint, Option<uint>) {
787 let len = self.inner.len();
792 impl<T> DoubleEndedIterator<T> for MoveItems<T> {
794 fn next_back(&mut self) -> Option<T> {
795 self.inner.pop_back()
800 impl<T> ExactSizeIterator<T> for MoveItems<T> {}
802 impl<A: PartialEq> PartialEq for RingBuf<A> {
803 fn eq(&self, other: &RingBuf<A>) -> bool {
804 self.len() == other.len() &&
805 self.iter().zip(other.iter()).all(|(a, b)| a.eq(b))
807 fn ne(&self, other: &RingBuf<A>) -> bool {
812 impl<A: Eq> Eq for RingBuf<A> {}
814 impl<A: PartialOrd> PartialOrd for RingBuf<A> {
815 fn partial_cmp(&self, other: &RingBuf<A>) -> Option<Ordering> {
816 iter::order::partial_cmp(self.iter(), other.iter())
820 impl<A: Ord> Ord for RingBuf<A> {
822 fn cmp(&self, other: &RingBuf<A>) -> Ordering {
823 iter::order::cmp(self.iter(), other.iter())
827 impl<S: Writer, A: Hash<S>> Hash<S> for RingBuf<A> {
828 fn hash(&self, state: &mut S) {
829 self.len().hash(state);
830 for elt in self.iter() {
836 impl<A> Index<uint, A> for RingBuf<A> {
838 fn index<'a>(&'a self, i: &uint) -> &'a A {
839 self.get(*i).expect("Out of bounds access")
843 impl<A> IndexMut<uint, A> for RingBuf<A> {
845 fn index_mut<'a>(&'a mut self, i: &uint) -> &'a mut A {
846 self.get_mut(*i).expect("Out of bounds access")
850 impl<A> FromIterator<A> for RingBuf<A> {
851 fn from_iter<T: Iterator<A>>(iterator: T) -> RingBuf<A> {
852 let (lower, _) = iterator.size_hint();
853 let mut deq = RingBuf::with_capacity(lower);
854 deq.extend(iterator);
859 impl<A> Extend<A> for RingBuf<A> {
860 fn extend<T: Iterator<A>>(&mut self, mut iterator: T) {
861 for elt in iterator {
867 impl<T: fmt::Show> fmt::Show for RingBuf<T> {
868 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
869 try!(write!(f, "["));
871 for (i, e) in self.iter().enumerate() {
872 if i != 0 { try!(write!(f, ", ")); }
873 try!(write!(f, "{}", *e));
883 use self::Taggypar::*;
896 let mut d = RingBuf::new();
897 assert_eq!(d.len(), 0u);
901 assert_eq!(d.len(), 3u);
903 assert_eq!(d.len(), 4u);
904 debug!("{}", d.front());
905 assert_eq!(*d.front().unwrap(), 42);
906 debug!("{}", d.back());
907 assert_eq!(*d.back().unwrap(), 137);
908 let mut i = d.pop_front();
910 assert_eq!(i, Some(42));
913 assert_eq!(i, Some(137));
916 assert_eq!(i, Some(137));
919 assert_eq!(i, Some(17));
920 assert_eq!(d.len(), 0u);
922 assert_eq!(d.len(), 1u);
924 assert_eq!(d.len(), 2u);
926 assert_eq!(d.len(), 3u);
928 assert_eq!(d.len(), 4u);
940 fn test_parameterized<T:Clone + PartialEq + Show>(a: T, b: T, c: T, d: T) {
941 let mut deq = RingBuf::new();
942 assert_eq!(deq.len(), 0);
943 deq.push_front(a.clone());
944 deq.push_front(b.clone());
945 deq.push_back(c.clone());
946 assert_eq!(deq.len(), 3);
947 deq.push_back(d.clone());
948 assert_eq!(deq.len(), 4);
949 assert_eq!((*deq.front().unwrap()).clone(), b.clone());
950 assert_eq!((*deq.back().unwrap()).clone(), d.clone());
951 assert_eq!(deq.pop_front().unwrap(), b.clone());
952 assert_eq!(deq.pop_back().unwrap(), d.clone());
953 assert_eq!(deq.pop_back().unwrap(), c.clone());
954 assert_eq!(deq.pop_back().unwrap(), a.clone());
955 assert_eq!(deq.len(), 0);
956 deq.push_back(c.clone());
957 assert_eq!(deq.len(), 1);
958 deq.push_front(b.clone());
959 assert_eq!(deq.len(), 2);
960 deq.push_back(d.clone());
961 assert_eq!(deq.len(), 3);
962 deq.push_front(a.clone());
963 assert_eq!(deq.len(), 4);
964 assert_eq!(deq[0].clone(), a.clone());
965 assert_eq!(deq[1].clone(), b.clone());
966 assert_eq!(deq[2].clone(), c.clone());
967 assert_eq!(deq[3].clone(), d.clone());
971 fn test_push_front_grow() {
972 let mut deq = RingBuf::new();
973 for i in range(0u, 66) {
976 assert_eq!(deq.len(), 66);
978 for i in range(0u, 66) {
979 assert_eq!(deq[i], 65 - i);
982 let mut deq = RingBuf::new();
983 for i in range(0u, 66) {
987 for i in range(0u, 66) {
988 assert_eq!(deq[i], i);
994 let mut deq = RingBuf::new();
995 for i in range(1u, 4) {
998 assert_eq!(deq[1], 2);
1003 fn test_index_out_of_bounds() {
1004 let mut deq = RingBuf::new();
1005 for i in range(1u, 4) {
1012 fn bench_new(b: &mut test::Bencher) {
1014 let ring: RingBuf<u64> = RingBuf::new();
1015 test::black_box(ring);
1020 fn bench_push_back_100(b: &mut test::Bencher) {
1021 let mut deq = RingBuf::with_capacity(101);
1023 for i in range(0i, 100) {
1032 fn bench_push_front_100(b: &mut test::Bencher) {
1033 let mut deq = RingBuf::with_capacity(101);
1035 for i in range(0i, 100) {
1044 fn bench_pop_back_100(b: &mut test::Bencher) {
1045 let mut deq: RingBuf<int> = RingBuf::with_capacity(101);
1050 while !deq.is_empty() {
1051 test::black_box(deq.pop_back());
1057 fn bench_pop_front_100(b: &mut test::Bencher) {
1058 let mut deq: RingBuf<int> = RingBuf::with_capacity(101);
1063 while !deq.is_empty() {
1064 test::black_box(deq.pop_front());
1070 fn bench_grow_1025(b: &mut test::Bencher) {
1072 let mut deq = RingBuf::new();
1073 for i in range(0i, 1025) {
1076 test::black_box(deq);
1081 fn bench_iter_1000(b: &mut test::Bencher) {
1082 let ring: RingBuf<int> = range(0i, 1000).collect();
1086 for &i in ring.iter() {
1089 test::black_box(sum);
1094 fn bench_mut_iter_1000(b: &mut test::Bencher) {
1095 let mut ring: RingBuf<int> = range(0i, 1000).collect();
1099 for i in ring.iter_mut() {
1102 test::black_box(sum);
1107 #[deriving(Clone, PartialEq, Show)]
1111 Three(int, int, int),
1114 #[deriving(Clone, PartialEq, Show)]
1118 Threepar(int, int, int),
1121 #[deriving(Clone, PartialEq, Show)]
1129 fn test_param_int() {
1130 test_parameterized::<int>(5, 72, 64, 175);
1134 fn test_param_taggy() {
1135 test_parameterized::<Taggy>(One(1), Two(1, 2), Three(1, 2, 3), Two(17, 42));
1139 fn test_param_taggypar() {
1140 test_parameterized::<Taggypar<int>>(Onepar::<int>(1),
1141 Twopar::<int>(1, 2),
1142 Threepar::<int>(1, 2, 3),
1143 Twopar::<int>(17, 42));
1147 fn test_param_reccy() {
1148 let reccy1 = RecCy { x: 1, y: 2, t: One(1) };
1149 let reccy2 = RecCy { x: 345, y: 2, t: Two(1, 2) };
1150 let reccy3 = RecCy { x: 1, y: 777, t: Three(1, 2, 3) };
1151 let reccy4 = RecCy { x: 19, y: 252, t: Two(17, 42) };
1152 test_parameterized::<RecCy>(reccy1, reccy2, reccy3, reccy4);
1156 fn test_with_capacity() {
1157 let mut d = RingBuf::with_capacity(0);
1159 assert_eq!(d.len(), 1);
1160 let mut d = RingBuf::with_capacity(50);
1162 assert_eq!(d.len(), 1);
1166 fn test_with_capacity_non_power_two() {
1167 let mut d3 = RingBuf::with_capacity(3);
1172 assert_eq!(d3.pop_front(), Some(1));
1174 assert_eq!(d3.front(), None);
1181 assert_eq!(d3.pop_front(), Some(3));
1183 // Pushing the lo past half way point to trigger
1184 // the 'B' scenario for growth
1191 // There used to be a bug here about how the
1192 // RingBuf made growth assumptions about the
1193 // underlying Vec which didn't hold and lead
1195 // (Vec grows to next power of two)
1196 //good- [9, 12, 15, X, X, X, X, |6]
1197 //bug- [15, 12, X, X, X, |6, X, X]
1198 assert_eq!(d3.pop_front(), Some(6));
1200 // Which leads us to the following state which
1201 // would be a failure case.
1202 //bug- [15, 12, X, X, X, X, |X, X]
1203 assert_eq!(d3.front(), Some(&9));
1207 fn test_reserve_exact() {
1208 let mut d = RingBuf::new();
1210 d.reserve_exact(50);
1211 assert!(d.capacity() >= 51);
1212 let mut d = RingBuf::new();
1214 d.reserve_exact(50);
1215 assert!(d.capacity() >= 51);
1220 let mut d = RingBuf::new();
1223 assert!(d.capacity() >= 51);
1224 let mut d = RingBuf::new();
1227 assert!(d.capacity() >= 51);
1232 let mut d: RingBuf<int> = range(0i, 5).collect();
1235 assert_eq!(d.iter().map(|&x|x).collect::<Vec<int>>(), vec!(4, 2, 3, 1));
1240 let mut d = RingBuf::new();
1241 assert_eq!(d.iter().next(), None);
1242 assert_eq!(d.iter().size_hint(), (0, Some(0)));
1244 for i in range(0i, 5) {
1248 let b: &[_] = &[&0,&1,&2,&3,&4];
1249 assert_eq!(d.iter().collect::<Vec<&int>>().as_slice(), b);
1252 for i in range(6i, 9) {
1256 let b: &[_] = &[&8,&7,&6,&0,&1,&2,&3,&4];
1257 assert_eq!(d.iter().collect::<Vec<&int>>().as_slice(), b);
1260 let mut it = d.iter();
1261 let mut len = d.len();
1265 _ => { len -= 1; assert_eq!(it.size_hint(), (len, Some(len))) }
1271 fn test_rev_iter() {
1272 let mut d = RingBuf::new();
1273 assert_eq!(d.iter().rev().next(), None);
1275 for i in range(0i, 5) {
1279 let b: &[_] = &[&4,&3,&2,&1,&0];
1280 assert_eq!(d.iter().rev().collect::<Vec<&int>>().as_slice(), b);
1283 for i in range(6i, 9) {
1286 let b: &[_] = &[&4,&3,&2,&1,&0,&6,&7,&8];
1287 assert_eq!(d.iter().rev().collect::<Vec<&int>>().as_slice(), b);
1291 fn test_mut_rev_iter_wrap() {
1292 let mut d = RingBuf::with_capacity(3);
1293 assert!(d.iter_mut().rev().next().is_none());
1298 assert_eq!(d.pop_front(), Some(1));
1301 assert_eq!(d.iter_mut().rev().map(|x| *x).collect::<Vec<int>>(),
1306 fn test_mut_iter() {
1307 let mut d = RingBuf::new();
1308 assert!(d.iter_mut().next().is_none());
1310 for i in range(0u, 3) {
1314 for (i, elt) in d.iter_mut().enumerate() {
1315 assert_eq!(*elt, 2 - i);
1320 let mut it = d.iter_mut();
1321 assert_eq!(*it.next().unwrap(), 0);
1322 assert_eq!(*it.next().unwrap(), 1);
1323 assert_eq!(*it.next().unwrap(), 2);
1324 assert!(it.next().is_none());
1329 fn test_mut_rev_iter() {
1330 let mut d = RingBuf::new();
1331 assert!(d.iter_mut().rev().next().is_none());
1333 for i in range(0u, 3) {
1337 for (i, elt) in d.iter_mut().rev().enumerate() {
1338 assert_eq!(*elt, i);
1343 let mut it = d.iter_mut().rev();
1344 assert_eq!(*it.next().unwrap(), 0);
1345 assert_eq!(*it.next().unwrap(), 1);
1346 assert_eq!(*it.next().unwrap(), 2);
1347 assert!(it.next().is_none());
1352 fn test_into_iter() {
1356 let d: RingBuf<int> = RingBuf::new();
1357 let mut iter = d.into_iter();
1359 assert_eq!(iter.size_hint(), (0, Some(0)));
1360 assert_eq!(iter.next(), None);
1361 assert_eq!(iter.size_hint(), (0, Some(0)));
1366 let mut d = RingBuf::new();
1367 for i in range(0i, 5) {
1371 let b = vec![0,1,2,3,4];
1372 assert_eq!(d.into_iter().collect::<Vec<int>>(), b);
1377 let mut d = RingBuf::new();
1378 for i in range(0i, 5) {
1381 for i in range(6, 9) {
1385 let b = vec![8,7,6,0,1,2,3,4];
1386 assert_eq!(d.into_iter().collect::<Vec<int>>(), b);
1391 let mut d = RingBuf::new();
1392 for i in range(0i, 5) {
1395 for i in range(6, 9) {
1399 let mut it = d.into_iter();
1400 assert_eq!(it.size_hint(), (8, Some(8)));
1401 assert_eq!(it.next(), Some(8));
1402 assert_eq!(it.size_hint(), (7, Some(7)));
1403 assert_eq!(it.next_back(), Some(4));
1404 assert_eq!(it.size_hint(), (6, Some(6)));
1405 assert_eq!(it.next(), Some(7));
1406 assert_eq!(it.size_hint(), (5, Some(5)));
1411 fn test_from_iter() {
1413 let v = vec!(1i,2,3,4,5,6,7);
1414 let deq: RingBuf<int> = v.iter().map(|&x| x).collect();
1415 let u: Vec<int> = deq.iter().map(|&x| x).collect();
1418 let seq = iter::count(0u, 2).take(256);
1419 let deq: RingBuf<uint> = seq.collect();
1420 for (i, &x) in deq.iter().enumerate() {
1423 assert_eq!(deq.len(), 256);
1428 let mut d = RingBuf::new();
1433 assert_eq!(d.len(), 4u);
1434 let mut e = d.clone();
1435 assert_eq!(e.len(), 4u);
1436 while !d.is_empty() {
1437 assert_eq!(d.pop_back(), e.pop_back());
1439 assert_eq!(d.len(), 0u);
1440 assert_eq!(e.len(), 0u);
1445 let mut d = RingBuf::new();
1446 assert!(d == RingBuf::with_capacity(0));
1451 let mut e = RingBuf::with_capacity(0);
1461 assert!(e == RingBuf::new());
1466 let mut x = RingBuf::new();
1467 let mut y = RingBuf::new();
1479 assert!(hash::hash(&x) == hash::hash(&y));
1484 let x = RingBuf::new();
1485 let mut y = RingBuf::new();
1497 let ringbuf: RingBuf<int> = range(0i, 10).collect();
1498 assert!(format!("{}", ringbuf).as_slice() == "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]");
1500 let ringbuf: RingBuf<&str> = vec!["just", "one", "test", "more"].iter()
1503 assert!(format!("{}", ringbuf).as_slice() == "[just, one, test, more]");
1508 static mut drops: uint = 0;
1510 impl Drop for Elem {
1511 fn drop(&mut self) {
1512 unsafe { drops += 1; }
1516 let mut ring = RingBuf::new();
1517 ring.push_back(Elem);
1518 ring.push_front(Elem);
1519 ring.push_back(Elem);
1520 ring.push_front(Elem);
1523 assert_eq!(unsafe {drops}, 4);
1527 fn test_drop_with_pop() {
1528 static mut drops: uint = 0;
1530 impl Drop for Elem {
1531 fn drop(&mut self) {
1532 unsafe { drops += 1; }
1536 let mut ring = RingBuf::new();
1537 ring.push_back(Elem);
1538 ring.push_front(Elem);
1539 ring.push_back(Elem);
1540 ring.push_front(Elem);
1542 drop(ring.pop_back());
1543 drop(ring.pop_front());
1544 assert_eq!(unsafe {drops}, 2);
1547 assert_eq!(unsafe {drops}, 4);
1551 fn test_drop_clear() {
1552 static mut drops: uint = 0;
1554 impl Drop for Elem {
1555 fn drop(&mut self) {
1556 unsafe { drops += 1; }
1560 let mut ring = RingBuf::new();
1561 ring.push_back(Elem);
1562 ring.push_front(Elem);
1563 ring.push_back(Elem);
1564 ring.push_front(Elem);
1566 assert_eq!(unsafe {drops}, 4);
1569 assert_eq!(unsafe {drops}, 4);
1573 fn test_reserve_grow() {
1574 // test growth path A
1575 // [T o o H] -> [T o o H . . . . ]
1576 let mut ring = RingBuf::with_capacity(4);
1577 for i in range(0i, 3) {
1581 for i in range(0i, 3) {
1582 assert_eq!(ring.pop_front(), Some(i));
1585 // test growth path B
1586 // [H T o o] -> [. T o o H . . . ]
1587 let mut ring = RingBuf::with_capacity(4);
1588 for i in range(0i, 1) {
1590 assert_eq!(ring.pop_front(), Some(i));
1592 for i in range(0i, 3) {
1596 for i in range(0i, 3) {
1597 assert_eq!(ring.pop_front(), Some(i));
1600 // test growth path C
1601 // [o o H T] -> [o o H . . . . T ]
1602 let mut ring = RingBuf::with_capacity(4);
1603 for i in range(0i, 3) {
1605 assert_eq!(ring.pop_front(), Some(i));
1607 for i in range(0i, 3) {
1611 for i in range(0i, 3) {
1612 assert_eq!(ring.pop_front(), Some(i));
1618 let mut ring = RingBuf::new();
1620 assert_eq!(ring.get(0), Some(&0));
1621 assert_eq!(ring.get(1), None);
1624 assert_eq!(ring.get(0), Some(&0));
1625 assert_eq!(ring.get(1), Some(&1));
1626 assert_eq!(ring.get(2), None);
1629 assert_eq!(ring.get(0), Some(&0));
1630 assert_eq!(ring.get(1), Some(&1));
1631 assert_eq!(ring.get(2), Some(&2));
1632 assert_eq!(ring.get(3), None);
1634 assert_eq!(ring.pop_front(), Some(0));
1635 assert_eq!(ring.get(0), Some(&1));
1636 assert_eq!(ring.get(1), Some(&2));
1637 assert_eq!(ring.get(2), None);
1639 assert_eq!(ring.pop_front(), Some(1));
1640 assert_eq!(ring.get(0), Some(&2));
1641 assert_eq!(ring.get(1), None);
1643 assert_eq!(ring.pop_front(), Some(2));
1644 assert_eq!(ring.get(0), None);
1645 assert_eq!(ring.get(1), None);
1650 let mut ring = RingBuf::new();
1651 for i in range(0i, 3) {
1655 match ring.get_mut(1) {
1660 assert_eq!(ring.get_mut(0), Some(&mut 0));
1661 assert_eq!(ring.get_mut(1), Some(&mut -1));
1662 assert_eq!(ring.get_mut(2), Some(&mut 2));
1663 assert_eq!(ring.get_mut(3), None);
1665 assert_eq!(ring.pop_front(), Some(0));
1666 assert_eq!(ring.get_mut(0), Some(&mut -1));
1667 assert_eq!(ring.get_mut(1), Some(&mut 2));
1668 assert_eq!(ring.get_mut(2), None);