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.
19 use core::cmp::Ordering;
20 use core::default::Default;
22 use core::iter::{self, repeat, FromIterator, RandomAccessIterator};
25 use core::num::{Int, UnsignedInt};
26 use core::ops::{Index, IndexMut};
28 use core::raw::Slice as RawSlice;
30 use std::hash::{Writer, Hash, Hasher};
35 static INITIAL_CAPACITY: uint = 7u; // 2^3 - 1
36 static MINIMUM_CAPACITY: uint = 1u; // 2 - 1
38 /// `RingBuf` is a circular buffer, which can be used as a double-ended queue efficiently.
40 pub struct RingBuf<T> {
41 // tail and head are pointers into the buffer. Tail always points
42 // to the first element that could be read, Head always points
43 // to where data should be written.
44 // If tail == head the buffer is empty. The length of the ringbuf
45 // is defined as the distance between the two.
54 unsafe impl<T: Send> Send for RingBuf<T> {}
57 unsafe impl<T: Sync> Sync for RingBuf<T> {}
60 impl<T: Clone> Clone for RingBuf<T> {
61 fn clone(&self) -> RingBuf<T> {
62 self.iter().map(|t| t.clone()).collect()
68 impl<T> Drop for RingBuf<T> {
72 if mem::size_of::<T>() != 0 {
73 heap::deallocate(self.ptr as *mut u8,
74 self.cap * mem::size_of::<T>(),
75 mem::min_align_of::<T>())
82 impl<T> Default for RingBuf<T> {
84 fn default() -> RingBuf<T> { RingBuf::new() }
88 /// Turn ptr into a slice
90 unsafe fn buffer_as_slice(&self) -> &[T] {
91 mem::transmute(RawSlice { data: self.ptr, len: self.cap })
94 /// Turn ptr into a mut slice
96 unsafe fn buffer_as_mut_slice(&mut self) -> &mut [T] {
97 mem::transmute(RawSlice { data: self.ptr, len: self.cap })
100 /// Moves an element out of the buffer
102 unsafe fn buffer_read(&mut self, off: uint) -> T {
103 ptr::read(self.ptr.offset(off as int))
106 /// Writes an element into the buffer, moving it.
108 unsafe fn buffer_write(&mut self, off: uint, t: T) {
109 ptr::write(self.ptr.offset(off as int), t);
112 /// Returns true iff the buffer is at capacity
114 fn is_full(&self) -> bool { self.cap - self.len() == 1 }
116 /// Returns the index in the underlying buffer for a given logical element index.
118 fn wrap_index(&self, idx: uint) -> uint { wrap_index(idx, self.cap) }
120 /// Copies a contiguous block of memory len long from src to dst
122 unsafe fn copy(&self, dst: uint, src: uint, len: uint) {
123 debug_assert!(dst + len <= self.cap, "dst={} src={} len={} cap={}", dst, src, len,
125 debug_assert!(src + len <= self.cap, "dst={} src={} len={} cap={}", dst, src, len,
128 self.ptr.offset(dst as int),
129 self.ptr.offset(src as int),
133 /// Copies a contiguous block of memory len long from src to dst
135 unsafe fn copy_nonoverlapping(&self, dst: uint, src: uint, len: uint) {
136 debug_assert!(dst + len <= self.cap, "dst={} src={} len={} cap={}", dst, src, len,
138 debug_assert!(src + len <= self.cap, "dst={} src={} len={} cap={}", dst, src, len,
140 ptr::copy_nonoverlapping_memory(
141 self.ptr.offset(dst as int),
142 self.ptr.offset(src as int),
148 /// Creates an empty `RingBuf`.
150 pub fn new() -> RingBuf<T> {
151 RingBuf::with_capacity(INITIAL_CAPACITY)
154 /// Creates an empty `RingBuf` with space for at least `n` elements.
156 pub fn with_capacity(n: uint) -> RingBuf<T> {
157 // +1 since the ringbuffer always leaves one space empty
158 let cap = cmp::max(n + 1, MINIMUM_CAPACITY + 1).next_power_of_two();
159 assert!(cap > n, "capacity overflow");
160 let size = cap.checked_mul(mem::size_of::<T>())
161 .expect("capacity overflow");
163 let ptr = if mem::size_of::<T>() != 0 {
165 let ptr = heap::allocate(size, mem::min_align_of::<T>()) as *mut T;;
166 if ptr.is_null() { ::alloc::oom() }
170 heap::EMPTY as *mut T
181 /// Retrieves an element in the `RingBuf` by index.
186 /// use std::collections::RingBuf;
188 /// let mut buf = RingBuf::new();
189 /// buf.push_back(3i);
190 /// buf.push_back(4);
191 /// buf.push_back(5);
192 /// assert_eq!(buf.get(1).unwrap(), &4);
195 pub fn get(&self, i: uint) -> Option<&T> {
197 let idx = self.wrap_index(self.tail + i);
198 unsafe { Some(&*self.ptr.offset(idx as int)) }
204 /// Retrieves an element in the `RingBuf` mutably by index.
209 /// use std::collections::RingBuf;
211 /// let mut buf = RingBuf::new();
212 /// buf.push_back(3i);
213 /// buf.push_back(4);
214 /// buf.push_back(5);
215 /// match buf.get_mut(1) {
222 /// assert_eq!(buf[1], 7);
225 pub fn get_mut(&mut self, i: uint) -> Option<&mut T> {
227 let idx = self.wrap_index(self.tail + i);
228 unsafe { Some(&mut *self.ptr.offset(idx as int)) }
234 /// Swaps elements at indices `i` and `j`.
236 /// `i` and `j` may be equal.
238 /// Fails if there is no element with either index.
243 /// use std::collections::RingBuf;
245 /// let mut buf = RingBuf::new();
246 /// buf.push_back(3i);
247 /// buf.push_back(4);
248 /// buf.push_back(5);
250 /// assert_eq!(buf[0], 5);
251 /// assert_eq!(buf[2], 3);
254 pub fn swap(&mut self, i: uint, j: uint) {
255 assert!(i < self.len());
256 assert!(j < self.len());
257 let ri = self.wrap_index(self.tail + i);
258 let rj = self.wrap_index(self.tail + j);
260 ptr::swap(self.ptr.offset(ri as int), self.ptr.offset(rj as int))
264 /// Returns the number of elements the `RingBuf` can hold without
270 /// use std::collections::RingBuf;
272 /// let buf: RingBuf<int> = RingBuf::with_capacity(10);
273 /// assert!(buf.capacity() >= 10);
277 pub fn capacity(&self) -> uint { self.cap - 1 }
279 /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the
280 /// given `RingBuf`. Does nothing if the capacity is already sufficient.
282 /// Note that the allocator may give the collection more space than it requests. Therefore
283 /// capacity can not be relied upon to be precisely minimal. Prefer `reserve` if future
284 /// insertions are expected.
288 /// Panics if the new capacity overflows `uint`.
293 /// use std::collections::RingBuf;
295 /// let mut buf: RingBuf<int> = vec![1].into_iter().collect();
296 /// buf.reserve_exact(10);
297 /// assert!(buf.capacity() >= 11);
300 pub fn reserve_exact(&mut self, additional: uint) {
301 self.reserve(additional);
304 /// Reserves capacity for at least `additional` more elements to be inserted in the given
305 /// `Ringbuf`. The collection may reserve more space to avoid frequent reallocations.
309 /// Panics if the new capacity overflows `uint`.
314 /// use std::collections::RingBuf;
316 /// let mut buf: RingBuf<int> = vec![1].into_iter().collect();
318 /// assert!(buf.capacity() >= 11);
321 pub fn reserve(&mut self, additional: uint) {
322 let new_len = self.len() + additional;
323 assert!(new_len + 1 > self.len(), "capacity overflow");
324 if new_len > self.capacity() {
325 let count = (new_len + 1).next_power_of_two();
326 assert!(count >= new_len + 1);
328 if mem::size_of::<T>() != 0 {
329 let old = self.cap * mem::size_of::<T>();
330 let new = count.checked_mul(mem::size_of::<T>())
331 .expect("capacity overflow");
333 self.ptr = heap::reallocate(self.ptr as *mut u8,
336 mem::min_align_of::<T>()) as *mut T;
337 if self.ptr.is_null() { ::alloc::oom() }
341 // Move the shortest contiguous section of the ring buffer
343 // [o o o o o o o . ]
345 // A [o o o o o o o . . . . . . . . . ]
347 // [o o . o o o o o ]
349 // B [. . . o o o o o o o . . . . . . ]
351 // [o o o o o . o o ]
353 // C [o o o o o . . . . . . . . . o o ]
355 let oldcap = self.cap;
358 if self.tail <= self.head { // A
360 } else if self.head < oldcap - self.tail { // B
362 self.copy_nonoverlapping(oldcap, 0, self.head);
365 debug_assert!(self.head > self.tail);
367 let new_tail = count - (oldcap - self.tail);
369 self.copy_nonoverlapping(new_tail, self.tail, oldcap - self.tail);
371 self.tail = new_tail;
372 debug_assert!(self.head < self.tail);
374 debug_assert!(self.head < self.cap);
375 debug_assert!(self.tail < self.cap);
376 debug_assert!(self.cap.count_ones() == 1);
380 /// Shrinks the capacity of the ringbuf as much as possible.
382 /// It will drop down as close as possible to the length but the allocator may still inform the
383 /// ringbuf that there is space for a few more elements.
388 /// use std::collections::RingBuf;
390 /// let mut buf = RingBuf::with_capacity(15);
391 /// buf.extend(range(0u, 4));
392 /// assert_eq!(buf.capacity(), 15);
393 /// buf.shrink_to_fit();
394 /// assert!(buf.capacity() >= 4);
396 pub fn shrink_to_fit(&mut self) {
397 // +1 since the ringbuffer always leaves one space empty
398 // len + 1 can't overflow for an existing, well-formed ringbuf.
399 let target_cap = cmp::max(self.len() + 1, MINIMUM_CAPACITY + 1).next_power_of_two();
400 if target_cap < self.cap {
401 // There are three cases of interest:
402 // All elements are out of desired bounds
403 // Elements are contiguous, and head is out of desired bounds
404 // Elements are discontiguous, and tail is out of desired bounds
406 // At all other times, element positions are unaffected.
408 // Indicates that elements at the head should be moved.
409 let head_outside = self.head == 0 || self.head >= target_cap;
410 // Move elements from out of desired bounds (positions after target_cap)
411 if self.tail >= target_cap && head_outside {
413 // [. . . . . . . . o o o o o o o . ]
415 // [o o o o o o o . ]
417 self.copy_nonoverlapping(0, self.tail, self.len());
419 self.head = self.len();
421 } else if self.tail != 0 && self.tail < target_cap && head_outside {
423 // [. . . o o o o o o o . . . . . . ]
425 // [o o . o o o o o ]
426 let len = self.wrap_index(self.head - target_cap);
428 self.copy_nonoverlapping(0, target_cap, len);
431 debug_assert!(self.head < self.tail);
432 } else if self.tail >= target_cap {
434 // [o o o o o . . . . . . . . . o o ]
436 // [o o o o o . o o ]
437 debug_assert!(self.wrap_index(self.head - 1) < target_cap);
438 let len = self.cap - self.tail;
439 let new_tail = target_cap - len;
441 self.copy_nonoverlapping(new_tail, self.tail, len);
443 self.tail = new_tail;
444 debug_assert!(self.head < self.tail);
447 if mem::size_of::<T>() != 0 {
448 let old = self.cap * mem::size_of::<T>();
449 let new_size = target_cap * mem::size_of::<T>();
451 self.ptr = heap::reallocate(self.ptr as *mut u8,
454 mem::min_align_of::<T>()) as *mut T;
455 if self.ptr.is_null() { ::alloc::oom() }
458 self.cap = target_cap;
459 debug_assert!(self.head < self.cap);
460 debug_assert!(self.tail < self.cap);
461 debug_assert!(self.cap.count_ones() == 1);
465 /// Shorten a ringbuf, dropping excess elements from the back.
467 /// If `len` is greater than the ringbuf's current length, this has no
473 /// use std::collections::RingBuf;
475 /// let mut buf = RingBuf::new();
476 /// buf.push_back(5i);
477 /// buf.push_back(10i);
478 /// buf.push_back(15);
480 /// assert_eq!(buf.len(), 1);
481 /// assert_eq!(Some(&5), buf.get(0));
483 #[unstable = "matches collection reform specification; waiting on panic semantics"]
484 pub fn truncate(&mut self, len: uint) {
485 for _ in range(len, self.len()) {
490 /// Returns a front-to-back iterator.
495 /// use std::collections::RingBuf;
497 /// let mut buf = RingBuf::new();
498 /// buf.push_back(5i);
499 /// buf.push_back(3);
500 /// buf.push_back(4);
501 /// let b: &[_] = &[&5, &3, &4];
502 /// assert_eq!(buf.iter().collect::<Vec<&int>>().as_slice(), b);
505 pub fn iter(&self) -> Iter<T> {
509 ring: unsafe { self.buffer_as_slice() }
513 /// Returns a front-to-back iterator that returns mutable references.
518 /// use std::collections::RingBuf;
520 /// let mut buf = RingBuf::new();
521 /// buf.push_back(5i);
522 /// buf.push_back(3);
523 /// buf.push_back(4);
524 /// for num in buf.iter_mut() {
527 /// let b: &[_] = &[&mut 3, &mut 1, &mut 2];
528 /// assert_eq!(&buf.iter_mut().collect::<Vec<&mut int>>()[], b);
531 pub fn iter_mut<'a>(&'a mut self) -> IterMut<'a, T> {
537 marker: marker::ContravariantLifetime::<'a>,
541 /// Consumes the list into an iterator yielding elements by value.
543 pub fn into_iter(self) -> IntoIter<T> {
549 /// Returns a pair of slices which contain, in order, the contents of the
552 #[unstable = "matches collection reform specification, waiting for dust to settle"]
553 pub fn as_slices<'a>(&'a self) -> (&'a [T], &'a [T]) {
555 let contiguous = self.is_contiguous();
556 let buf = self.buffer_as_slice();
558 let (empty, buf) = buf.split_at(0);
559 (&buf[self.tail..self.head], empty)
561 let (mid, right) = buf.split_at(self.tail);
562 let (left, _) = mid.split_at(self.head);
568 /// Returns a pair of slices which contain, in order, the contents of the
571 #[unstable = "matches collection reform specification, waiting for dust to settle"]
572 pub fn as_mut_slices<'a>(&'a mut self) -> (&'a mut [T], &'a mut [T]) {
574 let contiguous = self.is_contiguous();
575 let head = self.head;
576 let tail = self.tail;
577 let buf = self.buffer_as_mut_slice();
580 let (empty, buf) = buf.split_at_mut(0);
581 (buf.slice_mut(tail, head), empty)
583 let (mid, right) = buf.split_at_mut(tail);
584 let (left, _) = mid.split_at_mut(head);
591 /// Returns the number of elements in the `RingBuf`.
596 /// use std::collections::RingBuf;
598 /// let mut v = RingBuf::new();
599 /// assert_eq!(v.len(), 0);
601 /// assert_eq!(v.len(), 1);
604 pub fn len(&self) -> uint { count(self.tail, self.head, self.cap) }
606 /// Returns true if the buffer contains no elements
611 /// use std::collections::RingBuf;
613 /// let mut v = RingBuf::new();
614 /// assert!(v.is_empty());
615 /// v.push_front(1i);
616 /// assert!(!v.is_empty());
619 pub fn is_empty(&self) -> bool { self.len() == 0 }
621 /// Creates a draining iterator that clears the `RingBuf` and iterates over
622 /// the removed items from start to end.
627 /// use std::collections::RingBuf;
629 /// let mut v = RingBuf::new();
631 /// assert_eq!(v.drain().next(), Some(1));
632 /// assert!(v.is_empty());
635 #[unstable = "matches collection reform specification, waiting for dust to settle"]
636 pub fn drain(&mut self) -> Drain<T> {
642 /// Clears the buffer, removing all values.
647 /// use std::collections::RingBuf;
649 /// let mut v = RingBuf::new();
652 /// assert!(v.is_empty());
656 pub fn clear(&mut self) {
660 /// Provides a reference to the front element, or `None` if the sequence is
666 /// use std::collections::RingBuf;
668 /// let mut d = RingBuf::new();
669 /// assert_eq!(d.front(), None);
673 /// assert_eq!(d.front(), Some(&1i));
676 pub fn front(&self) -> Option<&T> {
677 if !self.is_empty() { Some(&self[0]) } else { None }
680 /// Provides a mutable reference to the front element, or `None` if the
681 /// sequence is empty.
686 /// use std::collections::RingBuf;
688 /// let mut d = RingBuf::new();
689 /// assert_eq!(d.front_mut(), None);
693 /// match d.front_mut() {
694 /// Some(x) => *x = 9i,
697 /// assert_eq!(d.front(), Some(&9i));
700 pub fn front_mut(&mut self) -> Option<&mut T> {
701 if !self.is_empty() { Some(&mut self[0]) } else { None }
704 /// Provides a reference to the back element, or `None` if the sequence is
710 /// use std::collections::RingBuf;
712 /// let mut d = RingBuf::new();
713 /// assert_eq!(d.back(), None);
717 /// assert_eq!(d.back(), Some(&2i));
720 pub fn back(&self) -> Option<&T> {
721 if !self.is_empty() { Some(&self[self.len() - 1]) } else { None }
724 /// Provides a mutable reference to the back element, or `None` if the
725 /// sequence is empty.
730 /// use std::collections::RingBuf;
732 /// let mut d = RingBuf::new();
733 /// assert_eq!(d.back(), None);
737 /// match d.back_mut() {
738 /// Some(x) => *x = 9i,
741 /// assert_eq!(d.back(), Some(&9i));
744 pub fn back_mut(&mut self) -> Option<&mut T> {
745 let len = self.len();
746 if !self.is_empty() { Some(&mut self[len - 1]) } else { None }
749 /// Removes the first element and returns it, or `None` if the sequence is
755 /// use std::collections::RingBuf;
757 /// let mut d = RingBuf::new();
761 /// assert_eq!(d.pop_front(), Some(1i));
762 /// assert_eq!(d.pop_front(), Some(2i));
763 /// assert_eq!(d.pop_front(), None);
766 pub fn pop_front(&mut self) -> Option<T> {
770 let tail = self.tail;
771 self.tail = self.wrap_index(self.tail + 1);
772 unsafe { Some(self.buffer_read(tail)) }
776 /// Inserts an element first in the sequence.
781 /// use std::collections::RingBuf;
783 /// let mut d = RingBuf::new();
784 /// d.push_front(1i);
785 /// d.push_front(2i);
786 /// assert_eq!(d.front(), Some(&2i));
789 pub fn push_front(&mut self, t: T) {
792 debug_assert!(!self.is_full());
795 self.tail = self.wrap_index(self.tail - 1);
796 let tail = self.tail;
797 unsafe { self.buffer_write(tail, t); }
800 /// Appends an element to the back of a buffer
805 /// use std::collections::RingBuf;
807 /// let mut buf = RingBuf::new();
808 /// buf.push_back(1i);
809 /// buf.push_back(3);
810 /// assert_eq!(3, *buf.back().unwrap());
813 pub fn push_back(&mut self, t: T) {
816 debug_assert!(!self.is_full());
819 let head = self.head;
820 self.head = self.wrap_index(self.head + 1);
821 unsafe { self.buffer_write(head, t) }
824 /// Removes the last element from a buffer and returns it, or `None` if
830 /// use std::collections::RingBuf;
832 /// let mut buf = RingBuf::new();
833 /// assert_eq!(buf.pop_back(), None);
834 /// buf.push_back(1i);
835 /// buf.push_back(3);
836 /// assert_eq!(buf.pop_back(), Some(3));
839 pub fn pop_back(&mut self) -> Option<T> {
843 self.head = self.wrap_index(self.head - 1);
844 let head = self.head;
845 unsafe { Some(self.buffer_read(head)) }
850 fn is_contiguous(&self) -> bool {
851 self.tail <= self.head
854 /// Removes an element from anywhere in the ringbuf and returns it, replacing it with the last
857 /// This does not preserve ordering, but is O(1).
859 /// Returns `None` if `index` is out of bounds.
864 /// use std::collections::RingBuf;
866 /// let mut buf = RingBuf::new();
867 /// assert_eq!(buf.swap_back_remove(0), None);
868 /// buf.push_back(5i);
869 /// buf.push_back(99);
870 /// buf.push_back(15);
871 /// buf.push_back(20);
872 /// buf.push_back(10);
873 /// assert_eq!(buf.swap_back_remove(1), Some(99));
875 #[unstable = "the naming of this function may be altered"]
876 pub fn swap_back_remove(&mut self, index: uint) -> Option<T> {
877 let length = self.len();
878 if length > 0 && index < length - 1 {
879 self.swap(index, length - 1);
880 } else if index >= length {
886 /// Removes an element from anywhere in the ringbuf and returns it, replacing it with the first
889 /// This does not preserve ordering, but is O(1).
891 /// Returns `None` if `index` is out of bounds.
896 /// use std::collections::RingBuf;
898 /// let mut buf = RingBuf::new();
899 /// assert_eq!(buf.swap_front_remove(0), None);
900 /// buf.push_back(15i);
901 /// buf.push_back(5);
902 /// buf.push_back(10);
903 /// buf.push_back(99);
904 /// buf.push_back(20i);
905 /// assert_eq!(buf.swap_front_remove(3), Some(99));
907 #[unstable = "the naming of this function may be altered"]
908 pub fn swap_front_remove(&mut self, index: uint) -> Option<T> {
909 let length = self.len();
910 if length > 0 && index < length && index != 0 {
912 } else if index >= length {
918 /// Inserts an element at position `i` within the ringbuf. Whichever
919 /// end is closer to the insertion point will be moved to make room,
920 /// and all the affected elements will be moved to new positions.
924 /// Panics if `i` is greater than ringbuf's length
928 /// use std::collections::RingBuf;
930 /// let mut buf = RingBuf::new();
931 /// buf.push_back(10i);
932 /// buf.push_back(12);
933 /// buf.insert(1,11);
934 /// assert_eq!(Some(&11), buf.get(1));
936 pub fn insert(&mut self, i: uint, t: T) {
937 assert!(i <= self.len(), "index out of bounds");
940 debug_assert!(!self.is_full());
943 // Move the least number of elements in the ring buffer and insert
946 // At most len/2 - 1 elements will be moved. O(min(n, n-i))
948 // There are three main cases:
949 // Elements are contiguous
950 // - special case when tail is 0
951 // Elements are discontiguous and the insert is in the tail section
952 // Elements are discontiguous and the insert is in the head section
954 // For each of those there are two more cases:
955 // Insert is closer to tail
956 // Insert is closer to head
958 // Key: H - self.head
961 // I - Insertion element
962 // A - The element that should be after the insertion point
963 // M - Indicates element was moved
965 let idx = self.wrap_index(self.tail + i);
967 let distance_to_tail = i;
968 let distance_to_head = self.len() - i;
970 let contiguous = self.is_contiguous();
972 match (contiguous, distance_to_tail <= distance_to_head, idx >= self.tail) {
973 (true, true, _) if i == 0 => {
978 // [A o o o o o o . . . . . . . . .]
981 // [A o o o o o o o . . . . . I]
984 self.tail = self.wrap_index(self.tail - 1);
986 (true, true, _) => unsafe {
987 // contiguous, insert closer to tail:
990 // [. . . o o A o o o o . . . . . .]
993 // [. . o o I A o o o o . . . . . .]
996 // contiguous, insert closer to tail and tail is 0:
1000 // [o o A o o o o . . . . . . . . .]
1003 // [o I A o o o o o . . . . . . . o]
1006 let new_tail = self.wrap_index(self.tail - 1);
1008 self.copy(new_tail, self.tail, 1);
1009 // Already moved the tail, so we only copy `i - 1` elements.
1010 self.copy(self.tail, self.tail + 1, i - 1);
1012 self.tail = new_tail;
1014 (true, false, _) => unsafe {
1015 // contiguous, insert closer to head:
1018 // [. . . o o o o A o o . . . . . .]
1021 // [. . . o o o o I A o o . . . . .]
1024 self.copy(idx + 1, idx, self.head - idx);
1025 self.head = self.wrap_index(self.head + 1);
1027 (false, true, true) => unsafe {
1028 // discontiguous, insert closer to tail, tail section:
1031 // [o o o o o o . . . . . o o A o o]
1034 // [o o o o o o . . . . o o I A o o]
1037 self.copy(self.tail - 1, self.tail, i);
1040 (false, false, true) => unsafe {
1041 // discontiguous, insert closer to head, tail section:
1044 // [o o . . . . . . . o o o o o A o]
1047 // [o o o . . . . . . o o o o o I A]
1050 // copy elements up to new head
1051 self.copy(1, 0, self.head);
1053 // copy last element into empty spot at bottom of buffer
1054 self.copy(0, self.cap - 1, 1);
1056 // move elements from idx to end forward not including ^ element
1057 self.copy(idx + 1, idx, self.cap - 1 - idx);
1061 (false, true, false) if idx == 0 => unsafe {
1062 // discontiguous, insert is closer to tail, head section,
1063 // and is at index zero in the internal buffer:
1066 // [A o o o o o o o o o . . . o o o]
1069 // [A o o o o o o o o o . . o o o I]
1072 // copy elements up to new tail
1073 self.copy(self.tail - 1, self.tail, self.cap - self.tail);
1075 // copy last element into empty spot at bottom of buffer
1076 self.copy(self.cap - 1, 0, 1);
1080 (false, true, false) => unsafe {
1081 // discontiguous, insert closer to tail, head section:
1084 // [o o o A o o o o o o . . . o o o]
1087 // [o o I A o o o o o o . . o o o o]
1090 // copy elements up to new tail
1091 self.copy(self.tail - 1, self.tail, self.cap - self.tail);
1093 // copy last element into empty spot at bottom of buffer
1094 self.copy(self.cap - 1, 0, 1);
1096 // move elements from idx-1 to end forward not including ^ element
1097 self.copy(0, 1, idx - 1);
1101 (false, false, false) => unsafe {
1102 // discontiguous, insert closer to head, head section:
1105 // [o o o o A o o . . . . . . o o o]
1108 // [o o o o I A o o . . . . . o o o]
1111 self.copy(idx + 1, idx, self.head - idx);
1116 // tail might've been changed so we need to recalculate
1117 let new_idx = self.wrap_index(self.tail + i);
1119 self.buffer_write(new_idx, t);
1123 /// Removes and returns the element at position `i` from the ringbuf.
1124 /// Whichever end is closer to the removal point will be moved to make
1125 /// room, and all the affected elements will be moved to new positions.
1126 /// Returns `None` if `i` is out of bounds.
1130 /// use std::collections::RingBuf;
1132 /// let mut buf = RingBuf::new();
1133 /// buf.push_back(5i);
1134 /// buf.push_back(10i);
1135 /// buf.push_back(12i);
1136 /// buf.push_back(15);
1138 /// assert_eq!(Some(&15), buf.get(2));
1141 pub fn remove(&mut self, i: uint) -> Option<T> {
1142 if self.is_empty() || self.len() <= i {
1146 // There are three main cases:
1147 // Elements are contiguous
1148 // Elements are discontiguous and the removal is in the tail section
1149 // Elements are discontiguous and the removal is in the head section
1150 // - special case when elements are technically contiguous,
1151 // but self.head = 0
1153 // For each of those there are two more cases:
1154 // Insert is closer to tail
1155 // Insert is closer to head
1157 // Key: H - self.head
1159 // o - Valid element
1160 // x - Element marked for removal
1161 // R - Indicates element that is being removed
1162 // M - Indicates element was moved
1164 let idx = self.wrap_index(self.tail + i);
1167 Some(self.buffer_read(idx))
1170 let distance_to_tail = i;
1171 let distance_to_head = self.len() - i;
1173 let contiguous = self.is_contiguous();
1175 match (contiguous, distance_to_tail <= distance_to_head, idx >= self.tail) {
1176 (true, true, _) => unsafe {
1177 // contiguous, remove closer to tail:
1180 // [. . . o o x o o o o . . . . . .]
1183 // [. . . . o o o o o o . . . . . .]
1186 self.copy(self.tail + 1, self.tail, i);
1189 (true, false, _) => unsafe {
1190 // contiguous, remove closer to head:
1193 // [. . . o o o o x o o . . . . . .]
1196 // [. . . o o o o o o . . . . . . .]
1199 self.copy(idx, idx + 1, self.head - idx - 1);
1202 (false, true, true) => unsafe {
1203 // discontiguous, remove closer to tail, tail section:
1206 // [o o o o o o . . . . . o o x o o]
1209 // [o o o o o o . . . . . . o o o o]
1212 self.copy(self.tail + 1, self.tail, i);
1213 self.tail = self.wrap_index(self.tail + 1);
1215 (false, false, false) => unsafe {
1216 // discontiguous, remove closer to head, head section:
1219 // [o o o o x o o . . . . . . o o o]
1222 // [o o o o o o . . . . . . . o o o]
1225 self.copy(idx, idx + 1, self.head - idx - 1);
1228 (false, false, true) => unsafe {
1229 // discontiguous, remove closer to head, tail section:
1232 // [o o o . . . . . . o o o o o x o]
1235 // [o o . . . . . . . o o o o o o o]
1238 // or quasi-discontiguous, remove next to head, tail section:
1241 // [. . . . . . . . . o o o o o x o]
1244 // [. . . . . . . . . o o o o o o .]
1247 // draw in elements in the tail section
1248 self.copy(idx, idx + 1, self.cap - idx - 1);
1250 // Prevents underflow.
1252 // copy first element into empty spot
1253 self.copy(self.cap - 1, 0, 1);
1255 // move elements in the head section backwards
1256 self.copy(0, 1, self.head - 1);
1259 self.head = self.wrap_index(self.head - 1);
1261 (false, true, false) => unsafe {
1262 // discontiguous, remove closer to tail, head section:
1265 // [o o x o o o o o o o . . . o o o]
1268 // [o o o o o o o o o o . . . . o o]
1271 // draw in elements up to idx
1272 self.copy(1, 0, idx);
1274 // copy last element into empty spot
1275 self.copy(0, self.cap - 1, 1);
1277 // move elements from tail to end forward, excluding the last one
1278 self.copy(self.tail + 1, self.tail, self.cap - self.tail - 1);
1280 self.tail = self.wrap_index(self.tail + 1);
1288 impl<T: Clone> RingBuf<T> {
1289 /// Modifies the ringbuf in-place so that `len()` is equal to new_len,
1290 /// either by removing excess elements or by appending copies of a value to the back.
1295 /// use std::collections::RingBuf;
1297 /// let mut buf = RingBuf::new();
1298 /// buf.push_back(5i);
1299 /// buf.push_back(10i);
1300 /// buf.push_back(15);
1301 /// buf.resize(2, 0);
1302 /// buf.resize(6, 20);
1303 /// for (a, b) in [5, 10, 20, 20, 20, 20].iter().zip(buf.iter()) {
1304 /// assert_eq!(a, b);
1307 #[unstable = "matches collection reform specification; waiting on panic semantics"]
1308 pub fn resize(&mut self, new_len: uint, value: T) {
1309 let len = self.len();
1312 self.extend(repeat(value).take(new_len - len))
1314 self.truncate(new_len);
1319 /// Returns the index in the underlying buffer for a given logical element index.
1321 fn wrap_index(index: uint, size: uint) -> uint {
1322 // size is always a power of 2
1326 /// Calculate the number of elements left to be read in the buffer
1328 fn count(tail: uint, head: uint, size: uint) -> uint {
1329 // size is always a power of 2
1330 (head - tail) & (size - 1)
1333 /// `RingBuf` iterator.
1335 pub struct Iter<'a, T:'a> {
1341 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1342 impl<'a, T> Clone for Iter<'a, T> {
1343 fn clone(&self) -> Iter<'a, T> {
1353 impl<'a, T> Iterator for Iter<'a, T> {
1357 fn next(&mut self) -> Option<&'a T> {
1358 if self.tail == self.head {
1361 let tail = self.tail;
1362 self.tail = wrap_index(self.tail + 1, self.ring.len());
1363 unsafe { Some(self.ring.get_unchecked(tail)) }
1367 fn size_hint(&self) -> (uint, Option<uint>) {
1368 let len = count(self.tail, self.head, self.ring.len());
1374 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
1376 fn next_back(&mut self) -> Option<&'a T> {
1377 if self.tail == self.head {
1380 self.head = wrap_index(self.head - 1, self.ring.len());
1381 unsafe { Some(self.ring.get_unchecked(self.head)) }
1386 impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
1389 impl<'a, T> RandomAccessIterator for Iter<'a, T> {
1391 fn indexable(&self) -> uint {
1392 let (len, _) = self.size_hint();
1397 fn idx(&mut self, j: uint) -> Option<&'a T> {
1398 if j >= self.indexable() {
1401 let idx = wrap_index(self.tail + j, self.ring.len());
1402 unsafe { Some(self.ring.get_unchecked(idx)) }
1407 // FIXME This was implemented differently from Iter because of a problem
1408 // with returning the mutable reference. I couldn't find a way to
1409 // make the lifetime checker happy so, but there should be a way.
1410 /// `RingBuf` mutable iterator.
1412 pub struct IterMut<'a, T:'a> {
1417 marker: marker::ContravariantLifetime<'a>,
1421 impl<'a, T> Iterator for IterMut<'a, T> {
1422 type Item = &'a mut T;
1425 fn next(&mut self) -> Option<&'a mut T> {
1426 if self.tail == self.head {
1429 let tail = self.tail;
1430 self.tail = wrap_index(self.tail + 1, self.cap);
1433 Some(&mut *self.ptr.offset(tail as int))
1438 fn size_hint(&self) -> (uint, Option<uint>) {
1439 let len = count(self.tail, self.head, self.cap);
1445 impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
1447 fn next_back(&mut self) -> Option<&'a mut T> {
1448 if self.tail == self.head {
1451 self.head = wrap_index(self.head - 1, self.cap);
1454 Some(&mut *self.ptr.offset(self.head as int))
1460 impl<'a, T> ExactSizeIterator for IterMut<'a, T> {}
1462 /// A by-value RingBuf iterator
1464 pub struct IntoIter<T> {
1469 impl<T> Iterator for IntoIter<T> {
1473 fn next(&mut self) -> Option<T> {
1474 self.inner.pop_front()
1478 fn size_hint(&self) -> (uint, Option<uint>) {
1479 let len = self.inner.len();
1485 impl<T> DoubleEndedIterator for IntoIter<T> {
1487 fn next_back(&mut self) -> Option<T> {
1488 self.inner.pop_back()
1493 impl<T> ExactSizeIterator for IntoIter<T> {}
1495 /// A draining RingBuf iterator
1496 #[unstable = "matches collection reform specification, waiting for dust to settle"]
1497 pub struct Drain<'a, T: 'a> {
1498 inner: &'a mut RingBuf<T>,
1501 #[unsafe_destructor]
1503 impl<'a, T: 'a> Drop for Drain<'a, T> {
1504 fn drop(&mut self) {
1506 self.inner.head = 0;
1507 self.inner.tail = 0;
1512 impl<'a, T: 'a> Iterator for Drain<'a, T> {
1516 fn next(&mut self) -> Option<T> {
1517 self.inner.pop_front()
1521 fn size_hint(&self) -> (uint, Option<uint>) {
1522 let len = self.inner.len();
1528 impl<'a, T: 'a> DoubleEndedIterator for Drain<'a, T> {
1530 fn next_back(&mut self) -> Option<T> {
1531 self.inner.pop_back()
1536 impl<'a, T: 'a> ExactSizeIterator for Drain<'a, T> {}
1539 impl<A: PartialEq> PartialEq for RingBuf<A> {
1540 fn eq(&self, other: &RingBuf<A>) -> bool {
1541 self.len() == other.len() &&
1542 self.iter().zip(other.iter()).all(|(a, b)| a.eq(b))
1547 impl<A: Eq> Eq for RingBuf<A> {}
1550 impl<A: PartialOrd> PartialOrd for RingBuf<A> {
1551 fn partial_cmp(&self, other: &RingBuf<A>) -> Option<Ordering> {
1552 iter::order::partial_cmp(self.iter(), other.iter())
1557 impl<A: Ord> Ord for RingBuf<A> {
1559 fn cmp(&self, other: &RingBuf<A>) -> Ordering {
1560 iter::order::cmp(self.iter(), other.iter())
1565 impl<S: Writer + Hasher, A: Hash<S>> Hash<S> for RingBuf<A> {
1566 fn hash(&self, state: &mut S) {
1567 self.len().hash(state);
1568 for elt in self.iter() {
1575 impl<A> Index<uint> for RingBuf<A> {
1579 fn index<'a>(&'a self, i: &uint) -> &'a A {
1580 self.get(*i).expect("Out of bounds access")
1585 impl<A> IndexMut<uint> for RingBuf<A> {
1589 fn index_mut<'a>(&'a mut self, i: &uint) -> &'a mut A {
1590 self.get_mut(*i).expect("Out of bounds access")
1595 impl<A> FromIterator<A> for RingBuf<A> {
1596 fn from_iter<T: Iterator<Item=A>>(iterator: T) -> RingBuf<A> {
1597 let (lower, _) = iterator.size_hint();
1598 let mut deq = RingBuf::with_capacity(lower);
1599 deq.extend(iterator);
1605 impl<A> Extend<A> for RingBuf<A> {
1606 fn extend<T: Iterator<Item=A>>(&mut self, mut iterator: T) {
1607 for elt in iterator {
1608 self.push_back(elt);
1614 impl<T: fmt::Show> fmt::Show for RingBuf<T> {
1615 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1616 try!(write!(f, "RingBuf ["));
1618 for (i, e) in self.iter().enumerate() {
1619 if i != 0 { try!(write!(f, ", ")); }
1620 try!(write!(f, "{:?}", *e));
1630 use self::Taggypar::*;
1634 use std::hash::{self, SipHasher};
1641 #[allow(deprecated)]
1643 let mut d = RingBuf::new();
1644 assert_eq!(d.len(), 0u);
1648 assert_eq!(d.len(), 3u);
1650 assert_eq!(d.len(), 4u);
1651 assert_eq!(*d.front().unwrap(), 42);
1652 assert_eq!(*d.back().unwrap(), 137);
1653 let mut i = d.pop_front();
1654 assert_eq!(i, Some(42));
1656 assert_eq!(i, Some(137));
1658 assert_eq!(i, Some(137));
1660 assert_eq!(i, Some(17));
1661 assert_eq!(d.len(), 0u);
1663 assert_eq!(d.len(), 1u);
1665 assert_eq!(d.len(), 2u);
1667 assert_eq!(d.len(), 3u);
1669 assert_eq!(d.len(), 4u);
1674 assert_eq!(d[0], 1);
1675 assert_eq!(d[1], 2);
1676 assert_eq!(d[2], 3);
1677 assert_eq!(d[3], 4);
1681 fn test_parameterized<T:Clone + PartialEq + Show>(a: T, b: T, c: T, d: T) {
1682 let mut deq = RingBuf::new();
1683 assert_eq!(deq.len(), 0);
1684 deq.push_front(a.clone());
1685 deq.push_front(b.clone());
1686 deq.push_back(c.clone());
1687 assert_eq!(deq.len(), 3);
1688 deq.push_back(d.clone());
1689 assert_eq!(deq.len(), 4);
1690 assert_eq!((*deq.front().unwrap()).clone(), b.clone());
1691 assert_eq!((*deq.back().unwrap()).clone(), d.clone());
1692 assert_eq!(deq.pop_front().unwrap(), b.clone());
1693 assert_eq!(deq.pop_back().unwrap(), d.clone());
1694 assert_eq!(deq.pop_back().unwrap(), c.clone());
1695 assert_eq!(deq.pop_back().unwrap(), a.clone());
1696 assert_eq!(deq.len(), 0);
1697 deq.push_back(c.clone());
1698 assert_eq!(deq.len(), 1);
1699 deq.push_front(b.clone());
1700 assert_eq!(deq.len(), 2);
1701 deq.push_back(d.clone());
1702 assert_eq!(deq.len(), 3);
1703 deq.push_front(a.clone());
1704 assert_eq!(deq.len(), 4);
1705 assert_eq!(deq[0].clone(), a.clone());
1706 assert_eq!(deq[1].clone(), b.clone());
1707 assert_eq!(deq[2].clone(), c.clone());
1708 assert_eq!(deq[3].clone(), d.clone());
1712 fn test_push_front_grow() {
1713 let mut deq = RingBuf::new();
1714 for i in range(0u, 66) {
1717 assert_eq!(deq.len(), 66);
1719 for i in range(0u, 66) {
1720 assert_eq!(deq[i], 65 - i);
1723 let mut deq = RingBuf::new();
1724 for i in range(0u, 66) {
1728 for i in range(0u, 66) {
1729 assert_eq!(deq[i], i);
1735 let mut deq = RingBuf::new();
1736 for i in range(1u, 4) {
1739 assert_eq!(deq[1], 2);
1744 fn test_index_out_of_bounds() {
1745 let mut deq = RingBuf::new();
1746 for i in range(1u, 4) {
1753 fn bench_new(b: &mut test::Bencher) {
1755 let ring: RingBuf<u64> = RingBuf::new();
1756 test::black_box(ring);
1761 fn bench_push_back_100(b: &mut test::Bencher) {
1762 let mut deq = RingBuf::with_capacity(101);
1764 for i in range(0i, 100) {
1773 fn bench_push_front_100(b: &mut test::Bencher) {
1774 let mut deq = RingBuf::with_capacity(101);
1776 for i in range(0i, 100) {
1785 fn bench_pop_back_100(b: &mut test::Bencher) {
1786 let mut deq: RingBuf<int> = RingBuf::with_capacity(101);
1791 while !deq.is_empty() {
1792 test::black_box(deq.pop_back());
1798 fn bench_pop_front_100(b: &mut test::Bencher) {
1799 let mut deq: RingBuf<int> = RingBuf::with_capacity(101);
1804 while !deq.is_empty() {
1805 test::black_box(deq.pop_front());
1811 fn bench_grow_1025(b: &mut test::Bencher) {
1813 let mut deq = RingBuf::new();
1814 for i in range(0i, 1025) {
1817 test::black_box(deq);
1822 fn bench_iter_1000(b: &mut test::Bencher) {
1823 let ring: RingBuf<int> = range(0i, 1000).collect();
1827 for &i in ring.iter() {
1830 test::black_box(sum);
1835 fn bench_mut_iter_1000(b: &mut test::Bencher) {
1836 let mut ring: RingBuf<int> = range(0i, 1000).collect();
1840 for i in ring.iter_mut() {
1843 test::black_box(sum);
1847 #[derive(Clone, PartialEq, Show)]
1851 Three(int, int, int),
1854 #[derive(Clone, PartialEq, Show)]
1858 Threepar(int, int, int),
1861 #[derive(Clone, PartialEq, Show)]
1869 fn test_param_int() {
1870 test_parameterized::<int>(5, 72, 64, 175);
1874 fn test_param_taggy() {
1875 test_parameterized::<Taggy>(One(1), Two(1, 2), Three(1, 2, 3), Two(17, 42));
1879 fn test_param_taggypar() {
1880 test_parameterized::<Taggypar<int>>(Onepar::<int>(1),
1881 Twopar::<int>(1, 2),
1882 Threepar::<int>(1, 2, 3),
1883 Twopar::<int>(17, 42));
1887 fn test_param_reccy() {
1888 let reccy1 = RecCy { x: 1, y: 2, t: One(1) };
1889 let reccy2 = RecCy { x: 345, y: 2, t: Two(1, 2) };
1890 let reccy3 = RecCy { x: 1, y: 777, t: Three(1, 2, 3) };
1891 let reccy4 = RecCy { x: 19, y: 252, t: Two(17, 42) };
1892 test_parameterized::<RecCy>(reccy1, reccy2, reccy3, reccy4);
1896 fn test_with_capacity() {
1897 let mut d = RingBuf::with_capacity(0);
1899 assert_eq!(d.len(), 1);
1900 let mut d = RingBuf::with_capacity(50);
1902 assert_eq!(d.len(), 1);
1906 fn test_with_capacity_non_power_two() {
1907 let mut d3 = RingBuf::with_capacity(3);
1912 assert_eq!(d3.pop_front(), Some(1));
1914 assert_eq!(d3.front(), None);
1921 assert_eq!(d3.pop_front(), Some(3));
1923 // Pushing the lo past half way point to trigger
1924 // the 'B' scenario for growth
1931 // There used to be a bug here about how the
1932 // RingBuf made growth assumptions about the
1933 // underlying Vec which didn't hold and lead
1935 // (Vec grows to next power of two)
1936 //good- [9, 12, 15, X, X, X, X, |6]
1937 //bug- [15, 12, X, X, X, |6, X, X]
1938 assert_eq!(d3.pop_front(), Some(6));
1940 // Which leads us to the following state which
1941 // would be a failure case.
1942 //bug- [15, 12, X, X, X, X, |X, X]
1943 assert_eq!(d3.front(), Some(&9));
1947 fn test_reserve_exact() {
1948 let mut d = RingBuf::new();
1950 d.reserve_exact(50);
1951 assert!(d.capacity() >= 51);
1952 let mut d = RingBuf::new();
1954 d.reserve_exact(50);
1955 assert!(d.capacity() >= 51);
1960 let mut d = RingBuf::new();
1963 assert!(d.capacity() >= 51);
1964 let mut d = RingBuf::new();
1967 assert!(d.capacity() >= 51);
1972 let mut d: RingBuf<int> = range(0i, 5).collect();
1975 assert_eq!(d.iter().map(|&x|x).collect::<Vec<int>>(), vec!(4, 2, 3, 1));
1980 let mut d = RingBuf::new();
1981 assert_eq!(d.iter().next(), None);
1982 assert_eq!(d.iter().size_hint(), (0, Some(0)));
1984 for i in range(0i, 5) {
1988 let b: &[_] = &[&0,&1,&2,&3,&4];
1989 assert_eq!(d.iter().collect::<Vec<&int>>(), b);
1992 for i in range(6i, 9) {
1996 let b: &[_] = &[&8,&7,&6,&0,&1,&2,&3,&4];
1997 assert_eq!(d.iter().collect::<Vec<&int>>(), b);
2000 let mut it = d.iter();
2001 let mut len = d.len();
2005 _ => { len -= 1; assert_eq!(it.size_hint(), (len, Some(len))) }
2011 fn test_rev_iter() {
2012 let mut d = RingBuf::new();
2013 assert_eq!(d.iter().rev().next(), None);
2015 for i in range(0i, 5) {
2019 let b: &[_] = &[&4,&3,&2,&1,&0];
2020 assert_eq!(d.iter().rev().collect::<Vec<&int>>(), b);
2023 for i in range(6i, 9) {
2026 let b: &[_] = &[&4,&3,&2,&1,&0,&6,&7,&8];
2027 assert_eq!(d.iter().rev().collect::<Vec<&int>>(), b);
2031 fn test_mut_rev_iter_wrap() {
2032 let mut d = RingBuf::with_capacity(3);
2033 assert!(d.iter_mut().rev().next().is_none());
2038 assert_eq!(d.pop_front(), Some(1));
2041 assert_eq!(d.iter_mut().rev().map(|x| *x).collect::<Vec<int>>(),
2046 fn test_mut_iter() {
2047 let mut d = RingBuf::new();
2048 assert!(d.iter_mut().next().is_none());
2050 for i in range(0u, 3) {
2054 for (i, elt) in d.iter_mut().enumerate() {
2055 assert_eq!(*elt, 2 - i);
2060 let mut it = d.iter_mut();
2061 assert_eq!(*it.next().unwrap(), 0);
2062 assert_eq!(*it.next().unwrap(), 1);
2063 assert_eq!(*it.next().unwrap(), 2);
2064 assert!(it.next().is_none());
2069 fn test_mut_rev_iter() {
2070 let mut d = RingBuf::new();
2071 assert!(d.iter_mut().rev().next().is_none());
2073 for i in range(0u, 3) {
2077 for (i, elt) in d.iter_mut().rev().enumerate() {
2078 assert_eq!(*elt, i);
2083 let mut it = d.iter_mut().rev();
2084 assert_eq!(*it.next().unwrap(), 0);
2085 assert_eq!(*it.next().unwrap(), 1);
2086 assert_eq!(*it.next().unwrap(), 2);
2087 assert!(it.next().is_none());
2092 fn test_into_iter() {
2096 let d: RingBuf<int> = RingBuf::new();
2097 let mut iter = d.into_iter();
2099 assert_eq!(iter.size_hint(), (0, Some(0)));
2100 assert_eq!(iter.next(), None);
2101 assert_eq!(iter.size_hint(), (0, Some(0)));
2106 let mut d = RingBuf::new();
2107 for i in range(0i, 5) {
2111 let b = vec![0,1,2,3,4];
2112 assert_eq!(d.into_iter().collect::<Vec<int>>(), b);
2117 let mut d = RingBuf::new();
2118 for i in range(0i, 5) {
2121 for i in range(6, 9) {
2125 let b = vec![8,7,6,0,1,2,3,4];
2126 assert_eq!(d.into_iter().collect::<Vec<int>>(), b);
2131 let mut d = RingBuf::new();
2132 for i in range(0i, 5) {
2135 for i in range(6, 9) {
2139 let mut it = d.into_iter();
2140 assert_eq!(it.size_hint(), (8, Some(8)));
2141 assert_eq!(it.next(), Some(8));
2142 assert_eq!(it.size_hint(), (7, Some(7)));
2143 assert_eq!(it.next_back(), Some(4));
2144 assert_eq!(it.size_hint(), (6, Some(6)));
2145 assert_eq!(it.next(), Some(7));
2146 assert_eq!(it.size_hint(), (5, Some(5)));
2155 let mut d: RingBuf<int> = RingBuf::new();
2158 let mut iter = d.drain();
2160 assert_eq!(iter.size_hint(), (0, Some(0)));
2161 assert_eq!(iter.next(), None);
2162 assert_eq!(iter.size_hint(), (0, Some(0)));
2165 assert!(d.is_empty());
2170 let mut d = RingBuf::new();
2171 for i in range(0i, 5) {
2175 assert_eq!(d.drain().collect::<Vec<int>>(), [0, 1, 2, 3, 4]);
2176 assert!(d.is_empty());
2181 let mut d = RingBuf::new();
2182 for i in range(0i, 5) {
2185 for i in range(6, 9) {
2189 assert_eq!(d.drain().collect::<Vec<int>>(), [8,7,6,0,1,2,3,4]);
2190 assert!(d.is_empty());
2195 let mut d = RingBuf::new();
2196 for i in range(0i, 5) {
2199 for i in range(6, 9) {
2204 let mut it = d.drain();
2205 assert_eq!(it.size_hint(), (8, Some(8)));
2206 assert_eq!(it.next(), Some(8));
2207 assert_eq!(it.size_hint(), (7, Some(7)));
2208 assert_eq!(it.next_back(), Some(4));
2209 assert_eq!(it.size_hint(), (6, Some(6)));
2210 assert_eq!(it.next(), Some(7));
2211 assert_eq!(it.size_hint(), (5, Some(5)));
2213 assert!(d.is_empty());
2218 fn test_from_iter() {
2220 let v = vec!(1i,2,3,4,5,6,7);
2221 let deq: RingBuf<int> = v.iter().map(|&x| x).collect();
2222 let u: Vec<int> = deq.iter().map(|&x| x).collect();
2225 let seq = iter::count(0u, 2).take(256);
2226 let deq: RingBuf<uint> = seq.collect();
2227 for (i, &x) in deq.iter().enumerate() {
2230 assert_eq!(deq.len(), 256);
2235 let mut d = RingBuf::new();
2240 assert_eq!(d.len(), 4u);
2241 let mut e = d.clone();
2242 assert_eq!(e.len(), 4u);
2243 while !d.is_empty() {
2244 assert_eq!(d.pop_back(), e.pop_back());
2246 assert_eq!(d.len(), 0u);
2247 assert_eq!(e.len(), 0u);
2252 let mut d = RingBuf::new();
2253 assert!(d == RingBuf::with_capacity(0));
2258 let mut e = RingBuf::with_capacity(0);
2268 assert!(e == RingBuf::new());
2273 let mut x = RingBuf::new();
2274 let mut y = RingBuf::new();
2286 assert!(hash::hash::<_, SipHasher>(&x) == hash::hash::<_, SipHasher>(&y));
2291 let x = RingBuf::new();
2292 let mut y = RingBuf::new();
2304 let ringbuf: RingBuf<int> = range(0i, 10).collect();
2305 assert_eq!(format!("{:?}", ringbuf), "RingBuf [0i, 1i, 2i, 3i, 4i, 5i, 6i, 7i, 8i, 9i]");
2307 let ringbuf: RingBuf<&str> = vec!["just", "one", "test", "more"].iter()
2310 assert_eq!(format!("{:?}", ringbuf), "RingBuf [\"just\", \"one\", \"test\", \"more\"]");
2315 static mut drops: uint = 0;
2317 impl Drop for Elem {
2318 fn drop(&mut self) {
2319 unsafe { drops += 1; }
2323 let mut ring = RingBuf::new();
2324 ring.push_back(Elem);
2325 ring.push_front(Elem);
2326 ring.push_back(Elem);
2327 ring.push_front(Elem);
2330 assert_eq!(unsafe {drops}, 4);
2334 fn test_drop_with_pop() {
2335 static mut drops: uint = 0;
2337 impl Drop for Elem {
2338 fn drop(&mut self) {
2339 unsafe { drops += 1; }
2343 let mut ring = RingBuf::new();
2344 ring.push_back(Elem);
2345 ring.push_front(Elem);
2346 ring.push_back(Elem);
2347 ring.push_front(Elem);
2349 drop(ring.pop_back());
2350 drop(ring.pop_front());
2351 assert_eq!(unsafe {drops}, 2);
2354 assert_eq!(unsafe {drops}, 4);
2358 fn test_drop_clear() {
2359 static mut drops: uint = 0;
2361 impl Drop for Elem {
2362 fn drop(&mut self) {
2363 unsafe { drops += 1; }
2367 let mut ring = RingBuf::new();
2368 ring.push_back(Elem);
2369 ring.push_front(Elem);
2370 ring.push_back(Elem);
2371 ring.push_front(Elem);
2373 assert_eq!(unsafe {drops}, 4);
2376 assert_eq!(unsafe {drops}, 4);
2380 fn test_reserve_grow() {
2381 // test growth path A
2382 // [T o o H] -> [T o o H . . . . ]
2383 let mut ring = RingBuf::with_capacity(4);
2384 for i in range(0i, 3) {
2388 for i in range(0i, 3) {
2389 assert_eq!(ring.pop_front(), Some(i));
2392 // test growth path B
2393 // [H T o o] -> [. T o o H . . . ]
2394 let mut ring = RingBuf::with_capacity(4);
2395 for i in range(0i, 1) {
2397 assert_eq!(ring.pop_front(), Some(i));
2399 for i in range(0i, 3) {
2403 for i in range(0i, 3) {
2404 assert_eq!(ring.pop_front(), Some(i));
2407 // test growth path C
2408 // [o o H T] -> [o o H . . . . T ]
2409 let mut ring = RingBuf::with_capacity(4);
2410 for i in range(0i, 3) {
2412 assert_eq!(ring.pop_front(), Some(i));
2414 for i in range(0i, 3) {
2418 for i in range(0i, 3) {
2419 assert_eq!(ring.pop_front(), Some(i));
2425 let mut ring = RingBuf::new();
2427 assert_eq!(ring.get(0), Some(&0));
2428 assert_eq!(ring.get(1), None);
2431 assert_eq!(ring.get(0), Some(&0));
2432 assert_eq!(ring.get(1), Some(&1));
2433 assert_eq!(ring.get(2), None);
2436 assert_eq!(ring.get(0), Some(&0));
2437 assert_eq!(ring.get(1), Some(&1));
2438 assert_eq!(ring.get(2), Some(&2));
2439 assert_eq!(ring.get(3), None);
2441 assert_eq!(ring.pop_front(), Some(0));
2442 assert_eq!(ring.get(0), Some(&1));
2443 assert_eq!(ring.get(1), Some(&2));
2444 assert_eq!(ring.get(2), None);
2446 assert_eq!(ring.pop_front(), Some(1));
2447 assert_eq!(ring.get(0), Some(&2));
2448 assert_eq!(ring.get(1), None);
2450 assert_eq!(ring.pop_front(), Some(2));
2451 assert_eq!(ring.get(0), None);
2452 assert_eq!(ring.get(1), None);
2457 let mut ring = RingBuf::new();
2458 for i in range(0i, 3) {
2462 match ring.get_mut(1) {
2467 assert_eq!(ring.get_mut(0), Some(&mut 0));
2468 assert_eq!(ring.get_mut(1), Some(&mut -1));
2469 assert_eq!(ring.get_mut(2), Some(&mut 2));
2470 assert_eq!(ring.get_mut(3), None);
2472 assert_eq!(ring.pop_front(), Some(0));
2473 assert_eq!(ring.get_mut(0), Some(&mut -1));
2474 assert_eq!(ring.get_mut(1), Some(&mut 2));
2475 assert_eq!(ring.get_mut(2), None);
2479 fn test_swap_front_back_remove() {
2480 fn test(back: bool) {
2481 // This test checks that every single combination of tail position and length is tested.
2482 // Capacity 15 should be large enough to cover every case.
2483 let mut tester = RingBuf::with_capacity(15);
2484 let usable_cap = tester.capacity();
2485 let final_len = usable_cap / 2;
2487 for len in range(0, final_len) {
2488 let expected = if back {
2489 range(0, len).collect()
2491 range(0, len).rev().collect()
2493 for tail_pos in range(0, usable_cap) {
2494 tester.tail = tail_pos;
2495 tester.head = tail_pos;
2497 for i in range(0, len * 2) {
2498 tester.push_front(i);
2500 for i in range(0, len) {
2501 assert_eq!(tester.swap_back_remove(i), Some(len * 2 - 1 - i));
2504 for i in range(0, len * 2) {
2505 tester.push_back(i);
2507 for i in range(0, len) {
2508 let idx = tester.len() - 1 - i;
2509 assert_eq!(tester.swap_front_remove(idx), Some(len * 2 - 1 - i));
2512 assert!(tester.tail < tester.cap);
2513 assert!(tester.head < tester.cap);
2514 assert_eq!(tester, expected);
2524 // This test checks that every single combination of tail position, length, and
2525 // insertion position is tested. Capacity 15 should be large enough to cover every case.
2527 let mut tester = RingBuf::with_capacity(15);
2528 // can't guarantee we got 15, so have to get what we got.
2529 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2530 // this test isn't covering what it wants to
2531 let cap = tester.capacity();
2534 // len is the length *after* insertion
2535 for len in range(1, cap) {
2536 // 0, 1, 2, .., len - 1
2537 let expected = iter::count(0, 1).take(len).collect();
2538 for tail_pos in range(0, cap) {
2539 for to_insert in range(0, len) {
2540 tester.tail = tail_pos;
2541 tester.head = tail_pos;
2542 for i in range(0, len) {
2544 tester.push_back(i);
2547 tester.insert(to_insert, to_insert);
2548 assert!(tester.tail < tester.cap);
2549 assert!(tester.head < tester.cap);
2550 assert_eq!(tester, expected);
2558 // This test checks that every single combination of tail position, length, and
2559 // removal position is tested. Capacity 15 should be large enough to cover every case.
2561 let mut tester = RingBuf::with_capacity(15);
2562 // can't guarantee we got 15, so have to get what we got.
2563 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2564 // this test isn't covering what it wants to
2565 let cap = tester.capacity();
2567 // len is the length *after* removal
2568 for len in range(0, cap - 1) {
2569 // 0, 1, 2, .., len - 1
2570 let expected = iter::count(0, 1).take(len).collect();
2571 for tail_pos in range(0, cap) {
2572 for to_remove in range(0, len + 1) {
2573 tester.tail = tail_pos;
2574 tester.head = tail_pos;
2575 for i in range(0, len) {
2577 tester.push_back(1234);
2579 tester.push_back(i);
2581 if to_remove == len {
2582 tester.push_back(1234);
2584 tester.remove(to_remove);
2585 assert!(tester.tail < tester.cap);
2586 assert!(tester.head < tester.cap);
2587 assert_eq!(tester, expected);
2594 fn test_shrink_to_fit() {
2595 // This test checks that every single combination of head and tail position,
2596 // is tested. Capacity 15 should be large enough to cover every case.
2598 let mut tester = RingBuf::with_capacity(15);
2599 // can't guarantee we got 15, so have to get what we got.
2600 // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2601 // this test isn't covering what it wants to
2602 let cap = tester.capacity();
2604 let max_cap = tester.capacity();
2606 for len in range(0, cap + 1) {
2607 // 0, 1, 2, .., len - 1
2608 let expected = iter::count(0, 1).take(len).collect();
2609 for tail_pos in range(0, max_cap + 1) {
2610 tester.tail = tail_pos;
2611 tester.head = tail_pos;
2613 for i in range(0, len) {
2614 tester.push_back(i);
2616 tester.shrink_to_fit();
2617 assert!(tester.capacity() <= cap);
2618 assert!(tester.tail < tester.cap);
2619 assert!(tester.head < tester.cap);
2620 assert_eq!(tester, expected);
2627 let mut ring = RingBuf::new();
2628 ring.push_back(10i);
2629 ring.push_back(20i);
2630 assert_eq!(ring.front(), Some(&10));
2632 assert_eq!(ring.front(), Some(&20));
2634 assert_eq!(ring.front(), None);
2638 fn test_as_slices() {
2639 let mut ring: RingBuf<int> = RingBuf::with_capacity(127);
2640 let cap = ring.capacity() as int;
2642 let last = cap - first;
2643 for i in range(0, first) {
2646 let (left, right) = ring.as_slices();
2647 let expected: Vec<_> = range(0, i+1).collect();
2648 assert_eq!(left, expected);
2649 assert_eq!(right, []);
2652 for j in range(-last, 0) {
2654 let (left, right) = ring.as_slices();
2655 let expected_left: Vec<_> = range(-last, j+1).rev().collect();
2656 let expected_right: Vec<_> = range(0, first).collect();
2657 assert_eq!(left, expected_left);
2658 assert_eq!(right, expected_right);
2661 assert_eq!(ring.len() as int, cap);
2662 assert_eq!(ring.capacity() as int, cap);
2666 fn test_as_mut_slices() {
2667 let mut ring: RingBuf<int> = RingBuf::with_capacity(127);
2668 let cap = ring.capacity() as int;
2670 let last = cap - first;
2671 for i in range(0, first) {
2674 let (left, right) = ring.as_mut_slices();
2675 let expected: Vec<_> = range(0, i+1).collect();
2676 assert_eq!(left, expected);
2677 assert_eq!(right, []);
2680 for j in range(-last, 0) {
2682 let (left, right) = ring.as_mut_slices();
2683 let expected_left: Vec<_> = range(-last, j+1).rev().collect();
2684 let expected_right: Vec<_> = range(0, first).collect();
2685 assert_eq!(left, expected_left);
2686 assert_eq!(right, expected_right);
2689 assert_eq!(ring.len() as int, cap);
2690 assert_eq!(ring.capacity() as int, cap);