Skip to main content

heapless/
deque.rs

1//! A fixed capacity double-ended queue.
2//!
3//! # Examples
4//!
5//! ```
6//! use heapless::Deque;
7//!
8//! // A deque with a fixed capacity of 8 elements allocated on the stack
9//! let mut deque = Deque::<_, 8>::new();
10//!
11//! // You can use it as a good old FIFO queue.
12//! deque.push_back(1);
13//! deque.push_back(2);
14//! assert_eq!(deque.len(), 2);
15//!
16//! assert_eq!(deque.pop_front(), Some(1));
17//! assert_eq!(deque.pop_front(), Some(2));
18//! assert_eq!(deque.len(), 0);
19//!
20//! // Deque is double-ended, you can push and pop from the front and back.
21//! deque.push_back(1);
22//! deque.push_front(2);
23//! deque.push_back(3);
24//! deque.push_front(4);
25//! assert_eq!(deque.pop_front(), Some(4));
26//! assert_eq!(deque.pop_front(), Some(2));
27//! assert_eq!(deque.pop_front(), Some(1));
28//! assert_eq!(deque.pop_front(), Some(3));
29//!
30//! // You can iterate it, yielding all the elements front-to-back.
31//! for x in &deque {
32//!     println!("{}", x);
33//! }
34//! ```
35
36use crate::{
37    vec::{OwnedVecStorage, VecStorage, VecStorageInner, ViewVecStorage},
38    CapacityError,
39};
40use core::{
41    cmp::Ordering,
42    fmt,
43    iter::FusedIterator,
44    marker::PhantomData,
45    mem::{ManuallyDrop, MaybeUninit},
46    ptr, slice,
47};
48
49#[cfg(feature = "zeroize")]
50use zeroize::Zeroize;
51
52/// Base struct for [`Deque`] and [`DequeView`], generic over the [`VecStorage`].
53///
54/// In most cases you should use [`Deque`] or [`DequeView`] directly. Only use this
55/// struct if you want to write code that's generic over both.
56#[cfg_attr(feature = "zeroize", derive(Zeroize))]
57pub struct DequeInner<T, S: VecStorage<T> + ?Sized> {
58    // This phantomdata is required because otherwise rustc thinks that `T` is not used
59    phantom: PhantomData<T>,
60    /// Front index. Always 0..=(N-1)
61    front: usize,
62    /// Back index. Always 0..=(N-1).
63    back: usize,
64
65    /// Used to distinguish "empty" and "full" cases when `front == back`.
66    /// May only be `true` if `front == back`, always `false` otherwise.
67    full: bool,
68    buffer: S,
69}
70
71/// A fixed capacity double-ended queue.
72///
73/// # Examples
74///
75/// ```
76/// use heapless::Deque;
77///
78/// // A deque with a fixed capacity of 8 elements allocated on the stack
79/// let mut deque = Deque::<_, 8>::new();
80///
81/// // You can use it as a good old FIFO queue.
82/// deque.push_back(1);
83/// deque.push_back(2);
84/// assert_eq!(deque.len(), 2);
85///
86/// assert_eq!(deque.pop_front(), Some(1));
87/// assert_eq!(deque.pop_front(), Some(2));
88/// assert_eq!(deque.len(), 0);
89///
90/// // Deque is double-ended, you can push and pop from the front and back.
91/// deque.push_back(1);
92/// deque.push_front(2);
93/// deque.push_back(3);
94/// deque.push_front(4);
95/// assert_eq!(deque.pop_front(), Some(4));
96/// assert_eq!(deque.pop_front(), Some(2));
97/// assert_eq!(deque.pop_front(), Some(1));
98/// assert_eq!(deque.pop_front(), Some(3));
99///
100/// // You can iterate it, yielding all the elements front-to-back.
101/// for x in &deque {
102///     println!("{}", x);
103/// }
104/// ```
105pub type Deque<T, const N: usize> = DequeInner<T, OwnedVecStorage<T, N>>;
106
107/// A double-ended queue with dynamic capacity.
108///
109/// # Examples
110///
111/// ```
112/// use heapless::deque::{Deque, DequeView};
113///
114/// // A deque with a fixed capacity of 8 elements allocated on the stack
115/// let mut deque_buf = Deque::<_, 8>::new();
116///
117/// // A DequeView can be obtained through unsized coercion of a `Deque`
118/// let deque: &mut DequeView<_> = &mut deque_buf;
119///
120/// // You can use it as a good old FIFO queue.
121/// deque.push_back(1);
122/// deque.push_back(2);
123/// assert_eq!(deque.storage_len(), 2);
124///
125/// assert_eq!(deque.pop_front(), Some(1));
126/// assert_eq!(deque.pop_front(), Some(2));
127/// assert_eq!(deque.storage_len(), 0);
128///
129/// // DequeView is double-ended, you can push and pop from the front and back.
130/// deque.push_back(1);
131/// deque.push_front(2);
132/// deque.push_back(3);
133/// deque.push_front(4);
134/// assert_eq!(deque.pop_front(), Some(4));
135/// assert_eq!(deque.pop_front(), Some(2));
136/// assert_eq!(deque.pop_front(), Some(1));
137/// assert_eq!(deque.pop_front(), Some(3));
138///
139/// // You can iterate it, yielding all the elements front-to-back.
140/// for x in deque {
141///     println!("{}", x);
142/// }
143/// ```
144pub type DequeView<T> = DequeInner<T, ViewVecStorage<T>>;
145
146impl<T, const N: usize> Deque<T, N> {
147    const INIT: MaybeUninit<T> = MaybeUninit::uninit();
148
149    /// Constructs a new, empty deque with a fixed capacity of `N`
150    ///
151    /// # Examples
152    ///
153    /// ```
154    /// use heapless::Deque;
155    ///
156    /// // allocate the deque on the stack
157    /// let mut x: Deque<u8, 16> = Deque::new();
158    ///
159    /// // allocate the deque in a static variable
160    /// static mut X: Deque<u8, 16> = Deque::new();
161    /// ```
162    pub const fn new() -> Self {
163        const {
164            assert!(N > 0);
165        }
166
167        Self {
168            phantom: PhantomData,
169            buffer: VecStorageInner {
170                buffer: [Self::INIT; N],
171            },
172            front: 0,
173            back: 0,
174            full: false,
175        }
176    }
177
178    /// Returns the maximum number of elements the deque can hold.
179    ///
180    /// This method is not available on a `DequeView`, use
181    /// [`storage_capacity`](DequeInner::storage_capacity) instead.
182    pub const fn capacity(&self) -> usize {
183        N
184    }
185
186    /// Returns the number of elements currently in the deque.
187    ///
188    /// This method is not available on a `DequeView`, use [`storage_len`](DequeInner::storage_len)
189    /// instead.
190    pub const fn len(&self) -> usize {
191        if self.full {
192            N
193        } else if self.back < self.front {
194            self.back + N - self.front
195        } else {
196            self.back - self.front
197        }
198    }
199}
200
201impl<T, S: VecStorage<T> + ?Sized> DequeInner<T, S> {
202    /// Get a reference to the `Deque`, erasing the `N` const-generic.
203    pub fn as_view(&self) -> &DequeView<T> {
204        S::as_deque_view(self)
205    }
206
207    /// Get a mutable reference to the `Deque`, erasing the `N` const-generic.
208    pub fn as_mut_view(&mut self) -> &mut DequeView<T> {
209        S::as_deque_view_mut(self)
210    }
211
212    /// Returns the maximum number of elements the deque can hold.
213    pub fn storage_capacity(&self) -> usize {
214        self.buffer.borrow().len()
215    }
216
217    fn increment(&self, i: usize) -> usize {
218        if i + 1 == self.storage_capacity() {
219            0
220        } else {
221            i + 1
222        }
223    }
224
225    fn decrement(&self, i: usize) -> usize {
226        if i == 0 {
227            self.storage_capacity() - 1
228        } else {
229            i - 1
230        }
231    }
232
233    /// Returns the number of elements currently in the deque.
234    pub fn storage_len(&self) -> usize {
235        if self.full {
236            self.storage_capacity()
237        } else if self.back < self.front {
238            self.back + self.storage_capacity() - self.front
239        } else {
240            self.back - self.front
241        }
242    }
243
244    /// Clears the deque, removing all values.
245    pub fn clear(&mut self) {
246        struct Guard<'a, T, S: VecStorage<T> + ?Sized>(&'a mut DequeInner<T, S>);
247        impl<'a, T, S: VecStorage<T> + ?Sized> Drop for Guard<'a, T, S> {
248            fn drop(&mut self) {
249                self.0.front = 0;
250                self.0.back = 0;
251                self.0.full = false;
252            }
253        }
254        let this = Guard(self);
255        // SAFETY: Guard will be dropped and lead to a consistent empty state even in the case of a
256        // panic leading to unwinding during the dropping of an item
257        unsafe { this.0.drop_contents() }
258    }
259
260    /// Drop all items in the `Deque`, leaving the state `back/front/full` unmodified.
261    ///
262    /// safety: leaves the `Deque` in an inconsistent state, so can cause duplicate drops.
263    unsafe fn drop_contents(&mut self) {
264        // We drop each element used in the deque by turning into a &mut[T]
265        let (a, b) = self.as_mut_slices();
266        ptr::drop_in_place(a);
267        ptr::drop_in_place(b);
268    }
269
270    /// Returns whether the deque is empty.
271    pub fn is_empty(&self) -> bool {
272        self.front == self.back && !self.full
273    }
274
275    /// Returns whether the deque is full (i.e. if `len() == capacity()`.
276    pub fn is_full(&self) -> bool {
277        self.full
278    }
279
280    /// Returns a pair of slices which contain, in order, the contents of the `Deque`.
281    pub fn as_slices(&self) -> (&[T], &[T]) {
282        // NOTE(unsafe) avoid bound checks in the slicing operation
283        unsafe {
284            if self.is_empty() {
285                (&[], &[])
286            } else if self.back <= self.front {
287                (
288                    slice::from_raw_parts(
289                        self.buffer.borrow().as_ptr().add(self.front).cast::<T>(),
290                        self.storage_capacity() - self.front,
291                    ),
292                    slice::from_raw_parts(self.buffer.borrow().as_ptr().cast::<T>(), self.back),
293                )
294            } else {
295                (
296                    slice::from_raw_parts(
297                        self.buffer.borrow().as_ptr().add(self.front).cast::<T>(),
298                        self.back - self.front,
299                    ),
300                    &[],
301                )
302            }
303        }
304    }
305
306    /// Returns a pair of mutable slices which contain, in order, the contents of the `Deque`.
307    pub fn as_mut_slices(&mut self) -> (&mut [T], &mut [T]) {
308        let ptr = self.buffer.borrow_mut().as_mut_ptr();
309
310        // NOTE(unsafe) avoid bound checks in the slicing operation
311        unsafe {
312            if self.is_empty() {
313                (&mut [], &mut [])
314            } else if self.back <= self.front {
315                (
316                    slice::from_raw_parts_mut(
317                        ptr.add(self.front).cast::<T>(),
318                        self.storage_capacity() - self.front,
319                    ),
320                    slice::from_raw_parts_mut(ptr.cast::<T>(), self.back),
321                )
322            } else {
323                (
324                    slice::from_raw_parts_mut(
325                        ptr.add(self.front).cast::<T>(),
326                        self.back - self.front,
327                    ),
328                    &mut [],
329                )
330            }
331        }
332    }
333
334    #[inline]
335    fn is_contiguous(&self) -> bool {
336        self.front <= self.storage_capacity() - self.storage_len()
337    }
338
339    /// Rearranges the internal storage of the [`Deque`] to make it into a contiguous slice,
340    /// which is returned.
341    ///
342    /// This does **not** change the order of the elements in the deque.
343    /// The returned slice can then be used to perform contiguous slice operations on the deque.
344    ///
345    /// After calling this method, subsequent [`as_slices`] and [`as_mut_slices`] calls will return
346    /// a single contiguous slice.
347    ///
348    /// [`as_slices`]: Deque::as_slices
349    /// [`as_mut_slices`]: Deque::as_mut_slices
350    ///
351    /// # Examples
352    /// Sorting a deque:
353    /// ```
354    /// use heapless::Deque;
355    ///
356    /// let mut buf = Deque::<_, 4>::new();
357    /// buf.push_back(2).unwrap();
358    /// buf.push_back(1).unwrap();
359    /// buf.push_back(3).unwrap();
360    ///
361    /// // Sort the deque
362    /// buf.make_contiguous().sort();
363    /// assert_eq!(buf.as_slices(), (&[1, 2, 3][..], &[][..]));
364    ///
365    /// // Sort the deque in reverse
366    /// buf.make_contiguous().sort_by(|a, b| b.cmp(a));
367    /// assert_eq!(buf.as_slices(), (&[3, 2, 1][..], &[][..]));
368    /// ```
369    pub fn make_contiguous(&mut self) -> &mut [T] {
370        if self.is_contiguous() {
371            return unsafe {
372                slice::from_raw_parts_mut(
373                    self.buffer.borrow_mut().as_mut_ptr().add(self.front).cast(),
374                    self.storage_len(),
375                )
376            };
377        }
378
379        let buffer_ptr: *mut T = self.buffer.borrow_mut().as_mut_ptr().cast();
380
381        let len = self.storage_len();
382
383        let free = self.storage_capacity() - len;
384        let front_len = self.storage_capacity() - self.front;
385        let back = len - front_len;
386        let back_len = back;
387
388        if free >= front_len {
389            // there is enough free space to copy the head in one go,
390            // this means that we first shift the tail backwards, and then
391            // copy the head to the correct position.
392            //
393            // from: DEFGH....ABC
394            // to:   ABCDEFGH....
395            unsafe {
396                ptr::copy(buffer_ptr, buffer_ptr.add(front_len), back_len);
397                // ...DEFGH.ABC
398                ptr::copy_nonoverlapping(buffer_ptr.add(self.front), buffer_ptr, front_len);
399                // ABCDEFGH....
400            }
401
402            self.front = 0;
403            self.back = len;
404        } else if free >= back_len {
405            // there is enough free space to copy the tail in one go,
406            // this means that we first shift the head forwards, and then
407            // copy the tail to the correct position.
408            //
409            // from: FGH....ABCDE
410            // to:   ...ABCDEFGH.
411            unsafe {
412                ptr::copy(
413                    buffer_ptr.add(self.front),
414                    buffer_ptr.add(self.back),
415                    front_len,
416                );
417                // FGHABCDE....
418                ptr::copy_nonoverlapping(
419                    buffer_ptr,
420                    buffer_ptr.add(self.back + front_len),
421                    back_len,
422                );
423                // ...ABCDEFGH.
424            }
425
426            self.front = back;
427            self.back = 0;
428        } else {
429            // `free` is smaller than both `head_len` and `tail_len`.
430            // the general algorithm for this first moves the slices
431            // right next to each other and then uses `slice::rotate`
432            // to rotate them into place:
433            //
434            // initially:   HIJK..ABCDEFG
435            // step 1:      ..HIJKABCDEFG
436            // step 2:      ..ABCDEFGHIJK
437            //
438            // or:
439            //
440            // initially:   FGHIJK..ABCDE
441            // step 1:      FGHIJKABCDE..
442            // step 2:      ABCDEFGHIJK..
443
444            // pick the shorter of the 2 slices to reduce the amount
445            // of memory that needs to be moved around.
446            if front_len > back_len {
447                // tail is shorter, so:
448                //  1. copy tail forwards
449                //  2. rotate used part of the buffer
450                //  3. update head to point to the new beginning (which is just `free`)
451                unsafe {
452                    // if there is no free space in the buffer, then the slices are already
453                    // right next to each other and we don't need to move any memory.
454                    if free != 0 {
455                        // because we only move the tail forward as much as there's free space
456                        // behind it, we don't overwrite any elements of the head slice, and
457                        // the slices end up right next to each other.
458                        ptr::copy(buffer_ptr, buffer_ptr.add(free), back_len);
459                    }
460
461                    // We just copied the tail right next to the head slice,
462                    // so all of the elements in the range are initialized
463                    let slice: &mut [T] = slice::from_raw_parts_mut(
464                        buffer_ptr.add(free),
465                        self.storage_capacity() - free,
466                    );
467
468                    // because the deque wasn't contiguous, we know that `tail_len < self.len ==
469                    // slice.len()`, so this will never panic.
470                    slice.rotate_left(back_len);
471
472                    // the used part of the buffer now is `free..self.capacity()`, so set
473                    // `head` to the beginning of that range.
474                    self.front = free;
475                    self.back = 0;
476                }
477            } else {
478                // head is shorter so:
479                //  1. copy head backwards
480                //  2. rotate used part of the buffer
481                //  3. update head to point to the new beginning (which is the beginning of the
482                //     buffer)
483
484                unsafe {
485                    // if there is no free space in the buffer, then the slices are already
486                    // right next to each other and we don't need to move any memory.
487                    if free != 0 {
488                        // copy the head slice to lie right behind the tail slice.
489                        ptr::copy(
490                            buffer_ptr.add(self.front),
491                            buffer_ptr.add(back_len),
492                            front_len,
493                        );
494                    }
495
496                    // because we copied the head slice so that both slices lie right
497                    // next to each other, all the elements in the range are initialized.
498                    let slice: &mut [T] = slice::from_raw_parts_mut(buffer_ptr, len);
499
500                    // because the deque wasn't contiguous, we know that `head_len < self.len ==
501                    // slice.len()` so this will never panic.
502                    slice.rotate_right(front_len);
503
504                    // the used part of the buffer now is `0..self.len`, so set
505                    // `head` to the beginning of that range.
506                    self.front = 0;
507                    self.back = len;
508                }
509            }
510        }
511
512        unsafe { slice::from_raw_parts_mut(buffer_ptr.add(self.front), len) }
513    }
514
515    /// Provides a reference to the front element, or None if the `Deque` is empty.
516    pub fn front(&self) -> Option<&T> {
517        if self.is_empty() {
518            None
519        } else {
520            Some(unsafe { &*self.buffer.borrow().get_unchecked(self.front).as_ptr() })
521        }
522    }
523
524    /// Provides a mutable reference to the front element, or None if the `Deque` is empty.
525    pub fn front_mut(&mut self) -> Option<&mut T> {
526        if self.is_empty() {
527            None
528        } else {
529            Some(unsafe {
530                &mut *self
531                    .buffer
532                    .borrow_mut()
533                    .get_unchecked_mut(self.front)
534                    .as_mut_ptr()
535            })
536        }
537    }
538
539    /// Provides a reference to the back element, or None if the `Deque` is empty.
540    pub fn back(&self) -> Option<&T> {
541        if self.is_empty() {
542            None
543        } else {
544            let index = self.decrement(self.back);
545            Some(unsafe { &*self.buffer.borrow().get_unchecked(index).as_ptr() })
546        }
547    }
548
549    /// Provides a mutable reference to the back element, or None if the `Deque` is empty.
550    pub fn back_mut(&mut self) -> Option<&mut T> {
551        if self.is_empty() {
552            None
553        } else {
554            let index = self.decrement(self.back);
555            Some(unsafe {
556                &mut *self
557                    .buffer
558                    .borrow_mut()
559                    .get_unchecked_mut(index)
560                    .as_mut_ptr()
561            })
562        }
563    }
564
565    /// Removes the item from the front of the deque and returns it, or `None` if it's empty
566    pub fn pop_front(&mut self) -> Option<T> {
567        if self.is_empty() {
568            None
569        } else {
570            Some(unsafe { self.pop_front_unchecked() })
571        }
572    }
573
574    /// Removes the item from the back of the deque and returns it, or `None` if it's empty
575    pub fn pop_back(&mut self) -> Option<T> {
576        if self.is_empty() {
577            None
578        } else {
579            Some(unsafe { self.pop_back_unchecked() })
580        }
581    }
582
583    /// Appends an `item` to the front of the deque
584    ///
585    /// Returns back the `item` if the deque is full
586    pub fn push_front(&mut self, item: T) -> Result<(), T> {
587        if self.is_full() {
588            Err(item)
589        } else {
590            unsafe { self.push_front_unchecked(item) }
591            Ok(())
592        }
593    }
594
595    /// Appends an `item` to the back of the deque
596    ///
597    /// Returns back the `item` if the deque is full
598    pub fn push_back(&mut self, item: T) -> Result<(), T> {
599        if self.is_full() {
600            Err(item)
601        } else {
602            unsafe { self.push_back_unchecked(item) }
603            Ok(())
604        }
605    }
606
607    /// Removes an item from the front of the deque and returns it, without checking that the deque
608    /// is not empty
609    ///
610    /// # Safety
611    ///
612    /// It's undefined behavior to call this on an empty deque
613    pub unsafe fn pop_front_unchecked(&mut self) -> T {
614        debug_assert!(!self.is_empty());
615
616        let index = self.front;
617        self.full = false;
618        self.front = self.increment(self.front);
619        self.buffer
620            .borrow_mut()
621            .get_unchecked_mut(index)
622            .as_ptr()
623            .read()
624    }
625
626    /// Removes an item from the back of the deque and returns it, without checking that the deque
627    /// is not empty
628    ///
629    /// # Safety
630    ///
631    /// It's undefined behavior to call this on an empty deque
632    pub unsafe fn pop_back_unchecked(&mut self) -> T {
633        debug_assert!(!self.is_empty());
634
635        self.full = false;
636        self.back = self.decrement(self.back);
637        self.buffer
638            .borrow_mut()
639            .get_unchecked_mut(self.back)
640            .as_ptr()
641            .read()
642    }
643
644    /// Appends an `item` to the front of the deque
645    ///
646    /// # Safety
647    ///
648    /// This assumes the deque is not full.
649    pub unsafe fn push_front_unchecked(&mut self, item: T) {
650        debug_assert!(!self.is_full());
651
652        let index = self.decrement(self.front);
653        // NOTE: the memory slot that we are about to write to is uninitialized. We assign
654        // a `MaybeUninit` to avoid running `T`'s destructor on the uninitialized memory
655        *self.buffer.borrow_mut().get_unchecked_mut(index) = MaybeUninit::new(item);
656        self.front = index;
657        if self.front == self.back {
658            self.full = true;
659        }
660    }
661
662    /// Appends an `item` to the back of the deque
663    ///
664    /// # Safety
665    ///
666    /// This assumes the deque is not full.
667    pub unsafe fn push_back_unchecked(&mut self, item: T) {
668        debug_assert!(!self.is_full());
669
670        // NOTE: the memory slot that we are about to write to is uninitialized. We assign
671        // a `MaybeUninit` to avoid running `T`'s destructor on the uninitialized memory
672        *self.buffer.borrow_mut().get_unchecked_mut(self.back) = MaybeUninit::new(item);
673        self.back = self.increment(self.back);
674        if self.front == self.back {
675            self.full = true;
676        }
677    }
678
679    /// Removes and returns the first element from the deque if the predicate
680    /// returns `true`, or [`None`] if the predicate returns false or the deque
681    /// is empty (the predicate will not be called in that case).
682    ///
683    /// # Examples
684    ///
685    /// ```
686    /// use heapless::Deque;
687    ///
688    /// let mut deque: Deque<i32, 5> = [0, 1, 2, 3, 4].try_into().unwrap();
689    /// let pred = |x: &mut i32| *x % 2 == 0;
690    ///
691    /// assert_eq!(deque.pop_front_if(pred), Some(0));
692    /// assert_eq!(deque, Deque::<i32,4>::try_from([1, 2, 3, 4]).unwrap());
693    /// assert_eq!(deque.pop_front_if(pred), None);
694    /// ```
695    pub fn pop_front_if(&mut self, predicate: impl FnOnce(&mut T) -> bool) -> Option<T> {
696        let first = self.front_mut()?;
697        if predicate(first) {
698            self.pop_front()
699        } else {
700            None
701        }
702    }
703
704    /// Removes and returns the last element from the deque if the predicate
705    /// returns `true`, or [`None`] if the predicate returns false or the deque
706    /// is empty (the predicate will not be called in that case).
707    ///
708    /// # Examples
709    ///
710    /// ```
711    /// use heapless::Deque;
712    ///
713    /// let mut deque: Deque<i32, 5> = [0, 1, 2, 3, 4].try_into().unwrap();
714    /// let pred = |x: &mut i32| *x % 2 == 0;
715    ///
716    /// assert_eq!(deque.pop_back_if(pred), Some(4));
717    /// assert_eq!(deque, Deque::<i32,4>::try_from([0, 1, 2, 3]).unwrap());
718    /// assert_eq!(deque.pop_back_if(pred), None);
719    /// ```
720    pub fn pop_back_if(&mut self, predicate: impl FnOnce(&mut T) -> bool) -> Option<T> {
721        let last = self.back_mut()?;
722        if predicate(last) {
723            self.pop_back()
724        } else {
725            None
726        }
727    }
728
729    /// Returns a reference to the element at the given index.
730    ///
731    /// Index 0 is the front of the `Deque`.
732    pub fn get(&self, index: usize) -> Option<&T> {
733        if index < self.storage_len() {
734            let idx = self.to_physical_index(index);
735            Some(unsafe { self.buffer.borrow().get_unchecked(idx).assume_init_ref() })
736        } else {
737            None
738        }
739    }
740
741    /// Returns a mutable reference to the element at the given index.
742    ///
743    /// Index 0 is the front of the `Deque`.
744    pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
745        if index < self.storage_len() {
746            let idx = self.to_physical_index(index);
747            Some(unsafe {
748                self.buffer
749                    .borrow_mut()
750                    .get_unchecked_mut(idx)
751                    .assume_init_mut()
752            })
753        } else {
754            None
755        }
756    }
757
758    /// Returns a reference to the element at the given index without checking if it exists.
759    ///
760    /// # Safety
761    ///
762    /// The element at the given `index` must exist (i.e. `index < self.len()`).
763    pub unsafe fn get_unchecked(&self, index: usize) -> &T {
764        debug_assert!(index < self.storage_len());
765
766        let idx = self.to_physical_index(index);
767        self.buffer.borrow().get_unchecked(idx).assume_init_ref()
768    }
769
770    /// Returns a mutable reference to the element at the given index without checking if it exists.
771    ///
772    /// # Safety
773    ///
774    /// The element at the given `index` must exist (i.e. `index < self.len()`).
775    pub unsafe fn get_unchecked_mut(&mut self, index: usize) -> &mut T {
776        debug_assert!(index < self.storage_len());
777
778        let idx = self.to_physical_index(index);
779        self.buffer
780            .borrow_mut()
781            .get_unchecked_mut(idx)
782            .assume_init_mut()
783    }
784
785    /// Swaps elements at indices `i` and `j`.
786    ///
787    /// # Panics
788    ///
789    /// Panics if either `i` or `j` are out of bounds.
790    pub fn swap(&mut self, i: usize, j: usize) {
791        let len = self.storage_len();
792        assert!(i < len);
793        assert!(j < len);
794        unsafe { self.swap_unchecked(i, j) }
795    }
796
797    /// Swaps elements at indices `i` and `j` without checking that they exist.
798    ///
799    /// # Safety
800    ///
801    /// Elements at indexes `i` and `j` must exist (i.e. `i < self.len()` and `j < self.len()`).
802    pub unsafe fn swap_unchecked(&mut self, i: usize, j: usize) {
803        debug_assert!(i < self.storage_len());
804        debug_assert!(j < self.storage_len());
805        let idx_i = self.to_physical_index(i);
806        let idx_j = self.to_physical_index(j);
807
808        let buffer = self.buffer.borrow_mut();
809        let buffer_ptr = buffer.as_mut_ptr();
810        let ptr_i = buffer_ptr.add(idx_i);
811        let ptr_j = buffer_ptr.add(idx_j);
812        ptr::swap(ptr_i, ptr_j);
813    }
814
815    /// Removes an element from anywhere in the deque and returns it, replacing it with the first
816    /// element.
817    ///
818    /// This does not preserve ordering, but is *O*(1).
819    ///
820    /// Returns `None` if `index` is out of bounds.
821    ///
822    /// Element at index 0 is the front of the queue.
823    pub fn swap_remove_front(&mut self, index: usize) -> Option<T> {
824        let len = self.storage_len();
825        if len > 0 && index < len {
826            Some(unsafe {
827                self.swap_unchecked(index, 0);
828                self.pop_front_unchecked()
829            })
830        } else {
831            None
832        }
833    }
834
835    /// Removes an element from anywhere in the deque and returns it, replacing it with the last
836    /// element.
837    ///
838    /// This does not preserve ordering, but is *O*(1).
839    ///
840    /// Returns `None` if `index` is out of bounds.
841    ///
842    /// Element at index 0 is the front of the queue.
843    pub fn swap_remove_back(&mut self, index: usize) -> Option<T> {
844        let len = self.storage_len();
845        if len > 0 && index < len {
846            Some(unsafe {
847                self.swap_unchecked(index, len - 1);
848                self.pop_back_unchecked()
849            })
850        } else {
851            None
852        }
853    }
854
855    fn to_physical_index(&self, index: usize) -> usize {
856        let mut res = self.front + index;
857        if res >= self.storage_capacity() {
858            res -= self.storage_capacity();
859        }
860        res
861    }
862
863    /// Returns an iterator over the deque.
864    pub fn iter(&self) -> Iter<'_, T> {
865        let (start, end) = self.as_slices();
866        Iter {
867            inner: start.iter().chain(end),
868        }
869    }
870
871    /// Returns an iterator that allows modifying each value.
872    pub fn iter_mut(&mut self) -> IterMut<'_, T> {
873        let (start, end) = self.as_mut_slices();
874        IterMut {
875            inner: start.iter_mut().chain(end),
876        }
877    }
878
879    /// Shortens the deque, keeping the first `len` elements and dropping
880    /// the rest.
881    ///
882    /// If `len` is greater or equal to the deque's current length, this has
883    /// no effect.
884    ///
885    /// # Examples
886    ///
887    /// ```
888    /// use heapless::Deque;
889    ///
890    /// let mut buf: Deque<_, 5> = Deque::new();
891    /// buf.push_back(5);
892    /// buf.push_back(10);
893    /// buf.push_back(15);
894    /// buf.truncate(1);
895    /// assert_eq!(buf.make_contiguous(), [5]);
896    /// ```
897    pub fn truncate(&mut self, len: usize) {
898        /// Runs the destructor for all items in the slice when it gets dropped (gracefully or
899        /// during unwinding).
900        struct Dropper<'a, T>(&'a mut [T]);
901
902        impl<'a, T> Drop for Dropper<'a, T> {
903            fn drop(&mut self) {
904                unsafe {
905                    ptr::drop_in_place(self.0);
906                }
907            }
908        }
909
910        // Safety:
911        // * Any slice passed to `drop_in_place` is valid; the second case has `len <= front.len()`
912        //   and returning on `len > self.storage_len()` ensures `begin <= back.len()` in the first
913        //   case
914        // * Deque front/back cursors are moved before calling `drop_in_place`, so no value is
915        //   dropped twice if `drop_in_place` panics
916        unsafe {
917            // If new desired length is greater or equal, we don't need to act.
918            if len >= self.storage_len() {
919                return;
920            }
921
922            let (front, back) = self.as_mut_slices();
923
924            // If `len` desires to keep elements past front's entire length,
925            // then only back's contents will need to be dropped
926            // as the two slices combined should be more than `len`.
927            if len > front.len() {
928                let begin = len - front.len();
929                let drop_back = core::ptr::from_mut(back.get_unchecked_mut(begin..));
930
931                // Self::to_physical_index returns the index `len` units _after_ the front cursor,
932                // meaning we can use it to find the decremented index for `back` for non-contiguous
933                // deques, as well as determine where the new "cap" for front needs
934                // to be placed for contiguous deques.
935                self.back = self.to_physical_index(len);
936                self.full = false;
937
938                ptr::drop_in_place(drop_back);
939            } else {
940                // Otherwise, we know back's entire contents need to be dropped,
941                // since the desired length never reaches into it.
942                let drop_back = core::ptr::from_mut(back);
943                let drop_front = core::ptr::from_mut(front.get_unchecked_mut(len..));
944
945                self.back = self.to_physical_index(len);
946                self.full = false;
947
948                // If `drop_front` causes a panic, the Dropper will still be called to drop it's
949                // slice during unwinding. In either case, front will always be
950                // dropped before back.
951                let _back_dropper = Dropper(&mut *drop_back);
952                ptr::drop_in_place(drop_front);
953            }
954        }
955    }
956
957    /// Retains only the elements specified by the predicate.
958    ///
959    /// In other words, remove all elements `e` for which `f(&e)` returns false.
960    /// This method operates in place, visiting each element exactly once in the
961    /// original order, and preserves the order of the retained elements.
962    ///
963    /// # Examples
964    ///
965    /// ```
966    /// use heapless::Deque;
967    ///
968    /// let mut buf: Deque<_, 10> = Deque::new();
969    /// buf.extend(1..5);
970    /// buf.retain(|&x| x % 2 == 0);
971    /// assert_eq!(buf.make_contiguous(), [2, 4]);
972    /// ```
973    ///
974    /// Because the elements are visited exactly once in the original order,
975    /// external state may be used to decide which elements to keep.
976    ///
977    /// ```
978    /// use heapless::Deque;
979    ///
980    /// let mut buf: Deque<_, 10> = Deque::new();
981    /// buf.extend(1..6);
982    ///
983    /// let keep = [false, true, true, false, true];
984    /// let mut iter = keep.iter();
985    /// buf.retain(|_| *iter.next().unwrap());
986    /// assert_eq!(buf.make_contiguous(), [2, 3, 5]);
987    /// ```
988    pub fn retain<F>(&mut self, mut f: F)
989    where
990        F: FnMut(&T) -> bool,
991    {
992        self.retain_mut(|elem| f(elem));
993    }
994
995    /// Retains only the elements specified by the predicate.
996    ///
997    /// In other words, remove all elements `e` for which `f(&mut e)` returns false.
998    /// This method operates in place, visiting each element exactly once in the
999    /// original order, and preserves the order of the retained elements.
1000    ///
1001    /// # Examples
1002    ///
1003    /// ```
1004    /// use heapless::Deque;
1005    ///
1006    /// let mut buf: Deque<_, 10> = Deque::new();
1007    /// buf.extend(1..5);
1008    /// buf.retain_mut(|x| {
1009    ///     if *x % 2 == 0 {
1010    ///         *x += 1;
1011    ///         true
1012    ///     } else {
1013    ///         false
1014    ///     }
1015    /// });
1016    /// assert_eq!(buf.make_contiguous(), [3, 5]);
1017    /// ```
1018    pub fn retain_mut<F>(&mut self, mut f: F)
1019    where
1020        F: FnMut(&mut T) -> bool,
1021    {
1022        let len = self.storage_len();
1023        let mut idx = 0;
1024        let mut cur = 0;
1025
1026        // Stage 1: Check if all values can be retained.
1027        while cur < len {
1028            let val = self
1029                .get_mut(cur)
1030                .expect("cur was checked to be less than deque's length");
1031            if !f(val) {
1032                cur += 1;
1033                break;
1034            }
1035
1036            cur += 1;
1037            idx += 1;
1038        }
1039        // Stage 2: Swap retained values into current idx, building a contiguous chunk from 0 to
1040        // idx.
1041        while cur < len {
1042            let val = self
1043                .get_mut(cur)
1044                .expect("cur was checked to be less than deque's length");
1045            if !f(val) {
1046                cur += 1;
1047                continue;
1048            }
1049
1050            self.swap(idx, cur);
1051            cur += 1;
1052            idx += 1;
1053        }
1054        // Stage 3: Truncate any moved values after idx.
1055        if cur != idx {
1056            self.truncate(idx);
1057        }
1058    }
1059}
1060
1061/// Iterator over the contents of a [`Deque`]
1062pub struct Iter<'a, T> {
1063    inner: core::iter::Chain<core::slice::Iter<'a, T>, core::slice::Iter<'a, T>>,
1064}
1065
1066/// Iterator over the contents of a [`Deque`]
1067pub struct IterMut<'a, T> {
1068    inner: core::iter::Chain<core::slice::IterMut<'a, T>, core::slice::IterMut<'a, T>>,
1069}
1070
1071impl<'a, T> Iterator for Iter<'a, T> {
1072    type Item = &'a T;
1073    #[inline]
1074    fn next(&mut self) -> Option<Self::Item> {
1075        self.inner.next()
1076    }
1077
1078    #[inline]
1079    fn size_hint(&self) -> (usize, Option<usize>) {
1080        self.inner.size_hint()
1081    }
1082}
1083
1084impl<T> DoubleEndedIterator for Iter<'_, T> {
1085    #[inline]
1086    fn next_back(&mut self) -> Option<Self::Item> {
1087        self.inner.next_back()
1088    }
1089}
1090
1091impl<T> ExactSizeIterator for Iter<'_, T> {}
1092impl<T> FusedIterator for Iter<'_, T> {}
1093
1094impl<'a, T> Iterator for IterMut<'a, T> {
1095    type Item = &'a mut T;
1096    #[inline]
1097    fn next(&mut self) -> Option<Self::Item> {
1098        self.inner.next()
1099    }
1100    #[inline]
1101    fn size_hint(&self) -> (usize, Option<usize>) {
1102        self.inner.size_hint()
1103    }
1104}
1105
1106impl<T> DoubleEndedIterator for IterMut<'_, T> {
1107    #[inline]
1108    fn next_back(&mut self) -> Option<Self::Item> {
1109        self.inner.next_back()
1110    }
1111}
1112
1113impl<T> ExactSizeIterator for IterMut<'_, T> {}
1114impl<T> FusedIterator for IterMut<'_, T> {}
1115
1116// Trait implementations
1117
1118impl<T, const N: usize> Default for Deque<T, N> {
1119    fn default() -> Self {
1120        Self::new()
1121    }
1122}
1123
1124impl<T, S: VecStorage<T> + ?Sized> Drop for DequeInner<T, S> {
1125    fn drop(&mut self) {
1126        // safety: `self` is left in an inconsistent state but it doesn't matter since
1127        // it's getting dropped. Nothing should be able to observe `self` after drop.
1128        unsafe { self.drop_contents() }
1129    }
1130}
1131
1132impl<T: fmt::Debug, S: VecStorage<T> + ?Sized> fmt::Debug for DequeInner<T, S> {
1133    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1134        f.debug_list().entries(self).finish()
1135    }
1136}
1137
1138/// As with the standard library's `VecDeque`, items are added via `push_back`.
1139impl<T, S: VecStorage<T> + ?Sized> Extend<T> for DequeInner<T, S> {
1140    fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1141        for item in iter {
1142            self.push_back(item).ok().unwrap();
1143        }
1144    }
1145}
1146impl<'a, T: 'a + Copy, S: VecStorage<T> + ?Sized> Extend<&'a T> for DequeInner<T, S> {
1147    fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
1148        self.extend(iter.into_iter().copied());
1149    }
1150}
1151
1152/// An iterator that moves out of a [`Deque`].
1153///
1154/// This struct is created by calling the `into_iter` method.
1155#[derive(Clone)]
1156pub struct IntoIter<T, const N: usize> {
1157    deque: Deque<T, N>,
1158}
1159
1160impl<T, const N: usize> Iterator for IntoIter<T, N> {
1161    type Item = T;
1162    fn next(&mut self) -> Option<Self::Item> {
1163        self.deque.pop_front()
1164    }
1165    fn size_hint(&self) -> (usize, Option<usize>) {
1166        let len = self.len();
1167        (len, Some(len))
1168    }
1169}
1170impl<T, const N: usize> DoubleEndedIterator for IntoIter<T, N> {
1171    fn next_back(&mut self) -> Option<Self::Item> {
1172        self.deque.pop_back()
1173    }
1174}
1175impl<T, const N: usize> FusedIterator for IntoIter<T, N> {}
1176impl<T, const N: usize> ExactSizeIterator for IntoIter<T, N> {
1177    fn len(&self) -> usize {
1178        self.deque.len()
1179    }
1180}
1181
1182impl<T, const N: usize> IntoIterator for Deque<T, N> {
1183    type Item = T;
1184    type IntoIter = IntoIter<T, N>;
1185
1186    fn into_iter(self) -> Self::IntoIter {
1187        IntoIter { deque: self }
1188    }
1189}
1190
1191impl<'a, T, S: VecStorage<T> + ?Sized> IntoIterator for &'a DequeInner<T, S> {
1192    type Item = &'a T;
1193    type IntoIter = Iter<'a, T>;
1194
1195    fn into_iter(self) -> Self::IntoIter {
1196        self.iter()
1197    }
1198}
1199
1200impl<'a, T, S: VecStorage<T> + ?Sized> IntoIterator for &'a mut DequeInner<T, S> {
1201    type Item = &'a mut T;
1202    type IntoIter = IterMut<'a, T>;
1203
1204    fn into_iter(self) -> Self::IntoIter {
1205        self.iter_mut()
1206    }
1207}
1208
1209impl<T, const N: usize> Clone for Deque<T, N>
1210where
1211    T: Clone,
1212{
1213    fn clone(&self) -> Self {
1214        let mut res = Self::new();
1215        for i in self {
1216            // safety: the original and new deques have the same capacity, so it can
1217            // not become full.
1218            unsafe { res.push_back_unchecked(i.clone()) }
1219        }
1220        res
1221    }
1222}
1223
1224impl<T: PartialEq, S1, S2> PartialEq<DequeInner<T, S2>> for DequeInner<T, S1>
1225where
1226    S1: VecStorage<T> + ?Sized,
1227    S2: VecStorage<T> + ?Sized,
1228{
1229    fn eq(&self, other: &DequeInner<T, S2>) -> bool {
1230        if self.storage_len() != other.storage_len() {
1231            return false;
1232        }
1233        let (sa, sb) = self.as_slices();
1234        let (oa, ob) = other.as_slices();
1235        match sa.len().cmp(&oa.len()) {
1236            Ordering::Equal => sa == oa && sb == ob,
1237            Ordering::Less => {
1238                // Always divisible in three sections, for example:
1239                // self:  [a b c|d e f]
1240                // other: [0 1 2 3|4 5]
1241                // front = 3, mid = 1,
1242                // [a b c] == [0 1 2] && [d] == [3] && [e f] == [4 5]
1243                let front = sa.len();
1244                let mid = oa.len() - front;
1245
1246                let (oa_front, oa_mid) = oa.split_at(front);
1247                let (sb_mid, sb_back) = sb.split_at(mid);
1248                debug_assert_eq!(sa.len(), oa_front.len());
1249                debug_assert_eq!(sb_mid.len(), oa_mid.len());
1250                debug_assert_eq!(sb_back.len(), ob.len());
1251                sa == oa_front && sb_mid == oa_mid && sb_back == ob
1252            }
1253            Ordering::Greater => {
1254                let front = oa.len();
1255                let mid = sa.len() - front;
1256
1257                let (sa_front, sa_mid) = sa.split_at(front);
1258                let (ob_mid, ob_back) = ob.split_at(mid);
1259                debug_assert_eq!(sa_front.len(), oa.len());
1260                debug_assert_eq!(sa_mid.len(), ob_mid.len());
1261                debug_assert_eq!(sb.len(), ob_back.len());
1262                sa_front == oa && sa_mid == ob_mid && sb == ob_back
1263            }
1264        }
1265    }
1266}
1267
1268impl<T: Eq, const N: usize> Eq for Deque<T, N> {}
1269
1270impl<T, const NS: usize, const ND: usize> TryFrom<[T; NS]> for Deque<T, ND> {
1271    /// Converts a `[T; NS]` into a `Deque<T, ND>`.
1272    ///
1273    /// ```
1274    /// use heapless::Deque;
1275    ///
1276    /// let deq1 = Deque::<u8, 5>::try_from([1, 2, 3]).unwrap();
1277    /// let mut deq2 = Deque::<u8, 5>::new();
1278    /// deq2.push_back(1).unwrap();
1279    /// deq2.push_back(2).unwrap();
1280    /// deq2.push_back(3).unwrap();
1281    ///
1282    /// assert_eq!(deq1, deq2);
1283    /// ```
1284    type Error = (CapacityError, [T; NS]);
1285
1286    /// Converts a `[T; NS]` array into a `Deque<T, ND>`.
1287    ///
1288    /// Returns back the `value` if NS > ND.
1289    fn try_from(value: [T; NS]) -> Result<Self, Self::Error> {
1290        if NS > ND {
1291            return Err((CapacityError, value));
1292        }
1293
1294        let mut deq = Self::default();
1295        let value = ManuallyDrop::new(value);
1296
1297        // SAFETY: We already ensured that value fits in deq.
1298        unsafe {
1299            ptr::copy_nonoverlapping(
1300                value.as_ptr(),
1301                deq.buffer.buffer.as_mut_ptr().cast::<T>(),
1302                NS,
1303            );
1304        }
1305
1306        deq.front = 0;
1307        deq.back = NS;
1308        deq.full = NS == ND;
1309
1310        Ok(deq)
1311    }
1312}
1313
1314#[cfg(test)]
1315mod tests {
1316    use std::{
1317        mem::ManuallyDrop,
1318        panic::{catch_unwind, AssertUnwindSafe},
1319        sync::atomic::{AtomicI32, Ordering::Relaxed},
1320    };
1321
1322    use super::Deque;
1323    use crate::CapacityError;
1324    use static_assertions::assert_not_impl_any;
1325
1326    // Ensure a `Deque` containing `!Send` values stays `!Send` itself.
1327    assert_not_impl_any!(Deque<*const (), 4>: Send);
1328
1329    #[test]
1330    fn static_new() {
1331        static mut _V: Deque<i32, 4> = Deque::new();
1332    }
1333
1334    #[test]
1335    fn stack_new() {
1336        let mut _v: Deque<i32, 4> = Deque::new();
1337    }
1338
1339    #[test]
1340    fn test_drop() {
1341        droppable!();
1342
1343        {
1344            let mut v: Deque<Droppable, 2> = Deque::new();
1345            v.push_back(Droppable::new()).ok().unwrap();
1346            v.push_back(Droppable::new()).ok().unwrap();
1347            v.pop_front().unwrap();
1348        }
1349
1350        assert_eq!(Droppable::count(), 0);
1351
1352        {
1353            let mut v: Deque<Droppable, 2> = Deque::new();
1354            v.push_back(Droppable::new()).ok().unwrap();
1355            v.push_back(Droppable::new()).ok().unwrap();
1356        }
1357
1358        assert_eq!(Droppable::count(), 0);
1359        {
1360            let mut v: Deque<Droppable, 2> = Deque::new();
1361            v.push_front(Droppable::new()).ok().unwrap();
1362            v.push_front(Droppable::new()).ok().unwrap();
1363        }
1364
1365        assert_eq!(Droppable::count(), 0);
1366    }
1367
1368    #[test]
1369    fn full() {
1370        let mut v: Deque<i32, 4> = Deque::new();
1371
1372        v.push_back(0).unwrap();
1373        v.push_front(1).unwrap();
1374        v.push_back(2).unwrap();
1375        v.push_back(3).unwrap();
1376
1377        assert!(v.push_front(4).is_err());
1378        assert!(v.push_back(4).is_err());
1379        assert!(v.is_full());
1380    }
1381
1382    #[test]
1383    fn empty() {
1384        let mut v: Deque<i32, 4> = Deque::new();
1385        assert!(v.is_empty());
1386
1387        v.push_back(0).unwrap();
1388        assert!(!v.is_empty());
1389
1390        v.push_front(1).unwrap();
1391        assert!(!v.is_empty());
1392
1393        v.pop_front().unwrap();
1394        v.pop_front().unwrap();
1395
1396        assert!(v.pop_front().is_none());
1397        assert!(v.pop_back().is_none());
1398        assert!(v.is_empty());
1399    }
1400
1401    #[test]
1402    fn front_back() {
1403        let mut v: Deque<i32, 4> = Deque::new();
1404        assert_eq!(v.front(), None);
1405        assert_eq!(v.front_mut(), None);
1406        assert_eq!(v.back(), None);
1407        assert_eq!(v.back_mut(), None);
1408
1409        v.push_back(4).unwrap();
1410        assert_eq!(v.front(), Some(&4));
1411        assert_eq!(v.front_mut(), Some(&mut 4));
1412        assert_eq!(v.back(), Some(&4));
1413        assert_eq!(v.back_mut(), Some(&mut 4));
1414
1415        v.push_front(3).unwrap();
1416        assert_eq!(v.front(), Some(&3));
1417        assert_eq!(v.front_mut(), Some(&mut 3));
1418        assert_eq!(v.back(), Some(&4));
1419        assert_eq!(v.back_mut(), Some(&mut 4));
1420
1421        v.pop_back().unwrap();
1422        assert_eq!(v.front(), Some(&3));
1423        assert_eq!(v.front_mut(), Some(&mut 3));
1424        assert_eq!(v.back(), Some(&3));
1425        assert_eq!(v.back_mut(), Some(&mut 3));
1426
1427        v.pop_front().unwrap();
1428        assert_eq!(v.front(), None);
1429        assert_eq!(v.front_mut(), None);
1430        assert_eq!(v.back(), None);
1431        assert_eq!(v.back_mut(), None);
1432    }
1433
1434    #[test]
1435    fn extend() {
1436        let mut v: Deque<i32, 4> = Deque::new();
1437        v.extend(&[1, 2, 3]);
1438        assert_eq!(v.pop_front().unwrap(), 1);
1439        assert_eq!(v.pop_front().unwrap(), 2);
1440        assert_eq!(*v.front().unwrap(), 3);
1441
1442        v.push_back(4).unwrap();
1443        v.extend(&[5, 6]);
1444        assert_eq!(v.pop_front().unwrap(), 3);
1445        assert_eq!(v.pop_front().unwrap(), 4);
1446        assert_eq!(v.pop_front().unwrap(), 5);
1447        assert_eq!(v.pop_front().unwrap(), 6);
1448        assert!(v.pop_front().is_none());
1449    }
1450
1451    #[test]
1452    #[should_panic]
1453    fn extend_panic() {
1454        let mut v: Deque<i32, 4> = Deque::new();
1455        // Is too many elements -> should panic
1456        v.extend(&[1, 2, 3, 4, 5]);
1457    }
1458
1459    #[test]
1460    fn iter() {
1461        let mut v: Deque<i32, 4> = Deque::new();
1462
1463        v.push_back(0).unwrap();
1464        v.push_back(1).unwrap();
1465        v.push_front(2).unwrap();
1466        v.push_front(3).unwrap();
1467        v.pop_back().unwrap();
1468        v.push_front(4).unwrap();
1469
1470        let mut items = v.iter();
1471
1472        assert_eq!(items.next(), Some(&4));
1473        assert_eq!(items.next(), Some(&3));
1474        assert_eq!(items.next(), Some(&2));
1475        assert_eq!(items.next(), Some(&0));
1476        assert_eq!(items.next(), None);
1477    }
1478
1479    #[test]
1480    fn iter_mut() {
1481        let mut v: Deque<i32, 4> = Deque::new();
1482
1483        v.push_back(0).unwrap();
1484        v.push_back(1).unwrap();
1485        v.push_front(2).unwrap();
1486        v.push_front(3).unwrap();
1487        v.pop_back().unwrap();
1488        v.push_front(4).unwrap();
1489
1490        let mut items = v.iter_mut();
1491
1492        assert_eq!(items.next(), Some(&mut 4));
1493        assert_eq!(items.next(), Some(&mut 3));
1494        assert_eq!(items.next(), Some(&mut 2));
1495        assert_eq!(items.next(), Some(&mut 0));
1496        assert_eq!(items.next(), None);
1497    }
1498
1499    #[test]
1500    fn iter_move() {
1501        let mut v: Deque<i32, 4> = Deque::new();
1502        v.push_back(0).unwrap();
1503        v.push_back(1).unwrap();
1504        v.push_back(2).unwrap();
1505        v.push_back(3).unwrap();
1506
1507        let mut items = v.into_iter();
1508
1509        assert_eq!(items.next(), Some(0));
1510        assert_eq!(items.next(), Some(1));
1511        assert_eq!(items.next(), Some(2));
1512        assert_eq!(items.next(), Some(3));
1513        assert_eq!(items.next(), None);
1514    }
1515
1516    #[test]
1517    fn iter_move_back() {
1518        let mut v: Deque<i32, 4> = Deque::new();
1519
1520        v.push_back(0).unwrap();
1521        v.push_back(1).unwrap();
1522        v.push_back(2).unwrap();
1523        v.push_back(3).unwrap();
1524
1525        let mut items = v.into_iter();
1526        assert_eq!(items.next_back(), Some(3));
1527        assert_eq!(items.next_back(), Some(2));
1528        assert_eq!(items.next_back(), Some(1));
1529        assert_eq!(items.next_back(), Some(0));
1530        assert_eq!(items.next_back(), None);
1531    }
1532
1533    #[test]
1534    fn iter_move_len() {
1535        let mut v: Deque<i32, 3> = Deque::new();
1536
1537        v.push_back(0).unwrap();
1538        v.push_back(1).unwrap();
1539        v.push_back(2).unwrap();
1540
1541        let mut items = v.into_iter();
1542        assert_eq!(items.len(), 3);
1543        let _ = items.next();
1544        assert_eq!(items.len(), 2);
1545        let _ = items.next_back();
1546        assert_eq!(items.len(), 1);
1547        let _ = items.next();
1548        assert_eq!(items.len(), 0);
1549    }
1550
1551    #[test]
1552    fn iter_move_drop() {
1553        droppable!();
1554
1555        {
1556            let mut deque: Deque<Droppable, 2> = Deque::new();
1557            deque.push_back(Droppable::new()).ok().unwrap();
1558            deque.push_back(Droppable::new()).ok().unwrap();
1559            let mut items = deque.into_iter();
1560            // Move all
1561            let _ = items.next();
1562            let _ = items.next();
1563        }
1564
1565        assert_eq!(Droppable::count(), 0);
1566
1567        {
1568            let mut deque: Deque<Droppable, 2> = Deque::new();
1569            deque.push_back(Droppable::new()).ok().unwrap();
1570            deque.push_back(Droppable::new()).ok().unwrap();
1571            let _items = deque.into_iter();
1572            // Move none
1573        }
1574
1575        assert_eq!(Droppable::count(), 0);
1576
1577        {
1578            let mut deque: Deque<Droppable, 2> = Deque::new();
1579            deque.push_back(Droppable::new()).ok().unwrap();
1580            deque.push_back(Droppable::new()).ok().unwrap();
1581            let mut items = deque.into_iter();
1582            let _ = items.next(); // Move partly
1583        }
1584
1585        assert_eq!(Droppable::count(), 0);
1586    }
1587
1588    #[test]
1589    fn push_and_pop() {
1590        let mut q: Deque<i32, 4> = Deque::new();
1591        assert_eq!(q.len(), 0);
1592
1593        assert_eq!(q.pop_front(), None);
1594        assert_eq!(q.pop_back(), None);
1595        assert_eq!(q.len(), 0);
1596
1597        q.push_back(0).unwrap();
1598        assert_eq!(q.len(), 1);
1599
1600        assert_eq!(q.pop_back(), Some(0));
1601        assert_eq!(q.len(), 0);
1602
1603        q.push_back(0).unwrap();
1604        q.push_back(1).unwrap();
1605        q.push_front(2).unwrap();
1606        q.push_front(3).unwrap();
1607        assert_eq!(q.len(), 4);
1608
1609        // deque contains: 3 2 0 1
1610        assert_eq!(q.pop_front(), Some(3));
1611        assert_eq!(q.len(), 3);
1612        assert_eq!(q.pop_front(), Some(2));
1613        assert_eq!(q.len(), 2);
1614        assert_eq!(q.pop_back(), Some(1));
1615        assert_eq!(q.len(), 1);
1616        assert_eq!(q.pop_front(), Some(0));
1617        assert_eq!(q.len(), 0);
1618
1619        // deque is now empty
1620        assert_eq!(q.pop_front(), None);
1621        assert_eq!(q.pop_back(), None);
1622        assert_eq!(q.len(), 0);
1623    }
1624
1625    #[test]
1626    fn as_slices() {
1627        let mut q: Deque<i32, 4> = Deque::new();
1628        assert_eq!(q.len(), 0);
1629
1630        q.push_back(0).unwrap();
1631        q.push_back(1).unwrap();
1632        q.push_back(2).unwrap();
1633        q.push_back(3).unwrap();
1634        assert_eq!(q.as_slices(), (&[0, 1, 2, 3][..], &[][..]));
1635
1636        q.pop_front().unwrap();
1637        assert_eq!(q.as_slices(), (&[1, 2, 3][..], &[][..]));
1638
1639        q.push_back(4).unwrap();
1640        assert_eq!(q.as_slices(), (&[1, 2, 3][..], &[4][..]));
1641    }
1642
1643    #[test]
1644    fn clear() {
1645        droppable!();
1646        let mut q: Deque<Droppable, 4> = Deque::new();
1647        assert_eq!(q.len(), 0);
1648
1649        q.push_back(Droppable::new()).unwrap();
1650        q.push_back(Droppable::new()).unwrap();
1651        q.push_back(Droppable::new()).unwrap();
1652        q.push_back(Droppable::new()).unwrap();
1653        assert_eq!(q.len(), 4);
1654
1655        q.clear();
1656        assert_eq!(q.len(), 0);
1657        assert_eq!(Droppable::count(), 0);
1658
1659        q.push_back(Droppable::new()).unwrap();
1660        assert_eq!(q.len(), 1);
1661        assert_eq!(Droppable::count(), 1);
1662    }
1663
1664    #[test]
1665    fn make_contiguous() {
1666        let mut q: Deque<i32, 4> = Deque::new();
1667        assert_eq!(q.len(), 0);
1668
1669        q.push_back(0).unwrap();
1670        q.push_back(1).unwrap();
1671        q.push_back(2).unwrap();
1672        q.push_back(3).unwrap();
1673
1674        // Deque contains: 0, 1, 2, 3
1675        assert_eq!(q.pop_front(), Some(0));
1676        assert_eq!(q.pop_front(), Some(1));
1677
1678        // Deque contains: ., ., 2, 3
1679        q.push_back(4).unwrap();
1680
1681        // Deque contains: 4, ., 2, 3
1682        assert_eq!(q.as_slices(), ([2, 3].as_slice(), [4].as_slice()));
1683
1684        assert_eq!(q.make_contiguous(), &[2, 3, 4]);
1685
1686        // Deque contains: ., 2, 3, 4
1687        assert_eq!(q.as_slices(), ([2, 3, 4].as_slice(), [].as_slice()));
1688
1689        assert_eq!(q.pop_front(), Some(2));
1690        assert_eq!(q.pop_front(), Some(3));
1691        q.push_back(5).unwrap();
1692        q.push_back(6).unwrap();
1693
1694        // Deque contains: 5, 6, ., 4
1695        assert_eq!(q.as_slices(), ([4].as_slice(), [5, 6].as_slice()));
1696
1697        assert_eq!(q.make_contiguous(), &[4, 5, 6]);
1698
1699        // Deque contains: 4, 5, 6, .
1700        assert_eq!(q.as_slices(), ([4, 5, 6].as_slice(), [].as_slice()));
1701
1702        assert_eq!(q.pop_front(), Some(4));
1703        q.push_back(7).unwrap();
1704        q.push_back(8).unwrap();
1705
1706        // Deque contains: 8, 5, 6, 7
1707        assert_eq!(q.as_slices(), ([5, 6, 7].as_slice(), [8].as_slice()));
1708
1709        assert_eq!(q.make_contiguous(), &[5, 6, 7, 8]);
1710
1711        // Deque contains: 5, 6, 7, 8
1712        assert_eq!(q.as_slices(), ([5, 6, 7, 8].as_slice(), [].as_slice()));
1713    }
1714
1715    #[test]
1716    fn get() {
1717        let mut q: Deque<i32, 4> = Deque::new();
1718        assert_eq!(q.get(0), None);
1719
1720        q.push_back(0).unwrap();
1721        assert_eq!(q.get(0), Some(&0));
1722        assert_eq!(q.get(1), None);
1723
1724        q.push_back(1).unwrap();
1725        assert_eq!(q.get(0), Some(&0));
1726        assert_eq!(q.get(1), Some(&1));
1727        assert_eq!(q.get(2), None);
1728
1729        q.pop_front().unwrap();
1730        assert_eq!(q.get(0), Some(&1));
1731        assert_eq!(q.get(1), None);
1732
1733        q.push_back(2).unwrap();
1734        q.push_back(3).unwrap();
1735        q.push_back(4).unwrap();
1736        assert_eq!(q.get(0), Some(&1));
1737        assert_eq!(q.get(1), Some(&2));
1738        assert_eq!(q.get(2), Some(&3));
1739        assert_eq!(q.get(3), Some(&4));
1740    }
1741
1742    #[test]
1743    fn get_mut() {
1744        let mut q: Deque<i32, 4> = Deque::new();
1745        assert_eq!(q.get(0), None);
1746
1747        q.push_back(0).unwrap();
1748        assert_eq!(q.get_mut(0), Some(&mut 0));
1749        assert_eq!(q.get_mut(1), None);
1750
1751        q.push_back(1).unwrap();
1752        assert_eq!(q.get_mut(0), Some(&mut 0));
1753        assert_eq!(q.get_mut(1), Some(&mut 1));
1754        assert_eq!(q.get_mut(2), None);
1755        *q.get_mut(0).unwrap() = 42;
1756        *q.get_mut(1).unwrap() = 43;
1757
1758        assert_eq!(q.pop_front(), Some(42));
1759        assert_eq!(q.pop_front(), Some(43));
1760        assert_eq!(q.pop_front(), None);
1761    }
1762
1763    #[test]
1764    fn swap() {
1765        let mut q: Deque<i32, 4> = Deque::new();
1766        q.push_back(40).unwrap();
1767        q.push_back(41).unwrap();
1768        q.push_back(42).unwrap();
1769        q.pop_front().unwrap();
1770        q.push_back(43).unwrap();
1771        assert_eq!(*q.get(0).unwrap(), 41);
1772        assert_eq!(*q.get(1).unwrap(), 42);
1773        assert_eq!(*q.get(2).unwrap(), 43);
1774
1775        q.swap(0, 1);
1776        assert_eq!(*q.get(0).unwrap(), 42);
1777        assert_eq!(*q.get(1).unwrap(), 41);
1778        assert_eq!(*q.get(2).unwrap(), 43);
1779
1780        q.swap(1, 2);
1781        assert_eq!(*q.get(0).unwrap(), 42);
1782        assert_eq!(*q.get(1).unwrap(), 43);
1783        assert_eq!(*q.get(2).unwrap(), 41);
1784
1785        q.swap(1, 1);
1786        assert_eq!(*q.get(0).unwrap(), 42);
1787        assert_eq!(*q.get(1).unwrap(), 43);
1788        assert_eq!(*q.get(2).unwrap(), 41);
1789    }
1790
1791    #[test]
1792    fn swap_remove_front() {
1793        let mut q: Deque<i32, 4> = Deque::new();
1794        q.push_back(40).unwrap();
1795        q.push_back(41).unwrap();
1796        q.push_back(42).unwrap();
1797        q.push_back(43).unwrap();
1798
1799        assert_eq!(q.swap_remove_front(2), Some(42));
1800        assert_eq!(q.swap_remove_front(1), Some(40));
1801        assert_eq!(q.swap_remove_front(0), Some(41));
1802        assert_eq!(q.swap_remove_front(1), None);
1803        assert_eq!(q.swap_remove_front(4), None);
1804        assert_eq!(q.swap_remove_front(6), None);
1805        assert_eq!(q.swap_remove_front(0), Some(43));
1806    }
1807
1808    #[test]
1809    fn swap_remove_back() {
1810        let mut q: Deque<i32, 4> = Deque::new();
1811        q.push_back(40).unwrap();
1812        q.push_back(41).unwrap();
1813        q.push_back(42).unwrap();
1814        q.push_back(43).unwrap();
1815        q.pop_front().unwrap();
1816        q.push_back(44).unwrap();
1817
1818        assert_eq!(q.swap_remove_back(1), Some(42));
1819        assert_eq!(q.swap_remove_front(1), Some(44));
1820        assert_eq!(q.swap_remove_front(0), Some(41));
1821        assert_eq!(q.swap_remove_front(1), None);
1822        assert_eq!(q.swap_remove_front(4), None);
1823        assert_eq!(q.swap_remove_front(6), None);
1824        assert_eq!(q.swap_remove_front(0), Some(43));
1825    }
1826
1827    #[test]
1828    #[should_panic = "i < len"]
1829    fn swap_i_out_of_bounds() {
1830        let mut q: Deque<i32, 4> = Deque::new();
1831        q.push_back(40).unwrap();
1832        q.push_back(41).unwrap();
1833        q.push_back(42).unwrap();
1834        q.pop_front().unwrap();
1835        q.swap(2, 0);
1836    }
1837
1838    #[test]
1839    #[should_panic = "j < len"]
1840    fn swap_j_out_of_bounds() {
1841        let mut q: Deque<i32, 4> = Deque::new();
1842        q.push_back(40).unwrap();
1843        q.push_back(41).unwrap();
1844        q.push_back(42).unwrap();
1845        q.pop_front().unwrap();
1846        q.swap(0, 2);
1847    }
1848
1849    #[test]
1850    fn equality() {
1851        let mut a: Deque<i32, 7> = Deque::new();
1852        let mut b: Deque<i32, 7> = Deque::new();
1853
1854        assert_eq!(a, b);
1855
1856        a.push_back(1).unwrap();
1857        a.push_back(2).unwrap();
1858        a.push_back(3).unwrap();
1859
1860        assert_ne!(a, b);
1861
1862        b.push_back(1).unwrap();
1863        b.push_back(2).unwrap();
1864        b.push_back(3).unwrap();
1865
1866        assert_eq!(a, b);
1867
1868        a.push_back(1).unwrap();
1869        a.push_back(2).unwrap();
1870        a.push_back(3).unwrap();
1871
1872        assert_ne!(a, b);
1873
1874        b.push_front(3).unwrap();
1875        b.push_front(2).unwrap();
1876        b.push_front(1).unwrap();
1877
1878        assert_eq!(a, b);
1879
1880        a.push_back(4).unwrap();
1881        b.push_back(4).unwrap();
1882
1883        assert_eq!(a, b);
1884
1885        a.clear();
1886        b.clear();
1887
1888        a.push_back(1).unwrap();
1889        a.push_back(2).unwrap();
1890        a.push_back(3).unwrap();
1891        a.push_front(3).unwrap();
1892        a.push_front(2).unwrap();
1893        a.push_front(1).unwrap();
1894
1895        b.push_back(2).unwrap();
1896        b.push_back(3).unwrap();
1897        b.push_back(1).unwrap();
1898        b.push_back(2).unwrap();
1899        b.push_back(3).unwrap();
1900        b.push_front(1).unwrap();
1901
1902        assert_eq!(a, b);
1903    }
1904
1905    #[test]
1906    fn try_from_array() {
1907        // Array is too big error.
1908        assert!(matches!(
1909            Deque::<u8, 3>::try_from([1, 2, 3, 4]),
1910            Err((CapacityError, [1, 2, 3, 4]))
1911        ));
1912
1913        // Array is at limit.
1914        let deq1 = Deque::<u8, 3>::try_from([1, 2, 3]).unwrap();
1915        let mut deq2 = Deque::<u8, 3>::new();
1916        deq2.push_back(1).unwrap();
1917        deq2.push_back(2).unwrap();
1918        deq2.push_back(3).unwrap();
1919        assert!(deq1.is_full());
1920        assert_eq!(deq1, deq2);
1921
1922        // Array is under limit.
1923        let deq1 = Deque::<u8, 8>::try_from([1, 2, 3, 4]).unwrap();
1924        let mut deq2 = Deque::<u8, 8>::new();
1925        deq2.push_back(1).unwrap();
1926        deq2.push_back(2).unwrap();
1927        deq2.push_back(3).unwrap();
1928        deq2.push_back(4).unwrap();
1929
1930        assert!(!deq1.is_full());
1931        assert_eq!(deq1, deq2);
1932    }
1933
1934    #[test]
1935    fn try_from_array_with_zst() {
1936        #[derive(Debug, PartialEq, Copy, Clone)]
1937        struct ZeroSizedType;
1938
1939        // Test with ZST (zero-sized type)
1940        let deq1 =
1941            Deque::<ZeroSizedType, 5>::try_from([ZeroSizedType, ZeroSizedType, ZeroSizedType])
1942                .unwrap();
1943        let mut deq2 = Deque::<ZeroSizedType, 5>::new();
1944        deq2.push_back(ZeroSizedType).unwrap();
1945        deq2.push_back(ZeroSizedType).unwrap();
1946        deq2.push_back(ZeroSizedType).unwrap();
1947
1948        assert_eq!(deq1, deq2);
1949        assert_eq!(deq1.len(), 3);
1950    }
1951
1952    #[test]
1953    fn try_from_array_drop() {
1954        droppable!();
1955
1956        // Array is over limit.
1957        {
1958            let _result = Deque::<Droppable, 2>::try_from([
1959                Droppable::new(),
1960                Droppable::new(),
1961                Droppable::new(),
1962            ]);
1963        }
1964
1965        assert_eq!(Droppable::count(), 0);
1966
1967        // Array is at limit.
1968        {
1969            let _result = Deque::<Droppable, 3>::try_from([
1970                Droppable::new(),
1971                Droppable::new(),
1972                Droppable::new(),
1973            ]);
1974        }
1975
1976        assert_eq!(Droppable::count(), 0);
1977
1978        // Array is under limit.
1979        {
1980            let _result = Deque::<Droppable, 4>::try_from([
1981                Droppable::new(),
1982                Droppable::new(),
1983                Droppable::new(),
1984            ]);
1985        }
1986
1987        assert_eq!(Droppable::count(), 0);
1988    }
1989
1990    #[test]
1991    #[cfg(feature = "zeroize")]
1992    fn test_deque_zeroize() {
1993        use zeroize::Zeroize;
1994
1995        let mut deque = Deque::<u8, 16>::new();
1996
1997        for i in 1..=8 {
1998            deque.push_back(i).unwrap();
1999        }
2000        for i in 9..=16 {
2001            deque.push_front(i).unwrap();
2002        }
2003
2004        assert_eq!(deque.len(), 16);
2005        assert_eq!(deque.front(), Some(&16));
2006        assert_eq!(deque.back(), Some(&8));
2007
2008        // zeroized using Vec's implementation
2009        deque.zeroize();
2010
2011        assert_eq!(deque.len(), 0);
2012        assert!(deque.is_empty());
2013    }
2014
2015    // Checking that no invalid destructors are called with empty Deques
2016    #[test]
2017    fn truncate_empty() {
2018        droppable!();
2019
2020        const LEN: usize = 1;
2021        let mut tester: Deque<_, LEN> = Deque::new();
2022
2023        // Truncate to 0 from 0
2024        tester.truncate(0);
2025        assert_eq!(tester.len(), 0);
2026        assert_eq!(Droppable::count(), 0);
2027
2028        // Truncate to 123 from 0 (thus clamping back down to 0)
2029        tester.truncate(123);
2030        assert_eq!(tester.len(), 0);
2031        assert_eq!(Droppable::count(), 0);
2032
2033        // Ensure state is still valid by pushing one element in and then truncating again
2034        assert!(tester.push_front(Droppable::new()).is_ok());
2035        assert_eq!(tester.len(), 1);
2036        assert_eq!(Droppable::count(), 1);
2037
2038        // Truncate to 0 from 1
2039        tester.truncate(0);
2040        assert_eq!(tester.len(), 0);
2041        assert_eq!(Droppable::count(), 0);
2042    }
2043
2044    // Testing truncation with contiguous Deques
2045    #[test]
2046    fn truncate_contiguous() {
2047        droppable!();
2048
2049        fn slice_lengths<T>(slices: (&[T], &[T])) -> (usize, usize) {
2050            let (a, b) = slices;
2051            (a.len(), b.len())
2052        }
2053
2054        const LEN: usize = 20;
2055        let mut tester: Deque<_, LEN> = Deque::new();
2056
2057        // Filling from front.
2058        for _ in 0..5 {
2059            assert!(tester.push_front(Droppable::new()).is_ok());
2060        }
2061
2062        // Truncating past the elements present, no change.
2063        tester.truncate(10);
2064        let lens = slice_lengths(tester.as_slices());
2065        assert_eq!(lens, (5, 0));
2066        assert_eq!(Droppable::count(), 5);
2067
2068        // Truncating equal to elements present, no change.
2069        tester.truncate(5);
2070        let lens = slice_lengths(tester.as_slices());
2071        assert_eq!(lens, (5, 0));
2072        assert_eq!(Droppable::count(), 5);
2073
2074        // Truncating to empty.
2075        tester.truncate(0);
2076        assert_eq!(tester.len(), 0);
2077        assert_eq!(Droppable::count(), 0);
2078
2079        // Refill from front.
2080        for _ in 0..5 {
2081            assert!(tester.push_front(Droppable::new()).is_ok());
2082        }
2083
2084        let lens = slice_lengths(tester.as_slices());
2085        assert_eq!(lens, (5, 0));
2086        assert_eq!(Droppable::count(), 5);
2087
2088        // Truncate into the middle of elements.
2089        tester.truncate(3);
2090        let lens = slice_lengths(tester.as_slices());
2091        assert_eq!(lens, (3, 0));
2092        assert_eq!(Droppable::count(), 3);
2093
2094        // Truncating to empty.
2095        tester.truncate(0);
2096        assert_eq!(tester.len(), 0);
2097        assert_eq!(Droppable::count(), 0);
2098
2099        // Resetting cursors.
2100        tester.clear();
2101
2102        // Filling from back...
2103        for _ in 0..5 {
2104            assert!(tester.push_back(Droppable::new()).is_ok());
2105        }
2106
2107        tester.truncate(10);
2108        let lens = slice_lengths(tester.as_slices());
2109        assert_eq!(lens, (5, 0));
2110        assert_eq!(Droppable::count(), 5);
2111
2112        tester.truncate(5);
2113        let lens = slice_lengths(tester.as_slices());
2114        assert_eq!(lens, (5, 0));
2115        assert_eq!(Droppable::count(), 5);
2116
2117        tester.truncate(0);
2118        assert_eq!(tester.len(), 0);
2119        assert_eq!(Droppable::count(), 0);
2120
2121        for _ in 0..5 {
2122            assert!(tester.push_back(Droppable::new()).is_ok());
2123        }
2124
2125        let lens = slice_lengths(tester.as_slices());
2126        assert_eq!(lens, (5, 0));
2127        assert_eq!(Droppable::count(), 5);
2128
2129        tester.truncate(3);
2130        let lens = slice_lengths(tester.as_slices());
2131        assert_eq!(lens, (3, 0));
2132        assert_eq!(Droppable::count(), 3);
2133
2134        tester.truncate(0);
2135        assert_eq!(tester.len(), 0);
2136        assert_eq!(Droppable::count(), 0);
2137    }
2138
2139    // Testing truncation with non-contiguous Deques
2140    #[test]
2141    fn truncate_non_contiguous() {
2142        const LEN: usize = 20;
2143        let mut tester: Deque<u8, LEN> = Deque::new();
2144
2145        // Filling non-contiguously.
2146        //
2147        // Expecting [3, 2, 1, 1, 2, 3]
2148        for x in 1..=3 {
2149            assert!(tester.push_front(x).is_ok());
2150        }
2151        for y in 1..=3 {
2152            assert!(tester.push_back(y).is_ok());
2153        }
2154
2155        // Truncating past the elements present, no change.
2156        tester.truncate(10);
2157        assert_eq!(tester.as_slices(), (&[3, 2, 1][..], &[1, 2, 3][..]));
2158        println!("{} {}", tester.front, tester.back);
2159        // Truncating equal to elements present, no change.
2160        tester.truncate(6);
2161        assert_eq!(tester.as_slices(), (&[3, 2, 1][..], &[1, 2, 3][..]));
2162
2163        // Truncating to empty.
2164        tester.truncate(0);
2165        assert_eq!(tester.as_slices(), (&[][..], &[][..]));
2166
2167        // Resetting cursors.
2168        tester.clear();
2169
2170        // Refilling.
2171        for x in 1..=3 {
2172            assert!(tester.push_front(x).is_ok());
2173        }
2174        for y in 1..=3 {
2175            assert!(tester.push_back(y).is_ok());
2176        }
2177
2178        assert_eq!(tester.as_slices(), (&[3, 2, 1][..], &[1, 2, 3][..]));
2179
2180        // Truncating only part of back, retaining front and part of back.
2181        tester.truncate(5);
2182        assert_eq!(tester.as_slices(), (&[3, 2, 1][..], &[1, 2][..]));
2183
2184        // Replacing the truncated element.
2185        assert!(tester.push_back(3).is_ok());
2186        assert_eq!(tester.as_slices(), (&[3, 2, 1][..], &[1, 2, 3][..]));
2187
2188        // Truncating away all of back's contents, but retaining all of front's contents.
2189        tester.truncate(3);
2190        assert_eq!(tester.as_slices(), (&[3, 2, 1][..], &[][..]));
2191
2192        // Replacing the truncated elements.
2193        for y in 1..=3 {
2194            assert!(tester.push_back(y).is_ok());
2195        }
2196        assert_eq!(tester.as_slices(), (&[3, 2, 1][..], &[1, 2, 3][..]));
2197
2198        // Truncating into front, thus also dropping all of back.
2199        tester.truncate(2);
2200        assert_eq!(tester.as_slices(), (&[3, 2][..], &[][..]));
2201
2202        // Truncating to empty.
2203        tester.truncate(0);
2204        assert_eq!(tester.as_slices(), (&[][..], &[][..]));
2205
2206        // Should remain empty.
2207        tester.truncate(123);
2208        assert_eq!(tester.as_slices(), (&[][..], &[][..]));
2209    }
2210
2211    // Tests that each element's destructor is called when being truncated.
2212    #[test]
2213    fn truncate_drop_count() {
2214        droppable!();
2215
2216        const LEN: usize = 20;
2217        const TRUNC: usize = 3;
2218        for push_front_amt in 0..=LEN {
2219            let mut tester: Deque<_, LEN> = Deque::new();
2220            for index in 0..LEN {
2221                if index < push_front_amt {
2222                    assert!(
2223                        tester.push_front(Droppable::new()).is_ok(),
2224                        "deque must have room for all {LEN} entries"
2225                    );
2226                } else {
2227                    assert!(
2228                        tester.push_back(Droppable::new()).is_ok(),
2229                        "deque must have room for all {LEN} entries"
2230                    );
2231                }
2232            }
2233
2234            assert_eq!(Droppable::count(), LEN as i32);
2235
2236            tester.truncate(TRUNC);
2237            assert_eq!(tester.len(), TRUNC);
2238            assert_eq!(Droppable::count(), TRUNC as i32);
2239
2240            tester.truncate(0);
2241            assert_eq!(tester.len(), 0);
2242            assert_eq!(Droppable::count(), 0);
2243        }
2244    }
2245
2246    #[test]
2247    fn retain() {
2248        droppable!();
2249
2250        const LEN: usize = 20;
2251        for push_front_amt in 0..=LEN {
2252            let mut tester: Deque<_, LEN> = Deque::new();
2253            for index in 0..LEN {
2254                if index < push_front_amt {
2255                    assert!(tester.push_front((index, Droppable::new())).is_ok());
2256                } else {
2257                    assert!(tester.push_back((index, Droppable::new())).is_ok());
2258                }
2259            }
2260            assert_eq!(Droppable::count(), LEN as i32);
2261
2262            tester.retain(|(x, _)| *x >= 10);
2263
2264            assert_eq!(tester.len(), 10);
2265            assert_eq!(Droppable::count(), 10);
2266        }
2267    }
2268
2269    #[test]
2270    fn test_pop_if() {
2271        let mut deq: Deque<i32, 5> = [0, 1, 2, 3, 4].try_into().unwrap();
2272        let pred = |x: &mut i32| *x % 2 == 0;
2273
2274        assert_eq!(deq.pop_front_if(pred), Some(0));
2275        assert_eq!(deq, Deque::<i32, 5>::try_from([1, 2, 3, 4]).unwrap());
2276
2277        assert_eq!(deq.pop_front_if(pred), None);
2278        assert_eq!(deq, Deque::<i32, 5>::try_from([1, 2, 3, 4]).unwrap());
2279
2280        assert_eq!(deq.pop_back_if(pred), Some(4));
2281        assert_eq!(deq, Deque::<i32, 5>::try_from([1, 2, 3]).unwrap());
2282
2283        assert_eq!(deq.pop_back_if(pred), None);
2284        assert_eq!(deq, Deque::<i32, 5>::try_from([1, 2, 3]).unwrap());
2285    }
2286
2287    #[test]
2288    fn test_pop_if_empty() {
2289        let mut deq = Deque::<i32, 5>::new();
2290        assert_eq!(deq.pop_front_if(|_| true), None);
2291        assert_eq!(deq.pop_back_if(|_| true), None);
2292        assert!(deq.is_empty());
2293    }
2294
2295    #[test]
2296    fn test_use_after_free_clear() {
2297        // See https://github.com/rust-embedded/heapless/issues/646
2298
2299        static COUNT: AtomicI32 = AtomicI32::new(0);
2300
2301        #[derive(Debug)]
2302        #[allow(unused)]
2303        struct Dropper();
2304
2305        impl Dropper {
2306            fn new() -> Self {
2307                COUNT.fetch_add(1, Relaxed);
2308                Self()
2309            }
2310            fn count() -> i32 {
2311                COUNT.load(Relaxed)
2312            }
2313        }
2314        impl Drop for Dropper {
2315            fn drop(&mut self) {
2316                COUNT.fetch_sub(1, Relaxed);
2317                panic!("Testing  panicking");
2318            }
2319        }
2320
2321        let mut deque = Deque::<Dropper, 5>::new();
2322        deque.push_back(Dropper::new()).unwrap();
2323        // Don't panic on dropping of the deque
2324        let mut deque = ManuallyDrop::new(deque);
2325        let mut unwind_safe_deque = AssertUnwindSafe(&mut deque);
2326
2327        catch_unwind(move || unwind_safe_deque.clear()).unwrap_err();
2328        assert_eq!(deque.len(), 0);
2329        deque.clear();
2330        assert_eq!(Dropper::count(), 0);
2331    }
2332}