1 #[cfg(not(no_global_oom_handling))]
2 use super::AsVecIntoIter;
3 use crate::alloc::{Allocator, Global};
4 use crate::raw_vec::RawVec;
8 FusedIterator, InPlaceIterable, SourceIter, TrustedLen, TrustedRandomAccessNoCoerce,
10 use core::marker::PhantomData;
11 use core::mem::{self, ManuallyDrop, MaybeUninit, SizedTypeProperties};
12 #[cfg(not(no_global_oom_handling))]
14 use core::ptr::{self, NonNull};
15 use core::slice::{self};
17 /// An iterator that moves out of a vector.
19 /// This `struct` is created by the `into_iter` method on [`Vec`](super::Vec)
20 /// (provided by the [`IntoIterator`] trait).
25 /// let v = vec![0, 1, 2];
26 /// let iter: std::vec::IntoIter<_> = v.into_iter();
28 #[stable(feature = "rust1", since = "1.0.0")]
29 #[rustc_insignificant_dtor]
32 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
34 pub(super) buf: NonNull<T>,
35 pub(super) phantom: PhantomData<T>,
36 pub(super) cap: usize,
37 // the drop impl reconstructs a RawVec from buf, cap and alloc
38 // to avoid dropping the allocator twice we need to wrap it into ManuallyDrop
39 pub(super) alloc: ManuallyDrop<A>,
40 pub(super) ptr: *const T,
41 pub(super) end: *const T,
44 #[stable(feature = "vec_intoiter_debug", since = "1.13.0")]
45 impl<T: fmt::Debug, A: Allocator> fmt::Debug for IntoIter<T, A> {
46 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
47 f.debug_tuple("IntoIter").field(&self.as_slice()).finish()
51 impl<T, A: Allocator> IntoIter<T, A> {
52 /// Returns the remaining items of this iterator as a slice.
57 /// let vec = vec!['a', 'b', 'c'];
58 /// let mut into_iter = vec.into_iter();
59 /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']);
60 /// let _ = into_iter.next().unwrap();
61 /// assert_eq!(into_iter.as_slice(), &['b', 'c']);
63 #[stable(feature = "vec_into_iter_as_slice", since = "1.15.0")]
64 pub fn as_slice(&self) -> &[T] {
65 unsafe { slice::from_raw_parts(self.ptr, self.len()) }
68 /// Returns the remaining items of this iterator as a mutable slice.
73 /// let vec = vec!['a', 'b', 'c'];
74 /// let mut into_iter = vec.into_iter();
75 /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']);
76 /// into_iter.as_mut_slice()[2] = 'z';
77 /// assert_eq!(into_iter.next().unwrap(), 'a');
78 /// assert_eq!(into_iter.next().unwrap(), 'b');
79 /// assert_eq!(into_iter.next().unwrap(), 'z');
81 #[stable(feature = "vec_into_iter_as_slice", since = "1.15.0")]
82 pub fn as_mut_slice(&mut self) -> &mut [T] {
83 unsafe { &mut *self.as_raw_mut_slice() }
86 /// Returns a reference to the underlying allocator.
87 #[unstable(feature = "allocator_api", issue = "32838")]
89 pub fn allocator(&self) -> &A {
93 fn as_raw_mut_slice(&mut self) -> *mut [T] {
94 ptr::slice_from_raw_parts_mut(self.ptr as *mut T, self.len())
97 /// Drops remaining elements and relinquishes the backing allocation.
98 /// This method guarantees it won't panic before relinquishing
99 /// the backing allocation.
101 /// This is roughly equivalent to the following, but more efficient
104 /// # let mut into_iter = Vec::<u8>::with_capacity(10).into_iter();
105 /// let mut into_iter = std::mem::replace(&mut into_iter, Vec::new().into_iter());
106 /// (&mut into_iter).for_each(core::mem::drop);
107 /// std::mem::forget(into_iter);
110 /// This method is used by in-place iteration, refer to the vec::in_place_collect
111 /// documentation for an overview.
112 #[cfg(not(no_global_oom_handling))]
113 pub(super) fn forget_allocation_drop_remaining(&mut self) {
114 let remaining = self.as_raw_mut_slice();
116 // overwrite the individual fields instead of creating a new
117 // struct and then overwriting &mut self.
118 // this creates less assembly
120 self.buf = unsafe { NonNull::new_unchecked(RawVec::NEW.ptr()) };
121 self.ptr = self.buf.as_ptr();
122 self.end = self.buf.as_ptr();
124 // Dropping the remaining elements can panic, so this needs to be
125 // done only after updating the other fields.
127 ptr::drop_in_place(remaining);
131 /// Forgets to Drop the remaining elements while still allowing the backing allocation to be freed.
132 pub(crate) fn forget_remaining_elements(&mut self) {
137 #[stable(feature = "vec_intoiter_as_ref", since = "1.46.0")]
138 impl<T, A: Allocator> AsRef<[T]> for IntoIter<T, A> {
139 fn as_ref(&self) -> &[T] {
144 #[stable(feature = "rust1", since = "1.0.0")]
145 unsafe impl<T: Send, A: Allocator + Send> Send for IntoIter<T, A> {}
146 #[stable(feature = "rust1", since = "1.0.0")]
147 unsafe impl<T: Sync, A: Allocator + Sync> Sync for IntoIter<T, A> {}
149 #[stable(feature = "rust1", since = "1.0.0")]
150 impl<T, A: Allocator> Iterator for IntoIter<T, A> {
154 fn next(&mut self) -> Option<T> {
155 if self.ptr == self.end {
157 } else if T::IS_ZST {
158 // purposefully don't use 'ptr.offset' because for
159 // vectors with 0-size elements this would return the
161 self.ptr = self.ptr.wrapping_byte_add(1);
163 // Make up a value of this ZST.
164 Some(unsafe { mem::zeroed() })
167 self.ptr = unsafe { self.ptr.add(1) };
169 Some(unsafe { ptr::read(old) })
174 fn size_hint(&self) -> (usize, Option<usize>) {
175 let exact = if T::IS_ZST {
176 self.end.addr().wrapping_sub(self.ptr.addr())
178 unsafe { self.end.sub_ptr(self.ptr) }
184 fn advance_by(&mut self, n: usize) -> Result<(), usize> {
185 let step_size = self.len().min(n);
186 let to_drop = ptr::slice_from_raw_parts_mut(self.ptr as *mut T, step_size);
188 // SAFETY: due to unchecked casts of unsigned amounts to signed offsets the wraparound
189 // effectively results in unsigned pointers representing positions 0..usize::MAX,
190 // which is valid for ZSTs.
191 self.ptr = self.ptr.wrapping_byte_add(step_size);
193 // SAFETY: the min() above ensures that step_size is in bounds
194 self.ptr = unsafe { self.ptr.add(step_size) };
196 // SAFETY: the min() above ensures that step_size is in bounds
198 ptr::drop_in_place(to_drop);
201 return Err(step_size);
207 fn count(self) -> usize {
212 fn next_chunk<const N: usize>(&mut self) -> Result<[T; N], core::array::IntoIter<T, N>> {
213 let mut raw_ary = MaybeUninit::uninit_array();
215 let len = self.len();
219 self.forget_remaining_elements();
220 // Safety: ZSTs can be conjured ex nihilo, only the amount has to be correct
221 return Err(unsafe { array::IntoIter::new_unchecked(raw_ary, 0..len) });
224 self.ptr = self.ptr.wrapping_byte_add(N);
226 return Ok(unsafe { raw_ary.transpose().assume_init() });
230 // Safety: `len` indicates that this many elements are available and we just checked that
231 // it fits into the array.
233 ptr::copy_nonoverlapping(self.ptr, raw_ary.as_mut_ptr() as *mut T, len);
234 self.forget_remaining_elements();
235 return Err(array::IntoIter::new_unchecked(raw_ary, 0..len));
239 // Safety: `len` is larger than the array size. Copy a fixed amount here to fully initialize
242 ptr::copy_nonoverlapping(self.ptr, raw_ary.as_mut_ptr() as *mut T, N);
243 self.ptr = self.ptr.add(N);
244 Ok(raw_ary.transpose().assume_init())
248 unsafe fn __iterator_get_unchecked(&mut self, i: usize) -> Self::Item
250 Self: TrustedRandomAccessNoCoerce,
252 // SAFETY: the caller must guarantee that `i` is in bounds of the
253 // `Vec<T>`, so `i` cannot overflow an `isize`, and the `self.ptr.add(i)`
254 // is guaranteed to pointer to an element of the `Vec<T>` and
255 // thus guaranteed to be valid to dereference.
257 // Also note the implementation of `Self: TrustedRandomAccess` requires
258 // that `T: Copy` so reading elements from the buffer doesn't invalidate
261 if T::IS_ZST { mem::zeroed() } else { ptr::read(self.ptr.add(i)) }
266 #[stable(feature = "rust1", since = "1.0.0")]
267 impl<T, A: Allocator> DoubleEndedIterator for IntoIter<T, A> {
269 fn next_back(&mut self) -> Option<T> {
270 if self.end == self.ptr {
272 } else if T::IS_ZST {
273 // See above for why 'ptr.offset' isn't used
274 self.end = self.end.wrapping_byte_sub(1);
276 // Make up a value of this ZST.
277 Some(unsafe { mem::zeroed() })
279 self.end = unsafe { self.end.sub(1) };
281 Some(unsafe { ptr::read(self.end) })
286 fn advance_back_by(&mut self, n: usize) -> Result<(), usize> {
287 let step_size = self.len().min(n);
289 // SAFETY: same as for advance_by()
290 self.end = self.end.wrapping_byte_sub(step_size);
292 // SAFETY: same as for advance_by()
293 self.end = unsafe { self.end.sub(step_size) };
295 let to_drop = ptr::slice_from_raw_parts_mut(self.end as *mut T, step_size);
296 // SAFETY: same as for advance_by()
298 ptr::drop_in_place(to_drop);
301 return Err(step_size);
307 #[stable(feature = "rust1", since = "1.0.0")]
308 impl<T, A: Allocator> ExactSizeIterator for IntoIter<T, A> {
309 fn is_empty(&self) -> bool {
314 #[stable(feature = "fused", since = "1.26.0")]
315 impl<T, A: Allocator> FusedIterator for IntoIter<T, A> {}
317 #[unstable(feature = "trusted_len", issue = "37572")]
318 unsafe impl<T, A: Allocator> TrustedLen for IntoIter<T, A> {}
321 #[unstable(issue = "none", feature = "std_internals")]
322 #[rustc_unsafe_specialization_marker]
325 // T: Copy as approximation for !Drop since get_unchecked does not advance self.ptr
326 // and thus we can't implement drop-handling
327 #[unstable(issue = "none", feature = "std_internals")]
328 impl<T: Copy> NonDrop for T {}
331 #[unstable(issue = "none", feature = "std_internals")]
332 // TrustedRandomAccess (without NoCoerce) must not be implemented because
333 // subtypes/supertypes of `T` might not be `NonDrop`
334 unsafe impl<T, A: Allocator> TrustedRandomAccessNoCoerce for IntoIter<T, A>
338 const MAY_HAVE_SIDE_EFFECT: bool = false;
341 #[cfg(not(no_global_oom_handling))]
342 #[stable(feature = "vec_into_iter_clone", since = "1.8.0")]
343 impl<T: Clone, A: Allocator + Clone> Clone for IntoIter<T, A> {
345 fn clone(&self) -> Self {
346 self.as_slice().to_vec_in(self.alloc.deref().clone()).into_iter()
349 fn clone(&self) -> Self {
350 crate::slice::to_vec(self.as_slice(), self.alloc.deref().clone()).into_iter()
354 #[stable(feature = "rust1", since = "1.0.0")]
355 unsafe impl<#[may_dangle] T, A: Allocator> Drop for IntoIter<T, A> {
357 struct DropGuard<'a, T, A: Allocator>(&'a mut IntoIter<T, A>);
359 impl<T, A: Allocator> Drop for DropGuard<'_, T, A> {
362 // `IntoIter::alloc` is not used anymore after this and will be dropped by RawVec
363 let alloc = ManuallyDrop::take(&mut self.0.alloc);
364 // RawVec handles deallocation
365 let _ = RawVec::from_raw_parts_in(self.0.buf.as_ptr(), self.0.cap, alloc);
370 let guard = DropGuard(self);
371 // destroy the remaining elements
373 ptr::drop_in_place(guard.0.as_raw_mut_slice());
375 // now `guard` will be dropped and do the rest
379 // In addition to the SAFETY invariants of the following three unsafe traits
380 // also refer to the vec::in_place_collect module documentation to get an overview
381 #[unstable(issue = "none", feature = "inplace_iteration")]
383 unsafe impl<T, A: Allocator> InPlaceIterable for IntoIter<T, A> {}
385 #[unstable(issue = "none", feature = "inplace_iteration")]
387 unsafe impl<T, A: Allocator> SourceIter for IntoIter<T, A> {
391 unsafe fn as_inner(&mut self) -> &mut Self::Source {
396 #[cfg(not(no_global_oom_handling))]
397 unsafe impl<T> AsVecIntoIter for IntoIter<T> {
400 fn as_into_iter(&mut self) -> &mut IntoIter<Self::Item> {