Skip to main content

alloc/vec/
into_iter.rs

1use core::iter::{
2    FusedIterator, InPlaceIterable, SourceIter, TrustedFused, TrustedLen,
3    TrustedRandomAccessNoCoerce,
4};
5use core::marker::PhantomData;
6use core::mem::{ManuallyDrop, MaybeUninit, SizedTypeProperties};
7use core::num::NonZero;
8#[cfg(not(no_global_oom_handling))]
9use core::ops::Deref;
10use core::panic::UnwindSafe;
11use core::ptr::{self, NonNull};
12use core::{array, fmt, slice};
13
14#[cfg(not(no_global_oom_handling))]
15use super::AsVecIntoIter;
16use crate::alloc::{Allocator, Global};
17#[cfg(not(no_global_oom_handling))]
18use crate::collections::VecDeque;
19use crate::raw_vec::RawVec;
20
21macro non_null {
22    (mut $place:expr, $t:ident) => {{
23        #![allow(unused_unsafe)] // we're sometimes used within an unsafe block
24        unsafe { &mut *((&raw mut $place) as *mut NonNull<$t>) }
25    }},
26    ($place:expr, $t:ident) => {{
27        #![allow(unused_unsafe)] // we're sometimes used within an unsafe block
28        unsafe { *((&raw const $place) as *const NonNull<$t>) }
29    }},
30}
31
32/// An iterator that moves out of a vector.
33///
34/// This `struct` is created by the `into_iter` method on [`Vec`](super::Vec)
35/// (provided by the [`IntoIterator`] trait).
36///
37/// # Example
38///
39/// ```
40/// let v = vec![0, 1, 2];
41/// let iter: std::vec::IntoIter<_> = v.into_iter();
42/// ```
43#[stable(feature = "rust1", since = "1.0.0")]
44#[rustc_insignificant_dtor]
45pub struct IntoIter<
46    T,
47    #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
48> {
49    pub(super) buf: NonNull<T>,
50    pub(super) phantom: PhantomData<T>,
51    pub(super) cap: usize,
52    // the drop impl reconstructs a RawVec from buf, cap and alloc
53    // to avoid dropping the allocator twice we need to wrap it into ManuallyDrop
54    pub(super) alloc: ManuallyDrop<A>,
55    pub(super) ptr: NonNull<T>,
56    /// If T is a ZST, this is actually ptr+len. This encoding is picked so that
57    /// ptr == end is a quick test for the Iterator being empty, that works
58    /// for both ZST and non-ZST.
59    /// For non-ZSTs the pointer is treated as `NonNull<T>`
60    pub(super) end: *const T,
61}
62
63// Manually mirroring what `Vec` has,
64// because otherwise we get `T: RefUnwindSafe` from `NonNull`.
65#[stable(feature = "catch_unwind", since = "1.9.0")]
66impl<T: UnwindSafe, A: Allocator + UnwindSafe> UnwindSafe for IntoIter<T, A> {}
67
68#[stable(feature = "vec_intoiter_debug", since = "1.13.0")]
69impl<T: fmt::Debug, A: Allocator> fmt::Debug for IntoIter<T, A> {
70    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
71        f.debug_tuple("IntoIter").field(&self.as_slice()).finish()
72    }
73}
74
75impl<T, A: Allocator> IntoIter<T, A> {
76    /// Returns the remaining items of this iterator as a slice.
77    ///
78    /// # Examples
79    ///
80    /// ```
81    /// let vec = vec!['a', 'b', 'c'];
82    /// let mut into_iter = vec.into_iter();
83    /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']);
84    /// let _ = into_iter.next().unwrap();
85    /// assert_eq!(into_iter.as_slice(), &['b', 'c']);
86    /// ```
87    #[stable(feature = "vec_into_iter_as_slice", since = "1.15.0")]
88    pub fn as_slice(&self) -> &[T] {
89        unsafe { slice::from_raw_parts(self.ptr.as_ptr(), self.len()) }
90    }
91
92    /// Returns the remaining items of this iterator as a mutable slice.
93    ///
94    /// # Examples
95    ///
96    /// ```
97    /// let vec = vec!['a', 'b', 'c'];
98    /// let mut into_iter = vec.into_iter();
99    /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']);
100    /// into_iter.as_mut_slice()[2] = 'z';
101    /// assert_eq!(into_iter.next().unwrap(), 'a');
102    /// assert_eq!(into_iter.next().unwrap(), 'b');
103    /// assert_eq!(into_iter.next().unwrap(), 'z');
104    /// ```
105    #[stable(feature = "vec_into_iter_as_slice", since = "1.15.0")]
106    pub fn as_mut_slice(&mut self) -> &mut [T] {
107        unsafe { &mut *self.as_raw_mut_slice() }
108    }
109
110    /// Returns a reference to the underlying allocator.
111    #[unstable(feature = "allocator_api", issue = "32838")]
112    #[inline]
113    pub fn allocator(&self) -> &A {
114        &self.alloc
115    }
116
117    fn as_raw_mut_slice(&mut self) -> *mut [T] {
118        ptr::slice_from_raw_parts_mut(self.ptr.as_ptr(), self.len())
119    }
120
121    /// Drops remaining elements and relinquishes the backing allocation.
122    ///
123    /// This method guarantees it won't panic before relinquishing the backing
124    /// allocation.
125    ///
126    /// This is roughly equivalent to the following, but more efficient
127    ///
128    /// ```
129    /// # let mut vec = Vec::<u8>::with_capacity(10);
130    /// # let ptr = vec.as_mut_ptr();
131    /// # let mut into_iter = vec.into_iter();
132    /// let mut into_iter = std::mem::replace(&mut into_iter, Vec::new().into_iter());
133    /// (&mut into_iter).for_each(drop);
134    /// std::mem::forget(into_iter);
135    /// # // FIXME(https://github.com/rust-lang/miri/issues/3670):
136    /// # // use -Zmiri-disable-leak-check instead of unleaking in tests meant to leak.
137    /// # drop(unsafe { Vec::<u8>::from_raw_parts(ptr, 0, 10) });
138    /// ```
139    ///
140    /// This method is used by in-place iteration, refer to the vec::in_place_collect
141    /// documentation for an overview.
142    #[cfg(not(no_global_oom_handling))]
143    pub(super) fn forget_allocation_drop_remaining(&mut self) {
144        let remaining = self.as_raw_mut_slice();
145
146        // overwrite the individual fields instead of creating a new
147        // struct and then overwriting &mut self.
148        // this creates less assembly
149        self.cap = 0;
150        self.buf = RawVec::new().non_null();
151        self.ptr = self.buf;
152        self.end = self.buf.as_ptr();
153
154        // Dropping the remaining elements can panic, so this needs to be
155        // done only after updating the other fields.
156        unsafe {
157            ptr::drop_in_place(remaining);
158        }
159    }
160
161    /// Forgets to Drop the remaining elements while still allowing the backing allocation to be freed.
162    pub(crate) fn forget_remaining_elements(&mut self) {
163        // For the ZST case, it is crucial that we mutate `end` here, not `ptr`.
164        // `ptr` must stay aligned, while `end` may be unaligned.
165        self.end = self.ptr.as_ptr();
166    }
167
168    #[cfg(not(no_global_oom_handling))]
169    #[inline]
170    pub(crate) fn into_vecdeque(self) -> VecDeque<T, A> {
171        // Keep our `Drop` impl from dropping the elements and the allocator
172        let mut this = ManuallyDrop::new(self);
173
174        // SAFETY: This allocation originally came from a `Vec`, so it passes
175        // all those checks. We have `this.buf` ≤ `this.ptr` ≤ `this.end`,
176        // so the `offset_from_unsigned`s below cannot wrap, and will produce a well-formed
177        // range. `end` ≤ `buf + cap`, so the range will be in-bounds.
178        // Taking `alloc` is ok because nothing else is going to look at it,
179        // since our `Drop` impl isn't going to run so there's no more code.
180        unsafe {
181            let buf = this.buf.as_ptr();
182            let initialized = if T::IS_ZST {
183                // All the pointers are the same for ZSTs, so it's fine to
184                // say that they're all at the beginning of the "allocation".
185                0..this.len()
186            } else {
187                this.ptr.offset_from_unsigned(this.buf)..this.end.offset_from_unsigned(buf)
188            };
189            let cap = this.cap;
190            let alloc = ManuallyDrop::take(&mut this.alloc);
191            VecDeque::from_contiguous_raw_parts_in(buf, initialized, cap, alloc)
192        }
193    }
194}
195
196#[stable(feature = "vec_intoiter_as_ref", since = "1.46.0")]
197impl<T, A: Allocator> AsRef<[T]> for IntoIter<T, A> {
198    fn as_ref(&self) -> &[T] {
199        self.as_slice()
200    }
201}
202
203#[stable(feature = "rust1", since = "1.0.0")]
204unsafe impl<T: Send, A: Allocator + Send> Send for IntoIter<T, A> {}
205#[stable(feature = "rust1", since = "1.0.0")]
206unsafe impl<T: Sync, A: Allocator + Sync> Sync for IntoIter<T, A> {}
207
208#[stable(feature = "rust1", since = "1.0.0")]
209impl<T, A: Allocator> Iterator for IntoIter<T, A> {
210    type Item = T;
211
212    #[inline]
213    fn next(&mut self) -> Option<T> {
214        let ptr = if T::IS_ZST {
215            if self.ptr.as_ptr() == self.end as *mut T {
216                return None;
217            }
218            // `ptr` has to stay where it is to remain aligned, so we reduce the length by 1 by
219            // reducing the `end`.
220            self.end = self.end.wrapping_byte_sub(1);
221            self.ptr
222        } else {
223            if self.ptr == non_null!(self.end, T) {
224                return None;
225            }
226            let old = self.ptr;
227            self.ptr = unsafe { old.add(1) };
228            old
229        };
230        Some(unsafe { ptr.read() })
231    }
232
233    #[inline]
234    fn size_hint(&self) -> (usize, Option<usize>) {
235        let exact = if T::IS_ZST {
236            self.end.addr().wrapping_sub(self.ptr.as_ptr().addr())
237        } else {
238            unsafe { non_null!(self.end, T).offset_from_unsigned(self.ptr) }
239        };
240        (exact, Some(exact))
241    }
242
243    #[inline]
244    fn advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
245        let step_size = self.len().min(n);
246        let to_drop = ptr::slice_from_raw_parts_mut(self.ptr.as_ptr(), step_size);
247        if T::IS_ZST {
248            // See `next` for why we sub `end` here.
249            self.end = self.end.wrapping_byte_sub(step_size);
250        } else {
251            // SAFETY: the min() above ensures that step_size is in bounds
252            self.ptr = unsafe { self.ptr.add(step_size) };
253        }
254        // SAFETY: the min() above ensures that step_size is in bounds
255        unsafe {
256            ptr::drop_in_place(to_drop);
257        }
258        NonZero::new(n - step_size).map_or(Ok(()), Err)
259    }
260
261    #[inline]
262    fn count(self) -> usize {
263        self.len()
264    }
265
266    #[inline]
267    fn last(mut self) -> Option<T> {
268        self.next_back()
269    }
270
271    #[inline]
272    fn next_chunk<const N: usize>(&mut self) -> Result<[T; N], core::array::IntoIter<T, N>> {
273        let mut raw_ary = [const { MaybeUninit::uninit() }; N];
274
275        let len = self.len();
276
277        if T::IS_ZST {
278            if len < N {
279                self.forget_remaining_elements();
280                // Safety: ZSTs can be conjured ex nihilo, only the amount has to be correct
281                return Err(unsafe { array::IntoIter::new_unchecked(raw_ary, 0..len) });
282            }
283
284            self.end = self.end.wrapping_byte_sub(N);
285            // Safety: ditto
286            return Ok(unsafe { raw_ary.transpose().assume_init() });
287        }
288
289        if len < N {
290            // Safety: `len` indicates that this many elements are available and we just checked that
291            // it fits into the array.
292            unsafe {
293                ptr::copy_nonoverlapping(self.ptr.as_ptr(), raw_ary.as_mut_ptr() as *mut T, len);
294                self.forget_remaining_elements();
295                return Err(array::IntoIter::new_unchecked(raw_ary, 0..len));
296            }
297        }
298
299        // Safety: `len` is larger than the array size. Copy a fixed amount here to fully initialize
300        // the array.
301        unsafe {
302            ptr::copy_nonoverlapping(self.ptr.as_ptr(), raw_ary.as_mut_ptr() as *mut T, N);
303            self.ptr = self.ptr.add(N);
304            Ok(raw_ary.transpose().assume_init())
305        }
306    }
307
308    fn fold<B, F>(mut self, mut accum: B, mut f: F) -> B
309    where
310        F: FnMut(B, Self::Item) -> B,
311    {
312        if T::IS_ZST {
313            while self.ptr.as_ptr() != self.end.cast_mut() {
314                // SAFETY: we just checked that `self.ptr` is in bounds.
315                let tmp = unsafe { self.ptr.read() };
316                // See `next` for why we subtract from `end` here.
317                self.end = self.end.wrapping_byte_sub(1);
318                accum = f(accum, tmp);
319            }
320        } else {
321            // SAFETY: `self.end` can only be null if `T` is a ZST.
322            while self.ptr != non_null!(self.end, T) {
323                // SAFETY: we just checked that `self.ptr` is in bounds.
324                let tmp = unsafe { self.ptr.read() };
325                // SAFETY: the maximum this can be is `self.end`.
326                // Increment `self.ptr` first to avoid double dropping in the event of a panic.
327                self.ptr = unsafe { self.ptr.add(1) };
328                accum = f(accum, tmp);
329            }
330        }
331        accum
332    }
333
334    fn try_fold<B, F, R>(&mut self, mut accum: B, mut f: F) -> R
335    where
336        Self: Sized,
337        F: FnMut(B, Self::Item) -> R,
338        R: core::ops::Try<Output = B>,
339    {
340        if T::IS_ZST {
341            while self.ptr.as_ptr() != self.end.cast_mut() {
342                // SAFETY: we just checked that `self.ptr` is in bounds.
343                let tmp = unsafe { self.ptr.read() };
344                // See `next` for why we subtract from `end` here.
345                self.end = self.end.wrapping_byte_sub(1);
346                accum = f(accum, tmp)?;
347            }
348        } else {
349            // SAFETY: `self.end` can only be null if `T` is a ZST.
350            while self.ptr != non_null!(self.end, T) {
351                // SAFETY: we just checked that `self.ptr` is in bounds.
352                let tmp = unsafe { self.ptr.read() };
353                // SAFETY: the maximum this can be is `self.end`.
354                // Increment `self.ptr` first to avoid double dropping in the event of a panic.
355                self.ptr = unsafe { self.ptr.add(1) };
356                accum = f(accum, tmp)?;
357            }
358        }
359        R::from_output(accum)
360    }
361
362    unsafe fn __iterator_get_unchecked(&mut self, i: usize) -> Self::Item
363    where
364        Self: TrustedRandomAccessNoCoerce,
365    {
366        // SAFETY: the caller must guarantee that `i` is in bounds of the
367        // `Vec<T>`, so `i` cannot overflow an `isize`, and the `self.ptr.add(i)`
368        // is guaranteed to pointer to an element of the `Vec<T>` and
369        // thus guaranteed to be valid to dereference.
370        //
371        // Also note the implementation of `Self: TrustedRandomAccess` requires
372        // that `T: Copy` so reading elements from the buffer doesn't invalidate
373        // them for `Drop`.
374        unsafe { self.ptr.add(i).read() }
375    }
376}
377
378#[stable(feature = "rust1", since = "1.0.0")]
379impl<T, A: Allocator> DoubleEndedIterator for IntoIter<T, A> {
380    #[inline]
381    fn next_back(&mut self) -> Option<T> {
382        if T::IS_ZST {
383            if self.ptr.as_ptr() == self.end as *mut _ {
384                return None;
385            }
386            // See above for why 'ptr.offset' isn't used
387            self.end = self.end.wrapping_byte_sub(1);
388            // Note that even though this is next_back() we're reading from `self.ptr`, not
389            // `self.end`. We track our length using the byte offset from `self.ptr` to `self.end`,
390            // so the end pointer may not be suitably aligned for T.
391            Some(unsafe { ptr::read(self.ptr.as_ptr()) })
392        } else {
393            if self.ptr == non_null!(self.end, T) {
394                return None;
395            }
396            unsafe {
397                self.end = self.end.sub(1);
398                Some(ptr::read(self.end))
399            }
400        }
401    }
402
403    #[inline]
404    fn advance_back_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
405        let step_size = self.len().min(n);
406        if T::IS_ZST {
407            // SAFETY: same as for advance_by()
408            self.end = self.end.wrapping_byte_sub(step_size);
409        } else {
410            // SAFETY: same as for advance_by()
411            self.end = unsafe { self.end.sub(step_size) };
412        }
413        let to_drop = if T::IS_ZST {
414            // ZST may cause unalignment
415            ptr::slice_from_raw_parts_mut(ptr::NonNull::<T>::dangling().as_ptr(), step_size)
416        } else {
417            ptr::slice_from_raw_parts_mut(self.end as *mut T, step_size)
418        };
419        // SAFETY: same as for advance_by()
420        unsafe {
421            ptr::drop_in_place(to_drop);
422        }
423        NonZero::new(n - step_size).map_or(Ok(()), Err)
424    }
425}
426
427#[stable(feature = "rust1", since = "1.0.0")]
428impl<T, A: Allocator> ExactSizeIterator for IntoIter<T, A> {
429    fn is_empty(&self) -> bool {
430        if T::IS_ZST {
431            self.ptr.as_ptr() == self.end as *mut _
432        } else {
433            self.ptr == non_null!(self.end, T)
434        }
435    }
436}
437
438#[stable(feature = "fused", since = "1.26.0")]
439impl<T, A: Allocator> FusedIterator for IntoIter<T, A> {}
440
441#[doc(hidden)]
442#[unstable(issue = "none", feature = "trusted_fused")]
443unsafe impl<T, A: Allocator> TrustedFused for IntoIter<T, A> {}
444
445#[unstable(feature = "trusted_len", issue = "37572")]
446unsafe impl<T, A: Allocator> TrustedLen for IntoIter<T, A> {}
447
448#[stable(feature = "default_iters", since = "1.70.0")]
449impl<T, A> Default for IntoIter<T, A>
450where
451    A: Allocator + Default,
452{
453    /// Creates an empty `vec::IntoIter`.
454    ///
455    /// ```
456    /// # use std::vec;
457    /// let iter: vec::IntoIter<u8> = Default::default();
458    /// assert_eq!(iter.len(), 0);
459    /// assert_eq!(iter.as_slice(), &[]);
460    /// ```
461    fn default() -> Self {
462        super::Vec::new_in(Default::default()).into_iter()
463    }
464}
465
466#[doc(hidden)]
467#[unstable(issue = "none", feature = "std_internals")]
468#[rustc_unsafe_specialization_marker]
469pub trait NonDrop {}
470
471// T: Copy as approximation for !Drop since get_unchecked does not advance self.ptr
472// and thus we can't implement drop-handling
473#[unstable(issue = "none", feature = "std_internals")]
474impl<T: Copy> NonDrop for T {}
475
476#[doc(hidden)]
477#[unstable(issue = "none", feature = "std_internals")]
478// TrustedRandomAccess (without NoCoerce) must not be implemented because
479// subtypes/supertypes of `T` might not be `NonDrop`
480unsafe impl<T, A: Allocator> TrustedRandomAccessNoCoerce for IntoIter<T, A>
481where
482    T: NonDrop,
483{
484    const MAY_HAVE_SIDE_EFFECT: bool = false;
485}
486
487#[cfg(not(no_global_oom_handling))]
488#[stable(feature = "vec_into_iter_clone", since = "1.8.0")]
489impl<T: Clone, A: Allocator + Clone> Clone for IntoIter<T, A> {
490    fn clone(&self) -> Self {
491        self.as_slice().to_vec_in(self.alloc.deref().clone()).into_iter()
492    }
493}
494
495#[stable(feature = "rust1", since = "1.0.0")]
496unsafe impl<#[may_dangle] T, A: Allocator> Drop for IntoIter<T, A> {
497    fn drop(&mut self) {
498        struct DropGuard<'a, T, A: Allocator>(&'a mut IntoIter<T, A>);
499
500        impl<T, A: Allocator> Drop for DropGuard<'_, T, A> {
501            fn drop(&mut self) {
502                unsafe {
503                    // `IntoIter::alloc` is not used anymore after this and will be dropped by RawVec
504                    let alloc = ManuallyDrop::take(&mut self.0.alloc);
505                    // RawVec handles deallocation
506                    let _ = RawVec::from_nonnull_in(self.0.buf, self.0.cap, alloc);
507                }
508            }
509        }
510
511        let guard = DropGuard(self);
512        // destroy the remaining elements
513        unsafe {
514            ptr::drop_in_place(guard.0.as_raw_mut_slice());
515        }
516        // now `guard` will be dropped and do the rest
517    }
518}
519
520// In addition to the SAFETY invariants of the following three unsafe traits
521// also refer to the vec::in_place_collect module documentation to get an overview
522#[unstable(issue = "none", feature = "inplace_iteration")]
523#[doc(hidden)]
524unsafe impl<T, A: Allocator> InPlaceIterable for IntoIter<T, A> {
525    const EXPAND_BY: Option<NonZero<usize>> = NonZero::new(1);
526    const MERGE_BY: Option<NonZero<usize>> = NonZero::new(1);
527}
528
529#[unstable(issue = "none", feature = "inplace_iteration")]
530#[doc(hidden)]
531unsafe impl<T, A: Allocator> SourceIter for IntoIter<T, A> {
532    type Source = Self;
533
534    #[inline]
535    unsafe fn as_inner(&mut self) -> &mut Self::Source {
536        self
537    }
538}
539
540#[cfg(not(no_global_oom_handling))]
541unsafe impl<T> AsVecIntoIter for IntoIter<T> {
542    type Item = T;
543
544    fn as_into_iter(&mut self) -> &mut IntoIter<Self::Item> {
545        self
546    }
547}