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::{self, repeat, 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 = 7u; // 2^3 - 1
34 static MINIMUM_CAPACITY: uint = 1u; // 2 - 1
36 /// `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 unsafe impl<T: Send> Send for RingBuf<T> {}
55 unsafe impl<T: Sync> Sync for RingBuf<T> {}
58 impl<T: Clone> Clone for RingBuf<T> {
59 fn clone(&self) -> RingBuf<T> {
60 self.iter().map(|t| t.clone()).collect()
66 impl<T> Drop for RingBuf<T> {
70 if mem::size_of::<T>() != 0 {
71 heap::deallocate(self.ptr as *mut u8,
72 self.cap * mem::size_of::<T>(),
73 mem::min_align_of::<T>())
80 impl<T> Default for RingBuf<T> {
82 fn default() -> RingBuf<T> { RingBuf::new() }
86 /// Turn ptr into a slice
88 unsafe fn buffer_as_slice(&self) -> &[T] {
89 mem::transmute(RawSlice { data: self.ptr as *const T, len: self.cap })
92 /// Turn ptr into a mut slice
94 unsafe fn buffer_as_mut_slice(&mut self) -> &mut [T] {
95 mem::transmute(RawSlice { data: self.ptr as *const T, len: self.cap })
98 /// Moves an element out of the buffer
100 unsafe fn buffer_read(&mut self, off: uint) -> T {
101 ptr::read(self.ptr.offset(off as int) as *const T)
104 /// Writes an element into the buffer, moving it.
106 unsafe fn buffer_write(&mut self, off: uint, t: T) {
107 ptr::write(self.ptr.offset(off as int), t);
110 /// Returns true iff the buffer is at capacity
112 fn is_full(&self) -> bool { self.cap - self.len() == 1 }
114 /// Returns the index in the underlying buffer for a given logical element index.
116 fn wrap_index(&self, idx: uint) -> uint { wrap_index(idx, self.cap) }
118 /// Copies a contiguous block of memory len long from src to dst
120 unsafe fn copy(&self, dst: uint, src: uint, len: uint) {
121 debug_assert!(dst + len <= self.cap, "dst={} src={} len={} cap={}", dst, src, len,
123 debug_assert!(src + len <= self.cap, "dst={} src={} len={} cap={}", dst, src, len,
126 self.ptr.offset(dst as int),
127 self.ptr.offset(src as int),
131 /// Copies a contiguous block of memory len long from src to dst
133 unsafe fn copy_nonoverlapping(&self, dst: uint, src: uint, len: uint) {
134 debug_assert!(dst + len <= self.cap, "dst={} src={} len={} cap={}", dst, src, len,
136 debug_assert!(src + len <= self.cap, "dst={} src={} len={} cap={}", dst, src, len,
138 ptr::copy_nonoverlapping_memory(
139 self.ptr.offset(dst as int),
140 self.ptr.offset(src as int),
146 /// Creates an empty `RingBuf`.
148 pub fn new() -> RingBuf<T> {
149 RingBuf::with_capacity(INITIAL_CAPACITY)
152 /// Creates an empty `RingBuf` with space for at least `n` elements.
154 pub fn with_capacity(n: uint) -> RingBuf<T> {
155 // +1 since the ringbuffer always leaves one space empty
156 let cap = cmp::max(n + 1, MINIMUM_CAPACITY + 1).next_power_of_two();
157 assert!(cap > n, "capacity overflow");
158 let size = cap.checked_mul(mem::size_of::<T>())
159 .expect("capacity overflow");
161 let ptr = if mem::size_of::<T>() != 0 {
163 let ptr = heap::allocate(size, mem::min_align_of::<T>()) as *mut T;;
164 if ptr.is_null() { ::alloc::oom() }
168 heap::EMPTY as *mut T
179 /// Retrieves an element in the `RingBuf` by index.
184 /// use std::collections::RingBuf;
186 /// let mut buf = RingBuf::new();
187 /// buf.push_back(3);
188 /// buf.push_back(4);
189 /// buf.push_back(5);
190 /// assert_eq!(buf.get(1).unwrap(), &4);
193 pub fn get(&self, i: uint) -> Option<&T> {
195 let idx = self.wrap_index(self.tail + i);
196 unsafe { Some(&*self.ptr.offset(idx as int)) }
202 /// Retrieves an element in the `RingBuf` mutably by index.
207 /// use std::collections::RingBuf;
209 /// let mut buf = RingBuf::new();
210 /// buf.push_back(3);
211 /// buf.push_back(4);
212 /// buf.push_back(5);
213 /// match buf.get_mut(1) {
220 /// assert_eq!(buf[1], 7);
223 pub fn get_mut(&mut self, i: uint) -> Option<&mut T> {
225 let idx = self.wrap_index(self.tail + i);
226 unsafe { Some(&mut *self.ptr.offset(idx as int)) }
232 /// Swaps elements at indices `i` and `j`.
234 /// `i` and `j` may be equal.
236 /// Fails if there is no element with either index.
241 /// use std::collections::RingBuf;
243 /// let mut buf = RingBuf::new();
244 /// buf.push_back(3);
245 /// buf.push_back(4);
246 /// buf.push_back(5);
248 /// assert_eq!(buf[0], 5);
249 /// assert_eq!(buf[2], 3);
252 pub fn swap(&mut self, i: uint, j: uint) {
253 assert!(i < self.len());
254 assert!(j < self.len());
255 let ri = self.wrap_index(self.tail + i);
256 let rj = self.wrap_index(self.tail + j);
258 ptr::swap(self.ptr.offset(ri as int), self.ptr.offset(rj as int))
262 /// Returns the number of elements the `RingBuf` can hold without
268 /// use std::collections::RingBuf;
270 /// let buf: RingBuf<int> = RingBuf::with_capacity(10);
271 /// assert!(buf.capacity() >= 10);
275 pub fn capacity(&self) -> uint { self.cap - 1 }
277 /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the
278 /// given `RingBuf`. Does nothing if the capacity is already sufficient.
280 /// Note that the allocator may give the collection more space than it requests. Therefore
281 /// capacity can not be relied upon to be precisely minimal. Prefer `reserve` if future
282 /// insertions are expected.
286 /// Panics if the new capacity overflows `uint`.
291 /// use std::collections::RingBuf;
293 /// let mut buf: RingBuf<int> = vec![1].into_iter().collect();
294 /// buf.reserve_exact(10);
295 /// assert!(buf.capacity() >= 11);
298 pub fn reserve_exact(&mut self, additional: uint) {
299 self.reserve(additional);
302 /// Reserves capacity for at least `additional` more elements to be inserted in the given
303 /// `Ringbuf`. The collection may reserve more space to avoid frequent reallocations.
307 /// Panics if the new capacity overflows `uint`.
312 /// use std::collections::RingBuf;
314 /// let mut buf: RingBuf<int> = vec![1].into_iter().collect();
316 /// assert!(buf.capacity() >= 11);
319 pub fn reserve(&mut self, additional: uint) {
320 let new_len = self.len() + additional;
321 assert!(new_len + 1 > self.len(), "capacity overflow");
322 if new_len > self.capacity() {
323 let count = (new_len + 1).next_power_of_two();
324 assert!(count >= new_len + 1);
326 if mem::size_of::<T>() != 0 {
327 let old = self.cap * mem::size_of::<T>();
328 let new = count.checked_mul(mem::size_of::<T>())
329 .expect("capacity overflow");
331 self.ptr = heap::reallocate(self.ptr as *mut u8,
334 mem::min_align_of::<T>()) as *mut T;
335 if self.ptr.is_null() { ::alloc::oom() }
339 // Move the shortest contiguous section of the ring buffer
341 // [o o o o o o o . ]
343 // A [o o o o o o o . . . . . . . . . ]
345 // [o o . o o o o o ]
347 // B [. . . o o o o o o o . . . . . . ]
349 // [o o o o o . o o ]
351 // C [o o o o o . . . . . . . . . o o ]
353 let oldcap = self.cap;
356 if self.tail <= self.head { // A
358 } else if self.head < oldcap - self.tail { // B
360 self.copy_nonoverlapping(oldcap, 0, self.head);
363 debug_assert!(self.head > self.tail);
365 let new_tail = count - (oldcap - self.tail);
367 self.copy_nonoverlapping(new_tail, self.tail, oldcap - self.tail);
369 self.tail = new_tail;
370 debug_assert!(self.head < self.tail);
372 debug_assert!(self.head < self.cap);
373 debug_assert!(self.tail < self.cap);
374 debug_assert!(self.cap.count_ones() == 1);
378 /// Shrinks the capacity of the ringbuf as much as possible.
380 /// It will drop down as close as possible to the length but the allocator may still inform the
381 /// ringbuf that there is space for a few more elements.
386 /// use std::collections::RingBuf;
388 /// let mut buf = RingBuf::with_capacity(15);
389 /// buf.extend(range(0u, 4));
390 /// assert_eq!(buf.capacity(), 15);
391 /// buf.shrink_to_fit();
392 /// assert!(buf.capacity() >= 4);
394 pub fn shrink_to_fit(&mut self) {
395 // +1 since the ringbuffer always leaves one space empty
396 // len + 1 can't overflow for an existing, well-formed ringbuf.
397 let target_cap = cmp::max(self.len() + 1, MINIMUM_CAPACITY + 1).next_power_of_two();
398 if target_cap < self.cap {
399 // There are three cases of interest:
400 // All elements are out of desired bounds
401 // Elements are contiguous, and head is out of desired bounds
402 // Elements are discontiguous, and tail is out of desired bounds
404 // At all other times, element positions are unaffected.
406 // Indicates that elements at the head should be moved.
407 let head_outside = self.head == 0 || self.head >= target_cap;
408 // Move elements from out of desired bounds (positions after target_cap)
409 if self.tail >= target_cap && head_outside {
411 // [. . . . . . . . o o o o o o o . ]
413 // [o o o o o o o . ]
415 self.copy_nonoverlapping(0, self.tail, self.len());
417 self.head = self.len();
419 } else if self.tail != 0 && self.tail < target_cap && head_outside {
421 // [. . . o o o o o o o . . . . . . ]
423 // [o o . o o o o o ]
424 let len = self.wrap_index(self.head - target_cap);
426 self.copy_nonoverlapping(0, target_cap, len);
429 debug_assert!(self.head < self.tail);
430 } else if self.tail >= target_cap {
432 // [o o o o o . . . . . . . . . o o ]
434 // [o o o o o . o o ]
435 debug_assert!(self.wrap_index(self.head - 1) < target_cap);
436 let len = self.cap - self.tail;
437 let new_tail = target_cap - len;
439 self.copy_nonoverlapping(new_tail, self.tail, len);
441 self.tail = new_tail;
442 debug_assert!(self.head < self.tail);
445 if mem::size_of::<T>() != 0 {
446 let old = self.cap * mem::size_of::<T>();
447 let new_size = target_cap * mem::size_of::<T>();
449 self.ptr = heap::reallocate(self.ptr as *mut u8,
452 mem::min_align_of::<T>()) as *mut T;
453 if self.ptr.is_null() { ::alloc::oom() }
456 self.cap = target_cap;
457 debug_assert!(self.head < self.cap);
458 debug_assert!(self.tail < self.cap);
459 debug_assert!(self.cap.count_ones() == 1);
463 /// Shorten a ringbuf, dropping excess elements from the back.
465 /// If `len` is greater than the ringbuf's current length, this has no
471 /// use std::collections::RingBuf;
473 /// let mut buf = RingBuf::new();
474 /// buf.push_back(5i);
475 /// buf.push_back(10i);
476 /// buf.push_back(15);
478 /// assert_eq!(buf.len(), 1);
479 /// assert_eq!(Some(&5), buf.get(0));
481 #[unstable = "matches collection reform specification; waiting on panic semantics"]
482 pub fn truncate(&mut self, len: uint) {
483 for _ in range(len, self.len()) {
488 /// Returns a front-to-back iterator.
493 /// use std::collections::RingBuf;
495 /// let mut buf = RingBuf::new();
496 /// buf.push_back(5);
497 /// buf.push_back(3);
498 /// buf.push_back(4);
499 /// let b: &[_] = &[&5, &3, &4];
500 /// assert_eq!(buf.iter().collect::<Vec<&int>>().as_slice(), b);
503 pub fn iter(&self) -> Iter<T> {
507 ring: unsafe { self.buffer_as_slice() }
511 /// Returns a front-to-back iterator that returns mutable references.
516 /// use std::collections::RingBuf;
518 /// let mut buf = RingBuf::new();
519 /// buf.push_back(5);
520 /// buf.push_back(3);
521 /// buf.push_back(4);
522 /// for num in buf.iter_mut() {
525 /// let b: &[_] = &[&mut 3, &mut 1, &mut 2];
526 /// assert_eq!(buf.iter_mut().collect::<Vec<&mut int>>()[], b);
529 pub fn iter_mut<'a>(&'a mut self) -> IterMut<'a, T> {
535 marker: marker::ContravariantLifetime::<'a>,
539 /// Consumes the list into an iterator yielding elements by value.
541 pub fn into_iter(self) -> IntoIter<T> {
547 /// Returns a pair of slices which contain, in order, the contents of the
550 #[unstable = "matches collection reform specification, waiting for dust to settle"]
551 pub fn as_slices<'a>(&'a self) -> (&'a [T], &'a [T]) {
553 let contiguous = self.is_contiguous();
554 let buf = self.buffer_as_slice();
556 let (empty, buf) = buf.split_at(0);
557 (buf[self.tail..self.head], empty)
559 let (mid, right) = buf.split_at(self.tail);
560 let (left, _) = mid.split_at(self.head);
566 /// Returns a pair of slices which contain, in order, the contents of the
569 #[unstable = "matches collection reform specification, waiting for dust to settle"]
570 pub fn as_mut_slices<'a>(&'a mut self) -> (&'a mut [T], &'a mut [T]) {
572 let contiguous = self.is_contiguous();
573 let head = self.head;
574 let tail = self.tail;
575 let buf = self.buffer_as_mut_slice();
578 let (empty, buf) = buf.split_at_mut(0);
579 (buf.slice_mut(tail, head), empty)
581 let (mid, right) = buf.split_at_mut(tail);
582 let (left, _) = mid.split_at_mut(head);
589 /// Returns the number of elements in the `RingBuf`.
594 /// use std::collections::RingBuf;
596 /// let mut v = RingBuf::new();
597 /// assert_eq!(v.len(), 0);
599 /// assert_eq!(v.len(), 1);
602 pub fn len(&self) -> uint { count(self.tail, self.head, self.cap) }
604 /// Returns true if the buffer contains no elements
609 /// use std::collections::RingBuf;
611 /// let mut v = RingBuf::new();
612 /// assert!(v.is_empty());
614 /// assert!(!v.is_empty());
617 pub fn is_empty(&self) -> bool { self.len() == 0 }
619 /// Creates a draining iterator that clears the `RingBuf` and iterates over
620 /// the removed items from start to end.
625 /// use std::collections::RingBuf;
627 /// let mut v = RingBuf::new();
629 /// assert_eq!(v.drain().next(), Some(1));
630 /// assert!(v.is_empty());
633 #[unstable = "matches collection reform specification, waiting for dust to settle"]
634 pub fn drain(&mut self) -> Drain<T> {
640 /// Clears the buffer, removing all values.
645 /// use std::collections::RingBuf;
647 /// let mut v = RingBuf::new();
650 /// assert!(v.is_empty());
654 pub fn clear(&mut self) {
658 /// Provides a reference to the front element, or `None` if the sequence is
664 /// use std::collections::RingBuf;
666 /// let mut d = RingBuf::new();
667 /// assert_eq!(d.front(), None);
671 /// assert_eq!(d.front(), Some(&1));
674 pub fn front(&self) -> Option<&T> {
675 if !self.is_empty() { Some(&self[0]) } else { None }
678 /// Provides a mutable reference to the front element, or `None` if the
679 /// sequence is empty.
684 /// use std::collections::RingBuf;
686 /// let mut d = RingBuf::new();
687 /// assert_eq!(d.front_mut(), None);
691 /// match d.front_mut() {
692 /// Some(x) => *x = 9,
695 /// assert_eq!(d.front(), Some(&9));
698 pub fn front_mut(&mut self) -> Option<&mut T> {
699 if !self.is_empty() { Some(&mut self[0]) } else { None }
702 /// Provides a reference to the back element, or `None` if the sequence is
708 /// use std::collections::RingBuf;
710 /// let mut d = RingBuf::new();
711 /// assert_eq!(d.back(), None);
715 /// assert_eq!(d.back(), Some(&2));
718 pub fn back(&self) -> Option<&T> {
719 if !self.is_empty() { Some(&self[self.len() - 1]) } else { None }
722 /// Provides a mutable reference to the back element, or `None` if the
723 /// sequence is empty.
728 /// use std::collections::RingBuf;
730 /// let mut d = RingBuf::new();
731 /// assert_eq!(d.back(), None);
735 /// match d.back_mut() {
736 /// Some(x) => *x = 9,
739 /// assert_eq!(d.back(), Some(&9));
742 pub fn back_mut(&mut self) -> Option<&mut T> {
743 let len = self.len();
744 if !self.is_empty() { Some(&mut self[len - 1]) } else { None }
747 /// Removes the first element and returns it, or `None` if the sequence is
753 /// use std::collections::RingBuf;
755 /// let mut d = RingBuf::new();
759 /// assert_eq!(d.pop_front(), Some(1));
760 /// assert_eq!(d.pop_front(), Some(2));
761 /// assert_eq!(d.pop_front(), None);
764 pub fn pop_front(&mut self) -> Option<T> {
768 let tail = self.tail;
769 self.tail = self.wrap_index(self.tail + 1);
770 unsafe { Some(self.buffer_read(tail)) }
774 /// Inserts an element first in the sequence.
779 /// use std::collections::RingBuf;
781 /// let mut d = RingBuf::new();
784 /// assert_eq!(d.front(), Some(&2));
787 pub fn push_front(&mut self, t: T) {
790 debug_assert!(!self.is_full());
793 self.tail = self.wrap_index(self.tail - 1);
794 let tail = self.tail;
795 unsafe { self.buffer_write(tail, t); }
798 /// Appends an element to the back of a buffer
803 /// use std::collections::RingBuf;
805 /// let mut buf = RingBuf::new();
806 /// buf.push_back(1);
807 /// buf.push_back(3);
808 /// assert_eq!(3, *buf.back().unwrap());
811 pub fn push_back(&mut self, t: T) {
814 debug_assert!(!self.is_full());
817 let head = self.head;
818 self.head = self.wrap_index(self.head + 1);
819 unsafe { self.buffer_write(head, t) }
822 /// Removes the last element from a buffer and returns it, or `None` if
828 /// use std::collections::RingBuf;
830 /// let mut buf = RingBuf::new();
831 /// assert_eq!(buf.pop_back(), None);
832 /// buf.push_back(1);
833 /// buf.push_back(3);
834 /// assert_eq!(buf.pop_back(), Some(3));
837 pub fn pop_back(&mut self) -> Option<T> {
841 self.head = self.wrap_index(self.head - 1);
842 let head = self.head;
843 unsafe { Some(self.buffer_read(head)) }
848 fn is_contiguous(&self) -> bool {
849 self.tail <= self.head
852 /// Removes an element from anywhere in the ringbuf and returns it, replacing it with the last
855 /// This does not preserve ordering, but is O(1).
857 /// Returns `None` if `index` is out of bounds.
862 /// use std::collections::RingBuf;
864 /// let mut buf = RingBuf::new();
865 /// assert_eq!(buf.swap_back_remove(0), None);
866 /// buf.push_back(5i);
867 /// buf.push_back(99);
868 /// buf.push_back(15);
869 /// buf.push_back(20);
870 /// buf.push_back(10);
871 /// assert_eq!(buf.swap_back_remove(1), Some(99));
873 #[unstable = "the naming of this function may be altered"]
874 pub fn swap_back_remove(&mut self, index: uint) -> Option<T> {
875 let length = self.len();
876 if length > 0 && index < length - 1 {
877 self.swap(index, length - 1);
878 } else if index >= length {
884 /// Removes an element from anywhere in the ringbuf and returns it, replacing it with the first
887 /// This does not preserve ordering, but is O(1).
889 /// Returns `None` if `index` is out of bounds.
894 /// use std::collections::RingBuf;
896 /// let mut buf = RingBuf::new();
897 /// assert_eq!(buf.swap_front_remove(0), None);
898 /// buf.push_back(15i);
899 /// buf.push_back(5);
900 /// buf.push_back(10);
901 /// buf.push_back(99);
902 /// buf.push_back(20i);
903 /// assert_eq!(buf.swap_front_remove(3), Some(99));
905 #[unstable = "the naming of this function may be altered"]
906 pub fn swap_front_remove(&mut self, index: uint) -> Option<T> {
907 let length = self.len();
908 if length > 0 && index < length && index != 0 {
910 } else if index >= length {
916 /// Inserts an element at position `i` within the ringbuf. Whichever
917 /// end is closer to the insertion point will be moved to make room,
918 /// and all the affected elements will be moved to new positions.
922 /// Panics if `i` is greater than ringbuf's length
926 /// use std::collections::RingBuf;
928 /// let mut buf = RingBuf::new();
929 /// buf.push_back(10);
930 /// buf.push_back(12);
931 /// buf.insert(1,11);
932 /// assert_eq!(Some(&11), buf.get(1));
934 pub fn insert(&mut self, i: uint, t: T) {
935 assert!(i <= self.len(), "index out of bounds");
938 debug_assert!(!self.is_full());
941 // Move the least number of elements in the ring buffer and insert
944 // At most len/2 - 1 elements will be moved. O(min(n, n-i))
946 // There are three main cases:
947 // Elements are contiguous
948 // - special case when tail is 0
949 // Elements are discontiguous and the insert is in the tail section
950 // Elements are discontiguous and the insert is in the head section
952 // For each of those there are two more cases:
953 // Insert is closer to tail
954 // Insert is closer to head
956 // Key: H - self.head
959 // I - Insertion element
960 // A - The element that should be after the insertion point
961 // M - Indicates element was moved
963 let idx = self.wrap_index(self.tail + i);
965 let distance_to_tail = i;
966 let distance_to_head = self.len() - i;
968 let contiguous = self.is_contiguous();
970 match (contiguous, distance_to_tail <= distance_to_head, idx >= self.tail) {
971 (true, true, _) if i == 0 => {
976 // [A o o o o o o . . . . . . . . .]
979 // [A o o o o o o o . . . . . I]
982 self.tail = self.wrap_index(self.tail - 1);
984 (true, true, _) => unsafe {
985 // contiguous, insert closer to tail:
988 // [. . . o o A o o o o . . . . . .]
991 // [. . o o I A o o o o . . . . . .]
994 // contiguous, insert closer to tail and tail is 0:
998 // [o o A o o o o . . . . . . . . .]
1001 // [o I A o o o o o . . . . . . . o]
1004 let new_tail = self.wrap_index(self.tail - 1);
1006 self.copy(new_tail, self.tail, 1);
1007 // Already moved the tail, so we only copy `i - 1` elements.
1008 self.copy(self.tail, self.tail + 1, i - 1);
1010 self.tail = new_tail;
1012 (true, false, _) => unsafe {
1013 // contiguous, insert closer to head:
1016 // [. . . o o o o A o o . . . . . .]
1019 // [. . . o o o o I A o o . . . . .]
1022 self.copy(idx + 1, idx, self.head - idx);
1023 self.head = self.wrap_index(self.head + 1);
1025 (false, true, true) => unsafe {
1026 // discontiguous, insert closer to tail, tail section:
1029 // [o o o o o o . . . . . o o A o o]
1032 // [o o o o o o . . . . o o I A o o]
1035 self.copy(self.tail - 1, self.tail, i);
1038 (false, false, true) => unsafe {
1039 // discontiguous, insert closer to head, tail section:
1042 // [o o . . . . . . . o o o o o A o]
1045 // [o o o . . . . . . o o o o o I A]
1048 // copy elements up to new head
1049 self.copy(1, 0, self.head);
1051 // copy last element into empty spot at bottom of buffer
1052 self.copy(0, self.cap - 1, 1);
1054 // move elements from idx to end forward not including ^ element
1055 self.copy(idx + 1, idx, self.cap - 1 - idx);
1059 (false, true, false) if idx == 0 => unsafe {
1060 // discontiguous, insert is closer to tail, head section,
1061 // and is at index zero in the internal buffer:
1064 // [A o o o o o o o o o . . . o o o]
1067 // [A o o o o o o o o o . . o o o I]
1070 // copy elements up to new tail
1071 self.copy(self.tail - 1, self.tail, self.cap - self.tail);
1073 // copy last element into empty spot at bottom of buffer
1074 self.copy(self.cap - 1, 0, 1);
1078 (false, true, false) => unsafe {
1079 // discontiguous, insert closer to tail, head section:
1082 // [o o o A o o o o o o . . . o o o]
1085 // [o o I A o o o o o o . . o o o o]
1088 // copy elements up to new tail
1089 self.copy(self.tail - 1, self.tail, self.cap - self.tail);
1091 // copy last element into empty spot at bottom of buffer
1092 self.copy(self.cap - 1, 0, 1);
1094 // move elements from idx-1 to end forward not including ^ element
1095 self.copy(0, 1, idx - 1);
1099 (false, false, false) => unsafe {
1100 // discontiguous, insert closer to head, head section:
1103 // [o o o o A o o . . . . . . o o o]
1106 // [o o o o I A o o . . . . . o o o]
1109 self.copy(idx + 1, idx, self.head - idx);
1114 // tail might've been changed so we need to recalculate
1115 let new_idx = self.wrap_index(self.tail + i);
1117 self.buffer_write(new_idx, t);
1121 /// Removes and returns the element at position `i` from the ringbuf.
1122 /// Whichever end is closer to the removal point will be moved to make
1123 /// room, and all the affected elements will be moved to new positions.
1124 /// Returns `None` if `i` is out of bounds.
1128 /// use std::collections::RingBuf;
1130 /// let mut buf = RingBuf::new();
1131 /// buf.push_back(5);
1132 /// buf.push_back(10);
1133 /// buf.push_back(12);
1134 /// buf.push_back(15);
1136 /// assert_eq!(Some(&15), buf.get(2));
1139 pub fn remove(&mut self, i: uint) -> Option<T> {
1140 if self.is_empty() || self.len() <= i {
1144 // There are three main cases:
1145 // Elements are contiguous
1146 // Elements are discontiguous and the removal is in the tail section
1147 // Elements are discontiguous and the removal is in the head section
1148 // - special case when elements are technically contiguous,
1149 // but self.head = 0
1151 // For each of those there are two more cases:
1152 // Insert is closer to tail
1153 // Insert is closer to head
1155 // Key: H - self.head
1157 // o - Valid element
1158 // x - Element marked for removal
1159 // R - Indicates element that is being removed
1160 // M - Indicates element was moved
1162 let idx = self.wrap_index(self.tail + i);
1165 Some(self.buffer_read(idx))
1168 let distance_to_tail = i;
1169 let distance_to_head = self.len() - i;
1171 let contiguous = self.is_contiguous();
1173 match (contiguous, distance_to_tail <= distance_to_head, idx >= self.tail) {
1174 (true, true, _) => unsafe {
1175 // contiguous, remove closer to tail:
1178 // [. . . o o x o o o o . . . . . .]
1181 // [. . . . o o o o o o . . . . . .]
1184 self.copy(self.tail + 1, self.tail, i);
1187 (true, false, _) => unsafe {
1188 // contiguous, remove closer to head:
1191 // [. . . o o o o x o o . . . . . .]
1194 // [. . . o o o o o o . . . . . . .]
1197 self.copy(idx, idx + 1, self.head - idx - 1);
1200 (false, true, true) => unsafe {
1201 // discontiguous, remove closer to tail, tail section:
1204 // [o o o o o o . . . . . o o x o o]
1207 // [o o o o o o . . . . . . o o o o]
1210 self.copy(self.tail + 1, self.tail, i);
1211 self.tail = self.wrap_index(self.tail + 1);
1213 (false, false, false) => unsafe {
1214 // discontiguous, remove closer to head, head section:
1217 // [o o o o x o o . . . . . . o o o]
1220 // [o o o o o o . . . . . . . o o o]
1223 self.copy(idx, idx + 1, self.head - idx - 1);
1226 (false, false, true) => unsafe {
1227 // discontiguous, remove closer to head, tail section:
1230 // [o o o . . . . . . o o o o o x o]
1233 // [o o . . . . . . . o o o o o o o]
1236 // or quasi-discontiguous, remove next to head, tail section:
1239 // [. . . . . . . . . o o o o o x o]
1242 // [. . . . . . . . . o o o o o o .]
1245 // draw in elements in the tail section
1246 self.copy(idx, idx + 1, self.cap - idx - 1);
1248 // Prevents underflow.
1250 // copy first element into empty spot
1251 self.copy(self.cap - 1, 0, 1);
1253 // move elements in the head section backwards
1254 self.copy(0, 1, self.head - 1);
1257 self.head = self.wrap_index(self.head - 1);
1259 (false, true, false) => unsafe {
1260 // discontiguous, remove closer to tail, head section:
1263 // [o o x o o o o o o o . . . o o o]
1266 // [o o o o o o o o o o . . . . o o]
1269 // draw in elements up to idx
1270 self.copy(1, 0, idx);
1272 // copy last element into empty spot
1273 self.copy(0, self.cap - 1, 1);
1275 // move elements from tail to end forward, excluding the last one
1276 self.copy(self.tail + 1, self.tail, self.cap - self.tail - 1);
1278 self.tail = self.wrap_index(self.tail + 1);
1286 impl<T: Clone> RingBuf<T> {
1287 /// Modifies the ringbuf in-place so that `len()` is equal to new_len,
1288 /// either by removing excess elements or by appending copies of a value to the back.
1293 /// use std::collections::RingBuf;
1295 /// let mut buf = RingBuf::new();
1296 /// buf.push_back(5i);
1297 /// buf.push_back(10i);
1298 /// buf.push_back(15);
1299 /// buf.resize(2, 0);
1300 /// buf.resize(6, 20);
1301 /// for (a, b) in [5, 10, 20, 20, 20, 20].iter().zip(buf.iter()) {
1302 /// assert_eq!(a, b);
1305 #[unstable = "matches collection reform specification; waiting on panic semantics"]
1306 pub fn resize(&mut self, new_len: uint, value: T) {
1307 let len = self.len();
1310 self.extend(repeat(value).take(new_len - len))
1312 self.truncate(new_len);
1317 /// Returns the index in the underlying buffer for a given logical element index.
1319 fn wrap_index(index: uint, size: uint) -> uint {
1320 // size is always a power of 2
1324 /// Calculate the number of elements left to be read in the buffer
1326 fn count(tail: uint, head: uint, size: uint) -> uint {
1327 // size is always a power of 2
1328 (head - tail) & (size - 1)
1331 /// `RingBuf` iterator.
1333 pub struct Iter<'a, T:'a> {
1339 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1340 impl<'a, T> Clone for Iter<'a, T> {
1341 fn clone(&self) -> Iter<'a, T> {
1351 impl<'a, T> Iterator for Iter<'a, T> {
1355 fn next(&mut self) -> Option<&'a T> {
1356 if self.tail == self.head {
1359 let tail = self.tail;
1360 self.tail = wrap_index(self.tail + 1, self.ring.len());
1361 unsafe { Some(self.ring.get_unchecked(tail)) }
1365 fn size_hint(&self) -> (uint, Option<uint>) {
1366 let len = count(self.tail, self.head, self.ring.len());
1372 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
1374 fn next_back(&mut self) -> Option<&'a T> {
1375 if self.tail == self.head {
1378 self.head = wrap_index(self.head - 1, self.ring.len());
1379 unsafe { Some(self.ring.get_unchecked(self.head)) }
1384 impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
1387 impl<'a, T> RandomAccessIterator for Iter<'a, T> {
1389 fn indexable(&self) -> uint {
1390 let (len, _) = self.size_hint();
1395 fn idx(&mut self, j: uint) -> Option<&'a T> {
1396 if j >= self.indexable() {
1399 let idx = wrap_index(self.tail + j, self.ring.len());
1400 unsafe { Some(self.ring.get_unchecked(idx)) }
1405 // FIXME This was implemented differently from Iter because of a problem
1406 // with returning the mutable reference. I couldn't find a way to
1407 // make the lifetime checker happy so, but there should be a way.
1408 /// `RingBuf` mutable iterator.
1410 pub struct IterMut<'a, T:'a> {
1415 marker: marker::ContravariantLifetime<'a>,
1419 impl<'a, T> Iterator for IterMut<'a, T> {
1420 type Item = &'a mut T;
1423 fn next(&mut self) -> Option<&'a mut T> {
1424 if self.tail == self.head {
1427 let tail = self.tail;
1428 self.tail = wrap_index(self.tail + 1, self.cap);
1431 Some(&mut *self.ptr.offset(tail as int))
1436 fn size_hint(&self) -> (uint, Option<uint>) {
1437 let len = count(self.tail, self.head, self.cap);
1443 impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
1445 fn next_back(&mut self) -> Option<&'a mut T> {
1446 if self.tail == self.head {
1449 self.head = wrap_index(self.head - 1, self.cap);
1452 Some(&mut *self.ptr.offset(self.head as int))
1458 impl<'a, T> ExactSizeIterator for IterMut<'a, T> {}
1460 /// A by-value RingBuf iterator
1462 pub struct IntoIter<T> {
1467 impl<T> Iterator for IntoIter<T> {
1471 fn next(&mut self) -> Option<T> {
1472 self.inner.pop_front()
1476 fn size_hint(&self) -> (uint, Option<uint>) {
1477 let len = self.inner.len();
1483 impl<T> DoubleEndedIterator for IntoIter<T> {
1485 fn next_back(&mut self) -> Option<T> {
1486 self.inner.pop_back()
1491 impl<T> ExactSizeIterator for IntoIter<T> {}
1493 /// A draining RingBuf iterator
1494 #[unstable = "matches collection reform specification, waiting for dust to settle"]
1495 pub struct Drain<'a, T: 'a> {
1496 inner: &'a mut RingBuf<T>,
1499 #[unsafe_destructor]
1501 impl<'a, T: 'a> Drop for Drain<'a, T> {
1502 fn drop(&mut self) {
1504 self.inner.head = 0;
1505 self.inner.tail = 0;
1510 impl<'a, T: 'a> Iterator for Drain<'a, T> {
1514 fn next(&mut self) -> Option<T> {
1515 self.inner.pop_front()
1519 fn size_hint(&self) -> (uint, Option<uint>) {
1520 let len = self.inner.len();
1526 impl<'a, T: 'a> DoubleEndedIterator for Drain<'a, T> {
1528 fn next_back(&mut self) -> Option<T> {
1529 self.inner.pop_back()
1534 impl<'a, T: 'a> ExactSizeIterator for Drain<'a, T> {}
1537 impl<A: PartialEq> PartialEq for RingBuf<A> {
1538 fn eq(&self, other: &RingBuf<A>) -> bool {
1539 self.len() == other.len() &&
1540 self.iter().zip(other.iter()).all(|(a, b)| a.eq(b))
1545 impl<A: Eq> Eq for RingBuf<A> {}
1548 impl<A: PartialOrd> PartialOrd for RingBuf<A> {
1549 fn partial_cmp(&self, other: &RingBuf<A>) -> Option<Ordering> {
1550 iter::order::partial_cmp(self.iter(), other.iter())
1555 impl<A: Ord> Ord for RingBuf<A> {
1557 fn cmp(&self, other: &RingBuf<A>) -> Ordering {
1558 iter::order::cmp(self.iter(), other.iter())
1563 impl<S: Writer, A: Hash<S>> Hash<S> for RingBuf<A> {
1564 fn hash(&self, state: &mut S) {
1565 self.len().hash(state);
1566 for elt in self.iter() {
1573 impl<A> Index<uint> for RingBuf<A> {
1577 fn index<'a>(&'a self, i: &uint) -> &'a A {
1578 self.get(*i).expect("Out of bounds access")
1583 impl<A> IndexMut<uint> for RingBuf<A> {
1587 fn index_mut<'a>(&'a mut self, i: &uint) -> &'a mut A {
1588 self.get_mut(*i).expect("Out of bounds access")
1593 impl<A> FromIterator<A> for RingBuf<A> {
1594 fn from_iter<T: Iterator<Item=A>>(iterator: T) -> RingBuf<A> {
1595 let (lower, _) = iterator.size_hint();
1596 let mut deq = RingBuf::with_capacity(lower);
1597 deq.extend(iterator);
1603 impl<A> Extend<A> for RingBuf<A> {
1604 fn extend<T: Iterator<Item=A>>(&mut self, mut iterator: T) {
1605 for elt in iterator {
1606 self.push_back(elt);
1612 impl<T: fmt::Show> fmt::Show for RingBuf<T> {
1613 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1614 try!(write!(f, "["));
1616 for (i, e) in self.iter().enumerate() {
1617 if i != 0 { try!(write!(f, ", ")); }
1618 try!(write!(f, "{}", *e));
1628 use self::Taggypar::*;
1639 #[allow(deprecated)]
1641 let mut d = RingBuf::new();
1642 assert_eq!(d.len(), 0u);
1646 assert_eq!(d.len(), 3u);
1648 assert_eq!(d.len(), 4u);
1649 debug!("{}", d.front());
1650 assert_eq!(*d.front().unwrap(), 42);
1651 debug!("{}", d.back());
1652 assert_eq!(*d.back().unwrap(), 137);
1653 let mut i = d.pop_front();
1655 assert_eq!(i, Some(42));
1658 assert_eq!(i, Some(137));
1661 assert_eq!(i, Some(137));
1664 assert_eq!(i, Some(17));
1665 assert_eq!(d.len(), 0u);
1667 assert_eq!(d.len(), 1u);
1669 assert_eq!(d.len(), 2u);
1671 assert_eq!(d.len(), 3u);
1673 assert_eq!(d.len(), 4u);
1678 assert_eq!(d[0], 1);
1679 assert_eq!(d[1], 2);
1680 assert_eq!(d[2], 3);
1681 assert_eq!(d[3], 4);
1685 fn test_parameterized<T:Clone + PartialEq + Show>(a: T, b: T, c: T, d: T) {
1686 let mut deq = RingBuf::new();
1687 assert_eq!(deq.len(), 0);
1688 deq.push_front(a.clone());
1689 deq.push_front(b.clone());
1690 deq.push_back(c.clone());
1691 assert_eq!(deq.len(), 3);
1692 deq.push_back(d.clone());
1693 assert_eq!(deq.len(), 4);
1694 assert_eq!((*deq.front().unwrap()).clone(), b.clone());
1695 assert_eq!((*deq.back().unwrap()).clone(), d.clone());
1696 assert_eq!(deq.pop_front().unwrap(), b.clone());
1697 assert_eq!(deq.pop_back().unwrap(), d.clone());
1698 assert_eq!(deq.pop_back().unwrap(), c.clone());
1699 assert_eq!(deq.pop_back().unwrap(), a.clone());
1700 assert_eq!(deq.len(), 0);
1701 deq.push_back(c.clone());
1702 assert_eq!(deq.len(), 1);
1703 deq.push_front(b.clone());
1704 assert_eq!(deq.len(), 2);
1705 deq.push_back(d.clone());
1706 assert_eq!(deq.len(), 3);
1707 deq.push_front(a.clone());
1708 assert_eq!(deq.len(), 4);
1709 assert_eq!(deq[0].clone(), a.clone());
1710 assert_eq!(deq[1].clone(), b.clone());
1711 assert_eq!(deq[2].clone(), c.clone());
1712 assert_eq!(deq[3].clone(), d.clone());
1716 fn test_push_front_grow() {
1717 let mut deq = RingBuf::new();
1718 for i in range(0u, 66) {
1721 assert_eq!(deq.len(), 66);
1723 for i in range(0u, 66) {
1724 assert_eq!(deq[i], 65 - i);
1727 let mut deq = RingBuf::new();
1728 for i in range(0u, 66) {
1732 for i in range(0u, 66) {
1733 assert_eq!(deq[i], i);
1739 let mut deq = RingBuf::new();
1740 for i in range(1u, 4) {
1743 assert_eq!(deq[1], 2);
1748 fn test_index_out_of_bounds() {
1749 let mut deq = RingBuf::new();
1750 for i in range(1u, 4) {
1757 fn bench_new(b: &mut test::Bencher) {
1759 let ring: RingBuf<u64> = RingBuf::new();
1760 test::black_box(ring);
1765 fn bench_push_back_100(b: &mut test::Bencher) {
1766 let mut deq = RingBuf::with_capacity(101);
1768 for i in range(0i, 100) {
1777 fn bench_push_front_100(b: &mut test::Bencher) {
1778 let mut deq = RingBuf::with_capacity(101);
1780 for i in range(0i, 100) {
1789 fn bench_pop_back_100(b: &mut test::Bencher) {
1790 let mut deq: RingBuf<int> = RingBuf::with_capacity(101);
1795 while !deq.is_empty() {
1796 test::black_box(deq.pop_back());
1802 fn bench_pop_front_100(b: &mut test::Bencher) {
1803 let mut deq: RingBuf<int> = RingBuf::with_capacity(101);
1808 while !deq.is_empty() {
1809 test::black_box(deq.pop_front());
1815 fn bench_grow_1025(b: &mut test::Bencher) {
1817 let mut deq = RingBuf::new();
1818 for i in range(0i, 1025) {
1821 test::black_box(deq);
1826 fn bench_iter_1000(b: &mut test::Bencher) {
1827 let ring: RingBuf<int> = range(0i, 1000).collect();
1831 for &i in ring.iter() {
1834 test::black_box(sum);
1839 fn bench_mut_iter_1000(b: &mut test::Bencher) {
1840 let mut ring: RingBuf<int> = range(0i, 1000).collect();
1844 for i in ring.iter_mut() {
1847 test::black_box(sum);
1851 #[derive(Clone, PartialEq, Show)]
1855 Three(int, int, int),
1858 #[derive(Clone, PartialEq, Show)]
1862 Threepar(int, int, int),
1865 #[derive(Clone, PartialEq, Show)]
1873 fn test_param_int() {
1874 test_parameterized::<int>(5, 72, 64, 175);
1878 fn test_param_taggy() {
1879 test_parameterized::<Taggy>(One(1), Two(1, 2), Three(1, 2, 3), Two(17, 42));
1883 fn test_param_taggypar() {
1884 test_parameterized::<Taggypar<int>>(Onepar::<int>(1),
1885 Twopar::<int>(1, 2),
1886 Threepar::<int>(1, 2, 3),
1887 Twopar::<int>(17, 42));
1891 fn test_param_reccy() {
1892 let reccy1 = RecCy { x: 1, y: 2, t: One(1) };
1893 let reccy2 = RecCy { x: 345, y: 2, t: Two(1, 2) };
1894 let reccy3 = RecCy { x: 1, y: 777, t: Three(1, 2, 3) };
1895 let reccy4 = RecCy { x: 19, y: 252, t: Two(17, 42) };
1896 test_parameterized::<RecCy>(reccy1, reccy2, reccy3, reccy4);
1900 fn test_with_capacity() {
1901 let mut d = RingBuf::with_capacity(0);
1903 assert_eq!(d.len(), 1);
1904 let mut d = RingBuf::with_capacity(50);
1906 assert_eq!(d.len(), 1);
1910 fn test_with_capacity_non_power_two() {
1911 let mut d3 = RingBuf::with_capacity(3);
1916 assert_eq!(d3.pop_front(), Some(1));
1918 assert_eq!(d3.front(), None);
1925 assert_eq!(d3.pop_front(), Some(3));
1927 // Pushing the lo past half way point to trigger
1928 // the 'B' scenario for growth
1935 // There used to be a bug here about how the
1936 // RingBuf made growth assumptions about the
1937 // underlying Vec which didn't hold and lead
1939 // (Vec grows to next power of two)
1940 //good- [9, 12, 15, X, X, X, X, |6]
1941 //bug- [15, 12, X, X, X, |6, X, X]
1942 assert_eq!(d3.pop_front(), Some(6));
1944 // Which leads us to the following state which
1945 // would be a failure case.
1946 //bug- [15, 12, X, X, X, X, |X, X]
1947 assert_eq!(d3.front(), Some(&9));
1951 fn test_reserve_exact() {
1952 let mut d = RingBuf::new();
1954 d.reserve_exact(50);
1955 assert!(d.capacity() >= 51);
1956 let mut d = RingBuf::new();
1958 d.reserve_exact(50);
1959 assert!(d.capacity() >= 51);
1964 let mut d = RingBuf::new();
1967 assert!(d.capacity() >= 51);
1968 let mut d = RingBuf::new();
1971 assert!(d.capacity() >= 51);
1976 let mut d: RingBuf<int> = range(0i, 5).collect();
1979 assert_eq!(d.iter().map(|&x|x).collect::<Vec<int>>(), vec!(4, 2, 3, 1));
1984 let mut d = RingBuf::new();
1985 assert_eq!(d.iter().next(), None);
1986 assert_eq!(d.iter().size_hint(), (0, Some(0)));
1988 for i in range(0i, 5) {
1992 let b: &[_] = &[&0,&1,&2,&3,&4];
1993 assert_eq!(d.iter().collect::<Vec<&int>>(), b);
1996 for i in range(6i, 9) {
2000 let b: &[_] = &[&8,&7,&6,&0,&1,&2,&3,&4];
2001 assert_eq!(d.iter().collect::<Vec<&int>>(), b);
2004 let mut it = d.iter();
2005 let mut len = d.len();
2009 _ => { len -= 1; assert_eq!(it.size_hint(), (len, Some(len))) }
2015 fn test_rev_iter() {
2016 let mut d = RingBuf::new();
2017 assert_eq!(d.iter().rev().next(), None);
2019 for i in range(0i, 5) {
2023 let b: &[_] = &[&4,&3,&2,&1,&0];
2024 assert_eq!(d.iter().rev().collect::<Vec<&int>>(), b);
2027 for i in range(6i, 9) {
2030 let b: &[_] = &[&4,&3,&2,&1,&0,&6,&7,&8];
2031 assert_eq!(d.iter().rev().collect::<Vec<&int>>(), b);
2035 fn test_mut_rev_iter_wrap() {
2036 let mut d = RingBuf::with_capacity(3);
2037 assert!(d.iter_mut().rev().next().is_none());
2042 assert_eq!(d.pop_front(), Some(1));
2045 assert_eq!(d.iter_mut().rev().map(|x| *x).collect::<Vec<int>>(),
2050 fn test_mut_iter() {
2051 let mut d = RingBuf::new();
2052 assert!(d.iter_mut().next().is_none());
2054 for i in range(0u, 3) {
2058 for (i, elt) in d.iter_mut().enumerate() {
2059 assert_eq!(*elt, 2 - i);
2064 let mut it = d.iter_mut();
2065 assert_eq!(*it.next().unwrap(), 0);
2066 assert_eq!(*it.next().unwrap(), 1);
2067 assert_eq!(*it.next().unwrap(), 2);
2068 assert!(it.next().is_none());
2073 fn test_mut_rev_iter() {
2074 let mut d = RingBuf::new();
2075 assert!(d.iter_mut().rev().next().is_none());
2077 for i in range(0u, 3) {
2081 for (i, elt) in d.iter_mut().rev().enumerate() {
2082 assert_eq!(*elt, i);
2087 let mut it = d.iter_mut().rev();
2088 assert_eq!(*it.next().unwrap(), 0);
2089 assert_eq!(*it.next().unwrap(), 1);
2090 assert_eq!(*it.next().unwrap(), 2);
2091 assert!(it.next().is_none());
2096 fn test_into_iter() {
2100 let d: RingBuf<int> = RingBuf::new();
2101 let mut iter = d.into_iter();
2103 assert_eq!(iter.size_hint(), (0, Some(0)));
2104 assert_eq!(iter.next(), None);
2105 assert_eq!(iter.size_hint(), (0, Some(0)));
2110 let mut d = RingBuf::new();
2111 for i in range(0i, 5) {
2115 let b = vec![0,1,2,3,4];
2116 assert_eq!(d.into_iter().collect::<Vec<int>>(), b);
2121 let mut d = RingBuf::new();
2122 for i in range(0i, 5) {
2125 for i in range(6, 9) {
2129 let b = vec![8,7,6,0,1,2,3,4];
2130 assert_eq!(d.into_iter().collect::<Vec<int>>(), b);
2135 let mut d = RingBuf::new();
2136 for i in range(0i, 5) {
2139 for i in range(6, 9) {
2143 let mut it = d.into_iter();
2144 assert_eq!(it.size_hint(), (8, Some(8)));
2145 assert_eq!(it.next(), Some(8));
2146 assert_eq!(it.size_hint(), (7, Some(7)));
2147 assert_eq!(it.next_back(), Some(4));
2148 assert_eq!(it.size_hint(), (6, Some(6)));
2149 assert_eq!(it.next(), Some(7));
2150 assert_eq!(it.size_hint(), (5, Some(5)));
2159 let mut d: RingBuf<int> = RingBuf::new();
2162 let mut iter = d.drain();
2164 assert_eq!(iter.size_hint(), (0, Some(0)));
2165 assert_eq!(iter.next(), None);
2166 assert_eq!(iter.size_hint(), (0, Some(0)));
2169 assert!(d.is_empty());
2174 let mut d = RingBuf::new();
2175 for i in range(0i, 5) {
2179 assert_eq!(d.drain().collect::<Vec<int>>(), [0, 1, 2, 3, 4]);
2180 assert!(d.is_empty());
2185 let mut d = RingBuf::new();
2186 for i in range(0i, 5) {
2189 for i in range(6, 9) {
2193 assert_eq!(d.drain().collect::<Vec<int>>(), [8,7,6,0,1,2,3,4]);
2194 assert!(d.is_empty());
2199 let mut d = RingBuf::new();
2200 for i in range(0i, 5) {
2203 for i in range(6, 9) {
2208 let mut it = d.drain();
2209 assert_eq!(it.size_hint(), (8, Some(8)));
2210 assert_eq!(it.next(), Some(8));
2211 assert_eq!(it.size_hint(), (7, Some(7)));
2212 assert_eq!(it.next_back(), Some(4));
2213 assert_eq!(it.size_hint(), (6, Some(6)));
2214 assert_eq!(it.next(), Some(7));
2215 assert_eq!(it.size_hint(), (5, Some(5)));
2217 assert!(d.is_empty());
2222 fn test_from_iter() {
2224 let v = vec!(1i,2,3,4,5,6,7);
2225 let deq: RingBuf<int> = v.iter().map(|&x| x).collect();
2226 let u: Vec<int> = deq.iter().map(|&x| x).collect();
2229 let seq = iter::count(0u, 2).take(256);
2230 let deq: RingBuf<uint> = seq.collect();
2231 for (i, &x) in deq.iter().enumerate() {
2234 assert_eq!(deq.len(), 256);
2239 let mut d = RingBuf::new();
2244 assert_eq!(d.len(), 4u);
2245 let mut e = d.clone();
2246 assert_eq!(e.len(), 4u);
2247 while !d.is_empty() {
2248 assert_eq!(d.pop_back(), e.pop_back());
2250 assert_eq!(d.len(), 0u);
2251 assert_eq!(e.len(), 0u);
2256 let mut d = RingBuf::new();
2257 assert!(d == RingBuf::with_capacity(0));
2262 let mut e = RingBuf::with_capacity(0);
2272 assert!(e == RingBuf::new());
2277 let mut x = RingBuf::new();
2278 let mut y = RingBuf::new();
2290 assert!(hash::hash(&x) == hash::hash(&y));
2295 let x = RingBuf::new();
2296 let mut y = RingBuf::new();
2308 let ringbuf: RingBuf<int> = range(0i, 10).collect();
2309 assert!(format!("{}", ringbuf) == "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]");
2311 let ringbuf: RingBuf<&str> = vec!["just", "one", "test", "more"].iter()
2314 assert!(format!("{}", ringbuf) == "[just, one, test, more]");
2319 static mut drops: uint = 0;
2321 impl Drop for Elem {
2322 fn drop(&mut self) {
2323 unsafe { drops += 1; }
2327 let mut ring = RingBuf::new();
2328 ring.push_back(Elem);
2329 ring.push_front(Elem);
2330 ring.push_back(Elem);
2331 ring.push_front(Elem);
2334 assert_eq!(unsafe {drops}, 4);
2338 fn test_drop_with_pop() {
2339 static mut drops: uint = 0;
2341 impl Drop for Elem {
2342 fn drop(&mut self) {
2343 unsafe { drops += 1; }
2347 let mut ring = RingBuf::new();
2348 ring.push_back(Elem);
2349 ring.push_front(Elem);
2350 ring.push_back(Elem);
2351 ring.push_front(Elem);
2353 drop(ring.pop_back());
2354 drop(ring.pop_front());
2355 assert_eq!(unsafe {drops}, 2);
2358 assert_eq!(unsafe {drops}, 4);
2362 fn test_drop_clear() {
2363 static mut drops: uint = 0;
2365 impl Drop for Elem {
2366 fn drop(&mut self) {
2367 unsafe { drops += 1; }
2371 let mut ring = RingBuf::new();
2372 ring.push_back(Elem);
2373 ring.push_front(Elem);
2374 ring.push_back(Elem);
2375 ring.push_front(Elem);
2377 assert_eq!(unsafe {drops}, 4);
2380 assert_eq!(unsafe {drops}, 4);
2384 fn test_reserve_grow() {
2385 // test growth path A
2386 // [T o o H] -> [T o o H . . . . ]
2387 let mut ring = RingBuf::with_capacity(4);
2388 for i in range(0i, 3) {
2392 for i in range(0i, 3) {
2393 assert_eq!(ring.pop_front(), Some(i));
2396 // test growth path B
2397 // [H T o o] -> [. T o o H . . . ]
2398 let mut ring = RingBuf::with_capacity(4);
2399 for i in range(0i, 1) {
2401 assert_eq!(ring.pop_front(), Some(i));
2403 for i in range(0i, 3) {
2407 for i in range(0i, 3) {
2408 assert_eq!(ring.pop_front(), Some(i));
2411 // test growth path C
2412 // [o o H T] -> [o o H . . . . T ]
2413 let mut ring = RingBuf::with_capacity(4);
2414 for i in range(0i, 3) {
2416 assert_eq!(ring.pop_front(), Some(i));
2418 for i in range(0i, 3) {
2422 for i in range(0i, 3) {
2423 assert_eq!(ring.pop_front(), Some(i));
2429 let mut ring = RingBuf::new();
2431 assert_eq!(ring.get(0), Some(&0));
2432 assert_eq!(ring.get(1), None);
2435 assert_eq!(ring.get(0), Some(&0));
2436 assert_eq!(ring.get(1), Some(&1));
2437 assert_eq!(ring.get(2), None);
2440 assert_eq!(ring.get(0), Some(&0));
2441 assert_eq!(ring.get(1), Some(&1));
2442 assert_eq!(ring.get(2), Some(&2));
2443 assert_eq!(ring.get(3), None);
2445 assert_eq!(ring.pop_front(), Some(0));
2446 assert_eq!(ring.get(0), Some(&1));
2447 assert_eq!(ring.get(1), Some(&2));
2448 assert_eq!(ring.get(2), None);
2450 assert_eq!(ring.pop_front(), Some(1));
2451 assert_eq!(ring.get(0), Some(&2));
2452 assert_eq!(ring.get(1), None);
2454 assert_eq!(ring.pop_front(), Some(2));
2455 assert_eq!(ring.get(0), None);
2456 assert_eq!(ring.get(1), None);
2461 let mut ring = RingBuf::new();
2462 for i in range(0i, 3) {
2466 match ring.get_mut(1) {
2471 assert_eq!(ring.get_mut(0), Some(&mut 0));
2472 assert_eq!(ring.get_mut(1), Some(&mut -1));
2473 assert_eq!(ring.get_mut(2), Some(&mut 2));
2474 assert_eq!(ring.get_mut(3), None);
2476 assert_eq!(ring.pop_front(), Some(0));
2477 assert_eq!(ring.get_mut(0), Some(&mut -1));
2478 assert_eq!(ring.get_mut(1), Some(&mut 2));
2479 assert_eq!(ring.get_mut(2), None);
2483 fn test_swap_front_back_remove() {
2484 fn test(back: bool) {
2485 // This test checks that every single combination of tail position and length is tested.
2486 // Capacity 15 should be large enough to cover every case.
2487 let mut tester = RingBuf::with_capacity(15);
2488 let usable_cap = tester.capacity();
2489 let final_len = usable_cap / 2;
2491 for len in range(0, final_len) {
2492 let expected = if back {
2493 range(0, len).collect()
2495 range(0, len).rev().collect()
2497 for tail_pos in range(0, usable_cap) {
2498 tester.tail = tail_pos;
2499 tester.head = tail_pos;
2501 for i in range(0, len * 2) {
2502 tester.push_front(i);
2504 for i in range(0, len) {
2505 assert_eq!(tester.swap_back_remove(i), Some(len * 2 - 1 - i));
2508 for i in range(0, len * 2) {
2509 tester.push_back(i);
2511 for i in range(0, len) {
2512 let idx = tester.len() - 1 - i;
2513 assert_eq!(tester.swap_front_remove(idx), Some(len * 2 - 1 - i));
2516 assert!(tester.tail < tester.cap);
2517 assert!(tester.head < tester.cap);
2518 assert_eq!(tester, expected);
2528 // This test checks that every single combination of tail position, length, and
2529 // insertion position is tested. Capacity 15 should be large enough to cover every case.
2531 let mut tester = RingBuf::with_capacity(15);
2532 // can't guarantee we got 15, so have to get what we got.
2533 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2534 // this test isn't covering what it wants to
2535 let cap = tester.capacity();
2538 // len is the length *after* insertion
2539 for len in range(1, cap) {
2540 // 0, 1, 2, .., len - 1
2541 let expected = iter::count(0, 1).take(len).collect();
2542 for tail_pos in range(0, cap) {
2543 for to_insert in range(0, len) {
2544 tester.tail = tail_pos;
2545 tester.head = tail_pos;
2546 for i in range(0, len) {
2548 tester.push_back(i);
2551 tester.insert(to_insert, to_insert);
2552 assert!(tester.tail < tester.cap);
2553 assert!(tester.head < tester.cap);
2554 assert_eq!(tester, expected);
2562 // This test checks that every single combination of tail position, length, and
2563 // removal position is tested. Capacity 15 should be large enough to cover every case.
2565 let mut tester = RingBuf::with_capacity(15);
2566 // can't guarantee we got 15, so have to get what we got.
2567 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2568 // this test isn't covering what it wants to
2569 let cap = tester.capacity();
2571 // len is the length *after* removal
2572 for len in range(0, cap - 1) {
2573 // 0, 1, 2, .., len - 1
2574 let expected = iter::count(0, 1).take(len).collect();
2575 for tail_pos in range(0, cap) {
2576 for to_remove in range(0, len + 1) {
2577 tester.tail = tail_pos;
2578 tester.head = tail_pos;
2579 for i in range(0, len) {
2581 tester.push_back(1234);
2583 tester.push_back(i);
2585 if to_remove == len {
2586 tester.push_back(1234);
2588 tester.remove(to_remove);
2589 assert!(tester.tail < tester.cap);
2590 assert!(tester.head < tester.cap);
2591 assert_eq!(tester, expected);
2598 fn test_shrink_to_fit() {
2599 // This test checks that every single combination of head and tail position,
2600 // is tested. Capacity 15 should be large enough to cover every case.
2602 let mut tester = RingBuf::with_capacity(15);
2603 // can't guarantee we got 15, so have to get what we got.
2604 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2605 // this test isn't covering what it wants to
2606 let cap = tester.capacity();
2608 let max_cap = tester.capacity();
2610 for len in range(0, cap + 1) {
2611 // 0, 1, 2, .., len - 1
2612 let expected = iter::count(0, 1).take(len).collect();
2613 for tail_pos in range(0, max_cap + 1) {
2614 tester.tail = tail_pos;
2615 tester.head = tail_pos;
2617 for i in range(0, len) {
2618 tester.push_back(i);
2620 tester.shrink_to_fit();
2621 assert!(tester.capacity() <= cap);
2622 assert!(tester.tail < tester.cap);
2623 assert!(tester.head < tester.cap);
2624 assert_eq!(tester, expected);
2631 let mut ring = RingBuf::new();
2632 ring.push_back(10i);
2633 ring.push_back(20i);
2634 assert_eq!(ring.front(), Some(&10));
2636 assert_eq!(ring.front(), Some(&20));
2638 assert_eq!(ring.front(), None);
2642 fn test_as_slices() {
2643 let mut ring: RingBuf<int> = RingBuf::with_capacity(127);
2644 let cap = ring.capacity() as int;
2646 let last = cap - first;
2647 for i in range(0, first) {
2650 let (left, right) = ring.as_slices();
2651 let expected: Vec<_> = range(0, i+1).collect();
2652 assert_eq!(left, expected);
2653 assert_eq!(right, []);
2656 for j in range(-last, 0) {
2658 let (left, right) = ring.as_slices();
2659 let expected_left: Vec<_> = range(-last, j+1).rev().collect();
2660 let expected_right: Vec<_> = range(0, first).collect();
2661 assert_eq!(left, expected_left);
2662 assert_eq!(right, expected_right);
2665 assert_eq!(ring.len() as int, cap);
2666 assert_eq!(ring.capacity() as int, cap);
2670 fn test_as_mut_slices() {
2671 let mut ring: RingBuf<int> = RingBuf::with_capacity(127);
2672 let cap = ring.capacity() as int;
2674 let last = cap - first;
2675 for i in range(0, first) {
2678 let (left, right) = ring.as_mut_slices();
2679 let expected: Vec<_> = range(0, i+1).collect();
2680 assert_eq!(left, expected);
2681 assert_eq!(right, []);
2684 for j in range(-last, 0) {
2686 let (left, right) = ring.as_mut_slices();
2687 let expected_left: Vec<_> = range(-last, j+1).rev().collect();
2688 let expected_right: Vec<_> = range(0, first).collect();
2689 assert_eq!(left, expected_left);
2690 assert_eq!(right, expected_right);
2693 assert_eq!(ring.len() as int, cap);
2694 assert_eq!(ring.capacity() as int, cap);