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, which can be used as a double-ended queue efficiently.
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.
52 impl<T: Clone> Clone for RingBuf<T> {
53 fn clone(&self) -> RingBuf<T> {
54 self.iter().map(|t| t.clone()).collect()
59 impl<T> Drop for RingBuf<T> {
63 if mem::size_of::<T>() != 0 {
64 heap::deallocate(self.ptr as *mut u8,
65 self.cap * mem::size_of::<T>(),
66 mem::min_align_of::<T>())
73 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<'a>(&'a self) -> &'a [T] {
83 mem::transmute(RawSlice { data: self.ptr as *const T, len: self.cap })
86 /// Turn ptr into a mut slice
88 unsafe fn buffer_as_mut_slice<'a>(&'a mut self) -> &'a mut [T] {
89 mem::transmute(RawSlice { data: self.ptr as *const T, len: self.cap })
92 /// Moves an element out of the buffer
94 unsafe fn buffer_read(&mut self, off: uint) -> T {
95 ptr::read(self.ptr.offset(off as int) as *const T)
98 /// Writes an element into the buffer, moving it.
100 unsafe fn buffer_write(&mut self, off: uint, t: T) {
101 ptr::write(self.ptr.offset(off as int), t);
104 /// Returns true iff the buffer is at capacity
106 fn is_full(&self) -> bool { self.cap - self.len() == 1 }
108 /// Returns the index in the underlying buffer for a given logical element index.
110 fn wrap_index(&self, idx: uint) -> uint { wrap_index(idx, self.cap) }
112 /// Copies a contiguous block of memory len long from src to dst
114 unsafe fn copy(&self, dst: uint, src: uint, len: uint) {
115 debug_assert!(dst + len <= self.cap, "dst={} src={} len={} cap={}", dst, src, len,
117 debug_assert!(src + len <= self.cap, "dst={} src={} len={} cap={}", dst, src, len,
120 self.ptr.offset(dst as int),
121 self.ptr.offset(src as int) as *const T,
127 /// Creates an empty `RingBuf`.
128 #[unstable = "matches collection reform specification, waiting for dust to settle"]
129 pub fn new() -> RingBuf<T> {
130 RingBuf::with_capacity(INITIAL_CAPACITY)
133 /// Creates an empty `RingBuf` with space for at least `n` elements.
134 #[unstable = "matches collection reform specification, waiting for dust to settle"]
135 pub fn with_capacity(n: uint) -> RingBuf<T> {
136 // +1 since the ringbuffer always leaves one space empty
137 let cap = cmp::max(n + 1, MINIMUM_CAPACITY).next_power_of_two();
138 let size = cap.checked_mul(mem::size_of::<T>())
139 .expect("capacity overflow");
141 let ptr = if mem::size_of::<T>() != 0 {
143 let ptr = heap::allocate(size, mem::min_align_of::<T>()) as *mut T;;
144 if ptr.is_null() { ::alloc::oom() }
148 heap::EMPTY as *mut T
159 /// Retrieves an element in the `RingBuf` by index.
164 /// use std::collections::RingBuf;
166 /// let mut buf = RingBuf::new();
167 /// buf.push_back(3i);
168 /// buf.push_back(4);
169 /// buf.push_back(5);
170 /// assert_eq!(buf.get(1).unwrap(), &4);
172 #[unstable = "matches collection reform specification, waiting for dust to settle"]
173 pub fn get(&self, i: uint) -> Option<&T> {
175 let idx = self.wrap_index(self.tail + i);
176 unsafe { Some(&*self.ptr.offset(idx as int)) }
182 /// Retrieves an element in the `RingBuf` mutably by index.
187 /// use std::collections::RingBuf;
189 /// let mut buf = RingBuf::new();
190 /// buf.push_back(3i);
191 /// buf.push_back(4);
192 /// buf.push_back(5);
193 /// match buf.get_mut(1) {
200 /// assert_eq!(buf[1], 7);
202 #[unstable = "matches collection reform specification, waiting for dust to settle"]
203 pub fn get_mut(&mut self, i: uint) -> Option<&mut T> {
205 let idx = self.wrap_index(self.tail + i);
206 unsafe { Some(&mut *self.ptr.offset(idx as int)) }
212 /// Swaps elements at indices `i` and `j`.
214 /// `i` and `j` may be equal.
216 /// Fails if there is no element with either index.
221 /// use std::collections::RingBuf;
223 /// let mut buf = RingBuf::new();
224 /// buf.push_back(3i);
225 /// buf.push_back(4);
226 /// buf.push_back(5);
228 /// assert_eq!(buf[0], 5);
229 /// assert_eq!(buf[2], 3);
232 pub fn swap(&mut self, i: uint, j: uint) {
233 assert!(i < self.len());
234 assert!(j < self.len());
235 let ri = self.wrap_index(self.tail + i);
236 let rj = self.wrap_index(self.tail + j);
238 ptr::swap(self.ptr.offset(ri as int), self.ptr.offset(rj as int))
242 /// Returns the number of elements the `RingBuf` can hold without
248 /// use std::collections::RingBuf;
250 /// let buf: RingBuf<int> = RingBuf::with_capacity(10);
251 /// assert!(buf.capacity() >= 10);
254 #[unstable = "matches collection reform specification, waiting for dust to settle"]
255 pub fn capacity(&self) -> uint { self.cap - 1 }
257 /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the
258 /// given `RingBuf`. Does nothing if the capacity is already sufficient.
260 /// Note that the allocator may give the collection more space than it requests. Therefore
261 /// capacity can not be relied upon to be precisely minimal. Prefer `reserve` if future
262 /// insertions are expected.
266 /// Panics if the new capacity overflows `uint`.
271 /// use std::collections::RingBuf;
273 /// let mut buf: RingBuf<int> = vec![1].into_iter().collect();
274 /// buf.reserve_exact(10);
275 /// assert!(buf.capacity() >= 11);
277 #[unstable = "matches collection reform specification, waiting for dust to settle"]
278 pub fn reserve_exact(&mut self, additional: uint) {
279 self.reserve(additional);
282 /// Reserves capacity for at least `additional` more elements to be inserted in the given
283 /// `Ringbuf`. The collection may reserve more space to avoid frequent reallocations.
287 /// Panics if the new capacity overflows `uint`.
292 /// use std::collections::RingBuf;
294 /// let mut buf: RingBuf<int> = vec![1].into_iter().collect();
296 /// assert!(buf.capacity() >= 11);
298 #[unstable = "matches collection reform specification, waiting for dust to settle"]
299 pub fn reserve(&mut self, additional: uint) {
300 let new_len = self.len() + additional;
301 assert!(new_len + 1 > self.len(), "capacity overflow");
302 if new_len > self.capacity() {
303 let count = (new_len + 1).next_power_of_two();
304 assert!(count >= new_len + 1);
306 if mem::size_of::<T>() != 0 {
307 let old = self.cap * mem::size_of::<T>();
308 let new = count.checked_mul(mem::size_of::<T>())
309 .expect("capacity overflow");
311 self.ptr = heap::reallocate(self.ptr as *mut u8,
314 mem::min_align_of::<T>()) as *mut T;
315 if self.ptr.is_null() { ::alloc::oom() }
319 // Move the shortest contiguous section of the ring buffer
321 // [o o o o o o o . ]
323 // A [o o o o o o o . . . . . . . . . ]
325 // [o o . o o o o o ]
327 // B [. . . o o o o o o o . . . . . . ]
329 // [o o o o o . o o ]
331 // C [o o o o o . . . . . . . . . o o ]
333 let oldcap = self.cap;
336 if self.tail <= self.head { // A
338 } else if self.head < oldcap - self.tail { // B
340 ptr::copy_nonoverlapping_memory(
341 self.ptr.offset(oldcap as int),
342 self.ptr as *const T,
347 debug_assert!(self.head > self.tail);
350 ptr::copy_nonoverlapping_memory(
351 self.ptr.offset((count - (oldcap - self.tail)) as int),
352 self.ptr.offset(self.tail as int) as *const T,
356 self.tail = count - (oldcap - self.tail);
357 debug_assert!(self.head < self.tail);
359 debug_assert!(self.head < self.cap);
360 debug_assert!(self.tail < self.cap);
361 debug_assert!(self.cap.count_ones() == 1);
365 /// Returns a front-to-back iterator.
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 /// let b: &[_] = &[&5, &3, &4];
377 /// assert_eq!(buf.iter().collect::<Vec<&int>>().as_slice(), b);
379 #[unstable = "matches collection reform specification, waiting for dust to settle"]
380 pub fn iter(&self) -> Iter<T> {
384 ring: unsafe { self.buffer_as_slice() }
388 /// Returns a front-to-back iterator that returns mutable references.
393 /// use std::collections::RingBuf;
395 /// let mut buf = RingBuf::new();
396 /// buf.push_back(5i);
397 /// buf.push_back(3);
398 /// buf.push_back(4);
399 /// for num in buf.iter_mut() {
402 /// let b: &[_] = &[&mut 3, &mut 1, &mut 2];
403 /// assert_eq!(buf.iter_mut().collect::<Vec<&mut int>>()[], b);
405 #[unstable = "matches collection reform specification, waiting for dust to settle"]
406 pub fn iter_mut<'a>(&'a mut self) -> IterMut<'a, T> {
412 marker: marker::ContravariantLifetime::<'a>,
416 /// Consumes the list into an iterator yielding elements by value.
417 #[unstable = "matches collection reform specification, waiting for dust to settle"]
418 pub fn into_iter(self) -> IntoIter<T> {
424 /// Returns a pair of slices which contain, in order, the contents of the
427 #[unstable = "matches collection reform specification, waiting for dust to settle"]
428 pub fn as_slices<'a>(&'a self) -> (&'a [T], &'a [T]) {
430 let contiguous = self.is_contiguous();
431 let buf = self.buffer_as_slice();
433 let (empty, buf) = buf.split_at(0);
434 (buf[self.tail..self.head], empty)
436 let (mid, right) = buf.split_at(self.tail);
437 let (left, _) = mid.split_at(self.head);
443 /// Returns a pair of slices which contain, in order, the contents of the
446 #[unstable = "matches collection reform specification, waiting for dust to settle"]
447 pub fn as_mut_slices<'a>(&'a mut self) -> (&'a mut [T], &'a mut [T]) {
449 let contiguous = self.is_contiguous();
450 let head = self.head;
451 let tail = self.tail;
452 let buf = self.buffer_as_mut_slice();
455 let (empty, buf) = buf.split_at_mut(0);
456 (buf.slice_mut(tail, head), empty)
458 let (mid, right) = buf.split_at_mut(tail);
459 let (left, _) = mid.split_at_mut(head);
466 /// Returns the number of elements in the `RingBuf`.
471 /// use std::collections::RingBuf;
473 /// let mut v = RingBuf::new();
474 /// assert_eq!(v.len(), 0);
476 /// assert_eq!(v.len(), 1);
478 #[unstable = "matches collection reform specification, waiting for dust to settle"]
479 pub fn len(&self) -> uint { count(self.tail, self.head, self.cap) }
481 /// Returns true if the buffer contains no elements
486 /// use std::collections::RingBuf;
488 /// let mut v = RingBuf::new();
489 /// assert!(v.is_empty());
490 /// v.push_front(1i);
491 /// assert!(!v.is_empty());
493 #[unstable = "matches collection reform specification, waiting for dust to settle"]
494 pub fn is_empty(&self) -> bool { self.len() == 0 }
496 /// Creates a draining iterator that clears the `RingBuf` and iterates over
497 /// the removed items from start to end.
502 /// use std::collections::RingBuf;
504 /// let mut v = RingBuf::new();
506 /// assert_eq!(v.drain().next(), Some(1));
507 /// assert!(v.is_empty());
510 #[unstable = "matches collection reform specification, waiting for dust to settle"]
511 pub fn drain<'a>(&'a mut self) -> Drain<'a, T> {
517 /// Clears the buffer, removing all values.
522 /// use std::collections::RingBuf;
524 /// let mut v = RingBuf::new();
527 /// assert!(v.is_empty());
529 #[unstable = "matches collection reform specification, waiting for dust to settle"]
531 pub fn clear(&mut self) {
535 /// Provides a reference to the front element, or `None` if the sequence is
541 /// use std::collections::RingBuf;
543 /// let mut d = RingBuf::new();
544 /// assert_eq!(d.front(), None);
548 /// assert_eq!(d.front(), Some(&1i));
551 pub fn front(&self) -> Option<&T> {
552 if !self.is_empty() { Some(&self[0]) } else { None }
555 /// Provides a mutable reference to the front element, or `None` if the
556 /// sequence is empty.
561 /// use std::collections::RingBuf;
563 /// let mut d = RingBuf::new();
564 /// assert_eq!(d.front_mut(), None);
568 /// match d.front_mut() {
569 /// Some(x) => *x = 9i,
572 /// assert_eq!(d.front(), Some(&9i));
575 pub fn front_mut(&mut self) -> Option<&mut T> {
576 if !self.is_empty() { Some(&mut self[0]) } else { None }
579 /// Provides a reference to the back element, or `None` if the sequence is
585 /// use std::collections::RingBuf;
587 /// let mut d = RingBuf::new();
588 /// assert_eq!(d.back(), None);
592 /// assert_eq!(d.back(), Some(&2i));
595 pub fn back(&self) -> Option<&T> {
596 if !self.is_empty() { Some(&self[self.len() - 1]) } else { None }
599 /// Provides a mutable reference to the back element, or `None` if the
600 /// sequence is empty.
605 /// use std::collections::RingBuf;
607 /// let mut d = RingBuf::new();
608 /// assert_eq!(d.back(), None);
612 /// match d.back_mut() {
613 /// Some(x) => *x = 9i,
616 /// assert_eq!(d.back(), Some(&9i));
619 pub fn back_mut(&mut self) -> Option<&mut T> {
620 let len = self.len();
621 if !self.is_empty() { Some(&mut self[len - 1]) } else { None }
624 /// Removes the first element and returns it, or `None` if the sequence is
630 /// use std::collections::RingBuf;
632 /// let mut d = RingBuf::new();
636 /// assert_eq!(d.pop_front(), Some(1i));
637 /// assert_eq!(d.pop_front(), Some(2i));
638 /// assert_eq!(d.pop_front(), None);
640 #[unstable = "matches collection reform specification, waiting for dust to settle"]
641 pub fn pop_front(&mut self) -> Option<T> {
645 let tail = self.tail;
646 self.tail = self.wrap_index(self.tail + 1);
647 unsafe { Some(self.buffer_read(tail)) }
651 /// Inserts an element first in the sequence.
656 /// use std::collections::RingBuf;
658 /// let mut d = RingBuf::new();
659 /// d.push_front(1i);
660 /// d.push_front(2i);
661 /// assert_eq!(d.front(), Some(&2i));
663 #[unstable = "matches collection reform specification, waiting for dust to settle"]
664 pub fn push_front(&mut self, t: T) {
667 debug_assert!(!self.is_full());
670 self.tail = self.wrap_index(self.tail - 1);
671 let tail = self.tail;
672 unsafe { self.buffer_write(tail, t); }
675 /// Deprecated: Renamed to `push_back`.
676 #[deprecated = "Renamed to `push_back`"]
677 pub fn push(&mut self, t: T) {
681 /// Appends an element to the back of a buffer
686 /// use std::collections::RingBuf;
688 /// let mut buf = RingBuf::new();
689 /// buf.push_back(1i);
690 /// buf.push_back(3);
691 /// assert_eq!(3, *buf.back().unwrap());
693 #[unstable = "matches collection reform specification, waiting for dust to settle"]
694 pub fn push_back(&mut self, t: T) {
697 debug_assert!(!self.is_full());
700 let head = self.head;
701 self.head = self.wrap_index(self.head + 1);
702 unsafe { self.buffer_write(head, t) }
705 /// Deprecated: Renamed to `pop_back`.
706 #[deprecated = "Renamed to `pop_back`"]
707 pub fn pop(&mut self) -> Option<T> {
711 /// Removes the last element from a buffer and returns it, or `None` if
717 /// use std::collections::RingBuf;
719 /// let mut buf = RingBuf::new();
720 /// assert_eq!(buf.pop_back(), None);
721 /// buf.push_back(1i);
722 /// buf.push_back(3);
723 /// assert_eq!(buf.pop_back(), Some(3));
725 #[unstable = "matches collection reform specification, waiting for dust to settle"]
726 pub fn pop_back(&mut self) -> Option<T> {
730 self.head = self.wrap_index(self.head - 1);
731 let head = self.head;
732 unsafe { Some(self.buffer_read(head)) }
737 fn is_contiguous(&self) -> bool {
738 self.tail <= self.head
741 /// Inserts an element at position `i` within the ringbuf. Whichever
742 /// end is closer to the insertion point will be moved to make room,
743 /// and all the affected elements will be moved to new positions.
747 /// Panics if `i` is greater than ringbuf's length
751 /// use std::collections::RingBuf;
753 /// let mut buf = RingBuf::new();
754 /// buf.push_back(10i);
755 /// buf.push_back(12);
756 /// buf.insert(1,11);
757 /// assert_eq!(Some(&11), buf.get(1));
759 pub fn insert(&mut self, i: uint, t: T) {
760 assert!(i <= self.len(), "index out of bounds");
763 debug_assert!(!self.is_full());
766 // Move the least number of elements in the ring buffer and insert
769 // At most len/2 - 1 elements will be moved. O(min(n, n-i))
771 // There are three main cases:
772 // Elements are contiguous
773 // - special case when tail is 0
774 // Elements are discontiguous and the insert is in the tail section
775 // Elements are discontiguous and the insert is in the head section
777 // For each of those there are two more cases:
778 // Insert is closer to tail
779 // Insert is closer to head
781 // Key: H - self.head
784 // I - Insertion element
785 // A - The element that should be after the insertion point
786 // M - Indicates element was moved
788 let idx = self.wrap_index(self.tail + i);
790 let distance_to_tail = i;
791 let distance_to_head = self.len() - i;
793 let contiguous = self.is_contiguous();
795 match (contiguous, distance_to_tail <= distance_to_head, idx >= self.tail) {
796 (true, true, _) if i == 0 => {
801 // [A o o o o o o . . . . . . . . .]
804 // [A o o o o o o o . . . . . I]
807 self.tail = self.wrap_index(self.tail - 1);
809 (true, true, _) => unsafe {
810 // contiguous, insert closer to tail:
813 // [. . . o o A o o o o . . . . . .]
816 // [. . o o I A o o o o . . . . . .]
819 // contiguous, insert closer to tail and tail is 0:
823 // [o o A o o o o . . . . . . . . .]
826 // [o I A o o o o o . . . . . . . o]
829 let new_tail = self.wrap_index(self.tail - 1);
831 self.copy(new_tail, self.tail, 1);
832 // Already moved the tail, so we only copy `i - 1` elements.
833 self.copy(self.tail, self.tail + 1, i - 1);
835 self.tail = new_tail;
837 (true, false, _) => unsafe {
838 // contiguous, insert closer to head:
841 // [. . . o o o o A o o . . . . . .]
844 // [. . . o o o o I A o o . . . . .]
847 self.copy(idx + 1, idx, self.head - idx);
848 self.head = self.wrap_index(self.head + 1);
850 (false, true, true) => unsafe {
851 // discontiguous, insert closer to tail, tail section:
854 // [o o o o o o . . . . . o o A o o]
857 // [o o o o o o . . . . o o I A o o]
860 self.copy(self.tail - 1, self.tail, i);
863 (false, false, true) => unsafe {
864 // discontiguous, insert closer to head, tail section:
867 // [o o . . . . . . . o o o o o A o]
870 // [o o o . . . . . . o o o o o I A]
873 // copy elements up to new head
874 self.copy(1, 0, self.head);
876 // copy last element into empty spot at bottom of buffer
877 self.copy(0, self.cap - 1, 1);
879 // move elements from idx to end forward not including ^ element
880 self.copy(idx + 1, idx, self.cap - 1 - idx);
884 (false, true, false) if idx == 0 => unsafe {
885 // discontiguous, insert is closer to tail, head section,
886 // and is at index zero in the internal buffer:
889 // [A o o o o o o o o o . . . o o o]
892 // [A o o o o o o o o o . . o o o I]
895 // copy elements up to new tail
896 self.copy(self.tail - 1, self.tail, self.cap - self.tail);
898 // copy last element into empty spot at bottom of buffer
899 self.copy(self.cap - 1, 0, 1);
903 (false, true, false) => unsafe {
904 // discontiguous, insert closer to tail, head section:
907 // [o o o A o o o o o o . . . o o o]
910 // [o o I A o o o o o o . . o o o o]
913 // copy elements up to new tail
914 self.copy(self.tail - 1, self.tail, self.cap - self.tail);
916 // copy last element into empty spot at bottom of buffer
917 self.copy(self.cap - 1, 0, 1);
919 // move elements from idx-1 to end forward not including ^ element
920 self.copy(0, 1, idx - 1);
924 (false, false, false) => unsafe {
925 // discontiguous, insert closer to head, head section:
928 // [o o o o A o o . . . . . . o o o]
931 // [o o o o I A o o . . . . . o o o]
934 self.copy(idx + 1, idx, self.head - idx);
939 // tail might've been changed so we need to recalculate
940 let new_idx = self.wrap_index(self.tail + i);
942 self.buffer_write(new_idx, t);
946 /// Removes and returns the element at position `i` from the ringbuf.
947 /// Whichever end is closer to the removal point will be moved to make
948 /// room, and all the affected elements will be moved to new positions.
949 /// Returns `None` if `i` is out of bounds.
953 /// use std::collections::RingBuf;
955 /// let mut buf = RingBuf::new();
956 /// buf.push_back(5i);
957 /// buf.push_back(10i);
958 /// buf.push_back(12i);
959 /// buf.push_back(15);
961 /// assert_eq!(Some(&15), buf.get(2));
963 #[unstable = "matches collection reform specification; waiting on panic semantics"]
964 pub fn remove(&mut self, i: uint) -> Option<T> {
965 if self.is_empty() || self.len() <= i {
969 // There are three main cases:
970 // Elements are contiguous
971 // Elements are discontiguous and the removal is in the tail section
972 // Elements are discontiguous and the removal is in the head section
973 // - special case when elements are technically contiguous,
976 // For each of those there are two more cases:
977 // Insert is closer to tail
978 // Insert is closer to head
980 // Key: H - self.head
983 // x - Element marked for removal
984 // R - Indicates element that is being removed
985 // M - Indicates element was moved
987 let idx = self.wrap_index(self.tail + i);
990 Some(self.buffer_read(idx))
993 let distance_to_tail = i;
994 let distance_to_head = self.len() - i;
996 let contiguous = self.tail <= self.head;
998 match (contiguous, distance_to_tail <= distance_to_head, idx >= self.tail) {
999 (true, true, _) => unsafe {
1000 // contiguous, remove closer to tail:
1003 // [. . . o o x o o o o . . . . . .]
1006 // [. . . . o o o o o o . . . . . .]
1009 self.copy(self.tail + 1, self.tail, i);
1012 (true, false, _) => unsafe {
1013 // contiguous, remove closer to head:
1016 // [. . . o o o o x o o . . . . . .]
1019 // [. . . o o o o o o . . . . . . .]
1022 self.copy(idx, idx + 1, self.head - idx - 1);
1025 (false, true, true) => unsafe {
1026 // discontiguous, remove closer to tail, tail section:
1029 // [o o o o o o . . . . . o o x o o]
1032 // [o o o o o o . . . . . . o o o o]
1035 self.copy(self.tail + 1, self.tail, i);
1036 self.tail = self.wrap_index(self.tail + 1);
1038 (false, false, false) => unsafe {
1039 // discontiguous, remove closer to head, head section:
1042 // [o o o o x o o . . . . . . o o o]
1045 // [o o o o o o . . . . . . . o o o]
1048 self.copy(idx, idx + 1, self.head - idx - 1);
1051 (false, false, true) => unsafe {
1052 // discontiguous, remove closer to head, tail section:
1055 // [o o o . . . . . . o o o o o x o]
1058 // [o o . . . . . . . o o o o o o o]
1061 // or quasi-discontiguous, remove next to head, tail section:
1064 // [. . . . . . . . . o o o o o x o]
1067 // [. . . . . . . . . o o o o o o .]
1070 // draw in elements in the tail section
1071 self.copy(idx, idx + 1, self.cap - idx - 1);
1073 // Prevents underflow.
1075 // copy first element into empty spot
1076 self.copy(self.cap - 1, 0, 1);
1078 // move elements in the head section backwards
1079 self.copy(0, 1, self.head - 1);
1082 self.head = self.wrap_index(self.head - 1);
1084 (false, true, false) => unsafe {
1085 // discontiguous, remove closer to tail, head section:
1088 // [o o x o o o o o o o . . . o o o]
1091 // [o o o o o o o o o o . . . . o o]
1094 // draw in elements up to idx
1095 self.copy(1, 0, idx);
1097 // copy last element into empty spot
1098 self.copy(0, self.cap - 1, 1);
1100 // move elements from tail to end forward, excluding the last one
1101 self.copy(self.tail + 1, self.tail, self.cap - self.tail - 1);
1103 self.tail = self.wrap_index(self.tail + 1);
1111 /// Returns the index in the underlying buffer for a given logical element index.
1113 fn wrap_index(index: uint, size: uint) -> uint {
1114 // size is always a power of 2
1118 /// Calculate the number of elements left to be read in the buffer
1120 fn count(tail: uint, head: uint, size: uint) -> uint {
1121 // size is always a power of 2
1122 (head - tail) & (size - 1)
1125 /// `RingBuf` iterator.
1126 pub struct Iter<'a, T:'a> {
1132 impl<'a, T> Iterator<&'a T> for Iter<'a, T> {
1134 fn next(&mut self) -> Option<&'a T> {
1135 if self.tail == self.head {
1138 let tail = self.tail;
1139 self.tail = wrap_index(self.tail + 1, self.ring.len());
1140 unsafe { Some(self.ring.unsafe_get(tail)) }
1144 fn size_hint(&self) -> (uint, Option<uint>) {
1145 let len = count(self.tail, self.head, self.ring.len());
1150 impl<'a, T> DoubleEndedIterator<&'a T> for Iter<'a, T> {
1152 fn next_back(&mut self) -> Option<&'a T> {
1153 if self.tail == self.head {
1156 self.head = wrap_index(self.head - 1, self.ring.len());
1157 unsafe { Some(self.ring.unsafe_get(self.head)) }
1161 impl<'a, T> ExactSizeIterator<&'a T> for Iter<'a, T> {}
1163 impl<'a, T> RandomAccessIterator<&'a T> for Iter<'a, T> {
1165 fn indexable(&self) -> uint {
1166 let (len, _) = self.size_hint();
1171 fn idx(&mut self, j: uint) -> Option<&'a T> {
1172 if j >= self.indexable() {
1175 let idx = wrap_index(self.tail + j, self.ring.len());
1176 unsafe { Some(self.ring.unsafe_get(idx)) }
1181 // FIXME This was implemented differently from Iter because of a problem
1182 // with returning the mutable reference. I couldn't find a way to
1183 // make the lifetime checker happy so, but there should be a way.
1184 /// `RingBuf` mutable iterator.
1185 pub struct IterMut<'a, T:'a> {
1190 marker: marker::ContravariantLifetime<'a>,
1193 impl<'a, T> Iterator<&'a mut T> for IterMut<'a, T> {
1195 fn next(&mut self) -> Option<&'a mut T> {
1196 if self.tail == self.head {
1199 let tail = self.tail;
1200 self.tail = wrap_index(self.tail + 1, self.cap);
1203 Some(&mut *self.ptr.offset(tail as int))
1208 fn size_hint(&self) -> (uint, Option<uint>) {
1209 let len = count(self.tail, self.head, self.cap);
1214 impl<'a, T> DoubleEndedIterator<&'a mut T> for IterMut<'a, T> {
1216 fn next_back(&mut self) -> Option<&'a mut T> {
1217 if self.tail == self.head {
1220 self.head = wrap_index(self.head - 1, self.cap);
1223 Some(&mut *self.ptr.offset(self.head as int))
1228 impl<'a, T> ExactSizeIterator<&'a mut T> for IterMut<'a, T> {}
1230 // A by-value RingBuf iterator
1231 pub struct IntoIter<T> {
1235 impl<T> Iterator<T> for IntoIter<T> {
1237 fn next(&mut self) -> Option<T> {
1238 self.inner.pop_front()
1242 fn size_hint(&self) -> (uint, Option<uint>) {
1243 let len = self.inner.len();
1248 impl<T> DoubleEndedIterator<T> for IntoIter<T> {
1250 fn next_back(&mut self) -> Option<T> {
1251 self.inner.pop_back()
1255 impl<T> ExactSizeIterator<T> for IntoIter<T> {}
1257 /// A draining RingBuf iterator
1258 pub struct Drain<'a, T: 'a> {
1259 inner: &'a mut RingBuf<T>,
1262 #[unsafe_destructor]
1263 impl<'a, T: 'a> Drop for Drain<'a, T> {
1264 fn drop(&mut self) {
1266 self.inner.head = 0;
1267 self.inner.tail = 0;
1271 impl<'a, T: 'a> Iterator<T> for Drain<'a, T> {
1273 fn next(&mut self) -> Option<T> {
1274 self.inner.pop_front()
1278 fn size_hint(&self) -> (uint, Option<uint>) {
1279 let len = self.inner.len();
1284 impl<'a, T: 'a> DoubleEndedIterator<T> for Drain<'a, T> {
1286 fn next_back(&mut self) -> Option<T> {
1287 self.inner.pop_back()
1291 impl<'a, T: 'a> ExactSizeIterator<T> for Drain<'a, T> {}
1293 impl<A: PartialEq> PartialEq for RingBuf<A> {
1294 fn eq(&self, other: &RingBuf<A>) -> bool {
1295 self.len() == other.len() &&
1296 self.iter().zip(other.iter()).all(|(a, b)| a.eq(b))
1300 impl<A: Eq> Eq for RingBuf<A> {}
1302 impl<A: PartialOrd> PartialOrd for RingBuf<A> {
1303 fn partial_cmp(&self, other: &RingBuf<A>) -> Option<Ordering> {
1304 iter::order::partial_cmp(self.iter(), other.iter())
1308 impl<A: Ord> Ord for RingBuf<A> {
1310 fn cmp(&self, other: &RingBuf<A>) -> Ordering {
1311 iter::order::cmp(self.iter(), other.iter())
1315 impl<S: Writer, A: Hash<S>> Hash<S> for RingBuf<A> {
1316 fn hash(&self, state: &mut S) {
1317 self.len().hash(state);
1318 for elt in self.iter() {
1324 impl<A> Index<uint, A> for RingBuf<A> {
1326 fn index<'a>(&'a self, i: &uint) -> &'a A {
1327 self.get(*i).expect("Out of bounds access")
1331 impl<A> IndexMut<uint, A> for RingBuf<A> {
1333 fn index_mut<'a>(&'a mut self, i: &uint) -> &'a mut A {
1334 self.get_mut(*i).expect("Out of bounds access")
1338 impl<A> FromIterator<A> for RingBuf<A> {
1339 fn from_iter<T: Iterator<A>>(iterator: T) -> RingBuf<A> {
1340 let (lower, _) = iterator.size_hint();
1341 let mut deq = RingBuf::with_capacity(lower);
1342 deq.extend(iterator);
1347 impl<A> Extend<A> for RingBuf<A> {
1348 fn extend<T: Iterator<A>>(&mut self, mut iterator: T) {
1349 for elt in iterator {
1350 self.push_back(elt);
1355 impl<T: fmt::Show> fmt::Show for RingBuf<T> {
1356 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1357 try!(write!(f, "["));
1359 for (i, e) in self.iter().enumerate() {
1360 if i != 0 { try!(write!(f, ", ")); }
1361 try!(write!(f, "{}", *e));
1371 use self::Taggypar::*;
1383 #[allow(deprecated)]
1385 let mut d = RingBuf::new();
1386 assert_eq!(d.len(), 0u);
1390 assert_eq!(d.len(), 3u);
1392 assert_eq!(d.len(), 4u);
1393 debug!("{}", d.front());
1394 assert_eq!(*d.front().unwrap(), 42);
1395 debug!("{}", d.back());
1396 assert_eq!(*d.back().unwrap(), 137);
1397 let mut i = d.pop_front();
1399 assert_eq!(i, Some(42));
1402 assert_eq!(i, Some(137));
1405 assert_eq!(i, Some(137));
1408 assert_eq!(i, Some(17));
1409 assert_eq!(d.len(), 0u);
1411 assert_eq!(d.len(), 1u);
1413 assert_eq!(d.len(), 2u);
1415 assert_eq!(d.len(), 3u);
1417 assert_eq!(d.len(), 4u);
1422 assert_eq!(d[0], 1);
1423 assert_eq!(d[1], 2);
1424 assert_eq!(d[2], 3);
1425 assert_eq!(d[3], 4);
1429 fn test_parameterized<T:Clone + PartialEq + Show>(a: T, b: T, c: T, d: T) {
1430 let mut deq = RingBuf::new();
1431 assert_eq!(deq.len(), 0);
1432 deq.push_front(a.clone());
1433 deq.push_front(b.clone());
1434 deq.push_back(c.clone());
1435 assert_eq!(deq.len(), 3);
1436 deq.push_back(d.clone());
1437 assert_eq!(deq.len(), 4);
1438 assert_eq!((*deq.front().unwrap()).clone(), b.clone());
1439 assert_eq!((*deq.back().unwrap()).clone(), d.clone());
1440 assert_eq!(deq.pop_front().unwrap(), b.clone());
1441 assert_eq!(deq.pop_back().unwrap(), d.clone());
1442 assert_eq!(deq.pop_back().unwrap(), c.clone());
1443 assert_eq!(deq.pop_back().unwrap(), a.clone());
1444 assert_eq!(deq.len(), 0);
1445 deq.push_back(c.clone());
1446 assert_eq!(deq.len(), 1);
1447 deq.push_front(b.clone());
1448 assert_eq!(deq.len(), 2);
1449 deq.push_back(d.clone());
1450 assert_eq!(deq.len(), 3);
1451 deq.push_front(a.clone());
1452 assert_eq!(deq.len(), 4);
1453 assert_eq!(deq[0].clone(), a.clone());
1454 assert_eq!(deq[1].clone(), b.clone());
1455 assert_eq!(deq[2].clone(), c.clone());
1456 assert_eq!(deq[3].clone(), d.clone());
1460 fn test_push_front_grow() {
1461 let mut deq = RingBuf::new();
1462 for i in range(0u, 66) {
1465 assert_eq!(deq.len(), 66);
1467 for i in range(0u, 66) {
1468 assert_eq!(deq[i], 65 - i);
1471 let mut deq = RingBuf::new();
1472 for i in range(0u, 66) {
1476 for i in range(0u, 66) {
1477 assert_eq!(deq[i], i);
1483 let mut deq = RingBuf::new();
1484 for i in range(1u, 4) {
1487 assert_eq!(deq[1], 2);
1492 fn test_index_out_of_bounds() {
1493 let mut deq = RingBuf::new();
1494 for i in range(1u, 4) {
1501 fn bench_new(b: &mut test::Bencher) {
1503 let ring: RingBuf<u64> = RingBuf::new();
1504 test::black_box(ring);
1509 fn bench_push_back_100(b: &mut test::Bencher) {
1510 let mut deq = RingBuf::with_capacity(101);
1512 for i in range(0i, 100) {
1521 fn bench_push_front_100(b: &mut test::Bencher) {
1522 let mut deq = RingBuf::with_capacity(101);
1524 for i in range(0i, 100) {
1533 fn bench_pop_back_100(b: &mut test::Bencher) {
1534 let mut deq: RingBuf<int> = RingBuf::with_capacity(101);
1539 while !deq.is_empty() {
1540 test::black_box(deq.pop_back());
1546 fn bench_pop_front_100(b: &mut test::Bencher) {
1547 let mut deq: RingBuf<int> = RingBuf::with_capacity(101);
1552 while !deq.is_empty() {
1553 test::black_box(deq.pop_front());
1559 fn bench_grow_1025(b: &mut test::Bencher) {
1561 let mut deq = RingBuf::new();
1562 for i in range(0i, 1025) {
1565 test::black_box(deq);
1570 fn bench_iter_1000(b: &mut test::Bencher) {
1571 let ring: RingBuf<int> = range(0i, 1000).collect();
1575 for &i in ring.iter() {
1578 test::black_box(sum);
1583 fn bench_mut_iter_1000(b: &mut test::Bencher) {
1584 let mut ring: RingBuf<int> = range(0i, 1000).collect();
1588 for i in ring.iter_mut() {
1591 test::black_box(sum);
1595 #[deriving(Clone, PartialEq, Show)]
1599 Three(int, int, int),
1602 #[deriving(Clone, PartialEq, Show)]
1606 Threepar(int, int, int),
1609 #[deriving(Clone, PartialEq, Show)]
1617 fn test_param_int() {
1618 test_parameterized::<int>(5, 72, 64, 175);
1622 fn test_param_taggy() {
1623 test_parameterized::<Taggy>(One(1), Two(1, 2), Three(1, 2, 3), Two(17, 42));
1627 fn test_param_taggypar() {
1628 test_parameterized::<Taggypar<int>>(Onepar::<int>(1),
1629 Twopar::<int>(1, 2),
1630 Threepar::<int>(1, 2, 3),
1631 Twopar::<int>(17, 42));
1635 fn test_param_reccy() {
1636 let reccy1 = RecCy { x: 1, y: 2, t: One(1) };
1637 let reccy2 = RecCy { x: 345, y: 2, t: Two(1, 2) };
1638 let reccy3 = RecCy { x: 1, y: 777, t: Three(1, 2, 3) };
1639 let reccy4 = RecCy { x: 19, y: 252, t: Two(17, 42) };
1640 test_parameterized::<RecCy>(reccy1, reccy2, reccy3, reccy4);
1644 fn test_with_capacity() {
1645 let mut d = RingBuf::with_capacity(0);
1647 assert_eq!(d.len(), 1);
1648 let mut d = RingBuf::with_capacity(50);
1650 assert_eq!(d.len(), 1);
1654 fn test_with_capacity_non_power_two() {
1655 let mut d3 = RingBuf::with_capacity(3);
1660 assert_eq!(d3.pop_front(), Some(1));
1662 assert_eq!(d3.front(), None);
1669 assert_eq!(d3.pop_front(), Some(3));
1671 // Pushing the lo past half way point to trigger
1672 // the 'B' scenario for growth
1679 // There used to be a bug here about how the
1680 // RingBuf made growth assumptions about the
1681 // underlying Vec which didn't hold and lead
1683 // (Vec grows to next power of two)
1684 //good- [9, 12, 15, X, X, X, X, |6]
1685 //bug- [15, 12, X, X, X, |6, X, X]
1686 assert_eq!(d3.pop_front(), Some(6));
1688 // Which leads us to the following state which
1689 // would be a failure case.
1690 //bug- [15, 12, X, X, X, X, |X, X]
1691 assert_eq!(d3.front(), Some(&9));
1695 fn test_reserve_exact() {
1696 let mut d = RingBuf::new();
1698 d.reserve_exact(50);
1699 assert!(d.capacity() >= 51);
1700 let mut d = RingBuf::new();
1702 d.reserve_exact(50);
1703 assert!(d.capacity() >= 51);
1708 let mut d = RingBuf::new();
1711 assert!(d.capacity() >= 51);
1712 let mut d = RingBuf::new();
1715 assert!(d.capacity() >= 51);
1720 let mut d: RingBuf<int> = range(0i, 5).collect();
1723 assert_eq!(d.iter().map(|&x|x).collect::<Vec<int>>(), vec!(4, 2, 3, 1));
1728 let mut d = RingBuf::new();
1729 assert_eq!(d.iter().next(), None);
1730 assert_eq!(d.iter().size_hint(), (0, Some(0)));
1732 for i in range(0i, 5) {
1736 let b: &[_] = &[&0,&1,&2,&3,&4];
1737 assert_eq!(d.iter().collect::<Vec<&int>>(), b);
1740 for i in range(6i, 9) {
1744 let b: &[_] = &[&8,&7,&6,&0,&1,&2,&3,&4];
1745 assert_eq!(d.iter().collect::<Vec<&int>>(), b);
1748 let mut it = d.iter();
1749 let mut len = d.len();
1753 _ => { len -= 1; assert_eq!(it.size_hint(), (len, Some(len))) }
1759 fn test_rev_iter() {
1760 let mut d = RingBuf::new();
1761 assert_eq!(d.iter().rev().next(), None);
1763 for i in range(0i, 5) {
1767 let b: &[_] = &[&4,&3,&2,&1,&0];
1768 assert_eq!(d.iter().rev().collect::<Vec<&int>>(), b);
1771 for i in range(6i, 9) {
1774 let b: &[_] = &[&4,&3,&2,&1,&0,&6,&7,&8];
1775 assert_eq!(d.iter().rev().collect::<Vec<&int>>(), b);
1779 fn test_mut_rev_iter_wrap() {
1780 let mut d = RingBuf::with_capacity(3);
1781 assert!(d.iter_mut().rev().next().is_none());
1786 assert_eq!(d.pop_front(), Some(1));
1789 assert_eq!(d.iter_mut().rev().map(|x| *x).collect::<Vec<int>>(),
1794 fn test_mut_iter() {
1795 let mut d = RingBuf::new();
1796 assert!(d.iter_mut().next().is_none());
1798 for i in range(0u, 3) {
1802 for (i, elt) in d.iter_mut().enumerate() {
1803 assert_eq!(*elt, 2 - i);
1808 let mut it = d.iter_mut();
1809 assert_eq!(*it.next().unwrap(), 0);
1810 assert_eq!(*it.next().unwrap(), 1);
1811 assert_eq!(*it.next().unwrap(), 2);
1812 assert!(it.next().is_none());
1817 fn test_mut_rev_iter() {
1818 let mut d = RingBuf::new();
1819 assert!(d.iter_mut().rev().next().is_none());
1821 for i in range(0u, 3) {
1825 for (i, elt) in d.iter_mut().rev().enumerate() {
1826 assert_eq!(*elt, i);
1831 let mut it = d.iter_mut().rev();
1832 assert_eq!(*it.next().unwrap(), 0);
1833 assert_eq!(*it.next().unwrap(), 1);
1834 assert_eq!(*it.next().unwrap(), 2);
1835 assert!(it.next().is_none());
1840 fn test_into_iter() {
1844 let d: RingBuf<int> = RingBuf::new();
1845 let mut iter = d.into_iter();
1847 assert_eq!(iter.size_hint(), (0, Some(0)));
1848 assert_eq!(iter.next(), None);
1849 assert_eq!(iter.size_hint(), (0, Some(0)));
1854 let mut d = RingBuf::new();
1855 for i in range(0i, 5) {
1859 let b = vec![0,1,2,3,4];
1860 assert_eq!(d.into_iter().collect::<Vec<int>>(), b);
1865 let mut d = RingBuf::new();
1866 for i in range(0i, 5) {
1869 for i in range(6, 9) {
1873 let b = vec![8,7,6,0,1,2,3,4];
1874 assert_eq!(d.into_iter().collect::<Vec<int>>(), b);
1879 let mut d = RingBuf::new();
1880 for i in range(0i, 5) {
1883 for i in range(6, 9) {
1887 let mut it = d.into_iter();
1888 assert_eq!(it.size_hint(), (8, Some(8)));
1889 assert_eq!(it.next(), Some(8));
1890 assert_eq!(it.size_hint(), (7, Some(7)));
1891 assert_eq!(it.next_back(), Some(4));
1892 assert_eq!(it.size_hint(), (6, Some(6)));
1893 assert_eq!(it.next(), Some(7));
1894 assert_eq!(it.size_hint(), (5, Some(5)));
1903 let mut d: RingBuf<int> = RingBuf::new();
1906 let mut iter = d.drain();
1908 assert_eq!(iter.size_hint(), (0, Some(0)));
1909 assert_eq!(iter.next(), None);
1910 assert_eq!(iter.size_hint(), (0, Some(0)));
1913 assert!(d.is_empty());
1918 let mut d = RingBuf::new();
1919 for i in range(0i, 5) {
1923 assert_eq!(d.drain().collect::<Vec<int>>(), [0, 1, 2, 3, 4]);
1924 assert!(d.is_empty());
1929 let mut d = RingBuf::new();
1930 for i in range(0i, 5) {
1933 for i in range(6, 9) {
1937 assert_eq!(d.drain().collect::<Vec<int>>(), [8,7,6,0,1,2,3,4]);
1938 assert!(d.is_empty());
1943 let mut d = RingBuf::new();
1944 for i in range(0i, 5) {
1947 for i in range(6, 9) {
1952 let mut it = d.drain();
1953 assert_eq!(it.size_hint(), (8, Some(8)));
1954 assert_eq!(it.next(), Some(8));
1955 assert_eq!(it.size_hint(), (7, Some(7)));
1956 assert_eq!(it.next_back(), Some(4));
1957 assert_eq!(it.size_hint(), (6, Some(6)));
1958 assert_eq!(it.next(), Some(7));
1959 assert_eq!(it.size_hint(), (5, Some(5)));
1961 assert!(d.is_empty());
1966 fn test_from_iter() {
1968 let v = vec!(1i,2,3,4,5,6,7);
1969 let deq: RingBuf<int> = v.iter().map(|&x| x).collect();
1970 let u: Vec<int> = deq.iter().map(|&x| x).collect();
1973 let seq = iter::count(0u, 2).take(256);
1974 let deq: RingBuf<uint> = seq.collect();
1975 for (i, &x) in deq.iter().enumerate() {
1978 assert_eq!(deq.len(), 256);
1983 let mut d = RingBuf::new();
1988 assert_eq!(d.len(), 4u);
1989 let mut e = d.clone();
1990 assert_eq!(e.len(), 4u);
1991 while !d.is_empty() {
1992 assert_eq!(d.pop_back(), e.pop_back());
1994 assert_eq!(d.len(), 0u);
1995 assert_eq!(e.len(), 0u);
2000 let mut d = RingBuf::new();
2001 assert!(d == RingBuf::with_capacity(0));
2006 let mut e = RingBuf::with_capacity(0);
2016 assert!(e == RingBuf::new());
2021 let mut x = RingBuf::new();
2022 let mut y = RingBuf::new();
2034 assert!(hash::hash(&x) == hash::hash(&y));
2039 let x = RingBuf::new();
2040 let mut y = RingBuf::new();
2052 let ringbuf: RingBuf<int> = range(0i, 10).collect();
2053 assert!(format!("{}", ringbuf) == "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]");
2055 let ringbuf: RingBuf<&str> = vec!["just", "one", "test", "more"].iter()
2058 assert!(format!("{}", ringbuf) == "[just, one, test, more]");
2063 static mut drops: uint = 0;
2065 impl Drop for Elem {
2066 fn drop(&mut self) {
2067 unsafe { drops += 1; }
2071 let mut ring = RingBuf::new();
2072 ring.push_back(Elem);
2073 ring.push_front(Elem);
2074 ring.push_back(Elem);
2075 ring.push_front(Elem);
2078 assert_eq!(unsafe {drops}, 4);
2082 fn test_drop_with_pop() {
2083 static mut drops: uint = 0;
2085 impl Drop for Elem {
2086 fn drop(&mut self) {
2087 unsafe { drops += 1; }
2091 let mut ring = RingBuf::new();
2092 ring.push_back(Elem);
2093 ring.push_front(Elem);
2094 ring.push_back(Elem);
2095 ring.push_front(Elem);
2097 drop(ring.pop_back());
2098 drop(ring.pop_front());
2099 assert_eq!(unsafe {drops}, 2);
2102 assert_eq!(unsafe {drops}, 4);
2106 fn test_drop_clear() {
2107 static mut drops: uint = 0;
2109 impl Drop for Elem {
2110 fn drop(&mut self) {
2111 unsafe { drops += 1; }
2115 let mut ring = RingBuf::new();
2116 ring.push_back(Elem);
2117 ring.push_front(Elem);
2118 ring.push_back(Elem);
2119 ring.push_front(Elem);
2121 assert_eq!(unsafe {drops}, 4);
2124 assert_eq!(unsafe {drops}, 4);
2128 fn test_reserve_grow() {
2129 // test growth path A
2130 // [T o o H] -> [T o o H . . . . ]
2131 let mut ring = RingBuf::with_capacity(4);
2132 for i in range(0i, 3) {
2136 for i in range(0i, 3) {
2137 assert_eq!(ring.pop_front(), Some(i));
2140 // test growth path B
2141 // [H T o o] -> [. T o o H . . . ]
2142 let mut ring = RingBuf::with_capacity(4);
2143 for i in range(0i, 1) {
2145 assert_eq!(ring.pop_front(), Some(i));
2147 for i in range(0i, 3) {
2151 for i in range(0i, 3) {
2152 assert_eq!(ring.pop_front(), Some(i));
2155 // test growth path C
2156 // [o o H T] -> [o o H . . . . T ]
2157 let mut ring = RingBuf::with_capacity(4);
2158 for i in range(0i, 3) {
2160 assert_eq!(ring.pop_front(), Some(i));
2162 for i in range(0i, 3) {
2166 for i in range(0i, 3) {
2167 assert_eq!(ring.pop_front(), Some(i));
2173 let mut ring = RingBuf::new();
2175 assert_eq!(ring.get(0), Some(&0));
2176 assert_eq!(ring.get(1), None);
2179 assert_eq!(ring.get(0), Some(&0));
2180 assert_eq!(ring.get(1), Some(&1));
2181 assert_eq!(ring.get(2), None);
2184 assert_eq!(ring.get(0), Some(&0));
2185 assert_eq!(ring.get(1), Some(&1));
2186 assert_eq!(ring.get(2), Some(&2));
2187 assert_eq!(ring.get(3), None);
2189 assert_eq!(ring.pop_front(), Some(0));
2190 assert_eq!(ring.get(0), Some(&1));
2191 assert_eq!(ring.get(1), Some(&2));
2192 assert_eq!(ring.get(2), None);
2194 assert_eq!(ring.pop_front(), Some(1));
2195 assert_eq!(ring.get(0), Some(&2));
2196 assert_eq!(ring.get(1), None);
2198 assert_eq!(ring.pop_front(), Some(2));
2199 assert_eq!(ring.get(0), None);
2200 assert_eq!(ring.get(1), None);
2205 let mut ring = RingBuf::new();
2206 for i in range(0i, 3) {
2210 match ring.get_mut(1) {
2215 assert_eq!(ring.get_mut(0), Some(&mut 0));
2216 assert_eq!(ring.get_mut(1), Some(&mut -1));
2217 assert_eq!(ring.get_mut(2), Some(&mut 2));
2218 assert_eq!(ring.get_mut(3), None);
2220 assert_eq!(ring.pop_front(), Some(0));
2221 assert_eq!(ring.get_mut(0), Some(&mut -1));
2222 assert_eq!(ring.get_mut(1), Some(&mut 2));
2223 assert_eq!(ring.get_mut(2), None);
2228 // This test checks that every single combination of tail position, length, and
2229 // insertion position is tested. Capacity 15 should be large enough to cover every case.
2231 let mut tester = RingBuf::with_capacity(15);
2232 // can't guarantee we got 15, so have to get what we got.
2233 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2234 // this test isn't covering what it wants to
2235 let cap = tester.capacity();
2238 // len is the length *after* insertion
2239 for len in range(1, cap) {
2240 // 0, 1, 2, .., len - 1
2241 let expected = iter::count(0, 1).take(len).collect();
2242 for tail_pos in range(0, cap) {
2243 for to_insert in range(0, len) {
2244 tester.tail = tail_pos;
2245 tester.head = tail_pos;
2246 for i in range(0, len) {
2248 tester.push_back(i);
2251 tester.insert(to_insert, to_insert);
2252 assert!(tester.tail < tester.cap);
2253 assert!(tester.head < tester.cap);
2254 assert_eq!(tester, expected);
2262 // This test checks that every single combination of tail position, length, and
2263 // removal position is tested. Capacity 15 should be large enough to cover every case.
2265 let mut tester = RingBuf::with_capacity(15);
2266 // can't guarantee we got 15, so have to get what we got.
2267 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2268 // this test isn't covering what it wants to
2269 let cap = tester.capacity();
2271 // len is the length *after* removal
2272 for len in range(0, cap - 1) {
2273 // 0, 1, 2, .., len - 1
2274 let expected = iter::count(0, 1).take(len).collect();
2275 for tail_pos in range(0, cap) {
2276 for to_remove in range(0, len + 1) {
2277 tester.tail = tail_pos;
2278 tester.head = tail_pos;
2279 for i in range(0, len) {
2281 tester.push_back(1234);
2283 tester.push_back(i);
2285 if to_remove == len {
2286 tester.push_back(1234);
2288 tester.remove(to_remove);
2289 assert!(tester.tail < tester.cap);
2290 assert!(tester.head < tester.cap);
2291 assert_eq!(tester, expected);
2299 let mut ring = RingBuf::new();
2300 ring.push_back(10i);
2301 ring.push_back(20i);
2302 assert_eq!(ring.front(), Some(&10));
2304 assert_eq!(ring.front(), Some(&20));
2306 assert_eq!(ring.front(), None);
2310 fn test_as_slices() {
2311 let mut ring: RingBuf<int> = RingBuf::with_capacity(127);
2312 let cap = ring.capacity() as int;
2314 let last = cap - first;
2315 for i in range(0, first) {
2318 let (left, right) = ring.as_slices();
2319 let expected: Vec<_> = range(0, i+1).collect();
2320 assert_eq!(left, expected);
2321 assert_eq!(right, []);
2324 for j in range(-last, 0) {
2326 let (left, right) = ring.as_slices();
2327 let expected_left: Vec<_> = range(-last, j+1).rev().collect();
2328 let expected_right: Vec<_> = range(0, first).collect();
2329 assert_eq!(left, expected_left);
2330 assert_eq!(right, expected_right);
2333 assert_eq!(ring.len() as int, cap);
2334 assert_eq!(ring.capacity() as int, cap);
2338 fn test_as_mut_slices() {
2339 let mut ring: RingBuf<int> = RingBuf::with_capacity(127);
2340 let cap = ring.capacity() as int;
2342 let last = cap - first;
2343 for i in range(0, first) {
2346 let (left, right) = ring.as_mut_slices();
2347 let expected: Vec<_> = range(0, i+1).collect();
2348 assert_eq!(left, expected);
2349 assert_eq!(right, []);
2352 for j in range(-last, 0) {
2354 let (left, right) = ring.as_mut_slices();
2355 let expected_left: Vec<_> = range(-last, j+1).rev().collect();
2356 let expected_right: Vec<_> = range(0, first).collect();
2357 assert_eq!(left, expected_left);
2358 assert_eq!(right, expected_right);
2361 assert_eq!(ring.len() as int, cap);
2362 assert_eq!(ring.capacity() as int, cap);