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)] unsafe { &mut *((&raw mut $place) as *mut NonNull<$t>) }
25 }},
26 ($place:expr, $t:ident) => {{
27 #![allow(unused_unsafe)] unsafe { *((&raw const $place) as *const NonNull<$t>) }
29 }},
30}
31
32#[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 pub(super) alloc: ManuallyDrop<A>,
55 pub(super) ptr: NonNull<T>,
56 pub(super) end: *const T,
61}
62
63#[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 #[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 #[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 #[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 #[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 self.cap = 0;
150 self.buf = RawVec::new().non_null();
151 self.ptr = self.buf;
152 self.end = self.buf.as_ptr();
153
154 unsafe {
157 ptr::drop_in_place(remaining);
158 }
159 }
160
161 pub(crate) fn forget_remaining_elements(&mut self) {
163 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 let mut this = ManuallyDrop::new(self);
173
174 unsafe {
181 let buf = this.buf.as_ptr();
182 let initialized = if T::IS_ZST {
183 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 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 self.end = self.end.wrapping_byte_sub(step_size);
250 } else {
251 self.ptr = unsafe { self.ptr.add(step_size) };
253 }
254 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 return Err(unsafe { array::IntoIter::new_unchecked(raw_ary, 0..len) });
282 }
283
284 self.end = self.end.wrapping_byte_sub(N);
285 return Ok(unsafe { raw_ary.transpose().assume_init() });
287 }
288
289 if len < N {
290 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 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 let tmp = unsafe { self.ptr.read() };
316 self.end = self.end.wrapping_byte_sub(1);
318 accum = f(accum, tmp);
319 }
320 } else {
321 while self.ptr != non_null!(self.end, T) {
323 let tmp = unsafe { self.ptr.read() };
325 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 let tmp = unsafe { self.ptr.read() };
344 self.end = self.end.wrapping_byte_sub(1);
346 accum = f(accum, tmp)?;
347 }
348 } else {
349 while self.ptr != non_null!(self.end, T) {
351 let tmp = unsafe { self.ptr.read() };
353 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 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 self.end = self.end.wrapping_byte_sub(1);
388 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 self.end = self.end.wrapping_byte_sub(step_size);
409 } else {
410 self.end = unsafe { self.end.sub(step_size) };
412 }
413 let to_drop = if T::IS_ZST {
414 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 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 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#[unstable(issue = "none", feature = "std_internals")]
474impl<T: Copy> NonDrop for T {}
475
476#[doc(hidden)]
477#[unstable(issue = "none", feature = "std_internals")]
478unsafe 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 let alloc = ManuallyDrop::take(&mut self.0.alloc);
505 let _ = RawVec::from_nonnull_in(self.0.buf, self.0.cap, alloc);
507 }
508 }
509 }
510
511 let guard = DropGuard(self);
512 unsafe {
514 ptr::drop_in_place(guard.0.as_raw_mut_slice());
515 }
516 }
518}
519
520#[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}