]> git.lizzy.rs Git - rust.git/blob - src/libcollections/ring_buf.rs
Merge pull request #20510 from tshepang/patch-6
[rust.git] / src / libcollections / ring_buf.rs
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.
4 //
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.
10
11 //! This crate implements a double-ended queue with `O(1)` amortized inserts and removals from both
12 //! ends of the container. It also has `O(1)` indexing like a vector. The contained elements are
13 //! not required to be copyable, and the queue will be sendable if the contained type is sendable.
14
15 use core::prelude::*;
16
17 use core::cmp::Ordering;
18 use core::default::Default;
19 use core::fmt;
20 use core::iter::{self, FromIterator, RandomAccessIterator};
21 use core::kinds::marker;
22 use core::mem;
23 use core::num::{Int, UnsignedInt};
24 use core::ops::{Index, IndexMut};
25 use core::ptr;
26 use core::raw::Slice as RawSlice;
27
28 use std::hash::{Writer, Hash};
29 use std::cmp;
30
31 use alloc::heap;
32
33 static INITIAL_CAPACITY: uint = 8u; // 2^3
34 static MINIMUM_CAPACITY: uint = 2u;
35
36 // FIXME(conventions): implement shrink_to_fit. Awkward with the current design, but it should
37 // be scrapped anyway. Defer to rewrite?
38
39 /// `RingBuf` is a circular buffer, which can be used as a double-ended queue efficiently.
40 #[stable]
41 pub struct RingBuf<T> {
42     // tail and head are pointers into the buffer. Tail always points
43     // to the first element that could be read, Head always points
44     // to where data should be written.
45     // If tail == head the buffer is empty. The length of the ringbuf
46     // is defined as the distance between the two.
47
48     tail: uint,
49     head: uint,
50     cap: uint,
51     ptr: *mut T
52 }
53
54 #[stable]
55 unsafe impl<T: Send> Send for RingBuf<T> {}
56
57 #[stable]
58 unsafe impl<T: Sync> Sync for RingBuf<T> {}
59
60 #[stable]
61 impl<T: Clone> Clone for RingBuf<T> {
62     fn clone(&self) -> RingBuf<T> {
63         self.iter().map(|t| t.clone()).collect()
64     }
65 }
66
67 #[unsafe_destructor]
68 #[stable]
69 impl<T> Drop for RingBuf<T> {
70     fn drop(&mut self) {
71         self.clear();
72         unsafe {
73             if mem::size_of::<T>() != 0 {
74                 heap::deallocate(self.ptr as *mut u8,
75                                  self.cap * mem::size_of::<T>(),
76                                  mem::min_align_of::<T>())
77             }
78         }
79     }
80 }
81
82 #[stable]
83 impl<T> Default for RingBuf<T> {
84     #[inline]
85     fn default() -> RingBuf<T> { RingBuf::new() }
86 }
87
88 impl<T> RingBuf<T> {
89     /// Turn ptr into a slice
90     #[inline]
91     unsafe fn buffer_as_slice(&self) -> &[T] {
92         mem::transmute(RawSlice { data: self.ptr as *const T, len: self.cap })
93     }
94
95     /// Turn ptr into a mut slice
96     #[inline]
97     unsafe fn buffer_as_mut_slice(&mut self) -> &mut [T] {
98         mem::transmute(RawSlice { data: self.ptr as *const T, len: self.cap })
99     }
100
101     /// Moves an element out of the buffer
102     #[inline]
103     unsafe fn buffer_read(&mut self, off: uint) -> T {
104         ptr::read(self.ptr.offset(off as int) as *const T)
105     }
106
107     /// Writes an element into the buffer, moving it.
108     #[inline]
109     unsafe fn buffer_write(&mut self, off: uint, t: T) {
110         ptr::write(self.ptr.offset(off as int), t);
111     }
112
113     /// Returns true iff the buffer is at capacity
114     #[inline]
115     fn is_full(&self) -> bool { self.cap - self.len() == 1 }
116
117     /// Returns the index in the underlying buffer for a given logical element index.
118     #[inline]
119     fn wrap_index(&self, idx: uint) -> uint { wrap_index(idx, self.cap) }
120
121     /// Copies a contiguous block of memory len long from src to dst
122     #[inline]
123     unsafe fn copy(&self, dst: uint, src: uint, len: uint) {
124         debug_assert!(dst + len <= self.cap, "dst={} src={} len={} cap={}", dst, src, len,
125                       self.cap);
126         debug_assert!(src + len <= self.cap, "dst={} src={} len={} cap={}", dst, src, len,
127                       self.cap);
128         ptr::copy_memory(
129             self.ptr.offset(dst as int),
130             self.ptr.offset(src as int) as *const T,
131             len);
132     }
133 }
134
135 impl<T> RingBuf<T> {
136     /// Creates an empty `RingBuf`.
137     #[stable]
138     pub fn new() -> RingBuf<T> {
139         RingBuf::with_capacity(INITIAL_CAPACITY)
140     }
141
142     /// Creates an empty `RingBuf` with space for at least `n` elements.
143     #[stable]
144     pub fn with_capacity(n: uint) -> RingBuf<T> {
145         // +1 since the ringbuffer always leaves one space empty
146         let cap = cmp::max(n + 1, MINIMUM_CAPACITY).next_power_of_two();
147         let size = cap.checked_mul(mem::size_of::<T>())
148                       .expect("capacity overflow");
149
150         let ptr = if mem::size_of::<T>() != 0 {
151             unsafe {
152                 let ptr = heap::allocate(size, mem::min_align_of::<T>())  as *mut T;;
153                 if ptr.is_null() { ::alloc::oom() }
154                 ptr
155             }
156         } else {
157             heap::EMPTY as *mut T
158         };
159
160         RingBuf {
161             tail: 0,
162             head: 0,
163             cap: cap,
164             ptr: ptr
165         }
166     }
167
168     /// Retrieves an element in the `RingBuf` by index.
169     ///
170     /// # Examples
171     ///
172     /// ```rust
173     /// use std::collections::RingBuf;
174     ///
175     /// let mut buf = RingBuf::new();
176     /// buf.push_back(3i);
177     /// buf.push_back(4);
178     /// buf.push_back(5);
179     /// assert_eq!(buf.get(1).unwrap(), &4);
180     /// ```
181     #[stable]
182     pub fn get(&self, i: uint) -> Option<&T> {
183         if i < self.len() {
184             let idx = self.wrap_index(self.tail + i);
185             unsafe { Some(&*self.ptr.offset(idx as int)) }
186         } else {
187             None
188         }
189     }
190
191     /// Retrieves an element in the `RingBuf` mutably by index.
192     ///
193     /// # Examples
194     ///
195     /// ```rust
196     /// use std::collections::RingBuf;
197     ///
198     /// let mut buf = RingBuf::new();
199     /// buf.push_back(3i);
200     /// buf.push_back(4);
201     /// buf.push_back(5);
202     /// match buf.get_mut(1) {
203     ///     None => {}
204     ///     Some(elem) => {
205     ///         *elem = 7;
206     ///     }
207     /// }
208     ///
209     /// assert_eq!(buf[1], 7);
210     /// ```
211     #[stable]
212     pub fn get_mut(&mut self, i: uint) -> Option<&mut T> {
213         if i < self.len() {
214             let idx = self.wrap_index(self.tail + i);
215             unsafe { Some(&mut *self.ptr.offset(idx as int)) }
216         } else {
217             None
218         }
219     }
220
221     /// Swaps elements at indices `i` and `j`.
222     ///
223     /// `i` and `j` may be equal.
224     ///
225     /// Fails if there is no element with either index.
226     ///
227     /// # Examples
228     ///
229     /// ```rust
230     /// use std::collections::RingBuf;
231     ///
232     /// let mut buf = RingBuf::new();
233     /// buf.push_back(3i);
234     /// buf.push_back(4);
235     /// buf.push_back(5);
236     /// buf.swap(0, 2);
237     /// assert_eq!(buf[0], 5);
238     /// assert_eq!(buf[2], 3);
239     /// ```
240     #[stable]
241     pub fn swap(&mut self, i: uint, j: uint) {
242         assert!(i < self.len());
243         assert!(j < self.len());
244         let ri = self.wrap_index(self.tail + i);
245         let rj = self.wrap_index(self.tail + j);
246         unsafe {
247             ptr::swap(self.ptr.offset(ri as int), self.ptr.offset(rj as int))
248         }
249     }
250
251     /// Returns the number of elements the `RingBuf` can hold without
252     /// reallocating.
253     ///
254     /// # Examples
255     ///
256     /// ```
257     /// use std::collections::RingBuf;
258     ///
259     /// let buf: RingBuf<int> = RingBuf::with_capacity(10);
260     /// assert!(buf.capacity() >= 10);
261     /// ```
262     #[inline]
263     #[stable]
264     pub fn capacity(&self) -> uint { self.cap - 1 }
265
266     /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the
267     /// given `RingBuf`. Does nothing if the capacity is already sufficient.
268     ///
269     /// Note that the allocator may give the collection more space than it requests. Therefore
270     /// capacity can not be relied upon to be precisely minimal. Prefer `reserve` if future
271     /// insertions are expected.
272     ///
273     /// # Panics
274     ///
275     /// Panics if the new capacity overflows `uint`.
276     ///
277     /// # Examples
278     ///
279     /// ```
280     /// use std::collections::RingBuf;
281     ///
282     /// let mut buf: RingBuf<int> = vec![1].into_iter().collect();
283     /// buf.reserve_exact(10);
284     /// assert!(buf.capacity() >= 11);
285     /// ```
286     #[stable]
287     pub fn reserve_exact(&mut self, additional: uint) {
288         self.reserve(additional);
289     }
290
291     /// Reserves capacity for at least `additional` more elements to be inserted in the given
292     /// `Ringbuf`. The collection may reserve more space to avoid frequent reallocations.
293     ///
294     /// # Panics
295     ///
296     /// Panics if the new capacity overflows `uint`.
297     ///
298     /// # Examples
299     ///
300     /// ```
301     /// use std::collections::RingBuf;
302     ///
303     /// let mut buf: RingBuf<int> = vec![1].into_iter().collect();
304     /// buf.reserve(10);
305     /// assert!(buf.capacity() >= 11);
306     /// ```
307     #[stable]
308     pub fn reserve(&mut self, additional: uint) {
309         let new_len = self.len() + additional;
310         assert!(new_len + 1 > self.len(), "capacity overflow");
311         if new_len > self.capacity() {
312             let count = (new_len + 1).next_power_of_two();
313             assert!(count >= new_len + 1);
314
315             if mem::size_of::<T>() != 0 {
316                 let old = self.cap * mem::size_of::<T>();
317                 let new = count.checked_mul(mem::size_of::<T>())
318                                .expect("capacity overflow");
319                 unsafe {
320                     self.ptr = heap::reallocate(self.ptr as *mut u8,
321                                                 old,
322                                                 new,
323                                                 mem::min_align_of::<T>()) as *mut T;
324                     if self.ptr.is_null() { ::alloc::oom() }
325                 }
326             }
327
328             // Move the shortest contiguous section of the ring buffer
329             //    T             H
330             //   [o o o o o o o . ]
331             //    T             H
332             // A [o o o o o o o . . . . . . . . . ]
333             //        H T
334             //   [o o . o o o o o ]
335             //          T             H
336             // B [. . . o o o o o o o . . . . . . ]
337             //              H T
338             //   [o o o o o . o o ]
339             //              H                 T
340             // C [o o o o o . . . . . . . . . o o ]
341
342             let oldcap = self.cap;
343             self.cap = count;
344
345             if self.tail <= self.head { // A
346                 // Nop
347             } else if self.head < oldcap - self.tail { // B
348                 unsafe {
349                     ptr::copy_nonoverlapping_memory(
350                         self.ptr.offset(oldcap as int),
351                         self.ptr as *const T,
352                         self.head
353                     );
354                 }
355                 self.head += oldcap;
356                 debug_assert!(self.head > self.tail);
357             } else { // C
358                 unsafe {
359                     ptr::copy_nonoverlapping_memory(
360                         self.ptr.offset((count - (oldcap - self.tail)) as int),
361                         self.ptr.offset(self.tail as int) as *const T,
362                         oldcap - self.tail
363                     );
364                 }
365                 self.tail = count - (oldcap - self.tail);
366                 debug_assert!(self.head < self.tail);
367             }
368             debug_assert!(self.head < self.cap);
369             debug_assert!(self.tail < self.cap);
370             debug_assert!(self.cap.count_ones() == 1);
371         }
372     }
373
374     /// Returns a front-to-back iterator.
375     ///
376     /// # Examples
377     ///
378     /// ```rust
379     /// use std::collections::RingBuf;
380     ///
381     /// let mut buf = RingBuf::new();
382     /// buf.push_back(5i);
383     /// buf.push_back(3);
384     /// buf.push_back(4);
385     /// let b: &[_] = &[&5, &3, &4];
386     /// assert_eq!(buf.iter().collect::<Vec<&int>>().as_slice(), b);
387     /// ```
388     #[stable]
389     pub fn iter(&self) -> Iter<T> {
390         Iter {
391             tail: self.tail,
392             head: self.head,
393             ring: unsafe { self.buffer_as_slice() }
394         }
395     }
396
397     /// Returns a front-to-back iterator that returns mutable references.
398     ///
399     /// # Examples
400     ///
401     /// ```rust
402     /// use std::collections::RingBuf;
403     ///
404     /// let mut buf = RingBuf::new();
405     /// buf.push_back(5i);
406     /// buf.push_back(3);
407     /// buf.push_back(4);
408     /// for num in buf.iter_mut() {
409     ///     *num = *num - 2;
410     /// }
411     /// let b: &[_] = &[&mut 3, &mut 1, &mut 2];
412     /// assert_eq!(buf.iter_mut().collect::<Vec<&mut int>>()[], b);
413     /// ```
414     #[stable]
415     pub fn iter_mut<'a>(&'a mut self) -> IterMut<'a, T> {
416         IterMut {
417             tail: self.tail,
418             head: self.head,
419             cap: self.cap,
420             ptr: self.ptr,
421             marker: marker::ContravariantLifetime::<'a>,
422         }
423     }
424
425     /// Consumes the list into an iterator yielding elements by value.
426     #[stable]
427     pub fn into_iter(self) -> IntoIter<T> {
428         IntoIter {
429             inner: self,
430         }
431     }
432
433     /// Returns a pair of slices which contain, in order, the contents of the
434     /// `RingBuf`.
435     #[inline]
436     #[unstable = "matches collection reform specification, waiting for dust to settle"]
437     pub fn as_slices<'a>(&'a self) -> (&'a [T], &'a [T]) {
438         unsafe {
439             let contiguous = self.is_contiguous();
440             let buf = self.buffer_as_slice();
441             if contiguous {
442                 let (empty, buf) = buf.split_at(0);
443                 (buf[self.tail..self.head], empty)
444             } else {
445                 let (mid, right) = buf.split_at(self.tail);
446                 let (left, _) = mid.split_at(self.head);
447                 (right, left)
448             }
449         }
450     }
451
452     /// Returns a pair of slices which contain, in order, the contents of the
453     /// `RingBuf`.
454     #[inline]
455     #[unstable = "matches collection reform specification, waiting for dust to settle"]
456     pub fn as_mut_slices<'a>(&'a mut self) -> (&'a mut [T], &'a mut [T]) {
457         unsafe {
458             let contiguous = self.is_contiguous();
459             let head = self.head;
460             let tail = self.tail;
461             let buf = self.buffer_as_mut_slice();
462
463             if contiguous {
464                 let (empty, buf) = buf.split_at_mut(0);
465                 (buf.slice_mut(tail, head), empty)
466             } else {
467                 let (mid, right) = buf.split_at_mut(tail);
468                 let (left, _) = mid.split_at_mut(head);
469
470                 (right, left)
471             }
472         }
473     }
474
475     /// Returns the number of elements in the `RingBuf`.
476     ///
477     /// # Examples
478     ///
479     /// ```
480     /// use std::collections::RingBuf;
481     ///
482     /// let mut v = RingBuf::new();
483     /// assert_eq!(v.len(), 0);
484     /// v.push_back(1i);
485     /// assert_eq!(v.len(), 1);
486     /// ```
487     #[stable]
488     pub fn len(&self) -> uint { count(self.tail, self.head, self.cap) }
489
490     /// Returns true if the buffer contains no elements
491     ///
492     /// # Examples
493     ///
494     /// ```
495     /// use std::collections::RingBuf;
496     ///
497     /// let mut v = RingBuf::new();
498     /// assert!(v.is_empty());
499     /// v.push_front(1i);
500     /// assert!(!v.is_empty());
501     /// ```
502     #[stable]
503     pub fn is_empty(&self) -> bool { self.len() == 0 }
504
505     /// Creates a draining iterator that clears the `RingBuf` and iterates over
506     /// the removed items from start to end.
507     ///
508     /// # Examples
509     ///
510     /// ```
511     /// use std::collections::RingBuf;
512     ///
513     /// let mut v = RingBuf::new();
514     /// v.push_back(1i);
515     /// assert_eq!(v.drain().next(), Some(1));
516     /// assert!(v.is_empty());
517     /// ```
518     #[inline]
519     #[unstable = "matches collection reform specification, waiting for dust to settle"]
520     pub fn drain(&mut self) -> Drain<T> {
521         Drain {
522             inner: self,
523         }
524     }
525
526     /// Clears the buffer, removing all values.
527     ///
528     /// # Examples
529     ///
530     /// ```
531     /// use std::collections::RingBuf;
532     ///
533     /// let mut v = RingBuf::new();
534     /// v.push_back(1i);
535     /// v.clear();
536     /// assert!(v.is_empty());
537     /// ```
538     #[stable]
539     #[inline]
540     pub fn clear(&mut self) {
541         self.drain();
542     }
543
544     /// Provides a reference to the front element, or `None` if the sequence is
545     /// empty.
546     ///
547     /// # Examples
548     ///
549     /// ```
550     /// use std::collections::RingBuf;
551     ///
552     /// let mut d = RingBuf::new();
553     /// assert_eq!(d.front(), None);
554     ///
555     /// d.push_back(1i);
556     /// d.push_back(2i);
557     /// assert_eq!(d.front(), Some(&1i));
558     /// ```
559     #[stable]
560     pub fn front(&self) -> Option<&T> {
561         if !self.is_empty() { Some(&self[0]) } else { None }
562     }
563
564     /// Provides a mutable reference to the front element, or `None` if the
565     /// sequence is empty.
566     ///
567     /// # Examples
568     ///
569     /// ```
570     /// use std::collections::RingBuf;
571     ///
572     /// let mut d = RingBuf::new();
573     /// assert_eq!(d.front_mut(), None);
574     ///
575     /// d.push_back(1i);
576     /// d.push_back(2i);
577     /// match d.front_mut() {
578     ///     Some(x) => *x = 9i,
579     ///     None => (),
580     /// }
581     /// assert_eq!(d.front(), Some(&9i));
582     /// ```
583     #[stable]
584     pub fn front_mut(&mut self) -> Option<&mut T> {
585         if !self.is_empty() { Some(&mut self[0]) } else { None }
586     }
587
588     /// Provides a reference to the back element, or `None` if the sequence is
589     /// empty.
590     ///
591     /// # Examples
592     ///
593     /// ```
594     /// use std::collections::RingBuf;
595     ///
596     /// let mut d = RingBuf::new();
597     /// assert_eq!(d.back(), None);
598     ///
599     /// d.push_back(1i);
600     /// d.push_back(2i);
601     /// assert_eq!(d.back(), Some(&2i));
602     /// ```
603     #[stable]
604     pub fn back(&self) -> Option<&T> {
605         if !self.is_empty() { Some(&self[self.len() - 1]) } else { None }
606     }
607
608     /// Provides a mutable reference to the back element, or `None` if the
609     /// sequence is empty.
610     ///
611     /// # Examples
612     ///
613     /// ```
614     /// use std::collections::RingBuf;
615     ///
616     /// let mut d = RingBuf::new();
617     /// assert_eq!(d.back(), None);
618     ///
619     /// d.push_back(1i);
620     /// d.push_back(2i);
621     /// match d.back_mut() {
622     ///     Some(x) => *x = 9i,
623     ///     None => (),
624     /// }
625     /// assert_eq!(d.back(), Some(&9i));
626     /// ```
627     #[stable]
628     pub fn back_mut(&mut self) -> Option<&mut T> {
629         let len = self.len();
630         if !self.is_empty() { Some(&mut self[len - 1]) } else { None }
631     }
632
633     /// Removes the first element and returns it, or `None` if the sequence is
634     /// empty.
635     ///
636     /// # Examples
637     ///
638     /// ```
639     /// use std::collections::RingBuf;
640     ///
641     /// let mut d = RingBuf::new();
642     /// d.push_back(1i);
643     /// d.push_back(2i);
644     ///
645     /// assert_eq!(d.pop_front(), Some(1i));
646     /// assert_eq!(d.pop_front(), Some(2i));
647     /// assert_eq!(d.pop_front(), None);
648     /// ```
649     #[stable]
650     pub fn pop_front(&mut self) -> Option<T> {
651         if self.is_empty() {
652             None
653         } else {
654             let tail = self.tail;
655             self.tail = self.wrap_index(self.tail + 1);
656             unsafe { Some(self.buffer_read(tail)) }
657         }
658     }
659
660     /// Inserts an element first in the sequence.
661     ///
662     /// # Examples
663     ///
664     /// ```
665     /// use std::collections::RingBuf;
666     ///
667     /// let mut d = RingBuf::new();
668     /// d.push_front(1i);
669     /// d.push_front(2i);
670     /// assert_eq!(d.front(), Some(&2i));
671     /// ```
672     #[stable]
673     pub fn push_front(&mut self, t: T) {
674         if self.is_full() {
675             self.reserve(1);
676             debug_assert!(!self.is_full());
677         }
678
679         self.tail = self.wrap_index(self.tail - 1);
680         let tail = self.tail;
681         unsafe { self.buffer_write(tail, t); }
682     }
683
684     /// Appends an element to the back of a buffer
685     ///
686     /// # Examples
687     ///
688     /// ```rust
689     /// use std::collections::RingBuf;
690     ///
691     /// let mut buf = RingBuf::new();
692     /// buf.push_back(1i);
693     /// buf.push_back(3);
694     /// assert_eq!(3, *buf.back().unwrap());
695     /// ```
696     #[stable]
697     pub fn push_back(&mut self, t: T) {
698         if self.is_full() {
699             self.reserve(1);
700             debug_assert!(!self.is_full());
701         }
702
703         let head = self.head;
704         self.head = self.wrap_index(self.head + 1);
705         unsafe { self.buffer_write(head, t) }
706     }
707
708     /// Removes the last element from a buffer and returns it, or `None` if
709     /// it is empty.
710     ///
711     /// # Examples
712     ///
713     /// ```rust
714     /// use std::collections::RingBuf;
715     ///
716     /// let mut buf = RingBuf::new();
717     /// assert_eq!(buf.pop_back(), None);
718     /// buf.push_back(1i);
719     /// buf.push_back(3);
720     /// assert_eq!(buf.pop_back(), Some(3));
721     /// ```
722     #[stable]
723     pub fn pop_back(&mut self) -> Option<T> {
724         if self.is_empty() {
725             None
726         } else {
727             self.head = self.wrap_index(self.head - 1);
728             let head = self.head;
729             unsafe { Some(self.buffer_read(head)) }
730         }
731     }
732
733     #[inline]
734     fn is_contiguous(&self) -> bool {
735         self.tail <= self.head
736     }
737
738     /// Inserts an element at position `i` within the ringbuf. Whichever
739     /// end is closer to the insertion point will be moved to make room,
740     /// and all the affected elements will be moved to new positions.
741     ///
742     /// # Panics
743     ///
744     /// Panics if `i` is greater than ringbuf's length
745     ///
746     /// # Example
747     /// ```rust
748     /// use std::collections::RingBuf;
749     ///
750     /// let mut buf = RingBuf::new();
751     /// buf.push_back(10i);
752     /// buf.push_back(12);
753     /// buf.insert(1,11);
754     /// assert_eq!(Some(&11), buf.get(1));
755     /// ```
756     pub fn insert(&mut self, i: uint, t: T) {
757         assert!(i <= self.len(), "index out of bounds");
758         if self.is_full() {
759             self.reserve(1);
760             debug_assert!(!self.is_full());
761         }
762
763         // Move the least number of elements in the ring buffer and insert
764         // the given object
765         //
766         // At most len/2 - 1 elements will be moved. O(min(n, n-i))
767         //
768         // There are three main cases:
769         //  Elements are contiguous
770         //      - special case when tail is 0
771         //  Elements are discontiguous and the insert is in the tail section
772         //  Elements are discontiguous and the insert is in the head section
773         //
774         // For each of those there are two more cases:
775         //  Insert is closer to tail
776         //  Insert is closer to head
777         //
778         // Key: H - self.head
779         //      T - self.tail
780         //      o - Valid element
781         //      I - Insertion element
782         //      A - The element that should be after the insertion point
783         //      M - Indicates element was moved
784
785         let idx = self.wrap_index(self.tail + i);
786
787         let distance_to_tail = i;
788         let distance_to_head = self.len() - i;
789
790         let contiguous = self.is_contiguous();
791
792         match (contiguous, distance_to_tail <= distance_to_head, idx >= self.tail) {
793             (true, true, _) if i == 0 => {
794                 // push_front
795                 //
796                 //       T
797                 //       I             H
798                 //      [A o o o o o o . . . . . . . . .]
799                 //
800                 //                       H         T
801                 //      [A o o o o o o o . . . . . I]
802                 //
803
804                 self.tail = self.wrap_index(self.tail - 1);
805             },
806             (true, true, _) => unsafe {
807                 // contiguous, insert closer to tail:
808                 //
809                 //             T   I         H
810                 //      [. . . o o A o o o o . . . . . .]
811                 //
812                 //           T               H
813                 //      [. . o o I A o o o o . . . . . .]
814                 //           M M
815                 //
816                 // contiguous, insert closer to tail and tail is 0:
817                 //
818                 //
819                 //       T   I         H
820                 //      [o o A o o o o . . . . . . . . .]
821                 //
822                 //                       H             T
823                 //      [o I A o o o o o . . . . . . . o]
824                 //       M                             M
825
826                 let new_tail = self.wrap_index(self.tail - 1);
827
828                 self.copy(new_tail, self.tail, 1);
829                 // Already moved the tail, so we only copy `i - 1` elements.
830                 self.copy(self.tail, self.tail + 1, i - 1);
831
832                 self.tail = new_tail;
833             },
834             (true, false, _) => unsafe {
835                 //  contiguous, insert closer to head:
836                 //
837                 //             T       I     H
838                 //      [. . . o o o o A o o . . . . . .]
839                 //
840                 //             T               H
841                 //      [. . . o o o o I A o o . . . . .]
842                 //                       M M M
843
844                 self.copy(idx + 1, idx, self.head - idx);
845                 self.head = self.wrap_index(self.head + 1);
846             },
847             (false, true, true) => unsafe {
848                 // discontiguous, insert closer to tail, tail section:
849                 //
850                 //                   H         T   I
851                 //      [o o o o o o . . . . . o o A o o]
852                 //
853                 //                   H       T
854                 //      [o o o o o o . . . . o o I A o o]
855                 //                           M M
856
857                 self.copy(self.tail - 1, self.tail, i);
858                 self.tail -= 1;
859             },
860             (false, false, true) => unsafe {
861                 // discontiguous, insert closer to head, tail section:
862                 //
863                 //           H             T         I
864                 //      [o o . . . . . . . o o o o o A o]
865                 //
866                 //             H           T
867                 //      [o o o . . . . . . o o o o o I A]
868                 //       M M M                         M
869
870                 // copy elements up to new head
871                 self.copy(1, 0, self.head);
872
873                 // copy last element into empty spot at bottom of buffer
874                 self.copy(0, self.cap - 1, 1);
875
876                 // move elements from idx to end forward not including ^ element
877                 self.copy(idx + 1, idx, self.cap - 1 - idx);
878
879                 self.head += 1;
880             },
881             (false, true, false) if idx == 0 => unsafe {
882                 // discontiguous, insert is closer to tail, head section,
883                 // and is at index zero in the internal buffer:
884                 //
885                 //       I                   H     T
886                 //      [A o o o o o o o o o . . . o o o]
887                 //
888                 //                           H   T
889                 //      [A o o o o o o o o o . . o o o I]
890                 //                               M M M
891
892                 // copy elements up to new tail
893                 self.copy(self.tail - 1, self.tail, self.cap - self.tail);
894
895                 // copy last element into empty spot at bottom of buffer
896                 self.copy(self.cap - 1, 0, 1);
897
898                 self.tail -= 1;
899             },
900             (false, true, false) => unsafe {
901                 // discontiguous, insert closer to tail, head section:
902                 //
903                 //             I             H     T
904                 //      [o o o A o o o o o o . . . o o o]
905                 //
906                 //                           H   T
907                 //      [o o I A o o o o o o . . o o o o]
908                 //       M M                     M M M M
909
910                 // copy elements up to new tail
911                 self.copy(self.tail - 1, self.tail, self.cap - self.tail);
912
913                 // copy last element into empty spot at bottom of buffer
914                 self.copy(self.cap - 1, 0, 1);
915
916                 // move elements from idx-1 to end forward not including ^ element
917                 self.copy(0, 1, idx - 1);
918
919                 self.tail -= 1;
920             },
921             (false, false, false) => unsafe {
922                 // discontiguous, insert closer to head, head section:
923                 //
924                 //               I     H           T
925                 //      [o o o o A o o . . . . . . o o o]
926                 //
927                 //                     H           T
928                 //      [o o o o I A o o . . . . . o o o]
929                 //                 M M M
930
931                 self.copy(idx + 1, idx, self.head - idx);
932                 self.head += 1;
933             }
934         }
935
936         // tail might've been changed so we need to recalculate
937         let new_idx = self.wrap_index(self.tail + i);
938         unsafe {
939             self.buffer_write(new_idx, t);
940         }
941     }
942
943     /// Removes and returns the element at position `i` from the ringbuf.
944     /// Whichever end is closer to the removal point will be moved to make
945     /// room, and all the affected elements will be moved to new positions.
946     /// Returns `None` if `i` is out of bounds.
947     ///
948     /// # Example
949     /// ```rust
950     /// use std::collections::RingBuf;
951     ///
952     /// let mut buf = RingBuf::new();
953     /// buf.push_back(5i);
954     /// buf.push_back(10i);
955     /// buf.push_back(12i);
956     /// buf.push_back(15);
957     /// buf.remove(2);
958     /// assert_eq!(Some(&15), buf.get(2));
959     /// ```
960     #[stable]
961     pub fn remove(&mut self, i: uint) -> Option<T> {
962         if self.is_empty() || self.len() <= i {
963             return None;
964         }
965
966         // There are three main cases:
967         //  Elements are contiguous
968         //  Elements are discontiguous and the removal is in the tail section
969         //  Elements are discontiguous and the removal is in the head section
970         //      - special case when elements are technically contiguous,
971         //        but self.head = 0
972         //
973         // For each of those there are two more cases:
974         //  Insert is closer to tail
975         //  Insert is closer to head
976         //
977         // Key: H - self.head
978         //      T - self.tail
979         //      o - Valid element
980         //      x - Element marked for removal
981         //      R - Indicates element that is being removed
982         //      M - Indicates element was moved
983
984         let idx = self.wrap_index(self.tail + i);
985
986         let elem = unsafe {
987             Some(self.buffer_read(idx))
988         };
989
990         let distance_to_tail = i;
991         let distance_to_head = self.len() - i;
992
993         let contiguous = self.tail <= self.head;
994
995         match (contiguous, distance_to_tail <= distance_to_head, idx >= self.tail) {
996             (true, true, _) => unsafe {
997                 // contiguous, remove closer to tail:
998                 //
999                 //             T   R         H
1000                 //      [. . . o o x o o o o . . . . . .]
1001                 //
1002                 //               T           H
1003                 //      [. . . . o o o o o o . . . . . .]
1004                 //               M M
1005
1006                 self.copy(self.tail + 1, self.tail, i);
1007                 self.tail += 1;
1008             },
1009             (true, false, _) => unsafe {
1010                 // contiguous, remove closer to head:
1011                 //
1012                 //             T       R     H
1013                 //      [. . . o o o o x o o . . . . . .]
1014                 //
1015                 //             T           H
1016                 //      [. . . o o o o o o . . . . . . .]
1017                 //                     M M
1018
1019                 self.copy(idx, idx + 1, self.head - idx - 1);
1020                 self.head -= 1;
1021             },
1022             (false, true, true) => unsafe {
1023                 // discontiguous, remove closer to tail, tail section:
1024                 //
1025                 //                   H         T   R
1026                 //      [o o o o o o . . . . . o o x o o]
1027                 //
1028                 //                   H           T
1029                 //      [o o o o o o . . . . . . o o o o]
1030                 //                               M M
1031
1032                 self.copy(self.tail + 1, self.tail, i);
1033                 self.tail = self.wrap_index(self.tail + 1);
1034             },
1035             (false, false, false) => unsafe {
1036                 // discontiguous, remove closer to head, head section:
1037                 //
1038                 //               R     H           T
1039                 //      [o o o o x o o . . . . . . o o o]
1040                 //
1041                 //                   H             T
1042                 //      [o o o o o o . . . . . . . o o o]
1043                 //               M M
1044
1045                 self.copy(idx, idx + 1, self.head - idx - 1);
1046                 self.head -= 1;
1047             },
1048             (false, false, true) => unsafe {
1049                 // discontiguous, remove closer to head, tail section:
1050                 //
1051                 //             H           T         R
1052                 //      [o o o . . . . . . o o o o o x o]
1053                 //
1054                 //           H             T
1055                 //      [o o . . . . . . . o o o o o o o]
1056                 //       M M                         M M
1057                 //
1058                 // or quasi-discontiguous, remove next to head, tail section:
1059                 //
1060                 //       H                 T         R
1061                 //      [. . . . . . . . . o o o o o x o]
1062                 //
1063                 //                         T           H
1064                 //      [. . . . . . . . . o o o o o o .]
1065                 //                                   M
1066
1067                 // draw in elements in the tail section
1068                 self.copy(idx, idx + 1, self.cap - idx - 1);
1069
1070                 // Prevents underflow.
1071                 if self.head != 0 {
1072                     // copy first element into empty spot
1073                     self.copy(self.cap - 1, 0, 1);
1074
1075                     // move elements in the head section backwards
1076                     self.copy(0, 1, self.head - 1);
1077                 }
1078
1079                 self.head = self.wrap_index(self.head - 1);
1080             },
1081             (false, true, false) => unsafe {
1082                 // discontiguous, remove closer to tail, head section:
1083                 //
1084                 //           R               H     T
1085                 //      [o o x o o o o o o o . . . o o o]
1086                 //
1087                 //                           H       T
1088                 //      [o o o o o o o o o o . . . . o o]
1089                 //       M M M                       M M
1090
1091                 // draw in elements up to idx
1092                 self.copy(1, 0, idx);
1093
1094                 // copy last element into empty spot
1095                 self.copy(0, self.cap - 1, 1);
1096
1097                 // move elements from tail to end forward, excluding the last one
1098                 self.copy(self.tail + 1, self.tail, self.cap - self.tail - 1);
1099
1100                 self.tail = self.wrap_index(self.tail + 1);
1101             }
1102         }
1103
1104         return elem;
1105     }
1106 }
1107
1108 /// Returns the index in the underlying buffer for a given logical element index.
1109 #[inline]
1110 fn wrap_index(index: uint, size: uint) -> uint {
1111     // size is always a power of 2
1112     index & (size - 1)
1113 }
1114
1115 /// Calculate the number of elements left to be read in the buffer
1116 #[inline]
1117 fn count(tail: uint, head: uint, size: uint) -> uint {
1118     // size is always a power of 2
1119     (head - tail) & (size - 1)
1120 }
1121
1122 /// `RingBuf` iterator.
1123 #[stable]
1124 pub struct Iter<'a, T:'a> {
1125     ring: &'a [T],
1126     tail: uint,
1127     head: uint
1128 }
1129
1130 // FIXME(#19839) Remove in favor of `#[derive(Clone)]`
1131 impl<'a, T> Clone for Iter<'a, T> {
1132     fn clone(&self) -> Iter<'a, T> {
1133         Iter {
1134             ring: self.ring,
1135             tail: self.tail,
1136             head: self.head
1137         }
1138     }
1139 }
1140
1141 #[stable]
1142 impl<'a, T> Iterator for Iter<'a, T> {
1143     type Item = &'a T;
1144
1145     #[inline]
1146     fn next(&mut self) -> Option<&'a T> {
1147         if self.tail == self.head {
1148             return None;
1149         }
1150         let tail = self.tail;
1151         self.tail = wrap_index(self.tail + 1, self.ring.len());
1152         unsafe { Some(self.ring.get_unchecked(tail)) }
1153     }
1154
1155     #[inline]
1156     fn size_hint(&self) -> (uint, Option<uint>) {
1157         let len = count(self.tail, self.head, self.ring.len());
1158         (len, Some(len))
1159     }
1160 }
1161
1162 #[stable]
1163 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
1164     #[inline]
1165     fn next_back(&mut self) -> Option<&'a T> {
1166         if self.tail == self.head {
1167             return None;
1168         }
1169         self.head = wrap_index(self.head - 1, self.ring.len());
1170         unsafe { Some(self.ring.get_unchecked(self.head)) }
1171     }
1172 }
1173
1174 #[stable]
1175 impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
1176
1177 #[stable]
1178 impl<'a, T> RandomAccessIterator for Iter<'a, T> {
1179     #[inline]
1180     fn indexable(&self) -> uint {
1181         let (len, _) = self.size_hint();
1182         len
1183     }
1184
1185     #[inline]
1186     fn idx(&mut self, j: uint) -> Option<&'a T> {
1187         if j >= self.indexable() {
1188             None
1189         } else {
1190             let idx = wrap_index(self.tail + j, self.ring.len());
1191             unsafe { Some(self.ring.get_unchecked(idx)) }
1192         }
1193     }
1194 }
1195
1196 // FIXME This was implemented differently from Iter because of a problem
1197 //       with returning the mutable reference. I couldn't find a way to
1198 //       make the lifetime checker happy so, but there should be a way.
1199 /// `RingBuf` mutable iterator.
1200 #[stable]
1201 pub struct IterMut<'a, T:'a> {
1202     ptr: *mut T,
1203     tail: uint,
1204     head: uint,
1205     cap: uint,
1206     marker: marker::ContravariantLifetime<'a>,
1207 }
1208
1209 #[stable]
1210 impl<'a, T> Iterator for IterMut<'a, T> {
1211     type Item = &'a mut T;
1212
1213     #[inline]
1214     fn next(&mut self) -> Option<&'a mut T> {
1215         if self.tail == self.head {
1216             return None;
1217         }
1218         let tail = self.tail;
1219         self.tail = wrap_index(self.tail + 1, self.cap);
1220
1221         unsafe {
1222             Some(&mut *self.ptr.offset(tail as int))
1223         }
1224     }
1225
1226     #[inline]
1227     fn size_hint(&self) -> (uint, Option<uint>) {
1228         let len = count(self.tail, self.head, self.cap);
1229         (len, Some(len))
1230     }
1231 }
1232
1233 #[stable]
1234 impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
1235     #[inline]
1236     fn next_back(&mut self) -> Option<&'a mut T> {
1237         if self.tail == self.head {
1238             return None;
1239         }
1240         self.head = wrap_index(self.head - 1, self.cap);
1241
1242         unsafe {
1243             Some(&mut *self.ptr.offset(self.head as int))
1244         }
1245     }
1246 }
1247
1248 #[stable]
1249 impl<'a, T> ExactSizeIterator for IterMut<'a, T> {}
1250
1251 /// A by-value RingBuf iterator
1252 #[stable]
1253 pub struct IntoIter<T> {
1254     inner: RingBuf<T>,
1255 }
1256
1257 #[stable]
1258 impl<T> Iterator for IntoIter<T> {
1259     type Item = T;
1260
1261     #[inline]
1262     fn next(&mut self) -> Option<T> {
1263         self.inner.pop_front()
1264     }
1265
1266     #[inline]
1267     fn size_hint(&self) -> (uint, Option<uint>) {
1268         let len = self.inner.len();
1269         (len, Some(len))
1270     }
1271 }
1272
1273 #[stable]
1274 impl<T> DoubleEndedIterator for IntoIter<T> {
1275     #[inline]
1276     fn next_back(&mut self) -> Option<T> {
1277         self.inner.pop_back()
1278     }
1279 }
1280
1281 #[stable]
1282 impl<T> ExactSizeIterator for IntoIter<T> {}
1283
1284 /// A draining RingBuf iterator
1285 #[unstable = "matches collection reform specification, waiting for dust to settle"]
1286 pub struct Drain<'a, T: 'a> {
1287     inner: &'a mut RingBuf<T>,
1288 }
1289
1290 #[unsafe_destructor]
1291 #[stable]
1292 impl<'a, T: 'a> Drop for Drain<'a, T> {
1293     fn drop(&mut self) {
1294         for _ in *self {}
1295         self.inner.head = 0;
1296         self.inner.tail = 0;
1297     }
1298 }
1299
1300 #[stable]
1301 impl<'a, T: 'a> Iterator for Drain<'a, T> {
1302     type Item = T;
1303
1304     #[inline]
1305     fn next(&mut self) -> Option<T> {
1306         self.inner.pop_front()
1307     }
1308
1309     #[inline]
1310     fn size_hint(&self) -> (uint, Option<uint>) {
1311         let len = self.inner.len();
1312         (len, Some(len))
1313     }
1314 }
1315
1316 #[stable]
1317 impl<'a, T: 'a> DoubleEndedIterator for Drain<'a, T> {
1318     #[inline]
1319     fn next_back(&mut self) -> Option<T> {
1320         self.inner.pop_back()
1321     }
1322 }
1323
1324 #[stable]
1325 impl<'a, T: 'a> ExactSizeIterator for Drain<'a, T> {}
1326
1327 #[stable]
1328 impl<A: PartialEq> PartialEq for RingBuf<A> {
1329     fn eq(&self, other: &RingBuf<A>) -> bool {
1330         self.len() == other.len() &&
1331             self.iter().zip(other.iter()).all(|(a, b)| a.eq(b))
1332     }
1333 }
1334
1335 #[stable]
1336 impl<A: Eq> Eq for RingBuf<A> {}
1337
1338 #[stable]
1339 impl<A: PartialOrd> PartialOrd for RingBuf<A> {
1340     fn partial_cmp(&self, other: &RingBuf<A>) -> Option<Ordering> {
1341         iter::order::partial_cmp(self.iter(), other.iter())
1342     }
1343 }
1344
1345 #[stable]
1346 impl<A: Ord> Ord for RingBuf<A> {
1347     #[inline]
1348     fn cmp(&self, other: &RingBuf<A>) -> Ordering {
1349         iter::order::cmp(self.iter(), other.iter())
1350     }
1351 }
1352
1353 #[stable]
1354 impl<S: Writer, A: Hash<S>> Hash<S> for RingBuf<A> {
1355     fn hash(&self, state: &mut S) {
1356         self.len().hash(state);
1357         for elt in self.iter() {
1358             elt.hash(state);
1359         }
1360     }
1361 }
1362
1363 // NOTE(stage0): remove impl after a snapshot
1364 #[cfg(stage0)]
1365 #[stable]
1366 impl<A> Index<uint, A> for RingBuf<A> {
1367     #[inline]
1368     fn index<'a>(&'a self, i: &uint) -> &'a A {
1369         self.get(*i).expect("Out of bounds access")
1370     }
1371 }
1372
1373 #[cfg(not(stage0))]  // NOTE(stage0): remove cfg after a snapshot
1374 #[stable]
1375 impl<A> Index<uint> for RingBuf<A> {
1376     type Output = A;
1377
1378     #[inline]
1379     fn index<'a>(&'a self, i: &uint) -> &'a A {
1380         self.get(*i).expect("Out of bounds access")
1381     }
1382 }
1383
1384 // NOTE(stage0): remove impl after a snapshot
1385 #[cfg(stage0)]
1386 #[stable]
1387 impl<A> IndexMut<uint, A> for RingBuf<A> {
1388     #[inline]
1389     fn index_mut<'a>(&'a mut self, i: &uint) -> &'a mut A {
1390         self.get_mut(*i).expect("Out of bounds access")
1391     }
1392 }
1393
1394 #[cfg(not(stage0))]  // NOTE(stage0): remove cfg after a snapshot
1395 #[stable]
1396 impl<A> IndexMut<uint> for RingBuf<A> {
1397     type Output = A;
1398
1399     #[inline]
1400     fn index_mut<'a>(&'a mut self, i: &uint) -> &'a mut A {
1401         self.get_mut(*i).expect("Out of bounds access")
1402     }
1403 }
1404
1405 #[stable]
1406 impl<A> FromIterator<A> for RingBuf<A> {
1407     fn from_iter<T: Iterator<Item=A>>(iterator: T) -> RingBuf<A> {
1408         let (lower, _) = iterator.size_hint();
1409         let mut deq = RingBuf::with_capacity(lower);
1410         deq.extend(iterator);
1411         deq
1412     }
1413 }
1414
1415 #[stable]
1416 impl<A> Extend<A> for RingBuf<A> {
1417     fn extend<T: Iterator<Item=A>>(&mut self, mut iterator: T) {
1418         for elt in iterator {
1419             self.push_back(elt);
1420         }
1421     }
1422 }
1423
1424 #[stable]
1425 impl<T: fmt::Show> fmt::Show for RingBuf<T> {
1426     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1427         try!(write!(f, "["));
1428
1429         for (i, e) in self.iter().enumerate() {
1430             if i != 0 { try!(write!(f, ", ")); }
1431             try!(write!(f, "{}", *e));
1432         }
1433
1434         write!(f, "]")
1435     }
1436 }
1437
1438 #[cfg(test)]
1439 mod tests {
1440     use self::Taggy::*;
1441     use self::Taggypar::*;
1442     use prelude::*;
1443     use core::iter;
1444     use std::fmt::Show;
1445     use std::hash;
1446     use test::Bencher;
1447     use test;
1448
1449     use super::RingBuf;
1450
1451     #[test]
1452     #[allow(deprecated)]
1453     fn test_simple() {
1454         let mut d = RingBuf::new();
1455         assert_eq!(d.len(), 0u);
1456         d.push_front(17i);
1457         d.push_front(42i);
1458         d.push_back(137);
1459         assert_eq!(d.len(), 3u);
1460         d.push_back(137);
1461         assert_eq!(d.len(), 4u);
1462         debug!("{}", d.front());
1463         assert_eq!(*d.front().unwrap(), 42);
1464         debug!("{}", d.back());
1465         assert_eq!(*d.back().unwrap(), 137);
1466         let mut i = d.pop_front();
1467         debug!("{}", i);
1468         assert_eq!(i, Some(42));
1469         i = d.pop_back();
1470         debug!("{}", i);
1471         assert_eq!(i, Some(137));
1472         i = d.pop_back();
1473         debug!("{}", i);
1474         assert_eq!(i, Some(137));
1475         i = d.pop_back();
1476         debug!("{}", i);
1477         assert_eq!(i, Some(17));
1478         assert_eq!(d.len(), 0u);
1479         d.push_back(3);
1480         assert_eq!(d.len(), 1u);
1481         d.push_front(2);
1482         assert_eq!(d.len(), 2u);
1483         d.push_back(4);
1484         assert_eq!(d.len(), 3u);
1485         d.push_front(1);
1486         assert_eq!(d.len(), 4u);
1487         debug!("{}", d[0]);
1488         debug!("{}", d[1]);
1489         debug!("{}", d[2]);
1490         debug!("{}", d[3]);
1491         assert_eq!(d[0], 1);
1492         assert_eq!(d[1], 2);
1493         assert_eq!(d[2], 3);
1494         assert_eq!(d[3], 4);
1495     }
1496
1497     #[cfg(test)]
1498     fn test_parameterized<T:Clone + PartialEq + Show>(a: T, b: T, c: T, d: T) {
1499         let mut deq = RingBuf::new();
1500         assert_eq!(deq.len(), 0);
1501         deq.push_front(a.clone());
1502         deq.push_front(b.clone());
1503         deq.push_back(c.clone());
1504         assert_eq!(deq.len(), 3);
1505         deq.push_back(d.clone());
1506         assert_eq!(deq.len(), 4);
1507         assert_eq!((*deq.front().unwrap()).clone(), b.clone());
1508         assert_eq!((*deq.back().unwrap()).clone(), d.clone());
1509         assert_eq!(deq.pop_front().unwrap(), b.clone());
1510         assert_eq!(deq.pop_back().unwrap(), d.clone());
1511         assert_eq!(deq.pop_back().unwrap(), c.clone());
1512         assert_eq!(deq.pop_back().unwrap(), a.clone());
1513         assert_eq!(deq.len(), 0);
1514         deq.push_back(c.clone());
1515         assert_eq!(deq.len(), 1);
1516         deq.push_front(b.clone());
1517         assert_eq!(deq.len(), 2);
1518         deq.push_back(d.clone());
1519         assert_eq!(deq.len(), 3);
1520         deq.push_front(a.clone());
1521         assert_eq!(deq.len(), 4);
1522         assert_eq!(deq[0].clone(), a.clone());
1523         assert_eq!(deq[1].clone(), b.clone());
1524         assert_eq!(deq[2].clone(), c.clone());
1525         assert_eq!(deq[3].clone(), d.clone());
1526     }
1527
1528     #[test]
1529     fn test_push_front_grow() {
1530         let mut deq = RingBuf::new();
1531         for i in range(0u, 66) {
1532             deq.push_front(i);
1533         }
1534         assert_eq!(deq.len(), 66);
1535
1536         for i in range(0u, 66) {
1537             assert_eq!(deq[i], 65 - i);
1538         }
1539
1540         let mut deq = RingBuf::new();
1541         for i in range(0u, 66) {
1542             deq.push_back(i);
1543         }
1544
1545         for i in range(0u, 66) {
1546             assert_eq!(deq[i], i);
1547         }
1548     }
1549
1550     #[test]
1551     fn test_index() {
1552         let mut deq = RingBuf::new();
1553         for i in range(1u, 4) {
1554             deq.push_front(i);
1555         }
1556         assert_eq!(deq[1], 2);
1557     }
1558
1559     #[test]
1560     #[should_fail]
1561     fn test_index_out_of_bounds() {
1562         let mut deq = RingBuf::new();
1563         for i in range(1u, 4) {
1564             deq.push_front(i);
1565         }
1566         deq[3];
1567     }
1568
1569     #[bench]
1570     fn bench_new(b: &mut test::Bencher) {
1571         b.iter(|| {
1572             let ring: RingBuf<u64> = RingBuf::new();
1573             test::black_box(ring);
1574         })
1575     }
1576
1577     #[bench]
1578     fn bench_push_back_100(b: &mut test::Bencher) {
1579         let mut deq = RingBuf::with_capacity(101);
1580         b.iter(|| {
1581             for i in range(0i, 100) {
1582                 deq.push_back(i);
1583             }
1584             deq.head = 0;
1585             deq.tail = 0;
1586         })
1587     }
1588
1589     #[bench]
1590     fn bench_push_front_100(b: &mut test::Bencher) {
1591         let mut deq = RingBuf::with_capacity(101);
1592         b.iter(|| {
1593             for i in range(0i, 100) {
1594                 deq.push_front(i);
1595             }
1596             deq.head = 0;
1597             deq.tail = 0;
1598         })
1599     }
1600
1601     #[bench]
1602     fn bench_pop_back_100(b: &mut test::Bencher) {
1603         let mut deq: RingBuf<int> = RingBuf::with_capacity(101);
1604
1605         b.iter(|| {
1606             deq.head = 100;
1607             deq.tail = 0;
1608             while !deq.is_empty() {
1609                 test::black_box(deq.pop_back());
1610             }
1611         })
1612     }
1613
1614     #[bench]
1615     fn bench_pop_front_100(b: &mut test::Bencher) {
1616         let mut deq: RingBuf<int> = RingBuf::with_capacity(101);
1617
1618         b.iter(|| {
1619             deq.head = 100;
1620             deq.tail = 0;
1621             while !deq.is_empty() {
1622                 test::black_box(deq.pop_front());
1623             }
1624         })
1625     }
1626
1627     #[bench]
1628     fn bench_grow_1025(b: &mut test::Bencher) {
1629         b.iter(|| {
1630             let mut deq = RingBuf::new();
1631             for i in range(0i, 1025) {
1632                 deq.push_front(i);
1633             }
1634             test::black_box(deq);
1635         })
1636     }
1637
1638     #[bench]
1639     fn bench_iter_1000(b: &mut test::Bencher) {
1640         let ring: RingBuf<int> = range(0i, 1000).collect();
1641
1642         b.iter(|| {
1643             let mut sum = 0;
1644             for &i in ring.iter() {
1645                 sum += i;
1646             }
1647             test::black_box(sum);
1648         })
1649     }
1650
1651     #[bench]
1652     fn bench_mut_iter_1000(b: &mut test::Bencher) {
1653         let mut ring: RingBuf<int> = range(0i, 1000).collect();
1654
1655         b.iter(|| {
1656             let mut sum = 0;
1657             for i in ring.iter_mut() {
1658                 sum += *i;
1659             }
1660             test::black_box(sum);
1661         })
1662     }
1663
1664     #[derive(Clone, PartialEq, Show)]
1665     enum Taggy {
1666         One(int),
1667         Two(int, int),
1668         Three(int, int, int),
1669     }
1670
1671     #[derive(Clone, PartialEq, Show)]
1672     enum Taggypar<T> {
1673         Onepar(int),
1674         Twopar(int, int),
1675         Threepar(int, int, int),
1676     }
1677
1678     #[derive(Clone, PartialEq, Show)]
1679     struct RecCy {
1680         x: int,
1681         y: int,
1682         t: Taggy
1683     }
1684
1685     #[test]
1686     fn test_param_int() {
1687         test_parameterized::<int>(5, 72, 64, 175);
1688     }
1689
1690     #[test]
1691     fn test_param_taggy() {
1692         test_parameterized::<Taggy>(One(1), Two(1, 2), Three(1, 2, 3), Two(17, 42));
1693     }
1694
1695     #[test]
1696     fn test_param_taggypar() {
1697         test_parameterized::<Taggypar<int>>(Onepar::<int>(1),
1698                                             Twopar::<int>(1, 2),
1699                                             Threepar::<int>(1, 2, 3),
1700                                             Twopar::<int>(17, 42));
1701     }
1702
1703     #[test]
1704     fn test_param_reccy() {
1705         let reccy1 = RecCy { x: 1, y: 2, t: One(1) };
1706         let reccy2 = RecCy { x: 345, y: 2, t: Two(1, 2) };
1707         let reccy3 = RecCy { x: 1, y: 777, t: Three(1, 2, 3) };
1708         let reccy4 = RecCy { x: 19, y: 252, t: Two(17, 42) };
1709         test_parameterized::<RecCy>(reccy1, reccy2, reccy3, reccy4);
1710     }
1711
1712     #[test]
1713     fn test_with_capacity() {
1714         let mut d = RingBuf::with_capacity(0);
1715         d.push_back(1i);
1716         assert_eq!(d.len(), 1);
1717         let mut d = RingBuf::with_capacity(50);
1718         d.push_back(1i);
1719         assert_eq!(d.len(), 1);
1720     }
1721
1722     #[test]
1723     fn test_with_capacity_non_power_two() {
1724         let mut d3 = RingBuf::with_capacity(3);
1725         d3.push_back(1i);
1726
1727         // X = None, | = lo
1728         // [|1, X, X]
1729         assert_eq!(d3.pop_front(), Some(1));
1730         // [X, |X, X]
1731         assert_eq!(d3.front(), None);
1732
1733         // [X, |3, X]
1734         d3.push_back(3);
1735         // [X, |3, 6]
1736         d3.push_back(6);
1737         // [X, X, |6]
1738         assert_eq!(d3.pop_front(), Some(3));
1739
1740         // Pushing the lo past half way point to trigger
1741         // the 'B' scenario for growth
1742         // [9, X, |6]
1743         d3.push_back(9);
1744         // [9, 12, |6]
1745         d3.push_back(12);
1746
1747         d3.push_back(15);
1748         // There used to be a bug here about how the
1749         // RingBuf made growth assumptions about the
1750         // underlying Vec which didn't hold and lead
1751         // to corruption.
1752         // (Vec grows to next power of two)
1753         //good- [9, 12, 15, X, X, X, X, |6]
1754         //bug-  [15, 12, X, X, X, |6, X, X]
1755         assert_eq!(d3.pop_front(), Some(6));
1756
1757         // Which leads us to the following state which
1758         // would be a failure case.
1759         //bug-  [15, 12, X, X, X, X, |X, X]
1760         assert_eq!(d3.front(), Some(&9));
1761     }
1762
1763     #[test]
1764     fn test_reserve_exact() {
1765         let mut d = RingBuf::new();
1766         d.push_back(0u64);
1767         d.reserve_exact(50);
1768         assert!(d.capacity() >= 51);
1769         let mut d = RingBuf::new();
1770         d.push_back(0u32);
1771         d.reserve_exact(50);
1772         assert!(d.capacity() >= 51);
1773     }
1774
1775     #[test]
1776     fn test_reserve() {
1777         let mut d = RingBuf::new();
1778         d.push_back(0u64);
1779         d.reserve(50);
1780         assert!(d.capacity() >= 51);
1781         let mut d = RingBuf::new();
1782         d.push_back(0u32);
1783         d.reserve(50);
1784         assert!(d.capacity() >= 51);
1785     }
1786
1787     #[test]
1788     fn test_swap() {
1789         let mut d: RingBuf<int> = range(0i, 5).collect();
1790         d.pop_front();
1791         d.swap(0, 3);
1792         assert_eq!(d.iter().map(|&x|x).collect::<Vec<int>>(), vec!(4, 2, 3, 1));
1793     }
1794
1795     #[test]
1796     fn test_iter() {
1797         let mut d = RingBuf::new();
1798         assert_eq!(d.iter().next(), None);
1799         assert_eq!(d.iter().size_hint(), (0, Some(0)));
1800
1801         for i in range(0i, 5) {
1802             d.push_back(i);
1803         }
1804         {
1805             let b: &[_] = &[&0,&1,&2,&3,&4];
1806             assert_eq!(d.iter().collect::<Vec<&int>>(), b);
1807         }
1808
1809         for i in range(6i, 9) {
1810             d.push_front(i);
1811         }
1812         {
1813             let b: &[_] = &[&8,&7,&6,&0,&1,&2,&3,&4];
1814             assert_eq!(d.iter().collect::<Vec<&int>>(), b);
1815         }
1816
1817         let mut it = d.iter();
1818         let mut len = d.len();
1819         loop {
1820             match it.next() {
1821                 None => break,
1822                 _ => { len -= 1; assert_eq!(it.size_hint(), (len, Some(len))) }
1823             }
1824         }
1825     }
1826
1827     #[test]
1828     fn test_rev_iter() {
1829         let mut d = RingBuf::new();
1830         assert_eq!(d.iter().rev().next(), None);
1831
1832         for i in range(0i, 5) {
1833             d.push_back(i);
1834         }
1835         {
1836             let b: &[_] = &[&4,&3,&2,&1,&0];
1837             assert_eq!(d.iter().rev().collect::<Vec<&int>>(), b);
1838         }
1839
1840         for i in range(6i, 9) {
1841             d.push_front(i);
1842         }
1843         let b: &[_] = &[&4,&3,&2,&1,&0,&6,&7,&8];
1844         assert_eq!(d.iter().rev().collect::<Vec<&int>>(), b);
1845     }
1846
1847     #[test]
1848     fn test_mut_rev_iter_wrap() {
1849         let mut d = RingBuf::with_capacity(3);
1850         assert!(d.iter_mut().rev().next().is_none());
1851
1852         d.push_back(1i);
1853         d.push_back(2);
1854         d.push_back(3);
1855         assert_eq!(d.pop_front(), Some(1));
1856         d.push_back(4);
1857
1858         assert_eq!(d.iter_mut().rev().map(|x| *x).collect::<Vec<int>>(),
1859                    vec!(4, 3, 2));
1860     }
1861
1862     #[test]
1863     fn test_mut_iter() {
1864         let mut d = RingBuf::new();
1865         assert!(d.iter_mut().next().is_none());
1866
1867         for i in range(0u, 3) {
1868             d.push_front(i);
1869         }
1870
1871         for (i, elt) in d.iter_mut().enumerate() {
1872             assert_eq!(*elt, 2 - i);
1873             *elt = i;
1874         }
1875
1876         {
1877             let mut it = d.iter_mut();
1878             assert_eq!(*it.next().unwrap(), 0);
1879             assert_eq!(*it.next().unwrap(), 1);
1880             assert_eq!(*it.next().unwrap(), 2);
1881             assert!(it.next().is_none());
1882         }
1883     }
1884
1885     #[test]
1886     fn test_mut_rev_iter() {
1887         let mut d = RingBuf::new();
1888         assert!(d.iter_mut().rev().next().is_none());
1889
1890         for i in range(0u, 3) {
1891             d.push_front(i);
1892         }
1893
1894         for (i, elt) in d.iter_mut().rev().enumerate() {
1895             assert_eq!(*elt, i);
1896             *elt = i;
1897         }
1898
1899         {
1900             let mut it = d.iter_mut().rev();
1901             assert_eq!(*it.next().unwrap(), 0);
1902             assert_eq!(*it.next().unwrap(), 1);
1903             assert_eq!(*it.next().unwrap(), 2);
1904             assert!(it.next().is_none());
1905         }
1906     }
1907
1908     #[test]
1909     fn test_into_iter() {
1910
1911         // Empty iter
1912         {
1913             let d: RingBuf<int> = RingBuf::new();
1914             let mut iter = d.into_iter();
1915
1916             assert_eq!(iter.size_hint(), (0, Some(0)));
1917             assert_eq!(iter.next(), None);
1918             assert_eq!(iter.size_hint(), (0, Some(0)));
1919         }
1920
1921         // simple iter
1922         {
1923             let mut d = RingBuf::new();
1924             for i in range(0i, 5) {
1925                 d.push_back(i);
1926             }
1927
1928             let b = vec![0,1,2,3,4];
1929             assert_eq!(d.into_iter().collect::<Vec<int>>(), b);
1930         }
1931
1932         // wrapped iter
1933         {
1934             let mut d = RingBuf::new();
1935             for i in range(0i, 5) {
1936                 d.push_back(i);
1937             }
1938             for i in range(6, 9) {
1939                 d.push_front(i);
1940             }
1941
1942             let b = vec![8,7,6,0,1,2,3,4];
1943             assert_eq!(d.into_iter().collect::<Vec<int>>(), b);
1944         }
1945
1946         // partially used
1947         {
1948             let mut d = RingBuf::new();
1949             for i in range(0i, 5) {
1950                 d.push_back(i);
1951             }
1952             for i in range(6, 9) {
1953                 d.push_front(i);
1954             }
1955
1956             let mut it = d.into_iter();
1957             assert_eq!(it.size_hint(), (8, Some(8)));
1958             assert_eq!(it.next(), Some(8));
1959             assert_eq!(it.size_hint(), (7, Some(7)));
1960             assert_eq!(it.next_back(), Some(4));
1961             assert_eq!(it.size_hint(), (6, Some(6)));
1962             assert_eq!(it.next(), Some(7));
1963             assert_eq!(it.size_hint(), (5, Some(5)));
1964         }
1965     }
1966
1967     #[test]
1968     fn test_drain() {
1969
1970         // Empty iter
1971         {
1972             let mut d: RingBuf<int> = RingBuf::new();
1973
1974             {
1975                 let mut iter = d.drain();
1976
1977                 assert_eq!(iter.size_hint(), (0, Some(0)));
1978                 assert_eq!(iter.next(), None);
1979                 assert_eq!(iter.size_hint(), (0, Some(0)));
1980             }
1981
1982             assert!(d.is_empty());
1983         }
1984
1985         // simple iter
1986         {
1987             let mut d = RingBuf::new();
1988             for i in range(0i, 5) {
1989                 d.push_back(i);
1990             }
1991
1992             assert_eq!(d.drain().collect::<Vec<int>>(), [0, 1, 2, 3, 4]);
1993             assert!(d.is_empty());
1994         }
1995
1996         // wrapped iter
1997         {
1998             let mut d = RingBuf::new();
1999             for i in range(0i, 5) {
2000                 d.push_back(i);
2001             }
2002             for i in range(6, 9) {
2003                 d.push_front(i);
2004             }
2005
2006             assert_eq!(d.drain().collect::<Vec<int>>(), [8,7,6,0,1,2,3,4]);
2007             assert!(d.is_empty());
2008         }
2009
2010         // partially used
2011         {
2012             let mut d = RingBuf::new();
2013             for i in range(0i, 5) {
2014                 d.push_back(i);
2015             }
2016             for i in range(6, 9) {
2017                 d.push_front(i);
2018             }
2019
2020             {
2021                 let mut it = d.drain();
2022                 assert_eq!(it.size_hint(), (8, Some(8)));
2023                 assert_eq!(it.next(), Some(8));
2024                 assert_eq!(it.size_hint(), (7, Some(7)));
2025                 assert_eq!(it.next_back(), Some(4));
2026                 assert_eq!(it.size_hint(), (6, Some(6)));
2027                 assert_eq!(it.next(), Some(7));
2028                 assert_eq!(it.size_hint(), (5, Some(5)));
2029             }
2030             assert!(d.is_empty());
2031         }
2032     }
2033
2034     #[test]
2035     fn test_from_iter() {
2036         use core::iter;
2037         let v = vec!(1i,2,3,4,5,6,7);
2038         let deq: RingBuf<int> = v.iter().map(|&x| x).collect();
2039         let u: Vec<int> = deq.iter().map(|&x| x).collect();
2040         assert_eq!(u, v);
2041
2042         let seq = iter::count(0u, 2).take(256);
2043         let deq: RingBuf<uint> = seq.collect();
2044         for (i, &x) in deq.iter().enumerate() {
2045             assert_eq!(2*i, x);
2046         }
2047         assert_eq!(deq.len(), 256);
2048     }
2049
2050     #[test]
2051     fn test_clone() {
2052         let mut d = RingBuf::new();
2053         d.push_front(17i);
2054         d.push_front(42);
2055         d.push_back(137);
2056         d.push_back(137);
2057         assert_eq!(d.len(), 4u);
2058         let mut e = d.clone();
2059         assert_eq!(e.len(), 4u);
2060         while !d.is_empty() {
2061             assert_eq!(d.pop_back(), e.pop_back());
2062         }
2063         assert_eq!(d.len(), 0u);
2064         assert_eq!(e.len(), 0u);
2065     }
2066
2067     #[test]
2068     fn test_eq() {
2069         let mut d = RingBuf::new();
2070         assert!(d == RingBuf::with_capacity(0));
2071         d.push_front(137i);
2072         d.push_front(17);
2073         d.push_front(42);
2074         d.push_back(137);
2075         let mut e = RingBuf::with_capacity(0);
2076         e.push_back(42);
2077         e.push_back(17);
2078         e.push_back(137);
2079         e.push_back(137);
2080         assert!(&e == &d);
2081         e.pop_back();
2082         e.push_back(0);
2083         assert!(e != d);
2084         e.clear();
2085         assert!(e == RingBuf::new());
2086     }
2087
2088     #[test]
2089     fn test_hash() {
2090       let mut x = RingBuf::new();
2091       let mut y = RingBuf::new();
2092
2093       x.push_back(1i);
2094       x.push_back(2);
2095       x.push_back(3);
2096
2097       y.push_back(0i);
2098       y.push_back(1i);
2099       y.pop_front();
2100       y.push_back(2);
2101       y.push_back(3);
2102
2103       assert!(hash::hash(&x) == hash::hash(&y));
2104     }
2105
2106     #[test]
2107     fn test_ord() {
2108         let x = RingBuf::new();
2109         let mut y = RingBuf::new();
2110         y.push_back(1i);
2111         y.push_back(2);
2112         y.push_back(3);
2113         assert!(x < y);
2114         assert!(y > x);
2115         assert!(x <= x);
2116         assert!(x >= x);
2117     }
2118
2119     #[test]
2120     fn test_show() {
2121         let ringbuf: RingBuf<int> = range(0i, 10).collect();
2122         assert!(format!("{}", ringbuf) == "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]");
2123
2124         let ringbuf: RingBuf<&str> = vec!["just", "one", "test", "more"].iter()
2125                                                                         .map(|&s| s)
2126                                                                         .collect();
2127         assert!(format!("{}", ringbuf) == "[just, one, test, more]");
2128     }
2129
2130     #[test]
2131     fn test_drop() {
2132         static mut drops: uint = 0;
2133         struct Elem;
2134         impl Drop for Elem {
2135             fn drop(&mut self) {
2136                 unsafe { drops += 1; }
2137             }
2138         }
2139
2140         let mut ring = RingBuf::new();
2141         ring.push_back(Elem);
2142         ring.push_front(Elem);
2143         ring.push_back(Elem);
2144         ring.push_front(Elem);
2145         drop(ring);
2146
2147         assert_eq!(unsafe {drops}, 4);
2148     }
2149
2150     #[test]
2151     fn test_drop_with_pop() {
2152         static mut drops: uint = 0;
2153         struct Elem;
2154         impl Drop for Elem {
2155             fn drop(&mut self) {
2156                 unsafe { drops += 1; }
2157             }
2158         }
2159
2160         let mut ring = RingBuf::new();
2161         ring.push_back(Elem);
2162         ring.push_front(Elem);
2163         ring.push_back(Elem);
2164         ring.push_front(Elem);
2165
2166         drop(ring.pop_back());
2167         drop(ring.pop_front());
2168         assert_eq!(unsafe {drops}, 2);
2169
2170         drop(ring);
2171         assert_eq!(unsafe {drops}, 4);
2172     }
2173
2174     #[test]
2175     fn test_drop_clear() {
2176         static mut drops: uint = 0;
2177         struct Elem;
2178         impl Drop for Elem {
2179             fn drop(&mut self) {
2180                 unsafe { drops += 1; }
2181             }
2182         }
2183
2184         let mut ring = RingBuf::new();
2185         ring.push_back(Elem);
2186         ring.push_front(Elem);
2187         ring.push_back(Elem);
2188         ring.push_front(Elem);
2189         ring.clear();
2190         assert_eq!(unsafe {drops}, 4);
2191
2192         drop(ring);
2193         assert_eq!(unsafe {drops}, 4);
2194     }
2195
2196     #[test]
2197     fn test_reserve_grow() {
2198         // test growth path A
2199         // [T o o H] -> [T o o H . . . . ]
2200         let mut ring = RingBuf::with_capacity(4);
2201         for i in range(0i, 3) {
2202             ring.push_back(i);
2203         }
2204         ring.reserve(7);
2205         for i in range(0i, 3) {
2206             assert_eq!(ring.pop_front(), Some(i));
2207         }
2208
2209         // test growth path B
2210         // [H T o o] -> [. T o o H . . . ]
2211         let mut ring = RingBuf::with_capacity(4);
2212         for i in range(0i, 1) {
2213             ring.push_back(i);
2214             assert_eq!(ring.pop_front(), Some(i));
2215         }
2216         for i in range(0i, 3) {
2217             ring.push_back(i);
2218         }
2219         ring.reserve(7);
2220         for i in range(0i, 3) {
2221             assert_eq!(ring.pop_front(), Some(i));
2222         }
2223
2224         // test growth path C
2225         // [o o H T] -> [o o H . . . . T ]
2226         let mut ring = RingBuf::with_capacity(4);
2227         for i in range(0i, 3) {
2228             ring.push_back(i);
2229             assert_eq!(ring.pop_front(), Some(i));
2230         }
2231         for i in range(0i, 3) {
2232             ring.push_back(i);
2233         }
2234         ring.reserve(7);
2235         for i in range(0i, 3) {
2236             assert_eq!(ring.pop_front(), Some(i));
2237         }
2238     }
2239
2240     #[test]
2241     fn test_get() {
2242         let mut ring = RingBuf::new();
2243         ring.push_back(0i);
2244         assert_eq!(ring.get(0), Some(&0));
2245         assert_eq!(ring.get(1), None);
2246
2247         ring.push_back(1);
2248         assert_eq!(ring.get(0), Some(&0));
2249         assert_eq!(ring.get(1), Some(&1));
2250         assert_eq!(ring.get(2), None);
2251
2252         ring.push_back(2);
2253         assert_eq!(ring.get(0), Some(&0));
2254         assert_eq!(ring.get(1), Some(&1));
2255         assert_eq!(ring.get(2), Some(&2));
2256         assert_eq!(ring.get(3), None);
2257
2258         assert_eq!(ring.pop_front(), Some(0));
2259         assert_eq!(ring.get(0), Some(&1));
2260         assert_eq!(ring.get(1), Some(&2));
2261         assert_eq!(ring.get(2), None);
2262
2263         assert_eq!(ring.pop_front(), Some(1));
2264         assert_eq!(ring.get(0), Some(&2));
2265         assert_eq!(ring.get(1), None);
2266
2267         assert_eq!(ring.pop_front(), Some(2));
2268         assert_eq!(ring.get(0), None);
2269         assert_eq!(ring.get(1), None);
2270     }
2271
2272     #[test]
2273     fn test_get_mut() {
2274         let mut ring = RingBuf::new();
2275         for i in range(0i, 3) {
2276             ring.push_back(i);
2277         }
2278
2279         match ring.get_mut(1) {
2280             Some(x) => *x = -1,
2281             None => ()
2282         };
2283
2284         assert_eq!(ring.get_mut(0), Some(&mut 0));
2285         assert_eq!(ring.get_mut(1), Some(&mut -1));
2286         assert_eq!(ring.get_mut(2), Some(&mut 2));
2287         assert_eq!(ring.get_mut(3), None);
2288
2289         assert_eq!(ring.pop_front(), Some(0));
2290         assert_eq!(ring.get_mut(0), Some(&mut -1));
2291         assert_eq!(ring.get_mut(1), Some(&mut 2));
2292         assert_eq!(ring.get_mut(2), None);
2293     }
2294
2295     #[test]
2296     fn test_insert() {
2297         // This test checks that every single combination of tail position, length, and
2298         // insertion position is tested. Capacity 15 should be large enough to cover every case.
2299
2300         let mut tester = RingBuf::with_capacity(15);
2301         // can't guarantee we got 15, so have to get what we got.
2302         // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2303         // this test isn't covering what it wants to
2304         let cap = tester.capacity();
2305
2306
2307         // len is the length *after* insertion
2308         for len in range(1, cap) {
2309             // 0, 1, 2, .., len - 1
2310             let expected = iter::count(0, 1).take(len).collect();
2311             for tail_pos in range(0, cap) {
2312                 for to_insert in range(0, len) {
2313                     tester.tail = tail_pos;
2314                     tester.head = tail_pos;
2315                     for i in range(0, len) {
2316                         if i != to_insert {
2317                             tester.push_back(i);
2318                         }
2319                     }
2320                     tester.insert(to_insert, to_insert);
2321                     assert!(tester.tail < tester.cap);
2322                     assert!(tester.head < tester.cap);
2323                     assert_eq!(tester, expected);
2324                 }
2325             }
2326         }
2327     }
2328
2329     #[test]
2330     fn test_remove() {
2331         // This test checks that every single combination of tail position, length, and
2332         // removal position is tested. Capacity 15 should be large enough to cover every case.
2333
2334         let mut tester = RingBuf::with_capacity(15);
2335         // can't guarantee we got 15, so have to get what we got.
2336         // 15 would be great, but we will definitely get 2^k - 1, for k >= 4, or else
2337         // this test isn't covering what it wants to
2338         let cap = tester.capacity();
2339
2340         // len is the length *after* removal
2341         for len in range(0, cap - 1) {
2342             // 0, 1, 2, .., len - 1
2343             let expected = iter::count(0, 1).take(len).collect();
2344             for tail_pos in range(0, cap) {
2345                 for to_remove in range(0, len + 1) {
2346                     tester.tail = tail_pos;
2347                     tester.head = tail_pos;
2348                     for i in range(0, len) {
2349                         if i == to_remove {
2350                             tester.push_back(1234);
2351                         }
2352                         tester.push_back(i);
2353                     }
2354                     if to_remove == len {
2355                         tester.push_back(1234);
2356                     }
2357                     tester.remove(to_remove);
2358                     assert!(tester.tail < tester.cap);
2359                     assert!(tester.head < tester.cap);
2360                     assert_eq!(tester, expected);
2361                 }
2362             }
2363         }
2364     }
2365
2366     #[test]
2367     fn test_front() {
2368         let mut ring = RingBuf::new();
2369         ring.push_back(10i);
2370         ring.push_back(20i);
2371         assert_eq!(ring.front(), Some(&10));
2372         ring.pop_front();
2373         assert_eq!(ring.front(), Some(&20));
2374         ring.pop_front();
2375         assert_eq!(ring.front(), None);
2376     }
2377
2378     #[test]
2379     fn test_as_slices() {
2380         let mut ring: RingBuf<int> = RingBuf::with_capacity(127);
2381         let cap = ring.capacity() as int;
2382         let first = cap/2;
2383         let last  = cap - first;
2384         for i in range(0, first) {
2385             ring.push_back(i);
2386
2387             let (left, right) = ring.as_slices();
2388             let expected: Vec<_> = range(0, i+1).collect();
2389             assert_eq!(left, expected);
2390             assert_eq!(right, []);
2391         }
2392
2393         for j in range(-last, 0) {
2394             ring.push_front(j);
2395             let (left, right) = ring.as_slices();
2396             let expected_left: Vec<_> = range(-last, j+1).rev().collect();
2397             let expected_right: Vec<_> = range(0, first).collect();
2398             assert_eq!(left, expected_left);
2399             assert_eq!(right, expected_right);
2400         }
2401
2402         assert_eq!(ring.len() as int, cap);
2403         assert_eq!(ring.capacity() as int, cap);
2404     }
2405
2406     #[test]
2407     fn test_as_mut_slices() {
2408         let mut ring: RingBuf<int> = RingBuf::with_capacity(127);
2409         let cap = ring.capacity() as int;
2410         let first = cap/2;
2411         let last  = cap - first;
2412         for i in range(0, first) {
2413             ring.push_back(i);
2414
2415             let (left, right) = ring.as_mut_slices();
2416             let expected: Vec<_> = range(0, i+1).collect();
2417             assert_eq!(left, expected);
2418             assert_eq!(right, []);
2419         }
2420
2421         for j in range(-last, 0) {
2422             ring.push_front(j);
2423             let (left, right) = ring.as_mut_slices();
2424             let expected_left: Vec<_> = range(-last, j+1).rev().collect();
2425             let expected_right: Vec<_> = range(0, first).collect();
2426             assert_eq!(left, expected_left);
2427             assert_eq!(right, expected_right);
2428         }
2429
2430         assert_eq!(ring.len() as int, cap);
2431         assert_eq!(ring.capacity() as int, cap);
2432     }
2433 }