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.
17 use core::default::Default;
20 use core::raw::Slice as RawSlice;
22 use core::kinds::marker;
24 use core::num::{Int, UnsignedInt};
26 use std::hash::{Writer, Hash};
31 static INITIAL_CAPACITY: uint = 8u; // 2^3
32 static MINIMUM_CAPACITY: uint = 2u;
34 // FIXME(conventions): implement shrink_to_fit. Awkward with the current design, but it should
35 // be scrapped anyway. Defer to rewrite?
37 /// `RingBuf` is a circular buffer.
38 pub struct RingBuf<T> {
39 // tail and head are pointers into the buffer. Tail always points
40 // to the first element that could be read, Head always points
41 // to where data should be written.
42 // If tail == head the buffer is empty. The length of the ringbuf
43 // is defined as the distance between the two.
51 impl<T: Clone> Clone for RingBuf<T> {
52 fn clone(&self) -> RingBuf<T> {
53 self.iter().map(|t| t.clone()).collect()
58 impl<T> Drop for RingBuf<T> {
62 if mem::size_of::<T>() != 0 {
63 heap::deallocate(self.ptr as *mut u8,
64 self.cap * mem::size_of::<T>(),
65 mem::min_align_of::<T>())
71 impl<T> Default for RingBuf<T> {
73 fn default() -> RingBuf<T> { RingBuf::new() }
77 /// Turn ptr into a slice
79 unsafe fn buffer_as_slice(&self) -> &[T] {
80 mem::transmute(RawSlice { data: self.ptr as *const T, len: self.cap })
83 /// Moves an element out of the buffer
85 unsafe fn buffer_read(&mut self, off: uint) -> T {
86 ptr::read(self.ptr.offset(off as int) as *const T)
89 /// Writes an element into the buffer, moving it.
91 unsafe fn buffer_write(&mut self, off: uint, t: T) {
92 ptr::write(self.ptr.offset(off as int), t);
95 /// Returns true iff the buffer is at capacity
97 fn is_full(&self) -> bool { self.cap - self.len() == 1 }
99 /// Returns the index in the underlying buffer for a given logical element index.
101 fn wrap_index(&self, idx: uint) -> uint { wrap_index(idx, self.cap) }
105 /// Creates an empty `RingBuf`.
106 #[unstable = "matches collection reform specification, waiting for dust to settle"]
107 pub fn new() -> RingBuf<T> {
108 RingBuf::with_capacity(INITIAL_CAPACITY)
111 /// Creates an empty `RingBuf` with space for at least `n` elements.
112 #[unstable = "matches collection reform specification, waiting for dust to settle"]
113 pub fn with_capacity(n: uint) -> RingBuf<T> {
114 // +1 since the ringbuffer always leaves one space empty
115 let cap = cmp::max(n + 1, MINIMUM_CAPACITY).next_power_of_two();
116 let size = cap.checked_mul(mem::size_of::<T>())
117 .expect("capacity overflow");
119 let ptr = if mem::size_of::<T>() != 0 {
121 let ptr = heap::allocate(size, mem::min_align_of::<T>()) as *mut T;;
122 if ptr.is_null() { ::alloc::oom() }
126 heap::EMPTY as *mut T
137 /// Retrieves an element in the `RingBuf` by index.
142 /// use std::collections::RingBuf;
144 /// let mut buf = RingBuf::new();
145 /// buf.push_back(3i);
146 /// buf.push_back(4);
147 /// buf.push_back(5);
148 /// assert_eq!(buf.get(1).unwrap(), &4);
150 #[unstable = "matches collection reform specification, waiting for dust to settle"]
151 pub fn get(&self, i: uint) -> Option<&T> {
153 let idx = self.wrap_index(self.tail + i);
154 unsafe { Some(&*self.ptr.offset(idx as int)) }
160 /// Retrieves an element in the `RingBuf` mutably by index.
165 /// use std::collections::RingBuf;
167 /// let mut buf = RingBuf::new();
168 /// buf.push_back(3i);
169 /// buf.push_back(4);
170 /// buf.push_back(5);
171 /// match buf.get_mut(1) {
178 /// assert_eq!(buf[1], 7);
180 #[unstable = "matches collection reform specification, waiting for dust to settle"]
181 pub fn get_mut(&mut self, i: uint) -> Option<&mut T> {
183 let idx = self.wrap_index(self.tail + i);
184 unsafe { Some(&mut *self.ptr.offset(idx as int)) }
190 /// Swaps elements at indices `i` and `j`.
192 /// `i` and `j` may be equal.
194 /// Fails if there is no element with either index.
199 /// use std::collections::RingBuf;
201 /// let mut buf = RingBuf::new();
202 /// buf.push_back(3i);
203 /// buf.push_back(4);
204 /// buf.push_back(5);
206 /// assert_eq!(buf[0], 5);
207 /// assert_eq!(buf[2], 3);
209 pub fn swap(&mut self, i: uint, j: uint) {
210 assert!(i < self.len());
211 assert!(j < self.len());
212 let ri = self.wrap_index(self.tail + i);
213 let rj = self.wrap_index(self.tail + j);
215 ptr::swap(self.ptr.offset(ri as int), self.ptr.offset(rj as int))
219 /// Returns the number of elements the `RingBuf` can hold without
225 /// use std::collections::RingBuf;
227 /// let buf: RingBuf<int> = RingBuf::with_capacity(10);
228 /// assert!(buf.capacity() >= 10);
231 #[unstable = "matches collection reform specification, waiting for dust to settle"]
232 pub fn capacity(&self) -> uint { self.cap - 1 }
234 /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the
235 /// given `RingBuf`. Does nothing if the capacity is already sufficient.
237 /// Note that the allocator may give the collection more space than it requests. Therefore
238 /// capacity can not be relied upon to be precisely minimal. Prefer `reserve` if future
239 /// insertions are expected.
243 /// Panics if the new capacity overflows `uint`.
248 /// use std::collections::RingBuf;
250 /// let mut buf: RingBuf<int> = vec![1].into_iter().collect();
251 /// buf.reserve_exact(10);
252 /// assert!(buf.capacity() >= 11);
254 #[unstable = "matches collection reform specification, waiting for dust to settle"]
255 pub fn reserve_exact(&mut self, additional: uint) {
256 self.reserve(additional);
259 /// Reserves capacity for at least `additional` more elements to be inserted in the given
260 /// `Ringbuf`. The collection may reserve more space to avoid frequent reallocations.
264 /// Panics if the new capacity overflows `uint`.
269 /// use std::collections::RingBuf;
271 /// let mut buf: RingBuf<int> = vec![1].into_iter().collect();
273 /// assert!(buf.capacity() >= 11);
275 #[unstable = "matches collection reform specification, waiting for dust to settle"]
276 pub fn reserve(&mut self, additional: uint) {
277 let new_len = self.len() + additional;
278 assert!(new_len + 1 > self.len(), "capacity overflow");
279 if new_len > self.capacity() {
280 let count = (new_len + 1).next_power_of_two();
281 assert!(count >= new_len + 1);
283 if mem::size_of::<T>() != 0 {
284 let old = self.cap * mem::size_of::<T>();
285 let new = count.checked_mul(mem::size_of::<T>())
286 .expect("capacity overflow");
288 self.ptr = heap::reallocate(self.ptr as *mut u8,
291 mem::min_align_of::<T>()) as *mut T;
292 if self.ptr.is_null() { ::alloc::oom() }
296 // Move the shortest contiguous section of the ring buffer
298 // [o o o o o o o . ]
300 // A [o o o o o o o . . . . . . . . . ]
302 // [o o . o o o o o ]
304 // B [. . . o o o o o o o . . . . . . ]
306 // [o o o o o . o o ]
308 // C [o o o o o . . . . . . . . . o o ]
310 let oldcap = self.cap;
313 if self.tail <= self.head { // A
315 } else if self.head < oldcap - self.tail { // B
317 ptr::copy_nonoverlapping_memory(
318 self.ptr.offset(oldcap as int),
319 self.ptr as *const T,
324 debug_assert!(self.head > self.tail);
327 ptr::copy_nonoverlapping_memory(
328 self.ptr.offset((count - (oldcap - self.tail)) as int),
329 self.ptr.offset(self.tail as int) as *const T,
333 self.tail = count - (oldcap - self.tail);
334 debug_assert!(self.head < self.tail);
336 debug_assert!(self.head < self.cap);
337 debug_assert!(self.tail < self.cap);
338 debug_assert!(self.cap.count_ones() == 1);
342 /// Returns a front-to-back iterator.
347 /// use std::collections::RingBuf;
349 /// let mut buf = RingBuf::new();
350 /// buf.push_back(5i);
351 /// buf.push_back(3);
352 /// buf.push_back(4);
353 /// let b: &[_] = &[&5, &3, &4];
354 /// assert_eq!(buf.iter().collect::<Vec<&int>>().as_slice(), b);
356 #[unstable = "matches collection reform specification, waiting for dust to settle"]
357 pub fn iter(&self) -> Items<T> {
361 ring: unsafe { self.buffer_as_slice() }
365 /// Returns a front-to-back iterator which returns mutable references.
370 /// use std::collections::RingBuf;
372 /// let mut buf = RingBuf::new();
373 /// buf.push_back(5i);
374 /// buf.push_back(3);
375 /// buf.push_back(4);
376 /// for num in buf.iter_mut() {
379 /// let b: &[_] = &[&mut 3, &mut 1, &mut 2];
380 /// assert_eq!(buf.iter_mut().collect::<Vec<&mut int>>()[], b);
382 #[unstable = "matches collection reform specification, waiting for dust to settle"]
383 pub fn iter_mut<'a>(&'a mut self) -> MutItems<'a, T> {
389 marker: marker::ContravariantLifetime::<'a>,
390 marker2: marker::NoCopy
394 /// Consumes the list into an iterator yielding elements by value.
395 #[unstable = "matches collection reform specification, waiting for dust to settle"]
396 pub fn into_iter(self) -> MoveItems<T> {
402 /// Returns the number of elements in the `RingBuf`.
407 /// use std::collections::RingBuf;
409 /// let mut v = RingBuf::new();
410 /// assert_eq!(v.len(), 0);
412 /// assert_eq!(v.len(), 1);
414 #[unstable = "matches collection reform specification, waiting for dust to settle"]
415 pub fn len(&self) -> uint { count(self.tail, self.head, self.cap) }
417 /// Returns true if the buffer contains no elements
422 /// use std::collections::RingBuf;
424 /// let mut v = RingBuf::new();
425 /// assert!(v.is_empty());
426 /// v.push_front(1i);
427 /// assert!(!v.is_empty());
429 #[unstable = "matches collection reform specification, waiting for dust to settle"]
430 pub fn is_empty(&self) -> bool { self.len() == 0 }
432 /// Clears the buffer, removing all values.
437 /// use std::collections::RingBuf;
439 /// let mut v = RingBuf::new();
442 /// assert!(v.is_empty());
444 #[unstable = "matches collection reform specification, waiting for dust to settle"]
445 pub fn clear(&mut self) {
446 while self.pop_front().is_some() {}
451 /// Provides a reference to the front element, or `None` if the sequence is
457 /// use std::collections::RingBuf;
459 /// let mut d = RingBuf::new();
460 /// assert_eq!(d.front(), None);
464 /// assert_eq!(d.front(), Some(&1i));
466 #[unstable = "matches collection reform specification, waiting for dust to settle"]
467 pub fn front(&self) -> Option<&T> {
468 if !self.is_empty() { Some(&self[0]) } else { None }
471 /// Provides a mutable reference to the front element, or `None` if the
472 /// sequence is empty.
477 /// use std::collections::RingBuf;
479 /// let mut d = RingBuf::new();
480 /// assert_eq!(d.front_mut(), None);
484 /// match d.front_mut() {
485 /// Some(x) => *x = 9i,
488 /// assert_eq!(d.front(), Some(&9i));
490 #[unstable = "matches collection reform specification, waiting for dust to settle"]
491 pub fn front_mut(&mut self) -> Option<&mut T> {
492 if !self.is_empty() { Some(&mut self[0]) } else { None }
495 /// Provides a reference to the back element, or `None` if the sequence is
501 /// use std::collections::RingBuf;
503 /// let mut d = RingBuf::new();
504 /// assert_eq!(d.back(), None);
508 /// assert_eq!(d.back(), Some(&2i));
510 #[unstable = "matches collection reform specification, waiting for dust to settle"]
511 pub fn back(&self) -> Option<&T> {
512 if !self.is_empty() { Some(&self[self.len() - 1]) } else { None }
515 /// Provides a mutable reference to the back element, or `None` if the
516 /// sequence is empty.
521 /// use std::collections::RingBuf;
523 /// let mut d = RingBuf::new();
524 /// assert_eq!(d.back(), None);
528 /// match d.back_mut() {
529 /// Some(x) => *x = 9i,
532 /// assert_eq!(d.back(), Some(&9i));
534 #[unstable = "matches collection reform specification, waiting for dust to settle"]
535 pub fn back_mut(&mut self) -> Option<&mut T> {
536 let len = self.len();
537 if !self.is_empty() { Some(&mut self[len - 1]) } else { None }
540 /// Removes the first element and returns it, or `None` if the sequence is
546 /// use std::collections::RingBuf;
548 /// let mut d = RingBuf::new();
552 /// assert_eq!(d.pop_front(), Some(1i));
553 /// assert_eq!(d.pop_front(), Some(2i));
554 /// assert_eq!(d.pop_front(), None);
556 #[unstable = "matches collection reform specification, waiting for dust to settle"]
557 pub fn pop_front(&mut self) -> Option<T> {
561 let tail = self.tail;
562 self.tail = self.wrap_index(self.tail + 1);
563 unsafe { Some(self.buffer_read(tail)) }
567 /// Inserts an element first in the sequence.
572 /// use std::collections::RingBuf;
574 /// let mut d = RingBuf::new();
575 /// d.push_front(1i);
576 /// d.push_front(2i);
577 /// assert_eq!(d.front(), Some(&2i));
579 #[unstable = "matches collection reform specification, waiting for dust to settle"]
580 pub fn push_front(&mut self, t: T) {
583 debug_assert!(!self.is_full());
586 self.tail = self.wrap_index(self.tail - 1);
587 let tail = self.tail;
588 unsafe { self.buffer_write(tail, t); }
591 /// Deprecated: Renamed to `push_back`.
592 #[deprecated = "Renamed to `push_back`"]
593 pub fn push(&mut self, t: T) {
597 /// Appends an element to the back of a buffer
602 /// use std::collections::RingBuf;
604 /// let mut buf = RingBuf::new();
605 /// buf.push_back(1i);
606 /// buf.push_back(3);
607 /// assert_eq!(3, *buf.back().unwrap());
609 #[unstable = "matches collection reform specification, waiting for dust to settle"]
610 pub fn push_back(&mut self, t: T) {
613 debug_assert!(!self.is_full());
616 let head = self.head;
617 self.head = self.wrap_index(self.head + 1);
618 unsafe { self.buffer_write(head, t) }
621 /// Deprecated: Renamed to `pop_back`.
622 #[deprecated = "Renamed to `pop_back`"]
623 pub fn pop(&mut self) -> Option<T> {
627 /// Removes the last element from a buffer and returns it, or `None` if
633 /// use std::collections::RingBuf;
635 /// let mut buf = RingBuf::new();
636 /// assert_eq!(buf.pop_back(), None);
637 /// buf.push_back(1i);
638 /// buf.push_back(3);
639 /// assert_eq!(buf.pop_back(), Some(3));
641 #[unstable = "matches collection reform specification, waiting for dust to settle"]
642 pub fn pop_back(&mut self) -> Option<T> {
646 self.head = self.wrap_index(self.head - 1);
647 let head = self.head;
648 unsafe { Some(self.buffer_read(head)) }
653 /// Returns the index in the underlying buffer for a given logical element index.
655 fn wrap_index(index: uint, size: uint) -> uint {
656 // size is always a power of 2
660 /// Calculate the number of elements left to be read in the buffer
662 fn count(tail: uint, head: uint, size: uint) -> uint {
663 // size is always a power of 2
664 (head - tail) & (size - 1)
667 /// `RingBuf` iterator.
668 pub struct Items<'a, T:'a> {
674 impl<'a, T> Iterator<&'a T> for Items<'a, T> {
676 fn next(&mut self) -> Option<&'a T> {
677 if self.tail == self.head {
680 let tail = self.tail;
681 self.tail = wrap_index(self.tail + 1, self.ring.len());
682 unsafe { Some(self.ring.unsafe_get(tail)) }
686 fn size_hint(&self) -> (uint, Option<uint>) {
687 let len = count(self.tail, self.head, self.ring.len());
692 impl<'a, T> DoubleEndedIterator<&'a T> for Items<'a, T> {
694 fn next_back(&mut self) -> Option<&'a T> {
695 if self.tail == self.head {
698 self.head = wrap_index(self.head - 1, self.ring.len());
699 unsafe { Some(self.ring.unsafe_get(self.head)) }
703 impl<'a, T> ExactSizeIterator<&'a T> for Items<'a, T> {}
705 impl<'a, T> RandomAccessIterator<&'a T> for Items<'a, T> {
707 fn indexable(&self) -> uint {
708 let (len, _) = self.size_hint();
713 fn idx(&mut self, j: uint) -> Option<&'a T> {
714 if j >= self.indexable() {
717 let idx = wrap_index(self.tail + j, self.ring.len());
718 unsafe { Some(self.ring.unsafe_get(idx)) }
723 // FIXME This was implemented differently from Items because of a problem
724 // with returning the mutable reference. I couldn't find a way to
725 // make the lifetime checker happy so, but there should be a way.
726 /// `RingBuf` mutable iterator.
727 pub struct MutItems<'a, T:'a> {
732 marker: marker::ContravariantLifetime<'a>,
733 marker2: marker::NoCopy
736 impl<'a, T> Iterator<&'a mut T> for MutItems<'a, T> {
738 fn next(&mut self) -> Option<&'a mut T> {
739 if self.tail == self.head {
742 let tail = self.tail;
743 self.tail = wrap_index(self.tail + 1, self.cap);
746 Some(&mut *self.ptr.offset(tail as int))
751 fn size_hint(&self) -> (uint, Option<uint>) {
752 let len = count(self.tail, self.head, self.cap);
757 impl<'a, T> DoubleEndedIterator<&'a mut T> for MutItems<'a, T> {
759 fn next_back(&mut self) -> Option<&'a mut T> {
760 if self.tail == self.head {
763 self.head = wrap_index(self.head - 1, self.cap);
766 Some(&mut *self.ptr.offset(self.head as int))
771 impl<'a, T> ExactSizeIterator<&'a mut T> for MutItems<'a, T> {}
773 // A by-value RingBuf iterator
774 pub struct MoveItems<T> {
778 impl<T> Iterator<T> for MoveItems<T> {
780 fn next(&mut self) -> Option<T> {
781 self.inner.pop_front()
785 fn size_hint(&self) -> (uint, Option<uint>) {
786 let len = self.inner.len();
791 impl<T> DoubleEndedIterator<T> for MoveItems<T> {
793 fn next_back(&mut self) -> Option<T> {
794 self.inner.pop_back()
799 impl<T> ExactSizeIterator<T> for MoveItems<T> {}
801 impl<A: PartialEq> PartialEq for RingBuf<A> {
802 fn eq(&self, other: &RingBuf<A>) -> bool {
803 self.len() == other.len() &&
804 self.iter().zip(other.iter()).all(|(a, b)| a.eq(b))
806 fn ne(&self, other: &RingBuf<A>) -> bool {
811 impl<A: Eq> Eq for RingBuf<A> {}
813 impl<A: PartialOrd> PartialOrd for RingBuf<A> {
814 fn partial_cmp(&self, other: &RingBuf<A>) -> Option<Ordering> {
815 iter::order::partial_cmp(self.iter(), other.iter())
819 impl<A: Ord> Ord for RingBuf<A> {
821 fn cmp(&self, other: &RingBuf<A>) -> Ordering {
822 iter::order::cmp(self.iter(), other.iter())
826 impl<S: Writer, A: Hash<S>> Hash<S> for RingBuf<A> {
827 fn hash(&self, state: &mut S) {
828 self.len().hash(state);
829 for elt in self.iter() {
835 impl<A> Index<uint, A> for RingBuf<A> {
837 fn index<'a>(&'a self, i: &uint) -> &'a A {
838 self.get(*i).expect("Out of bounds access")
842 impl<A> IndexMut<uint, A> for RingBuf<A> {
844 fn index_mut<'a>(&'a mut self, i: &uint) -> &'a mut A {
845 self.get_mut(*i).expect("Out of bounds access")
849 impl<A> FromIterator<A> for RingBuf<A> {
850 fn from_iter<T: Iterator<A>>(iterator: T) -> RingBuf<A> {
851 let (lower, _) = iterator.size_hint();
852 let mut deq = RingBuf::with_capacity(lower);
853 deq.extend(iterator);
858 impl<A> Extend<A> for RingBuf<A> {
859 fn extend<T: Iterator<A>>(&mut self, mut iterator: T) {
860 for elt in iterator {
866 impl<T: fmt::Show> fmt::Show for RingBuf<T> {
867 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
868 try!(write!(f, "["));
870 for (i, e) in self.iter().enumerate() {
871 if i != 0 { try!(write!(f, ", ")); }
872 try!(write!(f, "{}", *e));
882 use self::Taggypar::*;
895 let mut d = RingBuf::new();
896 assert_eq!(d.len(), 0u);
900 assert_eq!(d.len(), 3u);
902 assert_eq!(d.len(), 4u);
903 debug!("{}", d.front());
904 assert_eq!(*d.front().unwrap(), 42);
905 debug!("{}", d.back());
906 assert_eq!(*d.back().unwrap(), 137);
907 let mut i = d.pop_front();
909 assert_eq!(i, Some(42));
912 assert_eq!(i, Some(137));
915 assert_eq!(i, Some(137));
918 assert_eq!(i, Some(17));
919 assert_eq!(d.len(), 0u);
921 assert_eq!(d.len(), 1u);
923 assert_eq!(d.len(), 2u);
925 assert_eq!(d.len(), 3u);
927 assert_eq!(d.len(), 4u);
939 fn test_parameterized<T:Clone + PartialEq + Show>(a: T, b: T, c: T, d: T) {
940 let mut deq = RingBuf::new();
941 assert_eq!(deq.len(), 0);
942 deq.push_front(a.clone());
943 deq.push_front(b.clone());
944 deq.push_back(c.clone());
945 assert_eq!(deq.len(), 3);
946 deq.push_back(d.clone());
947 assert_eq!(deq.len(), 4);
948 assert_eq!((*deq.front().unwrap()).clone(), b.clone());
949 assert_eq!((*deq.back().unwrap()).clone(), d.clone());
950 assert_eq!(deq.pop_front().unwrap(), b.clone());
951 assert_eq!(deq.pop_back().unwrap(), d.clone());
952 assert_eq!(deq.pop_back().unwrap(), c.clone());
953 assert_eq!(deq.pop_back().unwrap(), a.clone());
954 assert_eq!(deq.len(), 0);
955 deq.push_back(c.clone());
956 assert_eq!(deq.len(), 1);
957 deq.push_front(b.clone());
958 assert_eq!(deq.len(), 2);
959 deq.push_back(d.clone());
960 assert_eq!(deq.len(), 3);
961 deq.push_front(a.clone());
962 assert_eq!(deq.len(), 4);
963 assert_eq!(deq[0].clone(), a.clone());
964 assert_eq!(deq[1].clone(), b.clone());
965 assert_eq!(deq[2].clone(), c.clone());
966 assert_eq!(deq[3].clone(), d.clone());
970 fn test_push_front_grow() {
971 let mut deq = RingBuf::new();
972 for i in range(0u, 66) {
975 assert_eq!(deq.len(), 66);
977 for i in range(0u, 66) {
978 assert_eq!(deq[i], 65 - i);
981 let mut deq = RingBuf::new();
982 for i in range(0u, 66) {
986 for i in range(0u, 66) {
987 assert_eq!(deq[i], i);
993 let mut deq = RingBuf::new();
994 for i in range(1u, 4) {
997 assert_eq!(deq[1], 2);
1002 fn test_index_out_of_bounds() {
1003 let mut deq = RingBuf::new();
1004 for i in range(1u, 4) {
1011 fn bench_new(b: &mut test::Bencher) {
1013 let ring: RingBuf<u64> = RingBuf::new();
1014 test::black_box(ring);
1019 fn bench_push_back_100(b: &mut test::Bencher) {
1020 let mut deq = RingBuf::with_capacity(101);
1022 for i in range(0i, 100) {
1031 fn bench_push_front_100(b: &mut test::Bencher) {
1032 let mut deq = RingBuf::with_capacity(101);
1034 for i in range(0i, 100) {
1043 fn bench_pop_back_100(b: &mut test::Bencher) {
1044 let mut deq: RingBuf<int> = RingBuf::with_capacity(101);
1049 while !deq.is_empty() {
1050 test::black_box(deq.pop_back());
1056 fn bench_pop_front_100(b: &mut test::Bencher) {
1057 let mut deq: RingBuf<int> = RingBuf::with_capacity(101);
1062 while !deq.is_empty() {
1063 test::black_box(deq.pop_front());
1069 fn bench_grow_1025(b: &mut test::Bencher) {
1071 let mut deq = RingBuf::new();
1072 for i in range(0i, 1025) {
1075 test::black_box(deq);
1080 fn bench_iter_1000(b: &mut test::Bencher) {
1081 let ring: RingBuf<int> = range(0i, 1000).collect();
1085 for &i in ring.iter() {
1088 test::black_box(sum);
1093 fn bench_mut_iter_1000(b: &mut test::Bencher) {
1094 let mut ring: RingBuf<int> = range(0i, 1000).collect();
1098 for i in ring.iter_mut() {
1101 test::black_box(sum);
1106 #[deriving(Clone, PartialEq, Show)]
1110 Three(int, int, int),
1113 #[deriving(Clone, PartialEq, Show)]
1117 Threepar(int, int, int),
1120 #[deriving(Clone, PartialEq, Show)]
1128 fn test_param_int() {
1129 test_parameterized::<int>(5, 72, 64, 175);
1133 fn test_param_taggy() {
1134 test_parameterized::<Taggy>(One(1), Two(1, 2), Three(1, 2, 3), Two(17, 42));
1138 fn test_param_taggypar() {
1139 test_parameterized::<Taggypar<int>>(Onepar::<int>(1),
1140 Twopar::<int>(1, 2),
1141 Threepar::<int>(1, 2, 3),
1142 Twopar::<int>(17, 42));
1146 fn test_param_reccy() {
1147 let reccy1 = RecCy { x: 1, y: 2, t: One(1) };
1148 let reccy2 = RecCy { x: 345, y: 2, t: Two(1, 2) };
1149 let reccy3 = RecCy { x: 1, y: 777, t: Three(1, 2, 3) };
1150 let reccy4 = RecCy { x: 19, y: 252, t: Two(17, 42) };
1151 test_parameterized::<RecCy>(reccy1, reccy2, reccy3, reccy4);
1155 fn test_with_capacity() {
1156 let mut d = RingBuf::with_capacity(0);
1158 assert_eq!(d.len(), 1);
1159 let mut d = RingBuf::with_capacity(50);
1161 assert_eq!(d.len(), 1);
1165 fn test_with_capacity_non_power_two() {
1166 let mut d3 = RingBuf::with_capacity(3);
1171 assert_eq!(d3.pop_front(), Some(1));
1173 assert_eq!(d3.front(), None);
1180 assert_eq!(d3.pop_front(), Some(3));
1182 // Pushing the lo past half way point to trigger
1183 // the 'B' scenario for growth
1190 // There used to be a bug here about how the
1191 // RingBuf made growth assumptions about the
1192 // underlying Vec which didn't hold and lead
1194 // (Vec grows to next power of two)
1195 //good- [9, 12, 15, X, X, X, X, |6]
1196 //bug- [15, 12, X, X, X, |6, X, X]
1197 assert_eq!(d3.pop_front(), Some(6));
1199 // Which leads us to the following state which
1200 // would be a failure case.
1201 //bug- [15, 12, X, X, X, X, |X, X]
1202 assert_eq!(d3.front(), Some(&9));
1206 fn test_reserve_exact() {
1207 let mut d = RingBuf::new();
1209 d.reserve_exact(50);
1210 assert!(d.capacity() >= 51);
1211 let mut d = RingBuf::new();
1213 d.reserve_exact(50);
1214 assert!(d.capacity() >= 51);
1219 let mut d = RingBuf::new();
1222 assert!(d.capacity() >= 51);
1223 let mut d = RingBuf::new();
1226 assert!(d.capacity() >= 51);
1231 let mut d: RingBuf<int> = range(0i, 5).collect();
1234 assert_eq!(d.iter().map(|&x|x).collect::<Vec<int>>(), vec!(4, 2, 3, 1));
1239 let mut d = RingBuf::new();
1240 assert_eq!(d.iter().next(), None);
1241 assert_eq!(d.iter().size_hint(), (0, Some(0)));
1243 for i in range(0i, 5) {
1247 let b: &[_] = &[&0,&1,&2,&3,&4];
1248 assert_eq!(d.iter().collect::<Vec<&int>>(), b);
1251 for i in range(6i, 9) {
1255 let b: &[_] = &[&8,&7,&6,&0,&1,&2,&3,&4];
1256 assert_eq!(d.iter().collect::<Vec<&int>>(), b);
1259 let mut it = d.iter();
1260 let mut len = d.len();
1264 _ => { len -= 1; assert_eq!(it.size_hint(), (len, Some(len))) }
1270 fn test_rev_iter() {
1271 let mut d = RingBuf::new();
1272 assert_eq!(d.iter().rev().next(), None);
1274 for i in range(0i, 5) {
1278 let b: &[_] = &[&4,&3,&2,&1,&0];
1279 assert_eq!(d.iter().rev().collect::<Vec<&int>>(), b);
1282 for i in range(6i, 9) {
1285 let b: &[_] = &[&4,&3,&2,&1,&0,&6,&7,&8];
1286 assert_eq!(d.iter().rev().collect::<Vec<&int>>(), b);
1290 fn test_mut_rev_iter_wrap() {
1291 let mut d = RingBuf::with_capacity(3);
1292 assert!(d.iter_mut().rev().next().is_none());
1297 assert_eq!(d.pop_front(), Some(1));
1300 assert_eq!(d.iter_mut().rev().map(|x| *x).collect::<Vec<int>>(),
1305 fn test_mut_iter() {
1306 let mut d = RingBuf::new();
1307 assert!(d.iter_mut().next().is_none());
1309 for i in range(0u, 3) {
1313 for (i, elt) in d.iter_mut().enumerate() {
1314 assert_eq!(*elt, 2 - i);
1319 let mut it = d.iter_mut();
1320 assert_eq!(*it.next().unwrap(), 0);
1321 assert_eq!(*it.next().unwrap(), 1);
1322 assert_eq!(*it.next().unwrap(), 2);
1323 assert!(it.next().is_none());
1328 fn test_mut_rev_iter() {
1329 let mut d = RingBuf::new();
1330 assert!(d.iter_mut().rev().next().is_none());
1332 for i in range(0u, 3) {
1336 for (i, elt) in d.iter_mut().rev().enumerate() {
1337 assert_eq!(*elt, i);
1342 let mut it = d.iter_mut().rev();
1343 assert_eq!(*it.next().unwrap(), 0);
1344 assert_eq!(*it.next().unwrap(), 1);
1345 assert_eq!(*it.next().unwrap(), 2);
1346 assert!(it.next().is_none());
1351 fn test_into_iter() {
1355 let d: RingBuf<int> = RingBuf::new();
1356 let mut iter = d.into_iter();
1358 assert_eq!(iter.size_hint(), (0, Some(0)));
1359 assert_eq!(iter.next(), None);
1360 assert_eq!(iter.size_hint(), (0, Some(0)));
1365 let mut d = RingBuf::new();
1366 for i in range(0i, 5) {
1370 let b = vec![0,1,2,3,4];
1371 assert_eq!(d.into_iter().collect::<Vec<int>>(), b);
1376 let mut d = RingBuf::new();
1377 for i in range(0i, 5) {
1380 for i in range(6, 9) {
1384 let b = vec![8,7,6,0,1,2,3,4];
1385 assert_eq!(d.into_iter().collect::<Vec<int>>(), b);
1390 let mut d = RingBuf::new();
1391 for i in range(0i, 5) {
1394 for i in range(6, 9) {
1398 let mut it = d.into_iter();
1399 assert_eq!(it.size_hint(), (8, Some(8)));
1400 assert_eq!(it.next(), Some(8));
1401 assert_eq!(it.size_hint(), (7, Some(7)));
1402 assert_eq!(it.next_back(), Some(4));
1403 assert_eq!(it.size_hint(), (6, Some(6)));
1404 assert_eq!(it.next(), Some(7));
1405 assert_eq!(it.size_hint(), (5, Some(5)));
1410 fn test_from_iter() {
1412 let v = vec!(1i,2,3,4,5,6,7);
1413 let deq: RingBuf<int> = v.iter().map(|&x| x).collect();
1414 let u: Vec<int> = deq.iter().map(|&x| x).collect();
1417 let seq = iter::count(0u, 2).take(256);
1418 let deq: RingBuf<uint> = seq.collect();
1419 for (i, &x) in deq.iter().enumerate() {
1422 assert_eq!(deq.len(), 256);
1427 let mut d = RingBuf::new();
1432 assert_eq!(d.len(), 4u);
1433 let mut e = d.clone();
1434 assert_eq!(e.len(), 4u);
1435 while !d.is_empty() {
1436 assert_eq!(d.pop_back(), e.pop_back());
1438 assert_eq!(d.len(), 0u);
1439 assert_eq!(e.len(), 0u);
1444 let mut d = RingBuf::new();
1445 assert!(d == RingBuf::with_capacity(0));
1450 let mut e = RingBuf::with_capacity(0);
1460 assert!(e == RingBuf::new());
1465 let mut x = RingBuf::new();
1466 let mut y = RingBuf::new();
1478 assert!(hash::hash(&x) == hash::hash(&y));
1483 let x = RingBuf::new();
1484 let mut y = RingBuf::new();
1496 let ringbuf: RingBuf<int> = range(0i, 10).collect();
1497 assert!(format!("{}", ringbuf) == "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]");
1499 let ringbuf: RingBuf<&str> = vec!["just", "one", "test", "more"].iter()
1502 assert!(format!("{}", ringbuf) == "[just, one, test, more]");
1507 static mut drops: uint = 0;
1509 impl Drop for Elem {
1510 fn drop(&mut self) {
1511 unsafe { drops += 1; }
1515 let mut ring = RingBuf::new();
1516 ring.push_back(Elem);
1517 ring.push_front(Elem);
1518 ring.push_back(Elem);
1519 ring.push_front(Elem);
1522 assert_eq!(unsafe {drops}, 4);
1526 fn test_drop_with_pop() {
1527 static mut drops: uint = 0;
1529 impl Drop for Elem {
1530 fn drop(&mut self) {
1531 unsafe { drops += 1; }
1535 let mut ring = RingBuf::new();
1536 ring.push_back(Elem);
1537 ring.push_front(Elem);
1538 ring.push_back(Elem);
1539 ring.push_front(Elem);
1541 drop(ring.pop_back());
1542 drop(ring.pop_front());
1543 assert_eq!(unsafe {drops}, 2);
1546 assert_eq!(unsafe {drops}, 4);
1550 fn test_drop_clear() {
1551 static mut drops: uint = 0;
1553 impl Drop for Elem {
1554 fn drop(&mut self) {
1555 unsafe { drops += 1; }
1559 let mut ring = RingBuf::new();
1560 ring.push_back(Elem);
1561 ring.push_front(Elem);
1562 ring.push_back(Elem);
1563 ring.push_front(Elem);
1565 assert_eq!(unsafe {drops}, 4);
1568 assert_eq!(unsafe {drops}, 4);
1572 fn test_reserve_grow() {
1573 // test growth path A
1574 // [T o o H] -> [T o o H . . . . ]
1575 let mut ring = RingBuf::with_capacity(4);
1576 for i in range(0i, 3) {
1580 for i in range(0i, 3) {
1581 assert_eq!(ring.pop_front(), Some(i));
1584 // test growth path B
1585 // [H T o o] -> [. T o o H . . . ]
1586 let mut ring = RingBuf::with_capacity(4);
1587 for i in range(0i, 1) {
1589 assert_eq!(ring.pop_front(), Some(i));
1591 for i in range(0i, 3) {
1595 for i in range(0i, 3) {
1596 assert_eq!(ring.pop_front(), Some(i));
1599 // test growth path C
1600 // [o o H T] -> [o o H . . . . T ]
1601 let mut ring = RingBuf::with_capacity(4);
1602 for i in range(0i, 3) {
1604 assert_eq!(ring.pop_front(), Some(i));
1606 for i in range(0i, 3) {
1610 for i in range(0i, 3) {
1611 assert_eq!(ring.pop_front(), Some(i));
1617 let mut ring = RingBuf::new();
1619 assert_eq!(ring.get(0), Some(&0));
1620 assert_eq!(ring.get(1), None);
1623 assert_eq!(ring.get(0), Some(&0));
1624 assert_eq!(ring.get(1), Some(&1));
1625 assert_eq!(ring.get(2), None);
1628 assert_eq!(ring.get(0), Some(&0));
1629 assert_eq!(ring.get(1), Some(&1));
1630 assert_eq!(ring.get(2), Some(&2));
1631 assert_eq!(ring.get(3), None);
1633 assert_eq!(ring.pop_front(), Some(0));
1634 assert_eq!(ring.get(0), Some(&1));
1635 assert_eq!(ring.get(1), Some(&2));
1636 assert_eq!(ring.get(2), None);
1638 assert_eq!(ring.pop_front(), Some(1));
1639 assert_eq!(ring.get(0), Some(&2));
1640 assert_eq!(ring.get(1), None);
1642 assert_eq!(ring.pop_front(), Some(2));
1643 assert_eq!(ring.get(0), None);
1644 assert_eq!(ring.get(1), None);
1649 let mut ring = RingBuf::new();
1650 for i in range(0i, 3) {
1654 match ring.get_mut(1) {
1659 assert_eq!(ring.get_mut(0), Some(&mut 0));
1660 assert_eq!(ring.get_mut(1), Some(&mut -1));
1661 assert_eq!(ring.get_mut(2), Some(&mut 2));
1662 assert_eq!(ring.get_mut(3), None);
1664 assert_eq!(ring.pop_front(), Some(0));
1665 assert_eq!(ring.get_mut(0), Some(&mut -1));
1666 assert_eq!(ring.get_mut(1), Some(&mut 2));
1667 assert_eq!(ring.get_mut(2), None);