rune_alloc/vec_deque/mod.rs
1//! A double-ended queue (deque) implemented with a growable ring buffer.
2//!
3//! This queue has *O*(1) amortized inserts and removals from both ends of the
4//! container. It also has *O*(1) indexing like a vector. The contained elements
5//! are not required to be copyable, and the queue will be sendable if the
6//! contained type is sendable.
7
8#![allow(clippy::redundant_closure)]
9
10use core::cmp::{self, Ordering};
11use core::fmt;
12use core::hash::{Hash, Hasher};
13use core::mem::ManuallyDrop;
14use core::ops::{Index, IndexMut, Range, RangeBounds};
15use core::ptr;
16use core::slice;
17
18// This is used in a bunch of intra-doc links.
19// FIXME: For some reason, `#[cfg(doc)]` wasn't sufficient, resulting in
20// failures in linkchecker even though rustdoc built the docs just fine.
21#[allow(unused_imports)]
22use core::mem;
23
24use crate::alloc::{Allocator, Global, SizedTypeProperties};
25use crate::clone::TryClone;
26use crate::error::Error;
27use crate::iter::{TryExtend, TryFromIteratorIn};
28use crate::raw_vec::RawVec;
29use crate::slice::range as slice_range;
30use crate::vec::Vec;
31
32#[macro_use]
33mod macros;
34
35pub use self::drain::Drain;
36
37mod drain;
38
39pub use self::iter_mut::IterMut;
40
41mod iter_mut;
42
43pub use self::into_iter::IntoIter;
44
45mod into_iter;
46
47pub use self::iter::Iter;
48
49mod iter;
50
51pub use self::raw_iter::RawIter;
52
53mod raw_iter;
54
55/// A double-ended queue implemented with a growable ring buffer.
56///
57/// The "default" usage of this type as a queue is to use [`try_push_back`] to add to
58/// the queue, and [`pop_front`] to remove from the queue. [`try_extend`] and [`try_append`]
59/// push onto the back in this manner, and iterating over `VecDeque` goes front
60/// to back.
61///
62/// A `VecDeque` with a known list of items can be initialized from an array:
63///
64/// ```
65/// use rune::alloc::VecDeque;
66///
67/// let deq = VecDeque::try_from([-1, 0, 1])?;
68/// # Ok::<_, rune::alloc::Error>(())
69/// ```
70///
71/// Since `VecDeque` is a ring buffer, its elements are not necessarily contiguous
72/// in memory. If you want to access the elements as a single slice, such as for
73/// efficient sorting, you can use [`make_contiguous`]. It rotates the `VecDeque`
74/// so that its elements do not wrap, and returns a mutable slice to the
75/// now-contiguous element sequence.
76///
77/// [`try_push_back`]: VecDeque::try_push_back
78/// [`pop_front`]: VecDeque::pop_front
79/// [`try_extend`]: VecDeque::try_extend
80/// [`try_append`]: VecDeque::try_append
81/// [`make_contiguous`]: VecDeque::make_contiguous
82pub struct VecDeque<T, A: Allocator = Global> {
83 // `self[0]`, if it exists, is `buf[head]`.
84 // `head < buf.capacity()`, unless `buf.capacity() == 0` when `head == 0`.
85 head: usize,
86 // the number of initialized elements, starting from the one at `head` and potentially wrapping around.
87 // if `len == 0`, the exact value of `head` is unimportant.
88 // if `T` is zero-Sized, then `self.len <= usize::MAX`, otherwise `self.len <= isize::MAX as usize`.
89 len: usize,
90 buf: RawVec<T, A>,
91}
92
93impl<T: TryClone, A: Allocator + Clone> TryClone for VecDeque<T, A> {
94 fn try_clone(&self) -> Result<Self, Error> {
95 let mut deq = Self::try_with_capacity_in(self.len(), self.allocator().clone())?;
96
97 for value in self.iter() {
98 deq.try_push_back(value.try_clone()?)?;
99 }
100
101 Ok(deq)
102 }
103
104 fn try_clone_from(&mut self, other: &Self) -> Result<(), Error> {
105 self.clear();
106
107 for value in other.iter() {
108 self.try_push_back(value.try_clone()?)?;
109 }
110
111 Ok(())
112 }
113}
114
115#[cfg(rune_nightly)]
116unsafe impl<#[may_dangle] T, A> Drop for VecDeque<T, A>
117where
118 A: Allocator,
119{
120 fn drop(&mut self) {
121 /// Runs the destructor for all items in the slice when it gets dropped (normally or
122 /// during unwinding).
123 struct Dropper<'a, T>(&'a mut [T]);
124
125 impl<'a, T> Drop for Dropper<'a, T> {
126 fn drop(&mut self) {
127 unsafe {
128 ptr::drop_in_place(self.0);
129 }
130 }
131 }
132
133 let (front, back) = self.as_mut_slices();
134 unsafe {
135 let _back_dropper = Dropper(back);
136 // use drop for [T]
137 ptr::drop_in_place(front);
138 }
139 // RawVec handles deallocation
140 }
141}
142
143#[cfg(not(rune_nightly))]
144impl<T, A> Drop for VecDeque<T, A>
145where
146 A: Allocator,
147{
148 fn drop(&mut self) {
149 /// Runs the destructor for all items in the slice when it gets dropped (normally or
150 /// during unwinding).
151 struct Dropper<'a, T>(&'a mut [T]);
152
153 impl<T> Drop for Dropper<'_, T> {
154 fn drop(&mut self) {
155 unsafe {
156 ptr::drop_in_place(self.0);
157 }
158 }
159 }
160
161 let (front, back) = self.as_mut_slices();
162 unsafe {
163 let _back_dropper = Dropper(back);
164 // use drop for [T]
165 ptr::drop_in_place(front);
166 }
167 // RawVec handles deallocation
168 }
169}
170
171impl<T> Default for VecDeque<T> {
172 /// Creates an empty deque.
173 #[inline]
174 fn default() -> VecDeque<T> {
175 VecDeque::new()
176 }
177}
178
179impl<T, A> VecDeque<T, A>
180where
181 A: Allocator,
182{
183 /// Marginally more convenient
184 #[inline]
185 fn ptr(&self) -> *mut T {
186 self.buf.ptr()
187 }
188
189 /// Moves an element out of the buffer
190 #[inline]
191 unsafe fn buffer_read(&mut self, off: usize) -> T {
192 unsafe { ptr::read(self.ptr().add(off)) }
193 }
194
195 /// Writes an element into the buffer, moving it.
196 #[inline]
197 unsafe fn buffer_write(&mut self, off: usize, value: T) {
198 unsafe {
199 ptr::write(self.ptr().add(off), value);
200 }
201 }
202
203 /// Returns a slice pointer into the buffer.
204 /// `range` must lie inside `0..self.capacity()`.
205 #[inline]
206 unsafe fn buffer_range(&self, range: Range<usize>) -> *mut [T] {
207 unsafe {
208 ptr::slice_from_raw_parts_mut(self.ptr().add(range.start), range.end - range.start)
209 }
210 }
211
212 /// Returns `true` if the buffer is at full capacity.
213 #[inline]
214 fn is_full(&self) -> bool {
215 self.len == self.capacity()
216 }
217
218 /// Returns the index in the underlying buffer for a given logical element
219 /// index + addend.
220 #[inline]
221 fn wrap_add(&self, idx: usize, addend: usize) -> usize {
222 wrap_index(idx.wrapping_add(addend), self.capacity())
223 }
224
225 #[inline]
226 fn to_physical_idx(&self, idx: usize) -> usize {
227 self.wrap_add(self.head, idx)
228 }
229
230 /// Returns the index in the underlying buffer for a given logical element
231 /// index - subtrahend.
232 #[inline]
233 fn wrap_sub(&self, idx: usize, subtrahend: usize) -> usize {
234 wrap_index(
235 idx.wrapping_sub(subtrahend).wrapping_add(self.capacity()),
236 self.capacity(),
237 )
238 }
239
240 /// Copies a contiguous block of memory len long from src to dst
241 #[inline]
242 unsafe fn copy(&mut self, src: usize, dst: usize, len: usize) {
243 debug_assert!(
244 dst + len <= self.capacity(),
245 "cpy dst={} src={} len={} cap={}",
246 dst,
247 src,
248 len,
249 self.capacity()
250 );
251 debug_assert!(
252 src + len <= self.capacity(),
253 "cpy dst={} src={} len={} cap={}",
254 dst,
255 src,
256 len,
257 self.capacity()
258 );
259 unsafe {
260 ptr::copy(self.ptr().add(src), self.ptr().add(dst), len);
261 }
262 }
263
264 /// Copies a contiguous block of memory len long from src to dst
265 #[inline]
266 unsafe fn copy_nonoverlapping(&mut self, src: usize, dst: usize, len: usize) {
267 debug_assert!(
268 dst + len <= self.capacity(),
269 "cno dst={} src={} len={} cap={}",
270 dst,
271 src,
272 len,
273 self.capacity()
274 );
275 debug_assert!(
276 src + len <= self.capacity(),
277 "cno dst={} src={} len={} cap={}",
278 dst,
279 src,
280 len,
281 self.capacity()
282 );
283 unsafe {
284 ptr::copy_nonoverlapping(self.ptr().add(src), self.ptr().add(dst), len);
285 }
286 }
287
288 /// Copies a potentially wrapping block of memory len long from src to dest.
289 /// (abs(dst - src) + len) must be no larger than capacity() (There must be at
290 /// most one continuous overlapping region between src and dest).
291 unsafe fn wrap_copy(&mut self, src: usize, dst: usize, len: usize) {
292 debug_assert!(
293 cmp::min(src.abs_diff(dst), self.capacity() - src.abs_diff(dst)) + len
294 <= self.capacity(),
295 "wrc dst={} src={} len={} cap={}",
296 dst,
297 src,
298 len,
299 self.capacity()
300 );
301
302 // If T is a ZST, don't do any copying.
303 if T::IS_ZST || src == dst || len == 0 {
304 return;
305 }
306
307 let dst_after_src = self.wrap_sub(dst, src) < len;
308
309 let src_pre_wrap_len = self.capacity() - src;
310 let dst_pre_wrap_len = self.capacity() - dst;
311 let src_wraps = src_pre_wrap_len < len;
312 let dst_wraps = dst_pre_wrap_len < len;
313
314 match (dst_after_src, src_wraps, dst_wraps) {
315 (_, false, false) => {
316 // src doesn't wrap, dst doesn't wrap
317 //
318 // S . . .
319 // 1 [_ _ A A B B C C _]
320 // 2 [_ _ A A A A B B _]
321 // D . . .
322 //
323 unsafe {
324 self.copy(src, dst, len);
325 }
326 }
327 (false, false, true) => {
328 // dst before src, src doesn't wrap, dst wraps
329 //
330 // S . . .
331 // 1 [A A B B _ _ _ C C]
332 // 2 [A A B B _ _ _ A A]
333 // 3 [B B B B _ _ _ A A]
334 // . . D .
335 //
336 unsafe {
337 self.copy(src, dst, dst_pre_wrap_len);
338 self.copy(src + dst_pre_wrap_len, 0, len - dst_pre_wrap_len);
339 }
340 }
341 (true, false, true) => {
342 // src before dst, src doesn't wrap, dst wraps
343 //
344 // S . . .
345 // 1 [C C _ _ _ A A B B]
346 // 2 [B B _ _ _ A A B B]
347 // 3 [B B _ _ _ A A A A]
348 // . . D .
349 //
350 unsafe {
351 self.copy(src + dst_pre_wrap_len, 0, len - dst_pre_wrap_len);
352 self.copy(src, dst, dst_pre_wrap_len);
353 }
354 }
355 (false, true, false) => {
356 // dst before src, src wraps, dst doesn't wrap
357 //
358 // . . S .
359 // 1 [C C _ _ _ A A B B]
360 // 2 [C C _ _ _ B B B B]
361 // 3 [C C _ _ _ B B C C]
362 // D . . .
363 //
364 unsafe {
365 self.copy(src, dst, src_pre_wrap_len);
366 self.copy(0, dst + src_pre_wrap_len, len - src_pre_wrap_len);
367 }
368 }
369 (true, true, false) => {
370 // src before dst, src wraps, dst doesn't wrap
371 //
372 // . . S .
373 // 1 [A A B B _ _ _ C C]
374 // 2 [A A A A _ _ _ C C]
375 // 3 [C C A A _ _ _ C C]
376 // D . . .
377 //
378 unsafe {
379 self.copy(0, dst + src_pre_wrap_len, len - src_pre_wrap_len);
380 self.copy(src, dst, src_pre_wrap_len);
381 }
382 }
383 (false, true, true) => {
384 // dst before src, src wraps, dst wraps
385 //
386 // . . . S .
387 // 1 [A B C D _ E F G H]
388 // 2 [A B C D _ E G H H]
389 // 3 [A B C D _ E G H A]
390 // 4 [B C C D _ E G H A]
391 // . . D . .
392 //
393 debug_assert!(dst_pre_wrap_len > src_pre_wrap_len);
394 let delta = dst_pre_wrap_len - src_pre_wrap_len;
395 unsafe {
396 self.copy(src, dst, src_pre_wrap_len);
397 self.copy(0, dst + src_pre_wrap_len, delta);
398 self.copy(delta, 0, len - dst_pre_wrap_len);
399 }
400 }
401 (true, true, true) => {
402 // src before dst, src wraps, dst wraps
403 //
404 // . . S . .
405 // 1 [A B C D _ E F G H]
406 // 2 [A A B D _ E F G H]
407 // 3 [H A B D _ E F G H]
408 // 4 [H A B D _ E F F G]
409 // . . . D .
410 //
411 debug_assert!(src_pre_wrap_len > dst_pre_wrap_len);
412 let delta = src_pre_wrap_len - dst_pre_wrap_len;
413 unsafe {
414 self.copy(0, delta, len - src_pre_wrap_len);
415 self.copy(self.capacity() - delta, 0, delta);
416 self.copy(src, dst, dst_pre_wrap_len);
417 }
418 }
419 }
420 }
421
422 /// Copies all values from `src` to `dst`, wrapping around if needed.
423 /// Assumes capacity is sufficient.
424 #[inline]
425 unsafe fn copy_slice(&mut self, dst: usize, src: &[T]) {
426 debug_assert!(src.len() <= self.capacity());
427 let head_room = self.capacity() - dst;
428 if src.len() <= head_room {
429 unsafe {
430 ptr::copy_nonoverlapping(src.as_ptr(), self.ptr().add(dst), src.len());
431 }
432 } else {
433 let (left, right) = src.split_at(head_room);
434 unsafe {
435 ptr::copy_nonoverlapping(left.as_ptr(), self.ptr().add(dst), left.len());
436 ptr::copy_nonoverlapping(right.as_ptr(), self.ptr(), right.len());
437 }
438 }
439 }
440
441 /// Frobs the head and tail sections around to handle the fact that we
442 /// just reallocated. Unsafe because it trusts old_capacity.
443 #[inline]
444 unsafe fn handle_capacity_increase(&mut self, old_capacity: usize) {
445 let new_capacity = self.capacity();
446 debug_assert!(new_capacity >= old_capacity);
447
448 // Move the shortest contiguous section of the ring buffer
449 //
450 // H := head
451 // L := last element (`self.to_physical_idx(self.len - 1)`)
452 //
453 // H L
454 // [o o o o o o o . ]
455 // H L
456 // A [o o o o o o o . . . . . . . . . ]
457 // L H
458 // [o o o o o o o o ]
459 // H L
460 // B [. . . o o o o o o o . . . . . . ]
461 // L H
462 // [o o o o o o o o ]
463 // L H
464 // C [o o o o o . . . . . . . . . o o ]
465
466 // can't use is_contiguous() because the capacity is already updated.
467 if self.head <= old_capacity - self.len {
468 // A
469 // Nop
470 } else {
471 let head_len = old_capacity - self.head;
472 let tail_len = self.len - head_len;
473 if head_len > tail_len && new_capacity - old_capacity >= tail_len {
474 // B
475 unsafe {
476 self.copy_nonoverlapping(0, old_capacity, tail_len);
477 }
478 } else {
479 // C
480 let new_head = new_capacity - head_len;
481 unsafe {
482 // can't use copy_nonoverlapping here, because if e.g. head_len = 2
483 // and new_capacity = old_capacity + 1, then the heads overlap.
484 self.copy(self.head, new_head, head_len);
485 }
486 self.head = new_head;
487 }
488 }
489 debug_assert!(self.head < self.capacity() || self.capacity() == 0);
490 }
491}
492
493impl<T> VecDeque<T> {
494 /// Creates an empty deque.
495 ///
496 /// # Examples
497 ///
498 /// ```
499 /// use rune::alloc::VecDeque;
500 ///
501 /// let deque: VecDeque<u32> = VecDeque::new();
502 /// ```
503 #[inline]
504 #[must_use]
505 pub const fn new() -> Self {
506 Self::new_in(Global)
507 }
508
509 /// Creates an empty deque with space for at least `capacity` elements.
510 ///
511 /// # Examples
512 ///
513 /// ```
514 /// use rune::alloc::VecDeque;
515 ///
516 /// let deque: VecDeque<u32> = VecDeque::try_with_capacity(10)?;
517 /// # Ok::<_, rune::alloc::Error>(())
518 /// ```
519 pub fn try_with_capacity(capacity: usize) -> Result<Self, Error> {
520 Self::try_with_capacity_in(capacity, Global)
521 }
522}
523
524impl<T, A> VecDeque<T, A>
525where
526 A: Allocator,
527{
528 /// Creates an empty deque.
529 ///
530 /// # Examples
531 ///
532 /// ```
533 /// use rune::alloc::VecDeque;
534 ///
535 /// let deque: VecDeque<u32> = VecDeque::new();
536 /// ```
537 #[inline]
538 pub const fn new_in(alloc: A) -> VecDeque<T, A> {
539 VecDeque {
540 head: 0,
541 len: 0,
542 buf: RawVec::new_in(alloc),
543 }
544 }
545
546 /// Creates an empty deque with space for at least `capacity` elements.
547 ///
548 /// # Examples
549 ///
550 /// ```
551 /// use rune::alloc::VecDeque;
552 /// use rune::alloc::alloc::Global;
553 ///
554 /// let deque: VecDeque<u32> = VecDeque::try_with_capacity_in(10, Global)?;
555 /// # Ok::<_, rune::alloc::Error>(())
556 /// ```
557 pub fn try_with_capacity_in(capacity: usize, alloc: A) -> Result<VecDeque<T, A>, Error> {
558 Ok(VecDeque {
559 head: 0,
560 len: 0,
561 buf: RawVec::try_with_capacity_in(capacity, alloc)?,
562 })
563 }
564
565 /// Provides a reference to the element at the given index.
566 ///
567 /// Element at index 0 is the front of the queue.
568 ///
569 /// # Examples
570 ///
571 /// ```
572 /// use rune::alloc::VecDeque;
573 ///
574 /// let mut buf = VecDeque::new();
575 ///
576 /// buf.try_push_back(3);
577 /// buf.try_push_back(4);
578 /// buf.try_push_back(5);
579 /// buf.try_push_back(6);
580 ///
581 /// assert_eq!(buf.get(1), Some(&4));
582 ///
583 /// # Ok::<_, rune::alloc::Error>(())
584 /// ```
585 pub fn get(&self, index: usize) -> Option<&T> {
586 if index < self.len {
587 let idx = self.to_physical_idx(index);
588 unsafe { Some(&*self.ptr().add(idx)) }
589 } else {
590 None
591 }
592 }
593
594 /// Provides a mutable reference to the element at the given index.
595 ///
596 /// Element at index 0 is the front of the queue.
597 ///
598 /// # Examples
599 ///
600 /// ```
601 /// use rune::alloc::VecDeque;
602 ///
603 /// let mut buf = VecDeque::new();
604 ///
605 /// buf.try_push_back(3)?;
606 /// buf.try_push_back(4)?;
607 /// buf.try_push_back(5)?;
608 /// buf.try_push_back(6)?;
609 ///
610 /// assert_eq!(buf[1], 4);
611 ///
612 /// if let Some(elem) = buf.get_mut(1) {
613 /// *elem = 7;
614 /// }
615 ///
616 /// assert_eq!(buf[1], 7);
617 /// # Ok::<_, rune::alloc::Error>(())
618 /// ```
619 pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
620 if index < self.len {
621 let idx = self.to_physical_idx(index);
622 unsafe { Some(&mut *self.ptr().add(idx)) }
623 } else {
624 None
625 }
626 }
627
628 /// Swaps elements at indices `i` and `j`.
629 ///
630 /// `i` and `j` may be equal.
631 ///
632 /// Element at index 0 is the front of the queue.
633 ///
634 /// # Panics
635 ///
636 /// Panics if either index is out of bounds.
637 ///
638 /// # Examples
639 ///
640 /// ```
641 /// use rune::alloc::VecDeque;
642 ///
643 /// let mut buf = VecDeque::new();
644 ///
645 /// buf.try_push_back(3)?;
646 /// buf.try_push_back(4)?;
647 /// buf.try_push_back(5)?;
648 ///
649 /// assert_eq!(buf, [3, 4, 5]);
650 ///
651 /// buf.swap(0, 2);
652 ///
653 /// assert_eq!(buf, [5, 4, 3]);
654 /// # Ok::<_, rune::alloc::Error>(())
655 /// ```
656 pub fn swap(&mut self, i: usize, j: usize) {
657 assert!(i < self.len());
658 assert!(j < self.len());
659 let ri = self.to_physical_idx(i);
660 let rj = self.to_physical_idx(j);
661 unsafe { ptr::swap(self.ptr().add(ri), self.ptr().add(rj)) }
662 }
663
664 /// Returns the number of elements the deque can hold without reallocating.
665 ///
666 /// # Examples
667 ///
668 /// ```
669 /// use rune::alloc::VecDeque;
670 ///
671 /// let buf: VecDeque<i32> = VecDeque::try_with_capacity(10)?;
672 /// assert!(buf.capacity() >= 10);
673 /// # Ok::<_, rune::alloc::Error>(())
674 /// ```
675 #[inline]
676 pub fn capacity(&self) -> usize {
677 if T::IS_ZST {
678 usize::MAX
679 } else {
680 self.buf.capacity()
681 }
682 }
683
684 /// Tries to reserve the minimum capacity for at least `additional` more elements to
685 /// be inserted in the given deque. After calling `try_reserve_exact`,
686 /// capacity will be greater than or equal to `self.len() + additional` if
687 /// it returns `Ok(())`. Does nothing if the capacity is already sufficient.
688 ///
689 /// Note that the allocator may give the collection more space than it
690 /// requests. Therefore, capacity can not be relied upon to be precisely
691 /// minimal. Prefer [`try_reserve`] if future insertions are expected.
692 ///
693 /// [`try_reserve`]: VecDeque::try_reserve
694 ///
695 /// # Errors
696 ///
697 /// If the capacity overflows `usize`, or the allocator reports a failure, then an error
698 /// is returned.
699 ///
700 /// # Examples
701 ///
702 /// ```
703 /// use rune::alloc::{VecDeque, Error};
704 /// use rune::alloc::prelude::*;
705 ///
706 /// fn process_data(data: &[u32]) -> Result<VecDeque<u32>, Error> {
707 /// let mut output = VecDeque::new();
708 ///
709 /// // Pre-reserve the memory, exiting if we can't
710 /// output.try_reserve_exact(data.len())?;
711 ///
712 /// // Now we know this can't OOM(Out-Of-Memory) in the middle of our complex work
713 /// output.try_extend(data.iter().map(|&val| {
714 /// val * 2 + 5 // very complicated
715 /// }))?;
716 ///
717 /// Ok(output)
718 /// }
719 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
720 /// ```
721 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), Error> {
722 let new_cap = self
723 .len
724 .checked_add(additional)
725 .ok_or(Error::CapacityOverflow)?;
726 let old_cap = self.capacity();
727
728 if new_cap > old_cap {
729 self.buf.try_reserve_exact(self.len, additional)?;
730 unsafe {
731 self.handle_capacity_increase(old_cap);
732 }
733 }
734 Ok(())
735 }
736
737 /// Tries to reserve capacity for at least `additional` more elements to be inserted
738 /// in the given deque. The collection may reserve more space to speculatively avoid
739 /// frequent reallocations. After calling `try_reserve`, capacity will be
740 /// greater than or equal to `self.len() + additional` if it returns
741 /// `Ok(())`. Does nothing if capacity is already sufficient. This method
742 /// preserves the contents even if an error occurs.
743 ///
744 /// # Errors
745 ///
746 /// If the capacity overflows `usize`, or the allocator reports a failure, then an error
747 /// is returned.
748 ///
749 /// # Examples
750 ///
751 /// ```
752 /// use rune::alloc::{VecDeque, Error};
753 /// use rune::alloc::prelude::*;
754 ///
755 /// fn process_data(data: &[u32]) -> Result<VecDeque<u32>, Error> {
756 /// let mut output = VecDeque::new();
757 ///
758 /// // Pre-reserve the memory, exiting if we can't
759 /// output.try_reserve(data.len())?;
760 ///
761 /// // Now we know this can't OOM in the middle of our complex work
762 /// output.try_extend(data.iter().map(|&val| {
763 /// val * 2 + 5 // very complicated
764 /// }))?;
765 ///
766 /// Ok(output)
767 /// }
768 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
769 /// ```
770 pub fn try_reserve(&mut self, additional: usize) -> Result<(), Error> {
771 let new_cap = self
772 .len
773 .checked_add(additional)
774 .ok_or(Error::CapacityOverflow)?;
775 let old_cap = self.capacity();
776
777 if new_cap > old_cap {
778 self.buf.try_reserve(self.len, additional)?;
779 unsafe {
780 self.handle_capacity_increase(old_cap);
781 }
782 }
783
784 Ok(())
785 }
786
787 /// Shrinks the capacity of the deque as much as possible.
788 ///
789 /// It will drop down as close as possible to the length but the allocator may still inform the
790 /// deque that there is space for a few more elements.
791 ///
792 /// # Examples
793 ///
794 /// ```
795 /// use rune::alloc::VecDeque;
796 /// use rune::alloc::prelude::*;
797 ///
798 /// let mut buf = VecDeque::try_with_capacity(15)?;
799 /// buf.try_extend(0..4)?;
800 /// assert_eq!(buf.capacity(), 15);
801 /// buf.try_shrink_to_fit()?;
802 /// assert!(buf.capacity() >= 4);
803 /// # Ok::<_, rune::alloc::Error>(())
804 /// ```
805 pub fn try_shrink_to_fit(&mut self) -> Result<(), Error> {
806 self.try_shrink_to(0)
807 }
808
809 /// Shrinks the capacity of the deque with a lower bound.
810 ///
811 /// The capacity will remain at least as large as both the length
812 /// and the supplied value.
813 ///
814 /// If the current capacity is less than the lower limit, this is a no-op.
815 ///
816 /// # Examples
817 ///
818 /// ```
819 /// use rune::alloc::VecDeque;
820 /// use rune::alloc::prelude::*;
821 ///
822 /// let mut buf = VecDeque::try_with_capacity(15)?;
823 /// buf.try_extend(0..4)?;
824 /// assert_eq!(buf.capacity(), 15);
825 /// buf.try_shrink_to(6)?;
826 /// assert!(buf.capacity() >= 6);
827 /// buf.try_shrink_to(0)?;
828 /// assert!(buf.capacity() >= 4);
829 /// # Ok::<_, rune::alloc::Error>(())
830 /// ```
831 pub fn try_shrink_to(&mut self, min_capacity: usize) -> Result<(), Error> {
832 let target_cap = min_capacity.max(self.len);
833
834 // never shrink ZSTs
835 if T::IS_ZST || self.capacity() <= target_cap {
836 return Ok(());
837 }
838
839 // There are three cases of interest:
840 // All elements are out of desired bounds
841 // Elements are contiguous, and tail is out of desired bounds
842 // Elements are discontiguous
843 //
844 // At all other times, element positions are unaffected.
845
846 // `head` and `len` are at most `isize::MAX` and `target_cap < self.capacity()`, so nothing can
847 // overflow.
848 let tail_outside = (target_cap + 1..=self.capacity()).contains(&(self.head + self.len));
849
850 if self.len == 0 {
851 self.head = 0;
852 } else if self.head >= target_cap && tail_outside {
853 // Head and tail are both out of bounds, so copy all of them to the front.
854 //
855 // H := head
856 // L := last element
857 // H L
858 // [. . . . . . . . o o o o o o o . ]
859 // H L
860 // [o o o o o o o . ]
861 unsafe {
862 // nonoverlapping because `self.head >= target_cap >= self.len`.
863 self.copy_nonoverlapping(self.head, 0, self.len);
864 }
865 self.head = 0;
866 } else if self.head < target_cap && tail_outside {
867 // Head is in bounds, tail is out of bounds.
868 // Copy the overflowing part to the beginning of the
869 // buffer. This won't overlap because `target_cap >= self.len`.
870 //
871 // H := head
872 // L := last element
873 // H L
874 // [. . . o o o o o o o . . . . . . ]
875 // L H
876 // [o o . o o o o o ]
877 let len = self.head + self.len - target_cap;
878 unsafe {
879 self.copy_nonoverlapping(target_cap, 0, len);
880 }
881 } else if !self.is_contiguous() {
882 // The head slice is at least partially out of bounds, tail is in bounds.
883 // Copy the head backwards so it lines up with the target capacity.
884 // This won't overlap because `target_cap >= self.len`.
885 //
886 // H := head
887 // L := last element
888 // L H
889 // [o o o o o . . . . . . . . . o o ]
890 // L H
891 // [o o o o o . o o ]
892 let head_len = self.capacity() - self.head;
893 let new_head = target_cap - head_len;
894 unsafe {
895 // can't use `copy_nonoverlapping()` here because the new and old
896 // regions for the head might overlap.
897 self.copy(self.head, new_head, head_len);
898 }
899 self.head = new_head;
900 }
901
902 self.buf.try_shrink_to_fit(target_cap)?;
903
904 debug_assert!(self.head < self.capacity() || self.capacity() == 0);
905 debug_assert!(self.len <= self.capacity());
906 Ok(())
907 }
908
909 /// Shortens the deque, keeping the first `len` elements and dropping
910 /// the rest.
911 ///
912 /// If `len` is greater than the deque's current length, this has no
913 /// effect.
914 ///
915 /// # Examples
916 ///
917 /// ```
918 /// use rune::alloc::VecDeque;
919 ///
920 /// let mut buf = VecDeque::new();
921 ///
922 /// buf.try_push_back(5)?;
923 /// buf.try_push_back(10)?;
924 /// buf.try_push_back(15)?;
925 ///
926 /// assert_eq!(buf, [5, 10, 15]);
927 ///
928 /// buf.truncate(1);
929 ///
930 /// assert_eq!(buf, [5]);
931 /// # Ok::<_, rune::alloc::Error>(())
932 /// ```
933 pub fn truncate(&mut self, len: usize) {
934 /// Runs the destructor for all items in the slice when it gets dropped (normally or
935 /// during unwinding).
936 struct Dropper<'a, T>(&'a mut [T]);
937
938 impl<T> Drop for Dropper<'_, T> {
939 fn drop(&mut self) {
940 unsafe {
941 ptr::drop_in_place(self.0);
942 }
943 }
944 }
945
946 // Safe because:
947 //
948 // * Any slice passed to `drop_in_place` is valid; the second case has
949 // `len <= front.len()` and returning on `len > self.len()` ensures
950 // `begin <= back.len()` in the first case
951 // * The head of the VecDeque is moved before calling `drop_in_place`,
952 // so no value is dropped twice if `drop_in_place` panics
953 unsafe {
954 if len >= self.len {
955 return;
956 }
957
958 let (front, back) = self.as_mut_slices();
959 if len > front.len() {
960 let begin = len - front.len();
961 let drop_back = back.get_unchecked_mut(begin..) as *mut _;
962 self.len = len;
963 ptr::drop_in_place(drop_back);
964 } else {
965 let drop_back = back as *mut _;
966 let drop_front = front.get_unchecked_mut(len..) as *mut _;
967 self.len = len;
968
969 // Make sure the second half is dropped even when a destructor
970 // in the first one panics.
971 let _back_dropper = Dropper(&mut *drop_back);
972 ptr::drop_in_place(drop_front);
973 }
974 }
975 }
976
977 /// Returns a reference to the underlying allocator.
978 #[inline]
979 pub fn allocator(&self) -> &A {
980 self.buf.allocator()
981 }
982
983 /// Returns a front-to-back iterator.
984 ///
985 /// # Examples
986 ///
987 /// ```
988 /// use rune::alloc::{Vec, VecDeque};
989 /// use rune::alloc::prelude::*;
990 ///
991 /// let mut buf = VecDeque::new();
992 /// buf.try_push_back(5)?;
993 /// buf.try_push_back(3)?;
994 /// buf.try_push_back(4)?;
995 /// let b: &[_] = &[&5, &3, &4];
996 /// let c: Vec<&i32> = buf.iter().try_collect()?;
997 /// assert_eq!(&c[..], b);
998 /// # Ok::<_, rune::alloc::Error>(())
999 /// ```
1000 pub fn iter(&self) -> Iter<'_, T> {
1001 let (a, b) = self.as_slices();
1002 Iter::new(a.iter(), b.iter())
1003 }
1004
1005 /// Returns a raw front-to-back iterator.
1006 ///
1007 /// # Safety
1008 ///
1009 /// The caller must ensure that the iterator doesn't outlive `self`.
1010 pub unsafe fn raw_iter(&self) -> RawIter<T> {
1011 let (a, b) = self.as_slices();
1012 RawIter::new(crate::slice::RawIter::new(a), crate::slice::RawIter::new(b))
1013 }
1014
1015 /// Returns a front-to-back iterator that returns mutable references.
1016 ///
1017 /// # Examples
1018 ///
1019 /// ```
1020 /// use rune::alloc::VecDeque;
1021 ///
1022 /// let mut buf = VecDeque::new();
1023 /// buf.try_push_back(5)?;
1024 /// buf.try_push_back(3)?;
1025 /// buf.try_push_back(4)?;
1026 /// for num in buf.iter_mut() {
1027 /// *num = *num - 2;
1028 /// }
1029 /// let b: &[_] = &[&mut 3, &mut 1, &mut 2];
1030 /// assert_eq!(&buf.iter_mut().collect::<Vec<&mut i32>>()[..], b);
1031 /// # Ok::<_, rune::alloc::Error>(())
1032 /// ```
1033 pub fn iter_mut(&mut self) -> IterMut<'_, T> {
1034 let (a, b) = self.as_mut_slices();
1035 IterMut::new(a.iter_mut(), b.iter_mut())
1036 }
1037
1038 /// Returns a pair of slices which contain, in order, the contents of the
1039 /// deque.
1040 ///
1041 /// If [`make_contiguous`] was previously called, all elements of the
1042 /// deque will be in the first slice and the second slice will be empty.
1043 ///
1044 /// [`make_contiguous`]: VecDeque::make_contiguous
1045 ///
1046 /// # Examples
1047 ///
1048 /// ```
1049 /// use rune::alloc::VecDeque;
1050 ///
1051 /// let mut deque = VecDeque::new();
1052 ///
1053 /// deque.try_push_back(0)?;
1054 /// deque.try_push_back(1)?;
1055 /// deque.try_push_back(2)?;
1056 ///
1057 /// assert_eq!(deque.as_slices(), (&[0, 1, 2][..], &[][..]));
1058 ///
1059 /// deque.try_push_front(10)?;
1060 /// deque.try_push_front(9)?;
1061 ///
1062 /// assert_eq!(deque.as_slices(), (&[9, 10][..], &[0, 1, 2][..]));
1063 /// # Ok::<_, rune::alloc::Error>(())
1064 /// ```
1065 #[inline]
1066 pub fn as_slices(&self) -> (&[T], &[T]) {
1067 let (a_range, b_range) = self.slice_ranges(.., self.len);
1068 // SAFETY: `slice_ranges` always returns valid ranges into
1069 // the physical buffer.
1070 unsafe { (&*self.buffer_range(a_range), &*self.buffer_range(b_range)) }
1071 }
1072
1073 /// Returns a pair of slices which contain, in order, the contents of the
1074 /// deque.
1075 ///
1076 /// If [`make_contiguous`] was previously called, all elements of the
1077 /// deque will be in the first slice and the second slice will be empty.
1078 ///
1079 /// [`make_contiguous`]: VecDeque::make_contiguous
1080 ///
1081 /// # Examples
1082 ///
1083 /// ```
1084 /// use rune::alloc::VecDeque;
1085 ///
1086 /// let mut deque = VecDeque::new();
1087 ///
1088 /// deque.try_push_back(0)?;
1089 /// deque.try_push_back(1)?;
1090 ///
1091 /// deque.try_push_front(10)?;
1092 /// deque.try_push_front(9)?;
1093 ///
1094 /// deque.as_mut_slices().0[0] = 42;
1095 /// deque.as_mut_slices().1[0] = 24;
1096 /// assert_eq!(deque.as_slices(), (&[42, 10][..], &[24, 1][..]));
1097 /// # Ok::<_, rune::alloc::Error>(())
1098 /// ```
1099 #[inline]
1100 pub fn as_mut_slices(&mut self) -> (&mut [T], &mut [T]) {
1101 let (a_range, b_range) = self.slice_ranges(.., self.len);
1102 // SAFETY: `slice_ranges` always returns valid ranges into
1103 // the physical buffer.
1104 unsafe {
1105 (
1106 &mut *self.buffer_range(a_range),
1107 &mut *self.buffer_range(b_range),
1108 )
1109 }
1110 }
1111
1112 /// Returns the number of elements in the deque.
1113 ///
1114 /// # Examples
1115 ///
1116 /// ```
1117 /// use rune::alloc::VecDeque;
1118 ///
1119 /// let mut deque = VecDeque::new();
1120 /// assert_eq!(deque.len(), 0);
1121 /// deque.try_push_back(1)?;
1122 /// assert_eq!(deque.len(), 1);
1123 /// # Ok::<_, rune::alloc::Error>(())
1124 /// ```
1125 pub fn len(&self) -> usize {
1126 self.len
1127 }
1128
1129 /// Returns `true` if the deque is empty.
1130 ///
1131 /// # Examples
1132 ///
1133 /// ```
1134 /// use rune::alloc::VecDeque;
1135 ///
1136 /// let mut deque = VecDeque::new();
1137 /// assert!(deque.is_empty());
1138 /// deque.try_push_front(1)?;
1139 /// assert!(!deque.is_empty());
1140 /// # Ok::<_, rune::alloc::Error>(())
1141 /// ```
1142 pub fn is_empty(&self) -> bool {
1143 self.len == 0
1144 }
1145
1146 /// Given a range into the logical buffer of the deque, this function
1147 /// return two ranges into the physical buffer that correspond to
1148 /// the given range. The `len` parameter should usually just be `self.len`;
1149 /// the reason it's passed explicitly is that if the deque is wrapped in a
1150 /// `Drain`, then `self.len` is not actually the length of the deque.
1151 ///
1152 /// # Safety
1153 ///
1154 /// This function is always safe to call. For the resulting ranges to be
1155 /// valid ranges into the physical buffer, the caller must ensure that the
1156 /// result of calling `slice::range(range, ..len)` represents a valid range
1157 /// into the logical buffer, and that all elements in that range are
1158 /// initialized.
1159 fn slice_ranges<R>(&self, range: R, len: usize) -> (Range<usize>, Range<usize>)
1160 where
1161 R: RangeBounds<usize>,
1162 {
1163 let Range { start, end } = slice_range(range, ..len);
1164 let len = end - start;
1165
1166 if len == 0 {
1167 (0..0, 0..0)
1168 } else {
1169 // `slice_range` guarantees that `start <= end <= len`.
1170 // because `len != 0`, we know that `start < end`, so `start < len`
1171 // and the indexing is valid.
1172 let wrapped_start = self.to_physical_idx(start);
1173
1174 // this subtraction can never overflow because `wrapped_start` is
1175 // at most `self.capacity()` (and if `self.capacity != 0`, then `wrapped_start` is strictly less
1176 // than `self.capacity`).
1177 let head_len = self.capacity() - wrapped_start;
1178
1179 if head_len >= len {
1180 // we know that `len + wrapped_start <= self.capacity <= usize::MAX`, so this addition can't overflow
1181 (wrapped_start..wrapped_start + len, 0..0)
1182 } else {
1183 // can't overflow because of the if condition
1184 let tail_len = len - head_len;
1185 (wrapped_start..self.capacity(), 0..tail_len)
1186 }
1187 }
1188 }
1189
1190 /// Creates an iterator that covers the specified range in the deque.
1191 ///
1192 /// # Panics
1193 ///
1194 /// Panics if the starting point is greater than the end point or if
1195 /// the end point is greater than the length of the deque.
1196 ///
1197 /// # Examples
1198 ///
1199 /// ```
1200 /// use rune::alloc::VecDeque;
1201 /// use rune::alloc::prelude::*;
1202 ///
1203 /// let deque: VecDeque<_> = [1, 2, 3].try_into()?;
1204 /// let range = deque.range(2..).copied().try_collect::<VecDeque<_>>()?;
1205 /// assert_eq!(range, [3]);
1206 ///
1207 /// // A full range covers all contents
1208 /// let all = deque.range(..);
1209 /// assert_eq!(all.len(), 3);
1210 /// # Ok::<_, rune::alloc::Error>(())
1211 /// ```
1212 #[inline]
1213 pub fn range<R>(&self, range: R) -> Iter<'_, T>
1214 where
1215 R: RangeBounds<usize>,
1216 {
1217 let (a_range, b_range) = self.slice_ranges(range, self.len);
1218 // SAFETY: The ranges returned by `slice_ranges`
1219 // are valid ranges into the physical buffer, so
1220 // it's ok to pass them to `buffer_range` and
1221 // dereference the result.
1222 let a = unsafe { &*self.buffer_range(a_range) };
1223 let b = unsafe { &*self.buffer_range(b_range) };
1224 Iter::new(a.iter(), b.iter())
1225 }
1226
1227 /// Creates an iterator that covers the specified mutable range in the deque.
1228 ///
1229 /// # Panics
1230 ///
1231 /// Panics if the starting point is greater than the end point or if
1232 /// the end point is greater than the length of the deque.
1233 ///
1234 /// # Examples
1235 ///
1236 /// ```
1237 /// use rune::alloc::VecDeque;
1238 ///
1239 /// let mut deque: VecDeque<_> = [1, 2, 3].try_into()?;
1240 /// for v in deque.range_mut(2..) {
1241 /// *v *= 2;
1242 /// }
1243 /// assert_eq!(deque, [1, 2, 6]);
1244 ///
1245 /// // A full range covers all contents
1246 /// for v in deque.range_mut(..) {
1247 /// *v *= 2;
1248 /// }
1249 /// assert_eq!(deque, [2, 4, 12]);
1250 /// # Ok::<_, rune::alloc::Error>(())
1251 /// ```
1252 #[inline]
1253 pub fn range_mut<R>(&mut self, range: R) -> IterMut<'_, T>
1254 where
1255 R: RangeBounds<usize>,
1256 {
1257 let (a_range, b_range) = self.slice_ranges(range, self.len);
1258 // SAFETY: The ranges returned by `slice_ranges`
1259 // are valid ranges into the physical buffer, so
1260 // it's ok to pass them to `buffer_range` and
1261 // dereference the result.
1262 let a = unsafe { &mut *self.buffer_range(a_range) };
1263 let b = unsafe { &mut *self.buffer_range(b_range) };
1264 IterMut::new(a.iter_mut(), b.iter_mut())
1265 }
1266
1267 /// Removes the specified range from the deque in bulk, returning all
1268 /// removed elements as an iterator. If the iterator is dropped before
1269 /// being fully consumed, it drops the remaining removed elements.
1270 ///
1271 /// The returned iterator keeps a mutable borrow on the queue to optimize
1272 /// its implementation.
1273 ///
1274 ///
1275 /// # Panics
1276 ///
1277 /// Panics if the starting point is greater than the end point or if
1278 /// the end point is greater than the length of the deque.
1279 ///
1280 /// # Leaking
1281 ///
1282 /// If the returned iterator goes out of scope without being dropped (due to
1283 /// [`mem::forget`], for example), the deque may have lost and leaked
1284 /// elements arbitrarily, including elements outside the range.
1285 ///
1286 /// # Examples
1287 ///
1288 /// ```
1289 /// use rune::alloc::VecDeque;
1290 /// use rune::alloc::prelude::*;
1291 ///
1292 /// let mut deque: VecDeque<_> = [1, 2, 3].try_into()?;
1293 /// let drained = deque.drain(2..).try_collect::<VecDeque<_>>()?;
1294 /// assert_eq!(drained, [3]);
1295 /// assert_eq!(deque, [1, 2]);
1296 ///
1297 /// // A full range clears all contents, like `clear()` does
1298 /// deque.drain(..);
1299 /// assert!(deque.is_empty());
1300 /// # Ok::<_, rune::alloc::Error>(())
1301 /// ```
1302 #[inline]
1303 pub fn drain<R>(&mut self, range: R) -> Drain<'_, T, A>
1304 where
1305 R: RangeBounds<usize>,
1306 {
1307 // Memory safety
1308 //
1309 // When the Drain is first created, the source deque is shortened to
1310 // make sure no uninitialized or moved-from elements are accessible at
1311 // all if the Drain's destructor never gets to run.
1312 //
1313 // Drain will ptr::read out the values to remove.
1314 // When finished, the remaining data will be copied back to cover the hole,
1315 // and the head/tail values will be restored correctly.
1316 //
1317 let Range { start, end } = slice_range(range, ..self.len);
1318 let drain_start = start;
1319 let drain_len = end - start;
1320
1321 // The deque's elements are parted into three segments:
1322 // * 0 -> drain_start
1323 // * drain_start -> drain_start+drain_len
1324 // * drain_start+drain_len -> self.len
1325 //
1326 // H = self.head; T = self.head+self.len; t = drain_start+drain_len; h = drain_head
1327 //
1328 // We store drain_start as self.len, and drain_len and self.len as
1329 // drain_len and orig_len respectively on the Drain. This also
1330 // truncates the effective array such that if the Drain is leaked, we
1331 // have forgotten about the potentially moved values after the start of
1332 // the drain.
1333 //
1334 // H h t T
1335 // [. . . o o x x o o . . .]
1336 //
1337 // "forget" about the values after the start of the drain until after
1338 // the drain is complete and the Drain destructor is run.
1339
1340 unsafe { Drain::new(self, drain_start, drain_len) }
1341 }
1342
1343 /// Clears the deque, removing all values.
1344 ///
1345 /// # Examples
1346 ///
1347 /// ```
1348 /// use rune::alloc::VecDeque;
1349 ///
1350 /// let mut deque = VecDeque::new();
1351 /// deque.try_push_back(1)?;
1352 /// deque.clear();
1353 /// assert!(deque.is_empty());
1354 /// # Ok::<_, rune::alloc::Error>(())
1355 /// ```
1356 #[inline]
1357 pub fn clear(&mut self) {
1358 self.truncate(0);
1359 // Not strictly necessary, but leaves things in a more consistent/predictable state.
1360 self.head = 0;
1361 }
1362
1363 /// Returns `true` if the deque contains an element equal to the
1364 /// given value.
1365 ///
1366 /// This operation is *O*(*n*).
1367 ///
1368 /// Note that if you have a sorted `VecDeque`, [`binary_search`] may be faster.
1369 ///
1370 /// [`binary_search`]: VecDeque::binary_search
1371 ///
1372 /// # Examples
1373 ///
1374 /// ```
1375 /// use rune::alloc::VecDeque;
1376 ///
1377 /// let mut deque: VecDeque<u32> = VecDeque::new();
1378 ///
1379 /// deque.try_push_back(0)?;
1380 /// deque.try_push_back(1)?;
1381 ///
1382 /// assert_eq!(deque.contains(&1), true);
1383 /// assert_eq!(deque.contains(&10), false);
1384 /// # Ok::<_, rune::alloc::Error>(())
1385 /// ```
1386 pub fn contains(&self, x: &T) -> bool
1387 where
1388 T: PartialEq<T>,
1389 {
1390 let (a, b) = self.as_slices();
1391 a.contains(x) || b.contains(x)
1392 }
1393
1394 /// Provides a reference to the front element, or `None` if the deque is
1395 /// empty.
1396 ///
1397 /// # Examples
1398 ///
1399 /// ```
1400 /// use rune::alloc::VecDeque;
1401 ///
1402 /// let mut d = VecDeque::new();
1403 /// assert_eq!(d.front(), None);
1404 ///
1405 /// d.try_push_back(1)?;
1406 /// d.try_push_back(2)?;
1407 /// assert_eq!(d.front(), Some(&1));
1408 /// # Ok::<_, rune::alloc::Error>(())
1409 /// ```
1410 pub fn front(&self) -> Option<&T> {
1411 self.get(0)
1412 }
1413
1414 /// Provides a mutable reference to the front element, or `None` if the
1415 /// deque is empty.
1416 ///
1417 /// # Examples
1418 ///
1419 /// ```
1420 /// use rune::alloc::VecDeque;
1421 ///
1422 /// let mut d = VecDeque::new();
1423 /// assert_eq!(d.front_mut(), None);
1424 ///
1425 /// d.try_push_back(1)?;
1426 /// d.try_push_back(2)?;
1427 /// match d.front_mut() {
1428 /// Some(x) => *x = 9,
1429 /// None => (),
1430 /// }
1431 /// assert_eq!(d.front(), Some(&9));
1432 /// # Ok::<_, rune::alloc::Error>(())
1433 /// ```
1434 pub fn front_mut(&mut self) -> Option<&mut T> {
1435 self.get_mut(0)
1436 }
1437
1438 /// Provides a reference to the back element, or `None` if the deque is
1439 /// empty.
1440 ///
1441 /// # Examples
1442 ///
1443 /// ```
1444 /// use rune::alloc::VecDeque;
1445 ///
1446 /// let mut d = VecDeque::new();
1447 /// assert_eq!(d.back(), None);
1448 ///
1449 /// d.try_push_back(1)?;
1450 /// d.try_push_back(2)?;
1451 /// assert_eq!(d.back(), Some(&2));
1452 /// # Ok::<_, rune::alloc::Error>(())
1453 /// ```
1454 pub fn back(&self) -> Option<&T> {
1455 self.get(self.len.wrapping_sub(1))
1456 }
1457
1458 /// Provides a mutable reference to the back element, or `None` if the
1459 /// deque is empty.
1460 ///
1461 /// # Examples
1462 ///
1463 /// ```
1464 /// use rune::alloc::VecDeque;
1465 ///
1466 /// let mut d = VecDeque::new();
1467 /// assert_eq!(d.back(), None);
1468 ///
1469 /// d.try_push_back(1)?;
1470 /// d.try_push_back(2)?;
1471 /// match d.back_mut() {
1472 /// Some(x) => *x = 9,
1473 /// None => (),
1474 /// }
1475 /// assert_eq!(d.back(), Some(&9));
1476 /// # Ok::<_, rune::alloc::Error>(())
1477 /// ```
1478 pub fn back_mut(&mut self) -> Option<&mut T> {
1479 self.get_mut(self.len.wrapping_sub(1))
1480 }
1481
1482 /// Removes the first element and returns it, or `None` if the deque is
1483 /// empty.
1484 ///
1485 /// # Examples
1486 ///
1487 /// ```
1488 /// use rune::alloc::VecDeque;
1489 ///
1490 /// let mut d = VecDeque::new();
1491 /// d.try_push_back(1)?;
1492 /// d.try_push_back(2)?;
1493 ///
1494 /// assert_eq!(d.pop_front(), Some(1));
1495 /// assert_eq!(d.pop_front(), Some(2));
1496 /// assert_eq!(d.pop_front(), None);
1497 /// # Ok::<_, rune::alloc::Error>(())
1498 /// ```
1499 pub fn pop_front(&mut self) -> Option<T> {
1500 if self.is_empty() {
1501 None
1502 } else {
1503 let old_head = self.head;
1504 self.head = self.to_physical_idx(1);
1505 self.len -= 1;
1506 Some(unsafe { self.buffer_read(old_head) })
1507 }
1508 }
1509
1510 /// Removes the last element from the deque and returns it, or `None` if
1511 /// it is empty.
1512 ///
1513 /// # Examples
1514 ///
1515 /// ```
1516 /// use rune::alloc::VecDeque;
1517 ///
1518 /// let mut buf = VecDeque::new();
1519 /// assert_eq!(buf.pop_back(), None);
1520 /// buf.try_push_back(1)?;
1521 /// buf.try_push_back(3)?;
1522 /// assert_eq!(buf.pop_back(), Some(3));
1523 /// # Ok::<_, rune::alloc::Error>(())
1524 /// ```
1525 pub fn pop_back(&mut self) -> Option<T> {
1526 if self.is_empty() {
1527 None
1528 } else {
1529 self.len -= 1;
1530 Some(unsafe { self.buffer_read(self.to_physical_idx(self.len)) })
1531 }
1532 }
1533
1534 /// Prepends an element to the deque.
1535 ///
1536 /// # Examples
1537 ///
1538 /// ```
1539 /// use rune::alloc::VecDeque;
1540 ///
1541 /// let mut d = VecDeque::new();
1542 /// d.try_push_front(1)?;
1543 /// d.try_push_front(2)?;
1544 /// assert_eq!(d.front(), Some(&2));
1545 /// # Ok::<_, rune::alloc::Error>(())
1546 /// ```
1547 pub fn try_push_front(&mut self, value: T) -> Result<(), Error> {
1548 if self.is_full() {
1549 self.try_grow()?;
1550 }
1551
1552 self.head = self.wrap_sub(self.head, 1);
1553 self.len += 1;
1554
1555 unsafe {
1556 self.buffer_write(self.head, value);
1557 }
1558
1559 Ok(())
1560 }
1561
1562 /// Appends an element to the back of the deque.
1563 ///
1564 /// # Examples
1565 ///
1566 /// ```
1567 /// use rune::alloc::VecDeque;
1568 ///
1569 /// let mut buf = VecDeque::new();
1570 /// buf.try_push_back(1)?;
1571 /// buf.try_push_back(3)?;
1572 /// assert_eq!(3, *buf.back().unwrap());
1573 /// # Ok::<_, rune::alloc::Error>(())
1574 /// ```
1575 pub fn try_push_back(&mut self, value: T) -> Result<(), Error> {
1576 if self.is_full() {
1577 self.try_grow()?;
1578 }
1579
1580 unsafe { self.buffer_write(self.to_physical_idx(self.len), value) }
1581 self.len += 1;
1582 Ok(())
1583 }
1584
1585 #[inline]
1586 fn is_contiguous(&self) -> bool {
1587 // Do the calculation like this to avoid overflowing if len + head > usize::MAX
1588 self.head <= self.capacity() - self.len
1589 }
1590
1591 /// Removes an element from anywhere in the deque and returns it,
1592 /// replacing it with the first element.
1593 ///
1594 /// This does not preserve ordering, but is *O*(1).
1595 ///
1596 /// Returns `None` if `index` is out of bounds.
1597 ///
1598 /// Element at index 0 is the front of the queue.
1599 ///
1600 /// # Examples
1601 ///
1602 /// ```
1603 /// use rune::alloc::VecDeque;
1604 ///
1605 /// let mut buf = VecDeque::new();
1606 /// assert_eq!(buf.swap_remove_front(0), None);
1607 /// buf.try_push_back(1)?;
1608 /// buf.try_push_back(2)?;
1609 /// buf.try_push_back(3)?;
1610 /// assert_eq!(buf, [1, 2, 3]);
1611 ///
1612 /// assert_eq!(buf.swap_remove_front(2), Some(3));
1613 /// assert_eq!(buf, [2, 1]);
1614 /// # Ok::<_, rune::alloc::Error>(())
1615 /// ```
1616 pub fn swap_remove_front(&mut self, index: usize) -> Option<T> {
1617 let length = self.len;
1618 if index < length && index != 0 {
1619 self.swap(index, 0);
1620 } else if index >= length {
1621 return None;
1622 }
1623 self.pop_front()
1624 }
1625
1626 /// Removes an element from anywhere in the deque and returns it,
1627 /// replacing it with the last element.
1628 ///
1629 /// This does not preserve ordering, but is *O*(1).
1630 ///
1631 /// Returns `None` if `index` is out of bounds.
1632 ///
1633 /// Element at index 0 is the front of the queue.
1634 ///
1635 /// # Examples
1636 ///
1637 /// ```
1638 /// use rune::alloc::VecDeque;
1639 ///
1640 /// let mut buf = VecDeque::new();
1641 /// assert_eq!(buf.swap_remove_back(0), None);
1642 /// buf.try_push_back(1)?;
1643 /// buf.try_push_back(2)?;
1644 /// buf.try_push_back(3)?;
1645 /// assert_eq!(buf, [1, 2, 3]);
1646 ///
1647 /// assert_eq!(buf.swap_remove_back(0), Some(1));
1648 /// assert_eq!(buf, [3, 2]);
1649 /// # Ok::<_, rune::alloc::Error>(())
1650 /// ```
1651 pub fn swap_remove_back(&mut self, index: usize) -> Option<T> {
1652 let length = self.len;
1653 if length > 0 && index < length - 1 {
1654 self.swap(index, length - 1);
1655 } else if index >= length {
1656 return None;
1657 }
1658 self.pop_back()
1659 }
1660
1661 /// Inserts an element at `index` within the deque, shifting all elements
1662 /// with indices greater than or equal to `index` towards the back.
1663 ///
1664 /// Element at index 0 is the front of the queue.
1665 ///
1666 /// # Panics
1667 ///
1668 /// Panics if `index` is greater than deque's length
1669 ///
1670 /// # Examples
1671 ///
1672 /// ```
1673 /// use rune::alloc::VecDeque;
1674 ///
1675 /// let mut vec_deque = VecDeque::new();
1676 /// vec_deque.try_push_back('a')?;
1677 /// vec_deque.try_push_back('b')?;
1678 /// vec_deque.try_push_back('c')?;
1679 /// assert_eq!(vec_deque, &['a', 'b', 'c']);
1680 ///
1681 /// vec_deque.try_insert(1, 'd')?;
1682 /// assert_eq!(vec_deque, &['a', 'd', 'b', 'c']);
1683 /// # Ok::<_, rune::alloc::Error>(())
1684 /// ```
1685 pub fn try_insert(&mut self, index: usize, value: T) -> Result<(), Error> {
1686 assert!(index <= self.len(), "index out of bounds");
1687
1688 if self.is_full() {
1689 self.try_grow()?;
1690 }
1691
1692 let k = self.len - index;
1693
1694 if k < index {
1695 // `index + 1` can't overflow, because if index was usize::MAX, then either the
1696 // assert would've failed, or the deque would've tried to grow past usize::MAX
1697 // and panicked.
1698 unsafe {
1699 // see `remove()` for explanation why this wrap_copy() call is safe.
1700 self.wrap_copy(
1701 self.to_physical_idx(index),
1702 self.to_physical_idx(index + 1),
1703 k,
1704 );
1705 self.buffer_write(self.to_physical_idx(index), value);
1706 self.len += 1;
1707 }
1708 } else {
1709 let old_head = self.head;
1710 self.head = self.wrap_sub(self.head, 1);
1711 unsafe {
1712 self.wrap_copy(old_head, self.head, index);
1713 self.buffer_write(self.to_physical_idx(index), value);
1714 self.len += 1;
1715 }
1716 }
1717
1718 Ok(())
1719 }
1720
1721 /// Removes and returns the element at `index` from the deque.
1722 /// Whichever end is closer to the removal point will be moved to make
1723 /// room, and all the affected elements will be moved to new positions.
1724 /// Returns `None` if `index` is out of bounds.
1725 ///
1726 /// Element at index 0 is the front of the queue.
1727 ///
1728 /// # Examples
1729 ///
1730 /// ```
1731 /// use rune::alloc::VecDeque;
1732 ///
1733 /// let mut buf = VecDeque::new();
1734 /// buf.try_push_back(1)?;
1735 /// buf.try_push_back(2)?;
1736 /// buf.try_push_back(3)?;
1737 /// assert_eq!(buf, [1, 2, 3]);
1738 ///
1739 /// assert_eq!(buf.remove(1), Some(2));
1740 /// assert_eq!(buf, [1, 3]);
1741 /// # Ok::<_, rune::alloc::Error>(())
1742 /// ```
1743 pub fn remove(&mut self, index: usize) -> Option<T> {
1744 if self.len <= index {
1745 return None;
1746 }
1747
1748 let wrapped_idx = self.to_physical_idx(index);
1749
1750 let elem = unsafe { Some(self.buffer_read(wrapped_idx)) };
1751
1752 let k = self.len - index - 1;
1753 // safety: due to the nature of the if-condition, whichever wrap_copy gets called,
1754 // its length argument will be at most `self.len / 2`, so there can't be more than
1755 // one overlapping area.
1756 if k < index {
1757 unsafe { self.wrap_copy(self.wrap_add(wrapped_idx, 1), wrapped_idx, k) };
1758 self.len -= 1;
1759 } else {
1760 let old_head = self.head;
1761 self.head = self.to_physical_idx(1);
1762 unsafe { self.wrap_copy(old_head, self.head, index) };
1763 self.len -= 1;
1764 }
1765
1766 elem
1767 }
1768
1769 /// Splits the deque into two at the given index.
1770 ///
1771 /// Returns a newly allocated `VecDeque`. `self` contains elements `[0, at)`,
1772 /// and the returned deque contains elements `[at, len)`.
1773 ///
1774 /// Note that the capacity of `self` does not change.
1775 ///
1776 /// Element at index 0 is the front of the queue.
1777 ///
1778 /// # Panics
1779 ///
1780 /// Panics if `at > len`.
1781 ///
1782 /// # Examples
1783 ///
1784 /// ```
1785 /// use rune::alloc::VecDeque;
1786 ///
1787 /// let mut buf: VecDeque<_> = [1, 2, 3].try_into()?;
1788 /// let buf2 = buf.try_split_off(1)?;
1789 /// assert_eq!(buf, [1]);
1790 /// assert_eq!(buf2, [2, 3]);
1791 /// # Ok::<_, rune::alloc::Error>(())
1792 /// ```
1793 #[inline]
1794 #[must_use = "use `.truncate()` if you don't need the other half"]
1795 pub fn try_split_off(&mut self, at: usize) -> Result<Self, Error>
1796 where
1797 A: Clone,
1798 {
1799 let len = self.len;
1800 assert!(at <= len, "`at` out of bounds");
1801
1802 let other_len = len - at;
1803 let mut other = VecDeque::try_with_capacity_in(other_len, self.allocator().clone())?;
1804
1805 unsafe {
1806 let (first_half, second_half) = self.as_slices();
1807
1808 let first_len = first_half.len();
1809 let second_len = second_half.len();
1810 if at < first_len {
1811 // `at` lies in the first half.
1812 let amount_in_first = first_len - at;
1813
1814 ptr::copy_nonoverlapping(first_half.as_ptr().add(at), other.ptr(), amount_in_first);
1815
1816 // just take all of the second half.
1817 ptr::copy_nonoverlapping(
1818 second_half.as_ptr(),
1819 other.ptr().add(amount_in_first),
1820 second_len,
1821 );
1822 } else {
1823 // `at` lies in the second half, need to factor in the elements we skipped
1824 // in the first half.
1825 let offset = at - first_len;
1826 let amount_in_second = second_len - offset;
1827 ptr::copy_nonoverlapping(
1828 second_half.as_ptr().add(offset),
1829 other.ptr(),
1830 amount_in_second,
1831 );
1832 }
1833 }
1834
1835 // Cleanup where the ends of the buffers are
1836 self.len = at;
1837 other.len = other_len;
1838
1839 Ok(other)
1840 }
1841
1842 /// Moves all the elements of `other` into `self`, leaving `other` empty.
1843 ///
1844 /// # Panics
1845 ///
1846 /// Panics if the new number of elements in self overflows a `usize`.
1847 ///
1848 /// # Examples
1849 ///
1850 /// ```
1851 /// use rune::alloc::VecDeque;
1852 ///
1853 /// let mut buf: VecDeque<_> = [1, 2].try_into()?;
1854 /// let mut buf2: VecDeque<_> = [3, 4].try_into()?;
1855 /// buf.try_append(&mut buf2)?;
1856 /// assert_eq!(buf, [1, 2, 3, 4]);
1857 /// assert!(buf2.is_empty());
1858 /// # Ok::<_, rune::alloc::Error>(())
1859 /// ```
1860 #[inline]
1861 pub fn try_append(&mut self, other: &mut Self) -> Result<(), Error> {
1862 if T::IS_ZST {
1863 self.len = self
1864 .len
1865 .checked_add(other.len)
1866 .ok_or(Error::CapacityOverflow)?;
1867 other.len = 0;
1868 other.head = 0;
1869 return Ok(());
1870 }
1871
1872 self.try_reserve(other.len)?;
1873
1874 unsafe {
1875 let (left, right) = other.as_slices();
1876 self.copy_slice(self.to_physical_idx(self.len), left);
1877 // no overflow, because self.capacity() >= old_cap + left.len() >= self.len + left.len()
1878 self.copy_slice(self.to_physical_idx(self.len + left.len()), right);
1879 }
1880
1881 // SAFETY: Update pointers after copying to avoid leaving doppelganger
1882 // in case of panics.
1883 self.len += other.len;
1884 // Now that we own its values, forget everything in `other`.
1885 other.len = 0;
1886 other.head = 0;
1887 Ok(())
1888 }
1889
1890 /// Retains only the elements specified by the predicate.
1891 ///
1892 /// In other words, remove all elements `e` for which `f(&e)` returns false.
1893 /// This method operates in place, visiting each element exactly once in the
1894 /// original order, and preserves the order of the retained elements.
1895 ///
1896 /// # Examples
1897 ///
1898 /// ```
1899 /// use rune::alloc::VecDeque;
1900 /// use rune::alloc::prelude::*;
1901 ///
1902 /// let mut buf = VecDeque::new();
1903 /// buf.try_extend(1..5)?;
1904 /// buf.retain(|&x| x % 2 == 0);
1905 /// assert_eq!(buf, [2, 4]);
1906 /// # Ok::<_, rune::alloc::Error>(())
1907 /// ```
1908 ///
1909 /// Because the elements are visited exactly once in the original order,
1910 /// external state may be used to decide which elements to keep.
1911 ///
1912 /// ```
1913 /// use rune::alloc::VecDeque;
1914 /// use rune::alloc::prelude::*;
1915 ///
1916 /// let mut buf = VecDeque::new();
1917 /// buf.try_extend(1..6)?;
1918 ///
1919 /// let keep = [false, true, true, false, true];
1920 /// let mut iter = keep.iter();
1921 /// buf.retain(|_| *iter.next().unwrap());
1922 /// assert_eq!(buf, [2, 3, 5]);
1923 /// # Ok::<_, rune::alloc::Error>(())
1924 /// ```
1925 pub fn retain<F>(&mut self, mut f: F)
1926 where
1927 F: FnMut(&T) -> bool,
1928 {
1929 self.retain_mut(|elem| f(elem));
1930 }
1931
1932 /// Retains only the elements specified by the predicate.
1933 ///
1934 /// In other words, remove all elements `e` for which `f(&e)` returns false.
1935 /// This method operates in place, visiting each element exactly once in the
1936 /// original order, and preserves the order of the retained elements.
1937 ///
1938 /// # Examples
1939 ///
1940 /// ```
1941 /// use rune::alloc::VecDeque;
1942 /// use rune::alloc::prelude::*;
1943 ///
1944 /// let mut buf = VecDeque::new();
1945 /// buf.try_extend(1..5)?;
1946 /// buf.retain_mut(|x| if *x % 2 == 0 {
1947 /// *x += 1;
1948 /// true
1949 /// } else {
1950 /// false
1951 /// });
1952 /// assert_eq!(buf, [3, 5]);
1953 /// # Ok::<_, rune::alloc::Error>(())
1954 /// ```
1955 pub fn retain_mut<F>(&mut self, mut f: F)
1956 where
1957 F: FnMut(&mut T) -> bool,
1958 {
1959 let len = self.len;
1960 let mut idx = 0;
1961 let mut cur = 0;
1962
1963 // Stage 1: All values are retained.
1964 while cur < len {
1965 if !f(&mut self[cur]) {
1966 cur += 1;
1967 break;
1968 }
1969 cur += 1;
1970 idx += 1;
1971 }
1972 // Stage 2: Swap retained value into current idx.
1973 while cur < len {
1974 if !f(&mut self[cur]) {
1975 cur += 1;
1976 continue;
1977 }
1978
1979 self.swap(idx, cur);
1980 cur += 1;
1981 idx += 1;
1982 }
1983 // Stage 3: Truncate all values after idx.
1984 if cur != idx {
1985 self.truncate(idx);
1986 }
1987 }
1988
1989 // Double the buffer size. This method is inline(never), so we expect it to only
1990 // be called in cold paths.
1991 // This may panic or abort
1992 #[inline(never)]
1993 fn try_grow(&mut self) -> Result<(), Error> {
1994 // Extend or possibly remove this assertion when valid use-cases for growing the
1995 // buffer without it being full emerge
1996 debug_assert!(self.is_full());
1997 let old_cap = self.capacity();
1998 self.buf.try_reserve_for_push(old_cap)?;
1999 unsafe {
2000 self.handle_capacity_increase(old_cap);
2001 }
2002 debug_assert!(!self.is_full());
2003 Ok(())
2004 }
2005
2006 /// Modifies the deque in-place so that `len()` is equal to `new_len`,
2007 /// either by removing excess elements from the back or by appending
2008 /// elements generated by calling `generator` to the back.
2009 ///
2010 /// # Examples
2011 ///
2012 /// ```
2013 /// use rune::alloc::VecDeque;
2014 ///
2015 /// let mut buf = VecDeque::new();
2016 /// buf.try_push_back(5)?;
2017 /// buf.try_push_back(10)?;
2018 /// buf.try_push_back(15)?;
2019 /// assert_eq!(buf, [5, 10, 15]);
2020 ///
2021 /// buf.try_resize_with(5, Default::default)?;
2022 /// assert_eq!(buf, [5, 10, 15, 0, 0]);
2023 ///
2024 /// buf.try_resize_with(2, || unreachable!())?;
2025 /// assert_eq!(buf, [5, 10]);
2026 ///
2027 /// let mut state = 100;
2028 /// buf.try_resize_with(5, || { state += 1; state })?;
2029 /// assert_eq!(buf, [5, 10, 101, 102, 103]);
2030 /// # Ok::<_, rune::alloc::Error>(())
2031 /// ```
2032 pub fn try_resize_with(
2033 &mut self,
2034 new_len: usize,
2035 mut generator: impl FnMut() -> T,
2036 ) -> Result<(), Error> {
2037 let len = self.len;
2038
2039 if new_len > len {
2040 for _ in 0..new_len - len {
2041 self.try_push_back(generator())?;
2042 }
2043 } else {
2044 self.truncate(new_len);
2045 }
2046
2047 Ok(())
2048 }
2049
2050 /// Rearranges the internal storage of this deque so it is one contiguous
2051 /// slice, which is then returned.
2052 ///
2053 /// This method does not allocate and does not change the order of the
2054 /// inserted elements. As it returns a mutable slice, this can be used to
2055 /// sort a deque.
2056 ///
2057 /// Once the internal storage is contiguous, the [`as_slices`] and
2058 /// [`as_mut_slices`] methods will return the entire contents of the
2059 /// deque in a single slice.
2060 ///
2061 /// [`as_slices`]: VecDeque::as_slices
2062 /// [`as_mut_slices`]: VecDeque::as_mut_slices
2063 ///
2064 /// # Examples
2065 ///
2066 /// Sorting the content of a deque.
2067 ///
2068 /// ```
2069 /// use rune::alloc::VecDeque;
2070 ///
2071 /// let mut buf = VecDeque::try_with_capacity(15)?;
2072 ///
2073 /// buf.try_push_back(2)?;
2074 /// buf.try_push_back(1)?;
2075 /// buf.try_push_front(3)?;
2076 ///
2077 /// // sorting the deque
2078 /// buf.make_contiguous().sort();
2079 /// assert_eq!(buf.as_slices(), (&[1, 2, 3] as &[_], &[] as &[_]));
2080 ///
2081 /// // sorting it in reverse order
2082 /// buf.make_contiguous().sort_by(|a, b| b.cmp(a));
2083 /// assert_eq!(buf.as_slices(), (&[3, 2, 1] as &[_], &[] as &[_]));
2084 /// # Ok::<_, rune::alloc::Error>(())
2085 /// ```
2086 ///
2087 /// Getting immutable access to the contiguous slice.
2088 ///
2089 /// ```rust
2090 /// use rune::alloc::VecDeque;
2091 ///
2092 /// let mut buf = VecDeque::new();
2093 ///
2094 /// buf.try_push_back(2)?;
2095 /// buf.try_push_back(1)?;
2096 /// buf.try_push_front(3)?;
2097 ///
2098 /// buf.make_contiguous();
2099 /// if let (slice, &[]) = buf.as_slices() {
2100 /// // we can now be sure that `slice` contains all elements of the deque,
2101 /// // while still having immutable access to `buf`.
2102 /// assert_eq!(buf.len(), slice.len());
2103 /// assert_eq!(slice, &[3, 2, 1] as &[_]);
2104 /// }
2105 /// # Ok::<_, rune::alloc::Error>(())
2106 /// ```
2107 pub fn make_contiguous(&mut self) -> &mut [T] {
2108 if T::IS_ZST {
2109 self.head = 0;
2110 }
2111
2112 if self.is_contiguous() {
2113 unsafe { return slice::from_raw_parts_mut(self.ptr().add(self.head), self.len) }
2114 }
2115
2116 let &mut Self { head, len, .. } = self;
2117 let ptr = self.ptr();
2118 let cap = self.capacity();
2119
2120 let free = cap - len;
2121 let head_len = cap - head;
2122 let tail = len - head_len;
2123 let tail_len = tail;
2124
2125 if free >= head_len {
2126 // there is enough free space to copy the head in one go,
2127 // this means that we first shift the tail backwards, and then
2128 // copy the head to the correct position.
2129 //
2130 // from: DEFGH....ABC
2131 // to: ABCDEFGH....
2132 unsafe {
2133 self.copy(0, head_len, tail_len);
2134 // ...DEFGH.ABC
2135 self.copy_nonoverlapping(head, 0, head_len);
2136 // ABCDEFGH....
2137 }
2138
2139 self.head = 0;
2140 } else if free >= tail_len {
2141 // there is enough free space to copy the tail in one go,
2142 // this means that we first shift the head forwards, and then
2143 // copy the tail to the correct position.
2144 //
2145 // from: FGH....ABCDE
2146 // to: ...ABCDEFGH.
2147 unsafe {
2148 self.copy(head, tail, head_len);
2149 // FGHABCDE....
2150 self.copy_nonoverlapping(0, tail + head_len, tail_len);
2151 // ...ABCDEFGH.
2152 }
2153
2154 self.head = tail;
2155 } else {
2156 // `free` is smaller than both `head_len` and `tail_len`.
2157 // the general algorithm for this first moves the slices
2158 // right next to each other and then uses `slice::rotate`
2159 // to rotate them into place:
2160 //
2161 // initially: HIJK..ABCDEFG
2162 // step 1: ..HIJKABCDEFG
2163 // step 2: ..ABCDEFGHIJK
2164 //
2165 // or:
2166 //
2167 // initially: FGHIJK..ABCDE
2168 // step 1: FGHIJKABCDE..
2169 // step 2: ABCDEFGHIJK..
2170
2171 // pick the shorter of the 2 slices to reduce the amount
2172 // of memory that needs to be moved around.
2173 if head_len > tail_len {
2174 // tail is shorter, so:
2175 // 1. copy tail forwards
2176 // 2. rotate used part of the buffer
2177 // 3. update head to point to the new beginning (which is just `free`)
2178
2179 unsafe {
2180 // if there is no free space in the buffer, then the slices are already
2181 // right next to each other and we don't need to move any memory.
2182 if free != 0 {
2183 // because we only move the tail forward as much as there's free space
2184 // behind it, we don't overwrite any elements of the head slice, and
2185 // the slices end up right next to each other.
2186 self.copy(0, free, tail_len);
2187 }
2188
2189 // We just copied the tail right next to the head slice,
2190 // so all of the elements in the range are initialized
2191 let slice = &mut *self.buffer_range(free..self.capacity());
2192
2193 // because the deque wasn't contiguous, we know that `tail_len < self.len == slice.len()`,
2194 // so this will never panic.
2195 slice.rotate_left(tail_len);
2196
2197 // the used part of the buffer now is `free..self.capacity()`, so set
2198 // `head` to the beginning of that range.
2199 self.head = free;
2200 }
2201 } else {
2202 // head is shorter so:
2203 // 1. copy head backwards
2204 // 2. rotate used part of the buffer
2205 // 3. update head to point to the new beginning (which is the beginning of the buffer)
2206
2207 unsafe {
2208 // if there is no free space in the buffer, then the slices are already
2209 // right next to each other and we don't need to move any memory.
2210 if free != 0 {
2211 // copy the head slice to lie right behind the tail slice.
2212 self.copy(self.head, tail_len, head_len);
2213 }
2214
2215 // because we copied the head slice so that both slices lie right
2216 // next to each other, all the elements in the range are initialized.
2217 let slice = &mut *self.buffer_range(0..self.len);
2218
2219 // because the deque wasn't contiguous, we know that `head_len < self.len == slice.len()`
2220 // so this will never panic.
2221 slice.rotate_right(head_len);
2222
2223 // the used part of the buffer now is `0..self.len`, so set
2224 // `head` to the beginning of that range.
2225 self.head = 0;
2226 }
2227 }
2228 }
2229
2230 unsafe { slice::from_raw_parts_mut(ptr.add(self.head), self.len) }
2231 }
2232
2233 /// Rotates the double-ended queue `mid` places to the left.
2234 ///
2235 /// Equivalently,
2236 /// - Rotates item `mid` into the first position.
2237 /// - Pops the first `mid` items and pushes them to the end.
2238 /// - Rotates `len() - mid` places to the right.
2239 ///
2240 /// # Panics
2241 ///
2242 /// If `mid` is greater than `len()`. Note that `mid == len()`
2243 /// does _not_ panic and is a no-op rotation.
2244 ///
2245 /// # Complexity
2246 ///
2247 /// Takes `*O*(min(mid, len() - mid))` time and no extra space.
2248 ///
2249 /// # Examples
2250 ///
2251 /// ```
2252 /// use rune::alloc::VecDeque;
2253 /// use rune::alloc::prelude::*;
2254 ///
2255 /// let mut buf: VecDeque<_> = (0..10).try_collect()?;
2256 ///
2257 /// buf.rotate_left(3);
2258 /// assert_eq!(buf, [3, 4, 5, 6, 7, 8, 9, 0, 1, 2]);
2259 ///
2260 /// for i in 1..10 {
2261 /// assert_eq!(i * 3 % 10, buf[0]);
2262 /// buf.rotate_left(3);
2263 /// }
2264 /// assert_eq!(buf, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
2265 /// # Ok::<_, rune::alloc::Error>(())
2266 /// ```
2267 pub fn rotate_left(&mut self, mid: usize) {
2268 assert!(mid <= self.len());
2269 let k = self.len - mid;
2270 if mid <= k {
2271 unsafe { self.rotate_left_inner(mid) }
2272 } else {
2273 unsafe { self.rotate_right_inner(k) }
2274 }
2275 }
2276
2277 /// Rotates the double-ended queue `k` places to the right.
2278 ///
2279 /// Equivalently,
2280 /// - Rotates the first item into position `k`.
2281 /// - Pops the last `k` items and pushes them to the front.
2282 /// - Rotates `len() - k` places to the left.
2283 ///
2284 /// # Panics
2285 ///
2286 /// If `k` is greater than `len()`. Note that `k == len()`
2287 /// does _not_ panic and is a no-op rotation.
2288 ///
2289 /// # Complexity
2290 ///
2291 /// Takes `*O*(min(k, len() - k))` time and no extra space.
2292 ///
2293 /// # Examples
2294 ///
2295 /// ```
2296 /// use rune::alloc::VecDeque;
2297 /// use rune::alloc::prelude::*;
2298 ///
2299 /// let mut buf: VecDeque<_> = (0..10).try_collect()?;
2300 ///
2301 /// buf.rotate_right(3);
2302 /// assert_eq!(buf, [7, 8, 9, 0, 1, 2, 3, 4, 5, 6]);
2303 ///
2304 /// for i in 1..10 {
2305 /// assert_eq!(0, buf[i * 3 % 10]);
2306 /// buf.rotate_right(3);
2307 /// }
2308 /// assert_eq!(buf, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
2309 /// # Ok::<_, rune::alloc::Error>(())
2310 /// ```
2311 pub fn rotate_right(&mut self, k: usize) {
2312 assert!(k <= self.len());
2313 let mid = self.len - k;
2314 if k <= mid {
2315 unsafe { self.rotate_right_inner(k) }
2316 } else {
2317 unsafe { self.rotate_left_inner(mid) }
2318 }
2319 }
2320
2321 // SAFETY: the following two methods require that the rotation amount
2322 // be less than half the length of the deque.
2323 //
2324 // `wrap_copy` requires that `min(x, capacity() - x) + copy_len <= capacity()`,
2325 // but then `min` is never more than half the capacity, regardless of x,
2326 // so it's sound to call here because we're calling with something
2327 // less than half the length, which is never above half the capacity.
2328
2329 unsafe fn rotate_left_inner(&mut self, mid: usize) {
2330 debug_assert!(mid * 2 <= self.len());
2331 unsafe {
2332 self.wrap_copy(self.head, self.to_physical_idx(self.len), mid);
2333 }
2334 self.head = self.to_physical_idx(mid);
2335 }
2336
2337 unsafe fn rotate_right_inner(&mut self, k: usize) {
2338 debug_assert!(k * 2 <= self.len());
2339 self.head = self.wrap_sub(self.head, k);
2340 unsafe {
2341 self.wrap_copy(self.to_physical_idx(self.len), self.head, k);
2342 }
2343 }
2344
2345 /// Binary searches this `VecDeque` for a given element.
2346 /// If the `VecDeque` is not sorted, the returned result is unspecified and
2347 /// meaningless.
2348 ///
2349 /// If the value is found then [`Result::Ok`] is returned, containing the
2350 /// index of the matching element. If there are multiple matches, then any
2351 /// one of the matches could be returned. If the value is not found then
2352 /// [`Result::Err`] is returned, containing the index where a matching
2353 /// element could be inserted while maintaining sorted order.
2354 ///
2355 /// See also [`binary_search_by`], [`binary_search_by_key`], and [`partition_point`].
2356 ///
2357 /// [`binary_search_by`]: VecDeque::binary_search_by
2358 /// [`binary_search_by_key`]: VecDeque::binary_search_by_key
2359 /// [`partition_point`]: VecDeque::partition_point
2360 ///
2361 /// # Examples
2362 ///
2363 /// Looks up a series of four elements. The first is found, with a
2364 /// uniquely determined position; the second and third are not
2365 /// found; the fourth could match any position in `[1, 4]`.
2366 ///
2367 /// ```
2368 /// use rune::alloc::VecDeque;
2369 ///
2370 /// let deque: VecDeque<_> = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].try_into()?;
2371 ///
2372 /// assert_eq!(deque.binary_search(&13), Ok(9));
2373 /// assert_eq!(deque.binary_search(&4), Err(7));
2374 /// assert_eq!(deque.binary_search(&100), Err(13));
2375 /// let r = deque.binary_search(&1);
2376 /// assert!(matches!(r, Ok(1..=4)));
2377 /// # Ok::<_, rune::alloc::Error>(())
2378 /// ```
2379 ///
2380 /// If you want to insert an item to a sorted deque, while maintaining
2381 /// sort order, consider using [`partition_point`]:
2382 ///
2383 /// ```
2384 /// use rune::alloc::VecDeque;
2385 ///
2386 /// let mut deque: VecDeque<_> = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].try_into()?;
2387 /// let num = 42;
2388 /// let idx = deque.partition_point(|&x| x < num);
2389 /// // The above is equivalent to `let idx = deque.binary_search(&num).unwrap_or_else(|x| x);`
2390 /// deque.try_insert(idx, num)?;
2391 /// assert_eq!(deque, &[0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
2392 /// # Ok::<_, rune::alloc::Error>(())
2393 /// ```
2394 #[inline]
2395 pub fn binary_search(&self, x: &T) -> Result<usize, usize>
2396 where
2397 T: Ord,
2398 {
2399 self.binary_search_by(|e| e.cmp(x))
2400 }
2401
2402 /// Binary searches this `VecDeque` with a comparator function.
2403 ///
2404 /// The comparator function should return an order code that indicates
2405 /// whether its argument is `Less`, `Equal` or `Greater` the desired
2406 /// target.
2407 /// If the `VecDeque` is not sorted or if the comparator function does not
2408 /// implement an order consistent with the sort order of the underlying
2409 /// `VecDeque`, the returned result is unspecified and meaningless.
2410 ///
2411 /// If the value is found then [`Result::Ok`] is returned, containing the
2412 /// index of the matching element. If there are multiple matches, then any
2413 /// one of the matches could be returned. If the value is not found then
2414 /// [`Result::Err`] is returned, containing the index where a matching
2415 /// element could be inserted while maintaining sorted order.
2416 ///
2417 /// See also [`binary_search`], [`binary_search_by_key`], and [`partition_point`].
2418 ///
2419 /// [`binary_search`]: VecDeque::binary_search
2420 /// [`binary_search_by_key`]: VecDeque::binary_search_by_key
2421 /// [`partition_point`]: VecDeque::partition_point
2422 ///
2423 /// # Examples
2424 ///
2425 /// Looks up a series of four elements. The first is found, with a
2426 /// uniquely determined position; the second and third are not
2427 /// found; the fourth could match any position in `[1, 4]`.
2428 ///
2429 /// ```
2430 /// use rune::alloc::VecDeque;
2431 ///
2432 /// let deque: VecDeque<_> = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].try_into()?;
2433 ///
2434 /// assert_eq!(deque.binary_search_by(|x| x.cmp(&13)), Ok(9));
2435 /// assert_eq!(deque.binary_search_by(|x| x.cmp(&4)), Err(7));
2436 /// assert_eq!(deque.binary_search_by(|x| x.cmp(&100)), Err(13));
2437 /// let r = deque.binary_search_by(|x| x.cmp(&1));
2438 /// assert!(matches!(r, Ok(1..=4)));
2439 /// # Ok::<_, rune::alloc::Error>(())
2440 /// ```
2441 pub fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result<usize, usize>
2442 where
2443 F: FnMut(&'a T) -> Ordering,
2444 {
2445 let (front, back) = self.as_slices();
2446 let cmp_back = back.first().map(|elem| f(elem));
2447
2448 if let Some(Ordering::Equal) = cmp_back {
2449 Ok(front.len())
2450 } else if let Some(Ordering::Less) = cmp_back {
2451 back.binary_search_by(f)
2452 .map(|idx| idx + front.len())
2453 .map_err(|idx| idx + front.len())
2454 } else {
2455 front.binary_search_by(f)
2456 }
2457 }
2458
2459 /// Binary searches this `VecDeque` with a key extraction function.
2460 ///
2461 /// Assumes that the deque is sorted by the key, for instance with
2462 /// [`make_contiguous().sort_by_key()`] using the same key extraction function.
2463 /// If the deque is not sorted by the key, the returned result is
2464 /// unspecified and meaningless.
2465 ///
2466 /// If the value is found then [`Result::Ok`] is returned, containing the
2467 /// index of the matching element. If there are multiple matches, then any
2468 /// one of the matches could be returned. If the value is not found then
2469 /// [`Result::Err`] is returned, containing the index where a matching
2470 /// element could be inserted while maintaining sorted order.
2471 ///
2472 /// See also [`binary_search`], [`binary_search_by`], and [`partition_point`].
2473 ///
2474 /// [`make_contiguous().sort_by_key()`]: VecDeque::make_contiguous
2475 /// [`binary_search`]: VecDeque::binary_search
2476 /// [`binary_search_by`]: VecDeque::binary_search_by
2477 /// [`partition_point`]: VecDeque::partition_point
2478 ///
2479 /// # Examples
2480 ///
2481 /// Looks up a series of four elements in a slice of pairs sorted by
2482 /// their second elements. The first is found, with a uniquely
2483 /// determined position; the second and third are not found; the
2484 /// fourth could match any position in `[1, 4]`.
2485 ///
2486 /// ```
2487 /// use rune::alloc::VecDeque;
2488 ///
2489 /// let deque: VecDeque<_> = [(0, 0), (2, 1), (4, 1), (5, 1),
2490 /// (3, 1), (1, 2), (2, 3), (4, 5), (5, 8), (3, 13),
2491 /// (1, 21), (2, 34), (4, 55)].try_into()?;
2492 ///
2493 /// assert_eq!(deque.binary_search_by_key(&13, |&(a, b)| b), Ok(9));
2494 /// assert_eq!(deque.binary_search_by_key(&4, |&(a, b)| b), Err(7));
2495 /// assert_eq!(deque.binary_search_by_key(&100, |&(a, b)| b), Err(13));
2496 /// let r = deque.binary_search_by_key(&1, |&(a, b)| b);
2497 /// assert!(matches!(r, Ok(1..=4)));
2498 /// # Ok::<_, rune::alloc::Error>(())
2499 /// ```
2500 #[inline]
2501 pub fn binary_search_by_key<'a, B, F>(&'a self, b: &B, mut f: F) -> Result<usize, usize>
2502 where
2503 F: FnMut(&'a T) -> B,
2504 B: Ord,
2505 {
2506 self.binary_search_by(|k| f(k).cmp(b))
2507 }
2508
2509 /// Returns the index of the partition point according to the given predicate
2510 /// (the index of the first element of the second partition).
2511 ///
2512 /// The deque is assumed to be partitioned according to the given predicate.
2513 /// This means that all elements for which the predicate returns true are at the start of the deque
2514 /// and all elements for which the predicate returns false are at the end.
2515 /// For example, `[7, 15, 3, 5, 4, 12, 6]` is partitioned under the predicate `x % 2 != 0`
2516 /// (all odd numbers are at the start, all even at the end).
2517 ///
2518 /// If the deque is not partitioned, the returned result is unspecified and meaningless,
2519 /// as this method performs a kind of binary search.
2520 ///
2521 /// See also [`binary_search`], [`binary_search_by`], and [`binary_search_by_key`].
2522 ///
2523 /// [`binary_search`]: VecDeque::binary_search
2524 /// [`binary_search_by`]: VecDeque::binary_search_by
2525 /// [`binary_search_by_key`]: VecDeque::binary_search_by_key
2526 ///
2527 /// # Examples
2528 ///
2529 /// ```
2530 /// use rune::alloc::VecDeque;
2531 ///
2532 /// let deque: VecDeque<_> = [1, 2, 3, 3, 5, 6, 7].try_into()?;
2533 /// let i = deque.partition_point(|&x| x < 5);
2534 ///
2535 /// assert_eq!(i, 4);
2536 /// assert!(deque.iter().take(i).all(|&x| x < 5));
2537 /// assert!(deque.iter().skip(i).all(|&x| !(x < 5)));
2538 /// # Ok::<_, rune::alloc::Error>(())
2539 /// ```
2540 ///
2541 /// If you want to insert an item to a sorted deque, while maintaining
2542 /// sort order:
2543 ///
2544 /// ```
2545 /// use rune::alloc::VecDeque;
2546 ///
2547 /// let mut deque: VecDeque<_> = [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55].try_into()?;
2548 /// let num = 42;
2549 /// let idx = deque.partition_point(|&x| x < num);
2550 /// deque.try_insert(idx, num)?;
2551 /// assert_eq!(deque, &[0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]);
2552 /// # Ok::<_, rune::alloc::Error>(())
2553 /// ```
2554 pub fn partition_point<P>(&self, mut pred: P) -> usize
2555 where
2556 P: FnMut(&T) -> bool,
2557 {
2558 let (front, back) = self.as_slices();
2559
2560 if let Some(true) = back.first().map(|v| pred(v)) {
2561 back.partition_point(pred) + front.len()
2562 } else {
2563 front.partition_point(pred)
2564 }
2565 }
2566}
2567
2568impl<T, A> VecDeque<T, A>
2569where
2570 T: TryClone,
2571 A: Allocator,
2572{
2573 /// Modifies the deque in-place so that `len()` is equal to new_len,
2574 /// either by removing excess elements from the back or by appending clones of `value`
2575 /// to the back.
2576 ///
2577 /// # Examples
2578 ///
2579 /// ```
2580 /// use rune::alloc::VecDeque;
2581 ///
2582 /// let mut buf = VecDeque::new();
2583 /// buf.try_push_back(5)?;
2584 /// buf.try_push_back(10)?;
2585 /// buf.try_push_back(15)?;
2586 /// assert_eq!(buf, [5, 10, 15]);
2587 ///
2588 /// buf.try_resize(2, 0)?;
2589 /// assert_eq!(buf, [5, 10]);
2590 ///
2591 /// buf.try_resize(5, 20)?;
2592 /// assert_eq!(buf, [5, 10, 20, 20, 20]);
2593 /// # Ok::<_, rune::alloc::Error>(())
2594 /// ```
2595 pub fn try_resize(&mut self, new_len: usize, value: T) -> Result<(), Error> {
2596 if new_len > self.len() {
2597 let extra = new_len - self.len();
2598
2599 for _ in 0..extra {
2600 self.try_push_back(value.try_clone()?)?;
2601 }
2602 } else {
2603 self.truncate(new_len);
2604 }
2605
2606 Ok(())
2607 }
2608}
2609
2610/// Returns the index in the underlying buffer for a given logical element index.
2611#[inline]
2612fn wrap_index(logical_index: usize, capacity: usize) -> usize {
2613 debug_assert!(
2614 (logical_index == 0 && capacity == 0)
2615 || logical_index < capacity
2616 || (logical_index - capacity) < capacity
2617 );
2618 if logical_index >= capacity {
2619 logical_index - capacity
2620 } else {
2621 logical_index
2622 }
2623}
2624
2625impl<T, A> PartialEq for VecDeque<T, A>
2626where
2627 T: PartialEq,
2628 A: Allocator,
2629{
2630 fn eq(&self, other: &Self) -> bool {
2631 if self.len != other.len() {
2632 return false;
2633 }
2634 let (sa, sb) = self.as_slices();
2635 let (oa, ob) = other.as_slices();
2636 if sa.len() == oa.len() {
2637 sa == oa && sb == ob
2638 } else if sa.len() < oa.len() {
2639 // Always divisible in three sections, for example:
2640 // self: [a b c|d e f]
2641 // other: [0 1 2 3|4 5]
2642 // front = 3, mid = 1,
2643 // [a b c] == [0 1 2] && [d] == [3] && [e f] == [4 5]
2644 let front = sa.len();
2645 let mid = oa.len() - front;
2646
2647 let (oa_front, oa_mid) = oa.split_at(front);
2648 let (sb_mid, sb_back) = sb.split_at(mid);
2649 debug_assert_eq!(sa.len(), oa_front.len());
2650 debug_assert_eq!(sb_mid.len(), oa_mid.len());
2651 debug_assert_eq!(sb_back.len(), ob.len());
2652 sa == oa_front && sb_mid == oa_mid && sb_back == ob
2653 } else {
2654 let front = oa.len();
2655 let mid = sa.len() - front;
2656
2657 let (sa_front, sa_mid) = sa.split_at(front);
2658 let (ob_mid, ob_back) = ob.split_at(mid);
2659 debug_assert_eq!(sa_front.len(), oa.len());
2660 debug_assert_eq!(sa_mid.len(), ob_mid.len());
2661 debug_assert_eq!(sb.len(), ob_back.len());
2662 sa_front == oa && sa_mid == ob_mid && sb == ob_back
2663 }
2664 }
2665}
2666
2667impl<T, A> Eq for VecDeque<T, A>
2668where
2669 T: Eq,
2670 A: Allocator,
2671{
2672}
2673
2674__impl_slice_eq1! { [] VecDeque<T, A>, Vec<U, A>, }
2675__impl_slice_eq1! { [] VecDeque<T, A>, &[U], }
2676__impl_slice_eq1! { [] VecDeque<T, A>, &mut [U], }
2677__impl_slice_eq1! { [const N: usize] VecDeque<T, A>, [U; N], }
2678__impl_slice_eq1! { [const N: usize] VecDeque<T, A>, &[U; N], }
2679__impl_slice_eq1! { [const N: usize] VecDeque<T, A>, &mut [U; N], }
2680
2681impl<T, A> PartialOrd for VecDeque<T, A>
2682where
2683 T: PartialOrd,
2684 A: Allocator,
2685{
2686 #[inline]
2687 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2688 self.iter().partial_cmp(other.iter())
2689 }
2690}
2691
2692impl<T, A> Ord for VecDeque<T, A>
2693where
2694 T: Ord,
2695 A: Allocator,
2696{
2697 #[inline]
2698 fn cmp(&self, other: &Self) -> Ordering {
2699 self.iter().cmp(other.iter())
2700 }
2701}
2702
2703impl<T, A> Hash for VecDeque<T, A>
2704where
2705 T: Hash,
2706 A: Allocator,
2707{
2708 #[inline]
2709 fn hash<H>(&self, state: &mut H)
2710 where
2711 H: Hasher,
2712 {
2713 state.write_usize(self.len);
2714 // It's not possible to use Hash::hash_slice on slices
2715 // returned by as_slices method as their length can vary
2716 // in otherwise identical deques.
2717 //
2718 // Hasher only guarantees equivalence for the exact same
2719 // set of calls to its methods.
2720 self.iter().for_each(|elem| elem.hash(state));
2721 }
2722}
2723
2724impl<T, A> Index<usize> for VecDeque<T, A>
2725where
2726 A: Allocator,
2727{
2728 type Output = T;
2729
2730 #[inline]
2731 fn index(&self, index: usize) -> &T {
2732 self.get(index).expect("Out of bounds access")
2733 }
2734}
2735
2736impl<T, A> IndexMut<usize> for VecDeque<T, A>
2737where
2738 A: Allocator,
2739{
2740 #[inline]
2741 fn index_mut(&mut self, index: usize) -> &mut T {
2742 self.get_mut(index).expect("Out of bounds access")
2743 }
2744}
2745
2746impl<T, A> IntoIterator for VecDeque<T, A>
2747where
2748 A: Allocator,
2749{
2750 type Item = T;
2751 type IntoIter = IntoIter<T, A>;
2752
2753 /// Consumes the deque into a front-to-back iterator yielding elements by
2754 /// value.
2755 fn into_iter(self) -> IntoIter<T, A> {
2756 IntoIter::new(self)
2757 }
2758}
2759
2760impl<'a, T, A> IntoIterator for &'a VecDeque<T, A>
2761where
2762 A: Allocator,
2763{
2764 type Item = &'a T;
2765 type IntoIter = Iter<'a, T>;
2766
2767 fn into_iter(self) -> Iter<'a, T> {
2768 self.iter()
2769 }
2770}
2771
2772impl<'a, T, A> IntoIterator for &'a mut VecDeque<T, A>
2773where
2774 A: Allocator,
2775{
2776 type Item = &'a mut T;
2777 type IntoIter = IterMut<'a, T>;
2778
2779 fn into_iter(self) -> IterMut<'a, T> {
2780 self.iter_mut()
2781 }
2782}
2783
2784impl<T, A> fmt::Debug for VecDeque<T, A>
2785where
2786 T: fmt::Debug,
2787 A: Allocator,
2788{
2789 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2790 f.debug_list().entries(self.iter()).finish()
2791 }
2792}
2793
2794impl<T, A> From<Vec<T, A>> for VecDeque<T, A>
2795where
2796 A: Allocator,
2797{
2798 /// Turn a [`Vec<T>`] into a [`VecDeque<T>`].
2799 ///
2800 /// [`Vec<T>`]: crate::Vec
2801 /// [`VecDeque<T>`]: crate::VecDeque
2802 ///
2803 /// This conversion is guaranteed to run in *O*(1) time
2804 /// and to not re-allocate the `Vec`'s buffer or allocate
2805 /// any additional memory.
2806 #[inline]
2807 fn from(other: Vec<T, A>) -> Self {
2808 let (buf, len) = other.into_raw_vec();
2809 Self { head: 0, len, buf }
2810 }
2811}
2812
2813impl<T, A> From<VecDeque<T, A>> for Vec<T, A>
2814where
2815 A: Allocator,
2816{
2817 /// Turn a [`VecDeque<T>`] into a [`Vec<T>`].
2818 ///
2819 /// [`Vec<T>`]: crate::Vec
2820 /// [`VecDeque<T>`]: crate::VecDeque
2821 ///
2822 /// This never needs to re-allocate, but does need to do *O*(*n*) data movement if
2823 /// the circular buffer doesn't happen to be at the beginning of the allocation.
2824 ///
2825 /// # Examples
2826 ///
2827 /// ```
2828 /// use rune::alloc::{VecDeque, Vec};
2829 /// use rune::alloc::prelude::*;
2830 ///
2831 /// // This one is *O*(1).
2832 /// let deque: VecDeque<_> = (1..5).try_collect()?;
2833 /// let ptr = deque.as_slices().0.as_ptr();
2834 /// let vec = Vec::from(deque);
2835 /// assert_eq!(vec, [1, 2, 3, 4]);
2836 /// assert_eq!(vec.as_ptr(), ptr);
2837 ///
2838 /// // This one needs data rearranging.
2839 /// let mut deque: VecDeque<_> = (1..5).try_collect()?;
2840 /// deque.try_push_front(9)?;
2841 /// deque.try_push_front(8)?;
2842 /// let ptr = deque.as_slices().1.as_ptr();
2843 /// let vec = Vec::from(deque);
2844 /// assert_eq!(vec, [8, 9, 1, 2, 3, 4]);
2845 /// assert_eq!(vec.as_ptr(), ptr);
2846 /// # Ok::<_, rune::alloc::Error>(())
2847 /// ```
2848 fn from(mut other: VecDeque<T, A>) -> Self {
2849 other.make_contiguous();
2850
2851 unsafe {
2852 let other = ManuallyDrop::new(other);
2853 let buf = other.buf.ptr();
2854 let len = other.len();
2855 let cap = other.capacity();
2856 let alloc = ptr::read(other.allocator());
2857
2858 if other.head != 0 {
2859 ptr::copy(buf.add(other.head), buf, len);
2860 }
2861 Vec::from_raw_parts_in(buf, len, cap, alloc)
2862 }
2863 }
2864}
2865
2866impl<T, const N: usize> TryFrom<[T; N]> for VecDeque<T> {
2867 type Error = Error;
2868
2869 /// Converts a `[T; N]` into a `VecDeque<T>`.
2870 ///
2871 /// ```
2872 /// use rune::alloc::VecDeque;
2873 ///
2874 /// let deq1 = VecDeque::try_from([1, 2, 3, 4])?;
2875 /// let deq2: VecDeque<_> = [1, 2, 3, 4].try_into()?;
2876 /// assert_eq!(deq1, deq2);
2877 /// # Ok::<_, rune::alloc::Error>(())
2878 /// ```
2879 fn try_from(arr: [T; N]) -> Result<Self, Self::Error> {
2880 Ok(VecDeque::from(Vec::try_from(arr)?))
2881 }
2882}
2883
2884impl<T, A> TryFromIteratorIn<T, A> for VecDeque<T, A>
2885where
2886 A: Allocator,
2887{
2888 fn try_from_iter_in<I>(iter: I, alloc: A) -> Result<Self, Error>
2889 where
2890 I: IntoIterator<Item = T>,
2891 {
2892 let mut this = VecDeque::new_in(alloc);
2893 this.try_extend(iter)?;
2894 Ok(this)
2895 }
2896}
2897
2898impl<T, A> TryExtend<T> for VecDeque<T, A>
2899where
2900 A: Allocator,
2901{
2902 #[inline]
2903 fn try_extend<I: IntoIterator<Item = T>>(&mut self, iter: I) -> Result<(), Error> {
2904 for value in iter {
2905 self.try_push_back(value)?;
2906 }
2907
2908 Ok(())
2909 }
2910}