alloc/collections/vec_deque/
iter_mut.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
use core::iter::{FusedIterator, TrustedLen, TrustedRandomAccess, TrustedRandomAccessNoCoerce};
use core::num::NonZero;
use core::ops::Try;
use core::{fmt, mem, slice};

/// A mutable iterator over the elements of a `VecDeque`.
///
/// This `struct` is created by the [`iter_mut`] method on [`super::VecDeque`]. See its
/// documentation for more.
///
/// [`iter_mut`]: super::VecDeque::iter_mut
#[stable(feature = "rust1", since = "1.0.0")]
pub struct IterMut<'a, T: 'a> {
    i1: slice::IterMut<'a, T>,
    i2: slice::IterMut<'a, T>,
}

impl<'a, T> IterMut<'a, T> {
    pub(super) fn new(i1: slice::IterMut<'a, T>, i2: slice::IterMut<'a, T>) -> Self {
        Self { i1, i2 }
    }

    /// Views the underlying data as a pair of subslices of the original data.
    ///
    /// The slices contain, in order, the contents of the deque not yet yielded
    /// by the iterator.
    ///
    /// To avoid creating `&mut` references that alias, this is forced to
    /// consume the iterator.
    ///
    /// # Examples
    ///
    /// ```
    /// #![feature(vec_deque_iter_as_slices)]
    ///
    /// use std::collections::VecDeque;
    ///
    /// let mut deque = VecDeque::new();
    /// deque.push_back(0);
    /// deque.push_back(1);
    /// deque.push_back(2);
    /// deque.push_front(10);
    /// deque.push_front(9);
    /// deque.push_front(8);
    ///
    /// let mut iter = deque.iter_mut();
    /// iter.next();
    /// iter.next_back();
    ///
    /// let slices = iter.into_slices();
    /// slices.0[0] = 42;
    /// slices.1[0] = 24;
    /// assert_eq!(deque.as_slices(), (&[8, 42, 10][..], &[24, 1, 2][..]));
    /// ```
    #[unstable(feature = "vec_deque_iter_as_slices", issue = "123947")]
    pub fn into_slices(self) -> (&'a mut [T], &'a mut [T]) {
        (self.i1.into_slice(), self.i2.into_slice())
    }

    /// Views the underlying data as a pair of subslices of the original data.
    ///
    /// The slices contain, in order, the contents of the deque not yet yielded
    /// by the iterator.
    ///
    /// To avoid creating `&mut [T]` references that alias, the returned slices
    /// borrow their lifetimes from the iterator the method is applied on.
    ///
    /// # Examples
    ///
    /// ```
    /// #![feature(vec_deque_iter_as_slices)]
    ///
    /// use std::collections::VecDeque;
    ///
    /// let mut deque = VecDeque::new();
    /// deque.push_back(0);
    /// deque.push_back(1);
    /// deque.push_back(2);
    /// deque.push_front(10);
    /// deque.push_front(9);
    /// deque.push_front(8);
    ///
    /// let mut iter = deque.iter_mut();
    /// iter.next();
    /// iter.next_back();
    ///
    /// assert_eq!(iter.as_slices(), (&[9, 10][..], &[0, 1][..]));
    /// ```
    #[unstable(feature = "vec_deque_iter_as_slices", issue = "123947")]
    pub fn as_slices(&self) -> (&[T], &[T]) {
        (self.i1.as_slice(), self.i2.as_slice())
    }

    /// Views the underlying data as a pair of subslices of the original data.
    ///
    /// The slices contain, in order, the contents of the deque not yet yielded
    /// by the iterator.
    ///
    /// To avoid creating `&mut [T]` references that alias, the returned slices
    /// borrow their lifetimes from the iterator the method is applied on.
    ///
    /// # Examples
    ///
    /// ```
    /// #![feature(vec_deque_iter_as_slices)]
    ///
    /// use std::collections::VecDeque;
    ///
    /// let mut deque = VecDeque::new();
    /// deque.push_back(0);
    /// deque.push_back(1);
    /// deque.push_back(2);
    /// deque.push_front(10);
    /// deque.push_front(9);
    /// deque.push_front(8);
    ///
    /// let mut iter = deque.iter_mut();
    /// iter.next();
    /// iter.next_back();
    ///
    /// iter.as_mut_slices().0[0] = 42;
    /// iter.as_mut_slices().1[0] = 24;
    /// assert_eq!(deque.as_slices(), (&[8, 42, 10][..], &[24, 1, 2][..]));
    /// ```
    #[unstable(feature = "vec_deque_iter_as_slices", issue = "123947")]
    pub fn as_mut_slices(&mut self) -> (&mut [T], &mut [T]) {
        (self.i1.as_mut_slice(), self.i2.as_mut_slice())
    }
}

