blob: 3c4c3fce61d774835fb0b482c1763ca4fe6b9699 [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
Alex Crichton6a585372014-05-30 01:50:1225use vec::Vec;
blake2-ppc70523712013-07-10 13:27:1426
blake2-ppc0ff5c172013-07-06 03:42:4527static INITIAL_CAPACITY: uint = 8u; // 2^3
28static MINIMUM_CAPACITY: uint = 2u;
Daniel Micayb47e1e92013-02-16 22:55:5529
P1startf2aa88c2014-08-04 10:48:3930/// `RingBuf` is a circular buffer that implements `Deque`.
blake2-ppc10c76982013-07-06 13:27:3231#[deriving(Clone)]
blake2-ppc70523712013-07-10 13:27:1432pub struct RingBuf<T> {
Alex Crichton8ad7e542014-03-27 22:10:0433 nelts: uint,
34 lo: uint,
Huon Wilson4b9a7a22014-04-05 05:45:4235 elts: Vec<Option<T>>
Marijn Haverbeke26610db2012-01-11 11:49:3336}
Roy Frostig9c818892010-07-21 01:03:0937
Tom Jakubowskid6a39412014-06-09 07:30:0438impl<T> Default for RingBuf<T> {
39 #[inline]
40 fn default() -> RingBuf<T> { RingBuf::new() }
41}
42
blake2-ppc70523712013-07-10 13:27:1443impl<T> RingBuf<T> {
P1startf2aa88c2014-08-04 10:48:3944 /// Creates an empty `RingBuf`.
blake2-ppc70523712013-07-10 13:27:1445 pub fn new() -> RingBuf<T> {
46 RingBuf::with_capacity(INITIAL_CAPACITY)
47 }
48
P1startf2aa88c2014-08-04 10:48:3949 /// Creates an empty `RingBuf` with space for at least `n` elements.
blake2-ppc70523712013-07-10 13:27:1450 pub fn with_capacity(n: uint) -> RingBuf<T> {
51 RingBuf{nelts: 0, lo: 0,
Huon Wilson4b9a7a22014-04-05 05:45:4252 elts: Vec::from_fn(cmp::max(MINIMUM_CAPACITY, n), |_| None)}
blake2-ppc70523712013-07-10 13:27:1453 }
54
P1startf2aa88c2014-08-04 10:48:3955 /// Retrieves an element in the `RingBuf` by index.
blake2-ppc70523712013-07-10 13:27:1456 ///
P1startf2aa88c2014-08-04 10:48:3957 /// Fails if there is no element with the given index.
nhamebe80972014-07-17 23:19:5158 ///
59 /// # Example
60 ///
61 /// ```rust
Alex Crichton1d356622014-10-23 15:42:2162 /// # #![allow(deprecated)]
nhamebe80972014-07-17 23:19:5163 /// use std::collections::RingBuf;
64 ///
65 /// let mut buf = RingBuf::new();
66 /// buf.push(3i);
67 /// buf.push(4);
68 /// buf.push(5);
69 /// *buf.get_mut(1) = 7;
P1startfd10d202014-08-02 06:39:3970 /// assert_eq!(buf[1], 7);
nhamebe80972014-07-17 23:19:5171 /// ```
Alex Crichton1d356622014-10-23 15:42:2172 #[deprecated = "use indexing instead: `buf[index] = value`"]
Alex Crichton21ac9852014-10-30 20:43:2473 pub fn get_mut(&mut self, i: uint) -> &mut T {
Alex Crichton1d356622014-10-23 15:42:2174 &mut self[i]
blake2-ppc70523712013-07-10 13:27:1475 }
76
P1startf2aa88c2014-08-04 10:48:3977 /// Swaps elements at indices `i` and `j`.
blake2-ppc57757a82013-09-26 07:19:2678 ///
79 /// `i` and `j` may be equal.
80 ///
P1startf2aa88c2014-08-04 10:48:3981 /// Fails if there is no element with either index.
nhamebe80972014-07-17 23:19:5182 ///
83 /// # Example
84 ///
85 /// ```rust
86 /// use std::collections::RingBuf;
87 ///
88 /// let mut buf = RingBuf::new();
89 /// buf.push(3i);
90 /// buf.push(4);
91 /// buf.push(5);
92 /// buf.swap(0, 2);
P1startfd10d202014-08-02 06:39:3993 /// assert_eq!(buf[0], 5);
94 /// assert_eq!(buf[2], 3);
nhamebe80972014-07-17 23:19:5195 /// ```
blake2-ppc57757a82013-09-26 07:19:2696 pub fn swap(&mut self, i: uint, j: uint) {
97 assert!(i < self.len());
98 assert!(j < self.len());
99 let ri = self.raw_index(i);
100 let rj = self.raw_index(j);
Huon Wilson4b9a7a22014-04-05 05:45:42101 self.elts.as_mut_slice().swap(ri, rj);
blake2-ppc57757a82013-09-26 07:19:26102 }
103
P1startf2aa88c2014-08-04 10:48:39104 /// Returns the index in the underlying `Vec` for a given logical element
105 /// index.
blake2-ppc70523712013-07-10 13:27:14106 fn raw_index(&self, idx: uint) -> uint {
107 raw_index(self.lo, self.elts.len(), idx)
108 }
109
P1startf2aa88c2014-08-04 10:48:39110 /// Reserves capacity for exactly `n` elements in the given `RingBuf`,
Tim Chevalier77de84b2013-05-27 18:47:38111 /// doing nothing if `self`'s capacity is already equal to or greater
P1startf2aa88c2014-08-04 10:48:39112 /// than the requested capacity.
David Manescu65f35782014-01-31 13:03:20113 pub fn reserve_exact(&mut self, n: uint) {
114 self.elts.reserve_exact(n);
Tim Chevalier77de84b2013-05-27 18:47:38115 }
116
P1startf2aa88c2014-08-04 10:48:39117 /// Reserves capacity for at least `n` elements in the given `RingBuf`,
Tim Chevalier77de84b2013-05-27 18:47:38118 /// over-allocating in case the caller needs to reserve additional
119 /// space.
120 ///
121 /// Do nothing if `self`'s capacity is already equal to or greater
122 /// than the requested capacity.
David Manescu65f35782014-01-31 13:03:20123 pub fn reserve(&mut self, n: uint) {
124 self.elts.reserve(n);
Tim Chevalier77de84b2013-05-27 18:47:38125 }
Jed Estep4f7a7422013-06-25 19:08:47126
P1startf2aa88c2014-08-04 10:48:39127 /// Returns a front-to-back iterator.
nhamebe80972014-07-17 23:19:51128 ///
129 /// # Example
130 ///
131 /// ```rust
132 /// use std::collections::RingBuf;
133 ///
134 /// let mut buf = RingBuf::new();
135 /// buf.push(5i);
136 /// buf.push(3);
137 /// buf.push(4);
Nick Cameron52ef4622014-08-06 09:59:40138 /// let b: &[_] = &[&5, &3, &4];
139 /// assert_eq!(buf.iter().collect::<Vec<&int>>().as_slice(), b);
nhamebe80972014-07-17 23:19:51140 /// ```
Alex Crichton21ac9852014-10-30 20:43:24141 pub fn iter(&self) -> Items<T> {
Huon Wilson4b9a7a22014-04-05 05:45:42142 Items{index: 0, rindex: self.nelts, lo: self.lo, elts: self.elts.as_slice()}
blake2-ppc3385e792013-07-15 23:13:26143 }
144
P1startf2aa88c2014-08-04 10:48:39145 /// Returns a front-to-back iterator which returns mutable references.
nhamebe80972014-07-17 23:19:51146 ///
147 /// # Example
148 ///
149 /// ```rust
150 /// use std::collections::RingBuf;
151 ///
152 /// let mut buf = RingBuf::new();
153 /// buf.push(5i);
154 /// buf.push(3);
155 /// buf.push(4);
Aaron Turonfc525ee2014-09-15 03:27:36156 /// for num in buf.iter_mut() {
nhamebe80972014-07-17 23:19:51157 /// *num = *num - 2;
158 /// }
Nick Cameron52ef4622014-08-06 09:59:40159 /// let b: &[_] = &[&mut 3, &mut 1, &mut 2];
Nick Cameron59976942014-09-24 11:41:09160 /// assert_eq!(buf.iter_mut().collect::<Vec<&mut int>>()[], b);
nhamebe80972014-07-17 23:19:51161 /// ```
Alex Crichton21ac9852014-10-30 20:43:24162 pub fn iter_mut(&mut self) -> MutItems<T> {
Niko Matsakisbc4164d2013-11-16 22:29:39163 let start_index = raw_index(self.lo, self.elts.len(), 0);
164 let end_index = raw_index(self.lo, self.elts.len(), self.nelts);
165
166 // Divide up the array
167 if end_index <= start_index {
168 // Items to iterate goes from:
169 // start_index to self.elts.len()
170 // and then
171 // 0 to end_index
Aaron Turonfc525ee2014-09-15 03:27:36172 let (temp, remaining1) = self.elts.split_at_mut(start_index);
173 let (remaining2, _) = temp.split_at_mut(end_index);
Alex Crichton9d5d97b2014-10-15 06:05:01174 MutItems {
175 remaining1: remaining1.iter_mut(),
176 remaining2: remaining2.iter_mut(),
177 nelts: self.nelts,
178 }
Niko Matsakisbc4164d2013-11-16 22:29:39179 } else {
180 // Items to iterate goes from start_index to end_index:
Aaron Turonfc525ee2014-09-15 03:27:36181 let (empty, elts) = self.elts.split_at_mut(0);
Nick Cameron59976942014-09-24 11:41:09182 let remaining1 = elts[mut start_index..end_index];
Alex Crichton9d5d97b2014-10-15 06:05:01183 MutItems {
184 remaining1: remaining1.iter_mut(),
185 remaining2: empty.iter_mut(),
186 nelts: self.nelts,
187 }
Niko Matsakisbc4164d2013-11-16 22:29:39188 }
Jed Estep4f7a7422013-06-25 19:08:47189 }
Alex Crichton21ac9852014-10-30 20:43:24190
191 /// Returns the number of elements in the `RingBuf`.
192 ///
193 /// # Example
194 ///
195 /// ```
196 /// use std::collections::RingBuf;
197 ///
198 /// let mut v = RingBuf::new();
199 /// assert_eq!(v.len(), 0);
200 /// v.push(1i);
201 /// assert_eq!(v.len(), 1);
202 /// ```
203 pub fn len(&self) -> uint { self.nelts }
204
205 /// Returns true if the buffer contains no elements
206 ///
207 /// # Example
208 ///
209 /// ```
210 /// use std::collections::RingBuf;
211 ///
212 /// let mut v = RingBuf::new();
213 /// assert!(v.is_empty());
214 /// v.push_front(1i);
215 /// assert!(!v.is_empty());
216 /// ```
217 pub fn is_empty(&self) -> bool { self.len() == 0 }
218
219 /// Clears the buffer, removing all values.
220 ///
221 /// # Example
222 ///
223 /// ```
224 /// use std::collections::RingBuf;
225 ///
226 /// let mut v = RingBuf::new();
227 /// v.push(1i);
228 /// v.clear();
229 /// assert!(v.is_empty());
230 /// ```
231 pub fn clear(&mut self) {
232 for x in self.elts.iter_mut() { *x = None }
233 self.nelts = 0;
234 self.lo = 0;
235 }
236
237 /// Provides a reference to the front element, or `None` if the sequence is
238 /// empty.
239 ///
240 /// # Example
241 ///
242 /// ```
243 /// use std::collections::RingBuf;
244 ///
245 /// let mut d = RingBuf::new();
246 /// assert_eq!(d.front(), None);
247 ///
248 /// d.push(1i);
249 /// d.push(2i);
250 /// assert_eq!(d.front(), Some(&1i));
251 /// ```
252 pub fn front(&self) -> Option<&T> {
253 if self.nelts > 0 { Some(&self[0]) } else { None }
254 }
255
256 /// Provides a mutable reference to the front element, or `None` if the
257 /// sequence is empty.
258 ///
259 /// # Example
260 ///
261 /// ```
262 /// use std::collections::RingBuf;
263 ///
264 /// let mut d = RingBuf::new();
265 /// assert_eq!(d.front_mut(), None);
266 ///
267 /// d.push(1i);
268 /// d.push(2i);
269 /// match d.front_mut() {
270 /// Some(x) => *x = 9i,
271 /// None => (),
272 /// }
273 /// assert_eq!(d.front(), Some(&9i));
274 /// ```
275 pub fn front_mut(&mut self) -> Option<&mut T> {
276 if self.nelts > 0 { Some(&mut self[0]) } else { None }
277 }
278
279 /// Provides a reference to the back element, or `None` if the sequence is
280 /// empty.
281 ///
282 /// # Example
283 ///
284 /// ```
285 /// use std::collections::RingBuf;
286 ///
287 /// let mut d = RingBuf::new();
288 /// assert_eq!(d.back(), None);
289 ///
290 /// d.push(1i);
291 /// d.push(2i);
292 /// assert_eq!(d.back(), Some(&2i));
293 /// ```
294 pub fn back(&self) -> Option<&T> {
295 if self.nelts > 0 { Some(&self[self.nelts - 1]) } else { None }
296 }
297
298 /// Provides a mutable reference to the back element, or `None` if the
299 /// sequence is empty.
300 ///
301 /// # Example
302 ///
303 /// ```
304 /// use std::collections::RingBuf;
305 ///
306 /// let mut d = RingBuf::new();
307 /// assert_eq!(d.back(), None);
308 ///
309 /// d.push(1i);
310 /// d.push(2i);
311 /// match d.back_mut() {
312 /// Some(x) => *x = 9i,
313 /// None => (),
314 /// }
315 /// assert_eq!(d.back(), Some(&9i));
316 /// ```
317 pub fn back_mut(&mut self) -> Option<&mut T> {
318 let nelts = self.nelts;
319 if nelts > 0 { Some(&mut self[nelts - 1]) } else { None }
320 }
321
322 /// Removes the first element and returns it, or `None` if the sequence is
323 /// empty.
324 ///
325 /// # Example
326 ///
327 /// ```
328 /// use std::collections::RingBuf;
329 ///
330 /// let mut d = RingBuf::new();
331 /// d.push(1i);
332 /// d.push(2i);
333 ///
334 /// assert_eq!(d.pop_front(), Some(1i));
335 /// assert_eq!(d.pop_front(), Some(2i));
336 /// assert_eq!(d.pop_front(), None);
337 /// ```
338 pub fn pop_front(&mut self) -> Option<T> {
339 let result = self.elts[self.lo].take();
340 if result.is_some() {
341 self.lo = (self.lo + 1u) % self.elts.len();
342 self.nelts -= 1u;
343 }
344 result
345 }
346
347 /// Inserts an element first in the sequence.
348 ///
349 /// # Example
350 ///
351 /// ```
352 /// use std::collections::RingBuf;
353 ///
354 /// let mut d = RingBuf::new();
355 /// d.push_front(1i);
356 /// d.push_front(2i);
357 /// assert_eq!(d.front(), Some(&2i));
358 /// ```
359 pub fn push_front(&mut self, t: T) {
360 if self.nelts == self.elts.len() {
361 grow(self.nelts, &mut self.lo, &mut self.elts);
362 }
363 if self.lo == 0u {
364 self.lo = self.elts.len() - 1u;
365 } else { self.lo -= 1u; }
366 self.elts[self.lo] = Some(t);
367 self.nelts += 1u;
368 }
369
370 /// Appends an element to the back of a buffer
371 ///
372 /// # Example
373 ///
374 /// ```rust
375 /// use std::collections::RingBuf;
376 ///
377 /// let mut buf = RingBuf::new();
378 /// buf.push(1i);
379 /// buf.push(3);
380 /// assert_eq!(3, *buf.back().unwrap());
381 /// ```
382 pub fn push(&mut self, t: T) {
383 if self.nelts == self.elts.len() {
384 grow(self.nelts, &mut self.lo, &mut self.elts);
385 }
386 let hi = self.raw_index(self.nelts);
387 self.elts[hi] = Some(t);
388 self.nelts += 1u;
389 }
390
391 /// Removes the last element from a buffer and returns it, or `None` if
392 /// it is empty.
393 ///
394 /// # Example
395 ///
396 /// ```rust
397 /// use std::collections::RingBuf;
398 ///
399 /// let mut buf = RingBuf::new();
400 /// assert_eq!(buf.pop(), None);
401 /// buf.push(1i);
402 /// buf.push(3);
403 /// assert_eq!(buf.pop(), Some(3));
404 /// ```
405 pub fn pop(&mut self) -> Option<T> {
406 if self.nelts > 0 {
407 self.nelts -= 1;
408 let hi = self.raw_index(self.nelts);
409 self.elts[hi].take()
410 } else {
411 None
412 }
413 }
Jed Estep4f7a7422013-06-25 19:08:47414}
415
Niko Matsakis1b487a82014-08-28 01:46:52416/// `RingBuf` iterator.
Niko Matsakis1b487a82014-08-28 01:46:52417pub struct Items<'a, T:'a> {
418 lo: uint,
419 index: uint,
420 rindex: uint,
421 elts: &'a [Option<T>],
422}
423
Palmer Cox3fd8c8b2014-01-15 03:32:24424impl<'a, T> Iterator<&'a T> for Items<'a, T> {
Niko Matsakisbc4164d2013-11-16 22:29:39425 #[inline]
Erik Price5731ca32013-12-10 07:16:18426 fn next(&mut self) -> Option<&'a T> {
Niko Matsakisbc4164d2013-11-16 22:29:39427 if self.index == self.rindex {
428 return None;
429 }
430 let raw_index = raw_index(self.lo, self.elts.len(), self.index);
431 self.index += 1;
Aaron Turon276b8b12014-08-19 00:52:38432 Some(self.elts[raw_index].as_ref().unwrap())
Niko Matsakisbc4164d2013-11-16 22:29:39433 }
434
435 #[inline]
436 fn size_hint(&self) -> (uint, Option<uint>) {
437 let len = self.rindex - self.index;
438 (len, Some(len))
439 }
440}
441
Palmer Cox3fd8c8b2014-01-15 03:32:24442impl<'a, T> DoubleEndedIterator<&'a T> for Items<'a, T> {
Niko Matsakisbc4164d2013-11-16 22:29:39443 #[inline]
Erik Price5731ca32013-12-10 07:16:18444 fn next_back(&mut self) -> Option<&'a T> {
Niko Matsakisbc4164d2013-11-16 22:29:39445 if self.index == self.rindex {
446 return None;
447 }
448 self.rindex -= 1;
449 let raw_index = raw_index(self.lo, self.elts.len(), self.rindex);
Aaron Turon276b8b12014-08-19 00:52:38450 Some(self.elts[raw_index].as_ref().unwrap())
Niko Matsakisbc4164d2013-11-16 22:29:39451 }
452}
Jed Estep35314c92013-06-26 15:38:29453
Palmer Cox3fd8c8b2014-01-15 03:32:24454impl<'a, T> ExactSize<&'a T> for Items<'a, T> {}
blake2-ppc7c369ee72013-09-01 16:20:24455
Palmer Cox3fd8c8b2014-01-15 03:32:24456impl<'a, T> RandomAccessIterator<&'a T> for Items<'a, T> {
blake2-ppcf6862132013-07-29 18:16:26457 #[inline]
458 fn indexable(&self) -> uint { self.rindex - self.index }
459
460 #[inline]
Alex Crichtonf4083a22014-04-22 05:15:42461 fn idx(&mut self, j: uint) -> Option<&'a T> {
blake2-ppcf6862132013-07-29 18:16:26462 if j >= self.indexable() {
463 None
464 } else {
465 let raw_index = raw_index(self.lo, self.elts.len(), self.index + j);
Aaron Turon276b8b12014-08-19 00:52:38466 Some(self.elts[raw_index].as_ref().unwrap())
blake2-ppcf6862132013-07-29 18:16:26467 }
468 }
469}
470
Niko Matsakis1b487a82014-08-28 01:46:52471/// `RingBuf` mutable iterator.
Niko Matsakis1b487a82014-08-28 01:46:52472pub struct MutItems<'a, T:'a> {
Alex Crichton9d5d97b2014-10-15 06:05:01473 remaining1: slice::MutItems<'a, Option<T>>,
474 remaining2: slice::MutItems<'a, Option<T>>,
Niko Matsakis1b487a82014-08-28 01:46:52475 nelts: uint,
476}
477
Palmer Cox3fd8c8b2014-01-15 03:32:24478impl<'a, T> Iterator<&'a mut T> for MutItems<'a, T> {
Niko Matsakisbc4164d2013-11-16 22:29:39479 #[inline]
Erik Price5731ca32013-12-10 07:16:18480 fn next(&mut self) -> Option<&'a mut T> {
Niko Matsakisbc4164d2013-11-16 22:29:39481 if self.nelts == 0 {
482 return None;
483 }
Niko Matsakisbc4164d2013-11-16 22:29:39484 self.nelts -= 1;
Alex Crichton9d5d97b2014-10-15 06:05:01485 match self.remaining1.next() {
486 Some(ptr) => return Some(ptr.as_mut().unwrap()),
487 None => {}
488 }
489 match self.remaining2.next() {
490 Some(ptr) => return Some(ptr.as_mut().unwrap()),
491 None => unreachable!(),
492 }
Niko Matsakisbc4164d2013-11-16 22:29:39493 }
494
495 #[inline]
496 fn size_hint(&self) -> (uint, Option<uint>) {
497 (self.nelts, Some(self.nelts))
498 }
499}
500
Palmer Cox3fd8c8b2014-01-15 03:32:24501impl<'a, T> DoubleEndedIterator<&'a mut T> for MutItems<'a, T> {
Niko Matsakisbc4164d2013-11-16 22:29:39502 #[inline]
Erik Price5731ca32013-12-10 07:16:18503 fn next_back(&mut self) -> Option<&'a mut T> {
Niko Matsakisbc4164d2013-11-16 22:29:39504 if self.nelts == 0 {
505 return None;
506 }
Niko Matsakisbc4164d2013-11-16 22:29:39507 self.nelts -= 1;
Alex Crichton9d5d97b2014-10-15 06:05:01508 match self.remaining2.next_back() {
509 Some(ptr) => return Some(ptr.as_mut().unwrap()),
510 None => {}
511 }
512 match self.remaining1.next_back() {
513 Some(ptr) => return Some(ptr.as_mut().unwrap()),
514 None => unreachable!(),
515 }
Niko Matsakisbc4164d2013-11-16 22:29:39516 }
517}
Daniel Micayb47e1e92013-02-16 22:55:55518
Palmer Cox3fd8c8b2014-01-15 03:32:24519impl<'a, T> ExactSize<&'a mut T> for MutItems<'a, T> {}
blake2-ppc7c369ee72013-09-01 16:20:24520
Daniel Micayb47e1e92013-02-16 22:55:55521/// Grow is only called on full elts, so nelts is also len(elts), unlike
522/// elsewhere.
Huon Wilson4b9a7a22014-04-05 05:45:42523fn grow<T>(nelts: uint, loptr: &mut uint, elts: &mut Vec<Option<T>>) {
Corey Richardsoncc57ca02013-05-19 02:02:45524 assert_eq!(nelts, elts.len());
blake2-ppc8a326762013-07-06 03:42:45525 let lo = *loptr;
Kevin Butler64896d62014-08-07 01:11:13526 elts.reserve(nelts * 2);
527 let newlen = elts.capacity();
Daniel Micayb47e1e92013-02-16 22:55:55528
blake2-ppc40ce0b72013-07-06 03:42:45529 /* fill with None */
Kevin Butler64896d62014-08-07 01:11:13530 for _ in range(elts.len(), newlen) {
blake2-ppc40ce0b72013-07-06 03:42:45531 elts.push(None);
Daniel Micayb47e1e92013-02-16 22:55:55532 }
blake2-ppc8a326762013-07-06 03:42:45533
534 /*
535 Move the shortest half into the newly reserved area.
536 lo ---->|
537 nelts ----------->|
538 [o o o|o o o o o]
539 A [. . .|o o o o o o o o|. . . . .]
540 B [o o o|. . . . . . . .|o o o o o]
541 */
542
543 assert!(newlen - nelts/2 >= nelts);
544 if lo <= (nelts - lo) { // A
Daniel Micay100894552013-08-03 16:45:23545 for i in range(0u, lo) {
Huon Wilson4b9a7a22014-04-05 05:45:42546 elts.as_mut_slice().swap(i, nelts + i);
blake2-ppc8a326762013-07-06 03:42:45547 }
548 } else { // B
Daniel Micay100894552013-08-03 16:45:23549 for i in range(lo, nelts) {
Huon Wilson4b9a7a22014-04-05 05:45:42550 elts.as_mut_slice().swap(i, newlen - nelts + i);
blake2-ppc8a326762013-07-06 03:42:45551 }
552 *loptr += newlen - nelts;
blake2-ppc40ce0b72013-07-06 03:42:45553 }
Daniel Micayb47e1e92013-02-16 22:55:55554}
555
P1startf2aa88c2014-08-04 10:48:39556/// Returns the index in the underlying `Vec` for a given logical element index.
blake2-ppc75015c32013-07-06 03:42:45557fn raw_index(lo: uint, len: uint, index: uint) -> uint {
558 if lo >= len - index {
559 lo + index - len
560 } else {
561 lo + index
562 }
563}
564
Alex Crichton748bc3c2014-05-30 00:45:07565impl<A: PartialEq> PartialEq for RingBuf<A> {
blake2-ppc70523712013-07-10 13:27:14566 fn eq(&self, other: &RingBuf<A>) -> bool {
blake2-ppc10c76982013-07-06 13:27:32567 self.nelts == other.nelts &&
568 self.iter().zip(other.iter()).all(|(a, b)| a.eq(b))
569 }
blake2-ppc70523712013-07-10 13:27:14570 fn ne(&self, other: &RingBuf<A>) -> bool {
blake2-ppc10c76982013-07-06 13:27:32571 !self.eq(other)
572 }
573}
574
nham25acfde2014-08-01 20:05:03575impl<A: Eq> Eq for RingBuf<A> {}
576
nham63615772014-07-27 03:18:56577impl<A: PartialOrd> PartialOrd for RingBuf<A> {
578 fn partial_cmp(&self, other: &RingBuf<A>) -> Option<Ordering> {
579 iter::order::partial_cmp(self.iter(), other.iter())
580 }
581}
582
nham3737c532014-08-01 20:22:48583impl<A: Ord> Ord for RingBuf<A> {
584 #[inline]
585 fn cmp(&self, other: &RingBuf<A>) -> Ordering {
586 iter::order::cmp(self.iter(), other.iter())
587 }
588}
589
nham1cfa6562014-07-27 02:33:47590impl<S: Writer, A: Hash<S>> Hash<S> for RingBuf<A> {
591 fn hash(&self, state: &mut S) {
nham9fa44242014-07-27 16:37:32592 self.len().hash(state);
nham1cfa6562014-07-27 02:33:47593 for elt in self.iter() {
594 elt.hash(state);
595 }
596 }
597}
598
P1startfd10d202014-08-02 06:39:39599impl<A> Index<uint, A> for RingBuf<A> {
600 #[inline]
601 fn index<'a>(&'a self, i: &uint) -> &'a A {
Alex Crichton9d5d97b2014-10-15 06:05:01602 let idx = self.raw_index(*i);
603 match self.elts[idx] {
Steve Klabnik7828c3d2014-10-09 19:17:22604 None => panic!(),
Alex Crichton9d5d97b2014-10-15 06:05:01605 Some(ref v) => v,
606 }
P1startfd10d202014-08-02 06:39:39607 }
608}
609
Alex Crichton1d356622014-10-23 15:42:21610impl<A> IndexMut<uint, A> for RingBuf<A> {
P1startfd10d202014-08-02 06:39:39611 #[inline]
Alex Crichton1d356622014-10-23 15:42:21612 fn index_mut<'a>(&'a mut self, i: &uint) -> &'a mut A {
613 let idx = self.raw_index(*i);
614 match *(&mut self.elts[idx]) {
615 None => panic!(),
616 Some(ref mut v) => v
617 }
P1startfd10d202014-08-02 06:39:39618 }
Alex Crichton1d356622014-10-23 15:42:21619}
P1startfd10d202014-08-02 06:39:39620
Huon Wilson53487a02013-08-13 13:08:14621impl<A> FromIterator<A> for RingBuf<A> {
Brian Andersonee052192014-03-31 04:45:55622 fn from_iter<T: Iterator<A>>(iterator: T) -> RingBuf<A> {
blake2-ppcf8ae5262013-07-30 00:06:49623 let (lower, _) = iterator.size_hint();
624 let mut deq = RingBuf::with_capacity(lower);
625 deq.extend(iterator);
blake2-ppc08dc72f2013-07-06 03:42:45626 deq
627 }
628}
629
Huon Wilson53487a02013-08-13 13:08:14630impl<A> Extendable<A> for RingBuf<A> {
Marvin Löbel6200e762014-03-20 13:12:56631 fn extend<T: Iterator<A>>(&mut self, mut iterator: T) {
632 for elt in iterator {
Aaron Turonf77cabe2014-08-11 23:47:46633 self.push(elt);
blake2-ppcf8ae5262013-07-30 00:06:49634 }
635 }
636}
637
Alex Crichton6a585372014-05-30 01:50:12638impl<T: fmt::Show> fmt::Show for RingBuf<T> {
Adolfo Ochagavía8e4e3ab2014-06-04 14:15:04639 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
640 try!(write!(f, "["));
641
642 for (i, e) in self.iter().enumerate() {
643 if i != 0 { try!(write!(f, ", ")); }
644 try!(write!(f, "{}", *e));
645 }
646
647 write!(f, "]")
648 }
649}
650
Brian Anderson6e27b272012-01-18 03:05:07651#[cfg(test)]
652mod tests {
Alex Crichton02882fb2014-02-28 09:23:06653 use std::fmt::Show;
Alex Crichton760b93a2014-05-30 02:03:06654 use std::prelude::*;
nham1cfa6562014-07-27 02:33:47655 use std::hash;
Alex Crichton760b93a2014-05-30 02:03:06656 use test::Bencher;
657 use test;
658
Alex Crichtonf47e4b22014-01-07 06:33:50659 use super::RingBuf;
Alex Crichton760b93a2014-05-30 02:03:06660 use vec::Vec;
Patrick Waltonfa5ee932012-12-28 02:24:18661
Brian Anderson6e27b272012-01-18 03:05:07662 #[test]
Victor Berger52ea83d2014-09-22 17:30:06663 #[allow(deprecated)]
Brian Anderson6e27b272012-01-18 03:05:07664 fn test_simple() {
blake2-ppc70523712013-07-10 13:27:14665 let mut d = RingBuf::new();
Corey Richardsoncc57ca02013-05-19 02:02:45666 assert_eq!(d.len(), 0u);
Niko Matsakis9e3d0b02014-04-21 21:58:52667 d.push_front(17i);
668 d.push_front(42i);
nham7b310582014-08-26 19:45:55669 d.push(137);
Corey Richardsoncc57ca02013-05-19 02:02:45670 assert_eq!(d.len(), 3u);
nham7b310582014-08-26 19:45:55671 d.push(137);
Corey Richardsoncc57ca02013-05-19 02:02:45672 assert_eq!(d.len(), 4u);
Luqman Aden3ef9aa02014-10-15 07:22:55673 debug!("{}", d.front());
blake2-ppc70523712013-07-10 13:27:14674 assert_eq!(*d.front().unwrap(), 42);
Luqman Aden3ef9aa02014-10-15 07:22:55675 debug!("{}", d.back());
blake2-ppc70523712013-07-10 13:27:14676 assert_eq!(*d.back().unwrap(), 137);
677 let mut i = d.pop_front();
Luqman Aden3ef9aa02014-10-15 07:22:55678 debug!("{}", i);
blake2-ppc70523712013-07-10 13:27:14679 assert_eq!(i, Some(42));
nham7b310582014-08-26 19:45:55680 i = d.pop();
Luqman Aden3ef9aa02014-10-15 07:22:55681 debug!("{}", i);
blake2-ppc70523712013-07-10 13:27:14682 assert_eq!(i, Some(137));
nham7b310582014-08-26 19:45:55683 i = d.pop();
Luqman Aden3ef9aa02014-10-15 07:22:55684 debug!("{}", i);
blake2-ppc70523712013-07-10 13:27:14685 assert_eq!(i, Some(137));
nham7b310582014-08-26 19:45:55686 i = d.pop();
Luqman Aden3ef9aa02014-10-15 07:22:55687 debug!("{}", i);
blake2-ppc70523712013-07-10 13:27:14688 assert_eq!(i, Some(17));
Corey Richardsoncc57ca02013-05-19 02:02:45689 assert_eq!(d.len(), 0u);
nham7b310582014-08-26 19:45:55690 d.push(3);
Corey Richardsoncc57ca02013-05-19 02:02:45691 assert_eq!(d.len(), 1u);
blake2-ppc70523712013-07-10 13:27:14692 d.push_front(2);
Corey Richardsoncc57ca02013-05-19 02:02:45693 assert_eq!(d.len(), 2u);
nham7b310582014-08-26 19:45:55694 d.push(4);
Corey Richardsoncc57ca02013-05-19 02:02:45695 assert_eq!(d.len(), 3u);
blake2-ppc70523712013-07-10 13:27:14696 d.push_front(1);
Corey Richardsoncc57ca02013-05-19 02:02:45697 assert_eq!(d.len(), 4u);
Alex Crichton9d5d97b2014-10-15 06:05:01698 debug!("{}", d[0]);
699 debug!("{}", d[1]);
700 debug!("{}", d[2]);
701 debug!("{}", d[3]);
702 assert_eq!(d[0], 1);
703 assert_eq!(d[1], 2);
704 assert_eq!(d[2], 3);
705 assert_eq!(d[3], 4);
Brian Anderson6e27b272012-01-18 03:05:07706 }
707
Felix S. Klock IIa636f512013-05-01 23:32:37708 #[cfg(test)]
Alex Crichton748bc3c2014-05-30 00:45:07709 fn test_parameterized<T:Clone + PartialEq + Show>(a: T, b: T, c: T, d: T) {
Patrick Waltondc4bf172013-07-13 04:05:59710 let mut deq = RingBuf::new();
Corey Richardsoncc57ca02013-05-19 02:02:45711 assert_eq!(deq.len(), 0);
Patrick Waltondc4bf172013-07-13 04:05:59712 deq.push_front(a.clone());
713 deq.push_front(b.clone());
nham7b310582014-08-26 19:45:55714 deq.push(c.clone());
Corey Richardsoncc57ca02013-05-19 02:02:45715 assert_eq!(deq.len(), 3);
nham7b310582014-08-26 19:45:55716 deq.push(d.clone());
Corey Richardsoncc57ca02013-05-19 02:02:45717 assert_eq!(deq.len(), 4);
Marvin Löbel0ac7a212013-08-03 23:59:24718 assert_eq!((*deq.front().unwrap()).clone(), b.clone());
719 assert_eq!((*deq.back().unwrap()).clone(), d.clone());
720 assert_eq!(deq.pop_front().unwrap(), b.clone());
nham7b310582014-08-26 19:45:55721 assert_eq!(deq.pop().unwrap(), d.clone());
722 assert_eq!(deq.pop().unwrap(), c.clone());
723 assert_eq!(deq.pop().unwrap(), a.clone());
Corey Richardsoncc57ca02013-05-19 02:02:45724 assert_eq!(deq.len(), 0);
nham7b310582014-08-26 19:45:55725 deq.push(c.clone());
Corey Richardsoncc57ca02013-05-19 02:02:45726 assert_eq!(deq.len(), 1);
Patrick Waltondc4bf172013-07-13 04:05:59727 deq.push_front(b.clone());
Corey Richardsoncc57ca02013-05-19 02:02:45728 assert_eq!(deq.len(), 2);
nham7b310582014-08-26 19:45:55729 deq.push(d.clone());
Corey Richardsoncc57ca02013-05-19 02:02:45730 assert_eq!(deq.len(), 3);
Patrick Waltondc4bf172013-07-13 04:05:59731 deq.push_front(a.clone());
Corey Richardsoncc57ca02013-05-19 02:02:45732 assert_eq!(deq.len(), 4);
NODA, Kaif27ad3d2014-10-05 10:11:17733 assert_eq!(deq[0].clone(), a.clone());
734 assert_eq!(deq[1].clone(), b.clone());
735 assert_eq!(deq[2].clone(), c.clone());
736 assert_eq!(deq[3].clone(), d.clone());
Brian Anderson6e27b272012-01-18 03:05:07737 }
738
blake2-ppc81933ed2013-07-06 03:42:45739 #[test]
blake2-ppc70523712013-07-10 13:27:14740 fn test_push_front_grow() {
741 let mut deq = RingBuf::new();
Daniel Micay100894552013-08-03 16:45:23742 for i in range(0u, 66) {
blake2-ppc70523712013-07-10 13:27:14743 deq.push_front(i);
blake2-ppc81933ed2013-07-06 03:42:45744 }
745 assert_eq!(deq.len(), 66);
746
Daniel Micay100894552013-08-03 16:45:23747 for i in range(0u, 66) {
NODA, Kaif27ad3d2014-10-05 10:11:17748 assert_eq!(deq[i], 65 - i);
blake2-ppc81933ed2013-07-06 03:42:45749 }
750
blake2-ppc70523712013-07-10 13:27:14751 let mut deq = RingBuf::new();
Daniel Micay100894552013-08-03 16:45:23752 for i in range(0u, 66) {
nham7b310582014-08-26 19:45:55753 deq.push(i);
blake2-ppc81933ed2013-07-06 03:42:45754 }
755
Daniel Micay100894552013-08-03 16:45:23756 for i in range(0u, 66) {
NODA, Kaif27ad3d2014-10-05 10:11:17757 assert_eq!(deq[i], i);
blake2-ppc81933ed2013-07-06 03:42:45758 }
759 }
760
P1startfd10d202014-08-02 06:39:39761 #[test]
762 fn test_index() {
763 let mut deq = RingBuf::new();
764 for i in range(1u, 4) {
765 deq.push_front(i);
766 }
767 assert_eq!(deq[1], 2);
768 }
769
770 #[test]
771 #[should_fail]
772 fn test_index_out_of_bounds() {
773 let mut deq = RingBuf::new();
774 for i in range(1u, 4) {
775 deq.push_front(i);
776 }
777 deq[3];
778 }
779
blake2-ppc81933ed2013-07-06 03:42:45780 #[bench]
Liigo Zhuang408f4842014-04-01 01:16:35781 fn bench_new(b: &mut test::Bencher) {
Patrick Walton38efa172013-11-22 03:20:48782 b.iter(|| {
Patrick Walton86939432013-08-08 18:38:10783 let _: RingBuf<u64> = RingBuf::new();
Patrick Walton38efa172013-11-22 03:20:48784 })
blake2-ppc81933ed2013-07-06 03:42:45785 }
786
787 #[bench]
Liigo Zhuang408f4842014-04-01 01:16:35788 fn bench_push_back(b: &mut test::Bencher) {
blake2-ppc70523712013-07-10 13:27:14789 let mut deq = RingBuf::new();
Patrick Walton38efa172013-11-22 03:20:48790 b.iter(|| {
nham7b310582014-08-26 19:45:55791 deq.push(0i);
Patrick Walton38efa172013-11-22 03:20:48792 })
blake2-ppc81933ed2013-07-06 03:42:45793 }
794
795 #[bench]
Liigo Zhuang408f4842014-04-01 01:16:35796 fn bench_push_front(b: &mut test::Bencher) {
blake2-ppc70523712013-07-10 13:27:14797 let mut deq = RingBuf::new();
Patrick Walton38efa172013-11-22 03:20:48798 b.iter(|| {
Patrick Waltona5bb0a32014-06-27 19:30:25799 deq.push_front(0i);
Patrick Walton38efa172013-11-22 03:20:48800 })
blake2-ppc81933ed2013-07-06 03:42:45801 }
802
803 #[bench]
Liigo Zhuang408f4842014-04-01 01:16:35804 fn bench_grow(b: &mut test::Bencher) {
blake2-ppc70523712013-07-10 13:27:14805 let mut deq = RingBuf::new();
Patrick Walton38efa172013-11-22 03:20:48806 b.iter(|| {
Niko Matsakis9e3d0b02014-04-21 21:58:52807 for _ in range(0i, 65) {
Patrick Waltona5bb0a32014-06-27 19:30:25808 deq.push_front(1i);
Brendan Zabarauskas729060d2014-01-30 00:20:34809 }
Patrick Walton38efa172013-11-22 03:20:48810 })
blake2-ppc81933ed2013-07-06 03:42:45811 }
812
Alex Crichton748bc3c2014-05-30 00:45:07813 #[deriving(Clone, PartialEq, Show)]
Patrick Walton99b33f72013-07-02 19:47:32814 enum Taggy {
815 One(int),
816 Two(int, int),
817 Three(int, int, int),
Brian Anderson6e27b272012-01-18 03:05:07818 }
819
Alex Crichton748bc3c2014-05-30 00:45:07820 #[deriving(Clone, PartialEq, Show)]
Patrick Walton99b33f72013-07-02 19:47:32821 enum Taggypar<T> {
822 Onepar(int),
823 Twopar(int, int),
824 Threepar(int, int, int),
825 }
826
Alex Crichton748bc3c2014-05-30 00:45:07827 #[deriving(Clone, PartialEq, Show)]
Erick Tryzelaare84576b2013-01-22 16:44:24828 struct RecCy {
829 x: int,
830 y: int,
Patrick Waltoneb4d39e2013-01-26 00:57:39831 t: Taggy
Patrick Walton9117dcb2012-09-20 01:00:26832 }
Kevin Cantuc43426e2012-09-13 05:09:55833
834 #[test]
835 fn test_param_int() {
836 test_parameterized::<int>(5, 72, 64, 175);
837 }
838
839 #[test]
Kevin Cantuc43426e2012-09-13 05:09:55840 fn test_param_taggy() {
Corey Richardsonf8ae9b02013-06-26 22:14:35841 test_parameterized::<Taggy>(One(1), Two(1, 2), Three(1, 2, 3), Two(17, 42));
Kevin Cantuc43426e2012-09-13 05:09:55842 }
843
844 #[test]
845 fn test_param_taggypar() {
846 test_parameterized::<Taggypar<int>>(Onepar::<int>(1),
Ben Striegela605fd02012-08-11 14:08:42847 Twopar::<int>(1, 2),
848 Threepar::<int>(1, 2, 3),
849 Twopar::<int>(17, 42));
Kevin Cantuc43426e2012-09-13 05:09:55850 }
Brian Anderson6e27b272012-01-18 03:05:07851
Kevin Cantuc43426e2012-09-13 05:09:55852 #[test]
853 fn test_param_reccy() {
Erick Tryzelaare84576b2013-01-22 16:44:24854 let reccy1 = RecCy { x: 1, y: 2, t: One(1) };
855 let reccy2 = RecCy { x: 345, y: 2, t: Two(1, 2) };
856 let reccy3 = RecCy { x: 1, y: 777, t: Three(1, 2, 3) };
857 let reccy4 = RecCy { x: 19, y: 252, t: Two(17, 42) };
Kevin Cantuc43426e2012-09-13 05:09:55858 test_parameterized::<RecCy>(reccy1, reccy2, reccy3, reccy4);
Brian Anderson6e27b272012-01-18 03:05:07859 }
Erick Tryzelaar909d8f02013-03-30 01:02:44860
861 #[test]
blake2-ppc0ff5c172013-07-06 03:42:45862 fn test_with_capacity() {
blake2-ppc70523712013-07-10 13:27:14863 let mut d = RingBuf::with_capacity(0);
nham7b310582014-08-26 19:45:55864 d.push(1i);
blake2-ppc0ff5c172013-07-06 03:42:45865 assert_eq!(d.len(), 1);
blake2-ppc70523712013-07-10 13:27:14866 let mut d = RingBuf::with_capacity(50);
nham7b310582014-08-26 19:45:55867 d.push(1i);
blake2-ppc0ff5c172013-07-06 03:42:45868 assert_eq!(d.len(), 1);
869 }
870
871 #[test]
Kevin Butler64896d62014-08-07 01:11:13872 fn test_with_capacity_non_power_two() {
873 let mut d3 = RingBuf::with_capacity(3);
874 d3.push(1i);
875
876 // X = None, | = lo
877 // [|1, X, X]
878 assert_eq!(d3.pop_front(), Some(1));
879 // [X, |X, X]
880 assert_eq!(d3.front(), None);
881
882 // [X, |3, X]
883 d3.push(3);
884 // [X, |3, 6]
885 d3.push(6);
886 // [X, X, |6]
887 assert_eq!(d3.pop_front(), Some(3));
888
889 // Pushing the lo past half way point to trigger
890 // the 'B' scenario for growth
891 // [9, X, |6]
892 d3.push(9);
893 // [9, 12, |6]
894 d3.push(12);
895
896 d3.push(15);
897 // There used to be a bug here about how the
898 // RingBuf made growth assumptions about the
899 // underlying Vec which didn't hold and lead
900 // to corruption.
901 // (Vec grows to next power of two)
902 //good- [9, 12, 15, X, X, X, X, |6]
903 //bug- [15, 12, X, X, X, |6, X, X]
904 assert_eq!(d3.pop_front(), Some(6));
905
906 // Which leads us to the following state which
907 // would be a failure case.
908 //bug- [15, 12, X, X, X, X, |X, X]
909 assert_eq!(d3.front(), Some(&9));
910 }
911
912 #[test]
David Manescu65f35782014-01-31 13:03:20913 fn test_reserve_exact() {
blake2-ppc70523712013-07-10 13:27:14914 let mut d = RingBuf::new();
nham7b310582014-08-26 19:45:55915 d.push(0u64);
David Manescu65f35782014-01-31 13:03:20916 d.reserve_exact(50);
Huon Wilson32d65592013-06-27 14:40:47917 assert_eq!(d.elts.capacity(), 50);
blake2-ppc70523712013-07-10 13:27:14918 let mut d = RingBuf::new();
nham7b310582014-08-26 19:45:55919 d.push(0u32);
David Manescu65f35782014-01-31 13:03:20920 d.reserve_exact(50);
Huon Wilson32d65592013-06-27 14:40:47921 assert_eq!(d.elts.capacity(), 50);
Tim Chevalier77de84b2013-05-27 18:47:38922 }
923
924 #[test]
David Manescu65f35782014-01-31 13:03:20925 fn test_reserve() {
blake2-ppc70523712013-07-10 13:27:14926 let mut d = RingBuf::new();
nham7b310582014-08-26 19:45:55927 d.push(0u64);
David Manescu65f35782014-01-31 13:03:20928 d.reserve(50);
Huon Wilson32d65592013-06-27 14:40:47929 assert_eq!(d.elts.capacity(), 64);
blake2-ppc70523712013-07-10 13:27:14930 let mut d = RingBuf::new();
nham7b310582014-08-26 19:45:55931 d.push(0u32);
David Manescu65f35782014-01-31 13:03:20932 d.reserve(50);
Huon Wilson32d65592013-06-27 14:40:47933 assert_eq!(d.elts.capacity(), 64);
Tim Chevalier77de84b2013-05-27 18:47:38934 }
935
Jed Estep096fb792013-06-26 14:04:44936 #[test]
blake2-ppc57757a82013-09-26 07:19:26937 fn test_swap() {
Niko Matsakis9e3d0b02014-04-21 21:58:52938 let mut d: RingBuf<int> = range(0i, 5).collect();
blake2-ppc57757a82013-09-26 07:19:26939 d.pop_front();
940 d.swap(0, 3);
Huon Wilson4b9a7a22014-04-05 05:45:42941 assert_eq!(d.iter().map(|&x|x).collect::<Vec<int>>(), vec!(4, 2, 3, 1));
blake2-ppc57757a82013-09-26 07:19:26942 }
943
944 #[test]
Jed Estep096fb792013-06-26 14:04:44945 fn test_iter() {
blake2-ppc70523712013-07-10 13:27:14946 let mut d = RingBuf::new();
blake2-ppcf88d5322013-07-06 03:42:45947 assert_eq!(d.iter().next(), None);
blake2-ppc9ccf4432013-07-14 20:30:22948 assert_eq!(d.iter().size_hint(), (0, Some(0)));
blake2-ppcf88d5322013-07-06 03:42:45949
Niko Matsakis9e3d0b02014-04-21 21:58:52950 for i in range(0i, 5) {
nham7b310582014-08-26 19:45:55951 d.push(i);
Jed Estep096fb792013-06-26 14:04:44952 }
Nick Cameron37a94b82014-08-04 12:19:02953 {
954 let b: &[_] = &[&0,&1,&2,&3,&4];
955 assert_eq!(d.iter().collect::<Vec<&int>>().as_slice(), b);
956 }
Corey Richardsonf8ae9b02013-06-26 22:14:35957
Niko Matsakis9e3d0b02014-04-21 21:58:52958 for i in range(6i, 9) {
blake2-ppc70523712013-07-10 13:27:14959 d.push_front(i);
Jed Estep096fb792013-06-26 14:04:44960 }
Nick Cameron37a94b82014-08-04 12:19:02961 {
962 let b: &[_] = &[&8,&7,&6,&0,&1,&2,&3,&4];
963 assert_eq!(d.iter().collect::<Vec<&int>>().as_slice(), b);
964 }
blake2-ppc9ccf4432013-07-14 20:30:22965
966 let mut it = d.iter();
967 let mut len = d.len();
968 loop {
969 match it.next() {
970 None => break,
971 _ => { len -= 1; assert_eq!(it.size_hint(), (len, Some(len))) }
972 }
973 }
Jed Estep096fb792013-06-26 14:04:44974 }
975
976 #[test]
977 fn test_rev_iter() {
blake2-ppc70523712013-07-10 13:27:14978 let mut d = RingBuf::new();
Jonathan S03609e52014-04-21 04:59:12979 assert_eq!(d.iter().rev().next(), None);
blake2-ppcf88d5322013-07-06 03:42:45980
Niko Matsakis9e3d0b02014-04-21 21:58:52981 for i in range(0i, 5) {
nham7b310582014-08-26 19:45:55982 d.push(i);
Jed Estep096fb792013-06-26 14:04:44983 }
Nick Cameron37a94b82014-08-04 12:19:02984 {
985 let b: &[_] = &[&4,&3,&2,&1,&0];
986 assert_eq!(d.iter().rev().collect::<Vec<&int>>().as_slice(), b);
987 }
Corey Richardsonf8ae9b02013-06-26 22:14:35988
Niko Matsakis9e3d0b02014-04-21 21:58:52989 for i in range(6i, 9) {
blake2-ppc70523712013-07-10 13:27:14990 d.push_front(i);
Jed Estep096fb792013-06-26 14:04:44991 }
Nick Cameron37a94b82014-08-04 12:19:02992 let b: &[_] = &[&4,&3,&2,&1,&0,&6,&7,&8];
993 assert_eq!(d.iter().rev().collect::<Vec<&int>>().as_slice(), b);
Jed Estep096fb792013-06-26 14:04:44994 }
blake2-ppc08dc72f2013-07-06 03:42:45995
996 #[test]
Niko Matsakisbc4164d2013-11-16 22:29:39997 fn test_mut_rev_iter_wrap() {
998 let mut d = RingBuf::with_capacity(3);
Aaron Turonfc525ee2014-09-15 03:27:36999 assert!(d.iter_mut().rev().next().is_none());
Niko Matsakisbc4164d2013-11-16 22:29:391000
nham7b310582014-08-26 19:45:551001 d.push(1i);
1002 d.push(2);
1003 d.push(3);
Niko Matsakisbc4164d2013-11-16 22:29:391004 assert_eq!(d.pop_front(), Some(1));
nham7b310582014-08-26 19:45:551005 d.push(4);
Niko Matsakisbc4164d2013-11-16 22:29:391006
Aaron Turonfc525ee2014-09-15 03:27:361007 assert_eq!(d.iter_mut().rev().map(|x| *x).collect::<Vec<int>>(),
Huon Wilson4b9a7a22014-04-05 05:45:421008 vec!(4, 3, 2));
Niko Matsakisbc4164d2013-11-16 22:29:391009 }
1010
1011 #[test]
blake2-ppcf88d5322013-07-06 03:42:451012 fn test_mut_iter() {
blake2-ppc70523712013-07-10 13:27:141013 let mut d = RingBuf::new();
Aaron Turonfc525ee2014-09-15 03:27:361014 assert!(d.iter_mut().next().is_none());
blake2-ppcf88d5322013-07-06 03:42:451015
Daniel Micay100894552013-08-03 16:45:231016 for i in range(0u, 3) {
blake2-ppc70523712013-07-10 13:27:141017 d.push_front(i);
blake2-ppcf88d5322013-07-06 03:42:451018 }
1019
Aaron Turonfc525ee2014-09-15 03:27:361020 for (i, elt) in d.iter_mut().enumerate() {
blake2-ppcf88d5322013-07-06 03:42:451021 assert_eq!(*elt, 2 - i);
1022 *elt = i;
1023 }
1024
1025 {
Aaron Turonfc525ee2014-09-15 03:27:361026 let mut it = d.iter_mut();
blake2-ppcf88d5322013-07-06 03:42:451027 assert_eq!(*it.next().unwrap(), 0);
1028 assert_eq!(*it.next().unwrap(), 1);
1029 assert_eq!(*it.next().unwrap(), 2);
1030 assert!(it.next().is_none());
1031 }
1032 }
1033
1034 #[test]
1035 fn test_mut_rev_iter() {
blake2-ppc70523712013-07-10 13:27:141036 let mut d = RingBuf::new();
Aaron Turonfc525ee2014-09-15 03:27:361037 assert!(d.iter_mut().rev().next().is_none());
blake2-ppcf88d5322013-07-06 03:42:451038
Daniel Micay100894552013-08-03 16:45:231039 for i in range(0u, 3) {
blake2-ppc70523712013-07-10 13:27:141040 d.push_front(i);
blake2-ppcf88d5322013-07-06 03:42:451041 }
1042
Aaron Turonfc525ee2014-09-15 03:27:361043 for (i, elt) in d.iter_mut().rev().enumerate() {
blake2-ppcf88d5322013-07-06 03:42:451044 assert_eq!(*elt, i);
1045 *elt = i;
1046 }
1047
1048 {
Aaron Turonfc525ee2014-09-15 03:27:361049 let mut it = d.iter_mut().rev();
blake2-ppcf88d5322013-07-06 03:42:451050 assert_eq!(*it.next().unwrap(), 0);
1051 assert_eq!(*it.next().unwrap(), 1);
1052 assert_eq!(*it.next().unwrap(), 2);
1053 assert!(it.next().is_none());
1054 }
1055 }
1056
1057 #[test]
Brian Andersonee052192014-03-31 04:45:551058 fn test_from_iter() {
Daniel Micay6919cf52013-09-08 15:01:161059 use std::iter;
Niko Matsakis9e3d0b02014-04-21 21:58:521060 let v = vec!(1i,2,3,4,5,6,7);
Erick Tryzelaar68f40d22013-08-10 03:09:471061 let deq: RingBuf<int> = v.iter().map(|&x| x).collect();
Huon Wilson4b9a7a22014-04-05 05:45:421062 let u: Vec<int> = deq.iter().map(|&x| x).collect();
blake2-ppc08dc72f2013-07-06 03:42:451063 assert_eq!(u, v);
1064
Daniel Micay6919cf52013-09-08 15:01:161065 let mut seq = iter::count(0u, 2).take(256);
blake2-ppc70523712013-07-10 13:27:141066 let deq: RingBuf<uint> = seq.collect();
Daniel Micay100894552013-08-03 16:45:231067 for (i, &x) in deq.iter().enumerate() {
blake2-ppc08dc72f2013-07-06 03:42:451068 assert_eq!(2*i, x);
1069 }
1070 assert_eq!(deq.len(), 256);
1071 }
blake2-ppc10c76982013-07-06 13:27:321072
1073 #[test]
1074 fn test_clone() {
blake2-ppc70523712013-07-10 13:27:141075 let mut d = RingBuf::new();
Niko Matsakis9e3d0b02014-04-21 21:58:521076 d.push_front(17i);
blake2-ppc70523712013-07-10 13:27:141077 d.push_front(42);
nham7b310582014-08-26 19:45:551078 d.push(137);
1079 d.push(137);
blake2-ppc10c76982013-07-06 13:27:321080 assert_eq!(d.len(), 4u);
1081 let mut e = d.clone();
1082 assert_eq!(e.len(), 4u);
1083 while !d.is_empty() {
nham7b310582014-08-26 19:45:551084 assert_eq!(d.pop(), e.pop());
blake2-ppc10c76982013-07-06 13:27:321085 }
1086 assert_eq!(d.len(), 0u);
1087 assert_eq!(e.len(), 0u);
1088 }
1089
1090 #[test]
1091 fn test_eq() {
blake2-ppc70523712013-07-10 13:27:141092 let mut d = RingBuf::new();
Alex Crichton02882fb2014-02-28 09:23:061093 assert!(d == RingBuf::with_capacity(0));
Niko Matsakis9e3d0b02014-04-21 21:58:521094 d.push_front(137i);
blake2-ppc70523712013-07-10 13:27:141095 d.push_front(17);
1096 d.push_front(42);
nham7b310582014-08-26 19:45:551097 d.push(137);
blake2-ppc70523712013-07-10 13:27:141098 let mut e = RingBuf::with_capacity(0);
nham7b310582014-08-26 19:45:551099 e.push(42);
1100 e.push(17);
1101 e.push(137);
1102 e.push(137);
Alex Crichton02882fb2014-02-28 09:23:061103 assert!(&e == &d);
nham7b310582014-08-26 19:45:551104 e.pop();
1105 e.push(0);
blake2-ppc10c76982013-07-06 13:27:321106 assert!(e != d);
1107 e.clear();
Alex Crichton02882fb2014-02-28 09:23:061108 assert!(e == RingBuf::new());
blake2-ppc10c76982013-07-06 13:27:321109 }
Adolfo Ochagavía8e4e3ab2014-06-04 14:15:041110
1111 #[test]
nham1cfa6562014-07-27 02:33:471112 fn test_hash() {
1113 let mut x = RingBuf::new();
1114 let mut y = RingBuf::new();
1115
1116 x.push(1i);
1117 x.push(2);
1118 x.push(3);
1119
1120 y.push(0i);
1121 y.push(1i);
1122 y.pop_front();
1123 y.push(2);
1124 y.push(3);
1125
1126 assert!(hash::hash(&x) == hash::hash(&y));
1127 }
1128
1129 #[test]
nham63615772014-07-27 03:18:561130 fn test_ord() {
1131 let x = RingBuf::new();
1132 let mut y = RingBuf::new();
1133 y.push(1i);
1134 y.push(2);
1135 y.push(3);
1136 assert!(x < y);
1137 assert!(y > x);
1138 assert!(x <= x);
1139 assert!(x >= x);
1140 }
1141
1142 #[test]
Adolfo Ochagavía8e4e3ab2014-06-04 14:15:041143 fn test_show() {
Niko Matsakis9e3d0b02014-04-21 21:58:521144 let ringbuf: RingBuf<int> = range(0i, 10).collect();
Adolfo Ochagavía8e4e3ab2014-06-04 14:15:041145 assert!(format!("{}", ringbuf).as_slice() == "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]");
1146
1147 let ringbuf: RingBuf<&str> = vec!["just", "one", "test", "more"].iter()
1148 .map(|&s| s)
1149 .collect();
1150 assert!(format!("{}", ringbuf).as_slice() == "[just, one, test, more]");
1151 }
Michael Sullivanc854d6e2012-07-03 17:52:321152}