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