bounded_vec_deque/lib.rs
1//! A double-ended queue|ringbuffer with an upper bound on its length.
2//!
3//! The primary item of interest in this crate is the [`BoundedVecDeque`] type, which is the
4//! double-ended q.r. with an etc. that was mentioned above.
5//!
6//! This crate requires Rust 1.28.0 or later.
7//!
8//! Much of the documentation of this crate was copied (with some modifications) from [the
9//! `VecDeque` documentation][`VecDeque`] and other documentation of the Rust standard library.
10//!
11//! # Features
12//!
13//! The following crate features exist:
14//!
15//! - `fused` (enabled by default): Implements [`FusedIterator`] for the various iterator types.
16//! - `resize_with` (requires Rust 1.33): Adds [`resize_with()`].
17//!
18//! [`VecDeque`]: https://doc.rust-lang.org/std/collections/struct.VecDeque.html
19//! [`BoundedVecDeque`]: struct.BoundedVecDeque.html
20//! [`FusedIterator`]: https://doc.rust-lang.org/std/iter/trait.FusedIterator.html
21//! [`resize_with()`]: struct.BoundedVecDeque.html#method.resize_with
22
23#![forbid(unsafe_code, bare_trait_objects)]
24#![warn(missing_docs)]
25
26use ::std::collections::VecDeque;
27use ::std::hash::{Hash, Hasher};
28use ::std::ops::{Deref, Index, IndexMut, RangeBounds};
29
30mod iter;
31mod test;
32
33pub use ::iter::{Iter, IterMut, IntoIter, Drain, Append};
34
35/// A double-ended queue|ringbuffer with an upper bound on its length.
36///
37/// The “default” usage of this type as a queue is to use [`push_back()`] to add to the queue, and
38/// [`pop_front()`] to remove from the queue. [`extend()`], [`append()`], and [`from_iter()`] push
39/// onto the back in this manner, and iterating over `BoundedVecDeque` goes front to back.
40///
41/// This type is a wrapper around [`VecDeque`]. Almost all of its associated functions delegate to
42/// `VecDeque`'s (after enforcing the length bound).
43///
44/// # Capacity and reallocation
45///
46/// At the time of writing, `VecDeque` behaves as follows:
47///
48/// * It always keeps its capacity at one less than a power of two.
49/// * It always keeps an allocation (unlike e.g. `Vec`, where `new()` does not allocate and the
50/// capacity can be reduced to zero).
51/// * Its `reserve_exact()` is just an alias for `reserve()`.
52///
53/// This behavior is inherited by `BoundedVecDeque` (because it is merely a wrapper). It is not
54/// documented by `VecDeque` (and is thus subject to change), but has been noted here because it
55/// may be surprising or undesirable.
56///
57/// Users may wish to use maximum lengths that are one less than powers of two to prevent (at least
58/// with the current `VecDeque` reallocation strategy) “wasted space” caused by the capacity
59/// growing beyond the maximum length.
60///
61/// [`push_back()`]: #method.push_back
62/// [`pop_front()`]: #method.pop_front
63/// [`extend()`]: #method.extend
64/// [`append()`]: #method.append
65/// [`from_iter()`]: #method.from_iter
66/// [`VecDeque`]: https://doc.rust-lang.org/std/collections/struct.VecDeque.html
67#[derive(Debug)]
68pub struct BoundedVecDeque<T> {
69 vec_deque: VecDeque<T>,
70 max_len: usize,
71}
72
73impl<T> BoundedVecDeque<T> {
74 /// Creates a new, empty `BoundedVecDeque`.
75 ///
76 /// The capacity is set to the length limit (as a result, no reallocations will be necessary
77 /// unless the length limit is later raised).
78 ///
79 /// # Examples
80 ///
81 /// ```
82 /// use ::bounded_vec_deque::BoundedVecDeque;
83 ///
84 /// let deque: BoundedVecDeque<i32> = BoundedVecDeque::new(255);
85 ///
86 /// assert!(deque.is_empty());
87 /// assert_eq!(deque.max_len(), 255);
88 /// assert!(deque.capacity() >= 255);
89 /// ```
90 pub fn new(max_len: usize) -> Self {
91 BoundedVecDeque::with_capacity(max_len, max_len)
92 }
93
94 /// Creates a new, empty `BoundedVecDeque` with space for at least `capacity` elements.
95 ///
96 /// # Examples
97 ///
98 /// ```
99 /// use ::bounded_vec_deque::BoundedVecDeque;
100 ///
101 /// let deque: BoundedVecDeque<i32> = BoundedVecDeque::with_capacity(63, 255);
102 ///
103 /// assert!(deque.is_empty());
104 /// assert_eq!(deque.max_len(), 255);
105 /// assert!(deque.capacity() >= 63);
106 /// ```
107 pub fn with_capacity(capacity: usize, max_len: usize) -> Self {
108 BoundedVecDeque {
109 vec_deque: VecDeque::with_capacity(capacity),
110 max_len,
111 }
112 }
113
114 /// Creates a new `BoundedVecDeque` from an iterator or iterable.
115 ///
116 /// At most `max_len` items are taken from the iterator.
117 ///
118 /// # Examples
119 ///
120 /// ```
121 /// use ::bounded_vec_deque::BoundedVecDeque;
122 ///
123 /// let five_fives = ::std::iter::repeat(5).take(5);
124 ///
125 /// let deque: BoundedVecDeque<i32> = BoundedVecDeque::from_iter(five_fives, 7);
126 ///
127 /// assert!(deque.iter().eq(&[5, 5, 5, 5, 5]));
128 ///
129 /// let mut numbers = 0..;
130 ///
131 /// let deque: BoundedVecDeque<i32> = BoundedVecDeque::from_iter(numbers.by_ref(), 7);
132 ///
133 /// assert!(deque.iter().eq(&[0, 1, 2, 3, 4, 5, 6]));
134 /// assert_eq!(numbers.next(), Some(7));
135 /// ```
136 pub fn from_iter<I>(iterable: I, max_len: usize) -> Self
137 where I: IntoIterator<Item=T> {
138 BoundedVecDeque {
139 vec_deque: iterable.into_iter().take(max_len).collect(),
140 max_len,
141 }
142 }
143
144 /// Creates a new `BoundedVecDeque` from a `VecDeque`.
145 ///
146 /// If `vec_deque` contains more than `max_len` items, excess items are dropped from the back.
147 /// If the capacity is greater than `max_len`, it is [shrunk to fit].
148 ///
149 /// # Examples
150 ///
151 /// ```
152 /// use ::std::collections::VecDeque;
153 /// use ::bounded_vec_deque::BoundedVecDeque;
154 ///
155 /// let unbounded = VecDeque::from(vec![42]);
156 ///
157 /// let bounded = BoundedVecDeque::from_unbounded(unbounded, 255);
158 /// ```
159 ///
160 /// [shrunk to fit]: #method.shrink_to_fit
161 pub fn from_unbounded(mut vec_deque: VecDeque<T>, max_len: usize) -> Self {
162 vec_deque.truncate(max_len);
163 if vec_deque.capacity() > max_len {
164 vec_deque.shrink_to_fit();
165 }
166 BoundedVecDeque {
167 vec_deque,
168 max_len,
169 }
170 }
171
172 /// Converts the `BoundedVecDeque` to `VecDeque`.
173 ///
174 /// This is a minimal-cost conversion.
175 ///
176 /// # Examples
177 ///
178 /// ```
179 /// use ::bounded_vec_deque::BoundedVecDeque;
180 ///
181 /// let bounded = BoundedVecDeque::from_iter(vec![0, 1, 2, 3], 255);
182 /// let unbounded = bounded.into_unbounded();
183 /// ```
184 pub fn into_unbounded(self) -> VecDeque<T> {
185 self.vec_deque
186 }
187
188 /// Returns a mutable reference to an element in the `VecDeque` by index.
189 ///
190 /// Returns `None` if there is no such element.
191 ///
192 /// The element at index `0` is the front of the queue.
193 ///
194 /// # Examples
195 ///
196 /// ```
197 /// use ::bounded_vec_deque::BoundedVecDeque;
198 ///
199 /// let mut deque = BoundedVecDeque::new(12);
200 /// deque.push_back(3);
201 /// deque.push_back(4);
202 /// deque.push_back(5);
203 ///
204 /// if let Some(elem) = deque.get_mut(1) {
205 /// *elem = 7;
206 /// }
207 ///
208 /// assert!(deque.iter().eq(&[3, 7, 5]));
209 /// ```
210 pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
211 self.vec_deque.get_mut(index)
212 }
213
214 /// Swaps the elements at indices `i` and `j`.
215 ///
216 /// `i` and `j` may be equal.
217 ///
218 /// The element at index `0` is the front of the queue.
219 ///
220 /// # Panics
221 ///
222 /// Panics if either index is out of bounds.
223 ///
224 /// # Examples
225 ///
226 /// ```
227 /// use ::bounded_vec_deque::BoundedVecDeque;
228 ///
229 /// let mut deque = BoundedVecDeque::new(12);
230 /// deque.push_back(3);
231 /// deque.push_back(4);
232 /// deque.push_back(5);
233 /// assert!(deque.iter().eq(&[3, 4, 5]));
234 ///
235 /// deque.swap(0, 2);
236 ///
237 /// assert!(deque.iter().eq(&[5, 4, 3]));
238 /// ```
239 pub fn swap(&mut self, i: usize, j: usize) {
240 self.vec_deque.swap(i, j)
241 }
242
243 fn reserve_priv(&mut self, additional: usize, exact: bool) {
244 let new_capacity = self.capacity()
245 .checked_add(additional)
246 .expect("capacity overflow");
247 if new_capacity > self.max_len {
248 panic!(
249 "capacity out of bounds: the max len is {} but the new cap is {}",
250 self.max_len,
251 new_capacity,
252 )
253 }
254 if exact {
255 self.vec_deque.reserve_exact(additional)
256 } else {
257 self.vec_deque.reserve(additional)
258 }
259 }
260
261 /// Reserves capacity for at least `additional` more elements to be inserted.
262 ///
263 /// To avoid frequent reallocations, more space than requested may be reserved.
264 ///
265 /// # Panics
266 ///
267 /// Panics if the requested new capacity exceeds the maximum length, or if the actual new
268 /// capacity overflows `usize`.
269 ///
270 /// # Examples
271 ///
272 /// ```
273 /// use ::bounded_vec_deque::BoundedVecDeque;
274 ///
275 /// let mut deque = BoundedVecDeque::from_iter(vec![1], 255);
276 ///
277 /// deque.reserve(10);
278 ///
279 /// assert!(deque.capacity() >= 11);
280 /// ```
281 pub fn reserve(&mut self, additional: usize) {
282 self.reserve_priv(additional, false)
283 }
284
285 /// Reserves the minimum capacity for exactly `additional` more elements to be inserted.
286 ///
287 /// Does nothing if the capacity is already sufficient.
288 ///
289 /// Note that the allocator may give the collection more space than it requests. Therefore
290 /// capacity cannot be relied upon to be precisely minimal. Prefer [`reserve()`] if future
291 /// insertions are expected.
292 ///
293 /// At the time of writing, **this method is equivalent to `reserve()`** because of
294 /// `VecDeque`'s capacity management. It has been provided anyway for compatibility reasons.
295 /// See [the relevant section of the type-level documentation][capacity] for details.
296 ///
297 /// # Panics
298 ///
299 /// Panics if the requested new capacity exceeds the maximum length, or if the actual new
300 /// capacity overflows `usize`.
301 ///
302 /// # Examples
303 ///
304 /// ```
305 /// use ::bounded_vec_deque::BoundedVecDeque;
306 ///
307 /// let mut deque = BoundedVecDeque::from_iter(vec![1], 255);
308 ///
309 /// deque.reserve_exact(10);
310 ///
311 /// assert!(deque.capacity() >= 11);
312 /// ```
313 ///
314 /// [`reserve()`]: #method.reserve
315 /// [capacity]: #capacity-and-reallocation
316 pub fn reserve_exact(&mut self, additional: usize) {
317 self.reserve_priv(additional, true)
318 }
319
320 /// Reserves enough capacity for the collection to be filled to its maximum length.
321 ///
322 /// Does nothing if the capacity is already sufficient.
323 ///
324 /// See the [`reserve_exact()`] documentation for caveats about capacity management.
325 ///
326 /// # Examples
327 ///
328 /// ```
329 /// use ::bounded_vec_deque::BoundedVecDeque;
330 ///
331 /// let mut deque = BoundedVecDeque::from_iter(vec![1], 255);
332 ///
333 /// deque.reserve_maximum();
334 ///
335 /// assert!(deque.capacity() >= 255);
336 /// ```
337 ///
338 /// [`reserve_exact()`]: #method.reserve_exact
339 pub fn reserve_maximum(&mut self) {
340 let capacity = self.max_len().saturating_sub(self.len());
341 self.vec_deque.reserve_exact(capacity)
342 }
343
344 /// Reduces the capacity as much as possible.
345 ///
346 /// The capacity is reduced to as close to the length as possible. However, [there are
347 /// restrictions on how much the capacity can be reduced][capacity], and on top of that, the
348 /// allocator may not shrink the allocation as much as `VecDeque` requests.
349 ///
350 /// # Examples
351 ///
352 /// ```
353 /// use ::bounded_vec_deque::BoundedVecDeque;
354 ///
355 /// let mut deque = BoundedVecDeque::with_capacity(15, 15);
356 /// deque.push_back(0);
357 /// deque.push_back(1);
358 /// deque.push_back(2);
359 /// deque.push_back(3);
360 /// assert_eq!(deque.capacity(), 15);
361 ///
362 /// deque.shrink_to_fit();
363 ///
364 /// assert!(deque.capacity() >= 4);
365 /// ```
366 ///
367 /// [capacity]: #capacity-and-reallocation
368 pub fn shrink_to_fit(&mut self) {
369 self.vec_deque.shrink_to_fit()
370 }
371
372 /// Returns the maximum number of elements.
373 ///
374 /// # Examples
375 ///
376 /// ```
377 /// use ::bounded_vec_deque::BoundedVecDeque;
378 ///
379 /// let deque: BoundedVecDeque<i32> = BoundedVecDeque::new(255);
380 ///
381 /// assert_eq!(deque.max_len(), 255);
382 /// ```
383 pub fn max_len(&self) -> usize {
384 self.max_len
385 }
386
387 /// Changes the maximum number of elements to `max_len`.
388 ///
389 /// If there are more elements than the new maximum, they are removed from the back and yielded
390 /// by the returned iterator (in front-to-back order).
391 ///
392 /// # Examples
393 ///
394 /// ```
395 /// use ::bounded_vec_deque::BoundedVecDeque;
396 ///
397 /// let mut deque: BoundedVecDeque<i32> = BoundedVecDeque::new(7);
398 /// deque.extend(vec![0, 1, 2, 3, 4, 5, 6]);
399 /// assert_eq!(deque.max_len(), 7);
400 ///
401 /// assert!(deque.set_max_len(3).eq(vec![3, 4, 5, 6]));
402 ///
403 /// assert_eq!(deque.max_len(), 3);
404 /// assert!(deque.iter().eq(&[0, 1, 2]));
405 /// ```
406 pub fn set_max_len(&mut self, max_len: usize) -> Drain<'_, T> {
407 let len = max_len.min(self.len());
408 self.max_len = max_len;
409 self.drain(len..)
410 }
411
412 /// Decreases the length, dropping excess elements from the back.
413 ///
414 /// If `new_len` is greater than the current length, this has no effect.
415 ///
416 /// # Examples
417 ///
418 /// ```
419 /// use ::bounded_vec_deque::BoundedVecDeque;
420 ///
421 /// let mut deque = BoundedVecDeque::new(7);
422 /// deque.push_back(5);
423 /// deque.push_back(10);
424 /// deque.push_back(15);
425 /// assert!(deque.iter().eq(&[5, 10, 15]));
426 ///
427 /// deque.truncate(1);
428 ///
429 /// assert!(deque.iter().eq(&[5]));
430 /// ```
431 pub fn truncate(&mut self, new_len: usize) {
432 self.vec_deque.truncate(new_len)
433 }
434
435 /// Returns a front-to-back iterator of immutable references.
436 ///
437 /// # Examples
438 ///
439 /// ```
440 /// use ::bounded_vec_deque::BoundedVecDeque;
441 ///
442 /// let mut deque = BoundedVecDeque::new(7);
443 /// deque.push_back(5);
444 /// deque.push_back(3);
445 /// deque.push_back(4);
446 ///
447 /// let deque_of_references: Vec<&i32> = deque.iter().collect();
448 ///
449 /// assert_eq!(&deque_of_references[..], &[&5, &3, &4]);
450 /// ```
451 pub fn iter(&self) -> Iter<'_, T> {
452 Iter {
453 iter: self.vec_deque.iter(),
454 }
455 }
456
457 /// Returns a front-to-back iterator of mutable references.
458 ///
459 /// # Examples
460 ///
461 /// ```
462 /// use ::bounded_vec_deque::BoundedVecDeque;
463 ///
464 /// let mut deque = BoundedVecDeque::new(7);
465 /// deque.push_back(5);
466 /// deque.push_back(3);
467 /// deque.push_back(4);
468 ///
469 /// for number in deque.iter_mut() {
470 /// *number -= 2;
471 /// }
472 /// let deque_of_references: Vec<&mut i32> = deque.iter_mut().collect();
473 ///
474 /// assert_eq!(&deque_of_references[..], &[&mut 3, &mut 1, &mut 2]);
475 /// ```
476 pub fn iter_mut(&mut self) -> IterMut<'_, T> {
477 IterMut {
478 iter: self.vec_deque.iter_mut(),
479 }
480 }
481
482 /// Returns a reference to the underlying `VecDeque`.
483 ///
484 /// # Examples
485 ///
486 /// ```
487 /// use ::bounded_vec_deque::BoundedVecDeque;
488 ///
489 /// let bounded = BoundedVecDeque::from_iter(vec![0, 1, 2, 3], 255);
490 /// let unbounded_ref = bounded.as_unbounded();
491 /// ```
492 pub fn as_unbounded(&self) -> &VecDeque<T> {
493 self.as_ref()
494 }
495
496 /// Returns a pair of slices which contain the contents in order.
497 ///
498 /// # Examples
499 ///
500 /// ```
501 /// use ::bounded_vec_deque::BoundedVecDeque;
502 ///
503 /// let mut deque = BoundedVecDeque::new(7);
504 /// deque.push_back(0);
505 /// deque.push_back(1);
506 /// deque.push_front(10);
507 /// deque.push_front(9);
508 ///
509 /// deque.as_mut_slices().0[0] = 42;
510 /// deque.as_mut_slices().1[0] = 24;
511 ///
512 /// assert_eq!(deque.as_slices(), (&[42, 10][..], &[24, 1][..]));
513 /// ```
514 pub fn as_mut_slices(&mut self) -> (&mut [T], &mut [T]) {
515 self.vec_deque.as_mut_slices()
516 }
517
518 /// Returns `true` if the `BoundedVecDeque` is full (and false otherwise).
519 ///
520 /// # Examples
521 ///
522 /// ```
523 /// use ::bounded_vec_deque::BoundedVecDeque;
524 ///
525 /// let mut deque = BoundedVecDeque::new(3);
526 ///
527 /// deque.push_back(0);
528 /// assert!(!deque.is_full());
529 /// deque.push_back(1);
530 /// assert!(!deque.is_full());
531 /// deque.push_back(2);
532 /// assert!(deque.is_full());
533 /// ```
534 pub fn is_full(&self) -> bool {
535 self.len() >= self.max_len
536 }
537
538 /// Creates a draining iterator that removes the specified range and yields the removed items.
539 ///
540 /// Note 1: The element range is removed even if the iterator is not consumed until the end.
541 ///
542 /// Note 2: It is unspecified how many elements are removed from the deque if the `Drain`
543 /// value is not dropped but the borrow it holds expires (e.g. due to [`forget()`]).
544 ///
545 /// # Panics
546 ///
547 /// Panics if the start index is greater than the end index or if the end index is greater than
548 /// the length of the deque.
549 ///
550 /// # Examples
551 ///
552 /// ```
553 /// use ::bounded_vec_deque::BoundedVecDeque;
554 ///
555 /// let mut deque = BoundedVecDeque::from_iter(vec![0, 1, 2, 3], 7);
556 ///
557 /// assert!(deque.drain(2..).eq(vec![2, 3]));
558 ///
559 /// assert!(deque.iter().eq(&[0, 1]));
560 ///
561 /// // A full range clears all contents
562 /// deque.drain(..);
563 ///
564 /// assert!(deque.is_empty());
565 /// ```
566 ///
567 /// [`forget()`]: https://doc.rust-lang.org/std/mem/fn.forget.html
568 pub fn drain<R>(&mut self, range: R) -> Drain<'_, T>
569 where R: RangeBounds<usize> {
570 Drain {
571 iter: self.vec_deque.drain(range),
572 }
573 }
574
575 /// Removes all values.
576 ///
577 /// # Examples
578 ///
579 /// ```
580 /// use ::bounded_vec_deque::BoundedVecDeque;
581 ///
582 /// let mut deque = BoundedVecDeque::new(7);
583 /// deque.push_back(0);
584 /// assert!(!deque.is_empty());
585 ///
586 /// deque.clear();
587 ///
588 /// assert!(deque.is_empty());
589 /// ```
590 pub fn clear(&mut self) {
591 self.vec_deque.clear()
592 }
593
594 /// Returns a mutable reference to the front element.
595 ///
596 /// Returns `None` if the deque is empty.
597 ///
598 /// # Examples
599 ///
600 /// ```
601 /// use ::bounded_vec_deque::BoundedVecDeque;
602 ///
603 /// let mut deque = BoundedVecDeque::new(7);
604 ///
605 /// assert_eq!(deque.front_mut(), None);
606 ///
607 /// deque.push_back(0);
608 /// deque.push_back(1);
609 ///
610 /// if let Some(x) = deque.front_mut() {
611 /// *x = 9;
612 /// }
613 ///
614 /// assert_eq!(deque.front(), Some(&9));
615 /// ```
616 pub fn front_mut(&mut self) -> Option<&mut T> {
617 self.vec_deque.front_mut()
618 }
619
620 /// Returns a mutable reference to the back element.
621 ///
622 /// Returns `None` if the deque is empty.
623 ///
624 /// # Examples
625 ///
626 /// ```
627 /// use ::bounded_vec_deque::BoundedVecDeque;
628 ///
629 /// let mut deque = BoundedVecDeque::new(7);
630 ///
631 /// assert_eq!(deque.back_mut(), None);
632 ///
633 /// deque.push_back(0);
634 /// deque.push_back(1);
635 ///
636 /// if let Some(x) = deque.back_mut() {
637 /// *x = 9;
638 /// }
639 ///
640 /// assert_eq!(deque.back(), Some(&9));
641 /// ```
642 pub fn back_mut(&mut self) -> Option<&mut T> {
643 self.vec_deque.back_mut()
644 }
645
646 /// Pushes an element onto the front of the deque.
647 ///
648 /// If the deque is full, an element is removed from the back and returned.
649 ///
650 /// # Examples
651 ///
652 /// ```
653 /// use ::bounded_vec_deque::BoundedVecDeque;
654 ///
655 /// let mut deque = BoundedVecDeque::new(2);
656 ///
657 /// assert_eq!(deque.push_front(0), None);
658 /// assert_eq!(deque.push_front(1), None);
659 /// assert_eq!(deque.push_front(2), Some(0));
660 /// assert_eq!(deque.push_front(3), Some(1));
661 /// assert_eq!(deque.front(), Some(&3));
662 /// ```
663 pub fn push_front(&mut self, value: T) -> Option<T> {
664 if self.max_len == 0 {
665 return Some(value)
666 }
667 let displaced_value = if self.is_full() { self.pop_back() } else { None };
668 self.vec_deque.push_front(value);
669 displaced_value
670 }
671
672 /// Removes and returns the first element.
673 ///
674 /// Returns `None` if the deque is empty.
675 ///
676 /// # Examples
677 ///
678 /// ```
679 /// use ::bounded_vec_deque::BoundedVecDeque;
680 ///
681 /// let mut deque = BoundedVecDeque::new(7);
682 /// deque.push_back(0);
683 /// deque.push_back(1);
684 ///
685 /// assert_eq!(deque.pop_front(), Some(0));
686 /// assert_eq!(deque.pop_front(), Some(1));
687 /// assert_eq!(deque.pop_front(), None);
688 /// ```
689 pub fn pop_front(&mut self) -> Option<T> {
690 self.vec_deque.pop_front()
691 }
692
693 /// Pushes an element onto the back of the deque.
694 ///
695 /// If the deque is full, an element is removed from the front and returned.
696 ///
697 /// # Examples
698 ///
699 /// ```
700 /// use ::bounded_vec_deque::BoundedVecDeque;
701 ///
702 /// let mut deque = BoundedVecDeque::new(2);
703 ///
704 /// assert_eq!(deque.push_back(0), None);
705 /// assert_eq!(deque.push_back(1), None);
706 /// assert_eq!(deque.push_back(2), Some(0));
707 /// assert_eq!(deque.push_back(3), Some(1));
708 /// assert_eq!(deque.back(), Some(&3));
709 /// ```
710 pub fn push_back(&mut self, value: T) -> Option<T> {
711 if self.max_len == 0 {
712 return Some(value)
713 }
714 let displaced_value = if self.is_full() { self.pop_front() } else { None };
715 self.vec_deque.push_back(value);
716 displaced_value
717 }
718
719 /// Removes and returns the last element.
720 ///
721 /// Returns `None` if the deque is empty.
722 ///
723 /// # Examples
724 ///
725 /// ```
726 /// use ::bounded_vec_deque::BoundedVecDeque;
727 ///
728 /// let mut deque = BoundedVecDeque::new(7);
729 /// deque.push_back(0);
730 /// deque.push_back(1);
731 ///
732 /// assert_eq!(deque.pop_back(), Some(1));
733 /// assert_eq!(deque.pop_back(), Some(0));
734 /// assert_eq!(deque.pop_back(), None);
735 /// ```
736 pub fn pop_back(&mut self) -> Option<T> {
737 self.vec_deque.pop_back()
738 }
739
740 /// Removes and returns the element at `index`, filling the gap with the element at the front.
741 ///
742 /// This does not preserve ordering, but is `O(1)`.
743 ///
744 /// Returns `None` if `index` is out of bounds.
745 ///
746 /// The element at index `0` is the front of the queue.
747 ///
748 /// # Examples
749 ///
750 /// ```
751 /// use ::bounded_vec_deque::BoundedVecDeque;
752 ///
753 /// let mut deque = BoundedVecDeque::new(7);
754 ///
755 /// assert_eq!(deque.swap_remove_front(0), None);
756 ///
757 /// deque.extend(vec![0, 1, 2, 3, 4, 5, 6]);
758 ///
759 /// assert_eq!(deque.swap_remove_front(3), Some(3));
760 /// assert!(deque.iter().eq(&[1, 2, 0, 4, 5, 6]));
761 /// ```
762 pub fn swap_remove_front(&mut self, index: usize) -> Option<T> {
763 self.vec_deque.swap_remove_front(index)
764 }
765
766 /// Removes and returns the element at `index`, filling the gap with the element at the back.
767 ///
768 /// This does not preserve ordering, but is `O(1)`.
769 ///
770 /// Returns `None` if `index` is out of bounds.
771 ///
772 /// The element at index `0` is the front of the queue.
773 ///
774 /// # Examples
775 ///
776 /// ```
777 /// use ::bounded_vec_deque::BoundedVecDeque;
778 ///
779 /// let mut deque = BoundedVecDeque::new(7);
780 ///
781 /// assert_eq!(deque.swap_remove_back(0), None);
782 ///
783 /// deque.extend(vec![0, 1, 2, 3, 4, 5, 6]);
784 ///
785 /// assert_eq!(deque.swap_remove_back(3), Some(3));
786 /// assert!(deque.iter().eq(&[0, 1, 2, 6, 4, 5]));
787 /// ```
788 pub fn swap_remove_back(&mut self, index: usize) -> Option<T> {
789 self.vec_deque.swap_remove_back(index)
790 }
791
792 /// Inserts an element at `index` in the deque, displacing the back if necessary.
793 ///
794 /// Elements with indices greater than or equal to `index` are shifted one place towards the
795 /// back to make room. If the deque is full, an element is removed from the back and returned.
796 ///
797 /// The element at index `0` is the front of the queue.
798 ///
799 /// # Panics
800 ///
801 /// Panics if `index` is greater than the length.
802 ///
803 /// # Examples
804 ///
805 /// ```
806 /// use ::bounded_vec_deque::BoundedVecDeque;
807 ///
808 /// let mut deque = BoundedVecDeque::new(5);
809 /// deque.extend(vec!['a', 'b', 'c', 'd']);
810 ///
811 /// assert_eq!(deque.insert_spill_back(1, 'e'), None);
812 /// assert!(deque.iter().eq(&['a', 'e', 'b', 'c', 'd']));
813 /// assert_eq!(deque.insert_spill_back(1, 'f'), Some('d'));
814 /// assert!(deque.iter().eq(&['a', 'f', 'e', 'b', 'c']));
815 /// ```
816 pub fn insert_spill_back(&mut self, index: usize, value: T) -> Option<T> {
817 if self.max_len == 0 {
818 return Some(value)
819 }
820 let displaced_value = if self.is_full() {
821 self.pop_back()
822 } else {
823 None
824 };
825 self.vec_deque.insert(index, value);
826 displaced_value
827 }
828
829 /// Inserts an element at `index` in the deque, displacing the front if necessary.
830 ///
831 /// If the deque is full, an element is removed from the front and returned, and elements with
832 /// indices less than or equal to `index` are shifted one place towards the front to make room.
833 /// Otherwise, elements with indices greater than or equal to `index` are shifted one place
834 /// towards the back to make room.
835 ///
836 /// The element at index `0` is the front of the queue.
837 ///
838 /// # Panics
839 ///
840 /// Panics if `index` is greater than the length.
841 ///
842 /// # Examples
843 ///
844 /// ```
845 /// use ::bounded_vec_deque::BoundedVecDeque;
846 ///
847 /// let mut deque = BoundedVecDeque::new(5);
848 /// deque.extend(vec!['a', 'b', 'c', 'd']);
849 ///
850 /// assert_eq!(deque.insert_spill_front(3, 'e'), None);
851 /// assert!(deque.iter().eq(&['a', 'b', 'c', 'e', 'd']));
852 /// assert_eq!(deque.insert_spill_front(3, 'f'), Some('a'));
853 /// assert!(deque.iter().eq(&['b', 'c', 'e', 'f', 'd']));
854 /// ```
855 pub fn insert_spill_front(&mut self, index: usize, value: T) -> Option<T> {
856 if self.max_len == 0 {
857 return Some(value)
858 }
859 let displaced_value = if self.is_full() {
860 self.pop_front()
861 } else {
862 None
863 };
864 self.vec_deque.insert(index, value);
865 displaced_value
866 }
867
868 /// Removes and returns the element at `index`.
869 ///
870 /// Elements with indices greater than `index` are shifted towards the front to fill the gap.
871 ///
872 /// Returns `None` if `index` is out of bounds.
873 ///
874 /// The element at index `0` is the front of the queue.
875 ///
876 /// # Examples
877 ///
878 /// ```
879 /// use ::bounded_vec_deque::BoundedVecDeque;
880 ///
881 /// let mut deque = BoundedVecDeque::new(7);
882 ///
883 /// assert_eq!(deque.remove(0), None);
884 ///
885 /// deque.extend(vec![0, 1, 2, 3, 4, 5, 6]);
886 ///
887 /// assert_eq!(deque.remove(3), Some(3));
888 /// assert!(deque.iter().eq(&[0, 1, 2, 4, 5, 6]));
889 /// ```
890 pub fn remove(&mut self, index: usize) -> Option<T> {
891 self.vec_deque.remove(index)
892 }
893
894 /// Splits the deque in two at the given index.
895 ///
896 /// Returns a new `BoundedVecDeque` containing elements `[at, len)`, leaving `self` with
897 /// elements `[0, at)`. The capacity and maximum length of `self` are unchanged, and the new
898 /// deque has the same maximum length as `self`.
899 ///
900 /// The element at index `0` is the front of the queue.
901 ///
902 /// # Panics
903 ///
904 /// Panics if `at > len`.
905 ///
906 /// # Examples
907 ///
908 /// ```
909 /// use ::bounded_vec_deque::BoundedVecDeque;
910 ///
911 /// let mut deque = BoundedVecDeque::from_iter(vec![0, 1, 2, 3], 7);
912 ///
913 /// let other_deque = deque.split_off(2);
914 ///
915 /// assert!(other_deque.iter().eq(&[2, 3]));
916 /// assert!(deque.iter().eq(&[0, 1]));
917 /// ```
918 pub fn split_off(&mut self, at: usize) -> Self {
919 BoundedVecDeque {
920 vec_deque: self.vec_deque.split_off(at),
921 max_len: self.max_len,
922 }
923 }
924
925 /// Moves all the elements of `other` into `self`, leaving `other` empty.
926 ///
927 /// Elements from `other` are pushed onto the back of `self`. If the maximum length is
928 /// exceeded, excess elements from the front of `self` are yielded by the returned iterator.
929 ///
930 /// # Panics
931 ///
932 /// Panics if the new number of elements in self overflows a `usize`.
933 ///
934 /// # Examples
935 ///
936 /// ```
937 /// use ::bounded_vec_deque::BoundedVecDeque;
938 ///
939 /// let mut deque = BoundedVecDeque::from_iter(vec![0, 1, 2, 3], 7);
940 /// let mut other_deque = BoundedVecDeque::from_iter(vec![4, 5, 6, 7, 8], 7);
941 ///
942 /// assert!(deque.append(&mut other_deque).eq(vec![0, 1]));
943 ///
944 /// assert!(deque.iter().eq(&[2, 3, 4, 5, 6, 7, 8]));
945 /// assert!(other_deque.is_empty());
946 /// ```
947 pub fn append<'a>(&'a mut self, other: &'a mut Self) -> Append<'a, T> {
948 Append {
949 source: other,
950 destination: self,
951 }
952 }
953
954 /// Retains only the elements specified by the predicate.
955 ///
956 /// `predicate` is called for each element; each element for which it returns `false` is
957 /// removed. This method operates in place and preserves the order of the retained elements.
958 ///
959 /// # Examples
960 ///
961 /// ```
962 /// use ::bounded_vec_deque::BoundedVecDeque;
963 ///
964 /// let mut deque = BoundedVecDeque::from_iter(1..5, 7);
965 ///
966 /// deque.retain(|&x| x % 2 == 0);
967 ///
968 /// assert!(deque.iter().eq(&[2, 4]));
969 /// ```
970 pub fn retain<F>(&mut self, predicate: F)
971 where F: FnMut(&T) -> bool {
972 self.vec_deque.retain(predicate)
973 }
974
975 /// Modifies the deque in-place so that its length is equal to `new_len`.
976 ///
977 /// This is done either by removing excess elements from the back or by pushing clones of
978 /// `value` to the back.
979 ///
980 /// # Examples
981 ///
982 /// ```
983 /// use ::bounded_vec_deque::BoundedVecDeque;
984 ///
985 /// let mut deque = BoundedVecDeque::from_iter(vec![5, 10, 15], 7);
986 ///
987 /// deque.resize(2, 0);
988 ///
989 /// assert!(deque.iter().eq(&[5, 10]));
990 ///
991 /// deque.resize(5, 20);
992 ///
993 /// assert!(deque.iter().eq(&[5, 10, 20, 20, 20]));
994 /// ```
995 pub fn resize(&mut self, new_len: usize, value: T)
996 where T: Clone {
997 if new_len > self.max_len {
998 panic!(
999 "length out of bounds: the new len is {} but the max len is {}",
1000 new_len,
1001 self.max_len,
1002 )
1003 }
1004 self.vec_deque.resize(new_len, value)
1005 }
1006
1007 /// Modifies the deque in-place so that its length is equal to `new_len`.
1008 ///
1009 /// This is done either by removing excess elements from the back or by pushing elements
1010 /// produced by calling `producer` to the back.
1011 ///
1012 /// # Availability
1013 ///
1014 /// This method requires [the `resize_with` feature], which requires Rust 1.33.
1015 ///
1016 /// [the `resize_with` feature]: index.html#features
1017 ///
1018 /// # Examples
1019 ///
1020 /// ```
1021 /// use ::bounded_vec_deque::BoundedVecDeque;
1022 ///
1023 /// let mut deque = BoundedVecDeque::from_iter(vec![5, 10, 15], 7);
1024 ///
1025 /// deque.resize_with(5, Default::default);
1026 /// assert!(deque.iter().eq(&[5, 10, 15, 0, 0]));
1027 ///
1028 /// deque.resize_with(2, || unreachable!());
1029 /// assert!(deque.iter().eq(&[5, 10]));
1030 ///
1031 /// let mut state = 100;
1032 /// deque.resize_with(5, || { state += 1; state });
1033 /// assert!(deque.iter().eq(&[5, 10, 101, 102, 103]));
1034 /// ```
1035 #[cfg(feature = "resize_with")]
1036 pub fn resize_with<F>(&mut self, new_len: usize, producer: F)
1037 where F: FnMut() -> T {
1038 if new_len > self.max_len {
1039 panic!(
1040 "length out of bounds: the new len is {} but the max len is {}",
1041 new_len,
1042 self.max_len,
1043 )
1044 }
1045 self.vec_deque.resize_with(new_len, producer)
1046 }
1047}
1048
1049impl<T: Clone> Clone for BoundedVecDeque<T> {
1050 fn clone(&self) -> Self {
1051 BoundedVecDeque {
1052 vec_deque: self.vec_deque.clone(),
1053 max_len: self.max_len,
1054 }
1055 }
1056
1057 /// Mutates `self` into a clone of `other` (like `*self = other.clone()`).
1058 ///
1059 /// `self` is cleared, and the elements of `other` are cloned and added. The maximum length is
1060 /// set to the same as `other`'s.
1061 ///
1062 /// This method reuses `self`'s allocation, but due to API limitations, the allocation cannot
1063 /// be shrunk to fit the maximum length. Because of this, if `self`'s capacity is more than the
1064 /// new maximum length, it is shrunk to fit _`other`'s_ length.
1065 fn clone_from(&mut self, other: &Self) {
1066 self.clear();
1067 self.max_len = other.max_len;
1068 let should_shrink = self.capacity() > self.max_len;
1069 if should_shrink {
1070 self.reserve_exact(other.len());
1071 } else {
1072 self.reserve(other.len());
1073 }
1074 self.extend(other.iter().cloned());
1075 if should_shrink {
1076 // Ideally, we would shrink to self.max_len, and do so _before_ pushing all the cloned
1077 // values, but shrink_to() isn't stable yet.
1078 self.shrink_to_fit();
1079 }
1080 }
1081}
1082
1083impl<T: Hash> Hash for BoundedVecDeque<T> {
1084 /// Feeds `self` into `hasher`.
1085 ///
1086 /// Only the values contained in `self` are hashed; the length bound is ignored.
1087 fn hash<H>(&self, hasher: &mut H)
1088 where H: Hasher {
1089 self.vec_deque.hash(hasher)
1090 }
1091}
1092
1093impl<T> Deref for BoundedVecDeque<T> {
1094 type Target = VecDeque<T>;
1095
1096 fn deref(&self) -> &Self::Target {
1097 self.as_ref()
1098 }
1099}
1100
1101impl<T> AsRef<VecDeque<T>> for BoundedVecDeque<T> {
1102 fn as_ref(&self) -> &VecDeque<T> {
1103 &self.vec_deque
1104 }
1105}
1106
1107impl<T> Index<usize> for BoundedVecDeque<T> {
1108 type Output = T;
1109
1110 /// Returns a reference to an element in the `VecDeque` by index.
1111 ///
1112 /// The element at index `0` is the front of the queue.
1113 ///
1114 /// # Panics
1115 ///
1116 /// Panics if there is no such element (i.e. `index >= len`).
1117 ///
1118 /// # Examples
1119 ///
1120 /// ```
1121 /// use ::bounded_vec_deque::BoundedVecDeque;
1122 ///
1123 /// let mut deque = BoundedVecDeque::new(7);
1124 /// deque.push_back(3);
1125 /// deque.push_back(4);
1126 /// deque.push_back(5);
1127 ///
1128 /// let value = &deque[1];
1129 ///
1130 /// assert_eq!(value, &4);
1131 /// ```
1132 fn index(&self, index: usize) -> &T {
1133 &self.vec_deque[index]
1134 }
1135}
1136
1137impl<T> IndexMut<usize> for BoundedVecDeque<T> {
1138 /// Returns a mutable reference to an element in the `VecDeque` by index.
1139 ///
1140 /// The element at index `0` is the front of the queue.
1141 ///
1142 /// # Panics
1143 ///
1144 /// Panics if there is no such element (i.e. `index >= len`).
1145 ///
1146 /// # Examples
1147 ///
1148 /// ```
1149 /// use ::bounded_vec_deque::BoundedVecDeque;
1150 ///
1151 /// let mut deque = BoundedVecDeque::new(12);
1152 /// deque.push_back(3);
1153 /// deque.push_back(4);
1154 /// deque.push_back(5);
1155 ///
1156 /// deque[1] = 7;
1157 ///
1158 /// assert_eq!(deque[1], 7);
1159 /// ```
1160 fn index_mut(&mut self, index: usize) -> &mut T {
1161 &mut self.vec_deque[index]
1162 }
1163}
1164
1165impl<T> IntoIterator for BoundedVecDeque<T> {
1166 type Item = T;
1167 type IntoIter = IntoIter<T>;
1168
1169 fn into_iter(self) -> Self::IntoIter {
1170 IntoIter {
1171 iter: self.vec_deque.into_iter(),
1172 }
1173 }
1174}
1175
1176impl<'a, T> IntoIterator for &'a BoundedVecDeque<T> {
1177 type Item = &'a T;
1178 type IntoIter = Iter<'a, T>;
1179
1180 fn into_iter(self) -> Self::IntoIter {
1181 self.iter()
1182 }
1183}
1184
1185impl<'a, T> IntoIterator for &'a mut BoundedVecDeque<T> {
1186 type Item = &'a mut T;
1187 type IntoIter = IterMut<'a, T>;
1188
1189 fn into_iter(self) -> Self::IntoIter {
1190 self.iter_mut()
1191 }
1192}
1193
1194impl<T> Extend<T> for BoundedVecDeque<T> {
1195 fn extend<I>(&mut self, iter: I)
1196 where I: IntoIterator<Item=T> {
1197 for value in iter {
1198 self.push_back(value);
1199 }
1200 }
1201}