1 // Copyright 2012-2013 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 //! A double-ended queue implemented as a circular buffer
13 //! RingBuf implements the trait Deque. It should be imported with `use
14 //! collections::deque::Deque`.
17 use std::iter::{Rev, RandomAccessIterator};
21 static INITIAL_CAPACITY: uint = 8u; // 2^3
22 static MINIMUM_CAPACITY: uint = 2u;
24 /// RingBuf is a circular buffer that implements Deque.
26 pub struct RingBuf<T> {
32 impl<T> Container for RingBuf<T> {
33 /// Return the number of elements in the RingBuf
34 fn len(&self) -> uint { self.nelts }
37 impl<T> Mutable for RingBuf<T> {
38 /// Clear the RingBuf, removing all values.
40 for x in self.elts.mut_iter() { *x = None }
46 impl<T> Deque<T> for RingBuf<T> {
47 /// Return a reference to the first element in the RingBuf
48 fn front<'a>(&'a self) -> Option<&'a T> {
49 if self.nelts > 0 { Some(self.get(0)) } else { None }
52 /// Return a mutable reference to the first element in the RingBuf
53 fn front_mut<'a>(&'a mut self) -> Option<&'a mut T> {
54 if self.nelts > 0 { Some(self.get_mut(0)) } else { None }
57 /// Return a reference to the last element in the RingBuf
58 fn back<'a>(&'a self) -> Option<&'a T> {
59 if self.nelts > 0 { Some(self.get(self.nelts - 1)) } else { None }
62 /// Return a mutable reference to the last element in the RingBuf
63 fn back_mut<'a>(&'a mut self) -> Option<&'a mut T> {
64 if self.nelts > 0 { Some(self.get_mut(self.nelts - 1)) } else { None }
67 /// Remove and return the first element in the RingBuf, or None if it is empty
68 fn pop_front(&mut self) -> Option<T> {
69 let result = self.elts.get_mut(self.lo).take();
71 self.lo = (self.lo + 1u) % self.elts.len();
77 /// Remove and return the last element in the RingBuf, or None if it is empty
78 fn pop_back(&mut self) -> Option<T> {
81 let hi = self.raw_index(self.nelts);
82 self.elts.get_mut(hi).take()
88 /// Prepend an element to the RingBuf
89 fn push_front(&mut self, t: T) {
90 if self.nelts == self.elts.len() {
91 grow(self.nelts, &mut self.lo, &mut self.elts);
94 self.lo = self.elts.len() - 1u;
95 } else { self.lo -= 1u; }
96 *self.elts.get_mut(self.lo) = Some(t);
100 /// Append an element to the RingBuf
101 fn push_back(&mut self, t: T) {
102 if self.nelts == self.elts.len() {
103 grow(self.nelts, &mut self.lo, &mut self.elts);
105 let hi = self.raw_index(self.nelts);
106 *self.elts.get_mut(hi) = Some(t);
112 /// Create an empty RingBuf
113 pub fn new() -> RingBuf<T> {
114 RingBuf::with_capacity(INITIAL_CAPACITY)
117 /// Create an empty RingBuf with space for at least `n` elements.
118 pub fn with_capacity(n: uint) -> RingBuf<T> {
119 RingBuf{nelts: 0, lo: 0,
120 elts: Vec::from_fn(cmp::max(MINIMUM_CAPACITY, n), |_| None)}
123 /// Retrieve an element in the RingBuf by index
125 /// Fails if there is no element with the given index
126 pub fn get<'a>(&'a self, i: uint) -> &'a T {
127 let idx = self.raw_index(i);
128 match *self.elts.get(idx) {
134 /// Retrieve an element in the RingBuf by index
136 /// Fails if there is no element with the given index
137 pub fn get_mut<'a>(&'a mut self, i: uint) -> &'a mut T {
138 let idx = self.raw_index(i);
139 match *self.elts.get_mut(idx) {
145 /// Swap elements at indices `i` and `j`
147 /// `i` and `j` may be equal.
149 /// Fails if there is no element with the given index
150 pub fn swap(&mut self, i: uint, j: uint) {
151 assert!(i < self.len());
152 assert!(j < self.len());
153 let ri = self.raw_index(i);
154 let rj = self.raw_index(j);
155 self.elts.as_mut_slice().swap(ri, rj);
158 /// Return index in underlying vec for a given logical element index
159 fn raw_index(&self, idx: uint) -> uint {
160 raw_index(self.lo, self.elts.len(), idx)
163 /// Reserve capacity for exactly `n` elements in the given RingBuf,
164 /// doing nothing if `self`'s capacity is already equal to or greater
165 /// than the requested capacity
169 /// * n - The number of elements to reserve space for
170 pub fn reserve_exact(&mut self, n: uint) {
171 self.elts.reserve_exact(n);
174 /// Reserve capacity for at least `n` elements in the given RingBuf,
175 /// over-allocating in case the caller needs to reserve additional
178 /// Do nothing if `self`'s capacity is already equal to or greater
179 /// than the requested capacity.
183 /// * n - The number of elements to reserve space for
184 pub fn reserve(&mut self, n: uint) {
185 self.elts.reserve(n);
188 /// Front-to-back iterator.
189 pub fn iter<'a>(&'a self) -> Items<'a, T> {
190 Items{index: 0, rindex: self.nelts, lo: self.lo, elts: self.elts.as_slice()}
193 /// Back-to-front iterator.
194 pub fn rev_iter<'a>(&'a self) -> Rev<Items<'a, T>> {
198 /// Front-to-back iterator which returns mutable values.
199 pub fn mut_iter<'a>(&'a mut self) -> MutItems<'a, T> {
200 let start_index = raw_index(self.lo, self.elts.len(), 0);
201 let end_index = raw_index(self.lo, self.elts.len(), self.nelts);
203 // Divide up the array
204 if end_index <= start_index {
205 // Items to iterate goes from:
206 // start_index to self.elts.len()
209 let (temp, remaining1) = self.elts.mut_split_at(start_index);
210 let (remaining2, _) = temp.mut_split_at(end_index);
211 MutItems { remaining1: remaining1,
212 remaining2: remaining2,
215 // Items to iterate goes from start_index to end_index:
216 let (empty, elts) = self.elts.mut_split_at(0);
217 let remaining1 = elts.mut_slice(start_index, end_index);
218 MutItems { remaining1: remaining1,
224 /// Back-to-front iterator which returns mutable values.
225 pub fn mut_rev_iter<'a>(&'a mut self) -> Rev<MutItems<'a, T>> {
226 self.mut_iter().rev()
231 pub struct Items<'a, T> {
235 elts: &'a [Option<T>],
238 impl<'a, T> Iterator<&'a T> for Items<'a, T> {
240 fn next(&mut self) -> Option<&'a T> {
241 if self.index == self.rindex {
244 let raw_index = raw_index(self.lo, self.elts.len(), self.index);
246 Some(self.elts[raw_index].get_ref())
250 fn size_hint(&self) -> (uint, Option<uint>) {
251 let len = self.rindex - self.index;
256 impl<'a, T> DoubleEndedIterator<&'a T> for Items<'a, T> {
258 fn next_back(&mut self) -> Option<&'a T> {
259 if self.index == self.rindex {
263 let raw_index = raw_index(self.lo, self.elts.len(), self.rindex);
264 Some(self.elts[raw_index].get_ref())
268 impl<'a, T> ExactSize<&'a T> for Items<'a, T> {}
270 impl<'a, T> RandomAccessIterator<&'a T> for Items<'a, T> {
272 fn indexable(&self) -> uint { self.rindex - self.index }
275 fn idx(&mut self, j: uint) -> Option<&'a T> {
276 if j >= self.indexable() {
279 let raw_index = raw_index(self.lo, self.elts.len(), self.index + j);
280 Some(self.elts[raw_index].get_ref())
285 /// RingBuf mutable iterator
286 pub struct MutItems<'a, T> {
287 remaining1: &'a mut [Option<T>],
288 remaining2: &'a mut [Option<T>],
292 impl<'a, T> Iterator<&'a mut T> for MutItems<'a, T> {
294 fn next(&mut self) -> Option<&'a mut T> {
298 let r = if self.remaining1.len() > 0 {
301 assert!(self.remaining2.len() > 0);
305 Some(r.mut_shift_ref().unwrap().get_mut_ref())
309 fn size_hint(&self) -> (uint, Option<uint>) {
310 (self.nelts, Some(self.nelts))
314 impl<'a, T> DoubleEndedIterator<&'a mut T> for MutItems<'a, T> {
316 fn next_back(&mut self) -> Option<&'a mut T> {
320 let r = if self.remaining2.len() > 0 {
323 assert!(self.remaining1.len() > 0);
327 Some(r.mut_pop_ref().unwrap().get_mut_ref())
331 impl<'a, T> ExactSize<&'a mut T> for MutItems<'a, T> {}
333 /// Grow is only called on full elts, so nelts is also len(elts), unlike
335 fn grow<T>(nelts: uint, loptr: &mut uint, elts: &mut Vec<Option<T>>) {
336 assert_eq!(nelts, elts.len());
338 let newlen = nelts * 2;
339 elts.reserve(newlen);
342 for _ in range(elts.len(), elts.capacity()) {
347 Move the shortest half into the newly reserved area.
351 A [. . .|o o o o o o o o|. . . . .]
352 B [o o o|. . . . . . . .|o o o o o]
355 assert!(newlen - nelts/2 >= nelts);
356 if lo <= (nelts - lo) { // A
357 for i in range(0u, lo) {
358 elts.as_mut_slice().swap(i, nelts + i);
361 for i in range(lo, nelts) {
362 elts.as_mut_slice().swap(i, newlen - nelts + i);
364 *loptr += newlen - nelts;
368 /// Return index in underlying vec for a given logical element index
369 fn raw_index(lo: uint, len: uint, index: uint) -> uint {
370 if lo >= len - index {
377 impl<A: Eq> Eq for RingBuf<A> {
378 fn eq(&self, other: &RingBuf<A>) -> bool {
379 self.nelts == other.nelts &&
380 self.iter().zip(other.iter()).all(|(a, b)| a.eq(b))
382 fn ne(&self, other: &RingBuf<A>) -> bool {
387 impl<A> FromIterator<A> for RingBuf<A> {
388 fn from_iter<T: Iterator<A>>(iterator: T) -> RingBuf<A> {
389 let (lower, _) = iterator.size_hint();
390 let mut deq = RingBuf::with_capacity(lower);
391 deq.extend(iterator);
396 impl<A> Extendable<A> for RingBuf<A> {
397 fn extend<T: Iterator<A>>(&mut self, mut iterator: T) {
398 for elt in iterator {
407 use self::test::Bencher;
409 use std::clone::Clone;
416 let mut d = RingBuf::new();
417 assert_eq!(d.len(), 0u);
421 assert_eq!(d.len(), 3u);
423 assert_eq!(d.len(), 4u);
424 debug!("{:?}", d.front());
425 assert_eq!(*d.front().unwrap(), 42);
426 debug!("{:?}", d.back());
427 assert_eq!(*d.back().unwrap(), 137);
428 let mut i = d.pop_front();
430 assert_eq!(i, Some(42));
433 assert_eq!(i, Some(137));
436 assert_eq!(i, Some(137));
439 assert_eq!(i, Some(17));
440 assert_eq!(d.len(), 0u);
442 assert_eq!(d.len(), 1u);
444 assert_eq!(d.len(), 2u);
446 assert_eq!(d.len(), 3u);
448 assert_eq!(d.len(), 4u);
449 debug!("{:?}", d.get(0));
450 debug!("{:?}", d.get(1));
451 debug!("{:?}", d.get(2));
452 debug!("{:?}", d.get(3));
453 assert_eq!(*d.get(0), 1);
454 assert_eq!(*d.get(1), 2);
455 assert_eq!(*d.get(2), 3);
456 assert_eq!(*d.get(3), 4);
466 let mut deq = RingBuf::new();
467 assert_eq!(deq.len(), 0);
471 assert_eq!(deq.len(), 3);
473 assert_eq!(deq.len(), 4);
474 assert_eq!(deq.front(), Some(&b));
475 assert_eq!(deq.back(), Some(&d));
476 assert_eq!(deq.pop_front(), Some(b));
477 assert_eq!(deq.pop_back(), Some(d));
478 assert_eq!(deq.pop_back(), Some(c));
479 assert_eq!(deq.pop_back(), Some(a));
480 assert_eq!(deq.len(), 0);
482 assert_eq!(deq.len(), 1);
484 assert_eq!(deq.len(), 2);
486 assert_eq!(deq.len(), 3);
488 assert_eq!(deq.len(), 4);
489 assert_eq!(*deq.get(0), a);
490 assert_eq!(*deq.get(1), b);
491 assert_eq!(*deq.get(2), c);
492 assert_eq!(*deq.get(3), d);
496 fn test_parameterized<T:Clone + Eq + Show>(a: T, b: T, c: T, d: T) {
497 let mut deq = RingBuf::new();
498 assert_eq!(deq.len(), 0);
499 deq.push_front(a.clone());
500 deq.push_front(b.clone());
501 deq.push_back(c.clone());
502 assert_eq!(deq.len(), 3);
503 deq.push_back(d.clone());
504 assert_eq!(deq.len(), 4);
505 assert_eq!((*deq.front().unwrap()).clone(), b.clone());
506 assert_eq!((*deq.back().unwrap()).clone(), d.clone());
507 assert_eq!(deq.pop_front().unwrap(), b.clone());
508 assert_eq!(deq.pop_back().unwrap(), d.clone());
509 assert_eq!(deq.pop_back().unwrap(), c.clone());
510 assert_eq!(deq.pop_back().unwrap(), a.clone());
511 assert_eq!(deq.len(), 0);
512 deq.push_back(c.clone());
513 assert_eq!(deq.len(), 1);
514 deq.push_front(b.clone());
515 assert_eq!(deq.len(), 2);
516 deq.push_back(d.clone());
517 assert_eq!(deq.len(), 3);
518 deq.push_front(a.clone());
519 assert_eq!(deq.len(), 4);
520 assert_eq!((*deq.get(0)).clone(), a.clone());
521 assert_eq!((*deq.get(1)).clone(), b.clone());
522 assert_eq!((*deq.get(2)).clone(), c.clone());
523 assert_eq!((*deq.get(3)).clone(), d.clone());
527 fn test_push_front_grow() {
528 let mut deq = RingBuf::new();
529 for i in range(0u, 66) {
532 assert_eq!(deq.len(), 66);
534 for i in range(0u, 66) {
535 assert_eq!(*deq.get(i), 65 - i);
538 let mut deq = RingBuf::new();
539 for i in range(0u, 66) {
543 for i in range(0u, 66) {
544 assert_eq!(*deq.get(i), i);
549 fn bench_new(b: &mut test::Bencher) {
551 let _: RingBuf<u64> = RingBuf::new();
556 fn bench_push_back(b: &mut test::Bencher) {
557 let mut deq = RingBuf::new();
564 fn bench_push_front(b: &mut test::Bencher) {
565 let mut deq = RingBuf::new();
572 fn bench_grow(b: &mut test::Bencher) {
573 let mut deq = RingBuf::new();
575 for _ in range(0, 65) {
581 #[deriving(Clone, Eq, Show)]
585 Three(int, int, int),
588 #[deriving(Clone, Eq, Show)]
592 Threepar(int, int, int),
595 #[deriving(Clone, Eq, Show)]
603 fn test_param_int() {
604 test_parameterized::<int>(5, 72, 64, 175);
608 fn test_param_at_int() {
609 test_parameterized::<@int>(@5, @72, @64, @175);
613 fn test_param_taggy() {
614 test_parameterized::<Taggy>(One(1), Two(1, 2), Three(1, 2, 3), Two(17, 42));
618 fn test_param_taggypar() {
619 test_parameterized::<Taggypar<int>>(Onepar::<int>(1),
621 Threepar::<int>(1, 2, 3),
622 Twopar::<int>(17, 42));
626 fn test_param_reccy() {
627 let reccy1 = RecCy { x: 1, y: 2, t: One(1) };
628 let reccy2 = RecCy { x: 345, y: 2, t: Two(1, 2) };
629 let reccy3 = RecCy { x: 1, y: 777, t: Three(1, 2, 3) };
630 let reccy4 = RecCy { x: 19, y: 252, t: Two(17, 42) };
631 test_parameterized::<RecCy>(reccy1, reccy2, reccy3, reccy4);
635 fn test_with_capacity() {
636 let mut d = RingBuf::with_capacity(0);
638 assert_eq!(d.len(), 1);
639 let mut d = RingBuf::with_capacity(50);
641 assert_eq!(d.len(), 1);
645 fn test_reserve_exact() {
646 let mut d = RingBuf::new();
649 assert_eq!(d.elts.capacity(), 50);
650 let mut d = RingBuf::new();
653 assert_eq!(d.elts.capacity(), 50);
658 let mut d = RingBuf::new();
661 assert_eq!(d.elts.capacity(), 64);
662 let mut d = RingBuf::new();
665 assert_eq!(d.elts.capacity(), 64);
670 let mut d: RingBuf<int> = range(0, 5).collect();
673 assert_eq!(d.iter().map(|&x|x).collect::<Vec<int>>(), vec!(4, 2, 3, 1));
678 let mut d = RingBuf::new();
679 assert_eq!(d.iter().next(), None);
680 assert_eq!(d.iter().size_hint(), (0, Some(0)));
682 for i in range(0, 5) {
685 assert_eq!(d.iter().collect::<Vec<&int>>().as_slice(), &[&0,&1,&2,&3,&4]);
687 for i in range(6, 9) {
690 assert_eq!(d.iter().collect::<Vec<&int>>().as_slice(), &[&8,&7,&6,&0,&1,&2,&3,&4]);
692 let mut it = d.iter();
693 let mut len = d.len();
697 _ => { len -= 1; assert_eq!(it.size_hint(), (len, Some(len))) }
704 let mut d = RingBuf::new();
705 assert_eq!(d.rev_iter().next(), None);
707 for i in range(0, 5) {
710 assert_eq!(d.rev_iter().collect::<Vec<&int>>().as_slice(), &[&4,&3,&2,&1,&0]);
712 for i in range(6, 9) {
715 assert_eq!(d.rev_iter().collect::<Vec<&int>>().as_slice(), &[&4,&3,&2,&1,&0,&6,&7,&8]);
719 fn test_mut_rev_iter_wrap() {
720 let mut d = RingBuf::with_capacity(3);
721 assert!(d.mut_rev_iter().next().is_none());
726 assert_eq!(d.pop_front(), Some(1));
729 assert_eq!(d.mut_rev_iter().map(|x| *x).collect::<Vec<int>>(),
735 let mut d = RingBuf::new();
736 assert!(d.mut_iter().next().is_none());
738 for i in range(0u, 3) {
742 for (i, elt) in d.mut_iter().enumerate() {
743 assert_eq!(*elt, 2 - i);
748 let mut it = d.mut_iter();
749 assert_eq!(*it.next().unwrap(), 0);
750 assert_eq!(*it.next().unwrap(), 1);
751 assert_eq!(*it.next().unwrap(), 2);
752 assert!(it.next().is_none());
757 fn test_mut_rev_iter() {
758 let mut d = RingBuf::new();
759 assert!(d.mut_rev_iter().next().is_none());
761 for i in range(0u, 3) {
765 for (i, elt) in d.mut_rev_iter().enumerate() {
771 let mut it = d.mut_rev_iter();
772 assert_eq!(*it.next().unwrap(), 0);
773 assert_eq!(*it.next().unwrap(), 1);
774 assert_eq!(*it.next().unwrap(), 2);
775 assert!(it.next().is_none());
780 fn test_from_iter() {
782 let v = vec!(1,2,3,4,5,6,7);
783 let deq: RingBuf<int> = v.iter().map(|&x| x).collect();
784 let u: Vec<int> = deq.iter().map(|&x| x).collect();
787 let mut seq = iter::count(0u, 2).take(256);
788 let deq: RingBuf<uint> = seq.collect();
789 for (i, &x) in deq.iter().enumerate() {
792 assert_eq!(deq.len(), 256);
797 let mut d = RingBuf::new();
802 assert_eq!(d.len(), 4u);
803 let mut e = d.clone();
804 assert_eq!(e.len(), 4u);
805 while !d.is_empty() {
806 assert_eq!(d.pop_back(), e.pop_back());
808 assert_eq!(d.len(), 0u);
809 assert_eq!(e.len(), 0u);
814 let mut d = RingBuf::new();
815 assert!(d == RingBuf::with_capacity(0));
820 let mut e = RingBuf::with_capacity(0);
830 assert!(e == RingBuf::new());