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::cmp::Ordering;
18 use core::default::Default;
20 use core::iter::{mod, FromIterator, RandomAccessIterator};
21 use core::kinds::marker;
23 use core::num::{Int, UnsignedInt};
24 use core::ops::{Index, IndexMut};
26 use core::raw::Slice as RawSlice;
28 use std::hash::{Writer, Hash};
33 static INITIAL_CAPACITY: uint = 8u; // 2^3
34 static MINIMUM_CAPACITY: uint = 2u;
36 // FIXME(conventions): implement shrink_to_fit. Awkward with the current design, but it should
37 // be scrapped anyway. Defer to rewrite?
39 /// `RingBuf` is a circular buffer, which can be used as a double-ended queue efficiently.
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.
55 unsafe impl<T: Send> Send for RingBuf<T> {}
58 unsafe impl<T: Sync> Sync for RingBuf<T> {}
61 impl<T: Clone> Clone for RingBuf<T> {
62 fn clone(&self) -> RingBuf<T> {
63 self.iter().map(|t| t.clone()).collect()
69 impl<T> Drop for RingBuf<T> {
73 if mem::size_of::<T>() != 0 {
74 heap::deallocate(self.ptr as *mut u8,
75 self.cap * mem::size_of::<T>(),
76 mem::min_align_of::<T>())
83 impl<T> Default for RingBuf<T> {
85 fn default() -> RingBuf<T> { RingBuf::new() }
89 /// Turn ptr into a slice
91 unsafe fn buffer_as_slice(&self) -> &[T] {
92 mem::transmute(RawSlice { data: self.ptr as *const T, len: self.cap })
95 /// Turn ptr into a mut slice
97 unsafe fn buffer_as_mut_slice(&mut self) -> &mut [T] {
98 mem::transmute(RawSlice { data: self.ptr as *const T, len: self.cap })
101 /// Moves an element out of the buffer
103 unsafe fn buffer_read(&mut self, off: uint) -> T {
104 ptr::read(self.ptr.offset(off as int) as *const T)
107 /// Writes an element into the buffer, moving it.
109 unsafe fn buffer_write(&mut self, off: uint, t: T) {
110 ptr::write(self.ptr.offset(off as int), t);
113 /// Returns true iff the buffer is at capacity
115 fn is_full(&self) -> bool { self.cap - self.len() == 1 }
117 /// Returns the index in the underlying buffer for a given logical element index.
119 fn wrap_index(&self, idx: uint) -> uint { wrap_index(idx, self.cap) }
121 /// Copies a contiguous block of memory len long from src to dst
123 unsafe fn copy(&self, dst: uint, src: uint, len: uint) {
124 debug_assert!(dst + len <= self.cap, "dst={} src={} len={} cap={}", dst, src, len,
126 debug_assert!(src + len <= self.cap, "dst={} src={} len={} cap={}", dst, src, len,
129 self.ptr.offset(dst as int),
130 self.ptr.offset(src as int) as *const T,
136 /// Creates an empty `RingBuf`.
138 pub fn new() -> RingBuf<T> {
139 RingBuf::with_capacity(INITIAL_CAPACITY)
142 /// Creates an empty `RingBuf` with space for at least `n` elements.
144 pub fn with_capacity(n: uint) -> RingBuf<T> {
145 // +1 since the ringbuffer always leaves one space empty
146 let cap = cmp::max(n + 1, MINIMUM_CAPACITY).next_power_of_two();
147 let size = cap.checked_mul(mem::size_of::<T>())
148 .expect("capacity overflow");
150 let ptr = if mem::size_of::<T>() != 0 {
152 let ptr = heap::allocate(size, mem::min_align_of::<T>()) as *mut T;;
153 if ptr.is_null() { ::alloc::oom() }
157 heap::EMPTY as *mut T
168 /// Retrieves an element in the `RingBuf` by index.
173 /// use std::collections::RingBuf;
175 /// let mut buf = RingBuf::new();
176 /// buf.push_back(3i);
177 /// buf.push_back(4);
178 /// buf.push_back(5);
179 /// assert_eq!(buf.get(1).unwrap(), &4);
182 pub fn get(&self, i: uint) -> Option<&T> {
184 let idx = self.wrap_index(self.tail + i);
185 unsafe { Some(&*self.ptr.offset(idx as int)) }
191 /// Retrieves an element in the `RingBuf` mutably by index.
196 /// use std::collections::RingBuf;
198 /// let mut buf = RingBuf::new();
199 /// buf.push_back(3i);
200 /// buf.push_back(4);
201 /// buf.push_back(5);
202 /// match buf.get_mut(1) {
209 /// assert_eq!(buf[1], 7);
212 pub fn get_mut(&mut self, i: uint) -> Option<&mut T> {
214 let idx = self.wrap_index(self.tail + i);
215 unsafe { Some(&mut *self.ptr.offset(idx as int)) }
221 /// Swaps elements at indices `i` and `j`.
223 /// `i` and `j` may be equal.
225 /// Fails if there is no element with either index.
230 /// use std::collections::RingBuf;
232 /// let mut buf = RingBuf::new();
233 /// buf.push_back(3i);
234 /// buf.push_back(4);
235 /// buf.push_back(5);
237 /// assert_eq!(buf[0], 5);
238 /// assert_eq!(buf[2], 3);
241 pub fn swap(&mut self, i: uint, j: uint) {
242 assert!(i < self.len());
243 assert!(j < self.len());
244 let ri = self.wrap_index(self.tail + i);
245 let rj = self.wrap_index(self.tail + j);
247 ptr::swap(self.ptr.offset(ri as int), self.ptr.offset(rj as int))
251 /// Returns the number of elements the `RingBuf` can hold without
257 /// use std::collections::RingBuf;
259 /// let buf: RingBuf<int> = RingBuf::with_capacity(10);
260 /// assert!(buf.capacity() >= 10);
264 pub fn capacity(&self) -> uint { self.cap - 1 }
266 /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the
267 /// given `RingBuf`. Does nothing if the capacity is already sufficient.
269 /// Note that the allocator may give the collection more space than it requests. Therefore
270 /// capacity can not be relied upon to be precisely minimal. Prefer `reserve` if future
271 /// insertions are expected.
275 /// Panics if the new capacity overflows `uint`.
280 /// use std::collections::RingBuf;
282 /// let mut buf: RingBuf<int> = vec![1].into_iter().collect();
283 /// buf.reserve_exact(10);
284 /// assert!(buf.capacity() >= 11);
287 pub fn reserve_exact(&mut self, additional: uint) {
288 self.reserve(additional);
291 /// Reserves capacity for at least `additional` more elements to be inserted in the given
292 /// `Ringbuf`. The collection may reserve more space to avoid frequent reallocations.
296 /// Panics if the new capacity overflows `uint`.
301 /// use std::collections::RingBuf;
303 /// let mut buf: RingBuf<int> = vec![1].into_iter().collect();
305 /// assert!(buf.capacity() >= 11);
308 pub fn reserve(&mut self, additional: uint) {
309 let new_len = self.len() + additional;
310 assert!(new_len + 1 > self.len(), "capacity overflow");
311 if new_len > self.capacity() {
312 let count = (new_len + 1).next_power_of_two();
313 assert!(count >= new_len + 1);
315 if mem::size_of::<T>() != 0 {
316 let old = self.cap * mem::size_of::<T>();
317 let new = count.checked_mul(mem::size_of::<T>())
318 .expect("capacity overflow");
320 self.ptr = heap::reallocate(self.ptr as *mut u8,
323 mem::min_align_of::<T>()) as *mut T;
324 if self.ptr.is_null() { ::alloc::oom() }
328 // Move the shortest contiguous section of the ring buffer
330 // [o o o o o o o . ]
332 // A [o o o o o o o . . . . . . . . . ]
334 // [o o . o o o o o ]
336 // B [. . . o o o o o o o . . . . . . ]
338 // [o o o o o . o o ]
340 // C [o o o o o . . . . . . . . . o o ]
342 let oldcap = self.cap;
345 if self.tail <= self.head { // A
347 } else if self.head < oldcap - self.tail { // B
349 ptr::copy_nonoverlapping_memory(
350 self.ptr.offset(oldcap as int),
351 self.ptr as *const T,
356 debug_assert!(self.head > self.tail);
359 ptr::copy_nonoverlapping_memory(
360 self.ptr.offset((count - (oldcap - self.tail)) as int),
361 self.ptr.offset(self.tail as int) as *const T,
365 self.tail = count - (oldcap - self.tail);
366 debug_assert!(self.head < self.tail);
368 debug_assert!(self.head < self.cap);
369 debug_assert!(self.tail < self.cap);
370 debug_assert!(self.cap.count_ones() == 1);
374 /// Returns a front-to-back iterator.
379 /// use std::collections::RingBuf;
381 /// let mut buf = RingBuf::new();
382 /// buf.push_back(5i);
383 /// buf.push_back(3);
384 /// buf.push_back(4);
385 /// let b: &[_] = &[&5, &3, &4];
386 /// assert_eq!(buf.iter().collect::<Vec<&int>>().as_slice(), b);
389 pub fn iter(&self) -> Iter<T> {
393 ring: unsafe { self.buffer_as_slice() }
397 /// Returns a front-to-back iterator that returns mutable references.
402 /// use std::collections::RingBuf;
404 /// let mut buf = RingBuf::new();
405 /// buf.push_back(5i);
406 /// buf.push_back(3);
407 /// buf.push_back(4);
408 /// for num in buf.iter_mut() {
411 /// let b: &[_] = &[&mut 3, &mut 1, &mut 2];
412 /// assert_eq!(buf.iter_mut().collect::<Vec<&mut int>>()[], b);
415 pub fn iter_mut<'a>(&'a mut self) -> IterMut<'a, T> {
421 marker: marker::ContravariantLifetime::<'a>,
425 /// Consumes the list into an iterator yielding elements by value.
427 pub fn into_iter(self) -> IntoIter<T> {
433 /// Returns a pair of slices which contain, in order, the contents of the
436 #[unstable = "matches collection reform specification, waiting for dust to settle"]
437 pub fn as_slices<'a>(&'a self) -> (&'a [T], &'a [T]) {
439 let contiguous = self.is_contiguous();
440 let buf = self.buffer_as_slice();
442 let (empty, buf) = buf.split_at(0);
443 (buf[self.tail..self.head], empty)
445 let (mid, right) = buf.split_at(self.tail);
446 let (left, _) = mid.split_at(self.head);
452 /// Returns a pair of slices which contain, in order, the contents of the
455 #[unstable = "matches collection reform specification, waiting for dust to settle"]
456 pub fn as_mut_slices<'a>(&'a mut self) -> (&'a mut [T], &'a mut [T]) {
458 let contiguous = self.is_contiguous();
459 let head = self.head;
460 let tail = self.tail;
461 let buf = self.buffer_as_mut_slice();
464 let (empty, buf) = buf.split_at_mut(0);
465 (buf.slice_mut(tail, head), empty)
467 let (mid, right) = buf.split_at_mut(tail);
468 let (left, _) = mid.split_at_mut(head);
475 /// Returns the number of elements in the `RingBuf`.
480 /// use std::collections::RingBuf;
482 /// let mut v = RingBuf::new();
483 /// assert_eq!(v.len(), 0);
485 /// assert_eq!(v.len(), 1);
488 pub fn len(&self) -> uint { count(self.tail, self.head, self.cap) }
490 /// Returns true if the buffer contains no elements
495 /// use std::collections::RingBuf;
497 /// let mut v = RingBuf::new();
498 /// assert!(v.is_empty());
499 /// v.push_front(1i);
500 /// assert!(!v.is_empty());
503 pub fn is_empty(&self) -> bool { self.len() == 0 }
505 /// Creates a draining iterator that clears the `RingBuf` and iterates over
506 /// the removed items from start to end.
511 /// use std::collections::RingBuf;
513 /// let mut v = RingBuf::new();
515 /// assert_eq!(v.drain().next(), Some(1));
516 /// assert!(v.is_empty());
519 #[unstable = "matches collection reform specification, waiting for dust to settle"]
520 pub fn drain(&mut self) -> Drain<T> {
526 /// Clears the buffer, removing all values.
531 /// use std::collections::RingBuf;
533 /// let mut v = RingBuf::new();
536 /// assert!(v.is_empty());
540 pub fn clear(&mut self) {
544 /// Provides a reference to the front element, or `None` if the sequence is
550 /// use std::collections::RingBuf;
552 /// let mut d = RingBuf::new();
553 /// assert_eq!(d.front(), None);
557 /// assert_eq!(d.front(), Some(&1i));
560 pub fn front(&self) -> Option<&T> {
561 if !self.is_empty() { Some(&self[0]) } else { None }
564 /// Provides a mutable reference to the front element, or `None` if the
565 /// sequence is empty.
570 /// use std::collections::RingBuf;
572 /// let mut d = RingBuf::new();
573 /// assert_eq!(d.front_mut(), None);
577 /// match d.front_mut() {
578 /// Some(x) => *x = 9i,
581 /// assert_eq!(d.front(), Some(&9i));
584 pub fn front_mut(&mut self) -> Option<&mut T> {
585 if !self.is_empty() { Some(&mut self[0]) } else { None }
588 /// Provides a reference to the back element, or `None` if the sequence is
594 /// use std::collections::RingBuf;
596 /// let mut d = RingBuf::new();
597 /// assert_eq!(d.back(), None);
601 /// assert_eq!(d.back(), Some(&2i));
604 pub fn back(&self) -> Option<&T> {
605 if !self.is_empty() { Some(&self[self.len() - 1]) } else { None }
608 /// Provides a mutable reference to the back element, or `None` if the
609 /// sequence is empty.
614 /// use std::collections::RingBuf;
616 /// let mut d = RingBuf::new();
617 /// assert_eq!(d.back(), None);
621 /// match d.back_mut() {
622 /// Some(x) => *x = 9i,
625 /// assert_eq!(d.back(), Some(&9i));
628 pub fn back_mut(&mut self) -> Option<&mut T> {
629 let len = self.len();
630 if !self.is_empty() { Some(&mut self[len - 1]) } else { None }
633 /// Removes the first element and returns it, or `None` if the sequence is
639 /// use std::collections::RingBuf;
641 /// let mut d = RingBuf::new();
645 /// assert_eq!(d.pop_front(), Some(1i));
646 /// assert_eq!(d.pop_front(), Some(2i));
647 /// assert_eq!(d.pop_front(), None);
650 pub fn pop_front(&mut self) -> Option<T> {
654 let tail = self.tail;
655 self.tail = self.wrap_index(self.tail + 1);
656 unsafe { Some(self.buffer_read(tail)) }
660 /// Inserts an element first in the sequence.
665 /// use std::collections::RingBuf;
667 /// let mut d = RingBuf::new();
668 /// d.push_front(1i);
669 /// d.push_front(2i);
670 /// assert_eq!(d.front(), Some(&2i));
673 pub fn push_front(&mut self, t: T) {
676 debug_assert!(!self.is_full());
679 self.tail = self.wrap_index(self.tail - 1);
680 let tail = self.tail;
681 unsafe { self.buffer_write(tail, t); }
684 /// Deprecated: Renamed to `push_back`.
685 #[deprecated = "Renamed to `push_back`"]
686 pub fn push(&mut self, t: T) {
690 /// Appends an element to the back of a buffer
695 /// use std::collections::RingBuf;
697 /// let mut buf = RingBuf::new();
698 /// buf.push_back(1i);
699 /// buf.push_back(3);
700 /// assert_eq!(3, *buf.back().unwrap());
703 pub fn push_back(&mut self, t: T) {
706 debug_assert!(!self.is_full());
709 let head = self.head;
710 self.head = self.wrap_index(self.head + 1);
711 unsafe { self.buffer_write(head, t) }
714 /// Deprecated: Renamed to `pop_back`.
715 #[deprecated = "Renamed to `pop_back`"]
716 pub fn pop(&mut self) -> Option<T> {
720 /// Removes the last element from a buffer and returns it, or `None` if
726 /// use std::collections::RingBuf;
728 /// let mut buf = RingBuf::new();
729 /// assert_eq!(buf.pop_back(), None);
730 /// buf.push_back(1i);
731 /// buf.push_back(3);
732 /// assert_eq!(buf.pop_back(), Some(3));
735 pub fn pop_back(&mut self) -> Option<T> {
739 self.head = self.wrap_index(self.head - 1);
740 let head = self.head;
741 unsafe { Some(self.buffer_read(head)) }
746 fn is_contiguous(&self) -> bool {
747 self.tail <= self.head
750 /// Inserts an element at position `i` within the ringbuf. Whichever
751 /// end is closer to the insertion point will be moved to make room,
752 /// and all the affected elements will be moved to new positions.
756 /// Panics if `i` is greater than ringbuf's length
760 /// use std::collections::RingBuf;
762 /// let mut buf = RingBuf::new();
763 /// buf.push_back(10i);
764 /// buf.push_back(12);
765 /// buf.insert(1,11);
766 /// assert_eq!(Some(&11), buf.get(1));
768 pub fn insert(&mut self, i: uint, t: T) {
769 assert!(i <= self.len(), "index out of bounds");
772 debug_assert!(!self.is_full());
775 // Move the least number of elements in the ring buffer and insert
778 // At most len/2 - 1 elements will be moved. O(min(n, n-i))
780 // There are three main cases:
781 // Elements are contiguous
782 // - special case when tail is 0
783 // Elements are discontiguous and the insert is in the tail section
784 // Elements are discontiguous and the insert is in the head section
786 // For each of those there are two more cases:
787 // Insert is closer to tail
788 // Insert is closer to head
790 // Key: H - self.head
793 // I - Insertion element
794 // A - The element that should be after the insertion point
795 // M - Indicates element was moved
797 let idx = self.wrap_index(self.tail + i);
799 let distance_to_tail = i;
800 let distance_to_head = self.len() - i;
802 let contiguous = self.is_contiguous();
804 match (contiguous, distance_to_tail <= distance_to_head, idx >= self.tail) {
805 (true, true, _) if i == 0 => {
810 // [A o o o o o o . . . . . . . . .]
813 // [A o o o o o o o . . . . . I]
816 self.tail = self.wrap_index(self.tail - 1);
818 (true, true, _) => unsafe {
819 // contiguous, insert closer to tail:
822 // [. . . o o A o o o o . . . . . .]
825 // [. . o o I A o o o o . . . . . .]
828 // contiguous, insert closer to tail and tail is 0:
832 // [o o A o o o o . . . . . . . . .]
835 // [o I A o o o o o . . . . . . . o]
838 let new_tail = self.wrap_index(self.tail - 1);
840 self.copy(new_tail, self.tail, 1);
841 // Already moved the tail, so we only copy `i - 1` elements.
842 self.copy(self.tail, self.tail + 1, i - 1);
844 self.tail = new_tail;
846 (true, false, _) => unsafe {
847 // contiguous, insert closer to head:
850 // [. . . o o o o A o o . . . . . .]
853 // [. . . o o o o I A o o . . . . .]
856 self.copy(idx + 1, idx, self.head - idx);
857 self.head = self.wrap_index(self.head + 1);
859 (false, true, true) => unsafe {
860 // discontiguous, insert closer to tail, tail section:
863 // [o o o o o o . . . . . o o A o o]
866 // [o o o o o o . . . . o o I A o o]
869 self.copy(self.tail - 1, self.tail, i);
872 (false, false, true) => unsafe {
873 // discontiguous, insert closer to head, tail section:
876 // [o o . . . . . . . o o o o o A o]
879 // [o o o . . . . . . o o o o o I A]
882 // copy elements up to new head
883 self.copy(1, 0, self.head);
885 // copy last element into empty spot at bottom of buffer
886 self.copy(0, self.cap - 1, 1);
888 // move elements from idx to end forward not including ^ element
889 self.copy(idx + 1, idx, self.cap - 1 - idx);
893 (false, true, false) if idx == 0 => unsafe {
894 // discontiguous, insert is closer to tail, head section,
895 // and is at index zero in the internal buffer:
898 // [A o o o o o o o o o . . . o o o]
901 // [A o o o o o o o o o . . o o o I]
904 // copy elements up to new tail
905 self.copy(self.tail - 1, self.tail, self.cap - self.tail);
907 // copy last element into empty spot at bottom of buffer
908 self.copy(self.cap - 1, 0, 1);
912 (false, true, false) => unsafe {
913 // discontiguous, insert closer to tail, head section:
916 // [o o o A o o o o o o . . . o o o]
919 // [o o I A o o o o o o . . o o o o]
922 // copy elements up to new tail
923 self.copy(self.tail - 1, self.tail, self.cap - self.tail);
925 // copy last element into empty spot at bottom of buffer
926 self.copy(self.cap - 1, 0, 1);
928 // move elements from idx-1 to end forward not including ^ element
929 self.copy(0, 1, idx - 1);
933 (false, false, false) => unsafe {
934 // discontiguous, insert closer to head, head section:
937 // [o o o o A o o . . . . . . o o o]
940 // [o o o o I A o o . . . . . o o o]
943 self.copy(idx + 1, idx, self.head - idx);
948 // tail might've been changed so we need to recalculate
949 let new_idx = self.wrap_index(self.tail + i);
951 self.buffer_write(new_idx, t);
955 /// Removes and returns the element at position `i` from the ringbuf.
956 /// Whichever end is closer to the removal point will be moved to make
957 /// room, and all the affected elements will be moved to new positions.
958 /// Returns `None` if `i` is out of bounds.
962 /// use std::collections::RingBuf;
964 /// let mut buf = RingBuf::new();
965 /// buf.push_back(5i);
966 /// buf.push_back(10i);
967 /// buf.push_back(12i);
968 /// buf.push_back(15);
970 /// assert_eq!(Some(&15), buf.get(2));
973 pub fn remove(&mut self, i: uint) -> Option<T> {
974 if self.is_empty() || self.len() <= i {
978 // There are three main cases:
979 // Elements are contiguous
980 // Elements are discontiguous and the removal is in the tail section
981 // Elements are discontiguous and the removal is in the head section
982 // - special case when elements are technically contiguous,
985 // For each of those there are two more cases:
986 // Insert is closer to tail
987 // Insert is closer to head
989 // Key: H - self.head
992 // x - Element marked for removal
993 // R - Indicates element that is being removed
994 // M - Indicates element was moved
996 let idx = self.wrap_index(self.tail + i);
999 Some(self.buffer_read(idx))
1002 let distance_to_tail = i;
1003 let distance_to_head = self.len() - i;
1005 let contiguous = self.tail <= self.head;
1007 match (contiguous, distance_to_tail <= distance_to_head, idx >= self.tail) {
1008 (true, true, _) => unsafe {
1009 // contiguous, remove closer to tail:
1012 // [. . . o o x o o o o . . . . . .]
1015 // [. . . . o o o o o o . . . . . .]
1018 self.copy(self.tail + 1, self.tail, i);
1021 (true, false, _) => unsafe {
1022 // contiguous, remove closer to head:
1025 // [. . . o o o o x o o . . . . . .]
1028 // [. . . o o o o o o . . . . . . .]
1031 self.copy(idx, idx + 1, self.head - idx - 1);
1034 (false, true, true) => unsafe {
1035 // discontiguous, remove closer to tail, tail section:
1038 // [o o o o o o . . . . . o o x o o]
1041 // [o o o o o o . . . . . . o o o o]
1044 self.copy(self.tail + 1, self.tail, i);
1045 self.tail = self.wrap_index(self.tail + 1);
1047 (false, false, false) => unsafe {
1048 // discontiguous, remove closer to head, head section:
1051 // [o o o o x o o . . . . . . o o o]
1054 // [o o o o o o . . . . . . . o o o]
1057 self.copy(idx, idx + 1, self.head - idx - 1);
1060 (false, false, true) => unsafe {
1061 // discontiguous, remove closer to head, tail section:
1064 // [o o o . . . . . . o o o o o x o]
1067 // [o o . . . . . . . o o o o o o o]
1070 // or quasi-discontiguous, remove next to head, tail section:
1073 // [. . . . . . . . . o o o o o x o]
1076 // [. . . . . . . . . o o o o o o .]
1079 // draw in elements in the tail section
1080 self.copy(idx, idx + 1, self.cap - idx - 1);
1082 // Prevents underflow.
1084 // copy first element into empty spot
1085 self.copy(self.cap - 1, 0, 1);
1087 // move elements in the head section backwards
1088 self.copy(0, 1, self.head - 1);
1091 self.head = self.wrap_index(self.head - 1);
1093 (false, true, false) => unsafe {
1094 // discontiguous, remove closer to tail, head section:
1097 // [o o x o o o o o o o . . . o o o]
1100 // [o o o o o o o o o o . . . . o o]
1103 // draw in elements up to idx
1104 self.copy(1, 0, idx);
1106 // copy last element into empty spot
1107 self.copy(0, self.cap - 1, 1);
1109 // move elements from tail to end forward, excluding the last one
1110 self.copy(self.tail + 1, self.tail, self.cap - self.tail - 1);
1112 self.tail = self.wrap_index(self.tail + 1);
1120 /// Returns the index in the underlying buffer for a given logical element index.
1122 fn wrap_index(index: uint, size: uint) -> uint {
1123 // size is always a power of 2
1127 /// Calculate the number of elements left to be read in the buffer
1129 fn count(tail: uint, head: uint, size: uint) -> uint {
1130 // size is always a power of 2
1131 (head - tail) & (size - 1)
1134 /// `RingBuf` iterator.
1136 pub struct Iter<'a, T:'a> {
1142 // FIXME(#19839) Remove in favor of `#[deriving(Clone)]`
1143 impl<'a, T> Clone for Iter<'a, T> {
1144 fn clone(&self) -> Iter<'a, T> {
1154 impl<'a, T> Iterator for Iter<'a, T> {
1158 fn next(&mut self) -> Option<&'a T> {
1159 if self.tail == self.head {
1162 let tail = self.tail;
1163 self.tail = wrap_index(self.tail + 1, self.ring.len());
1164 unsafe { Some(self.ring.get_unchecked(tail)) }
1168 fn size_hint(&self) -> (uint, Option<uint>) {
1169 let len = count(self.tail, self.head, self.ring.len());
1175 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
1177 fn next_back(&mut self) -> Option<&'a T> {
1178 if self.tail == self.head {
1181 self.head = wrap_index(self.head - 1, self.ring.len());
1182 unsafe { Some(self.ring.get_unchecked(self.head)) }
1187 impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
1190 impl<'a, T> RandomAccessIterator for Iter<'a, T> {
1192 fn indexable(&self) -> uint {
1193 let (len, _) = self.size_hint();
1198 fn idx(&mut self, j: uint) -> Option<&'a T> {
1199 if j >= self.indexable() {
1202 let idx = wrap_index(self.tail + j, self.ring.len());
1203 unsafe { Some(self.ring.get_unchecked(idx)) }
1208 // FIXME This was implemented differently from Iter because of a problem
1209 // with returning the mutable reference. I couldn't find a way to
1210 // make the lifetime checker happy so, but there should be a way.
1211 /// `RingBuf` mutable iterator.
1213 pub struct IterMut<'a, T:'a> {
1218 marker: marker::ContravariantLifetime<'a>,
1222 impl<'a, T> Iterator for IterMut<'a, T> {
1223 type Item = &'a mut T;
1226 fn next(&mut self) -> Option<&'a mut T> {
1227 if self.tail == self.head {
1230 let tail = self.tail;
1231 self.tail = wrap_index(self.tail + 1, self.cap);
1234 Some(&mut *self.ptr.offset(tail as int))
1239 fn size_hint(&self) -> (uint, Option<uint>) {
1240 let len = count(self.tail, self.head, self.cap);
1246 impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
1248 fn next_back(&mut self) -> Option<&'a mut T> {
1249 if self.tail == self.head {
1252 self.head = wrap_index(self.head - 1, self.cap);
1255 Some(&mut *self.ptr.offset(self.head as int))
1261 impl<'a, T> ExactSizeIterator for IterMut<'a, T> {}
1263 /// A by-value RingBuf iterator
1265 pub struct IntoIter<T> {
1270 impl<T> Iterator for IntoIter<T> {
1274 fn next(&mut self) -> Option<T> {
1275 self.inner.pop_front()
1279 fn size_hint(&self) -> (uint, Option<uint>) {
1280 let len = self.inner.len();
1286 impl<T> DoubleEndedIterator for IntoIter<T> {
1288 fn next_back(&mut self) -> Option<T> {
1289 self.inner.pop_back()
1294 impl<T> ExactSizeIterator for IntoIter<T> {}
1296 /// A draining RingBuf iterator
1297 #[unstable = "matches collection reform specification, waiting for dust to settle"]
1298 pub struct Drain<'a, T: 'a> {
1299 inner: &'a mut RingBuf<T>,
1302 #[unsafe_destructor]
1304 impl<'a, T: 'a> Drop for Drain<'a, T> {
1305 fn drop(&mut self) {
1307 self.inner.head = 0;
1308 self.inner.tail = 0;
1313 impl<'a, T: 'a> Iterator for Drain<'a, T> {
1317 fn next(&mut self) -> Option<T> {
1318 self.inner.pop_front()
1322 fn size_hint(&self) -> (uint, Option<uint>) {
1323 let len = self.inner.len();
1329 impl<'a, T: 'a> DoubleEndedIterator for Drain<'a, T> {
1331 fn next_back(&mut self) -> Option<T> {
1332 self.inner.pop_back()
1337 impl<'a, T: 'a> ExactSizeIterator for Drain<'a, T> {}
1340 impl<A: PartialEq> PartialEq for RingBuf<A> {
1341 fn eq(&self, other: &RingBuf<A>) -> bool {
1342 self.len() == other.len() &&
1343 self.iter().zip(other.iter()).all(|(a, b)| a.eq(b))
1348 impl<A: Eq> Eq for RingBuf<A> {}
1351 impl<A: PartialOrd> PartialOrd for RingBuf<A> {
1352 fn partial_cmp(&self, other: &RingBuf<A>) -> Option<Ordering> {
1353 iter::order::partial_cmp(self.iter(), other.iter())
1358 impl<A: Ord> Ord for RingBuf<A> {
1360 fn cmp(&self, other: &RingBuf<A>) -> Ordering {
1361 iter::order::cmp(self.iter(), other.iter())
1366 impl<S: Writer, A: Hash<S>> Hash<S> for RingBuf<A> {
1367 fn hash(&self, state: &mut S) {
1368 self.len().hash(state);
1369 for elt in self.iter() {
1375 // NOTE(stage0): remove impl after a snapshot
1378 impl<A> Index<uint, A> for RingBuf<A> {
1380 fn index<'a>(&'a self, i: &uint) -> &'a A {
1381 self.get(*i).expect("Out of bounds access")
1385 #[cfg(not(stage0))] // NOTE(stage0): remove cfg after a snapshot
1387 impl<A> Index<uint> for RingBuf<A> {
1391 fn index<'a>(&'a self, i: &uint) -> &'a A {
1392 self.get(*i).expect("Out of bounds access")
1396 // NOTE(stage0): remove impl after a snapshot
1399 impl<A> IndexMut<uint, A> for RingBuf<A> {
1401 fn index_mut<'a>(&'a mut self, i: &uint) -> &'a mut A {
1402 self.get_mut(*i).expect("Out of bounds access")
1406 #[cfg(not(stage0))] // NOTE(stage0): remove cfg after a snapshot
1408 impl<A> IndexMut<uint> for RingBuf<A> {
1412 fn index_mut<'a>(&'a mut self, i: &uint) -> &'a mut A {
1413 self.get_mut(*i).expect("Out of bounds access")
1418 impl<A> FromIterator<A> for RingBuf<A> {
1419 fn from_iter<T: Iterator<Item=A>>(iterator: T) -> RingBuf<A> {
1420 let (lower, _) = iterator.size_hint();
1421 let mut deq = RingBuf::with_capacity(lower);
1422 deq.extend(iterator);
1428 impl<A> Extend<A> for RingBuf<A> {
1429 fn extend<T: Iterator<Item=A>>(&mut self, mut iterator: T) {
1430 for elt in iterator {
1431 self.push_back(elt);
1437 impl<T: fmt::Show> fmt::Show for RingBuf<T> {
1438 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1439 try!(write!(f, "["));
1441 for (i, e) in self.iter().enumerate() {
1442 if i != 0 { try!(write!(f, ", ")); }
1443 try!(write!(f, "{}", *e));
1453 use self::Taggypar::*;
1465 #[allow(deprecated)]
1467 let mut d = RingBuf::new();
1468 assert_eq!(d.len(), 0u);
1472 assert_eq!(d.len(), 3u);
1474 assert_eq!(d.len(), 4u);
1475 debug!("{}", d.front());
1476 assert_eq!(*d.front().unwrap(), 42);
1477 debug!("{}", d.back());
1478 assert_eq!(*d.back().unwrap(), 137);
1479 let mut i = d.pop_front();
1481 assert_eq!(i, Some(42));
1484 assert_eq!(i, Some(137));
1487 assert_eq!(i, Some(137));
1490 assert_eq!(i, Some(17));
1491 assert_eq!(d.len(), 0u);
1493 assert_eq!(d.len(), 1u);
1495 assert_eq!(d.len(), 2u);
1497 assert_eq!(d.len(), 3u);
1499 assert_eq!(d.len(), 4u);
1504 assert_eq!(d[0], 1);
1505 assert_eq!(d[1], 2);
1506 assert_eq!(d[2], 3);
1507 assert_eq!(d[3], 4);
1511 fn test_parameterized<T:Clone + PartialEq + Show>(a: T, b: T, c: T, d: T) {
1512 let mut deq = RingBuf::new();
1513 assert_eq!(deq.len(), 0);
1514 deq.push_front(a.clone());
1515 deq.push_front(b.clone());
1516 deq.push_back(c.clone());
1517 assert_eq!(deq.len(), 3);
1518 deq.push_back(d.clone());
1519 assert_eq!(deq.len(), 4);
1520 assert_eq!((*deq.front().unwrap()).clone(), b.clone());
1521 assert_eq!((*deq.back().unwrap()).clone(), d.clone());
1522 assert_eq!(deq.pop_front().unwrap(), b.clone());
1523 assert_eq!(deq.pop_back().unwrap(), d.clone());
1524 assert_eq!(deq.pop_back().unwrap(), c.clone());
1525 assert_eq!(deq.pop_back().unwrap(), a.clone());
1526 assert_eq!(deq.len(), 0);
1527 deq.push_back(c.clone());
1528 assert_eq!(deq.len(), 1);
1529 deq.push_front(b.clone());
1530 assert_eq!(deq.len(), 2);
1531 deq.push_back(d.clone());
1532 assert_eq!(deq.len(), 3);
1533 deq.push_front(a.clone());
1534 assert_eq!(deq.len(), 4);
1535 assert_eq!(deq[0].clone(), a.clone());
1536 assert_eq!(deq[1].clone(), b.clone());
1537 assert_eq!(deq[2].clone(), c.clone());
1538 assert_eq!(deq[3].clone(), d.clone());
1542 fn test_push_front_grow() {
1543 let mut deq = RingBuf::new();
1544 for i in range(0u, 66) {
1547 assert_eq!(deq.len(), 66);
1549 for i in range(0u, 66) {
1550 assert_eq!(deq[i], 65 - i);
1553 let mut deq = RingBuf::new();
1554 for i in range(0u, 66) {
1558 for i in range(0u, 66) {
1559 assert_eq!(deq[i], i);
1565 let mut deq = RingBuf::new();
1566 for i in range(1u, 4) {
1569 assert_eq!(deq[1], 2);
1574 fn test_index_out_of_bounds() {
1575 let mut deq = RingBuf::new();
1576 for i in range(1u, 4) {
1583 fn bench_new(b: &mut test::Bencher) {
1585 let ring: RingBuf<u64> = RingBuf::new();
1586 test::black_box(ring);
1591 fn bench_push_back_100(b: &mut test::Bencher) {
1592 let mut deq = RingBuf::with_capacity(101);
1594 for i in range(0i, 100) {
1603 fn bench_push_front_100(b: &mut test::Bencher) {
1604 let mut deq = RingBuf::with_capacity(101);
1606 for i in range(0i, 100) {
1615 fn bench_pop_back_100(b: &mut test::Bencher) {
1616 let mut deq: RingBuf<int> = RingBuf::with_capacity(101);
1621 while !deq.is_empty() {
1622 test::black_box(deq.pop_back());
1628 fn bench_pop_front_100(b: &mut test::Bencher) {
1629 let mut deq: RingBuf<int> = RingBuf::with_capacity(101);
1634 while !deq.is_empty() {
1635 test::black_box(deq.pop_front());
1641 fn bench_grow_1025(b: &mut test::Bencher) {
1643 let mut deq = RingBuf::new();
1644 for i in range(0i, 1025) {
1647 test::black_box(deq);
1652 fn bench_iter_1000(b: &mut test::Bencher) {
1653 let ring: RingBuf<int> = range(0i, 1000).collect();
1657 for &i in ring.iter() {
1660 test::black_box(sum);
1665 fn bench_mut_iter_1000(b: &mut test::Bencher) {
1666 let mut ring: RingBuf<int> = range(0i, 1000).collect();
1670 for i in ring.iter_mut() {
1673 test::black_box(sum);
1677 #[deriving(Clone, PartialEq, Show)]
1681 Three(int, int, int),
1684 #[deriving(Clone, PartialEq, Show)]
1688 Threepar(int, int, int),
1691 #[deriving(Clone, PartialEq, Show)]
1699 fn test_param_int() {
1700 test_parameterized::<int>(5, 72, 64, 175);
1704 fn test_param_taggy() {
1705 test_parameterized::<Taggy>(One(1), Two(1, 2), Three(1, 2, 3), Two(17, 42));
1709 fn test_param_taggypar() {
1710 test_parameterized::<Taggypar<int>>(Onepar::<int>(1),
1711 Twopar::<int>(1, 2),
1712 Threepar::<int>(1, 2, 3),
1713 Twopar::<int>(17, 42));
1717 fn test_param_reccy() {
1718 let reccy1 = RecCy { x: 1, y: 2, t: One(1) };
1719 let reccy2 = RecCy { x: 345, y: 2, t: Two(1, 2) };
1720 let reccy3 = RecCy { x: 1, y: 777, t: Three(1, 2, 3) };
1721 let reccy4 = RecCy { x: 19, y: 252, t: Two(17, 42) };
1722 test_parameterized::<RecCy>(reccy1, reccy2, reccy3, reccy4);
1726 fn test_with_capacity() {
1727 let mut d = RingBuf::with_capacity(0);
1729 assert_eq!(d.len(), 1);
1730 let mut d = RingBuf::with_capacity(50);
1732 assert_eq!(d.len(), 1);
1736 fn test_with_capacity_non_power_two() {
1737 let mut d3 = RingBuf::with_capacity(3);
1742 assert_eq!(d3.pop_front(), Some(1));
1744 assert_eq!(d3.front(), None);
1751 assert_eq!(d3.pop_front(), Some(3));
1753 // Pushing the lo past half way point to trigger
1754 // the 'B' scenario for growth
1761 // There used to be a bug here about how the
1762 // RingBuf made growth assumptions about the
1763 // underlying Vec which didn't hold and lead
1765 // (Vec grows to next power of two)
1766 //good- [9, 12, 15, X, X, X, X, |6]
1767 //bug- [15, 12, X, X, X, |6, X, X]
1768 assert_eq!(d3.pop_front(), Some(6));
1770 // Which leads us to the following state which
1771 // would be a failure case.
1772 //bug- [15, 12, X, X, X, X, |X, X]
1773 assert_eq!(d3.front(), Some(&9));
1777 fn test_reserve_exact() {
1778 let mut d = RingBuf::new();
1780 d.reserve_exact(50);
1781 assert!(d.capacity() >= 51);
1782 let mut d = RingBuf::new();
1784 d.reserve_exact(50);
1785 assert!(d.capacity() >= 51);
1790 let mut d = RingBuf::new();
1793 assert!(d.capacity() >= 51);
1794 let mut d = RingBuf::new();
1797 assert!(d.capacity() >= 51);
1802 let mut d: RingBuf<int> = range(0i, 5).collect();
1805 assert_eq!(d.iter().map(|&x|x).collect::<Vec<int>>(), vec!(4, 2, 3, 1));
1810 let mut d = RingBuf::new();
1811 assert_eq!(d.iter().next(), None);
1812 assert_eq!(d.iter().size_hint(), (0, Some(0)));
1814 for i in range(0i, 5) {
1818 let b: &[_] = &[&0,&1,&2,&3,&4];
1819 assert_eq!(d.iter().collect::<Vec<&int>>(), b);
1822 for i in range(6i, 9) {
1826 let b: &[_] = &[&8,&7,&6,&0,&1,&2,&3,&4];
1827 assert_eq!(d.iter().collect::<Vec<&int>>(), b);
1830 let mut it = d.iter();
1831 let mut len = d.len();
1835 _ => { len -= 1; assert_eq!(it.size_hint(), (len, Some(len))) }
1841 fn test_rev_iter() {
1842 let mut d = RingBuf::new();
1843 assert_eq!(d.iter().rev().next(), None);
1845 for i in range(0i, 5) {
1849 let b: &[_] = &[&4,&3,&2,&1,&0];
1850 assert_eq!(d.iter().rev().collect::<Vec<&int>>(), b);
1853 for i in range(6i, 9) {
1856 let b: &[_] = &[&4,&3,&2,&1,&0,&6,&7,&8];
1857 assert_eq!(d.iter().rev().collect::<Vec<&int>>(), b);
1861 fn test_mut_rev_iter_wrap() {
1862 let mut d = RingBuf::with_capacity(3);
1863 assert!(d.iter_mut().rev().next().is_none());
1868 assert_eq!(d.pop_front(), Some(1));
1871 assert_eq!(d.iter_mut().rev().map(|x| *x).collect::<Vec<int>>(),
1876 fn test_mut_iter() {
1877 let mut d = RingBuf::new();
1878 assert!(d.iter_mut().next().is_none());
1880 for i in range(0u, 3) {
1884 for (i, elt) in d.iter_mut().enumerate() {
1885 assert_eq!(*elt, 2 - i);
1890 let mut it = d.iter_mut();
1891 assert_eq!(*it.next().unwrap(), 0);
1892 assert_eq!(*it.next().unwrap(), 1);
1893 assert_eq!(*it.next().unwrap(), 2);
1894 assert!(it.next().is_none());
1899 fn test_mut_rev_iter() {
1900 let mut d = RingBuf::new();
1901 assert!(d.iter_mut().rev().next().is_none());
1903 for i in range(0u, 3) {
1907 for (i, elt) in d.iter_mut().rev().enumerate() {
1908 assert_eq!(*elt, i);
1913 let mut it = d.iter_mut().rev();
1914 assert_eq!(*it.next().unwrap(), 0);
1915 assert_eq!(*it.next().unwrap(), 1);
1916 assert_eq!(*it.next().unwrap(), 2);
1917 assert!(it.next().is_none());
1922 fn test_into_iter() {
1926 let d: RingBuf<int> = RingBuf::new();
1927 let mut iter = d.into_iter();
1929 assert_eq!(iter.size_hint(), (0, Some(0)));
1930 assert_eq!(iter.next(), None);
1931 assert_eq!(iter.size_hint(), (0, Some(0)));
1936 let mut d = RingBuf::new();
1937 for i in range(0i, 5) {
1941 let b = vec![0,1,2,3,4];
1942 assert_eq!(d.into_iter().collect::<Vec<int>>(), b);
1947 let mut d = RingBuf::new();
1948 for i in range(0i, 5) {
1951 for i in range(6, 9) {
1955 let b = vec![8,7,6,0,1,2,3,4];
1956 assert_eq!(d.into_iter().collect::<Vec<int>>(), b);
1961 let mut d = RingBuf::new();
1962 for i in range(0i, 5) {
1965 for i in range(6, 9) {
1969 let mut it = d.into_iter();
1970 assert_eq!(it.size_hint(), (8, Some(8)));
1971 assert_eq!(it.next(), Some(8));
1972 assert_eq!(it.size_hint(), (7, Some(7)));
1973 assert_eq!(it.next_back(), Some(4));
1974 assert_eq!(it.size_hint(), (6, Some(6)));
1975 assert_eq!(it.next(), Some(7));
1976 assert_eq!(it.size_hint(), (5, Some(5)));
1985 let mut d: RingBuf<int> = RingBuf::new();
1988 let mut iter = d.drain();
1990 assert_eq!(iter.size_hint(), (0, Some(0)));
1991 assert_eq!(iter.next(), None);
1992 assert_eq!(iter.size_hint(), (0, Some(0)));
1995 assert!(d.is_empty());
2000 let mut d = RingBuf::new();
2001 for i in range(0i, 5) {
2005 assert_eq!(d.drain().collect::<Vec<int>>(), [0, 1, 2, 3, 4]);
2006 assert!(d.is_empty());
2011 let mut d = RingBuf::new();
2012 for i in range(0i, 5) {
2015 for i in range(6, 9) {
2019 assert_eq!(d.drain().collect::<Vec<int>>(), [8,7,6,0,1,2,3,4]);
2020 assert!(d.is_empty());
2025 let mut d = RingBuf::new();
2026 for i in range(0i, 5) {
2029 for i in range(6, 9) {
2034 let mut it = d.drain();
2035 assert_eq!(it.size_hint(), (8, Some(8)));
2036 assert_eq!(it.next(), Some(8));
2037 assert_eq!(it.size_hint(), (7, Some(7)));
2038 assert_eq!(it.next_back(), Some(4));
2039 assert_eq!(it.size_hint(), (6, Some(6)));
2040 assert_eq!(it.next(), Some(7));
2041 assert_eq!(it.size_hint(), (5, Some(5)));
2043 assert!(d.is_empty());
2048 fn test_from_iter() {
2050 let v = vec!(1i,2,3,4,5,6,7);
2051 let deq: RingBuf<int> = v.iter().map(|&x| x).collect();
2052 let u: Vec<int> = deq.iter().map(|&x| x).collect();
2055 let seq = iter::count(0u, 2).take(256);
2056 let deq: RingBuf<uint> = seq.collect();
2057 for (i, &x) in deq.iter().enumerate() {
2060 assert_eq!(deq.len(), 256);
2065 let mut d = RingBuf::new();
2070 assert_eq!(d.len(), 4u);
2071 let mut e = d.clone();
2072 assert_eq!(e.len(), 4u);
2073 while !d.is_empty() {
2074 assert_eq!(d.pop_back(), e.pop_back());
2076 assert_eq!(d.len(), 0u);
2077 assert_eq!(e.len(), 0u);
2082 let mut d = RingBuf::new();
2083 assert!(d == RingBuf::with_capacity(0));
2088 let mut e = RingBuf::with_capacity(0);
2098 assert!(e == RingBuf::new());
2103 let mut x = RingBuf::new();
2104 let mut y = RingBuf::new();
2116 assert!(hash::hash(&x) == hash::hash(&y));
2121 let x = RingBuf::new();
2122 let mut y = RingBuf::new();
2134 let ringbuf: RingBuf<int> = range(0i, 10).collect();
2135 assert!(format!("{}", ringbuf) == "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]");
2137 let ringbuf: RingBuf<&str> = vec!["just", "one", "test", "more"].iter()
2140 assert!(format!("{}", ringbuf) == "[just, one, test, more]");
2145 static mut drops: uint = 0;
2147 impl Drop for Elem {
2148 fn drop(&mut self) {
2149 unsafe { drops += 1; }
2153 let mut ring = RingBuf::new();
2154 ring.push_back(Elem);
2155 ring.push_front(Elem);
2156 ring.push_back(Elem);
2157 ring.push_front(Elem);
2160 assert_eq!(unsafe {drops}, 4);
2164 fn test_drop_with_pop() {
2165 static mut drops: uint = 0;
2167 impl Drop for Elem {
2168 fn drop(&mut self) {
2169 unsafe { drops += 1; }
2173 let mut ring = RingBuf::new();
2174 ring.push_back(Elem);
2175 ring.push_front(Elem);
2176 ring.push_back(Elem);
2177 ring.push_front(Elem);
2179 drop(ring.pop_back());
2180 drop(ring.pop_front());
2181 assert_eq!(unsafe {drops}, 2);
2184 assert_eq!(unsafe {drops}, 4);
2188 fn test_drop_clear() {
2189 static mut drops: uint = 0;
2191 impl Drop for Elem {
2192 fn drop(&mut self) {
2193 unsafe { drops += 1; }
2197 let mut ring = RingBuf::new();
2198 ring.push_back(Elem);
2199 ring.push_front(Elem);
2200 ring.push_back(Elem);
2201 ring.push_front(Elem);
2203 assert_eq!(unsafe {drops}, 4);
2206 assert_eq!(unsafe {drops}, 4);
2210 fn test_reserve_grow() {
2211 // test growth path A
2212 // [T o o H] -> [T o o H . . . . ]
2213 let mut ring = RingBuf::with_capacity(4);
2214 for i in range(0i, 3) {
2218 for i in range(0i, 3) {
2219 assert_eq!(ring.pop_front(), Some(i));
2222 // test growth path B
2223 // [H T o o] -> [. T o o H . . . ]
2224 let mut ring = RingBuf::with_capacity(4);
2225 for i in range(0i, 1) {
2227 assert_eq!(ring.pop_front(), Some(i));
2229 for i in range(0i, 3) {
2233 for i in range(0i, 3) {
2234 assert_eq!(ring.pop_front(), Some(i));
2237 // test growth path C
2238 // [o o H T] -> [o o H . . . . T ]
2239 let mut ring = RingBuf::with_capacity(4);
2240 for i in range(0i, 3) {
2242 assert_eq!(ring.pop_front(), Some(i));
2244 for i in range(0i, 3) {
2248 for i in range(0i, 3) {
2249 assert_eq!(ring.pop_front(), Some(i));
2255 let mut ring = RingBuf::new();
2257 assert_eq!(ring.get(0), Some(&0));
2258 assert_eq!(ring.get(1), None);
2261 assert_eq!(ring.get(0), Some(&0));
2262 assert_eq!(ring.get(1), Some(&1));
2263 assert_eq!(ring.get(2), None);
2266 assert_eq!(ring.get(0), Some(&0));
2267 assert_eq!(ring.get(1), Some(&1));
2268 assert_eq!(ring.get(2), Some(&2));
2269 assert_eq!(ring.get(3), None);
2271 assert_eq!(ring.pop_front(), Some(0));
2272 assert_eq!(ring.get(0), Some(&1));
2273 assert_eq!(ring.get(1), Some(&2));
2274 assert_eq!(ring.get(2), None);
2276 assert_eq!(ring.pop_front(), Some(1));
2277 assert_eq!(ring.get(0), Some(&2));
2278 assert_eq!(ring.get(1), None);
2280 assert_eq!(ring.pop_front(), Some(2));
2281 assert_eq!(ring.get(0), None);
2282 assert_eq!(ring.get(1), None);
2287 let mut ring = RingBuf::new();
2288 for i in range(0i, 3) {
2292 match ring.get_mut(1) {
2297 assert_eq!(ring.get_mut(0), Some(&mut 0));
2298 assert_eq!(ring.get_mut(1), Some(&mut -1));
2299 assert_eq!(ring.get_mut(2), Some(&mut 2));
2300 assert_eq!(ring.get_mut(3), None);
2302 assert_eq!(ring.pop_front(), Some(0));
2303 assert_eq!(ring.get_mut(0), Some(&mut -1));
2304 assert_eq!(ring.get_mut(1), Some(&mut 2));
2305 assert_eq!(ring.get_mut(2), None);
2310 // This test checks that every single combination of tail position, length, and
2311 // insertion position is tested. Capacity 15 should be large enough to cover every case.
2313 let mut tester = RingBuf::with_capacity(15);
2314 // can't guarantee we got 15, so have to get what we got.
2315 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2316 // this test isn't covering what it wants to
2317 let cap = tester.capacity();
2320 // len is the length *after* insertion
2321 for len in range(1, cap) {
2322 // 0, 1, 2, .., len - 1
2323 let expected = iter::count(0, 1).take(len).collect();
2324 for tail_pos in range(0, cap) {
2325 for to_insert in range(0, len) {
2326 tester.tail = tail_pos;
2327 tester.head = tail_pos;
2328 for i in range(0, len) {
2330 tester.push_back(i);
2333 tester.insert(to_insert, to_insert);
2334 assert!(tester.tail < tester.cap);
2335 assert!(tester.head < tester.cap);
2336 assert_eq!(tester, expected);
2344 // This test checks that every single combination of tail position, length, and
2345 // removal position is tested. Capacity 15 should be large enough to cover every case.
2347 let mut tester = RingBuf::with_capacity(15);
2348 // can't guarantee we got 15, so have to get what we got.
2349 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2350 // this test isn't covering what it wants to
2351 let cap = tester.capacity();
2353 // len is the length *after* removal
2354 for len in range(0, cap - 1) {
2355 // 0, 1, 2, .., len - 1
2356 let expected = iter::count(0, 1).take(len).collect();
2357 for tail_pos in range(0, cap) {
2358 for to_remove in range(0, len + 1) {
2359 tester.tail = tail_pos;
2360 tester.head = tail_pos;
2361 for i in range(0, len) {
2363 tester.push_back(1234);
2365 tester.push_back(i);
2367 if to_remove == len {
2368 tester.push_back(1234);
2370 tester.remove(to_remove);
2371 assert!(tester.tail < tester.cap);
2372 assert!(tester.head < tester.cap);
2373 assert_eq!(tester, expected);
2381 let mut ring = RingBuf::new();
2382 ring.push_back(10i);
2383 ring.push_back(20i);
2384 assert_eq!(ring.front(), Some(&10));
2386 assert_eq!(ring.front(), Some(&20));
2388 assert_eq!(ring.front(), None);
2392 fn test_as_slices() {
2393 let mut ring: RingBuf<int> = RingBuf::with_capacity(127);
2394 let cap = ring.capacity() as int;
2396 let last = cap - first;
2397 for i in range(0, first) {
2400 let (left, right) = ring.as_slices();
2401 let expected: Vec<_> = range(0, i+1).collect();
2402 assert_eq!(left, expected);
2403 assert_eq!(right, []);
2406 for j in range(-last, 0) {
2408 let (left, right) = ring.as_slices();
2409 let expected_left: Vec<_> = range(-last, j+1).rev().collect();
2410 let expected_right: Vec<_> = range(0, first).collect();
2411 assert_eq!(left, expected_left);
2412 assert_eq!(right, expected_right);
2415 assert_eq!(ring.len() as int, cap);
2416 assert_eq!(ring.capacity() as int, cap);
2420 fn test_as_mut_slices() {
2421 let mut ring: RingBuf<int> = RingBuf::with_capacity(127);
2422 let cap = ring.capacity() as int;
2424 let last = cap - first;
2425 for i in range(0, first) {
2428 let (left, right) = ring.as_mut_slices();
2429 let expected: Vec<_> = range(0, i+1).collect();
2430 assert_eq!(left, expected);
2431 assert_eq!(right, []);
2434 for j in range(-last, 0) {
2436 let (left, right) = ring.as_mut_slices();
2437 let expected_left: Vec<_> = range(-last, j+1).rev().collect();
2438 let expected_right: Vec<_> = range(0, first).collect();
2439 assert_eq!(left, expected_left);
2440 assert_eq!(right, expected_right);
2443 assert_eq!(ring.len() as int, cap);
2444 assert_eq!(ring.capacity() as int, cap);