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