1use core::fmt;
2use core::iter::FusedIterator;
3use core::marker::PhantomData;
4use core::mem::{self, ManuallyDrop};
5use core::slice::{self};
67use crate::alloc::SizedTypeProperties;
8use crate::alloc::{Allocator, Global};
9use crate::ptr::{self, NonNull};
10use crate::raw_vec::RawVec;
1112/// An iterator that moves out of a vector.
13///
14/// This `struct` is created by the `into_iter` method on [`Vec`](super::Vec)
15/// (provided by the [`IntoIterator`] trait).
16///
17/// # Example
18///
19/// ```
20/// let v = vec![0, 1, 2];
21/// let iter: std::vec::IntoIter<_> = v.into_iter();
22/// ```
23pub struct IntoIter<T, A: Allocator = Global> {
24pub(super) buf: NonNull<T>,
25pub(super) phantom: PhantomData<T>,
26pub(super) cap: usize,
27// the drop impl reconstructs a RawVec from buf, cap and alloc
28 // to avoid dropping the allocator twice we need to wrap it into ManuallyDrop
29pub(super) alloc: ManuallyDrop<A>,
30pub(super) ptr: *const T,
31pub(super) end: *const T, // If T is a ZST, this is actually ptr+len. This encoding is picked so that
32 // ptr == end is a quick test for the Iterator being empty, that works
33 // for both ZST and non-ZST.
34}
3536impl<T: fmt::Debug, A: Allocator> fmt::Debug for IntoIter<T, A> {
37fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38 f.debug_tuple("IntoIter").field(&self.as_slice()).finish()
39 }
40}
4142impl<T, A: Allocator> IntoIter<T, A> {
43/// Returns the remaining items of this iterator as a slice.
44 ///
45 /// # Examples
46 ///
47 /// ```
48 /// let vec = vec!['a', 'b', 'c'];
49 /// let mut into_iter = vec.into_iter();
50 /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']);
51 /// let _ = into_iter.next().unwrap();
52 /// assert_eq!(into_iter.as_slice(), &['b', 'c']);
53 /// ```
54pub fn as_slice(&self) -> &[T] {
55unsafe { slice::from_raw_parts(self.ptr, self.len()) }
56 }
5758/// Returns the remaining items of this iterator as a mutable slice.
59 ///
60 /// # Examples
61 ///
62 /// ```
63 /// let vec = vec!['a', 'b', 'c'];
64 /// let mut into_iter = vec.into_iter();
65 /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']);
66 /// into_iter.as_mut_slice()[2] = 'z';
67 /// assert_eq!(into_iter.next().unwrap(), 'a');
68 /// assert_eq!(into_iter.next().unwrap(), 'b');
69 /// assert_eq!(into_iter.next().unwrap(), 'z');
70 /// ```
71pub fn as_mut_slice(&mut self) -> &mut [T] {
72unsafe { &mut *self.as_raw_mut_slice() }
73 }
7475/// Returns a reference to the underlying allocator.
76#[inline]
77pub fn allocator(&self) -> &A {
78&self.alloc
79 }
8081fn as_raw_mut_slice(&mut self) -> *mut [T] {
82 ptr::slice_from_raw_parts_mut(self.ptr as *mut T, self.len())
83 }
8485/// Forgets to Drop the remaining elements while still allowing the backing allocation to be freed.
86#[cfg(rune_nightly)]
87pub(crate) fn forget_remaining_elements(&mut self) {
88// For th ZST case, it is crucial that we mutate `end` here, not `ptr`.
89 // `ptr` must stay aligned, while `end` may be unaligned.
90self.end = self.ptr;
91 }
92}
9394impl<T, A: Allocator> AsRef<[T]> for IntoIter<T, A> {
95fn as_ref(&self) -> &[T] {
96self.as_slice()
97 }
98}
99100unsafe impl<T: Send, A: Allocator + Send> Send for IntoIter<T, A> {}
101unsafe impl<T: Sync, A: Allocator + Sync> Sync for IntoIter<T, A> {}
102103impl<T, A: Allocator> Iterator for IntoIter<T, A> {
104type Item = T;
105106#[inline]
107fn next(&mut self) -> Option<T> {
108if self.ptr == self.end {
109None
110} else if T::IS_ZST {
111// `ptr` has to stay where it is to remain aligned, so we reduce the length by 1 by
112 // reducing the `end`.
113self.end = self.end.wrapping_byte_sub(1);
114115// Make up a value of this ZST.
116Some(unsafe { mem::zeroed() })
117 } else {
118let old = self.ptr;
119self.ptr = unsafe { self.ptr.add(1) };
120121Some(unsafe { ptr::read(old) })
122 }
123 }
124125#[inline]
126fn size_hint(&self) -> (usize, Option<usize>) {
127let exact = if T::IS_ZST {
128 ptr::addr(self.end).wrapping_sub(ptr::addr(self.ptr))
129 } else {
130unsafe { ptr::sub_ptr(self.end, self.ptr) }
131 };
132 (exact, Some(exact))
133 }
134135#[inline]
136fn count(self) -> usize {
137self.len()
138 }
139}
140141impl<T, A: Allocator> DoubleEndedIterator for IntoIter<T, A> {
142#[inline]
143fn next_back(&mut self) -> Option<T> {
144if self.end == self.ptr {
145None
146} else if T::IS_ZST {
147// See above for why 'ptr.offset' isn't used
148self.end = self.end.wrapping_byte_sub(1);
149150// Make up a value of this ZST.
151Some(unsafe { mem::zeroed() })
152 } else {
153self.end = unsafe { self.end.sub(1) };
154155Some(unsafe { ptr::read(self.end) })
156 }
157 }
158}
159160impl<T, A: Allocator> ExactSizeIterator for IntoIter<T, A> {}
161162impl<T, A: Allocator> FusedIterator for IntoIter<T, A> {}
163164impl<T, A> Default for IntoIter<T, A>
165where
166A: Allocator + Default,
167{
168/// Creates an empty `vec::IntoIter`.
169 ///
170 /// ```
171 /// # use std::vec;
172 /// let iter: vec::IntoIter<u8> = Default::default();
173 /// assert_eq!(iter.len(), 0);
174 /// assert_eq!(iter.as_slice(), &[]);
175 /// ```
176fn default() -> Self {
177super::Vec::new_in(Default::default()).into_iter()
178 }
179}
180181#[cfg(rune_nightly)]
182unsafe impl<#[may_dangle] T, A: Allocator> Drop for IntoIter<T, A> {
183fn drop(&mut self) {
184struct DropGuard<'a, T, A: Allocator>(&'a mut IntoIter<T, A>);
185186impl<T, A: Allocator> Drop for DropGuard<'_, T, A> {
187fn drop(&mut self) {
188unsafe {
189// `IntoIter::alloc` is not used anymore after this and will be dropped by RawVec
190let alloc = ManuallyDrop::take(&mut self.0.alloc);
191// RawVec handles deallocation
192let _ = RawVec::from_raw_parts_in(self.0.buf.as_ptr(), self.0.cap, alloc);
193 }
194 }
195 }
196197let guard = DropGuard(self);
198// destroy the remaining elements
199unsafe {
200 ptr::drop_in_place(guard.0.as_raw_mut_slice());
201 }
202// now `guard` will be dropped and do the rest
203}
204}
205206#[cfg(not(rune_nightly))]
207impl<T, A: Allocator> Drop for IntoIter<T, A> {
208fn drop(&mut self) {
209struct DropGuard<'a, T, A: Allocator>(&'a mut IntoIter<T, A>);
210211impl<T, A: Allocator> Drop for DropGuard<'_, T, A> {
212fn drop(&mut self) {
213unsafe {
214// `IntoIter::alloc` is not used anymore after this and will be dropped by RawVec
215let alloc = ManuallyDrop::take(&mut self.0.alloc);
216// RawVec handles deallocation
217let _ = RawVec::from_raw_parts_in(self.0.buf.as_ptr(), self.0.cap, alloc);
218 }
219 }
220 }
221222let guard = DropGuard(self);
223// destroy the remaining elements
224unsafe {
225 ptr::drop_in_place(guard.0.as_raw_mut_slice());
226 }
227// now `guard` will be dropped and do the rest
228}
229}