blob: e32e8145d172e2087edb08907062510b275da049 [file] [log] [blame]
Jonathan S03609e52014-04-21 04:59:121// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
Graydon Hoare00c856c2012-12-04 00:48:012// 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
Steve Klabnik84030fd2014-08-30 21:11:2211//! 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//! Its interface `Deque` is defined in `collections`.
Patrick Waltonf3723cf2013-05-17 22:28:4415
Alex Crichton6a585372014-05-30 01:50:1216use core::prelude::*;
17
18use core::cmp;
Tom Jakubowskid6a39412014-06-09 07:30:0419use core::default::Default;
Alex Crichton6a585372014-05-30 01:50:1220use core::fmt;
nham63615772014-07-27 03:18:5621use core::iter;
Alex Crichton9d5d97b2014-10-15 06:05:0122use core::slice;
nham1cfa6562014-07-27 02:33:4723use std::hash::{Writer, Hash};
Alex Crichton998fece2013-05-06 04:42:5424
Patrick Walton7f928d12014-08-13 03:31:3025use {Deque, Mutable, MutableSeq};
Alex Crichton6a585372014-05-30 01:50:1226use vec::Vec;
blake2-ppc70523712013-07-10 13:27:1427
blake2-ppc0ff5c172013-07-06 03:42:4528static INITIAL_CAPACITY: uint = 8u; // 2^3
29static MINIMUM_CAPACITY: uint = 2u;
Daniel Micayb47e1e92013-02-16 22:55:5530
P1startf2aa88c2014-08-04 10:48:3931/// `RingBuf` is a circular buffer that implements `Deque`.
blake2-ppc10c76982013-07-06 13:27:3232#[deriving(Clone)]
blake2-ppc70523712013-07-10 13:27:1433pub struct RingBuf<T> {
Alex Crichton8ad7e542014-03-27 22:10:0434 nelts: uint,
35 lo: uint,
Huon Wilson4b9a7a22014-04-05 05:45:4236 elts: Vec<Option<T>>
Marijn Haverbeke26610db2012-01-11 11:49:3337}
Roy Frostig9c818892010-07-21 01:03:0938
Brian Anderson50942c72014-05-19 18:32:0939impl<T> Collection for RingBuf<T> {
P1startf2aa88c2014-08-04 10:48:3940 /// Returns the number of elements in the `RingBuf`.
Alex Crichtonb29c3682013-06-24 03:44:1141 fn len(&self) -> uint { self.nelts }
Daniel Micayb47e1e92013-02-16 22:55:5542}
Roy Frostig9c818892010-07-21 01:03:0943
blake2-ppc70523712013-07-10 13:27:1444impl<T> Mutable for RingBuf<T> {
P1startf2aa88c2014-08-04 10:48:3945 /// Clears the `RingBuf`, removing all values.
Daniel Micayed7c9c42013-02-16 23:55:2546 fn clear(&mut self) {
Aaron Turonfc525ee2014-09-15 03:27:3647 for x in self.elts.iter_mut() { *x = None }
Daniel Micayed7c9c42013-02-16 23:55:2548 self.nelts = 0;
49 self.lo = 0;
Daniel Micayed7c9c42013-02-16 23:55:2550 }
51}
52
blake2-ppc70523712013-07-10 13:27:1453impl<T> Deque<T> for RingBuf<T> {
P1startf2aa88c2014-08-04 10:48:3954 /// Returns a reference to the first element in the `RingBuf`.
blake2-ppc70523712013-07-10 13:27:1455 fn front<'a>(&'a self) -> Option<&'a T> {
Aaron Turonf77cabe2014-08-11 23:47:4656 if self.nelts > 0 { Some(&self[0]) } else { None }
blake2-ppc0ff5c172013-07-06 03:42:4557 }
58
P1startf2aa88c2014-08-04 10:48:3959 /// Returns a mutable reference to the first element in the `RingBuf`.
blake2-ppc70523712013-07-10 13:27:1460 fn front_mut<'a>(&'a mut self) -> Option<&'a mut T> {
61 if self.nelts > 0 { Some(self.get_mut(0)) } else { None }
Niko Matsakis03396472013-04-10 20:14:0662 }
63
P1startf2aa88c2014-08-04 10:48:3964 /// Returns a reference to the last element in the `RingBuf`.
blake2-ppc70523712013-07-10 13:27:1465 fn back<'a>(&'a self) -> Option<&'a T> {
Aaron Turonf77cabe2014-08-11 23:47:4666 if self.nelts > 0 { Some(&self[self.nelts - 1]) } else { None }
blake2-ppc70523712013-07-10 13:27:1467 }
Niko Matsakis03396472013-04-10 20:14:0668
P1startf2aa88c2014-08-04 10:48:3969 /// Returns a mutable reference to the last element in the `RingBuf`.
blake2-ppc70523712013-07-10 13:27:1470 fn back_mut<'a>(&'a mut self) -> Option<&'a mut T> {
Cameron Zwarich159e27a2014-06-14 03:48:0971 let nelts = self.nelts;
72 if nelts > 0 { Some(self.get_mut(nelts - 1)) } else { None }
blake2-ppc70523712013-07-10 13:27:1473 }
74
P1startf2aa88c2014-08-04 10:48:3975 /// Removes and returns the first element in the `RingBuf`, or `None` if it
76 /// is empty.
blake2-ppc70523712013-07-10 13:27:1477 fn pop_front(&mut self) -> Option<T> {
Huon Wilson4b9a7a22014-04-05 05:45:4278 let result = self.elts.get_mut(self.lo).take();
blake2-ppc70523712013-07-10 13:27:1479 if result.is_some() {
80 self.lo = (self.lo + 1u) % self.elts.len();
81 self.nelts -= 1u;
blake2-ppc5d72f3f2013-07-06 03:42:4582 }
Daniel Micay61906612013-02-17 00:43:2983 result
84 }
85
P1startf2aa88c2014-08-04 10:48:3986 /// Prepends an element to the `RingBuf`.
blake2-ppc70523712013-07-10 13:27:1487 fn push_front(&mut self, t: T) {
blake2-ppc40ce0b72013-07-06 03:42:4588 if self.nelts == self.elts.len() {
blake2-ppc8a326762013-07-06 03:42:4589 grow(self.nelts, &mut self.lo, &mut self.elts);
blake2-ppc40ce0b72013-07-06 03:42:4590 }
Daniel Micayb47e1e92013-02-16 22:55:5591 if self.lo == 0u {
92 self.lo = self.elts.len() - 1u;
93 } else { self.lo -= 1u; }
Huon Wilson4b9a7a22014-04-05 05:45:4294 *self.elts.get_mut(self.lo) = Some(t);
Daniel Micayb47e1e92013-02-16 22:55:5595 self.nelts += 1u;
Erick Tryzelaare84576b2013-01-22 16:44:2496 }
Brian Anderson94e42c22014-07-12 01:08:4697}
Marijn Haverbeke26610db2012-01-11 11:49:3398
Brian Anderson94e42c22014-07-12 01:08:4699impl<T> MutableSeq<T> for RingBuf<T> {
100 fn push(&mut self, t: T) {
blake2-ppc5d72f3f2013-07-06 03:42:45101 if self.nelts == self.elts.len() {
blake2-ppc8a326762013-07-06 03:42:45102 grow(self.nelts, &mut self.lo, &mut self.elts);
Graydon Hoare2880ecd2010-09-22 22:44:13103 }
blake2-ppc5d72f3f2013-07-06 03:42:45104 let hi = self.raw_index(self.nelts);
Huon Wilson4b9a7a22014-04-05 05:45:42105 *self.elts.get_mut(hi) = Some(t);
Daniel Micayb47e1e92013-02-16 22:55:55106 self.nelts += 1u;
Graydon Hoarece729932011-06-15 18:19:50107 }
Brian Anderson94e42c22014-07-12 01:08:46108 fn pop(&mut self) -> Option<T> {
109 if self.nelts > 0 {
110 self.nelts -= 1;
111 let hi = self.raw_index(self.nelts);
112 self.elts.get_mut(hi).take()
113 } else {
114 None
115 }
116 }
Brian Andersond36a8f32014-07-11 17:12:38117}
118
Tom Jakubowskid6a39412014-06-09 07:30:04119impl<T> Default for RingBuf<T> {
120 #[inline]
121 fn default() -> RingBuf<T> { RingBuf::new() }
122}
123
blake2-ppc70523712013-07-10 13:27:14124impl<T> RingBuf<T> {
P1startf2aa88c2014-08-04 10:48:39125 /// Creates an empty `RingBuf`.
blake2-ppc70523712013-07-10 13:27:14126 pub fn new() -> RingBuf<T> {
127 RingBuf::with_capacity(INITIAL_CAPACITY)
128 }
129
P1startf2aa88c2014-08-04 10:48:39130 /// Creates an empty `RingBuf` with space for at least `n` elements.
blake2-ppc70523712013-07-10 13:27:14131 pub fn with_capacity(n: uint) -> RingBuf<T> {
132 RingBuf{nelts: 0, lo: 0,
Huon Wilson4b9a7a22014-04-05 05:45:42133 elts: Vec::from_fn(cmp::max(MINIMUM_CAPACITY, n), |_| None)}
blake2-ppc70523712013-07-10 13:27:14134 }
135
P1startf2aa88c2014-08-04 10:48:39136 /// Retrieves an element in the `RingBuf` by index.
blake2-ppc70523712013-07-10 13:27:14137 ///
P1startf2aa88c2014-08-04 10:48:39138 /// Fails if there is no element with the given index.
nhamebe80972014-07-17 23:19:51139 ///
140 /// # Example
141 ///
142 /// ```rust
143 /// use std::collections::RingBuf;
144 ///
145 /// let mut buf = RingBuf::new();
146 /// buf.push(3i);
147 /// buf.push(4);
148 /// buf.push(5);
149 /// *buf.get_mut(1) = 7;
P1startfd10d202014-08-02 06:39:39150 /// assert_eq!(buf[1], 7);
nhamebe80972014-07-17 23:19:51151 /// ```
blake2-ppc70523712013-07-10 13:27:14152 pub fn get_mut<'a>(&'a mut self, i: uint) -> &'a mut T {
153 let idx = self.raw_index(i);
Huon Wilson4b9a7a22014-04-05 05:45:42154 match *self.elts.get_mut(idx) {
Alex Crichtondaf5f5a2013-10-21 20:08:31155 None => fail!(),
blake2-ppc70523712013-07-10 13:27:14156 Some(ref mut v) => v
157 }
158 }
159
P1startf2aa88c2014-08-04 10:48:39160 /// Swaps elements at indices `i` and `j`.
blake2-ppc57757a82013-09-26 07:19:26161 ///
162 /// `i` and `j` may be equal.
163 ///
P1startf2aa88c2014-08-04 10:48:39164 /// Fails if there is no element with either index.
nhamebe80972014-07-17 23:19:51165 ///
166 /// # Example
167 ///
168 /// ```rust
169 /// use std::collections::RingBuf;
170 ///
171 /// let mut buf = RingBuf::new();
172 /// buf.push(3i);
173 /// buf.push(4);
174 /// buf.push(5);
175 /// buf.swap(0, 2);
P1startfd10d202014-08-02 06:39:39176 /// assert_eq!(buf[0], 5);
177 /// assert_eq!(buf[2], 3);
nhamebe80972014-07-17 23:19:51178 /// ```
blake2-ppc57757a82013-09-26 07:19:26179 pub fn swap(&mut self, i: uint, j: uint) {
180 assert!(i < self.len());
181 assert!(j < self.len());
182 let ri = self.raw_index(i);
183 let rj = self.raw_index(j);
Huon Wilson4b9a7a22014-04-05 05:45:42184 self.elts.as_mut_slice().swap(ri, rj);
blake2-ppc57757a82013-09-26 07:19:26185 }
186
P1startf2aa88c2014-08-04 10:48:39187 /// Returns the index in the underlying `Vec` for a given logical element
188 /// index.
blake2-ppc70523712013-07-10 13:27:14189 fn raw_index(&self, idx: uint) -> uint {
190 raw_index(self.lo, self.elts.len(), idx)
191 }
192
P1startf2aa88c2014-08-04 10:48:39193 /// Reserves capacity for exactly `n` elements in the given `RingBuf`,
Tim Chevalier77de84b2013-05-27 18:47:38194 /// doing nothing if `self`'s capacity is already equal to or greater
P1startf2aa88c2014-08-04 10:48:39195 /// than the requested capacity.
David Manescu65f35782014-01-31 13:03:20196 pub fn reserve_exact(&mut self, n: uint) {
197 self.elts.reserve_exact(n);
Tim Chevalier77de84b2013-05-27 18:47:38198 }
199
P1startf2aa88c2014-08-04 10:48:39200 /// Reserves capacity for at least `n` elements in the given `RingBuf`,
Tim Chevalier77de84b2013-05-27 18:47:38201 /// over-allocating in case the caller needs to reserve additional
202 /// space.
203 ///
204 /// Do nothing if `self`'s capacity is already equal to or greater
205 /// than the requested capacity.
David Manescu65f35782014-01-31 13:03:20206 pub fn reserve(&mut self, n: uint) {
207 self.elts.reserve(n);
Tim Chevalier77de84b2013-05-27 18:47:38208 }
Jed Estep4f7a7422013-06-25 19:08:47209
P1startf2aa88c2014-08-04 10:48:39210 /// Returns a front-to-back iterator.
nhamebe80972014-07-17 23:19:51211 ///
212 /// # Example
213 ///
214 /// ```rust
215 /// use std::collections::RingBuf;
216 ///
217 /// let mut buf = RingBuf::new();
218 /// buf.push(5i);
219 /// buf.push(3);
220 /// buf.push(4);
Nick Cameron52ef4622014-08-06 09:59:40221 /// let b: &[_] = &[&5, &3, &4];
222 /// assert_eq!(buf.iter().collect::<Vec<&int>>().as_slice(), b);
nhamebe80972014-07-17 23:19:51223 /// ```
Palmer Cox3fd8c8b2014-01-15 03:32:24224 pub fn iter<'a>(&'a self) -> Items<'a, T> {
Huon Wilson4b9a7a22014-04-05 05:45:42225 Items{index: 0, rindex: self.nelts, lo: self.lo, elts: self.elts.as_slice()}
blake2-ppc3385e792013-07-15 23:13:26226 }
227
P1startf2aa88c2014-08-04 10:48:39228 /// Returns a front-to-back iterator which returns mutable references.
nhamebe80972014-07-17 23:19:51229 ///
230 /// # Example
231 ///
232 /// ```rust
233 /// use std::collections::RingBuf;
234 ///
235 /// let mut buf = RingBuf::new();
236 /// buf.push(5i);
237 /// buf.push(3);
238 /// buf.push(4);
Aaron Turonfc525ee2014-09-15 03:27:36239 /// for num in buf.iter_mut() {
nhamebe80972014-07-17 23:19:51240 /// *num = *num - 2;
241 /// }
Nick Cameron52ef4622014-08-06 09:59:40242 /// let b: &[_] = &[&mut 3, &mut 1, &mut 2];
Nick Cameron59976942014-09-24 11:41:09243 /// assert_eq!(buf.iter_mut().collect::<Vec<&mut int>>()[], b);
nhamebe80972014-07-17 23:19:51244 /// ```
Aaron Turond8dfe192014-09-14 22:57:55245 pub fn iter_mut<'a>(&'a mut self) -> MutItems<'a, T> {
Niko Matsakisbc4164d2013-11-16 22:29:39246 let start_index = raw_index(self.lo, self.elts.len(), 0);
247 let end_index = raw_index(self.lo, self.elts.len(), self.nelts);
248
249 // Divide up the array
250 if end_index <= start_index {
251 // Items to iterate goes from:
252 // start_index to self.elts.len()
253 // and then
254 // 0 to end_index
Aaron Turonfc525ee2014-09-15 03:27:36255 let (temp, remaining1) = self.elts.split_at_mut(start_index);
256 let (remaining2, _) = temp.split_at_mut(end_index);
Alex Crichton9d5d97b2014-10-15 06:05:01257 MutItems {
258 remaining1: remaining1.iter_mut(),
259 remaining2: remaining2.iter_mut(),
260 nelts: self.nelts,
261 }
Niko Matsakisbc4164d2013-11-16 22:29:39262 } else {
263 // Items to iterate goes from start_index to end_index:
Aaron Turonfc525ee2014-09-15 03:27:36264 let (empty, elts) = self.elts.split_at_mut(0);
Nick Cameron59976942014-09-24 11:41:09265 let remaining1 = elts[mut start_index..end_index];
Alex Crichton9d5d97b2014-10-15 06:05:01266 MutItems {
267 remaining1: remaining1.iter_mut(),
268 remaining2: empty.iter_mut(),
269 nelts: self.nelts,
270 }
Niko Matsakisbc4164d2013-11-16 22:29:39271 }
Jed Estep4f7a7422013-06-25 19:08:47272 }
Jed Estep4f7a7422013-06-25 19:08:47273}
274
Niko Matsakis1b487a82014-08-28 01:46:52275/// `RingBuf` iterator.
Niko Matsakis1b487a82014-08-28 01:46:52276pub struct Items<'a, T:'a> {
277 lo: uint,
278 index: uint,
279 rindex: uint,
280 elts: &'a [Option<T>],
281}
282
Palmer Cox3fd8c8b2014-01-15 03:32:24283impl<'a, T> Iterator<&'a T> for Items<'a, T> {
Niko Matsakisbc4164d2013-11-16 22:29:39284 #[inline]
Erik Price5731ca32013-12-10 07:16:18285 fn next(&mut self) -> Option<&'a T> {
Niko Matsakisbc4164d2013-11-16 22:29:39286 if self.index == self.rindex {
287 return None;
288 }
289 let raw_index = raw_index(self.lo, self.elts.len(), self.index);
290 self.index += 1;
Aaron Turon276b8b12014-08-19 00:52:38291 Some(self.elts[raw_index].as_ref().unwrap())
Niko Matsakisbc4164d2013-11-16 22:29:39292 }
293
294 #[inline]
295 fn size_hint(&self) -> (uint, Option<uint>) {
296 let len = self.rindex - self.index;
297 (len, Some(len))
298 }
299}
300
Palmer Cox3fd8c8b2014-01-15 03:32:24301impl<'a, T> DoubleEndedIterator<&'a T> for Items<'a, T> {
Niko Matsakisbc4164d2013-11-16 22:29:39302 #[inline]
Erik Price5731ca32013-12-10 07:16:18303 fn next_back(&mut self) -> Option<&'a T> {
Niko Matsakisbc4164d2013-11-16 22:29:39304 if self.index == self.rindex {
305 return None;
306 }
307 self.rindex -= 1;
308 let raw_index = raw_index(self.lo, self.elts.len(), self.rindex);
Aaron Turon276b8b12014-08-19 00:52:38309 Some(self.elts[raw_index].as_ref().unwrap())
Niko Matsakisbc4164d2013-11-16 22:29:39310 }
311}
Jed Estep35314c92013-06-26 15:38:29312
Palmer Cox3fd8c8b2014-01-15 03:32:24313impl<'a, T> ExactSize<&'a T> for Items<'a, T> {}
blake2-ppc7c369ee72013-09-01 16:20:24314
Palmer Cox3fd8c8b2014-01-15 03:32:24315impl<'a, T> RandomAccessIterator<&'a T> for Items<'a, T> {
blake2-ppcf6862132013-07-29 18:16:26316 #[inline]
317 fn indexable(&self) -> uint { self.rindex - self.index }
318
319 #[inline]
Alex Crichtonf4083a22014-04-22 05:15:42320 fn idx(&mut self, j: uint) -> Option<&'a T> {
blake2-ppcf6862132013-07-29 18:16:26321 if j >= self.indexable() {
322 None
323 } else {
324 let raw_index = raw_index(self.lo, self.elts.len(), self.index + j);
Aaron Turon276b8b12014-08-19 00:52:38325 Some(self.elts[raw_index].as_ref().unwrap())
blake2-ppcf6862132013-07-29 18:16:26326 }
327 }
328}
329
Niko Matsakis1b487a82014-08-28 01:46:52330/// `RingBuf` mutable iterator.
Niko Matsakis1b487a82014-08-28 01:46:52331pub struct MutItems<'a, T:'a> {
Alex Crichton9d5d97b2014-10-15 06:05:01332 remaining1: slice::MutItems<'a, Option<T>>,
333 remaining2: slice::MutItems<'a, Option<T>>,
Niko Matsakis1b487a82014-08-28 01:46:52334 nelts: uint,
335}
336
Palmer Cox3fd8c8b2014-01-15 03:32:24337impl<'a, T> Iterator<&'a mut T> for MutItems<'a, T> {
Niko Matsakisbc4164d2013-11-16 22:29:39338 #[inline]
Erik Price5731ca32013-12-10 07:16:18339 fn next(&mut self) -> Option<&'a mut T> {
Niko Matsakisbc4164d2013-11-16 22:29:39340 if self.nelts == 0 {
341 return None;
342 }
Niko Matsakisbc4164d2013-11-16 22:29:39343 self.nelts -= 1;
Alex Crichton9d5d97b2014-10-15 06:05:01344 match self.remaining1.next() {
345 Some(ptr) => return Some(ptr.as_mut().unwrap()),
346 None => {}
347 }
348 match self.remaining2.next() {
349 Some(ptr) => return Some(ptr.as_mut().unwrap()),
350 None => unreachable!(),
351 }
Niko Matsakisbc4164d2013-11-16 22:29:39352 }
353
354 #[inline]
355 fn size_hint(&self) -> (uint, Option<uint>) {
356 (self.nelts, Some(self.nelts))
357 }
358}
359
Palmer Cox3fd8c8b2014-01-15 03:32:24360impl<'a, T> DoubleEndedIterator<&'a mut T> for MutItems<'a, T> {
Niko Matsakisbc4164d2013-11-16 22:29:39361 #[inline]
Erik Price5731ca32013-12-10 07:16:18362 fn next_back(&mut self) -> Option<&'a mut T> {
Niko Matsakisbc4164d2013-11-16 22:29:39363 if self.nelts == 0 {
364 return None;
365 }
Niko Matsakisbc4164d2013-11-16 22:29:39366 self.nelts -= 1;
Alex Crichton9d5d97b2014-10-15 06:05:01367 match self.remaining2.next_back() {
368 Some(ptr) => return Some(ptr.as_mut().unwrap()),
369 None => {}
370 }
371 match self.remaining1.next_back() {
372 Some(ptr) => return Some(ptr.as_mut().unwrap()),
373 None => unreachable!(),
374 }
Niko Matsakisbc4164d2013-11-16 22:29:39375 }
376}
Daniel Micayb47e1e92013-02-16 22:55:55377
Palmer Cox3fd8c8b2014-01-15 03:32:24378impl<'a, T> ExactSize<&'a mut T> for MutItems<'a, T> {}
blake2-ppc7c369ee72013-09-01 16:20:24379
Daniel Micayb47e1e92013-02-16 22:55:55380/// Grow is only called on full elts, so nelts is also len(elts), unlike
381/// elsewhere.
Huon Wilson4b9a7a22014-04-05 05:45:42382fn grow<T>(nelts: uint, loptr: &mut uint, elts: &mut Vec<Option<T>>) {
Corey Richardsoncc57ca02013-05-19 02:02:45383 assert_eq!(nelts, elts.len());
blake2-ppc8a326762013-07-06 03:42:45384 let lo = *loptr;
Kevin Butler64896d62014-08-07 01:11:13385 elts.reserve(nelts * 2);
386 let newlen = elts.capacity();
Daniel Micayb47e1e92013-02-16 22:55:55387
blake2-ppc40ce0b72013-07-06 03:42:45388 /* fill with None */
Kevin Butler64896d62014-08-07 01:11:13389 for _ in range(elts.len(), newlen) {
blake2-ppc40ce0b72013-07-06 03:42:45390 elts.push(None);
Daniel Micayb47e1e92013-02-16 22:55:55391 }
blake2-ppc8a326762013-07-06 03:42:45392
393 /*
394 Move the shortest half into the newly reserved area.
395 lo ---->|
396 nelts ----------->|
397 [o o o|o o o o o]
398 A [. . .|o o o o o o o o|. . . . .]
399 B [o o o|. . . . . . . .|o o o o o]
400 */
401
402 assert!(newlen - nelts/2 >= nelts);
403 if lo <= (nelts - lo) { // A
Daniel Micay100894552013-08-03 16:45:23404 for i in range(0u, lo) {
Huon Wilson4b9a7a22014-04-05 05:45:42405 elts.as_mut_slice().swap(i, nelts + i);
blake2-ppc8a326762013-07-06 03:42:45406 }
407 } else { // B
Daniel Micay100894552013-08-03 16:45:23408 for i in range(lo, nelts) {
Huon Wilson4b9a7a22014-04-05 05:45:42409 elts.as_mut_slice().swap(i, newlen - nelts + i);
blake2-ppc8a326762013-07-06 03:42:45410 }
411 *loptr += newlen - nelts;
blake2-ppc40ce0b72013-07-06 03:42:45412 }
Daniel Micayb47e1e92013-02-16 22:55:55413}
414
P1startf2aa88c2014-08-04 10:48:39415/// Returns the index in the underlying `Vec` for a given logical element index.
blake2-ppc75015c32013-07-06 03:42:45416fn raw_index(lo: uint, len: uint, index: uint) -> uint {
417 if lo >= len - index {
418 lo + index - len
419 } else {
420 lo + index
421 }
422}
423
Alex Crichton748bc3c2014-05-30 00:45:07424impl<A: PartialEq> PartialEq for RingBuf<A> {
blake2-ppc70523712013-07-10 13:27:14425 fn eq(&self, other: &RingBuf<A>) -> bool {
blake2-ppc10c76982013-07-06 13:27:32426 self.nelts == other.nelts &&
427 self.iter().zip(other.iter()).all(|(a, b)| a.eq(b))
428 }
blake2-ppc70523712013-07-10 13:27:14429 fn ne(&self, other: &RingBuf<A>) -> bool {
blake2-ppc10c76982013-07-06 13:27:32430 !self.eq(other)
431 }
432}
433
nham25acfde2014-08-01 20:05:03434impl<A: Eq> Eq for RingBuf<A> {}
435
nham63615772014-07-27 03:18:56436impl<A: PartialOrd> PartialOrd for RingBuf<A> {
437 fn partial_cmp(&self, other: &RingBuf<A>) -> Option<Ordering> {
438 iter::order::partial_cmp(self.iter(), other.iter())
439 }
440}
441
nham3737c532014-08-01 20:22:48442impl<A: Ord> Ord for RingBuf<A> {
443 #[inline]
444 fn cmp(&self, other: &RingBuf<A>) -> Ordering {
445 iter::order::cmp(self.iter(), other.iter())
446 }
447}
448
nham1cfa6562014-07-27 02:33:47449impl<S: Writer, A: Hash<S>> Hash<S> for RingBuf<A> {
450 fn hash(&self, state: &mut S) {
nham9fa44242014-07-27 16:37:32451 self.len().hash(state);
nham1cfa6562014-07-27 02:33:47452 for elt in self.iter() {
453 elt.hash(state);
454 }
455 }
456}
457
P1startfd10d202014-08-02 06:39:39458impl<A> Index<uint, A> for RingBuf<A> {
459 #[inline]
460 fn index<'a>(&'a self, i: &uint) -> &'a A {
Alex Crichton9d5d97b2014-10-15 06:05:01461 let idx = self.raw_index(*i);
462 match self.elts[idx] {
463 None => fail!(),
464 Some(ref v) => v,
465 }
P1startfd10d202014-08-02 06:39:39466 }
467}
468
469// FIXME(#12825) Indexing will always try IndexMut first and that causes issues.
470/*impl<A> IndexMut<uint, A> for RingBuf<A> {
471 #[inline]
472 fn index_mut<'a>(&'a mut self, index: &uint) -> &'a mut A {
473 self.get_mut(*index)
474 }
475}*/
476
Huon Wilson53487a02013-08-13 13:08:14477impl<A> FromIterator<A> for RingBuf<A> {
Brian Andersonee052192014-03-31 04:45:55478 fn from_iter<T: Iterator<A>>(iterator: T) -> RingBuf<A> {
blake2-ppcf8ae5262013-07-30 00:06:49479 let (lower, _) = iterator.size_hint();
480 let mut deq = RingBuf::with_capacity(lower);
481 deq.extend(iterator);
blake2-ppc08dc72f2013-07-06 03:42:45482 deq
483 }
484}
485
Huon Wilson53487a02013-08-13 13:08:14486impl<A> Extendable<A> for RingBuf<A> {
Marvin Löbel6200e762014-03-20 13:12:56487 fn extend<T: Iterator<A>>(&mut self, mut iterator: T) {
488 for elt in iterator {
Aaron Turonf77cabe2014-08-11 23:47:46489 self.push(elt);
blake2-ppcf8ae5262013-07-30 00:06:49490 }
491 }
492}
493
Alex Crichton6a585372014-05-30 01:50:12494impl<T: fmt::Show> fmt::Show for RingBuf<T> {
Adolfo Ochagavía8e4e3ab2014-06-04 14:15:04495 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
496 try!(write!(f, "["));
497
498 for (i, e) in self.iter().enumerate() {
499 if i != 0 { try!(write!(f, ", ")); }
500 try!(write!(f, "{}", *e));
501 }
502
503 write!(f, "]")
504 }
505}
506
Brian Anderson6e27b272012-01-18 03:05:07507#[cfg(test)]
508mod tests {
Alex Crichton02882fb2014-02-28 09:23:06509 use std::fmt::Show;
Alex Crichton760b93a2014-05-30 02:03:06510 use std::prelude::*;
nham1cfa6562014-07-27 02:33:47511 use std::hash;
Alex Crichton760b93a2014-05-30 02:03:06512 use test::Bencher;
513 use test;
514
Brian Anderson054b1ff2014-07-14 21:45:10515 use {Deque, Mutable, MutableSeq};
Alex Crichtonf47e4b22014-01-07 06:33:50516 use super::RingBuf;
Alex Crichton760b93a2014-05-30 02:03:06517 use vec::Vec;
Patrick Waltonfa5ee932012-12-28 02:24:18518
Brian Anderson6e27b272012-01-18 03:05:07519 #[test]
Victor Berger52ea83d2014-09-22 17:30:06520 #[allow(deprecated)]
Brian Anderson6e27b272012-01-18 03:05:07521 fn test_simple() {
blake2-ppc70523712013-07-10 13:27:14522 let mut d = RingBuf::new();
Corey Richardsoncc57ca02013-05-19 02:02:45523 assert_eq!(d.len(), 0u);
Niko Matsakis9e3d0b02014-04-21 21:58:52524 d.push_front(17i);
525 d.push_front(42i);
nham7b310582014-08-26 19:45:55526 d.push(137);
Corey Richardsoncc57ca02013-05-19 02:02:45527 assert_eq!(d.len(), 3u);
nham7b310582014-08-26 19:45:55528 d.push(137);
Corey Richardsoncc57ca02013-05-19 02:02:45529 assert_eq!(d.len(), 4u);
Luqman Aden3ef9aa02014-10-15 07:22:55530 debug!("{}", d.front());
blake2-ppc70523712013-07-10 13:27:14531 assert_eq!(*d.front().unwrap(), 42);
Luqman Aden3ef9aa02014-10-15 07:22:55532 debug!("{}", d.back());
blake2-ppc70523712013-07-10 13:27:14533 assert_eq!(*d.back().unwrap(), 137);
534 let mut i = d.pop_front();
Luqman Aden3ef9aa02014-10-15 07:22:55535 debug!("{}", i);
blake2-ppc70523712013-07-10 13:27:14536 assert_eq!(i, Some(42));
nham7b310582014-08-26 19:45:55537 i = d.pop();
Luqman Aden3ef9aa02014-10-15 07:22:55538 debug!("{}", i);
blake2-ppc70523712013-07-10 13:27:14539 assert_eq!(i, Some(137));
nham7b310582014-08-26 19:45:55540 i = d.pop();
Luqman Aden3ef9aa02014-10-15 07:22:55541 debug!("{}", i);
blake2-ppc70523712013-07-10 13:27:14542 assert_eq!(i, Some(137));
nham7b310582014-08-26 19:45:55543 i = d.pop();
Luqman Aden3ef9aa02014-10-15 07:22:55544 debug!("{}", i);
blake2-ppc70523712013-07-10 13:27:14545 assert_eq!(i, Some(17));
Corey Richardsoncc57ca02013-05-19 02:02:45546 assert_eq!(d.len(), 0u);
nham7b310582014-08-26 19:45:55547 d.push(3);
Corey Richardsoncc57ca02013-05-19 02:02:45548 assert_eq!(d.len(), 1u);
blake2-ppc70523712013-07-10 13:27:14549 d.push_front(2);
Corey Richardsoncc57ca02013-05-19 02:02:45550 assert_eq!(d.len(), 2u);
nham7b310582014-08-26 19:45:55551 d.push(4);
Corey Richardsoncc57ca02013-05-19 02:02:45552 assert_eq!(d.len(), 3u);
blake2-ppc70523712013-07-10 13:27:14553 d.push_front(1);
Corey Richardsoncc57ca02013-05-19 02:02:45554 assert_eq!(d.len(), 4u);
Alex Crichton9d5d97b2014-10-15 06:05:01555 debug!("{}", d[0]);
556 debug!("{}", d[1]);
557 debug!("{}", d[2]);
558 debug!("{}", d[3]);
559 assert_eq!(d[0], 1);
560 assert_eq!(d[1], 2);
561 assert_eq!(d[2], 3);
562 assert_eq!(d[3], 4);
Brian Anderson6e27b272012-01-18 03:05:07563 }
564
Felix S. Klock IIa636f512013-05-01 23:32:37565 #[cfg(test)]
Alex Crichton748bc3c2014-05-30 00:45:07566 fn test_parameterized<T:Clone + PartialEq + Show>(a: T, b: T, c: T, d: T) {
Patrick Waltondc4bf172013-07-13 04:05:59567 let mut deq = RingBuf::new();
Corey Richardsoncc57ca02013-05-19 02:02:45568 assert_eq!(deq.len(), 0);
Patrick Waltondc4bf172013-07-13 04:05:59569 deq.push_front(a.clone());
570 deq.push_front(b.clone());
nham7b310582014-08-26 19:45:55571 deq.push(c.clone());
Corey Richardsoncc57ca02013-05-19 02:02:45572 assert_eq!(deq.len(), 3);
nham7b310582014-08-26 19:45:55573 deq.push(d.clone());
Corey Richardsoncc57ca02013-05-19 02:02:45574 assert_eq!(deq.len(), 4);
Marvin Löbel0ac7a212013-08-03 23:59:24575 assert_eq!((*deq.front().unwrap()).clone(), b.clone());
576 assert_eq!((*deq.back().unwrap()).clone(), d.clone());
577 assert_eq!(deq.pop_front().unwrap(), b.clone());
nham7b310582014-08-26 19:45:55578 assert_eq!(deq.pop().unwrap(), d.clone());
579 assert_eq!(deq.pop().unwrap(), c.clone());
580 assert_eq!(deq.pop().unwrap(), a.clone());
Corey Richardsoncc57ca02013-05-19 02:02:45581 assert_eq!(deq.len(), 0);
nham7b310582014-08-26 19:45:55582 deq.push(c.clone());
Corey Richardsoncc57ca02013-05-19 02:02:45583 assert_eq!(deq.len(), 1);
Patrick Waltondc4bf172013-07-13 04:05:59584 deq.push_front(b.clone());
Corey Richardsoncc57ca02013-05-19 02:02:45585 assert_eq!(deq.len(), 2);
nham7b310582014-08-26 19:45:55586 deq.push(d.clone());
Corey Richardsoncc57ca02013-05-19 02:02:45587 assert_eq!(deq.len(), 3);
Patrick Waltondc4bf172013-07-13 04:05:59588 deq.push_front(a.clone());
Corey Richardsoncc57ca02013-05-19 02:02:45589 assert_eq!(deq.len(), 4);
NODA, Kaif27ad3d2014-10-05 10:11:17590 assert_eq!(deq[0].clone(), a.clone());
591 assert_eq!(deq[1].clone(), b.clone());
592 assert_eq!(deq[2].clone(), c.clone());
593 assert_eq!(deq[3].clone(), d.clone());
Brian Anderson6e27b272012-01-18 03:05:07594 }
595
blake2-ppc81933ed2013-07-06 03:42:45596 #[test]
blake2-ppc70523712013-07-10 13:27:14597 fn test_push_front_grow() {
598 let mut deq = RingBuf::new();
Daniel Micay100894552013-08-03 16:45:23599 for i in range(0u, 66) {
blake2-ppc70523712013-07-10 13:27:14600 deq.push_front(i);
blake2-ppc81933ed2013-07-06 03:42:45601 }
602 assert_eq!(deq.len(), 66);
603
Daniel Micay100894552013-08-03 16:45:23604 for i in range(0u, 66) {
NODA, Kaif27ad3d2014-10-05 10:11:17605 assert_eq!(deq[i], 65 - i);
blake2-ppc81933ed2013-07-06 03:42:45606 }
607
blake2-ppc70523712013-07-10 13:27:14608 let mut deq = RingBuf::new();
Daniel Micay100894552013-08-03 16:45:23609 for i in range(0u, 66) {
nham7b310582014-08-26 19:45:55610 deq.push(i);
blake2-ppc81933ed2013-07-06 03:42:45611 }
612
Daniel Micay100894552013-08-03 16:45:23613 for i in range(0u, 66) {
NODA, Kaif27ad3d2014-10-05 10:11:17614 assert_eq!(deq[i], i);
blake2-ppc81933ed2013-07-06 03:42:45615 }
616 }
617
P1startfd10d202014-08-02 06:39:39618 #[test]
619 fn test_index() {
620 let mut deq = RingBuf::new();
621 for i in range(1u, 4) {
622 deq.push_front(i);
623 }
624 assert_eq!(deq[1], 2);
625 }
626
627 #[test]
628 #[should_fail]
629 fn test_index_out_of_bounds() {
630 let mut deq = RingBuf::new();
631 for i in range(1u, 4) {
632 deq.push_front(i);
633 }
634 deq[3];
635 }
636
blake2-ppc81933ed2013-07-06 03:42:45637 #[bench]
Liigo Zhuang408f4842014-04-01 01:16:35638 fn bench_new(b: &mut test::Bencher) {
Patrick Walton38efa172013-11-22 03:20:48639 b.iter(|| {
Patrick Walton86939432013-08-08 18:38:10640 let _: RingBuf<u64> = RingBuf::new();
Patrick Walton38efa172013-11-22 03:20:48641 })
blake2-ppc81933ed2013-07-06 03:42:45642 }
643
644 #[bench]
Liigo Zhuang408f4842014-04-01 01:16:35645 fn bench_push_back(b: &mut test::Bencher) {
blake2-ppc70523712013-07-10 13:27:14646 let mut deq = RingBuf::new();
Patrick Walton38efa172013-11-22 03:20:48647 b.iter(|| {
nham7b310582014-08-26 19:45:55648 deq.push(0i);
Patrick Walton38efa172013-11-22 03:20:48649 })
blake2-ppc81933ed2013-07-06 03:42:45650 }
651
652 #[bench]
Liigo Zhuang408f4842014-04-01 01:16:35653 fn bench_push_front(b: &mut test::Bencher) {
blake2-ppc70523712013-07-10 13:27:14654 let mut deq = RingBuf::new();
Patrick Walton38efa172013-11-22 03:20:48655 b.iter(|| {
Patrick Waltona5bb0a32014-06-27 19:30:25656 deq.push_front(0i);
Patrick Walton38efa172013-11-22 03:20:48657 })
blake2-ppc81933ed2013-07-06 03:42:45658 }
659
660 #[bench]
Liigo Zhuang408f4842014-04-01 01:16:35661 fn bench_grow(b: &mut test::Bencher) {
blake2-ppc70523712013-07-10 13:27:14662 let mut deq = RingBuf::new();
Patrick Walton38efa172013-11-22 03:20:48663 b.iter(|| {
Niko Matsakis9e3d0b02014-04-21 21:58:52664 for _ in range(0i, 65) {
Patrick Waltona5bb0a32014-06-27 19:30:25665 deq.push_front(1i);
Brendan Zabarauskas729060d2014-01-30 00:20:34666 }
Patrick Walton38efa172013-11-22 03:20:48667 })
blake2-ppc81933ed2013-07-06 03:42:45668 }
669
Alex Crichton748bc3c2014-05-30 00:45:07670 #[deriving(Clone, PartialEq, Show)]
Patrick Walton99b33f72013-07-02 19:47:32671 enum Taggy {
672 One(int),
673 Two(int, int),
674 Three(int, int, int),
Brian Anderson6e27b272012-01-18 03:05:07675 }
676
Alex Crichton748bc3c2014-05-30 00:45:07677 #[deriving(Clone, PartialEq, Show)]
Patrick Walton99b33f72013-07-02 19:47:32678 enum Taggypar<T> {
679 Onepar(int),
680 Twopar(int, int),
681 Threepar(int, int, int),
682 }
683
Alex Crichton748bc3c2014-05-30 00:45:07684 #[deriving(Clone, PartialEq, Show)]
Erick Tryzelaare84576b2013-01-22 16:44:24685 struct RecCy {
686 x: int,
687 y: int,
Patrick Waltoneb4d39e2013-01-26 00:57:39688 t: Taggy
Patrick Walton9117dcb2012-09-20 01:00:26689 }
Kevin Cantuc43426e2012-09-13 05:09:55690
691 #[test]
692 fn test_param_int() {
693 test_parameterized::<int>(5, 72, 64, 175);
694 }
695
696 #[test]
Kevin Cantuc43426e2012-09-13 05:09:55697 fn test_param_taggy() {
Corey Richardsonf8ae9b02013-06-26 22:14:35698 test_parameterized::<Taggy>(One(1), Two(1, 2), Three(1, 2, 3), Two(17, 42));
Kevin Cantuc43426e2012-09-13 05:09:55699 }
700
701 #[test]
702 fn test_param_taggypar() {
703 test_parameterized::<Taggypar<int>>(Onepar::<int>(1),
Ben Striegela605fd02012-08-11 14:08:42704 Twopar::<int>(1, 2),
705 Threepar::<int>(1, 2, 3),
706 Twopar::<int>(17, 42));
Kevin Cantuc43426e2012-09-13 05:09:55707 }
Brian Anderson6e27b272012-01-18 03:05:07708
Kevin Cantuc43426e2012-09-13 05:09:55709 #[test]
710 fn test_param_reccy() {
Erick Tryzelaare84576b2013-01-22 16:44:24711 let reccy1 = RecCy { x: 1, y: 2, t: One(1) };
712 let reccy2 = RecCy { x: 345, y: 2, t: Two(1, 2) };
713 let reccy3 = RecCy { x: 1, y: 777, t: Three(1, 2, 3) };
714 let reccy4 = RecCy { x: 19, y: 252, t: Two(17, 42) };
Kevin Cantuc43426e2012-09-13 05:09:55715 test_parameterized::<RecCy>(reccy1, reccy2, reccy3, reccy4);
Brian Anderson6e27b272012-01-18 03:05:07716 }
Erick Tryzelaar909d8f02013-03-30 01:02:44717
718 #[test]
blake2-ppc0ff5c172013-07-06 03:42:45719 fn test_with_capacity() {
blake2-ppc70523712013-07-10 13:27:14720 let mut d = RingBuf::with_capacity(0);
nham7b310582014-08-26 19:45:55721 d.push(1i);
blake2-ppc0ff5c172013-07-06 03:42:45722 assert_eq!(d.len(), 1);
blake2-ppc70523712013-07-10 13:27:14723 let mut d = RingBuf::with_capacity(50);
nham7b310582014-08-26 19:45:55724 d.push(1i);
blake2-ppc0ff5c172013-07-06 03:42:45725 assert_eq!(d.len(), 1);
726 }
727
728 #[test]
Kevin Butler64896d62014-08-07 01:11:13729 fn test_with_capacity_non_power_two() {
730 let mut d3 = RingBuf::with_capacity(3);
731 d3.push(1i);
732
733 // X = None, | = lo
734 // [|1, X, X]
735 assert_eq!(d3.pop_front(), Some(1));
736 // [X, |X, X]
737 assert_eq!(d3.front(), None);
738
739 // [X, |3, X]
740 d3.push(3);
741 // [X, |3, 6]
742 d3.push(6);
743 // [X, X, |6]
744 assert_eq!(d3.pop_front(), Some(3));
745
746 // Pushing the lo past half way point to trigger
747 // the 'B' scenario for growth
748 // [9, X, |6]
749 d3.push(9);
750 // [9, 12, |6]
751 d3.push(12);
752
753 d3.push(15);
754 // There used to be a bug here about how the
755 // RingBuf made growth assumptions about the
756 // underlying Vec which didn't hold and lead
757 // to corruption.
758 // (Vec grows to next power of two)
759 //good- [9, 12, 15, X, X, X, X, |6]
760 //bug- [15, 12, X, X, X, |6, X, X]
761 assert_eq!(d3.pop_front(), Some(6));
762
763 // Which leads us to the following state which
764 // would be a failure case.
765 //bug- [15, 12, X, X, X, X, |X, X]
766 assert_eq!(d3.front(), Some(&9));
767 }
768
769 #[test]
David Manescu65f35782014-01-31 13:03:20770 fn test_reserve_exact() {
blake2-ppc70523712013-07-10 13:27:14771 let mut d = RingBuf::new();
nham7b310582014-08-26 19:45:55772 d.push(0u64);
David Manescu65f35782014-01-31 13:03:20773 d.reserve_exact(50);
Huon Wilson32d65592013-06-27 14:40:47774 assert_eq!(d.elts.capacity(), 50);
blake2-ppc70523712013-07-10 13:27:14775 let mut d = RingBuf::new();
nham7b310582014-08-26 19:45:55776 d.push(0u32);
David Manescu65f35782014-01-31 13:03:20777 d.reserve_exact(50);
Huon Wilson32d65592013-06-27 14:40:47778 assert_eq!(d.elts.capacity(), 50);
Tim Chevalier77de84b2013-05-27 18:47:38779 }
780
781 #[test]
David Manescu65f35782014-01-31 13:03:20782 fn test_reserve() {
blake2-ppc70523712013-07-10 13:27:14783 let mut d = RingBuf::new();
nham7b310582014-08-26 19:45:55784 d.push(0u64);
David Manescu65f35782014-01-31 13:03:20785 d.reserve(50);
Huon Wilson32d65592013-06-27 14:40:47786 assert_eq!(d.elts.capacity(), 64);
blake2-ppc70523712013-07-10 13:27:14787 let mut d = RingBuf::new();
nham7b310582014-08-26 19:45:55788 d.push(0u32);
David Manescu65f35782014-01-31 13:03:20789 d.reserve(50);
Huon Wilson32d65592013-06-27 14:40:47790 assert_eq!(d.elts.capacity(), 64);
Tim Chevalier77de84b2013-05-27 18:47:38791 }
792
Jed Estep096fb792013-06-26 14:04:44793 #[test]
blake2-ppc57757a82013-09-26 07:19:26794 fn test_swap() {
Niko Matsakis9e3d0b02014-04-21 21:58:52795 let mut d: RingBuf<int> = range(0i, 5).collect();
blake2-ppc57757a82013-09-26 07:19:26796 d.pop_front();
797 d.swap(0, 3);
Huon Wilson4b9a7a22014-04-05 05:45:42798 assert_eq!(d.iter().map(|&x|x).collect::<Vec<int>>(), vec!(4, 2, 3, 1));
blake2-ppc57757a82013-09-26 07:19:26799 }
800
801 #[test]
Jed Estep096fb792013-06-26 14:04:44802 fn test_iter() {
blake2-ppc70523712013-07-10 13:27:14803 let mut d = RingBuf::new();
blake2-ppcf88d5322013-07-06 03:42:45804 assert_eq!(d.iter().next(), None);
blake2-ppc9ccf4432013-07-14 20:30:22805 assert_eq!(d.iter().size_hint(), (0, Some(0)));
blake2-ppcf88d5322013-07-06 03:42:45806
Niko Matsakis9e3d0b02014-04-21 21:58:52807 for i in range(0i, 5) {
nham7b310582014-08-26 19:45:55808 d.push(i);
Jed Estep096fb792013-06-26 14:04:44809 }
Nick Cameron37a94b82014-08-04 12:19:02810 {
811 let b: &[_] = &[&0,&1,&2,&3,&4];
812 assert_eq!(d.iter().collect::<Vec<&int>>().as_slice(), b);
813 }
Corey Richardsonf8ae9b02013-06-26 22:14:35814
Niko Matsakis9e3d0b02014-04-21 21:58:52815 for i in range(6i, 9) {
blake2-ppc70523712013-07-10 13:27:14816 d.push_front(i);
Jed Estep096fb792013-06-26 14:04:44817 }
Nick Cameron37a94b82014-08-04 12:19:02818 {
819 let b: &[_] = &[&8,&7,&6,&0,&1,&2,&3,&4];
820 assert_eq!(d.iter().collect::<Vec<&int>>().as_slice(), b);
821 }
blake2-ppc9ccf4432013-07-14 20:30:22822
823 let mut it = d.iter();
824 let mut len = d.len();
825 loop {
826 match it.next() {
827 None => break,
828 _ => { len -= 1; assert_eq!(it.size_hint(), (len, Some(len))) }
829 }
830 }
Jed Estep096fb792013-06-26 14:04:44831 }
832
833 #[test]
834 fn test_rev_iter() {
blake2-ppc70523712013-07-10 13:27:14835 let mut d = RingBuf::new();
Jonathan S03609e52014-04-21 04:59:12836 assert_eq!(d.iter().rev().next(), None);
blake2-ppcf88d5322013-07-06 03:42:45837
Niko Matsakis9e3d0b02014-04-21 21:58:52838 for i in range(0i, 5) {
nham7b310582014-08-26 19:45:55839 d.push(i);
Jed Estep096fb792013-06-26 14:04:44840 }
Nick Cameron37a94b82014-08-04 12:19:02841 {
842 let b: &[_] = &[&4,&3,&2,&1,&0];
843 assert_eq!(d.iter().rev().collect::<Vec<&int>>().as_slice(), b);
844 }
Corey Richardsonf8ae9b02013-06-26 22:14:35845
Niko Matsakis9e3d0b02014-04-21 21:58:52846 for i in range(6i, 9) {
blake2-ppc70523712013-07-10 13:27:14847 d.push_front(i);
Jed Estep096fb792013-06-26 14:04:44848 }
Nick Cameron37a94b82014-08-04 12:19:02849 let b: &[_] = &[&4,&3,&2,&1,&0,&6,&7,&8];
850 assert_eq!(d.iter().rev().collect::<Vec<&int>>().as_slice(), b);
Jed Estep096fb792013-06-26 14:04:44851 }
blake2-ppc08dc72f2013-07-06 03:42:45852
853 #[test]
Niko Matsakisbc4164d2013-11-16 22:29:39854 fn test_mut_rev_iter_wrap() {
855 let mut d = RingBuf::with_capacity(3);
Aaron Turonfc525ee2014-09-15 03:27:36856 assert!(d.iter_mut().rev().next().is_none());
Niko Matsakisbc4164d2013-11-16 22:29:39857
nham7b310582014-08-26 19:45:55858 d.push(1i);
859 d.push(2);
860 d.push(3);
Niko Matsakisbc4164d2013-11-16 22:29:39861 assert_eq!(d.pop_front(), Some(1));
nham7b310582014-08-26 19:45:55862 d.push(4);
Niko Matsakisbc4164d2013-11-16 22:29:39863
Aaron Turonfc525ee2014-09-15 03:27:36864 assert_eq!(d.iter_mut().rev().map(|x| *x).collect::<Vec<int>>(),
Huon Wilson4b9a7a22014-04-05 05:45:42865 vec!(4, 3, 2));
Niko Matsakisbc4164d2013-11-16 22:29:39866 }
867
868 #[test]
blake2-ppcf88d5322013-07-06 03:42:45869 fn test_mut_iter() {
blake2-ppc70523712013-07-10 13:27:14870 let mut d = RingBuf::new();
Aaron Turonfc525ee2014-09-15 03:27:36871 assert!(d.iter_mut().next().is_none());
blake2-ppcf88d5322013-07-06 03:42:45872
Daniel Micay100894552013-08-03 16:45:23873 for i in range(0u, 3) {
blake2-ppc70523712013-07-10 13:27:14874 d.push_front(i);
blake2-ppcf88d5322013-07-06 03:42:45875 }
876
Aaron Turonfc525ee2014-09-15 03:27:36877 for (i, elt) in d.iter_mut().enumerate() {
blake2-ppcf88d5322013-07-06 03:42:45878 assert_eq!(*elt, 2 - i);
879 *elt = i;
880 }
881
882 {
Aaron Turonfc525ee2014-09-15 03:27:36883 let mut it = d.iter_mut();
blake2-ppcf88d5322013-07-06 03:42:45884 assert_eq!(*it.next().unwrap(), 0);
885 assert_eq!(*it.next().unwrap(), 1);
886 assert_eq!(*it.next().unwrap(), 2);
887 assert!(it.next().is_none());
888 }
889 }
890
891 #[test]
892 fn test_mut_rev_iter() {
blake2-ppc70523712013-07-10 13:27:14893 let mut d = RingBuf::new();
Aaron Turonfc525ee2014-09-15 03:27:36894 assert!(d.iter_mut().rev().next().is_none());
blake2-ppcf88d5322013-07-06 03:42:45895
Daniel Micay100894552013-08-03 16:45:23896 for i in range(0u, 3) {
blake2-ppc70523712013-07-10 13:27:14897 d.push_front(i);
blake2-ppcf88d5322013-07-06 03:42:45898 }
899
Aaron Turonfc525ee2014-09-15 03:27:36900 for (i, elt) in d.iter_mut().rev().enumerate() {
blake2-ppcf88d5322013-07-06 03:42:45901 assert_eq!(*elt, i);
902 *elt = i;
903 }
904
905 {
Aaron Turonfc525ee2014-09-15 03:27:36906 let mut it = d.iter_mut().rev();
blake2-ppcf88d5322013-07-06 03:42:45907 assert_eq!(*it.next().unwrap(), 0);
908 assert_eq!(*it.next().unwrap(), 1);
909 assert_eq!(*it.next().unwrap(), 2);
910 assert!(it.next().is_none());
911 }
912 }
913
914 #[test]
Brian Andersonee052192014-03-31 04:45:55915 fn test_from_iter() {
Daniel Micay6919cf52013-09-08 15:01:16916 use std::iter;
Niko Matsakis9e3d0b02014-04-21 21:58:52917 let v = vec!(1i,2,3,4,5,6,7);
Erick Tryzelaar68f40d22013-08-10 03:09:47918 let deq: RingBuf<int> = v.iter().map(|&x| x).collect();
Huon Wilson4b9a7a22014-04-05 05:45:42919 let u: Vec<int> = deq.iter().map(|&x| x).collect();
blake2-ppc08dc72f2013-07-06 03:42:45920 assert_eq!(u, v);
921
Daniel Micay6919cf52013-09-08 15:01:16922 let mut seq = iter::count(0u, 2).take(256);
blake2-ppc70523712013-07-10 13:27:14923 let deq: RingBuf<uint> = seq.collect();
Daniel Micay100894552013-08-03 16:45:23924 for (i, &x) in deq.iter().enumerate() {
blake2-ppc08dc72f2013-07-06 03:42:45925 assert_eq!(2*i, x);
926 }
927 assert_eq!(deq.len(), 256);
928 }
blake2-ppc10c76982013-07-06 13:27:32929
930 #[test]
931 fn test_clone() {
blake2-ppc70523712013-07-10 13:27:14932 let mut d = RingBuf::new();
Niko Matsakis9e3d0b02014-04-21 21:58:52933 d.push_front(17i);
blake2-ppc70523712013-07-10 13:27:14934 d.push_front(42);
nham7b310582014-08-26 19:45:55935 d.push(137);
936 d.push(137);
blake2-ppc10c76982013-07-06 13:27:32937 assert_eq!(d.len(), 4u);
938 let mut e = d.clone();
939 assert_eq!(e.len(), 4u);
940 while !d.is_empty() {
nham7b310582014-08-26 19:45:55941 assert_eq!(d.pop(), e.pop());
blake2-ppc10c76982013-07-06 13:27:32942 }
943 assert_eq!(d.len(), 0u);
944 assert_eq!(e.len(), 0u);
945 }
946
947 #[test]
948 fn test_eq() {
blake2-ppc70523712013-07-10 13:27:14949 let mut d = RingBuf::new();
Alex Crichton02882fb2014-02-28 09:23:06950 assert!(d == RingBuf::with_capacity(0));
Niko Matsakis9e3d0b02014-04-21 21:58:52951 d.push_front(137i);
blake2-ppc70523712013-07-10 13:27:14952 d.push_front(17);
953 d.push_front(42);
nham7b310582014-08-26 19:45:55954 d.push(137);
blake2-ppc70523712013-07-10 13:27:14955 let mut e = RingBuf::with_capacity(0);
nham7b310582014-08-26 19:45:55956 e.push(42);
957 e.push(17);
958 e.push(137);
959 e.push(137);
Alex Crichton02882fb2014-02-28 09:23:06960 assert!(&e == &d);
nham7b310582014-08-26 19:45:55961 e.pop();
962 e.push(0);
blake2-ppc10c76982013-07-06 13:27:32963 assert!(e != d);
964 e.clear();
Alex Crichton02882fb2014-02-28 09:23:06965 assert!(e == RingBuf::new());
blake2-ppc10c76982013-07-06 13:27:32966 }
Adolfo Ochagavía8e4e3ab2014-06-04 14:15:04967
968 #[test]
nham1cfa6562014-07-27 02:33:47969 fn test_hash() {
970 let mut x = RingBuf::new();
971 let mut y = RingBuf::new();
972
973 x.push(1i);
974 x.push(2);
975 x.push(3);
976
977 y.push(0i);
978 y.push(1i);
979 y.pop_front();
980 y.push(2);
981 y.push(3);
982
983 assert!(hash::hash(&x) == hash::hash(&y));
984 }
985
986 #[test]
nham63615772014-07-27 03:18:56987 fn test_ord() {
988 let x = RingBuf::new();
989 let mut y = RingBuf::new();
990 y.push(1i);
991 y.push(2);
992 y.push(3);
993 assert!(x < y);
994 assert!(y > x);
995 assert!(x <= x);
996 assert!(x >= x);
997 }
998
999 #[test]
Adolfo Ochagavía8e4e3ab2014-06-04 14:15:041000 fn test_show() {
Niko Matsakis9e3d0b02014-04-21 21:58:521001 let ringbuf: RingBuf<int> = range(0i, 10).collect();
Adolfo Ochagavía8e4e3ab2014-06-04 14:15:041002 assert!(format!("{}", ringbuf).as_slice() == "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]");
1003
1004 let ringbuf: RingBuf<&str> = vec!["just", "one", "test", "more"].iter()
1005 .map(|&s| s)
1006 .collect();
1007 assert!(format!("{}", ringbuf).as_slice() == "[just, one, test, more]");
1008 }
Michael Sullivanc854d6e2012-07-03 17:52:321009}