blob: fcf9e33cc9d9e7a93b15925cd13d49d45d656ee6 [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
Tom Jakubowskid6a39412014-06-09 07:30:0418use core::default::Default;
Alex Crichton6a585372014-05-30 01:50:1219use core::fmt;
nham63615772014-07-27 03:18:5620use core::iter;
Colin Sherratt7a666df2014-10-19 20:19:0721use core::raw::Slice as RawSlice;
22use core::ptr;
23use core::kinds::marker;
24use core::mem;
25use core::num;
Alex Crichton998fece2013-05-06 04:42:5426
Colin Sherratt7a666df2014-10-19 20:19:0727use std::hash::{Writer, Hash};
28use std::cmp;
29
30use alloc::heap;
blake2-ppc70523712013-07-10 13:27:1431
blake2-ppc0ff5c172013-07-06 03:42:4532static INITIAL_CAPACITY: uint = 8u; // 2^3
33static MINIMUM_CAPACITY: uint = 2u;
Daniel Micayb47e1e92013-02-16 22:55:5534
Alexis Beingessnercf3b2e42014-11-06 17:24:4735// FIXME(conventions): implement shrink_to_fit. Awkward with the current design, but it should
36// be scrapped anyway. Defer to rewrite?
37// FIXME(conventions): implement into_iter
38
39
P1startf2aa88c2014-08-04 10:48:3940/// `RingBuf` is a circular buffer that implements `Deque`.
blake2-ppc70523712013-07-10 13:27:1441pub struct RingBuf<T> {
Colin Sherratt7a666df2014-10-19 20:19:0742 // tail and head are pointers into the buffer. Tail always points
43 // to the first element that could be read, Head always points
44 // to where data should be written.
45 // If tail == head the buffer is empty. The length of the ringbuf
46 // is defined as the distance between the two.
47
48 tail: uint,
49 head: uint,
50 cap: uint,
51 ptr: *mut T
52}
53
54impl<T: Clone> Clone for RingBuf<T> {
55 fn clone(&self) -> RingBuf<T> {
56 self.iter().map(|t| t.clone()).collect()
57 }
58}
59
60#[unsafe_destructor]
61impl<T> Drop for RingBuf<T> {
62 fn drop(&mut self) {
63 self.clear();
64 unsafe {
65 if mem::size_of::<T>() != 0 {
66 heap::deallocate(self.ptr as *mut u8,
67 self.cap * mem::size_of::<T>(),
68 mem::min_align_of::<T>())
69 }
70 }
71 }
Marijn Haverbeke26610db2012-01-11 11:49:3372}
Roy Frostig9c818892010-07-21 01:03:0973
Tom Jakubowskid6a39412014-06-09 07:30:0474impl<T> Default for RingBuf<T> {
75 #[inline]
76 fn default() -> RingBuf<T> { RingBuf::new() }
77}
78
blake2-ppc70523712013-07-10 13:27:1479impl<T> RingBuf<T> {
Colin Sherratt7a666df2014-10-19 20:19:0780 /// Turn ptr into a slice
81 #[inline]
82 unsafe fn buffer_as_slice(&self) -> &[T] {
83 mem::transmute(RawSlice { data: self.ptr as *const T, len: self.cap })
84 }
85
86 /// Moves an element out of the buffer
87 #[inline]
88 unsafe fn buffer_read(&mut self, off: uint) -> T {
89 ptr::read(self.ptr.offset(off as int) as *const T)
90 }
91
92 /// Writes an element into the buffer, moving it.
93 #[inline]
94 unsafe fn buffer_write(&mut self, off: uint, t: T) {
95 ptr::write(self.ptr.offset(off as int), t);
96 }
97
98 /// Returns true iff the buffer is at capacity
99 #[inline]
100 fn is_full(&self) -> bool { self.cap - self.len() == 1 }
101}
102
103impl<T> RingBuf<T> {
P1startf2aa88c2014-08-04 10:48:39104 /// Creates an empty `RingBuf`.
Alexis Beingessnercf3b2e42014-11-06 17:24:47105 #[unstable = "matches collection reform specification, waiting for dust to settle"]
blake2-ppc70523712013-07-10 13:27:14106 pub fn new() -> RingBuf<T> {
107 RingBuf::with_capacity(INITIAL_CAPACITY)
108 }
109
P1startf2aa88c2014-08-04 10:48:39110 /// Creates an empty `RingBuf` with space for at least `n` elements.
Alexis Beingessnercf3b2e42014-11-06 17:24:47111 #[unstable = "matches collection reform specification, waiting for dust to settle"]
blake2-ppc70523712013-07-10 13:27:14112 pub fn with_capacity(n: uint) -> RingBuf<T> {
Colin Sherratt7a666df2014-10-19 20:19:07113 // +1 since the ringbuffer always leaves one space empty
114 let cap = num::next_power_of_two(cmp::max(n + 1, MINIMUM_CAPACITY));
115 let size = cap.checked_mul(&mem::size_of::<T>())
116 .expect("capacity overflow");
117
118 RingBuf {
119 tail: 0,
120 head: 0,
121 cap: cap,
122 ptr: if mem::size_of::<T>() != 0 {
123 unsafe { heap::allocate(size, mem::min_align_of::<T>()) as *mut T }
124 } else {
125 heap::EMPTY as *mut T
126 }
127 }
blake2-ppc70523712013-07-10 13:27:14128 }
129
P1startf2aa88c2014-08-04 10:48:39130 /// Retrieves an element in the `RingBuf` by index.
blake2-ppc70523712013-07-10 13:27:14131 ///
Alexis Beingessnercf3b2e42014-11-06 17:24:47132 /// # Example
133 ///
134 /// ```rust
135 /// use std::collections::RingBuf;
136 ///
137 /// let mut buf = RingBuf::new();
138 /// buf.push_back(3i);
139 /// buf.push_back(4);
140 /// buf.push_back(5);
141 /// assert_eq!(buf.get(1).unwrap(), &4);
142 /// ```
143 #[unstable = "matches collection reform specification, waiting for dust to settle"]
144 pub fn get(&self, i: uint) -> Option<&T> {
Colin Sherratt7a666df2014-10-19 20:19:07145 if i < self.len() {
146 let idx = wrap_index(self.tail + i, self.cap);
147 unsafe { Some(&*self.ptr.offset(idx as int)) }
148 } else {
149 None
Alexis Beingessnercf3b2e42014-11-06 17:24:47150 }
151 }
152
153 /// Retrieves an element in the `RingBuf` mutably by index.
nhamebe80972014-07-17 23:19:51154 ///
155 /// # Example
156 ///
157 /// ```rust
158 /// use std::collections::RingBuf;
159 ///
160 /// let mut buf = RingBuf::new();
Alexis Beingessnercf3b2e42014-11-06 17:24:47161 /// buf.push_back(3i);
162 /// buf.push_back(4);
163 /// buf.push_back(5);
164 /// match buf.get_mut(1) {
165 /// None => {}
166 /// Some(elem) => {
167 /// *elem = 7;
168 /// }
169 /// }
170 ///
P1startfd10d202014-08-02 06:39:39171 /// assert_eq!(buf[1], 7);
nhamebe80972014-07-17 23:19:51172 /// ```
Alexis Beingessnercf3b2e42014-11-06 17:24:47173 #[unstable = "matches collection reform specification, waiting for dust to settle"]
174 pub fn get_mut(&mut self, i: uint) -> Option<&mut T> {
Colin Sherratt7a666df2014-10-19 20:19:07175 if i < self.len() {
176 let idx = wrap_index(self.tail + i, self.cap);
177 unsafe { Some(&mut *self.ptr.offset(idx as int)) }
178 } else {
179 None
Alexis Beingessnercf3b2e42014-11-06 17:24:47180 }
blake2-ppc70523712013-07-10 13:27:14181 }
182
P1startf2aa88c2014-08-04 10:48:39183 /// Swaps elements at indices `i` and `j`.
blake2-ppc57757a82013-09-26 07:19:26184 ///
185 /// `i` and `j` may be equal.
186 ///
P1startf2aa88c2014-08-04 10:48:39187 /// Fails if there is no element with either index.
nhamebe80972014-07-17 23:19:51188 ///
189 /// # Example
190 ///
191 /// ```rust
192 /// use std::collections::RingBuf;
193 ///
194 /// let mut buf = RingBuf::new();
Alexis Beingessnercf3b2e42014-11-06 17:24:47195 /// buf.push_back(3i);
196 /// buf.push_back(4);
197 /// buf.push_back(5);
nhamebe80972014-07-17 23:19:51198 /// buf.swap(0, 2);
P1startfd10d202014-08-02 06:39:39199 /// assert_eq!(buf[0], 5);
200 /// assert_eq!(buf[2], 3);
nhamebe80972014-07-17 23:19:51201 /// ```
blake2-ppc57757a82013-09-26 07:19:26202 pub fn swap(&mut self, i: uint, j: uint) {
203 assert!(i < self.len());
204 assert!(j < self.len());
Colin Sherratt7a666df2014-10-19 20:19:07205 let ri = wrap_index(self.tail + i, self.cap);
206 let rj = wrap_index(self.tail + j, self.cap);
207 unsafe {
208 ptr::swap(self.ptr.offset(ri as int), self.ptr.offset(rj as int))
209 }
blake2-ppc70523712013-07-10 13:27:14210 }
211
Alexis Beingessnercf3b2e42014-11-06 17:24:47212 /// Returns the number of elements the `RingBuf` can hold without
213 /// reallocating.
214 ///
215 /// # Example
216 ///
217 /// ```
218 /// use std::collections::RingBuf;
219 ///
220 /// let buf: RingBuf<int> = RingBuf::with_capacity(10);
Colin Sherratt7a666df2014-10-19 20:19:07221 /// assert!(buf.capacity() >= 10);
Alexis Beingessnercf3b2e42014-11-06 17:24:47222 /// ```
223 #[inline]
224 #[unstable = "matches collection reform specification, waiting for dust to settle"]
Colin Sherratt7a666df2014-10-19 20:19:07225 pub fn capacity(&self) -> uint { self.cap - 1 }
Tim Chevalier77de84b2013-05-27 18:47:38226
Alexis Beingessnercf3b2e42014-11-06 17:24:47227 /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the
228 /// given `RingBuf`. Does nothing if the capacity is already sufficient.
Tim Chevalier77de84b2013-05-27 18:47:38229 ///
Alexis Beingessnercf3b2e42014-11-06 17:24:47230 /// Note that the allocator may give the collection more space than it requests. Therefore
231 /// capacity can not be relied upon to be precisely minimal. Prefer `reserve` if future
232 /// insertions are expected.
233 ///
234 /// # Panics
235 ///
236 /// Panics if the new capacity overflows `uint`.
237 ///
238 /// # Example
239 ///
240 /// ```
241 /// use std::collections::RingBuf;
242 ///
243 /// let mut buf: RingBuf<int> = vec![1].into_iter().collect();
244 /// buf.reserve_exact(10);
245 /// assert!(buf.capacity() >= 11);
246 /// ```
247 #[unstable = "matches collection reform specification, waiting for dust to settle"]
248 pub fn reserve_exact(&mut self, additional: uint) {
Colin Sherratt7a666df2014-10-19 20:19:07249 self.reserve(additional);
Alexis Beingessnercf3b2e42014-11-06 17:24:47250 }
251
252 /// Reserves capacity for at least `additional` more elements to be inserted in the given
253 /// `Ringbuf`. The collection may reserve more space to avoid frequent reallocations.
254 ///
255 /// # Panics
256 ///
257 /// Panics if the new capacity overflows `uint`.
258 ///
259 /// # Example
260 ///
261 /// ```
262 /// use std::collections::RingBuf;
263 ///
264 /// let mut buf: RingBuf<int> = vec![1].into_iter().collect();
265 /// buf.reserve(10);
266 /// assert!(buf.capacity() >= 11);
267 /// ```
268 #[unstable = "matches collection reform specification, waiting for dust to settle"]
269 pub fn reserve(&mut self, additional: uint) {
Colin Sherratt7a666df2014-10-19 20:19:07270 let new_len = self.len() + additional;
271 assert!(new_len + 1 > self.len(), "capacity overflow");
272 if new_len > self.capacity() {
273 let count = num::next_power_of_two(new_len + 1);
274 assert!(count >= new_len + 1);
275
276 if mem::size_of::<T>() != 0 {
277 let old = self.cap * mem::size_of::<T>();
278 let new = count.checked_mul(&mem::size_of::<T>())
279 .expect("capacity overflow");
280 unsafe {
281 self.ptr = heap::reallocate(self.ptr as *mut u8,
282 old,
283 new,
284 mem::min_align_of::<T>()) as *mut T;
285 }
286 }
287
288 // Move the shortest contiguous section of the ring buffer
289 // T H
290 // [o o o o o o o . ]
291 // T H
292 // A [o o o o o o o . . . . . . . . . ]
293 // H T
294 // [o o . o o o o o ]
295 // T H
296 // B [. . . o o o o o o o . . . . . . ]
297 // H T
298 // [o o o o o . o o ]
299 // H T
300 // C [o o o o o . . . . . . . . . o o ]
301
302 let oldcap = self.cap;
303 self.cap = count;
304
305 if self.tail <= self.head { // A
306 // Nop
307 } else if self.head < oldcap - self.tail { // B
308 unsafe {
309 ptr::copy_nonoverlapping_memory(
310 self.ptr.offset(oldcap as int),
311 self.ptr as *const T,
312 self.head
313 );
314 }
315 self.head += oldcap;
316 } else { // C
317 unsafe {
318 ptr::copy_nonoverlapping_memory(
319 self.ptr.offset((count - (oldcap - self.tail)) as int),
320 self.ptr.offset(self.tail as int) as *const T,
321 oldcap - self.tail
322 );
323 }
324 self.tail = count - (oldcap - self.tail);
325 }
326 }
Tim Chevalier77de84b2013-05-27 18:47:38327 }
Jed Estep4f7a7422013-06-25 19:08:47328
P1startf2aa88c2014-08-04 10:48:39329 /// Returns a front-to-back iterator.
nhamebe80972014-07-17 23:19:51330 ///
331 /// # Example
332 ///
333 /// ```rust
334 /// use std::collections::RingBuf;
335 ///
336 /// let mut buf = RingBuf::new();
Alexis Beingessnercf3b2e42014-11-06 17:24:47337 /// buf.push_back(5i);
338 /// buf.push_back(3);
339 /// buf.push_back(4);
Nick Cameron52ef4622014-08-06 09:59:40340 /// let b: &[_] = &[&5, &3, &4];
341 /// assert_eq!(buf.iter().collect::<Vec<&int>>().as_slice(), b);
nhamebe80972014-07-17 23:19:51342 /// ```
Alexis Beingessnercf3b2e42014-11-06 17:24:47343 #[unstable = "matches collection reform specification, waiting for dust to settle"]
Alex Crichton21ac9852014-10-30 20:43:24344 pub fn iter(&self) -> Items<T> {
Colin Sherratt7a666df2014-10-19 20:19:07345 Items {
346 tail: self.tail,
347 head: self.head,
348 ring: unsafe { self.buffer_as_slice() }
349 }
blake2-ppc3385e792013-07-15 23:13:26350 }
351
P1startf2aa88c2014-08-04 10:48:39352 /// Returns a front-to-back iterator which returns mutable references.
nhamebe80972014-07-17 23:19:51353 ///
354 /// # Example
355 ///
356 /// ```rust
357 /// use std::collections::RingBuf;
358 ///
359 /// let mut buf = RingBuf::new();
Alexis Beingessnercf3b2e42014-11-06 17:24:47360 /// buf.push_back(5i);
361 /// buf.push_back(3);
362 /// buf.push_back(4);
Aaron Turonfc525ee2014-09-15 03:27:36363 /// for num in buf.iter_mut() {
nhamebe80972014-07-17 23:19:51364 /// *num = *num - 2;
365 /// }
Nick Cameron52ef4622014-08-06 09:59:40366 /// let b: &[_] = &[&mut 3, &mut 1, &mut 2];
Nick Cameron59976942014-09-24 11:41:09367 /// assert_eq!(buf.iter_mut().collect::<Vec<&mut int>>()[], b);
nhamebe80972014-07-17 23:19:51368 /// ```
Alexis Beingessnercf3b2e42014-11-06 17:24:47369 #[unstable = "matches collection reform specification, waiting for dust to settle"]
Colin Sherratt7a666df2014-10-19 20:19:07370 pub fn iter_mut<'a>(&'a mut self) -> MutItems<'a, T> {
371 MutItems {
372 tail: self.tail,
373 head: self.head,
374 cap: self.cap,
375 ptr: self.ptr,
376 marker: marker::ContravariantLifetime::<'a>,
377 marker2: marker::NoCopy
Niko Matsakisbc4164d2013-11-16 22:29:39378 }
Jed Estep4f7a7422013-06-25 19:08:47379 }
Alex Crichton21ac9852014-10-30 20:43:24380
381 /// Returns the number of elements in the `RingBuf`.
382 ///
383 /// # Example
384 ///
385 /// ```
386 /// use std::collections::RingBuf;
387 ///
388 /// let mut v = RingBuf::new();
389 /// assert_eq!(v.len(), 0);
Alexis Beingessnercf3b2e42014-11-06 17:24:47390 /// v.push_back(1i);
Alex Crichton21ac9852014-10-30 20:43:24391 /// assert_eq!(v.len(), 1);
392 /// ```
Alexis Beingessnercf3b2e42014-11-06 17:24:47393 #[unstable = "matches collection reform specification, waiting for dust to settle"]
Colin Sherratt7a666df2014-10-19 20:19:07394 pub fn len(&self) -> uint { count(self.tail, self.head, self.cap) }
Alex Crichton21ac9852014-10-30 20:43:24395
396 /// Returns true if the buffer contains no elements
397 ///
398 /// # Example
399 ///
400 /// ```
401 /// use std::collections::RingBuf;
402 ///
403 /// let mut v = RingBuf::new();
404 /// assert!(v.is_empty());
405 /// v.push_front(1i);
406 /// assert!(!v.is_empty());
407 /// ```
Alexis Beingessnercf3b2e42014-11-06 17:24:47408 #[unstable = "matches collection reform specification, waiting for dust to settle"]
Alex Crichton21ac9852014-10-30 20:43:24409 pub fn is_empty(&self) -> bool { self.len() == 0 }
410
411 /// Clears the buffer, removing all values.
412 ///
413 /// # Example
414 ///
415 /// ```
416 /// use std::collections::RingBuf;
417 ///
418 /// let mut v = RingBuf::new();
Alexis Beingessnercf3b2e42014-11-06 17:24:47419 /// v.push_back(1i);
Alex Crichton21ac9852014-10-30 20:43:24420 /// v.clear();
421 /// assert!(v.is_empty());
422 /// ```
Alexis Beingessnercf3b2e42014-11-06 17:24:47423 #[unstable = "matches collection reform specification, waiting for dust to settle"]
Alex Crichton21ac9852014-10-30 20:43:24424 pub fn clear(&mut self) {
Colin Sherratt7a666df2014-10-19 20:19:07425 while !self.is_empty() {
426 self.pop_front();
427 }
428 self.head = 0;
429 self.tail = 0;
Alex Crichton21ac9852014-10-30 20:43:24430 }
431
432 /// Provides a reference to the front element, or `None` if the sequence is
433 /// empty.
434 ///
435 /// # Example
436 ///
437 /// ```
438 /// use std::collections::RingBuf;
439 ///
440 /// let mut d = RingBuf::new();
441 /// assert_eq!(d.front(), None);
442 ///
Alexis Beingessnercf3b2e42014-11-06 17:24:47443 /// d.push_back(1i);
444 /// d.push_back(2i);
Alex Crichton21ac9852014-10-30 20:43:24445 /// assert_eq!(d.front(), Some(&1i));
446 /// ```
Alexis Beingessnercf3b2e42014-11-06 17:24:47447 #[unstable = "matches collection reform specification, waiting for dust to settle"]
Alex Crichton21ac9852014-10-30 20:43:24448 pub fn front(&self) -> Option<&T> {
Colin Sherratt7a666df2014-10-19 20:19:07449 if !self.is_empty() { Some(&self[0]) } else { None }
Alex Crichton21ac9852014-10-30 20:43:24450 }
451
452 /// Provides a mutable reference to the front element, or `None` if the
453 /// sequence is empty.
454 ///
455 /// # Example
456 ///
457 /// ```
458 /// use std::collections::RingBuf;
459 ///
460 /// let mut d = RingBuf::new();
461 /// assert_eq!(d.front_mut(), None);
462 ///
Alexis Beingessnercf3b2e42014-11-06 17:24:47463 /// d.push_back(1i);
464 /// d.push_back(2i);
Alex Crichton21ac9852014-10-30 20:43:24465 /// match d.front_mut() {
466 /// Some(x) => *x = 9i,
467 /// None => (),
468 /// }
469 /// assert_eq!(d.front(), Some(&9i));
470 /// ```
Alexis Beingessnercf3b2e42014-11-06 17:24:47471 #[unstable = "matches collection reform specification, waiting for dust to settle"]
Alex Crichton21ac9852014-10-30 20:43:24472 pub fn front_mut(&mut self) -> Option<&mut T> {
Colin Sherratt7a666df2014-10-19 20:19:07473 if !self.is_empty() { Some(&mut self[0]) } else { None }
Alex Crichton21ac9852014-10-30 20:43:24474 }
475
476 /// Provides a reference to the back element, or `None` if the sequence is
477 /// empty.
478 ///
479 /// # Example
480 ///
481 /// ```
482 /// use std::collections::RingBuf;
483 ///
484 /// let mut d = RingBuf::new();
485 /// assert_eq!(d.back(), None);
486 ///
Alexis Beingessnercf3b2e42014-11-06 17:24:47487 /// d.push_back(1i);
488 /// d.push_back(2i);
Alex Crichton21ac9852014-10-30 20:43:24489 /// assert_eq!(d.back(), Some(&2i));
490 /// ```
Alexis Beingessnercf3b2e42014-11-06 17:24:47491 #[unstable = "matches collection reform specification, waiting for dust to settle"]
Alex Crichton21ac9852014-10-30 20:43:24492 pub fn back(&self) -> Option<&T> {
Colin Sherratt7a666df2014-10-19 20:19:07493 if !self.is_empty() { Some(&self[self.len() - 1]) } else { None }
Alex Crichton21ac9852014-10-30 20:43:24494 }
495
496 /// Provides a mutable reference to the back element, or `None` if the
497 /// sequence is empty.
498 ///
499 /// # Example
500 ///
501 /// ```
502 /// use std::collections::RingBuf;
503 ///
504 /// let mut d = RingBuf::new();
505 /// assert_eq!(d.back(), None);
506 ///
Alexis Beingessnercf3b2e42014-11-06 17:24:47507 /// d.push_back(1i);
508 /// d.push_back(2i);
Alex Crichton21ac9852014-10-30 20:43:24509 /// match d.back_mut() {
510 /// Some(x) => *x = 9i,
511 /// None => (),
512 /// }
513 /// assert_eq!(d.back(), Some(&9i));
514 /// ```
Alexis Beingessnercf3b2e42014-11-06 17:24:47515 #[unstable = "matches collection reform specification, waiting for dust to settle"]
Alex Crichton21ac9852014-10-30 20:43:24516 pub fn back_mut(&mut self) -> Option<&mut T> {
Colin Sherratt7a666df2014-10-19 20:19:07517 let len = self.len();
518 if !self.is_empty() { Some(&mut self[len - 1]) } else { None }
Alex Crichton21ac9852014-10-30 20:43:24519 }
520
521 /// Removes the first element and returns it, or `None` if the sequence is
522 /// empty.
523 ///
524 /// # Example
525 ///
526 /// ```
527 /// use std::collections::RingBuf;
528 ///
529 /// let mut d = RingBuf::new();
Alexis Beingessnercf3b2e42014-11-06 17:24:47530 /// d.push_back(1i);
531 /// d.push_back(2i);
Alex Crichton21ac9852014-10-30 20:43:24532 ///
533 /// assert_eq!(d.pop_front(), Some(1i));
534 /// assert_eq!(d.pop_front(), Some(2i));
535 /// assert_eq!(d.pop_front(), None);
536 /// ```
Alexis Beingessnercf3b2e42014-11-06 17:24:47537 #[unstable = "matches collection reform specification, waiting for dust to settle"]
Alex Crichton21ac9852014-10-30 20:43:24538 pub fn pop_front(&mut self) -> Option<T> {
Colin Sherratt7a666df2014-10-19 20:19:07539 if self.is_empty() {
540 None
541 } else {
542 let tail = self.tail;
543 self.tail = wrap_index(self.tail + 1, self.cap);
544 unsafe { Some(self.buffer_read(tail)) }
Alex Crichton21ac9852014-10-30 20:43:24545 }
Alex Crichton21ac9852014-10-30 20:43:24546 }
547
548 /// Inserts an element first in the sequence.
549 ///
550 /// # Example
551 ///
552 /// ```
553 /// use std::collections::RingBuf;
554 ///
555 /// let mut d = RingBuf::new();
556 /// d.push_front(1i);
557 /// d.push_front(2i);
558 /// assert_eq!(d.front(), Some(&2i));
559 /// ```
Alexis Beingessnercf3b2e42014-11-06 17:24:47560 #[unstable = "matches collection reform specification, waiting for dust to settle"]
Alex Crichton21ac9852014-10-30 20:43:24561 pub fn push_front(&mut self, t: T) {
Colin Sherratt7a666df2014-10-19 20:19:07562 if self.is_full() { self.reserve(1) }
563
564 self.tail = wrap_index(self.tail - 1, self.cap);
565 let tail = self.tail;
566 unsafe { self.buffer_write(tail, t); }
Alex Crichton21ac9852014-10-30 20:43:24567 }
568
Alexis Beingessnercf3b2e42014-11-06 17:24:47569 /// Deprecated: Renamed to `push_back`.
570 #[deprecated = "Renamed to `push_back`"]
571 pub fn push(&mut self, t: T) {
572 self.push_back(t)
573 }
574
Alex Crichton21ac9852014-10-30 20:43:24575 /// Appends an element to the back of a buffer
576 ///
577 /// # Example
578 ///
579 /// ```rust
580 /// use std::collections::RingBuf;
581 ///
582 /// let mut buf = RingBuf::new();
Alexis Beingessnercf3b2e42014-11-06 17:24:47583 /// buf.push_back(1i);
584 /// buf.push_back(3);
Alex Crichton21ac9852014-10-30 20:43:24585 /// assert_eq!(3, *buf.back().unwrap());
586 /// ```
Alexis Beingessnercf3b2e42014-11-06 17:24:47587 #[unstable = "matches collection reform specification, waiting for dust to settle"]
588 pub fn push_back(&mut self, t: T) {
Colin Sherratt7a666df2014-10-19 20:19:07589 if self.is_full() { self.reserve(1) }
590
591 let head = self.head;
592 self.head = wrap_index(self.head + 1, self.cap);
593 unsafe { self.buffer_write(head, t) }
Alex Crichton21ac9852014-10-30 20:43:24594 }
595
Alexis Beingessnercf3b2e42014-11-06 17:24:47596 /// Deprecated: Renamed to `pop_back`.
597 #[deprecated = "Renamed to `pop_back`"]
598 pub fn pop(&mut self) -> Option<T> {
599 self.pop_back()
600 }
601
Alex Crichton21ac9852014-10-30 20:43:24602 /// Removes the last element from a buffer and returns it, or `None` if
603 /// it is empty.
604 ///
605 /// # Example
606 ///
607 /// ```rust
608 /// use std::collections::RingBuf;
609 ///
610 /// let mut buf = RingBuf::new();
Alexis Beingessnercf3b2e42014-11-06 17:24:47611 /// assert_eq!(buf.pop_back(), None);
612 /// buf.push_back(1i);
613 /// buf.push_back(3);
614 /// assert_eq!(buf.pop_back(), Some(3));
Alex Crichton21ac9852014-10-30 20:43:24615 /// ```
Alexis Beingessnercf3b2e42014-11-06 17:24:47616 #[unstable = "matches collection reform specification, waiting for dust to settle"]
617 pub fn pop_back(&mut self) -> Option<T> {
Colin Sherratt7a666df2014-10-19 20:19:07618 if self.is_empty() {
Alex Crichton21ac9852014-10-30 20:43:24619 None
Colin Sherratt7a666df2014-10-19 20:19:07620 } else {
621 self.head = wrap_index(self.head - 1, self.cap);
622 let head = self.head;
623 unsafe { Some(self.buffer_read(head)) }
Alex Crichton21ac9852014-10-30 20:43:24624 }
625 }
Jed Estep4f7a7422013-06-25 19:08:47626}
627
Colin Sherratt7a666df2014-10-19 20:19:07628/// Returns the index in the underlying buffer for a given logical element index.
629#[inline]
630fn wrap_index(index: uint, size: uint) -> uint {
631 // size is always a power of 2
632 index & (size - 1)
633}
634
635/// Calculate the number of elements left to be read in the buffer
636#[inline]
637fn count(tail: uint, head: uint, size: uint) -> uint {
638 // size is always a power of 2
639 (head - tail) & (size - 1)
640}
641
Niko Matsakis1b487a82014-08-28 01:46:52642/// `RingBuf` iterator.
Niko Matsakis1b487a82014-08-28 01:46:52643pub struct Items<'a, T:'a> {
Colin Sherratt7a666df2014-10-19 20:19:07644 ring: &'a [T],
645 tail: uint,
646 head: uint
Niko Matsakis1b487a82014-08-28 01:46:52647}
648
Palmer Cox3fd8c8b2014-01-15 03:32:24649impl<'a, T> Iterator<&'a T> for Items<'a, T> {
Niko Matsakisbc4164d2013-11-16 22:29:39650 #[inline]
Erik Price5731ca32013-12-10 07:16:18651 fn next(&mut self) -> Option<&'a T> {
Colin Sherratt7a666df2014-10-19 20:19:07652 if self.tail == self.head {
Niko Matsakisbc4164d2013-11-16 22:29:39653 return None;
654 }
Colin Sherratt7a666df2014-10-19 20:19:07655 let tail = self.tail;
656 self.tail = wrap_index(self.tail + 1, self.ring.len());
657 unsafe { Some(self.ring.unsafe_get(tail)) }
Niko Matsakisbc4164d2013-11-16 22:29:39658 }
659
660 #[inline]
661 fn size_hint(&self) -> (uint, Option<uint>) {
Colin Sherratt7a666df2014-10-19 20:19:07662 let len = count(self.tail, self.head, self.ring.len());
Niko Matsakisbc4164d2013-11-16 22:29:39663 (len, Some(len))
664 }
665}
666
Palmer Cox3fd8c8b2014-01-15 03:32:24667impl<'a, T> DoubleEndedIterator<&'a T> for Items<'a, T> {
Niko Matsakisbc4164d2013-11-16 22:29:39668 #[inline]
Erik Price5731ca32013-12-10 07:16:18669 fn next_back(&mut self) -> Option<&'a T> {
Colin Sherratt7a666df2014-10-19 20:19:07670 if self.tail == self.head {
Niko Matsakisbc4164d2013-11-16 22:29:39671 return None;
672 }
Colin Sherratt7a666df2014-10-19 20:19:07673 self.head = wrap_index(self.head - 1, self.ring.len());
674 unsafe { Some(self.ring.unsafe_get(self.head)) }
Niko Matsakisbc4164d2013-11-16 22:29:39675 }
676}
Jed Estep35314c92013-06-26 15:38:29677
Colin Sherratt7a666df2014-10-19 20:19:07678
Palmer Cox3fd8c8b2014-01-15 03:32:24679impl<'a, T> ExactSize<&'a T> for Items<'a, T> {}
blake2-ppc7c369ee72013-09-01 16:20:24680
Palmer Cox3fd8c8b2014-01-15 03:32:24681impl<'a, T> RandomAccessIterator<&'a T> for Items<'a, T> {
blake2-ppcf6862132013-07-29 18:16:26682 #[inline]
Colin Sherratt7a666df2014-10-19 20:19:07683 fn indexable(&self) -> uint {
684 let (len, _) = self.size_hint();
685 len
686 }
blake2-ppcf6862132013-07-29 18:16:26687
688 #[inline]
Alex Crichtonf4083a22014-04-22 05:15:42689 fn idx(&mut self, j: uint) -> Option<&'a T> {
blake2-ppcf6862132013-07-29 18:16:26690 if j >= self.indexable() {
691 None
692 } else {
Colin Sherratt7a666df2014-10-19 20:19:07693 let idx = wrap_index(self.tail + j, self.ring.len());
694 unsafe { Some(self.ring.unsafe_get(idx)) }
blake2-ppcf6862132013-07-29 18:16:26695 }
696 }
697}
698
Colin Sherratt7a666df2014-10-19 20:19:07699// FIXME This was implemented differently from Items because of a problem
700// with returning the mutable reference. I couldn't find a way to
701// make the lifetime checker happy so, but there should be a way.
Niko Matsakis1b487a82014-08-28 01:46:52702/// `RingBuf` mutable iterator.
Niko Matsakis1b487a82014-08-28 01:46:52703pub struct MutItems<'a, T:'a> {
Colin Sherratt7a666df2014-10-19 20:19:07704 ptr: *mut T,
705 tail: uint,
706 head: uint,
707 cap: uint,
708 marker: marker::ContravariantLifetime<'a>,
709 marker2: marker::NoCopy
Niko Matsakis1b487a82014-08-28 01:46:52710}
711
Palmer Cox3fd8c8b2014-01-15 03:32:24712impl<'a, T> Iterator<&'a mut T> for MutItems<'a, T> {
Niko Matsakisbc4164d2013-11-16 22:29:39713 #[inline]
Erik Price5731ca32013-12-10 07:16:18714 fn next(&mut self) -> Option<&'a mut T> {
Colin Sherratt7a666df2014-10-19 20:19:07715 if self.tail == self.head {
Niko Matsakisbc4164d2013-11-16 22:29:39716 return None;
717 }
Colin Sherratt7a666df2014-10-19 20:19:07718 let tail = self.tail;
719 self.tail = wrap_index(self.tail + 1, self.cap);
720 if mem::size_of::<T>() != 0 {
721 unsafe { Some(&mut *self.ptr.offset(tail as int)) }
722 } else {
723 // use a none zero pointer
724 Some(unsafe { mem::transmute(1u) })
Alex Crichton9d5d97b2014-10-15 06:05:01725 }
Niko Matsakisbc4164d2013-11-16 22:29:39726 }
727
728 #[inline]
729 fn size_hint(&self) -> (uint, Option<uint>) {
Colin Sherratt7a666df2014-10-19 20:19:07730 let len = count(self.tail, self.head, self.cap);
731 (len, Some(len))
Niko Matsakisbc4164d2013-11-16 22:29:39732 }
733}
734
Palmer Cox3fd8c8b2014-01-15 03:32:24735impl<'a, T> DoubleEndedIterator<&'a mut T> for MutItems<'a, T> {
Niko Matsakisbc4164d2013-11-16 22:29:39736 #[inline]
Erik Price5731ca32013-12-10 07:16:18737 fn next_back(&mut self) -> Option<&'a mut T> {
Colin Sherratt7a666df2014-10-19 20:19:07738 if self.tail == self.head {
Niko Matsakisbc4164d2013-11-16 22:29:39739 return None;
740 }
Colin Sherratt7a666df2014-10-19 20:19:07741 self.head = wrap_index(self.head - 1, self.cap);
742 unsafe { Some(&mut *self.ptr.offset(self.head as int)) }
Niko Matsakisbc4164d2013-11-16 22:29:39743 }
744}
Daniel Micayb47e1e92013-02-16 22:55:55745
Palmer Cox3fd8c8b2014-01-15 03:32:24746impl<'a, T> ExactSize<&'a mut T> for MutItems<'a, T> {}
blake2-ppc7c369ee72013-09-01 16:20:24747
Alex Crichton748bc3c2014-05-30 00:45:07748impl<A: PartialEq> PartialEq for RingBuf<A> {
blake2-ppc70523712013-07-10 13:27:14749 fn eq(&self, other: &RingBuf<A>) -> bool {
Colin Sherratt7a666df2014-10-19 20:19:07750 self.len() == other.len() &&
blake2-ppc10c76982013-07-06 13:27:32751 self.iter().zip(other.iter()).all(|(a, b)| a.eq(b))
752 }
blake2-ppc70523712013-07-10 13:27:14753 fn ne(&self, other: &RingBuf<A>) -> bool {
blake2-ppc10c76982013-07-06 13:27:32754 !self.eq(other)
755 }
756}
757
nham25acfde2014-08-01 20:05:03758impl<A: Eq> Eq for RingBuf<A> {}
759
nham63615772014-07-27 03:18:56760impl<A: PartialOrd> PartialOrd for RingBuf<A> {
761 fn partial_cmp(&self, other: &RingBuf<A>) -> Option<Ordering> {
762 iter::order::partial_cmp(self.iter(), other.iter())
763 }
764}
765
nham3737c532014-08-01 20:22:48766impl<A: Ord> Ord for RingBuf<A> {
767 #[inline]
768 fn cmp(&self, other: &RingBuf<A>) -> Ordering {
769 iter::order::cmp(self.iter(), other.iter())
770 }
771}
772
nham1cfa6562014-07-27 02:33:47773impl<S: Writer, A: Hash<S>> Hash<S> for RingBuf<A> {
774 fn hash(&self, state: &mut S) {
nham9fa44242014-07-27 16:37:32775 self.len().hash(state);
nham1cfa6562014-07-27 02:33:47776 for elt in self.iter() {
777 elt.hash(state);
778 }
779 }
780}
781
P1startfd10d202014-08-02 06:39:39782impl<A> Index<uint, A> for RingBuf<A> {
783 #[inline]
784 fn index<'a>(&'a self, i: &uint) -> &'a A {
Colin Sherratt7a666df2014-10-19 20:19:07785 self.get(*i).expect("Out of bounds access")
P1startfd10d202014-08-02 06:39:39786 }
787}
788
Alex Crichton1d356622014-10-23 15:42:21789impl<A> IndexMut<uint, A> for RingBuf<A> {
P1startfd10d202014-08-02 06:39:39790 #[inline]
Alex Crichton1d356622014-10-23 15:42:21791 fn index_mut<'a>(&'a mut self, i: &uint) -> &'a mut A {
Colin Sherratt7a666df2014-10-19 20:19:07792 self.get_mut(*i).expect("Out of bounds access")
P1startfd10d202014-08-02 06:39:39793 }
Alex Crichton1d356622014-10-23 15:42:21794}
P1startfd10d202014-08-02 06:39:39795
Huon Wilson53487a02013-08-13 13:08:14796impl<A> FromIterator<A> for RingBuf<A> {
Brian Andersonee052192014-03-31 04:45:55797 fn from_iter<T: Iterator<A>>(iterator: T) -> RingBuf<A> {
blake2-ppcf8ae5262013-07-30 00:06:49798 let (lower, _) = iterator.size_hint();
799 let mut deq = RingBuf::with_capacity(lower);
800 deq.extend(iterator);
blake2-ppc08dc72f2013-07-06 03:42:45801 deq
802 }
803}
804
gamazeps16c8cd92014-11-08 00:39:39805impl<A> Extend<A> for RingBuf<A> {
Marvin Löbel6200e762014-03-20 13:12:56806 fn extend<T: Iterator<A>>(&mut self, mut iterator: T) {
807 for elt in iterator {
Alexis Beingessnercf3b2e42014-11-06 17:24:47808 self.push_back(elt);
blake2-ppcf8ae5262013-07-30 00:06:49809 }
810 }
811}
812
Alex Crichton6a585372014-05-30 01:50:12813impl<T: fmt::Show> fmt::Show for RingBuf<T> {
Adolfo Ochagavía8e4e3ab2014-06-04 14:15:04814 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
815 try!(write!(f, "["));
816
817 for (i, e) in self.iter().enumerate() {
818 if i != 0 { try!(write!(f, ", ")); }
819 try!(write!(f, "{}", *e));
820 }
821
822 write!(f, "]")
823 }
824}
825
Brian Anderson6e27b272012-01-18 03:05:07826#[cfg(test)]
827mod tests {
Alex Crichton02882fb2014-02-28 09:23:06828 use std::fmt::Show;
Alex Crichton760b93a2014-05-30 02:03:06829 use std::prelude::*;
nham1cfa6562014-07-27 02:33:47830 use std::hash;
Alex Crichton760b93a2014-05-30 02:03:06831 use test::Bencher;
832 use test;
833
Alex Crichtonf47e4b22014-01-07 06:33:50834 use super::RingBuf;
Alex Crichton760b93a2014-05-30 02:03:06835 use vec::Vec;
Patrick Waltonfa5ee932012-12-28 02:24:18836
Brian Anderson6e27b272012-01-18 03:05:07837 #[test]
Victor Berger52ea83d2014-09-22 17:30:06838 #[allow(deprecated)]
Brian Anderson6e27b272012-01-18 03:05:07839 fn test_simple() {
blake2-ppc70523712013-07-10 13:27:14840 let mut d = RingBuf::new();
Corey Richardsoncc57ca02013-05-19 02:02:45841 assert_eq!(d.len(), 0u);
Niko Matsakis9e3d0b02014-04-21 21:58:52842 d.push_front(17i);
843 d.push_front(42i);
Alexis Beingessnercf3b2e42014-11-06 17:24:47844 d.push_back(137);
Corey Richardsoncc57ca02013-05-19 02:02:45845 assert_eq!(d.len(), 3u);
Alexis Beingessnercf3b2e42014-11-06 17:24:47846 d.push_back(137);
Corey Richardsoncc57ca02013-05-19 02:02:45847 assert_eq!(d.len(), 4u);
Luqman Aden3ef9aa02014-10-15 07:22:55848 debug!("{}", d.front());
blake2-ppc70523712013-07-10 13:27:14849 assert_eq!(*d.front().unwrap(), 42);
Luqman Aden3ef9aa02014-10-15 07:22:55850 debug!("{}", d.back());
blake2-ppc70523712013-07-10 13:27:14851 assert_eq!(*d.back().unwrap(), 137);
852 let mut i = d.pop_front();
Luqman Aden3ef9aa02014-10-15 07:22:55853 debug!("{}", i);
blake2-ppc70523712013-07-10 13:27:14854 assert_eq!(i, Some(42));
Alexis Beingessnercf3b2e42014-11-06 17:24:47855 i = d.pop_back();
Luqman Aden3ef9aa02014-10-15 07:22:55856 debug!("{}", i);
blake2-ppc70523712013-07-10 13:27:14857 assert_eq!(i, Some(137));
Alexis Beingessnercf3b2e42014-11-06 17:24:47858 i = d.pop_back();
Luqman Aden3ef9aa02014-10-15 07:22:55859 debug!("{}", i);
blake2-ppc70523712013-07-10 13:27:14860 assert_eq!(i, Some(137));
Alexis Beingessnercf3b2e42014-11-06 17:24:47861 i = d.pop_back();
Luqman Aden3ef9aa02014-10-15 07:22:55862 debug!("{}", i);
blake2-ppc70523712013-07-10 13:27:14863 assert_eq!(i, Some(17));
Corey Richardsoncc57ca02013-05-19 02:02:45864 assert_eq!(d.len(), 0u);
Alexis Beingessnercf3b2e42014-11-06 17:24:47865 d.push_back(3);
Corey Richardsoncc57ca02013-05-19 02:02:45866 assert_eq!(d.len(), 1u);
blake2-ppc70523712013-07-10 13:27:14867 d.push_front(2);
Corey Richardsoncc57ca02013-05-19 02:02:45868 assert_eq!(d.len(), 2u);
Alexis Beingessnercf3b2e42014-11-06 17:24:47869 d.push_back(4);
Corey Richardsoncc57ca02013-05-19 02:02:45870 assert_eq!(d.len(), 3u);
blake2-ppc70523712013-07-10 13:27:14871 d.push_front(1);
Corey Richardsoncc57ca02013-05-19 02:02:45872 assert_eq!(d.len(), 4u);
Alex Crichton9d5d97b2014-10-15 06:05:01873 debug!("{}", d[0]);
874 debug!("{}", d[1]);
875 debug!("{}", d[2]);
876 debug!("{}", d[3]);
877 assert_eq!(d[0], 1);
878 assert_eq!(d[1], 2);
879 assert_eq!(d[2], 3);
880 assert_eq!(d[3], 4);
Brian Anderson6e27b272012-01-18 03:05:07881 }
882
Felix S. Klock IIa636f512013-05-01 23:32:37883 #[cfg(test)]
Alex Crichton748bc3c2014-05-30 00:45:07884 fn test_parameterized<T:Clone + PartialEq + Show>(a: T, b: T, c: T, d: T) {
Patrick Waltondc4bf172013-07-13 04:05:59885 let mut deq = RingBuf::new();
Corey Richardsoncc57ca02013-05-19 02:02:45886 assert_eq!(deq.len(), 0);
Patrick Waltondc4bf172013-07-13 04:05:59887 deq.push_front(a.clone());
888 deq.push_front(b.clone());
Alexis Beingessnercf3b2e42014-11-06 17:24:47889 deq.push_back(c.clone());
Corey Richardsoncc57ca02013-05-19 02:02:45890 assert_eq!(deq.len(), 3);
Alexis Beingessnercf3b2e42014-11-06 17:24:47891 deq.push_back(d.clone());
Corey Richardsoncc57ca02013-05-19 02:02:45892 assert_eq!(deq.len(), 4);
Marvin Löbel0ac7a212013-08-03 23:59:24893 assert_eq!((*deq.front().unwrap()).clone(), b.clone());
894 assert_eq!((*deq.back().unwrap()).clone(), d.clone());
895 assert_eq!(deq.pop_front().unwrap(), b.clone());
Alexis Beingessnercf3b2e42014-11-06 17:24:47896 assert_eq!(deq.pop_back().unwrap(), d.clone());
897 assert_eq!(deq.pop_back().unwrap(), c.clone());
898 assert_eq!(deq.pop_back().unwrap(), a.clone());
Corey Richardsoncc57ca02013-05-19 02:02:45899 assert_eq!(deq.len(), 0);
Alexis Beingessnercf3b2e42014-11-06 17:24:47900 deq.push_back(c.clone());
Corey Richardsoncc57ca02013-05-19 02:02:45901 assert_eq!(deq.len(), 1);
Patrick Waltondc4bf172013-07-13 04:05:59902 deq.push_front(b.clone());
Corey Richardsoncc57ca02013-05-19 02:02:45903 assert_eq!(deq.len(), 2);
Alexis Beingessnercf3b2e42014-11-06 17:24:47904 deq.push_back(d.clone());
Corey Richardsoncc57ca02013-05-19 02:02:45905 assert_eq!(deq.len(), 3);
Patrick Waltondc4bf172013-07-13 04:05:59906 deq.push_front(a.clone());
Corey Richardsoncc57ca02013-05-19 02:02:45907 assert_eq!(deq.len(), 4);
NODA, Kaif27ad3d2014-10-05 10:11:17908 assert_eq!(deq[0].clone(), a.clone());
909 assert_eq!(deq[1].clone(), b.clone());
910 assert_eq!(deq[2].clone(), c.clone());
911 assert_eq!(deq[3].clone(), d.clone());
Brian Anderson6e27b272012-01-18 03:05:07912 }
913
blake2-ppc81933ed2013-07-06 03:42:45914 #[test]
blake2-ppc70523712013-07-10 13:27:14915 fn test_push_front_grow() {
916 let mut deq = RingBuf::new();
Daniel Micay100894552013-08-03 16:45:23917 for i in range(0u, 66) {
blake2-ppc70523712013-07-10 13:27:14918 deq.push_front(i);
blake2-ppc81933ed2013-07-06 03:42:45919 }
920 assert_eq!(deq.len(), 66);
921
Daniel Micay100894552013-08-03 16:45:23922 for i in range(0u, 66) {
NODA, Kaif27ad3d2014-10-05 10:11:17923 assert_eq!(deq[i], 65 - i);
blake2-ppc81933ed2013-07-06 03:42:45924 }
925
blake2-ppc70523712013-07-10 13:27:14926 let mut deq = RingBuf::new();
Daniel Micay100894552013-08-03 16:45:23927 for i in range(0u, 66) {
Alexis Beingessnercf3b2e42014-11-06 17:24:47928 deq.push_back(i);
blake2-ppc81933ed2013-07-06 03:42:45929 }
930
Daniel Micay100894552013-08-03 16:45:23931 for i in range(0u, 66) {
NODA, Kaif27ad3d2014-10-05 10:11:17932 assert_eq!(deq[i], i);
blake2-ppc81933ed2013-07-06 03:42:45933 }
934 }
935
P1startfd10d202014-08-02 06:39:39936 #[test]
937 fn test_index() {
938 let mut deq = RingBuf::new();
939 for i in range(1u, 4) {
940 deq.push_front(i);
941 }
942 assert_eq!(deq[1], 2);
943 }
944
945 #[test]
946 #[should_fail]
947 fn test_index_out_of_bounds() {
948 let mut deq = RingBuf::new();
949 for i in range(1u, 4) {
950 deq.push_front(i);
951 }
952 deq[3];
953 }
954
blake2-ppc81933ed2013-07-06 03:42:45955 #[bench]
Liigo Zhuang408f4842014-04-01 01:16:35956 fn bench_new(b: &mut test::Bencher) {
Patrick Walton38efa172013-11-22 03:20:48957 b.iter(|| {
Patrick Walton86939432013-08-08 18:38:10958 let _: RingBuf<u64> = RingBuf::new();
Patrick Walton38efa172013-11-22 03:20:48959 })
blake2-ppc81933ed2013-07-06 03:42:45960 }
961
962 #[bench]
Colin Sherratt7a666df2014-10-19 20:19:07963 fn bench_push_back_100(b: &mut test::Bencher) {
964 let mut deq = RingBuf::with_capacity(100);
Patrick Walton38efa172013-11-22 03:20:48965 b.iter(|| {
Colin Sherratt7a666df2014-10-19 20:19:07966 for i in range(0i, 100) {
967 deq.push_back(i);
968 }
969 deq.clear();
Patrick Walton38efa172013-11-22 03:20:48970 })
blake2-ppc81933ed2013-07-06 03:42:45971 }
972
973 #[bench]
Colin Sherratt7a666df2014-10-19 20:19:07974 fn bench_push_front_100(b: &mut test::Bencher) {
975 let mut deq = RingBuf::with_capacity(100);
Patrick Walton38efa172013-11-22 03:20:48976 b.iter(|| {
Colin Sherratt7a666df2014-10-19 20:19:07977 for i in range(0i, 100) {
978 deq.push_front(i);
979 }
980 deq.clear();
Patrick Walton38efa172013-11-22 03:20:48981 })
blake2-ppc81933ed2013-07-06 03:42:45982 }
983
984 #[bench]
Colin Sherratt7a666df2014-10-19 20:19:07985 fn bench_pop_100(b: &mut test::Bencher) {
986 let mut deq = RingBuf::with_capacity(100);
987
Patrick Walton38efa172013-11-22 03:20:48988 b.iter(|| {
Colin Sherratt7a666df2014-10-19 20:19:07989 for i in range(0i, 100) {
990 deq.push_back(i);
991 }
992 while None != deq.pop_back() {}
993 })
994 }
995
996 #[bench]
997 fn bench_pop_front_100(b: &mut test::Bencher) {
998 let mut deq = RingBuf::with_capacity(100);
999
1000 b.iter(|| {
1001 for i in range(0i, 100) {
1002 deq.push_back(i);
1003 }
1004 while None != deq.pop_front() {}
1005 })
1006 }
1007
1008 #[bench]
1009 fn bench_grow_1025(b: &mut test::Bencher) {
1010 b.iter(|| {
1011 let mut deq = RingBuf::new();
1012 for i in range(0i, 1025) {
1013 deq.push_front(i);
Brendan Zabarauskas729060d2014-01-30 00:20:341014 }
Patrick Walton38efa172013-11-22 03:20:481015 })
blake2-ppc81933ed2013-07-06 03:42:451016 }
1017
Colin Sherratt7a666df2014-10-19 20:19:071018 #[bench]
1019 fn bench_iter_1000(b: &mut test::Bencher) {
1020 let ring: RingBuf<int> = range(0i, 1000).collect();
1021
1022 b.iter(|| {
1023 let mut sum = 0;
1024 for &i in ring.iter() {
1025 sum += i;
1026 }
1027 sum
1028 })
1029 }
1030
1031 #[bench]
1032 fn bench_mut_iter_1000(b: &mut test::Bencher) {
1033 let mut ring: RingBuf<int> = range(0i, 1000).collect();
1034
1035 b.iter(|| {
1036 for i in ring.iter_mut() {
1037 *i += 1;
1038 }
1039 })
1040 }
1041
1042
Alex Crichton748bc3c2014-05-30 00:45:071043 #[deriving(Clone, PartialEq, Show)]
Patrick Walton99b33f72013-07-02 19:47:321044 enum Taggy {
1045 One(int),
1046 Two(int, int),
1047 Three(int, int, int),
Brian Anderson6e27b272012-01-18 03:05:071048 }
1049
Alex Crichton748bc3c2014-05-30 00:45:071050 #[deriving(Clone, PartialEq, Show)]
Patrick Walton99b33f72013-07-02 19:47:321051 enum Taggypar<T> {
1052 Onepar(int),
1053 Twopar(int, int),
1054 Threepar(int, int, int),
1055 }
1056
Alex Crichton748bc3c2014-05-30 00:45:071057 #[deriving(Clone, PartialEq, Show)]
Erick Tryzelaare84576b2013-01-22 16:44:241058 struct RecCy {
1059 x: int,
1060 y: int,
Patrick Waltoneb4d39e2013-01-26 00:57:391061 t: Taggy
Patrick Walton9117dcb2012-09-20 01:00:261062 }
Kevin Cantuc43426e2012-09-13 05:09:551063
1064 #[test]
1065 fn test_param_int() {
1066 test_parameterized::<int>(5, 72, 64, 175);
1067 }
1068
1069 #[test]
Kevin Cantuc43426e2012-09-13 05:09:551070 fn test_param_taggy() {
Corey Richardsonf8ae9b02013-06-26 22:14:351071 test_parameterized::<Taggy>(One(1), Two(1, 2), Three(1, 2, 3), Two(17, 42));
Kevin Cantuc43426e2012-09-13 05:09:551072 }
1073
1074 #[test]
1075 fn test_param_taggypar() {
1076 test_parameterized::<Taggypar<int>>(Onepar::<int>(1),
Ben Striegela605fd02012-08-11 14:08:421077 Twopar::<int>(1, 2),
1078 Threepar::<int>(1, 2, 3),
1079 Twopar::<int>(17, 42));
Kevin Cantuc43426e2012-09-13 05:09:551080 }
Brian Anderson6e27b272012-01-18 03:05:071081
Kevin Cantuc43426e2012-09-13 05:09:551082 #[test]
1083 fn test_param_reccy() {
Erick Tryzelaare84576b2013-01-22 16:44:241084 let reccy1 = RecCy { x: 1, y: 2, t: One(1) };
1085 let reccy2 = RecCy { x: 345, y: 2, t: Two(1, 2) };
1086 let reccy3 = RecCy { x: 1, y: 777, t: Three(1, 2, 3) };
1087 let reccy4 = RecCy { x: 19, y: 252, t: Two(17, 42) };
Kevin Cantuc43426e2012-09-13 05:09:551088 test_parameterized::<RecCy>(reccy1, reccy2, reccy3, reccy4);
Brian Anderson6e27b272012-01-18 03:05:071089 }
Erick Tryzelaar909d8f02013-03-30 01:02:441090
1091 #[test]
blake2-ppc0ff5c172013-07-06 03:42:451092 fn test_with_capacity() {
blake2-ppc70523712013-07-10 13:27:141093 let mut d = RingBuf::with_capacity(0);
Alexis Beingessnercf3b2e42014-11-06 17:24:471094 d.push_back(1i);
blake2-ppc0ff5c172013-07-06 03:42:451095 assert_eq!(d.len(), 1);
blake2-ppc70523712013-07-10 13:27:141096 let mut d = RingBuf::with_capacity(50);
Alexis Beingessnercf3b2e42014-11-06 17:24:471097 d.push_back(1i);
blake2-ppc0ff5c172013-07-06 03:42:451098 assert_eq!(d.len(), 1);
1099 }
1100
1101 #[test]
Kevin Butler64896d62014-08-07 01:11:131102 fn test_with_capacity_non_power_two() {
1103 let mut d3 = RingBuf::with_capacity(3);
Alexis Beingessnercf3b2e42014-11-06 17:24:471104 d3.push_back(1i);
Kevin Butler64896d62014-08-07 01:11:131105
1106 // X = None, | = lo
1107 // [|1, X, X]
1108 assert_eq!(d3.pop_front(), Some(1));
1109 // [X, |X, X]
1110 assert_eq!(d3.front(), None);
1111
1112 // [X, |3, X]
Alexis Beingessnercf3b2e42014-11-06 17:24:471113 d3.push_back(3);
Kevin Butler64896d62014-08-07 01:11:131114 // [X, |3, 6]
Alexis Beingessnercf3b2e42014-11-06 17:24:471115 d3.push_back(6);
Kevin Butler64896d62014-08-07 01:11:131116 // [X, X, |6]
1117 assert_eq!(d3.pop_front(), Some(3));
1118
1119 // Pushing the lo past half way point to trigger
1120 // the 'B' scenario for growth
1121 // [9, X, |6]
Alexis Beingessnercf3b2e42014-11-06 17:24:471122 d3.push_back(9);
Kevin Butler64896d62014-08-07 01:11:131123 // [9, 12, |6]
Alexis Beingessnercf3b2e42014-11-06 17:24:471124 d3.push_back(12);
Kevin Butler64896d62014-08-07 01:11:131125
Alexis Beingessnercf3b2e42014-11-06 17:24:471126 d3.push_back(15);
Kevin Butler64896d62014-08-07 01:11:131127 // There used to be a bug here about how the
1128 // RingBuf made growth assumptions about the
1129 // underlying Vec which didn't hold and lead
1130 // to corruption.
1131 // (Vec grows to next power of two)
1132 //good- [9, 12, 15, X, X, X, X, |6]
1133 //bug- [15, 12, X, X, X, |6, X, X]
1134 assert_eq!(d3.pop_front(), Some(6));
1135
1136 // Which leads us to the following state which
1137 // would be a failure case.
1138 //bug- [15, 12, X, X, X, X, |X, X]
1139 assert_eq!(d3.front(), Some(&9));
1140 }
1141
1142 #[test]
David Manescu65f35782014-01-31 13:03:201143 fn test_reserve_exact() {
blake2-ppc70523712013-07-10 13:27:141144 let mut d = RingBuf::new();
Alexis Beingessnercf3b2e42014-11-06 17:24:471145 d.push_back(0u64);
David Manescu65f35782014-01-31 13:03:201146 d.reserve_exact(50);
Alexis Beingessnercf3b2e42014-11-06 17:24:471147 assert!(d.capacity() >= 51);
blake2-ppc70523712013-07-10 13:27:141148 let mut d = RingBuf::new();
Alexis Beingessnercf3b2e42014-11-06 17:24:471149 d.push_back(0u32);
David Manescu65f35782014-01-31 13:03:201150 d.reserve_exact(50);
Alexis Beingessnercf3b2e42014-11-06 17:24:471151 assert!(d.capacity() >= 51);
Tim Chevalier77de84b2013-05-27 18:47:381152 }
1153
1154 #[test]
David Manescu65f35782014-01-31 13:03:201155 fn test_reserve() {
blake2-ppc70523712013-07-10 13:27:141156 let mut d = RingBuf::new();
Alexis Beingessnercf3b2e42014-11-06 17:24:471157 d.push_back(0u64);
David Manescu65f35782014-01-31 13:03:201158 d.reserve(50);
Colin Sherratt7a666df2014-10-19 20:19:071159 assert!(d.capacity() >= 51);
blake2-ppc70523712013-07-10 13:27:141160 let mut d = RingBuf::new();
Alexis Beingessnercf3b2e42014-11-06 17:24:471161 d.push_back(0u32);
David Manescu65f35782014-01-31 13:03:201162 d.reserve(50);
Colin Sherratt7a666df2014-10-19 20:19:071163 assert!(d.capacity() >= 51);
Tim Chevalier77de84b2013-05-27 18:47:381164 }
1165
Jed Estep096fb792013-06-26 14:04:441166 #[test]
blake2-ppc57757a82013-09-26 07:19:261167 fn test_swap() {
Niko Matsakis9e3d0b02014-04-21 21:58:521168 let mut d: RingBuf<int> = range(0i, 5).collect();
blake2-ppc57757a82013-09-26 07:19:261169 d.pop_front();
1170 d.swap(0, 3);
Huon Wilson4b9a7a22014-04-05 05:45:421171 assert_eq!(d.iter().map(|&x|x).collect::<Vec<int>>(), vec!(4, 2, 3, 1));
blake2-ppc57757a82013-09-26 07:19:261172 }
1173
1174 #[test]
Jed Estep096fb792013-06-26 14:04:441175 fn test_iter() {
blake2-ppc70523712013-07-10 13:27:141176 let mut d = RingBuf::new();
blake2-ppcf88d5322013-07-06 03:42:451177 assert_eq!(d.iter().next(), None);
blake2-ppc9ccf4432013-07-14 20:30:221178 assert_eq!(d.iter().size_hint(), (0, Some(0)));
blake2-ppcf88d5322013-07-06 03:42:451179
Niko Matsakis9e3d0b02014-04-21 21:58:521180 for i in range(0i, 5) {
Alexis Beingessnercf3b2e42014-11-06 17:24:471181 d.push_back(i);
Jed Estep096fb792013-06-26 14:04:441182 }
Nick Cameron37a94b82014-08-04 12:19:021183 {
1184 let b: &[_] = &[&0,&1,&2,&3,&4];
1185 assert_eq!(d.iter().collect::<Vec<&int>>().as_slice(), b);
1186 }
Corey Richardsonf8ae9b02013-06-26 22:14:351187
Niko Matsakis9e3d0b02014-04-21 21:58:521188 for i in range(6i, 9) {
blake2-ppc70523712013-07-10 13:27:141189 d.push_front(i);
Jed Estep096fb792013-06-26 14:04:441190 }
Nick Cameron37a94b82014-08-04 12:19:021191 {
1192 let b: &[_] = &[&8,&7,&6,&0,&1,&2,&3,&4];
1193 assert_eq!(d.iter().collect::<Vec<&int>>().as_slice(), b);
1194 }
blake2-ppc9ccf4432013-07-14 20:30:221195
1196 let mut it = d.iter();
1197 let mut len = d.len();
1198 loop {
1199 match it.next() {
1200 None => break,
1201 _ => { len -= 1; assert_eq!(it.size_hint(), (len, Some(len))) }
1202 }
1203 }
Jed Estep096fb792013-06-26 14:04:441204 }
1205
1206 #[test]
1207 fn test_rev_iter() {
blake2-ppc70523712013-07-10 13:27:141208 let mut d = RingBuf::new();
Jonathan S03609e52014-04-21 04:59:121209 assert_eq!(d.iter().rev().next(), None);
blake2-ppcf88d5322013-07-06 03:42:451210
Niko Matsakis9e3d0b02014-04-21 21:58:521211 for i in range(0i, 5) {
Alexis Beingessnercf3b2e42014-11-06 17:24:471212 d.push_back(i);
Jed Estep096fb792013-06-26 14:04:441213 }
Nick Cameron37a94b82014-08-04 12:19:021214 {
1215 let b: &[_] = &[&4,&3,&2,&1,&0];
1216 assert_eq!(d.iter().rev().collect::<Vec<&int>>().as_slice(), b);
1217 }
Corey Richardsonf8ae9b02013-06-26 22:14:351218
Niko Matsakis9e3d0b02014-04-21 21:58:521219 for i in range(6i, 9) {
blake2-ppc70523712013-07-10 13:27:141220 d.push_front(i);
Jed Estep096fb792013-06-26 14:04:441221 }
Nick Cameron37a94b82014-08-04 12:19:021222 let b: &[_] = &[&4,&3,&2,&1,&0,&6,&7,&8];
1223 assert_eq!(d.iter().rev().collect::<Vec<&int>>().as_slice(), b);
Jed Estep096fb792013-06-26 14:04:441224 }
blake2-ppc08dc72f2013-07-06 03:42:451225
1226 #[test]
Niko Matsakisbc4164d2013-11-16 22:29:391227 fn test_mut_rev_iter_wrap() {
1228 let mut d = RingBuf::with_capacity(3);
Aaron Turonfc525ee2014-09-15 03:27:361229 assert!(d.iter_mut().rev().next().is_none());
Niko Matsakisbc4164d2013-11-16 22:29:391230
Alexis Beingessnercf3b2e42014-11-06 17:24:471231 d.push_back(1i);
1232 d.push_back(2);
1233 d.push_back(3);
Niko Matsakisbc4164d2013-11-16 22:29:391234 assert_eq!(d.pop_front(), Some(1));
Alexis Beingessnercf3b2e42014-11-06 17:24:471235 d.push_back(4);
Niko Matsakisbc4164d2013-11-16 22:29:391236
Aaron Turonfc525ee2014-09-15 03:27:361237 assert_eq!(d.iter_mut().rev().map(|x| *x).collect::<Vec<int>>(),
Huon Wilson4b9a7a22014-04-05 05:45:421238 vec!(4, 3, 2));
Niko Matsakisbc4164d2013-11-16 22:29:391239 }
1240
1241 #[test]
blake2-ppcf88d5322013-07-06 03:42:451242 fn test_mut_iter() {
blake2-ppc70523712013-07-10 13:27:141243 let mut d = RingBuf::new();
Aaron Turonfc525ee2014-09-15 03:27:361244 assert!(d.iter_mut().next().is_none());
blake2-ppcf88d5322013-07-06 03:42:451245
Daniel Micay100894552013-08-03 16:45:231246 for i in range(0u, 3) {
blake2-ppc70523712013-07-10 13:27:141247 d.push_front(i);
blake2-ppcf88d5322013-07-06 03:42:451248 }
1249
Aaron Turonfc525ee2014-09-15 03:27:361250 for (i, elt) in d.iter_mut().enumerate() {
blake2-ppcf88d5322013-07-06 03:42:451251 assert_eq!(*elt, 2 - i);
1252 *elt = i;
1253 }
1254
1255 {
Aaron Turonfc525ee2014-09-15 03:27:361256 let mut it = d.iter_mut();
blake2-ppcf88d5322013-07-06 03:42:451257 assert_eq!(*it.next().unwrap(), 0);
1258 assert_eq!(*it.next().unwrap(), 1);
1259 assert_eq!(*it.next().unwrap(), 2);
1260 assert!(it.next().is_none());
1261 }
1262 }
1263
1264 #[test]
1265 fn test_mut_rev_iter() {
blake2-ppc70523712013-07-10 13:27:141266 let mut d = RingBuf::new();
Aaron Turonfc525ee2014-09-15 03:27:361267 assert!(d.iter_mut().rev().next().is_none());
blake2-ppcf88d5322013-07-06 03:42:451268
Daniel Micay100894552013-08-03 16:45:231269 for i in range(0u, 3) {
blake2-ppc70523712013-07-10 13:27:141270 d.push_front(i);
blake2-ppcf88d5322013-07-06 03:42:451271 }
1272
Aaron Turonfc525ee2014-09-15 03:27:361273 for (i, elt) in d.iter_mut().rev().enumerate() {
blake2-ppcf88d5322013-07-06 03:42:451274 assert_eq!(*elt, i);
1275 *elt = i;
1276 }
1277
1278 {
Aaron Turonfc525ee2014-09-15 03:27:361279 let mut it = d.iter_mut().rev();
blake2-ppcf88d5322013-07-06 03:42:451280 assert_eq!(*it.next().unwrap(), 0);
1281 assert_eq!(*it.next().unwrap(), 1);
1282 assert_eq!(*it.next().unwrap(), 2);
1283 assert!(it.next().is_none());
1284 }
1285 }
1286
1287 #[test]
Brian Andersonee052192014-03-31 04:45:551288 fn test_from_iter() {
Daniel Micay6919cf52013-09-08 15:01:161289 use std::iter;
Niko Matsakis9e3d0b02014-04-21 21:58:521290 let v = vec!(1i,2,3,4,5,6,7);
Erick Tryzelaar68f40d22013-08-10 03:09:471291 let deq: RingBuf<int> = v.iter().map(|&x| x).collect();
Huon Wilson4b9a7a22014-04-05 05:45:421292 let u: Vec<int> = deq.iter().map(|&x| x).collect();
blake2-ppc08dc72f2013-07-06 03:42:451293 assert_eq!(u, v);
1294
Daniel Micay6919cf52013-09-08 15:01:161295 let mut seq = iter::count(0u, 2).take(256);
blake2-ppc70523712013-07-10 13:27:141296 let deq: RingBuf<uint> = seq.collect();
Daniel Micay100894552013-08-03 16:45:231297 for (i, &x) in deq.iter().enumerate() {
blake2-ppc08dc72f2013-07-06 03:42:451298 assert_eq!(2*i, x);
1299 }
1300 assert_eq!(deq.len(), 256);
1301 }
blake2-ppc10c76982013-07-06 13:27:321302
1303 #[test]
1304 fn test_clone() {
blake2-ppc70523712013-07-10 13:27:141305 let mut d = RingBuf::new();
Niko Matsakis9e3d0b02014-04-21 21:58:521306 d.push_front(17i);
blake2-ppc70523712013-07-10 13:27:141307 d.push_front(42);
Alexis Beingessnercf3b2e42014-11-06 17:24:471308 d.push_back(137);
1309 d.push_back(137);
blake2-ppc10c76982013-07-06 13:27:321310 assert_eq!(d.len(), 4u);
1311 let mut e = d.clone();
1312 assert_eq!(e.len(), 4u);
1313 while !d.is_empty() {
Alexis Beingessnercf3b2e42014-11-06 17:24:471314 assert_eq!(d.pop_back(), e.pop_back());
blake2-ppc10c76982013-07-06 13:27:321315 }
1316 assert_eq!(d.len(), 0u);
1317 assert_eq!(e.len(), 0u);
1318 }
1319
1320 #[test]
1321 fn test_eq() {
blake2-ppc70523712013-07-10 13:27:141322 let mut d = RingBuf::new();
Alex Crichton02882fb2014-02-28 09:23:061323 assert!(d == RingBuf::with_capacity(0));
Niko Matsakis9e3d0b02014-04-21 21:58:521324 d.push_front(137i);
blake2-ppc70523712013-07-10 13:27:141325 d.push_front(17);
1326 d.push_front(42);
Alexis Beingessnercf3b2e42014-11-06 17:24:471327 d.push_back(137);
blake2-ppc70523712013-07-10 13:27:141328 let mut e = RingBuf::with_capacity(0);
Alexis Beingessnercf3b2e42014-11-06 17:24:471329 e.push_back(42);
1330 e.push_back(17);
1331 e.push_back(137);
1332 e.push_back(137);
Alex Crichton02882fb2014-02-28 09:23:061333 assert!(&e == &d);
Alexis Beingessnercf3b2e42014-11-06 17:24:471334 e.pop_back();
1335 e.push_back(0);
blake2-ppc10c76982013-07-06 13:27:321336 assert!(e != d);
1337 e.clear();
Alex Crichton02882fb2014-02-28 09:23:061338 assert!(e == RingBuf::new());
blake2-ppc10c76982013-07-06 13:27:321339 }
Adolfo Ochagavía8e4e3ab2014-06-04 14:15:041340
1341 #[test]
nham1cfa6562014-07-27 02:33:471342 fn test_hash() {
1343 let mut x = RingBuf::new();
1344 let mut y = RingBuf::new();
1345
Alexis Beingessnercf3b2e42014-11-06 17:24:471346 x.push_back(1i);
1347 x.push_back(2);
1348 x.push_back(3);
nham1cfa6562014-07-27 02:33:471349
Alexis Beingessnercf3b2e42014-11-06 17:24:471350 y.push_back(0i);
1351 y.push_back(1i);
nham1cfa6562014-07-27 02:33:471352 y.pop_front();
Alexis Beingessnercf3b2e42014-11-06 17:24:471353 y.push_back(2);
1354 y.push_back(3);
nham1cfa6562014-07-27 02:33:471355
1356 assert!(hash::hash(&x) == hash::hash(&y));
1357 }
1358
1359 #[test]
nham63615772014-07-27 03:18:561360 fn test_ord() {
1361 let x = RingBuf::new();
1362 let mut y = RingBuf::new();
Alexis Beingessnercf3b2e42014-11-06 17:24:471363 y.push_back(1i);
1364 y.push_back(2);
1365 y.push_back(3);
nham63615772014-07-27 03:18:561366 assert!(x < y);
1367 assert!(y > x);
1368 assert!(x <= x);
1369 assert!(x >= x);
1370 }
1371
1372 #[test]
Adolfo Ochagavía8e4e3ab2014-06-04 14:15:041373 fn test_show() {
Niko Matsakis9e3d0b02014-04-21 21:58:521374 let ringbuf: RingBuf<int> = range(0i, 10).collect();
Adolfo Ochagavía8e4e3ab2014-06-04 14:15:041375 assert!(format!("{}", ringbuf).as_slice() == "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]");
1376
1377 let ringbuf: RingBuf<&str> = vec!["just", "one", "test", "more"].iter()
1378 .map(|&s| s)
1379 .collect();
1380 assert!(format!("{}", ringbuf).as_slice() == "[just, one, test, more]");
1381 }
Colin Sherratt7a666df2014-10-19 20:19:071382
1383 #[test]
1384 fn test_drop() {
1385 static mut drops: uint = 0;
1386 struct Elem;
1387 impl Drop for Elem {
1388 fn drop(&mut self) {
1389 unsafe { drops += 1; }
1390 }
1391 }
1392
1393 let mut ring = RingBuf::new();
1394 ring.push_back(Elem);
1395 ring.push_front(Elem);
1396 ring.push_back(Elem);
1397 ring.push_front(Elem);
1398 drop(ring);
1399
1400 assert_eq!(unsafe {drops}, 4);
1401 }
1402
1403 #[test]
1404 fn test_drop_with_pop() {
1405 static mut drops: uint = 0;
1406 struct Elem;
1407 impl Drop for Elem {
1408 fn drop(&mut self) {
1409 unsafe { drops += 1; }
1410 }
1411 }
1412
1413 let mut ring = RingBuf::new();
1414 ring.push_back(Elem);
1415 ring.push_front(Elem);
1416 ring.push_back(Elem);
1417 ring.push_front(Elem);
1418
1419 drop(ring.pop_back());
1420 drop(ring.pop_front());
1421 assert_eq!(unsafe {drops}, 2);
1422
1423 drop(ring);
1424 assert_eq!(unsafe {drops}, 4);
1425 }
1426
1427 #[test]
1428 fn test_drop_clear() {
1429 static mut drops: uint = 0;
1430 struct Elem;
1431 impl Drop for Elem {
1432 fn drop(&mut self) {
1433 unsafe { drops += 1; }
1434 }
1435 }
1436
1437 let mut ring = RingBuf::new();
1438 ring.push_back(Elem);
1439 ring.push_front(Elem);
1440 ring.push_back(Elem);
1441 ring.push_front(Elem);
1442 ring.clear();
1443 assert_eq!(unsafe {drops}, 4);
1444
1445 drop(ring);
1446 assert_eq!(unsafe {drops}, 4);
1447 }
1448
1449 #[test]
1450 fn test_reserve_grow() {
1451 // test growth path A
1452 // [T o o H] -> [T o o H . . . . ]
1453 let mut ring = RingBuf::with_capacity(4);
1454 for i in range(0i, 3) {
1455 ring.push_back(i);
1456 }
1457 ring.reserve(7);
1458 for i in range(0i, 3) {
1459 assert_eq!(ring.pop_front(), Some(i));
1460 }
1461
1462 // test growth path B
1463 // [H T o o] -> [. T o o H . . . ]
1464 let mut ring = RingBuf::with_capacity(4);
1465 for i in range(0i, 1) {
1466 ring.push_back(i);
1467 assert_eq!(ring.pop_front(), Some(i));
1468 }
1469 for i in range(0i, 3) {
1470 ring.push_back(i);
1471 }
1472 ring.reserve(7);
1473 for i in range(0i, 3) {
1474 assert_eq!(ring.pop_front(), Some(i));
1475 }
1476
1477 // test growth path C
1478 // [o o H T] -> [o o H . . . . T ]
1479 let mut ring = RingBuf::with_capacity(4);
1480 for i in range(0i, 3) {
1481 ring.push_back(i);
1482 assert_eq!(ring.pop_front(), Some(i));
1483 }
1484 for i in range(0i, 3) {
1485 ring.push_back(i);
1486 }
1487 ring.reserve(7);
1488 for i in range(0i, 3) {
1489 assert_eq!(ring.pop_front(), Some(i));
1490 }
1491 }
1492
1493 #[test]
1494 fn test_get() {
1495 let mut ring = RingBuf::new();
1496 ring.push_back(0i);
1497 assert_eq!(ring.get(0), Some(&0));
1498 assert_eq!(ring.get(1), None);
1499
1500 ring.push_back(1);
1501 assert_eq!(ring.get(0), Some(&0));
1502 assert_eq!(ring.get(1), Some(&1));
1503 assert_eq!(ring.get(2), None);
1504
1505 ring.push_back(2);
1506 assert_eq!(ring.get(0), Some(&0));
1507 assert_eq!(ring.get(1), Some(&1));
1508 assert_eq!(ring.get(2), Some(&2));
1509 assert_eq!(ring.get(3), None);
1510
1511 assert_eq!(ring.pop_front(), Some(0));
1512 assert_eq!(ring.get(0), Some(&1));
1513 assert_eq!(ring.get(1), Some(&2));
1514 assert_eq!(ring.get(2), None);
1515
1516 assert_eq!(ring.pop_front(), Some(1));
1517 assert_eq!(ring.get(0), Some(&2));
1518 assert_eq!(ring.get(1), None);
1519
1520 assert_eq!(ring.pop_front(), Some(2));
1521 assert_eq!(ring.get(0), None);
1522 assert_eq!(ring.get(1), None);
1523 }
1524
1525 #[test]
1526 fn test_get_mut() {
1527 let mut ring = RingBuf::new();
1528 for i in range(0i, 3) {
1529 ring.push_back(i);
1530 }
1531
1532 match ring.get_mut(1) {
1533 Some(x) => *x = -1,
1534 None => ()
1535 };
1536
1537 assert_eq!(ring.get_mut(0), Some(&mut 0));
1538 assert_eq!(ring.get_mut(1), Some(&mut -1));
1539 assert_eq!(ring.get_mut(2), Some(&mut 2));
1540 assert_eq!(ring.get_mut(3), None);
1541
1542 assert_eq!(ring.pop_front(), Some(0));
1543 assert_eq!(ring.get_mut(0), Some(&mut -1));
1544 assert_eq!(ring.get_mut(1), Some(&mut 2));
1545 assert_eq!(ring.get_mut(2), None);
1546 }
Michael Sullivanc854d6e2012-07-03 17:52:321547}