iter_mut.rs - source
Description: Source of the Rust file `library/alloc/src/collections/vec_deque/iter_mut.rs`.

#
alloc/collections/vec_deque/
iter_mut.rs

    1use core::iter::{FusedIterator, TrustedLen, TrustedRandomAccess, TrustedRandomAccessNoCoerce};
    2use core::num::NonZero;
    3use core::ops::Try;
    4use core::{fmt, mem, slice};
    5
    6/// A mutable iterator over the elements of a `VecDeque`.
    7///
    8/// This `struct` is created by the [`iter_mut`] method on [`super::VecDeque`]. See its
    9/// documentation for more.
    10///
    11/// [`iter_mut`]: super::VecDeque::iter_mut
    12#[stable(feature = "rust1", since = "1.0.0")]
    13pub struct IterMut<'a, T: 'a> {
    14    i1: slice::IterMut<'a, T>,
    15    i2: slice::IterMut<'a, T>,
    16}
    17
    18impl<'a, T> IterMut<'a, T> {
    19    pub(super) fn new(i1: slice::IterMut<'a, T>, i2: slice::IterMut<'a, T>) -> Self {
    20        Self { i1, i2 }
    21    }
    22
    23    /// Views the underlying data as a pair of subslices of the original data.
    24    ///
    25    /// The slices contain, in order, the contents of the deque not yet yielded
    26    /// by the iterator.
    27    ///
    28    /// To avoid creating `&mut` references that alias, this is forced to
    29    /// consume the iterator.
    30    ///
    31    /// # Examples
    32    ///
    33    /// ```
    34    /// #![feature(vec_deque_iter_as_slices)]
    35    ///
    36    /// use std::collections::VecDeque;
    37    ///
    38    /// let mut deque = VecDeque::new();
    39    /// deque.push_back(0);
    40    /// deque.push_back(1);
    41    /// deque.push_back(2);
    42    /// deque.push_front(10);
    43    /// deque.push_front(9);
    44    /// deque.push_front(8);
    45    ///
    46    /// let mut iter = deque.iter_mut();
    47    /// iter.next();
    48    /// iter.next_back();
    49    ///
    50    /// let slices = iter.into_slices();
    51    /// slices.0[0] = 42;
    52    /// slices.1[0] = 24;
    53    /// assert_eq!(deque.as_slices(), (&[8, 42, 10][..], &[24, 1, 2][..]));
    54    /// ```
    55    #[unstable(feature = "vec_deque_iter_as_slices", issue = "123947")]
    56    pub fn into_slices(self) -> (&'a mut [T], &'a mut [T]) {
    57        (self.i1.into_slice(), self.i2.into_slice())
    58    }
    59
    60    /// Views the underlying data as a pair of subslices of the original data.
    61    ///
    62    /// The slices contain, in order, the contents of the deque not yet yielded
    63    /// by the iterator.
    64    ///
    65    /// To avoid creating `&mut [T]` references that alias, the returned slices
    66    /// borrow their lifetimes from the iterator the method is applied on.
    67    ///
    68    /// # Examples
    69    ///
    70    /// ```
    71    /// #![feature(vec_deque_iter_as_slices)]
    72    ///
    73    /// use std::collections::VecDeque;
    74    ///
    75    /// let mut deque = VecDeque::new();
    76    /// deque.push_back(0);
    77    /// deque.push_back(1);
    78    /// deque.push_back(2);
    79    /// deque.push_front(10);
    80    /// deque.push_front(9);
    81    /// deque.push_front(8);
    82    ///
    83    /// let mut iter = deque.iter_mut();
    84    /// iter.next();
    85    /// iter.next_back();
    86    ///
    87    /// assert_eq!(iter.as_slices(), (&[9, 10][..], &[0, 1][..]));
    88    /// ```
    89    #[unstable(feature = "vec_deque_iter_as_slices", issue = "123947")]
    90    pub fn as_slices(&self) -> (&[T], &[T]) {
    91        (self.i1.as_slice(), self.i2.as_slice())
    92    }
    93
    94    /// Views the underlying data as a pair of subslices of the original data.
    95    ///
    96    /// The slices contain, in order, the contents of the deque not yet yielded
    97    /// by the iterator.
    98    ///
    99    /// To avoid creating `&mut [T]` references that alias, the returned slices
    100    /// borrow their lifetimes from the iterator the method is applied on.
    101    ///
    102    /// # Examples
    103    ///
    104    /// ```
    105    /// #![feature(vec_deque_iter_as_slices)]
    106    ///
    107    /// use std::collections::VecDeque;
    108    ///
    109    /// let mut deque = VecDeque::new();
    110    /// deque.push_back(0);
    111    /// deque.push_back(1);
    112    /// deque.push_back(2);
    113    /// deque.push_front(10);
    114    /// deque.push_front(9);
    115    /// deque.push_front(8);
    116    ///
    117    /// let mut iter = deque.iter_mut();
    118    /// iter.next();
    119    /// iter.next_back();
    120    ///
    121    /// iter.as_mut_slices().0[0] = 42;
    122    /// iter.as_mut_slices().1[0] = 24;
    123    /// assert_eq!(deque.as_slices(), (&[8, 42, 10][..], &[24, 1, 2][..]));
    124    /// ```
    125    #[unstable(feature = "vec_deque_iter_as_slices", issue = "123947")]
    126    pub fn as_mut_slices(&mut self) -> (&mut [T], &mut [T]) {
    127        (self.i1.as_mut_slice(), self.i2.as_mut_slice())
    128    }
    129}
    130
    131#[stable(feature = "collection_debug", since = "1.17.0")]
    132impl<T: fmt::Debug> fmt::Debug for IterMut<'_, T> {
    133    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    134        f.debug_tuple("IterMut").field(&self.i1.as_slice()).field(&self.i2.as_slice()).finish()
    135    }
    136}
    137
    138#[stable(feature = "default_iters_sequel", since = "1.82.0")]
    139impl<T> Default for IterMut<'_, T> {
    140    /// Creates an empty `vec_deque::IterMut`.
    141    ///
    142    /// ```
    143    /// # use std::collections::vec_deque;
    144    /// let iter: vec_deque::IterMut<'_, u8> = Default::default();
    145    /// assert_eq!(iter.len(), 0);
    146    /// ```
    147    fn default() -> Self {
    148        IterMut { i1: Default::default(), i2: Default::default() }
    149    }
    150}
    151
    152#[stable(feature = "rust1", since = "1.0.0")]
    153impl<'a, T> Iterator for IterMut<'a, T> {
    154    type Item = &'a mut T;
    155
    156    #[inline]
    157    fn next(&mut self) -> Option<&'a mut T> {
    158        match self.i1.next() {
    159            Some(val) => Some(val),
    160            None => {
    161                // most of the time, the iterator will either always
    162                // call next(), or always call next_back(). By swapping
    163                // the iterators once the first one is empty, we ensure
    164                // that the first branch is taken as often as possible,
    165                // without sacrificing correctness, as i1 is empty anyways
    166                mem::swap(&mut self.i1, &mut self.i2);
    167                self.i1.next()
    168            }
    169        }
    170    }
    171
    172    fn advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
    173        match self.i1.advance_by(n) {
    174            Ok(()) => Ok(()),
    175            Err(remaining) => {
    176                mem::swap(&mut self.i1, &mut self.i2);
    177                self.i1.advance_by(remaining.get())
    178            }
    179        }
    180    }
    181
    182    #[inline]
    183    fn size_hint(&self) -> (usize, Option<usize>) {
    184        let len = self.len();
    185        (len, Some(len))
    186    }
    187
    188    fn fold<Acc, F>(self, accum: Acc, mut f: F) -> Acc
    189    where
    190        F: FnMut(Acc, Self::Item) -> Acc,
    191    {
    192        let accum = self.i1.fold(accum, &mut f);
    193        self.i2.fold(accum, &mut f)
    194    }
    195
    196    fn try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R
    197    where
    198        F: FnMut(B, Self::Item) -> R,
    199        R: Try<Output = B>,
    200    {
    201        let acc = self.i1.try_fold(init, &mut f)?;
    202        self.i2.try_fold(acc, &mut f)
    203    }
    204
    205    #[inline]
    206    fn last(mut self) -> Option<&'a mut T> {
    207        self.next_back()
    208    }
    209
    210    #[inline]
    211    unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item {
    212        // Safety: The TrustedRandomAccess contract requires that callers only pass an index
    213        // that is in bounds.
    214        unsafe {
    215            let i1_len = self.i1.len();
    216            if idx < i1_len {
    217                self.i1.__iterator_get_unchecked(idx)
    218            } else {
    219                self.i2.__iterator_get_unchecked(idx - i1_len)
    220            }
    221        }
    222    }
    223}
    224
    225#[stable(feature = "rust1", since = "1.0.0")]
    226impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
    227    #[inline]
    228    fn next_back(&mut self) -> Option<&'a mut T> {
    229        match self.i2.next_back() {
    230            Some(val) => Some(val),
    231            None => {
    232                // most of the time, the iterator will either always
    233                // call next(), or always call next_back(). By swapping
    234                // the iterators once the first one is empty, we ensure
    235                // that the first branch is taken as often as possible,
    236                // without sacrificing correctness, as i2 is empty anyways
    237                mem::swap(&mut self.i1, &mut self.i2);
    238                self.i2.next_back()
    239            }
    240        }
    241    }
    242
    243    fn advance_back_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
    244        match self.i2.advance_back_by(n) {
    245            Ok(()) => Ok(()),
    246            Err(remaining) => {
    247                mem::swap(&mut self.i1, &mut self.i2);
    248                self.i2.advance_back_by(remaining.get())
    249            }
    250        }
    251    }
    252
    253    fn rfold<Acc, F>(self, accum: Acc, mut f: F) -> Acc
    254    where
    255        F: FnMut(Acc, Self::Item) -> Acc,
    256    {
    257        let accum = self.i2.rfold(accum, &mut f);
    258        self.i1.rfold(accum, &mut f)
    259    }
    260
    261    fn try_rfold<B, F, R>(&mut self, init: B, mut f: F) -> R
    262    where
    263        F: FnMut(B, Self::Item) -> R,
    264        R: Try<Output = B>,
    265    {
    266        let acc = self.i2.try_rfold(init, &mut f)?;
    267        self.i1.try_rfold(acc, &mut f)
    268    }
    269}
    270
    271#[stable(feature = "rust1", since = "1.0.0")]
    272impl<T> ExactSizeIterator for IterMut<'_, T> {
    273    fn len(&self) -> usize {
    274        self.i1.len() + self.i2.len()
    275    }
    276
    277    fn is_empty(&self) -> bool {
    278        self.i1.is_empty() && self.i2.is_empty()
    279    }
    280}
    281
    282#[stable(feature = "fused", since = "1.26.0")]
    283impl<T> FusedIterator for IterMut<'_, T> {}
    284
    285#[unstable(feature = "trusted_len", issue = "37572")]
    286unsafe impl<T> TrustedLen for IterMut<'_, T> {}
    287
    288#[doc(hidden)]
    289#[unstable(feature = "trusted_random_access", issue = "none")]
    290unsafe impl<T> TrustedRandomAccess for IterMut<'_, T> {}
    291
    292#[doc(hidden)]
    293#[unstable(feature = "trusted_random_access", issue = "none")]
    294unsafe impl<T> TrustedRandomAccessNoCoerce for IterMut<'_, T> {
    295    const MAY_HAVE_SIDE_EFFECT: bool = false;
    296}