#[stable(feature = "collection_debug", since = "1.17.0")]
impl<T: fmt::Debug> fmt::Debug for IterMut<'_, T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("IterMut").field(&self.i1.as_slice()).field(&self.i2.as_slice()).finish()
    }
}

#[stable(feature = "default_iters_sequel", since = "1.82.0")]
impl<T> Default for IterMut<'_, T> {
    /// Creates an empty `vec_deque::IterMut`.
    ///
    /// ```
    /// # use std::collections::vec_deque;
    /// let iter: vec_deque::IterMut<'_, u8> = Default::default();
    /// assert_eq!(iter.len(), 0);
    /// ```
    fn default() -> Self {
        IterMut { i1: Default::default(), i2: Default::default() }
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T> Iterator for IterMut<'a, T> {
    type Item = &'a mut T;

    #[inline]
    fn next(&mut self) -> Option<&'a mut T> {
        match self.i1.next() {
            Some(val) => Some(val),
            None => {
                // most of the time, the iterator will either always
                // call next(), or always call next_back(). By swapping
                // the iterators once the first one is empty, we ensure
                // that the first branch is taken as often as possible,
                // without sacrificing correctness, as i1 is empty anyways
                mem::swap(&mut self.i1, &mut self.i2);
                self.i1.next()
            }
        }
    }

    fn advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
        match self.i1.advance_by(n) {
            Ok(()) => Ok(()),
            Err(remaining) => {
                mem::swap(&mut self.i1, &mut self.i2);
                self.i1.advance_by(remaining.get())
            }
        }
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        let len = self.len();
        (len, Some(len))
    }

    fn fold<Acc, F>(self, accum: Acc, mut f: F) -> Acc
    where
        F: FnMut(Acc, Self::Item) -> Acc,
    {
        let accum = self.i1.fold(accum, &mut f);
        self.i2.fold(accum, &mut f)
    }

    fn try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R
    where
        F: FnMut(B, Self::Item) -> R,
        R: Try<Output = B>,
    {
        let acc = self.i1.try_fold(init, &mut f)?;
        self.i2.try_fold(acc, &mut f)
    }

    #[inline]
    fn last(mut self) -> Option<&'a mut T> {
        self.next_back()
    }

    #[inline]
    unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item {
        // Safety: The TrustedRandomAccess contract requires that callers only pass an index
        // that is in bounds.
        unsafe {
            let i1_len = self.i1.len();
            if idx < i1_len {
                self.i1.__iterator_get_unchecked(idx)
            } else {
                self.i2.__iterator_get_unchecked(idx - i1_len)
            }
        }
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
    #[inline]
    fn next_back(&mut self) -> Option<&'a mut T> {
        match self.i2.next_back() {
            Some(val) => Some(val),
            None => {
                // most of the time, the iterator will either always
                // call next(), or always call next_back(). By swapping
                // the iterators once the first one is empty, we ensure
                // that the first branch is taken as often as possible,
                // without sacrificing correctness, as i2 is empty anyways
                mem::swap(&mut self.i1, &mut self.i2);
                self.i2.next_back()
            }
        }
    }

    fn advance_back_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
        match self.i2.advance_back_by(n) {
            Ok(()) => Ok(()),
            Err(remaining) => {
                mem::swap(&mut self.i1, &mut self.i2);
                self.i2.advance_back_by(remaining.get())
            }
        }
    }

    fn rfold<Acc, F>(self, accum: Acc, mut f: F) -> Acc
    where
        F: FnMut(Acc, Self::Item) -> Acc,
    {
        let accum = self.i2.rfold(accum, &mut f);
        self.i1.rfold(accum, &mut f)
    }

    fn try_rfold<B, F, R>(&mut self, init: B, mut f: F) -> R
    where
        F: FnMut(B, Self::Item) -> R,
        R: Try<Output = B>,
    {
        let acc = self.i2.try_rfold(init, &mut f)?;
        self.i1.try_rfold(acc, &mut f)
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<T> ExactSizeIterator for IterMut<'_, T> {
    fn len(&self) -> usize {
        self.i1.len() + self.i2.len()
    }

    fn is_empty(&self) -> bool {
        self.i1.is_empty() && self.i2.is_empty()
    }
}

#[stable(feature = "fused", since = "1.26.0")]
impl<T> FusedIterator for IterMut<'_, T> {}

#[unstable(feature = "trusted_len", issue = "37572")]
unsafe impl<T> TrustedLen for IterMut<'_, T> {}

#[doc(hidden)]
#[unstable(feature = "trusted_random_access", issue = "none")]
unsafe impl<T> TrustedRandomAccess for IterMut<'_, T> {}

#[doc(hidden)]
#[unstable(feature = "trusted_random_access", issue = "none")]
unsafe impl<T> TrustedRandomAccessNoCoerce for IterMut<'_, T> {
    const MAY_HAVE_SIDE_EFFECT: bool = false;
}