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 core::cmp::Ordering;
37use core::fmt;
38use core::iter::FusedIterator;
39use core::marker::PhantomData;
40use core::mem::MaybeUninit;
41use core::{ptr, slice};
42
43use crate::vec::{OwnedVecStorage, VecStorage, VecStorageInner, ViewVecStorage};
44
45/// Base struct for [`Deque`] and [`DequeView`], generic over the [`VecStorage`].
46///
47/// In most cases you should use [`Deque`] or [`DequeView`] directly. Only use this
48/// struct if you want to write code that's generic over both.
49pub struct DequeInner<T, S: VecStorage<T> + ?Sized> {
50    // This phantomdata is required because otherwise rustc thinks that `T` is not used
51    phantom: PhantomData<T>,
52    /// Front index. Always 0..=(N-1)
53    front: usize,
54    /// Back index. Always 0..=(N-1).
55    back: usize,
56
57    /// Used to distinguish "empty" and "full" cases when `front == back`.
58    /// May only be `true` if `front == back`, always `false` otherwise.
59    full: bool,
60    buffer: S,
61}
62
63/// A fixed capacity double-ended queue.
64///
65/// # Examples
66///
67/// ```
68/// use heapless::Deque;
69///
70/// // A deque with a fixed capacity of 8 elements allocated on the stack
71/// let mut deque = Deque::<_, 8>::new();
72///
73/// // You can use it as a good old FIFO queue.
74/// deque.push_back(1);
75/// deque.push_back(2);
76/// assert_eq!(deque.len(), 2);
77///
78/// assert_eq!(deque.pop_front(), Some(1));
79/// assert_eq!(deque.pop_front(), Some(2));
80/// assert_eq!(deque.len(), 0);
81///
82/// // Deque is double-ended, you can push and pop from the front and back.
83/// deque.push_back(1);
84/// deque.push_front(2);
85/// deque.push_back(3);
86/// deque.push_front(4);
87/// assert_eq!(deque.pop_front(), Some(4));
88/// assert_eq!(deque.pop_front(), Some(2));
89/// assert_eq!(deque.pop_front(), Some(1));
90/// assert_eq!(deque.pop_front(), Some(3));
91///
92/// // You can iterate it, yielding all the elements front-to-back.
93/// for x in &deque {
94///     println!("{}", x);
95/// }
96/// ```
97pub type Deque<T, const N: usize> = DequeInner<T, OwnedVecStorage<T, N>>;
98
99/// A double-ended queue with dynamic capacity.
100///
101/// # Examples
102///
103/// ```
104/// use heapless::deque::{Deque, DequeView};
105///
106/// // A deque with a fixed capacity of 8 elements allocated on the stack
107/// let mut deque_buf = Deque::<_, 8>::new();
108///
109/// // A DequeView can be obtained through unsized coercion of a `Deque`
110/// let deque: &mut DequeView<_> = &mut deque_buf;
111///
112/// // You can use it as a good old FIFO queue.
113/// deque.push_back(1);
114/// deque.push_back(2);
115/// assert_eq!(deque.storage_len(), 2);
116///
117/// assert_eq!(deque.pop_front(), Some(1));
118/// assert_eq!(deque.pop_front(), Some(2));
119/// assert_eq!(deque.storage_len(), 0);
120///
121/// // DequeView is double-ended, you can push and pop from the front and back.
122/// deque.push_back(1);
123/// deque.push_front(2);
124/// deque.push_back(3);
125/// deque.push_front(4);
126/// assert_eq!(deque.pop_front(), Some(4));
127/// assert_eq!(deque.pop_front(), Some(2));
128/// assert_eq!(deque.pop_front(), Some(1));
129/// assert_eq!(deque.pop_front(), Some(3));
130///
131/// // You can iterate it, yielding all the elements front-to-back.
132/// for x in deque {
133///     println!("{}", x);
134/// }
135/// ```
136pub type DequeView<T> = DequeInner<T, ViewVecStorage<T>>;
137
138impl<T, const N: usize> Deque<T, N> {
139    const INIT: MaybeUninit<T> = MaybeUninit::uninit();
140
141    /// Constructs a new, empty deque with a fixed capacity of `N`
142    ///
143    /// # Examples
144    ///
145    /// ```
146    /// use heapless::Deque;
147    ///
148    /// // allocate the deque on the stack
149    /// let mut x: Deque<u8, 16> = Deque::new();
150    ///
151    /// // allocate the deque in a static variable
152    /// static mut X: Deque<u8, 16> = Deque::new();
153    /// ```
154    pub const fn new() -> Self {
155        const {
156            assert!(N > 0);
157        }
158
159        Self {
160            phantom: PhantomData,
161            buffer: VecStorageInner {
162                buffer: [Self::INIT; N],
163            },
164            front: 0,
165            back: 0,
166            full: false,
167        }
168    }
169
170    /// Returns the maximum number of elements the deque can hold.
171    ///
172    /// This method is not available on a `DequeView`, use [`storage_capacity`](DequeInner::storage_capacity) instead.
173    pub const fn capacity(&self) -> usize {
174        N
175    }
176
177    /// Returns the number of elements currently in the deque.
178    ///
179    /// This method is not available on a `DequeView`, use [`storage_len`](DequeInner::storage_len) instead.
180    pub const fn len(&self) -> usize {
181        if self.full {
182            N
183        } else if self.back < self.front {
184            self.back + N - self.front
185        } else {
186            self.back - self.front
187        }
188    }
189}
190
191impl<T, S: VecStorage<T> + ?Sized> DequeInner<T, S> {
192    /// Get a reference to the `Deque`, erasing the `N` const-generic.
193    pub fn as_view(&self) -> &DequeView<T> {
194        S::as_deque_view(self)
195    }
196
197    /// Get a mutable reference to the `Deque`, erasing the `N` const-generic.
198    pub fn as_mut_view(&mut self) -> &mut DequeView<T> {
199        S::as_deque_view_mut(self)
200    }
201
202    /// Returns the maximum number of elements the deque can hold.
203    pub fn storage_capacity(&self) -> usize {
204        self.buffer.borrow().len()
205    }
206
207    fn increment(&self, i: usize) -> usize {
208        if i + 1 == self.storage_capacity() {
209            0
210        } else {
211            i + 1
212        }
213    }
214
215    fn decrement(&self, i: usize) -> usize {
216        if i == 0 {
217            self.storage_capacity() - 1
218        } else {
219            i - 1
220        }
221    }
222
223    /// Returns the number of elements currently in the deque.
224    pub fn storage_len(&self) -> usize {
225        if self.full {
226            self.storage_capacity()
227        } else if self.back < self.front {
228            self.back + self.storage_capacity() - self.front
229        } else {
230            self.back - self.front
231        }
232    }
233
234    /// Clears the deque, removing all values.
235    pub fn clear(&mut self) {
236        // safety: we're immediately setting a consistent empty state.
237        unsafe { self.drop_contents() }
238        self.front = 0;
239        self.back = 0;
240        self.full = false;
241    }
242
243    /// Drop all items in the `Deque`, leaving the state `back/front/full` unmodified.
244    ///
245    /// safety: leaves the `Deque` in an inconsistent state, so can cause duplicate drops.
246    unsafe fn drop_contents(&mut self) {
247        // We drop each element used in the deque by turning into a &mut[T]
248        let (a, b) = self.as_mut_slices();
249        ptr::drop_in_place(a);
250        ptr::drop_in_place(b);
251    }
252
253    /// Returns whether the deque is empty.
254    pub fn is_empty(&self) -> bool {
255        self.front == self.back && !self.full
256    }
257
258    /// Returns whether the deque is full (i.e. if `len() == capacity()`.
259    pub fn is_full(&self) -> bool {
260        self.full
261    }
262
263    /// Returns a pair of slices which contain, in order, the contents of the `Deque`.
264    pub fn as_slices(&self) -> (&[T], &[T]) {
265        // NOTE(unsafe) avoid bound checks in the slicing operation
266        unsafe {
267            if self.is_empty() {
268                (&[], &[])
269            } else if self.back <= self.front {
270                (
271                    slice::from_raw_parts(
272                        self.buffer.borrow().as_ptr().add(self.front).cast::<T>(),
273                        self.storage_capacity() - self.front,
274                    ),
275                    slice::from_raw_parts(self.buffer.borrow().as_ptr().cast::<T>(), self.back),
276                )
277            } else {
278                (
279                    slice::from_raw_parts(
280                        self.buffer.borrow().as_ptr().add(self.front).cast::<T>(),
281                        self.back - self.front,
282                    ),
283                    &[],
284                )
285            }
286        }
287    }
288
289    /// Returns a pair of mutable slices which contain, in order, the contents of the `Deque`.
290    pub fn as_mut_slices(&mut self) -> (&mut [T], &mut [T]) {
291        let ptr = self.buffer.borrow_mut().as_mut_ptr();
292
293        // NOTE(unsafe) avoid bound checks in the slicing operation
294        unsafe {
295            if self.is_empty() {
296                (&mut [], &mut [])
297            } else if self.back <= self.front {
298                (
299                    slice::from_raw_parts_mut(
300                        ptr.add(self.front).cast::<T>(),
301                        self.storage_capacity() - self.front,
302                    ),
303                    slice::from_raw_parts_mut(ptr.cast::<T>(), self.back),
304                )
305            } else {
306                (
307                    slice::from_raw_parts_mut(
308                        ptr.add(self.front).cast::<T>(),
309                        self.back - self.front,
310                    ),
311                    &mut [],
312                )
313            }
314        }
315    }
316
317    #[inline]
318    fn is_contiguous(&self) -> bool {
319        self.front <= self.storage_capacity() - self.storage_len()
320    }
321
322    /// Rearranges the internal storage of the [`Deque`] to make it into a contiguous slice,
323    /// which is returned.
324    ///
325    /// This does **not** change the order of the elements in the deque.
326    /// The returned slice can then be used to perform contiguous slice operations on the deque.
327    ///
328    /// After calling this method, subsequent [`as_slices`] and [`as_mut_slices`] calls will return
329    /// a single contiguous slice.
330    ///
331    /// [`as_slices`]: Deque::as_slices
332    /// [`as_mut_slices`]: Deque::as_mut_slices
333    ///
334    /// # Examples
335    /// Sorting a deque:
336    /// ```
337    /// use heapless::Deque;
338    ///
339    /// let mut buf = Deque::<_, 4>::new();
340    /// buf.push_back(2).unwrap();
341    /// buf.push_back(1).unwrap();
342    /// buf.push_back(3).unwrap();
343    ///
344    /// // Sort the deque
345    /// buf.make_contiguous().sort();
346    /// assert_eq!(buf.as_slices(), (&[1, 2, 3][..], &[][..]));
347    ///
348    /// // Sort the deque in reverse
349    /// buf.make_contiguous().sort_by(|a, b| b.cmp(a));
350    /// assert_eq!(buf.as_slices(), (&[3, 2, 1][..], &[][..]));
351    /// ```
352    pub fn make_contiguous(&mut self) -> &mut [T] {
353        if self.is_contiguous() {
354            return unsafe {
355                slice::from_raw_parts_mut(
356                    self.buffer.borrow_mut().as_mut_ptr().add(self.front).cast(),
357                    self.storage_len(),
358                )
359            };
360        }
361
362        let buffer_ptr: *mut T = self.buffer.borrow_mut().as_mut_ptr().cast();
363
364        let len = self.storage_len();
365
366        let free = self.storage_capacity() - len;
367        let front_len = self.storage_capacity() - self.front;
368        let back = len - front_len;
369        let back_len = back;
370
371        if free >= front_len {
372            // there is enough free space to copy the head in one go,
373            // this means that we first shift the tail backwards, and then
374            // copy the head to the correct position.
375            //
376            // from: DEFGH....ABC
377            // to:   ABCDEFGH....
378            unsafe {
379                ptr::copy(buffer_ptr, buffer_ptr.add(front_len), back_len);
380                // ...DEFGH.ABC
381                ptr::copy_nonoverlapping(buffer_ptr.add(self.front), buffer_ptr, front_len);
382                // ABCDEFGH....
383            }
384
385            self.front = 0;
386            self.back = len;
387        } else if free >= back_len {
388            // there is enough free space to copy the tail in one go,
389            // this means that we first shift the head forwards, and then
390            // copy the tail to the correct position.
391            //
392            // from: FGH....ABCDE
393            // to:   ...ABCDEFGH.
394            unsafe {
395                ptr::copy(
396                    buffer_ptr.add(self.front),
397                    buffer_ptr.add(self.back),
398                    front_len,
399                );
400                // FGHABCDE....
401                ptr::copy_nonoverlapping(
402                    buffer_ptr,
403                    buffer_ptr.add(self.back + front_len),
404                    back_len,
405                );
406                // ...ABCDEFGH.
407            }
408
409            self.front = back;
410            self.back = 0;
411        } else {
412            // `free` is smaller than both `head_len` and `tail_len`.
413            // the general algorithm for this first moves the slices
414            // right next to each other and then uses `slice::rotate`
415            // to rotate them into place:
416            //
417            // initially:   HIJK..ABCDEFG
418            // step 1:      ..HIJKABCDEFG
419            // step 2:      ..ABCDEFGHIJK
420            //
421            // or:
422            //
423            // initially:   FGHIJK..ABCDE
424            // step 1:      FGHIJKABCDE..
425            // step 2:      ABCDEFGHIJK..
426
427            // pick the shorter of the 2 slices to reduce the amount
428            // of memory that needs to be moved around.
429            if front_len > back_len {
430                // tail is shorter, so:
431                //  1. copy tail forwards
432                //  2. rotate used part of the buffer
433                //  3. update head to point to the new beginning (which is just `free`)
434                unsafe {
435                    // if there is no free space in the buffer, then the slices are already
436                    // right next to each other and we don't need to move any memory.
437                    if free != 0 {
438                        // because we only move the tail forward as much as there's free space
439                        // behind it, we don't overwrite any elements of the head slice, and
440                        // the slices end up right next to each other.
441                        ptr::copy(buffer_ptr, buffer_ptr.add(free), back_len);
442                    }
443
444                    // We just copied the tail right next to the head slice,
445                    // so all of the elements in the range are initialized
446                    let slice: &mut [T] = slice::from_raw_parts_mut(
447                        buffer_ptr.add(free),
448                        self.storage_capacity() - free,
449                    );
450
451                    // because the deque wasn't contiguous, we know that `tail_len < self.len == slice.len()`,
452                    // so this will never panic.
453                    slice.rotate_left(back_len);
454
455                    // the used part of the buffer now is `free..self.capacity()`, so set
456                    // `head` to the beginning of that range.
457                    self.front = free;
458                    self.back = 0;
459                }
460            } else {
461                // head is shorter so:
462                //  1. copy head backwards
463                //  2. rotate used part of the buffer
464                //  3. update head to point to the new beginning (which is the beginning of the buffer)
465
466                unsafe {
467                    // if there is no free space in the buffer, then the slices are already
468                    // right next to each other and we don't need to move any memory.
469                    if free != 0 {
470                        // copy the head slice to lie right behind the tail slice.
471                        ptr::copy(
472                            buffer_ptr.add(self.front),
473                            buffer_ptr.add(back_len),
474                            front_len,
475                        );
476                    }
477
478                    // because we copied the head slice so that both slices lie right
479                    // next to each other, all the elements in the range are initialized.
480                    let slice: &mut [T] = slice::from_raw_parts_mut(buffer_ptr, len);
481
482                    // because the deque wasn't contiguous, we know that `head_len < self.len == slice.len()`
483                    // so this will never panic.
484                    slice.rotate_right(front_len);
485
486                    // the used part of the buffer now is `0..self.len`, so set
487                    // `head` to the beginning of that range.
488                    self.front = 0;
489                    self.back = len;
490                }
491            }
492        }
493
494        unsafe { slice::from_raw_parts_mut(buffer_ptr.add(self.front), len) }
495    }
496
497    /// Provides a reference to the front element, or None if the `Deque` is empty.
498    pub fn front(&self) -> Option<&T> {
499        if self.is_empty() {
500            None
501        } else {
502            Some(unsafe { &*self.buffer.borrow().get_unchecked(self.front).as_ptr() })
503        }
504    }
505
506    /// Provides a mutable reference to the front element, or None if the `Deque` is empty.
507    pub fn front_mut(&mut self) -> Option<&mut T> {
508        if self.is_empty() {
509            None
510        } else {
511            Some(unsafe {
512                &mut *self
513                    .buffer
514                    .borrow_mut()
515                    .get_unchecked_mut(self.front)
516                    .as_mut_ptr()
517            })
518        }
519    }
520
521    /// Provides a reference to the back element, or None if the `Deque` is empty.
522    pub fn back(&self) -> Option<&T> {
523        if self.is_empty() {
524            None
525        } else {
526            let index = self.decrement(self.back);
527            Some(unsafe { &*self.buffer.borrow().get_unchecked(index).as_ptr() })
528        }
529    }
530
531    /// Provides a mutable reference to the back element, or None if the `Deque` is empty.
532    pub fn back_mut(&mut self) -> Option<&mut T> {
533        if self.is_empty() {
534            None
535        } else {
536            let index = self.decrement(self.back);
537            Some(unsafe {
538                &mut *self
539                    .buffer
540                    .borrow_mut()
541                    .get_unchecked_mut(index)
542                    .as_mut_ptr()
543            })
544        }
545    }
546
547    /// Removes the item from the front of the deque and returns it, or `None` if it's empty
548    pub fn pop_front(&mut self) -> Option<T> {
549        if self.is_empty() {
550            None
551        } else {
552            Some(unsafe { self.pop_front_unchecked() })
553        }
554    }
555
556    /// Removes the item from the back of the deque and returns it, or `None` if it's empty
557    pub fn pop_back(&mut self) -> Option<T> {
558        if self.is_empty() {
559            None
560        } else {
561            Some(unsafe { self.pop_back_unchecked() })
562        }
563    }
564
565    /// Appends an `item` to the front of the deque
566    ///
567    /// Returns back the `item` if the deque is full
568    pub fn push_front(&mut self, item: T) -> Result<(), T> {
569        if self.is_full() {
570            Err(item)
571        } else {
572            unsafe { self.push_front_unchecked(item) }
573            Ok(())
574        }
575    }
576
577    /// Appends an `item` to the back of the deque
578    ///
579    /// Returns back the `item` if the deque is full
580    pub fn push_back(&mut self, item: T) -> Result<(), T> {
581        if self.is_full() {
582            Err(item)
583        } else {
584            unsafe { self.push_back_unchecked(item) }
585            Ok(())
586        }
587    }
588
589    /// Removes an item from the front of the deque and returns it, without checking that the deque
590    /// is not empty
591    ///
592    /// # Safety
593    ///
594    /// It's undefined behavior to call this on an empty deque
595    pub unsafe fn pop_front_unchecked(&mut self) -> T {
596        debug_assert!(!self.is_empty());
597
598        let index = self.front;
599        self.full = false;
600        self.front = self.increment(self.front);
601        self.buffer
602            .borrow_mut()
603            .get_unchecked_mut(index)
604            .as_ptr()
605            .read()
606    }
607
608    /// Removes an item from the back of the deque and returns it, without checking that the deque
609    /// is not empty
610    ///
611    /// # Safety
612    ///
613    /// It's undefined behavior to call this on an empty deque
614    pub unsafe fn pop_back_unchecked(&mut self) -> T {
615        debug_assert!(!self.is_empty());
616
617        self.full = false;
618        self.back = self.decrement(self.back);
619        self.buffer
620            .borrow_mut()
621            .get_unchecked_mut(self.back)
622            .as_ptr()
623            .read()
624    }
625
626    /// Appends an `item` to the front of the deque
627    ///
628    /// # Safety
629    ///
630    /// This assumes the deque is not full.
631    pub unsafe fn push_front_unchecked(&mut self, item: T) {
632        debug_assert!(!self.is_full());
633
634        let index = self.decrement(self.front);
635        // NOTE: the memory slot that we are about to write to is uninitialized. We assign
636        // a `MaybeUninit` to avoid running `T`'s destructor on the uninitialized memory
637        *self.buffer.borrow_mut().get_unchecked_mut(index) = MaybeUninit::new(item);
638        self.front = index;
639        if self.front == self.back {
640            self.full = true;
641        }
642    }
643
644    /// Appends an `item` to the back of the deque
645    ///
646    /// # Safety
647    ///
648    /// This assumes the deque is not full.
649    pub unsafe fn push_back_unchecked(&mut self, item: T) {
650        debug_assert!(!self.is_full());
651
652        // NOTE: the memory slot that we are about to write to is uninitialized. We assign
653        // a `MaybeUninit` to avoid running `T`'s destructor on the uninitialized memory
654        *self.buffer.borrow_mut().get_unchecked_mut(self.back) = MaybeUninit::new(item);
655        self.back = self.increment(self.back);
656        if self.front == self.back {
657            self.full = true;
658        }
659    }
660
661    /// Returns a reference to the element at the given index.
662    ///
663    /// Index 0 is the front of the `Deque`.
664    pub fn get(&self, index: usize) -> Option<&T> {
665        if index < self.storage_len() {
666            let idx = self.to_physical_index(index);
667            Some(unsafe { self.buffer.borrow().get_unchecked(idx).assume_init_ref() })
668        } else {
669            None
670        }
671    }
672
673    /// Returns a mutable reference to the element at the given index.
674    ///
675    /// Index 0 is the front of the `Deque`.
676    pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
677        if index < self.storage_len() {
678            let idx = self.to_physical_index(index);
679            Some(unsafe {
680                self.buffer
681                    .borrow_mut()
682                    .get_unchecked_mut(idx)
683                    .assume_init_mut()
684            })
685        } else {
686            None
687        }
688    }
689
690    /// Returns a reference to the element at the given index without checking if it exists.
691    ///
692    /// # Safety
693    ///
694    /// The element at the given `index` must exist (i.e. `index < self.len()`).
695    pub unsafe fn get_unchecked(&self, index: usize) -> &T {
696        debug_assert!(index < self.storage_len());
697
698        let idx = self.to_physical_index(index);
699        self.buffer.borrow().get_unchecked(idx).assume_init_ref()
700    }
701
702    /// Returns a mutable reference to the element at the given index without checking if it exists.
703    ///
704    /// # Safety
705    ///
706    /// The element at the given `index` must exist (i.e. `index < self.len()`).
707    pub unsafe fn get_unchecked_mut(&mut self, index: usize) -> &mut T {
708        debug_assert!(index < self.storage_len());
709
710        let idx = self.to_physical_index(index);
711        self.buffer
712            .borrow_mut()
713            .get_unchecked_mut(idx)
714            .assume_init_mut()
715    }
716
717    /// Swaps elements at indices `i` and `j`.
718    ///
719    /// # Panics
720    ///
721    /// Panics if either `i` or `j` are out of bounds.
722    pub fn swap(&mut self, i: usize, j: usize) {
723        let len = self.storage_len();
724        assert!(i < len);
725        assert!(j < len);
726        unsafe { self.swap_unchecked(i, j) }
727    }
728
729    /// Swaps elements at indices `i` and `j` without checking that they exist.
730    ///
731    /// # Safety
732    ///
733    /// Elements at indexes `i` and `j` must exist (i.e. `i < self.len()` and `j < self.len()`).
734    pub unsafe fn swap_unchecked(&mut self, i: usize, j: usize) {
735        debug_assert!(i < self.storage_len());
736        debug_assert!(j < self.storage_len());
737        let idx_i = self.to_physical_index(i);
738        let idx_j = self.to_physical_index(j);
739
740        let buffer = self.buffer.borrow_mut();
741        let buffer_ptr = buffer.as_mut_ptr();
742        let ptr_i = buffer_ptr.add(idx_i);
743        let ptr_j = buffer_ptr.add(idx_j);
744        ptr::swap(ptr_i, ptr_j);
745    }
746
747    /// Removes an element from anywhere in the deque and returns it, replacing it with the first
748    /// element.
749    ///
750    /// This does not preserve ordering, but is *O*(1).
751    ///
752    /// Returns `None` if `index` is out of bounds.
753    ///
754    /// Element at index 0 is the front of the queue.
755    pub fn swap_remove_front(&mut self, index: usize) -> Option<T> {
756        let len = self.storage_len();
757        if len > 0 && index < len {
758            Some(unsafe {
759                self.swap_unchecked(index, 0);
760                self.pop_front_unchecked()
761            })
762        } else {
763            None
764        }
765    }
766
767    /// Removes an element from anywhere in the deque and returns it, replacing it with the last
768    /// element.
769    ///
770    /// This does not preserve ordering, but is *O*(1).
771    ///
772    /// Returns `None` if `index` is out of bounds.
773    ///
774    /// Element at index 0 is the front of the queue.
775    pub fn swap_remove_back(&mut self, index: usize) -> Option<T> {
776        let len = self.storage_len();
777        if len > 0 && index < len {
778            Some(unsafe {
779                self.swap_unchecked(index, len - 1);
780                self.pop_back_unchecked()
781            })
782        } else {
783            None
784        }
785    }
786
787    fn to_physical_index(&self, index: usize) -> usize {
788        let mut res = self.front + index;
789        if res >= self.storage_capacity() {
790            res -= self.storage_capacity();
791        }
792        res
793    }
794
795    /// Returns an iterator over the deque.
796    pub fn iter(&self) -> Iter<'_, T> {
797        let (start, end) = self.as_slices();
798        Iter {
799            inner: start.iter().chain(end),
800        }
801    }
802
803    /// Returns an iterator that allows modifying each value.
804    pub fn iter_mut(&mut self) -> IterMut<'_, T> {
805        let (start, end) = self.as_mut_slices();
806        IterMut {
807            inner: start.iter_mut().chain(end),
808        }
809    }
810}
811
812/// Iterator over the contents of a [`Deque`]
813pub struct Iter<'a, T> {
814    inner: core::iter::Chain<core::slice::Iter<'a, T>, core::slice::Iter<'a, T>>,
815}
816
817/// Iterator over the contents of a [`Deque`]
818pub struct IterMut<'a, T> {
819    inner: core::iter::Chain<core::slice::IterMut<'a, T>, core::slice::IterMut<'a, T>>,
820}
821
822impl<'a, T> Iterator for Iter<'a, T> {
823    type Item = &'a T;
824    #[inline]
825    fn next(&mut self) -> Option<Self::Item> {
826        self.inner.next()
827    }
828
829    #[inline]
830    fn size_hint(&self) -> (usize, Option<usize>) {
831        self.inner.size_hint()
832    }
833}
834
835impl<T> DoubleEndedIterator for Iter<'_, T> {
836    #[inline]
837    fn next_back(&mut self) -> Option<Self::Item> {
838        self.inner.next_back()
839    }
840}
841
842impl<T> ExactSizeIterator for Iter<'_, T> {}
843impl<T> FusedIterator for Iter<'_, T> {}
844
845impl<'a, T> Iterator for IterMut<'a, T> {
846    type Item = &'a mut T;
847    #[inline]
848    fn next(&mut self) -> Option<Self::Item> {
849        self.inner.next()
850    }
851    #[inline]
852    fn size_hint(&self) -> (usize, Option<usize>) {
853        self.inner.size_hint()
854    }
855}
856
857impl<T> DoubleEndedIterator for IterMut<'_, T> {
858    #[inline]
859    fn next_back(&mut self) -> Option<Self::Item> {
860        self.inner.next_back()
861    }
862}
863
864impl<T> ExactSizeIterator for IterMut<'_, T> {}
865impl<T> FusedIterator for IterMut<'_, T> {}
866
867// Trait implementations
868
869impl<T, const N: usize> Default for Deque<T, N> {
870    fn default() -> Self {
871        Self::new()
872    }
873}
874
875impl<T, S: VecStorage<T> + ?Sized> Drop for DequeInner<T, S> {
876    fn drop(&mut self) {
877        // safety: `self` is left in an inconsistent state but it doesn't matter since
878        // it's getting dropped. Nothing should be able to observe `self` after drop.
879        unsafe { self.drop_contents() }
880    }
881}
882
883impl<T: fmt::Debug, S: VecStorage<T> + ?Sized> fmt::Debug for DequeInner<T, S> {
884    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
885        f.debug_list().entries(self).finish()
886    }
887}
888
889/// As with the standard library's `VecDeque`, items are added via `push_back`.
890impl<T, S: VecStorage<T> + ?Sized> Extend<T> for DequeInner<T, S> {
891    fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
892        for item in iter {
893            self.push_back(item).ok().unwrap();
894        }
895    }
896}
897impl<'a, T: 'a + Copy, S: VecStorage<T> + ?Sized> Extend<&'a T> for DequeInner<T, S> {
898    fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
899        self.extend(iter.into_iter().copied());
900    }
901}
902
903/// An iterator that moves out of a [`Deque`].
904///
905/// This struct is created by calling the `into_iter` method.
906#[derive(Clone)]
907pub struct IntoIter<T, const N: usize> {
908    deque: Deque<T, N>,
909}
910
911impl<T, const N: usize> Iterator for IntoIter<T, N> {
912    type Item = T;
913    fn next(&mut self) -> Option<Self::Item> {
914        self.deque.pop_front()
915    }
916}
917
918impl<T, const N: usize> IntoIterator for Deque<T, N> {
919    type Item = T;
920    type IntoIter = IntoIter<T, N>;
921
922    fn into_iter(self) -> Self::IntoIter {
923        IntoIter { deque: self }
924    }
925}
926
927impl<'a, T, S: VecStorage<T> + ?Sized> IntoIterator for &'a DequeInner<T, S> {
928    type Item = &'a T;
929    type IntoIter = Iter<'a, T>;
930
931    fn into_iter(self) -> Self::IntoIter {
932        self.iter()
933    }
934}
935
936impl<'a, T, S: VecStorage<T> + ?Sized> IntoIterator for &'a mut DequeInner<T, S> {
937    type Item = &'a mut T;
938    type IntoIter = IterMut<'a, T>;
939
940    fn into_iter(self) -> Self::IntoIter {
941        self.iter_mut()
942    }
943}
944
945impl<T, const N: usize> Clone for Deque<T, N>
946where
947    T: Clone,
948{
949    fn clone(&self) -> Self {
950        let mut res = Self::new();
951        for i in self {
952            // safety: the original and new deques have the same capacity, so it can
953            // not become full.
954            unsafe { res.push_back_unchecked(i.clone()) }
955        }
956        res
957    }
958}
959
960impl<T: PartialEq, const N: usize> PartialEq for Deque<T, N> {
961    fn eq(&self, other: &Self) -> bool {
962        if self.len() != other.len() {
963            return false;
964        }
965        let (sa, sb) = self.as_slices();
966        let (oa, ob) = other.as_slices();
967        match sa.len().cmp(&oa.len()) {
968            Ordering::Equal => sa == oa && sb == ob,
969            Ordering::Less => {
970                // Always divisible in three sections, for example:
971                // self:  [a b c|d e f]
972                // other: [0 1 2 3|4 5]
973                // front = 3, mid = 1,
974                // [a b c] == [0 1 2] && [d] == [3] && [e f] == [4 5]
975                let front = sa.len();
976                let mid = oa.len() - front;
977
978                let (oa_front, oa_mid) = oa.split_at(front);
979                let (sb_mid, sb_back) = sb.split_at(mid);
980                debug_assert_eq!(sa.len(), oa_front.len());
981                debug_assert_eq!(sb_mid.len(), oa_mid.len());
982                debug_assert_eq!(sb_back.len(), ob.len());
983                sa == oa_front && sb_mid == oa_mid && sb_back == ob
984            }
985            Ordering::Greater => {
986                let front = oa.len();
987                let mid = sa.len() - front;
988
989                let (sa_front, sa_mid) = sa.split_at(front);
990                let (ob_mid, ob_back) = ob.split_at(mid);
991                debug_assert_eq!(sa_front.len(), oa.len());
992                debug_assert_eq!(sa_mid.len(), ob_mid.len());
993                debug_assert_eq!(sb.len(), ob_back.len());
994                sa_front == oa && sa_mid == ob_mid && sb == ob_back
995            }
996        }
997    }
998}
999
1000impl<T: Eq, const N: usize> Eq for Deque<T, N> {}
1001
1002#[cfg(test)]
1003mod tests {
1004    use static_assertions::assert_not_impl_any;
1005
1006    use super::Deque;
1007
1008    // Ensure a `Deque` containing `!Send` values stays `!Send` itself.
1009    assert_not_impl_any!(Deque<*const (), 4>: Send);
1010
1011    #[test]
1012    fn static_new() {
1013        static mut _V: Deque<i32, 4> = Deque::new();
1014    }
1015
1016    #[test]
1017    fn stack_new() {
1018        let mut _v: Deque<i32, 4> = Deque::new();
1019    }
1020
1021    #[test]
1022    fn drop() {
1023        droppable!();
1024
1025        {
1026            let mut v: Deque<Droppable, 2> = Deque::new();
1027            v.push_back(Droppable::new()).ok().unwrap();
1028            v.push_back(Droppable::new()).ok().unwrap();
1029            v.pop_front().unwrap();
1030        }
1031
1032        assert_eq!(Droppable::count(), 0);
1033
1034        {
1035            let mut v: Deque<Droppable, 2> = Deque::new();
1036            v.push_back(Droppable::new()).ok().unwrap();
1037            v.push_back(Droppable::new()).ok().unwrap();
1038        }
1039
1040        assert_eq!(Droppable::count(), 0);
1041        {
1042            let mut v: Deque<Droppable, 2> = Deque::new();
1043            v.push_front(Droppable::new()).ok().unwrap();
1044            v.push_front(Droppable::new()).ok().unwrap();
1045        }
1046
1047        assert_eq!(Droppable::count(), 0);
1048    }
1049
1050    #[test]
1051    fn full() {
1052        let mut v: Deque<i32, 4> = Deque::new();
1053
1054        v.push_back(0).unwrap();
1055        v.push_front(1).unwrap();
1056        v.push_back(2).unwrap();
1057        v.push_back(3).unwrap();
1058
1059        assert!(v.push_front(4).is_err());
1060        assert!(v.push_back(4).is_err());
1061        assert!(v.is_full());
1062    }
1063
1064    #[test]
1065    fn empty() {
1066        let mut v: Deque<i32, 4> = Deque::new();
1067        assert!(v.is_empty());
1068
1069        v.push_back(0).unwrap();
1070        assert!(!v.is_empty());
1071
1072        v.push_front(1).unwrap();
1073        assert!(!v.is_empty());
1074
1075        v.pop_front().unwrap();
1076        v.pop_front().unwrap();
1077
1078        assert!(v.pop_front().is_none());
1079        assert!(v.pop_back().is_none());
1080        assert!(v.is_empty());
1081    }
1082
1083    #[test]
1084    fn front_back() {
1085        let mut v: Deque<i32, 4> = Deque::new();
1086        assert_eq!(v.front(), None);
1087        assert_eq!(v.front_mut(), None);
1088        assert_eq!(v.back(), None);
1089        assert_eq!(v.back_mut(), None);
1090
1091        v.push_back(4).unwrap();
1092        assert_eq!(v.front(), Some(&4));
1093        assert_eq!(v.front_mut(), Some(&mut 4));
1094        assert_eq!(v.back(), Some(&4));
1095        assert_eq!(v.back_mut(), Some(&mut 4));
1096
1097        v.push_front(3).unwrap();
1098        assert_eq!(v.front(), Some(&3));
1099        assert_eq!(v.front_mut(), Some(&mut 3));
1100        assert_eq!(v.back(), Some(&4));
1101        assert_eq!(v.back_mut(), Some(&mut 4));
1102
1103        v.pop_back().unwrap();
1104        assert_eq!(v.front(), Some(&3));
1105        assert_eq!(v.front_mut(), Some(&mut 3));
1106        assert_eq!(v.back(), Some(&3));
1107        assert_eq!(v.back_mut(), Some(&mut 3));
1108
1109        v.pop_front().unwrap();
1110        assert_eq!(v.front(), None);
1111        assert_eq!(v.front_mut(), None);
1112        assert_eq!(v.back(), None);
1113        assert_eq!(v.back_mut(), None);
1114    }
1115
1116    #[test]
1117    fn extend() {
1118        let mut v: Deque<i32, 4> = Deque::new();
1119        v.extend(&[1, 2, 3]);
1120        assert_eq!(v.pop_front().unwrap(), 1);
1121        assert_eq!(v.pop_front().unwrap(), 2);
1122        assert_eq!(*v.front().unwrap(), 3);
1123
1124        v.push_back(4).unwrap();
1125        v.extend(&[5, 6]);
1126        assert_eq!(v.pop_front().unwrap(), 3);
1127        assert_eq!(v.pop_front().unwrap(), 4);
1128        assert_eq!(v.pop_front().unwrap(), 5);
1129        assert_eq!(v.pop_front().unwrap(), 6);
1130        assert!(v.pop_front().is_none());
1131    }
1132
1133    #[test]
1134    #[should_panic]
1135    fn extend_panic() {
1136        let mut v: Deque<i32, 4> = Deque::new();
1137        // Is too many elements -> should panic
1138        v.extend(&[1, 2, 3, 4, 5]);
1139    }
1140
1141    #[test]
1142    fn iter() {
1143        let mut v: Deque<i32, 4> = Deque::new();
1144
1145        v.push_back(0).unwrap();
1146        v.push_back(1).unwrap();
1147        v.push_front(2).unwrap();
1148        v.push_front(3).unwrap();
1149        v.pop_back().unwrap();
1150        v.push_front(4).unwrap();
1151
1152        let mut items = v.iter();
1153
1154        assert_eq!(items.next(), Some(&4));
1155        assert_eq!(items.next(), Some(&3));
1156        assert_eq!(items.next(), Some(&2));
1157        assert_eq!(items.next(), Some(&0));
1158        assert_eq!(items.next(), None);
1159    }
1160
1161    #[test]
1162    fn iter_mut() {
1163        let mut v: Deque<i32, 4> = Deque::new();
1164
1165        v.push_back(0).unwrap();
1166        v.push_back(1).unwrap();
1167        v.push_front(2).unwrap();
1168        v.push_front(3).unwrap();
1169        v.pop_back().unwrap();
1170        v.push_front(4).unwrap();
1171
1172        let mut items = v.iter_mut();
1173
1174        assert_eq!(items.next(), Some(&mut 4));
1175        assert_eq!(items.next(), Some(&mut 3));
1176        assert_eq!(items.next(), Some(&mut 2));
1177        assert_eq!(items.next(), Some(&mut 0));
1178        assert_eq!(items.next(), None);
1179    }
1180
1181    #[test]
1182    fn iter_move() {
1183        let mut v: Deque<i32, 4> = Deque::new();
1184        v.push_back(0).unwrap();
1185        v.push_back(1).unwrap();
1186        v.push_back(2).unwrap();
1187        v.push_back(3).unwrap();
1188
1189        let mut items = v.into_iter();
1190
1191        assert_eq!(items.next(), Some(0));
1192        assert_eq!(items.next(), Some(1));
1193        assert_eq!(items.next(), Some(2));
1194        assert_eq!(items.next(), Some(3));
1195        assert_eq!(items.next(), None);
1196    }
1197
1198    #[test]
1199    fn iter_move_drop() {
1200        droppable!();
1201
1202        {
1203            let mut deque: Deque<Droppable, 2> = Deque::new();
1204            deque.push_back(Droppable::new()).ok().unwrap();
1205            deque.push_back(Droppable::new()).ok().unwrap();
1206            let mut items = deque.into_iter();
1207            // Move all
1208            let _ = items.next();
1209            let _ = items.next();
1210        }
1211
1212        assert_eq!(Droppable::count(), 0);
1213
1214        {
1215            let mut deque: Deque<Droppable, 2> = Deque::new();
1216            deque.push_back(Droppable::new()).ok().unwrap();
1217            deque.push_back(Droppable::new()).ok().unwrap();
1218            let _items = deque.into_iter();
1219            // Move none
1220        }
1221
1222        assert_eq!(Droppable::count(), 0);
1223
1224        {
1225            let mut deque: Deque<Droppable, 2> = Deque::new();
1226            deque.push_back(Droppable::new()).ok().unwrap();
1227            deque.push_back(Droppable::new()).ok().unwrap();
1228            let mut items = deque.into_iter();
1229            let _ = items.next(); // Move partly
1230        }
1231
1232        assert_eq!(Droppable::count(), 0);
1233    }
1234
1235    #[test]
1236    fn push_and_pop() {
1237        let mut q: Deque<i32, 4> = Deque::new();
1238        assert_eq!(q.len(), 0);
1239
1240        assert_eq!(q.pop_front(), None);
1241        assert_eq!(q.pop_back(), None);
1242        assert_eq!(q.len(), 0);
1243
1244        q.push_back(0).unwrap();
1245        assert_eq!(q.len(), 1);
1246
1247        assert_eq!(q.pop_back(), Some(0));
1248        assert_eq!(q.len(), 0);
1249
1250        q.push_back(0).unwrap();
1251        q.push_back(1).unwrap();
1252        q.push_front(2).unwrap();
1253        q.push_front(3).unwrap();
1254        assert_eq!(q.len(), 4);
1255
1256        // deque contains: 3 2 0 1
1257        assert_eq!(q.pop_front(), Some(3));
1258        assert_eq!(q.len(), 3);
1259        assert_eq!(q.pop_front(), Some(2));
1260        assert_eq!(q.len(), 2);
1261        assert_eq!(q.pop_back(), Some(1));
1262        assert_eq!(q.len(), 1);
1263        assert_eq!(q.pop_front(), Some(0));
1264        assert_eq!(q.len(), 0);
1265
1266        // deque is now empty
1267        assert_eq!(q.pop_front(), None);
1268        assert_eq!(q.pop_back(), None);
1269        assert_eq!(q.len(), 0);
1270    }
1271
1272    #[test]
1273    fn as_slices() {
1274        let mut q: Deque<i32, 4> = Deque::new();
1275        assert_eq!(q.len(), 0);
1276
1277        q.push_back(0).unwrap();
1278        q.push_back(1).unwrap();
1279        q.push_back(2).unwrap();
1280        q.push_back(3).unwrap();
1281        assert_eq!(q.as_slices(), (&[0, 1, 2, 3][..], &[][..]));
1282
1283        q.pop_front().unwrap();
1284        assert_eq!(q.as_slices(), (&[1, 2, 3][..], &[][..]));
1285
1286        q.push_back(4).unwrap();
1287        assert_eq!(q.as_slices(), (&[1, 2, 3][..], &[4][..]));
1288    }
1289
1290    #[test]
1291    fn clear() {
1292        let mut q: Deque<i32, 4> = Deque::new();
1293        assert_eq!(q.len(), 0);
1294
1295        q.push_back(0).unwrap();
1296        q.push_back(1).unwrap();
1297        q.push_back(2).unwrap();
1298        q.push_back(3).unwrap();
1299        assert_eq!(q.len(), 4);
1300
1301        q.clear();
1302        assert_eq!(q.len(), 0);
1303
1304        q.push_back(0).unwrap();
1305        assert_eq!(q.len(), 1);
1306    }
1307
1308    #[test]
1309    fn make_contiguous() {
1310        let mut q: Deque<i32, 4> = Deque::new();
1311        assert_eq!(q.len(), 0);
1312
1313        q.push_back(0).unwrap();
1314        q.push_back(1).unwrap();
1315        q.push_back(2).unwrap();
1316        q.push_back(3).unwrap();
1317
1318        // Deque contains: 0, 1, 2, 3
1319        assert_eq!(q.pop_front(), Some(0));
1320        assert_eq!(q.pop_front(), Some(1));
1321
1322        // Deque contains: ., ., 2, 3
1323        q.push_back(4).unwrap();
1324
1325        // Deque contains: 4, ., 2, 3
1326        assert_eq!(q.as_slices(), ([2, 3].as_slice(), [4].as_slice()));
1327
1328        assert_eq!(q.make_contiguous(), &[2, 3, 4]);
1329
1330        // Deque contains: ., 2, 3, 4
1331        assert_eq!(q.as_slices(), ([2, 3, 4].as_slice(), [].as_slice()));
1332
1333        assert_eq!(q.pop_front(), Some(2));
1334        assert_eq!(q.pop_front(), Some(3));
1335        q.push_back(5).unwrap();
1336        q.push_back(6).unwrap();
1337
1338        // Deque contains: 5, 6, ., 4
1339        assert_eq!(q.as_slices(), ([4].as_slice(), [5, 6].as_slice()));
1340
1341        assert_eq!(q.make_contiguous(), &[4, 5, 6]);
1342
1343        // Deque contains: 4, 5, 6, .
1344        assert_eq!(q.as_slices(), ([4, 5, 6].as_slice(), [].as_slice()));
1345
1346        assert_eq!(q.pop_front(), Some(4));
1347        q.push_back(7).unwrap();
1348        q.push_back(8).unwrap();
1349
1350        // Deque contains: 8, 5, 6, 7
1351        assert_eq!(q.as_slices(), ([5, 6, 7].as_slice(), [8].as_slice()));
1352
1353        assert_eq!(q.make_contiguous(), &[5, 6, 7, 8]);
1354
1355        // Deque contains: 5, 6, 7, 8
1356        assert_eq!(q.as_slices(), ([5, 6, 7, 8].as_slice(), [].as_slice()));
1357    }
1358
1359    #[test]
1360    fn get() {
1361        let mut q: Deque<i32, 4> = Deque::new();
1362        assert_eq!(q.get(0), None);
1363
1364        q.push_back(0).unwrap();
1365        assert_eq!(q.get(0), Some(&0));
1366        assert_eq!(q.get(1), None);
1367
1368        q.push_back(1).unwrap();
1369        assert_eq!(q.get(0), Some(&0));
1370        assert_eq!(q.get(1), Some(&1));
1371        assert_eq!(q.get(2), None);
1372
1373        q.pop_front().unwrap();
1374        assert_eq!(q.get(0), Some(&1));
1375        assert_eq!(q.get(1), None);
1376
1377        q.push_back(2).unwrap();
1378        q.push_back(3).unwrap();
1379        q.push_back(4).unwrap();
1380        assert_eq!(q.get(0), Some(&1));
1381        assert_eq!(q.get(1), Some(&2));
1382        assert_eq!(q.get(2), Some(&3));
1383        assert_eq!(q.get(3), Some(&4));
1384    }
1385
1386    #[test]
1387    fn get_mut() {
1388        let mut q: Deque<i32, 4> = Deque::new();
1389        assert_eq!(q.get(0), None);
1390
1391        q.push_back(0).unwrap();
1392        assert_eq!(q.get_mut(0), Some(&mut 0));
1393        assert_eq!(q.get_mut(1), None);
1394
1395        q.push_back(1).unwrap();
1396        assert_eq!(q.get_mut(0), Some(&mut 0));
1397        assert_eq!(q.get_mut(1), Some(&mut 1));
1398        assert_eq!(q.get_mut(2), None);
1399        *q.get_mut(0).unwrap() = 42;
1400        *q.get_mut(1).unwrap() = 43;
1401
1402        assert_eq!(q.pop_front(), Some(42));
1403        assert_eq!(q.pop_front(), Some(43));
1404        assert_eq!(q.pop_front(), None);
1405    }
1406
1407    #[test]
1408    fn swap() {
1409        let mut q: Deque<i32, 4> = Deque::new();
1410        q.push_back(40).unwrap();
1411        q.push_back(41).unwrap();
1412        q.push_back(42).unwrap();
1413        q.pop_front().unwrap();
1414        q.push_back(43).unwrap();
1415        assert_eq!(*q.get(0).unwrap(), 41);
1416        assert_eq!(*q.get(1).unwrap(), 42);
1417        assert_eq!(*q.get(2).unwrap(), 43);
1418
1419        q.swap(0, 1);
1420        assert_eq!(*q.get(0).unwrap(), 42);
1421        assert_eq!(*q.get(1).unwrap(), 41);
1422        assert_eq!(*q.get(2).unwrap(), 43);
1423
1424        q.swap(1, 2);
1425        assert_eq!(*q.get(0).unwrap(), 42);
1426        assert_eq!(*q.get(1).unwrap(), 43);
1427        assert_eq!(*q.get(2).unwrap(), 41);
1428
1429        q.swap(1, 1);
1430        assert_eq!(*q.get(0).unwrap(), 42);
1431        assert_eq!(*q.get(1).unwrap(), 43);
1432        assert_eq!(*q.get(2).unwrap(), 41);
1433    }
1434
1435    #[test]
1436    fn swap_remove_front() {
1437        let mut q: Deque<i32, 4> = Deque::new();
1438        q.push_back(40).unwrap();
1439        q.push_back(41).unwrap();
1440        q.push_back(42).unwrap();
1441        q.push_back(43).unwrap();
1442
1443        assert_eq!(q.swap_remove_front(2), Some(42));
1444        assert_eq!(q.swap_remove_front(1), Some(40));
1445        assert_eq!(q.swap_remove_front(0), Some(41));
1446        assert_eq!(q.swap_remove_front(1), None);
1447        assert_eq!(q.swap_remove_front(4), None);
1448        assert_eq!(q.swap_remove_front(6), None);
1449        assert_eq!(q.swap_remove_front(0), Some(43));
1450    }
1451
1452    #[test]
1453    fn swap_remove_back() {
1454        let mut q: Deque<i32, 4> = Deque::new();
1455        q.push_back(40).unwrap();
1456        q.push_back(41).unwrap();
1457        q.push_back(42).unwrap();
1458        q.push_back(43).unwrap();
1459        q.pop_front().unwrap();
1460        q.push_back(44).unwrap();
1461
1462        assert_eq!(q.swap_remove_back(1), Some(42));
1463        assert_eq!(q.swap_remove_front(1), Some(44));
1464        assert_eq!(q.swap_remove_front(0), Some(41));
1465        assert_eq!(q.swap_remove_front(1), None);
1466        assert_eq!(q.swap_remove_front(4), None);
1467        assert_eq!(q.swap_remove_front(6), None);
1468        assert_eq!(q.swap_remove_front(0), Some(43));
1469    }
1470
1471    #[test]
1472    #[should_panic = "i < len"]
1473    fn swap_i_out_of_bounds() {
1474        let mut q: Deque<i32, 4> = Deque::new();
1475        q.push_back(40).unwrap();
1476        q.push_back(41).unwrap();
1477        q.push_back(42).unwrap();
1478        q.pop_front().unwrap();
1479        q.swap(2, 0);
1480    }
1481
1482    #[test]
1483    #[should_panic = "j < len"]
1484    fn swap_j_out_of_bounds() {
1485        let mut q: Deque<i32, 4> = Deque::new();
1486        q.push_back(40).unwrap();
1487        q.push_back(41).unwrap();
1488        q.push_back(42).unwrap();
1489        q.pop_front().unwrap();
1490        q.swap(0, 2);
1491    }
1492
1493    #[test]
1494    fn equality() {
1495        let mut a: Deque<i32, 7> = Deque::new();
1496        let mut b: Deque<i32, 7> = Deque::new();
1497
1498        assert_eq!(a, b);
1499
1500        a.push_back(1).unwrap();
1501        a.push_back(2).unwrap();
1502        a.push_back(3).unwrap();
1503
1504        assert_ne!(a, b);
1505
1506        b.push_back(1).unwrap();
1507        b.push_back(2).unwrap();
1508        b.push_back(3).unwrap();
1509
1510        assert_eq!(a, b);
1511
1512        a.push_back(1).unwrap();
1513        a.push_back(2).unwrap();
1514        a.push_back(3).unwrap();
1515
1516        assert_ne!(a, b);
1517
1518        b.push_front(3).unwrap();
1519        b.push_front(2).unwrap();
1520        b.push_front(1).unwrap();
1521
1522        assert_eq!(a, b);
1523
1524        a.push_back(4).unwrap();
1525        b.push_back(4).unwrap();
1526
1527        assert_eq!(a, b);
1528
1529        a.clear();
1530        b.clear();
1531
1532        a.push_back(1).unwrap();
1533        a.push_back(2).unwrap();
1534        a.push_back(3).unwrap();
1535        a.push_front(3).unwrap();
1536        a.push_front(2).unwrap();
1537        a.push_front(1).unwrap();
1538
1539        b.push_back(2).unwrap();
1540        b.push_back(3).unwrap();
1541        b.push_back(1).unwrap();
1542        b.push_back(2).unwrap();
1543        b.push_back(3).unwrap();
1544        b.push_front(1).unwrap();
1545
1546        assert_eq!(a, b);
1547    }
1548}