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?
37 // FIXME(conventions): implement into_iter
40 /// `RingBuf` is a circular buffer that implements `Deque`.
41 pub struct RingBuf<T> {
42 // tail and head are pointers into the buffer. Tail always points
43 // to the first element that could be read, Head always points
44 // to where data should be written.
45 // If tail == head the buffer is empty. The length of the ringbuf
46 // is defined as the distance between the two.
54 impl<T: Clone> Clone for RingBuf<T> {
55 fn clone(&self) -> RingBuf<T> {
56 self.iter().map(|t| t.clone()).collect()
61 impl<T> Drop for RingBuf<T> {
65 if mem::size_of::<T>() != 0 {
66 heap::deallocate(self.ptr as *mut u8,
67 self.cap * mem::size_of::<T>(),
68 mem::min_align_of::<T>())
74 impl<T> Default for RingBuf<T> {
76 fn default() -> RingBuf<T> { RingBuf::new() }
80 /// Turn ptr into a slice
82 unsafe fn buffer_as_slice(&self) -> &[T] {
83 mem::transmute(RawSlice { data: self.ptr as *const T, len: self.cap })
86 /// Moves an element out of the buffer
88 unsafe fn buffer_read(&mut self, off: uint) -> T {
89 ptr::read(self.ptr.offset(off as int) as *const T)
92 /// Writes an element into the buffer, moving it.
94 unsafe fn buffer_write(&mut self, off: uint, t: T) {
95 ptr::write(self.ptr.offset(off as int), t);
98 /// Returns true iff the buffer is at capacity
100 fn is_full(&self) -> bool { self.cap - self.len() == 1 }
102 /// Returns the index in the underlying buffer for a given logical element index.
104 fn wrap_index(&self, idx: uint) -> uint { wrap_index(idx, self.cap) }
108 /// Creates an empty `RingBuf`.
109 #[unstable = "matches collection reform specification, waiting for dust to settle"]
110 pub fn new() -> RingBuf<T> {
111 RingBuf::with_capacity(INITIAL_CAPACITY)
114 /// Creates an empty `RingBuf` with space for at least `n` elements.
115 #[unstable = "matches collection reform specification, waiting for dust to settle"]
116 pub fn with_capacity(n: uint) -> RingBuf<T> {
117 // +1 since the ringbuffer always leaves one space empty
118 let cap = cmp::max(n + 1, MINIMUM_CAPACITY).next_power_of_two();
119 let size = cap.checked_mul(mem::size_of::<T>())
120 .expect("capacity overflow");
122 let ptr = if mem::size_of::<T>() != 0 {
124 let ptr = heap::allocate(size, mem::min_align_of::<T>()) as *mut T;;
125 if ptr.is_null() { ::alloc::oom() }
129 heap::EMPTY as *mut T
140 /// Retrieves an element in the `RingBuf` by index.
145 /// use std::collections::RingBuf;
147 /// let mut buf = RingBuf::new();
148 /// buf.push_back(3i);
149 /// buf.push_back(4);
150 /// buf.push_back(5);
151 /// assert_eq!(buf.get(1).unwrap(), &4);
153 #[unstable = "matches collection reform specification, waiting for dust to settle"]
154 pub fn get(&self, i: uint) -> Option<&T> {
156 let idx = self.wrap_index(self.tail + i);
157 unsafe { Some(&*self.ptr.offset(idx as int)) }
163 /// Retrieves an element in the `RingBuf` mutably by index.
168 /// use std::collections::RingBuf;
170 /// let mut buf = RingBuf::new();
171 /// buf.push_back(3i);
172 /// buf.push_back(4);
173 /// buf.push_back(5);
174 /// match buf.get_mut(1) {
181 /// assert_eq!(buf[1], 7);
183 #[unstable = "matches collection reform specification, waiting for dust to settle"]
184 pub fn get_mut(&mut self, i: uint) -> Option<&mut T> {
186 let idx = self.wrap_index(self.tail + i);
187 unsafe { Some(&mut *self.ptr.offset(idx as int)) }
193 /// Swaps elements at indices `i` and `j`.
195 /// `i` and `j` may be equal.
197 /// Fails if there is no element with either index.
202 /// use std::collections::RingBuf;
204 /// let mut buf = RingBuf::new();
205 /// buf.push_back(3i);
206 /// buf.push_back(4);
207 /// buf.push_back(5);
209 /// assert_eq!(buf[0], 5);
210 /// assert_eq!(buf[2], 3);
212 pub fn swap(&mut self, i: uint, j: uint) {
213 assert!(i < self.len());
214 assert!(j < self.len());
215 let ri = self.wrap_index(self.tail + i);
216 let rj = self.wrap_index(self.tail + j);
218 ptr::swap(self.ptr.offset(ri as int), self.ptr.offset(rj as int))
222 /// Returns the number of elements the `RingBuf` can hold without
228 /// use std::collections::RingBuf;
230 /// let buf: RingBuf<int> = RingBuf::with_capacity(10);
231 /// assert!(buf.capacity() >= 10);
234 #[unstable = "matches collection reform specification, waiting for dust to settle"]
235 pub fn capacity(&self) -> uint { self.cap - 1 }
237 /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the
238 /// given `RingBuf`. Does nothing if the capacity is already sufficient.
240 /// Note that the allocator may give the collection more space than it requests. Therefore
241 /// capacity can not be relied upon to be precisely minimal. Prefer `reserve` if future
242 /// insertions are expected.
246 /// Panics if the new capacity overflows `uint`.
251 /// use std::collections::RingBuf;
253 /// let mut buf: RingBuf<int> = vec![1].into_iter().collect();
254 /// buf.reserve_exact(10);
255 /// assert!(buf.capacity() >= 11);
257 #[unstable = "matches collection reform specification, waiting for dust to settle"]
258 pub fn reserve_exact(&mut self, additional: uint) {
259 self.reserve(additional);
262 /// Reserves capacity for at least `additional` more elements to be inserted in the given
263 /// `Ringbuf`. The collection may reserve more space to avoid frequent reallocations.
267 /// Panics if the new capacity overflows `uint`.
272 /// use std::collections::RingBuf;
274 /// let mut buf: RingBuf<int> = vec![1].into_iter().collect();
276 /// assert!(buf.capacity() >= 11);
278 #[unstable = "matches collection reform specification, waiting for dust to settle"]
279 pub fn reserve(&mut self, additional: uint) {
280 let new_len = self.len() + additional;
281 assert!(new_len + 1 > self.len(), "capacity overflow");
282 if new_len > self.capacity() {
283 let count = (new_len + 1).next_power_of_two();
284 assert!(count >= new_len + 1);
286 if mem::size_of::<T>() != 0 {
287 let old = self.cap * mem::size_of::<T>();
288 let new = count.checked_mul(mem::size_of::<T>())
289 .expect("capacity overflow");
291 self.ptr = heap::reallocate(self.ptr as *mut u8,
294 mem::min_align_of::<T>()) as *mut T;
295 if self.ptr.is_null() { ::alloc::oom() }
299 // Move the shortest contiguous section of the ring buffer
301 // [o o o o o o o . ]
303 // A [o o o o o o o . . . . . . . . . ]
305 // [o o . o o o o o ]
307 // B [. . . o o o o o o o . . . . . . ]
309 // [o o o o o . o o ]
311 // C [o o o o o . . . . . . . . . o o ]
313 let oldcap = self.cap;
316 if self.tail <= self.head { // A
318 } else if self.head < oldcap - self.tail { // B
320 ptr::copy_nonoverlapping_memory(
321 self.ptr.offset(oldcap as int),
322 self.ptr as *const T,
327 debug_assert!(self.head > self.tail);
330 ptr::copy_nonoverlapping_memory(
331 self.ptr.offset((count - (oldcap - self.tail)) as int),
332 self.ptr.offset(self.tail as int) as *const T,
336 self.tail = count - (oldcap - self.tail);
337 debug_assert!(self.head < self.tail);
339 debug_assert!(self.head < self.cap);
340 debug_assert!(self.tail < self.cap);
341 debug_assert!(self.cap.count_ones() == 1);
345 /// Returns a front-to-back iterator.
350 /// use std::collections::RingBuf;
352 /// let mut buf = RingBuf::new();
353 /// buf.push_back(5i);
354 /// buf.push_back(3);
355 /// buf.push_back(4);
356 /// let b: &[_] = &[&5, &3, &4];
357 /// assert_eq!(buf.iter().collect::<Vec<&int>>().as_slice(), b);
359 #[unstable = "matches collection reform specification, waiting for dust to settle"]
360 pub fn iter(&self) -> Items<T> {
364 ring: unsafe { self.buffer_as_slice() }
368 /// Returns a front-to-back iterator which returns mutable references.
373 /// use std::collections::RingBuf;
375 /// let mut buf = RingBuf::new();
376 /// buf.push_back(5i);
377 /// buf.push_back(3);
378 /// buf.push_back(4);
379 /// for num in buf.iter_mut() {
382 /// let b: &[_] = &[&mut 3, &mut 1, &mut 2];
383 /// assert_eq!(buf.iter_mut().collect::<Vec<&mut int>>()[], b);
385 #[unstable = "matches collection reform specification, waiting for dust to settle"]
386 pub fn iter_mut<'a>(&'a mut self) -> MutItems<'a, T> {
392 marker: marker::ContravariantLifetime::<'a>,
393 marker2: marker::NoCopy
397 /// Returns the number of elements in the `RingBuf`.
402 /// use std::collections::RingBuf;
404 /// let mut v = RingBuf::new();
405 /// assert_eq!(v.len(), 0);
407 /// assert_eq!(v.len(), 1);
409 #[unstable = "matches collection reform specification, waiting for dust to settle"]
410 pub fn len(&self) -> uint { count(self.tail, self.head, self.cap) }
412 /// Returns true if the buffer contains no elements
417 /// use std::collections::RingBuf;
419 /// let mut v = RingBuf::new();
420 /// assert!(v.is_empty());
421 /// v.push_front(1i);
422 /// assert!(!v.is_empty());
424 #[unstable = "matches collection reform specification, waiting for dust to settle"]
425 pub fn is_empty(&self) -> bool { self.len() == 0 }
427 /// Clears the buffer, removing all values.
432 /// use std::collections::RingBuf;
434 /// let mut v = RingBuf::new();
437 /// assert!(v.is_empty());
439 #[unstable = "matches collection reform specification, waiting for dust to settle"]
440 pub fn clear(&mut self) {
441 while self.pop_front().is_some() {}
446 /// Provides a reference to the front element, or `None` if the sequence is
452 /// use std::collections::RingBuf;
454 /// let mut d = RingBuf::new();
455 /// assert_eq!(d.front(), None);
459 /// assert_eq!(d.front(), Some(&1i));
461 #[unstable = "matches collection reform specification, waiting for dust to settle"]
462 pub fn front(&self) -> Option<&T> {
463 if !self.is_empty() { Some(&self[0]) } else { None }
466 /// Provides a mutable reference to the front element, or `None` if the
467 /// sequence is empty.
472 /// use std::collections::RingBuf;
474 /// let mut d = RingBuf::new();
475 /// assert_eq!(d.front_mut(), None);
479 /// match d.front_mut() {
480 /// Some(x) => *x = 9i,
483 /// assert_eq!(d.front(), Some(&9i));
485 #[unstable = "matches collection reform specification, waiting for dust to settle"]
486 pub fn front_mut(&mut self) -> Option<&mut T> {
487 if !self.is_empty() { Some(&mut self[0]) } else { None }
490 /// Provides a reference to the back element, or `None` if the sequence is
496 /// use std::collections::RingBuf;
498 /// let mut d = RingBuf::new();
499 /// assert_eq!(d.back(), None);
503 /// assert_eq!(d.back(), Some(&2i));
505 #[unstable = "matches collection reform specification, waiting for dust to settle"]
506 pub fn back(&self) -> Option<&T> {
507 if !self.is_empty() { Some(&self[self.len() - 1]) } else { None }
510 /// Provides a mutable reference to the back element, or `None` if the
511 /// sequence is empty.
516 /// use std::collections::RingBuf;
518 /// let mut d = RingBuf::new();
519 /// assert_eq!(d.back(), None);
523 /// match d.back_mut() {
524 /// Some(x) => *x = 9i,
527 /// assert_eq!(d.back(), Some(&9i));
529 #[unstable = "matches collection reform specification, waiting for dust to settle"]
530 pub fn back_mut(&mut self) -> Option<&mut T> {
531 let len = self.len();
532 if !self.is_empty() { Some(&mut self[len - 1]) } else { None }
535 /// Removes the first element and returns it, or `None` if the sequence is
541 /// use std::collections::RingBuf;
543 /// let mut d = RingBuf::new();
547 /// assert_eq!(d.pop_front(), Some(1i));
548 /// assert_eq!(d.pop_front(), Some(2i));
549 /// assert_eq!(d.pop_front(), None);
551 #[unstable = "matches collection reform specification, waiting for dust to settle"]
552 pub fn pop_front(&mut self) -> Option<T> {
556 let tail = self.tail;
557 self.tail = self.wrap_index(self.tail + 1);
558 unsafe { Some(self.buffer_read(tail)) }
562 /// Inserts an element first in the sequence.
567 /// use std::collections::RingBuf;
569 /// let mut d = RingBuf::new();
570 /// d.push_front(1i);
571 /// d.push_front(2i);
572 /// assert_eq!(d.front(), Some(&2i));
574 #[unstable = "matches collection reform specification, waiting for dust to settle"]
575 pub fn push_front(&mut self, t: T) {
578 debug_assert!(!self.is_full());
581 self.tail = self.wrap_index(self.tail - 1);
582 let tail = self.tail;
583 unsafe { self.buffer_write(tail, t); }
586 /// Deprecated: Renamed to `push_back`.
587 #[deprecated = "Renamed to `push_back`"]
588 pub fn push(&mut self, t: T) {
592 /// Appends an element to the back of a buffer
597 /// use std::collections::RingBuf;
599 /// let mut buf = RingBuf::new();
600 /// buf.push_back(1i);
601 /// buf.push_back(3);
602 /// assert_eq!(3, *buf.back().unwrap());
604 #[unstable = "matches collection reform specification, waiting for dust to settle"]
605 pub fn push_back(&mut self, t: T) {
608 debug_assert!(!self.is_full());
611 let head = self.head;
612 self.head = self.wrap_index(self.head + 1);
613 unsafe { self.buffer_write(head, t) }
616 /// Deprecated: Renamed to `pop_back`.
617 #[deprecated = "Renamed to `pop_back`"]
618 pub fn pop(&mut self) -> Option<T> {
622 /// Removes the last element from a buffer and returns it, or `None` if
628 /// use std::collections::RingBuf;
630 /// let mut buf = RingBuf::new();
631 /// assert_eq!(buf.pop_back(), None);
632 /// buf.push_back(1i);
633 /// buf.push_back(3);
634 /// assert_eq!(buf.pop_back(), Some(3));
636 #[unstable = "matches collection reform specification, waiting for dust to settle"]
637 pub fn pop_back(&mut self) -> Option<T> {
641 self.head = self.wrap_index(self.head - 1);
642 let head = self.head;
643 unsafe { Some(self.buffer_read(head)) }
648 /// Returns the index in the underlying buffer for a given logical element index.
650 fn wrap_index(index: uint, size: uint) -> uint {
651 // size is always a power of 2
655 /// Calculate the number of elements left to be read in the buffer
657 fn count(tail: uint, head: uint, size: uint) -> uint {
658 // size is always a power of 2
659 (head - tail) & (size - 1)
662 /// `RingBuf` iterator.
663 pub struct Items<'a, T:'a> {
669 impl<'a, T> Iterator<&'a T> for Items<'a, T> {
671 fn next(&mut self) -> Option<&'a T> {
672 if self.tail == self.head {
675 let tail = self.tail;
676 self.tail = wrap_index(self.tail + 1, self.ring.len());
677 unsafe { Some(self.ring.unsafe_get(tail)) }
681 fn size_hint(&self) -> (uint, Option<uint>) {
682 let len = count(self.tail, self.head, self.ring.len());
687 impl<'a, T> DoubleEndedIterator<&'a T> for Items<'a, T> {
689 fn next_back(&mut self) -> Option<&'a T> {
690 if self.tail == self.head {
693 self.head = wrap_index(self.head - 1, self.ring.len());
694 unsafe { Some(self.ring.unsafe_get(self.head)) }
698 impl<'a, T> ExactSizeIterator<&'a T> for Items<'a, T> {}
700 impl<'a, T> RandomAccessIterator<&'a T> for Items<'a, T> {
702 fn indexable(&self) -> uint {
703 let (len, _) = self.size_hint();
708 fn idx(&mut self, j: uint) -> Option<&'a T> {
709 if j >= self.indexable() {
712 let idx = wrap_index(self.tail + j, self.ring.len());
713 unsafe { Some(self.ring.unsafe_get(idx)) }
718 // FIXME This was implemented differently from Items because of a problem
719 // with returning the mutable reference. I couldn't find a way to
720 // make the lifetime checker happy so, but there should be a way.
721 /// `RingBuf` mutable iterator.
722 pub struct MutItems<'a, T:'a> {
727 marker: marker::ContravariantLifetime<'a>,
728 marker2: marker::NoCopy
731 impl<'a, T> Iterator<&'a mut T> for MutItems<'a, T> {
733 fn next(&mut self) -> Option<&'a mut T> {
734 if self.tail == self.head {
737 let tail = self.tail;
738 self.tail = wrap_index(self.tail + 1, self.cap);
739 if mem::size_of::<T>() != 0 {
740 unsafe { Some(&mut *self.ptr.offset(tail as int)) }
742 // use a non-zero pointer
743 Some(unsafe { mem::transmute(1u) })
748 fn size_hint(&self) -> (uint, Option<uint>) {
749 let len = count(self.tail, self.head, self.cap);
754 impl<'a, T> DoubleEndedIterator<&'a mut T> for MutItems<'a, T> {
756 fn next_back(&mut self) -> Option<&'a mut T> {
757 if self.tail == self.head {
760 self.head = wrap_index(self.head - 1, self.cap);
761 unsafe { Some(&mut *self.ptr.offset(self.head as int)) }
765 impl<'a, T> ExactSizeIterator<&'a mut T> for MutItems<'a, T> {}
767 impl<A: PartialEq> PartialEq for RingBuf<A> {
768 fn eq(&self, other: &RingBuf<A>) -> bool {
769 self.len() == other.len() &&
770 self.iter().zip(other.iter()).all(|(a, b)| a.eq(b))
772 fn ne(&self, other: &RingBuf<A>) -> bool {
777 impl<A: Eq> Eq for RingBuf<A> {}
779 impl<A: PartialOrd> PartialOrd for RingBuf<A> {
780 fn partial_cmp(&self, other: &RingBuf<A>) -> Option<Ordering> {
781 iter::order::partial_cmp(self.iter(), other.iter())
785 impl<A: Ord> Ord for RingBuf<A> {
787 fn cmp(&self, other: &RingBuf<A>) -> Ordering {
788 iter::order::cmp(self.iter(), other.iter())
792 impl<S: Writer, A: Hash<S>> Hash<S> for RingBuf<A> {
793 fn hash(&self, state: &mut S) {
794 self.len().hash(state);
795 for elt in self.iter() {
801 impl<A> Index<uint, A> for RingBuf<A> {
803 fn index<'a>(&'a self, i: &uint) -> &'a A {
804 self.get(*i).expect("Out of bounds access")
808 impl<A> IndexMut<uint, A> for RingBuf<A> {
810 fn index_mut<'a>(&'a mut self, i: &uint) -> &'a mut A {
811 self.get_mut(*i).expect("Out of bounds access")
815 impl<A> FromIterator<A> for RingBuf<A> {
816 fn from_iter<T: Iterator<A>>(iterator: T) -> RingBuf<A> {
817 let (lower, _) = iterator.size_hint();
818 let mut deq = RingBuf::with_capacity(lower);
819 deq.extend(iterator);
824 impl<A> Extend<A> for RingBuf<A> {
825 fn extend<T: Iterator<A>>(&mut self, mut iterator: T) {
826 for elt in iterator {
832 impl<T: fmt::Show> fmt::Show for RingBuf<T> {
833 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
834 try!(write!(f, "["));
836 for (i, e) in self.iter().enumerate() {
837 if i != 0 { try!(write!(f, ", ")); }
838 try!(write!(f, "{}", *e));
848 use self::Taggypar::*;
861 let mut d = RingBuf::new();
862 assert_eq!(d.len(), 0u);
866 assert_eq!(d.len(), 3u);
868 assert_eq!(d.len(), 4u);
869 debug!("{}", d.front());
870 assert_eq!(*d.front().unwrap(), 42);
871 debug!("{}", d.back());
872 assert_eq!(*d.back().unwrap(), 137);
873 let mut i = d.pop_front();
875 assert_eq!(i, Some(42));
878 assert_eq!(i, Some(137));
881 assert_eq!(i, Some(137));
884 assert_eq!(i, Some(17));
885 assert_eq!(d.len(), 0u);
887 assert_eq!(d.len(), 1u);
889 assert_eq!(d.len(), 2u);
891 assert_eq!(d.len(), 3u);
893 assert_eq!(d.len(), 4u);
905 fn test_parameterized<T:Clone + PartialEq + Show>(a: T, b: T, c: T, d: T) {
906 let mut deq = RingBuf::new();
907 assert_eq!(deq.len(), 0);
908 deq.push_front(a.clone());
909 deq.push_front(b.clone());
910 deq.push_back(c.clone());
911 assert_eq!(deq.len(), 3);
912 deq.push_back(d.clone());
913 assert_eq!(deq.len(), 4);
914 assert_eq!((*deq.front().unwrap()).clone(), b.clone());
915 assert_eq!((*deq.back().unwrap()).clone(), d.clone());
916 assert_eq!(deq.pop_front().unwrap(), b.clone());
917 assert_eq!(deq.pop_back().unwrap(), d.clone());
918 assert_eq!(deq.pop_back().unwrap(), c.clone());
919 assert_eq!(deq.pop_back().unwrap(), a.clone());
920 assert_eq!(deq.len(), 0);
921 deq.push_back(c.clone());
922 assert_eq!(deq.len(), 1);
923 deq.push_front(b.clone());
924 assert_eq!(deq.len(), 2);
925 deq.push_back(d.clone());
926 assert_eq!(deq.len(), 3);
927 deq.push_front(a.clone());
928 assert_eq!(deq.len(), 4);
929 assert_eq!(deq[0].clone(), a.clone());
930 assert_eq!(deq[1].clone(), b.clone());
931 assert_eq!(deq[2].clone(), c.clone());
932 assert_eq!(deq[3].clone(), d.clone());
936 fn test_push_front_grow() {
937 let mut deq = RingBuf::new();
938 for i in range(0u, 66) {
941 assert_eq!(deq.len(), 66);
943 for i in range(0u, 66) {
944 assert_eq!(deq[i], 65 - i);
947 let mut deq = RingBuf::new();
948 for i in range(0u, 66) {
952 for i in range(0u, 66) {
953 assert_eq!(deq[i], i);
959 let mut deq = RingBuf::new();
960 for i in range(1u, 4) {
963 assert_eq!(deq[1], 2);
968 fn test_index_out_of_bounds() {
969 let mut deq = RingBuf::new();
970 for i in range(1u, 4) {
977 fn bench_new(b: &mut test::Bencher) {
979 let ring: RingBuf<u64> = RingBuf::new();
980 test::black_box(ring);
985 fn bench_push_back_100(b: &mut test::Bencher) {
986 let mut deq = RingBuf::with_capacity(101);
988 for i in range(0i, 100) {
997 fn bench_push_front_100(b: &mut test::Bencher) {
998 let mut deq = RingBuf::with_capacity(101);
1000 for i in range(0i, 100) {
1009 fn bench_pop_back_100(b: &mut test::Bencher) {
1010 let mut deq: RingBuf<int> = RingBuf::with_capacity(101);
1015 while !deq.is_empty() {
1016 test::black_box(deq.pop_back());
1022 fn bench_pop_front_100(b: &mut test::Bencher) {
1023 let mut deq: RingBuf<int> = RingBuf::with_capacity(101);
1028 while !deq.is_empty() {
1029 test::black_box(deq.pop_front());
1035 fn bench_grow_1025(b: &mut test::Bencher) {
1037 let mut deq = RingBuf::new();
1038 for i in range(0i, 1025) {
1041 test::black_box(deq);
1046 fn bench_iter_1000(b: &mut test::Bencher) {
1047 let ring: RingBuf<int> = range(0i, 1000).collect();
1051 for &i in ring.iter() {
1054 test::black_box(sum);
1059 fn bench_mut_iter_1000(b: &mut test::Bencher) {
1060 let mut ring: RingBuf<int> = range(0i, 1000).collect();
1064 for i in ring.iter_mut() {
1067 test::black_box(sum);
1072 #[deriving(Clone, PartialEq, Show)]
1076 Three(int, int, int),
1079 #[deriving(Clone, PartialEq, Show)]
1083 Threepar(int, int, int),
1086 #[deriving(Clone, PartialEq, Show)]
1094 fn test_param_int() {
1095 test_parameterized::<int>(5, 72, 64, 175);
1099 fn test_param_taggy() {
1100 test_parameterized::<Taggy>(One(1), Two(1, 2), Three(1, 2, 3), Two(17, 42));
1104 fn test_param_taggypar() {
1105 test_parameterized::<Taggypar<int>>(Onepar::<int>(1),
1106 Twopar::<int>(1, 2),
1107 Threepar::<int>(1, 2, 3),
1108 Twopar::<int>(17, 42));
1112 fn test_param_reccy() {
1113 let reccy1 = RecCy { x: 1, y: 2, t: One(1) };
1114 let reccy2 = RecCy { x: 345, y: 2, t: Two(1, 2) };
1115 let reccy3 = RecCy { x: 1, y: 777, t: Three(1, 2, 3) };
1116 let reccy4 = RecCy { x: 19, y: 252, t: Two(17, 42) };
1117 test_parameterized::<RecCy>(reccy1, reccy2, reccy3, reccy4);
1121 fn test_with_capacity() {
1122 let mut d = RingBuf::with_capacity(0);
1124 assert_eq!(d.len(), 1);
1125 let mut d = RingBuf::with_capacity(50);
1127 assert_eq!(d.len(), 1);
1131 fn test_with_capacity_non_power_two() {
1132 let mut d3 = RingBuf::with_capacity(3);
1137 assert_eq!(d3.pop_front(), Some(1));
1139 assert_eq!(d3.front(), None);
1146 assert_eq!(d3.pop_front(), Some(3));
1148 // Pushing the lo past half way point to trigger
1149 // the 'B' scenario for growth
1156 // There used to be a bug here about how the
1157 // RingBuf made growth assumptions about the
1158 // underlying Vec which didn't hold and lead
1160 // (Vec grows to next power of two)
1161 //good- [9, 12, 15, X, X, X, X, |6]
1162 //bug- [15, 12, X, X, X, |6, X, X]
1163 assert_eq!(d3.pop_front(), Some(6));
1165 // Which leads us to the following state which
1166 // would be a failure case.
1167 //bug- [15, 12, X, X, X, X, |X, X]
1168 assert_eq!(d3.front(), Some(&9));
1172 fn test_reserve_exact() {
1173 let mut d = RingBuf::new();
1175 d.reserve_exact(50);
1176 assert!(d.capacity() >= 51);
1177 let mut d = RingBuf::new();
1179 d.reserve_exact(50);
1180 assert!(d.capacity() >= 51);
1185 let mut d = RingBuf::new();
1188 assert!(d.capacity() >= 51);
1189 let mut d = RingBuf::new();
1192 assert!(d.capacity() >= 51);
1197 let mut d: RingBuf<int> = range(0i, 5).collect();
1200 assert_eq!(d.iter().map(|&x|x).collect::<Vec<int>>(), vec!(4, 2, 3, 1));
1205 let mut d = RingBuf::new();
1206 assert_eq!(d.iter().next(), None);
1207 assert_eq!(d.iter().size_hint(), (0, Some(0)));
1209 for i in range(0i, 5) {
1213 let b: &[_] = &[&0,&1,&2,&3,&4];
1214 assert_eq!(d.iter().collect::<Vec<&int>>().as_slice(), b);
1217 for i in range(6i, 9) {
1221 let b: &[_] = &[&8,&7,&6,&0,&1,&2,&3,&4];
1222 assert_eq!(d.iter().collect::<Vec<&int>>().as_slice(), b);
1225 let mut it = d.iter();
1226 let mut len = d.len();
1230 _ => { len -= 1; assert_eq!(it.size_hint(), (len, Some(len))) }
1236 fn test_rev_iter() {
1237 let mut d = RingBuf::new();
1238 assert_eq!(d.iter().rev().next(), None);
1240 for i in range(0i, 5) {
1244 let b: &[_] = &[&4,&3,&2,&1,&0];
1245 assert_eq!(d.iter().rev().collect::<Vec<&int>>().as_slice(), b);
1248 for i in range(6i, 9) {
1251 let b: &[_] = &[&4,&3,&2,&1,&0,&6,&7,&8];
1252 assert_eq!(d.iter().rev().collect::<Vec<&int>>().as_slice(), b);
1256 fn test_mut_rev_iter_wrap() {
1257 let mut d = RingBuf::with_capacity(3);
1258 assert!(d.iter_mut().rev().next().is_none());
1263 assert_eq!(d.pop_front(), Some(1));
1266 assert_eq!(d.iter_mut().rev().map(|x| *x).collect::<Vec<int>>(),
1271 fn test_mut_iter() {
1272 let mut d = RingBuf::new();
1273 assert!(d.iter_mut().next().is_none());
1275 for i in range(0u, 3) {
1279 for (i, elt) in d.iter_mut().enumerate() {
1280 assert_eq!(*elt, 2 - i);
1285 let mut it = d.iter_mut();
1286 assert_eq!(*it.next().unwrap(), 0);
1287 assert_eq!(*it.next().unwrap(), 1);
1288 assert_eq!(*it.next().unwrap(), 2);
1289 assert!(it.next().is_none());
1294 fn test_mut_rev_iter() {
1295 let mut d = RingBuf::new();
1296 assert!(d.iter_mut().rev().next().is_none());
1298 for i in range(0u, 3) {
1302 for (i, elt) in d.iter_mut().rev().enumerate() {
1303 assert_eq!(*elt, i);
1308 let mut it = d.iter_mut().rev();
1309 assert_eq!(*it.next().unwrap(), 0);
1310 assert_eq!(*it.next().unwrap(), 1);
1311 assert_eq!(*it.next().unwrap(), 2);
1312 assert!(it.next().is_none());
1317 fn test_from_iter() {
1319 let v = vec!(1i,2,3,4,5,6,7);
1320 let deq: RingBuf<int> = v.iter().map(|&x| x).collect();
1321 let u: Vec<int> = deq.iter().map(|&x| x).collect();
1324 let seq = iter::count(0u, 2).take(256);
1325 let deq: RingBuf<uint> = seq.collect();
1326 for (i, &x) in deq.iter().enumerate() {
1329 assert_eq!(deq.len(), 256);
1334 let mut d = RingBuf::new();
1339 assert_eq!(d.len(), 4u);
1340 let mut e = d.clone();
1341 assert_eq!(e.len(), 4u);
1342 while !d.is_empty() {
1343 assert_eq!(d.pop_back(), e.pop_back());
1345 assert_eq!(d.len(), 0u);
1346 assert_eq!(e.len(), 0u);
1351 let mut d = RingBuf::new();
1352 assert!(d == RingBuf::with_capacity(0));
1357 let mut e = RingBuf::with_capacity(0);
1367 assert!(e == RingBuf::new());
1372 let mut x = RingBuf::new();
1373 let mut y = RingBuf::new();
1385 assert!(hash::hash(&x) == hash::hash(&y));
1390 let x = RingBuf::new();
1391 let mut y = RingBuf::new();
1403 let ringbuf: RingBuf<int> = range(0i, 10).collect();
1404 assert!(format!("{}", ringbuf).as_slice() == "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]");
1406 let ringbuf: RingBuf<&str> = vec!["just", "one", "test", "more"].iter()
1409 assert!(format!("{}", ringbuf).as_slice() == "[just, one, test, more]");
1414 static mut drops: uint = 0;
1416 impl Drop for Elem {
1417 fn drop(&mut self) {
1418 unsafe { drops += 1; }
1422 let mut ring = RingBuf::new();
1423 ring.push_back(Elem);
1424 ring.push_front(Elem);
1425 ring.push_back(Elem);
1426 ring.push_front(Elem);
1429 assert_eq!(unsafe {drops}, 4);
1433 fn test_drop_with_pop() {
1434 static mut drops: uint = 0;
1436 impl Drop for Elem {
1437 fn drop(&mut self) {
1438 unsafe { drops += 1; }
1442 let mut ring = RingBuf::new();
1443 ring.push_back(Elem);
1444 ring.push_front(Elem);
1445 ring.push_back(Elem);
1446 ring.push_front(Elem);
1448 drop(ring.pop_back());
1449 drop(ring.pop_front());
1450 assert_eq!(unsafe {drops}, 2);
1453 assert_eq!(unsafe {drops}, 4);
1457 fn test_drop_clear() {
1458 static mut drops: uint = 0;
1460 impl Drop for Elem {
1461 fn drop(&mut self) {
1462 unsafe { drops += 1; }
1466 let mut ring = RingBuf::new();
1467 ring.push_back(Elem);
1468 ring.push_front(Elem);
1469 ring.push_back(Elem);
1470 ring.push_front(Elem);
1472 assert_eq!(unsafe {drops}, 4);
1475 assert_eq!(unsafe {drops}, 4);
1479 fn test_reserve_grow() {
1480 // test growth path A
1481 // [T o o H] -> [T o o H . . . . ]
1482 let mut ring = RingBuf::with_capacity(4);
1483 for i in range(0i, 3) {
1487 for i in range(0i, 3) {
1488 assert_eq!(ring.pop_front(), Some(i));
1491 // test growth path B
1492 // [H T o o] -> [. T o o H . . . ]
1493 let mut ring = RingBuf::with_capacity(4);
1494 for i in range(0i, 1) {
1496 assert_eq!(ring.pop_front(), Some(i));
1498 for i in range(0i, 3) {
1502 for i in range(0i, 3) {
1503 assert_eq!(ring.pop_front(), Some(i));
1506 // test growth path C
1507 // [o o H T] -> [o o H . . . . T ]
1508 let mut ring = RingBuf::with_capacity(4);
1509 for i in range(0i, 3) {
1511 assert_eq!(ring.pop_front(), Some(i));
1513 for i in range(0i, 3) {
1517 for i in range(0i, 3) {
1518 assert_eq!(ring.pop_front(), Some(i));
1524 let mut ring = RingBuf::new();
1526 assert_eq!(ring.get(0), Some(&0));
1527 assert_eq!(ring.get(1), None);
1530 assert_eq!(ring.get(0), Some(&0));
1531 assert_eq!(ring.get(1), Some(&1));
1532 assert_eq!(ring.get(2), None);
1535 assert_eq!(ring.get(0), Some(&0));
1536 assert_eq!(ring.get(1), Some(&1));
1537 assert_eq!(ring.get(2), Some(&2));
1538 assert_eq!(ring.get(3), None);
1540 assert_eq!(ring.pop_front(), Some(0));
1541 assert_eq!(ring.get(0), Some(&1));
1542 assert_eq!(ring.get(1), Some(&2));
1543 assert_eq!(ring.get(2), None);
1545 assert_eq!(ring.pop_front(), Some(1));
1546 assert_eq!(ring.get(0), Some(&2));
1547 assert_eq!(ring.get(1), None);
1549 assert_eq!(ring.pop_front(), Some(2));
1550 assert_eq!(ring.get(0), None);
1551 assert_eq!(ring.get(1), None);
1556 let mut ring = RingBuf::new();
1557 for i in range(0i, 3) {
1561 match ring.get_mut(1) {
1566 assert_eq!(ring.get_mut(0), Some(&mut 0));
1567 assert_eq!(ring.get_mut(1), Some(&mut -1));
1568 assert_eq!(ring.get_mut(2), Some(&mut 2));
1569 assert_eq!(ring.get_mut(3), None);
1571 assert_eq!(ring.pop_front(), Some(0));
1572 assert_eq!(ring.get_mut(0), Some(&mut -1));
1573 assert_eq!(ring.get_mut(1), Some(&mut 2));
1574 assert_eq!(ring.get_mut(2), None);