rune_alloc/vec/
into_iter.rs

1use core::fmt;
2use core::iter::FusedIterator;
3use core::marker::PhantomData;
4use core::mem::{self, ManuallyDrop};
5use core::slice::{self};
6
7use crate::alloc::SizedTypeProperties;
8use crate::alloc::{Allocator, Global};
9use crate::ptr::{self, NonNull};
10use crate::raw_vec::RawVec;
11
12/// 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> {
24    pub(super) buf: NonNull<T>,
25    pub(super) phantom: PhantomData<T>,
26    pub(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
29    pub(super) alloc: ManuallyDrop<A>,
30    pub(super) ptr: *const T,
31    pub(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}
35
36impl<T: fmt::Debug, A: Allocator> fmt::Debug for IntoIter<T, A> {
37    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38        f.debug_tuple("IntoIter").field(&self.as_slice()).finish()
39    }
40}
41
42impl<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    /// ```
54    pub fn as_slice(&self) -> &[T] {
55        unsafe { slice::from_raw_parts(self.ptr, self.len()) }
56    }
57
58    /// 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    /// ```
71    pub fn as_mut_slice(&mut self) -> &mut [T] {
72        unsafe { &mut *self.as_raw_mut_slice() }
73    }
74
75    /// Returns a reference to the underlying allocator.
76    #[inline]
77    pub fn allocator(&self) -> &A {
78        &self.alloc
79    }
80
81    fn as_raw_mut_slice(&mut self) -> *mut [T] {
82        ptr::slice_from_raw_parts_mut(self.ptr as *mut T, self.len())
83    }
84
85    /// Forgets to Drop the remaining elements while still allowing the backing allocation to be freed.
86    #[cfg(rune_nightly)]
87    pub(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.
90        self.end = self.ptr;
91    }
92}
93
94impl<T, A: Allocator> AsRef<[T]> for IntoIter<T, A> {
95    fn as_ref(&self) -> &[T] {
96        self.as_slice()
97    }
98}
99
100unsafe impl<T: Send, A: Allocator + Send> Send for IntoIter<T, A> {}
101unsafe impl<T: Sync, A: Allocator + Sync> Sync for IntoIter<T, A> {}
102
103impl<T, A: Allocator> Iterator for IntoIter<T, A> {
104    type Item = T;
105
106    #[inline]
107    fn next(&mut self) -> Option<T> {
108        if self.ptr == self.end {
109            None
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`.
113            self.end = self.end.wrapping_byte_sub(1);
114
115            // Make up a value of this ZST.
116            Some(unsafe { mem::zeroed() })
117        } else {
118            let old = self.ptr;
119            self.ptr = unsafe { self.ptr.add(1) };
120
121            Some(unsafe { ptr::read(old) })
122        }
123    }
124
125    #[inline]
126    fn size_hint(&self) -> (usize, Option<usize>) {
127        let exact = if T::IS_ZST {
128            ptr::addr(self.end).wrapping_sub(ptr::addr(self.ptr))
129        } else {
130            unsafe { ptr::sub_ptr(self.end, self.ptr) }
131        };
132        (exact, Some(exact))
133    }
134
135    #[inline]
136    fn count(self) -> usize {
137        self.len()
138    }
139}
140
141impl<T, A: Allocator> DoubleEndedIterator for IntoIter<T, A> {
142    #[inline]
143    fn next_back(&mut self) -> Option<T> {
144        if self.end == self.ptr {
145            None
146        } else if T::IS_ZST {
147            // See above for why 'ptr.offset' isn't used
148            self.end = self.end.wrapping_byte_sub(1);
149
150            // Make up a value of this ZST.
151            Some(unsafe { mem::zeroed() })
152        } else {
153            self.end = unsafe { self.end.sub(1) };
154
155            Some(unsafe { ptr::read(self.end) })
156        }
157    }
158}
159
160impl<T, A: Allocator> ExactSizeIterator for IntoIter<T, A> {}
161
162impl<T, A: Allocator> FusedIterator for IntoIter<T, A> {}
163
164impl<T, A> Default for IntoIter<T, A>
165where
166    A: 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    /// ```
176    fn default() -> Self {
177        super::Vec::new_in(Default::default()).into_iter()
178    }
179}
180
181#[cfg(rune_nightly)]
182unsafe impl<#[may_dangle] T, A: Allocator> Drop for IntoIter<T, A> {
183    fn drop(&mut self) {
184        struct DropGuard<'a, T, A: Allocator>(&'a mut IntoIter<T, A>);
185
186        impl<T, A: Allocator> Drop for DropGuard<'_, T, A> {
187            fn drop(&mut self) {
188                unsafe {
189                    // `IntoIter::alloc` is not used anymore after this and will be dropped by RawVec
190                    let alloc = ManuallyDrop::take(&mut self.0.alloc);
191                    // RawVec handles deallocation
192                    let _ = RawVec::from_raw_parts_in(self.0.buf.as_ptr(), self.0.cap, alloc);
193                }
194            }
195        }
196
197        let guard = DropGuard(self);
198        // destroy the remaining elements
199        unsafe {
200            ptr::drop_in_place(guard.0.as_raw_mut_slice());
201        }
202        // now `guard` will be dropped and do the rest
203    }
204}
205
206#[cfg(not(rune_nightly))]
207impl<T, A: Allocator> Drop for IntoIter<T, A> {
208    fn drop(&mut self) {
209        struct DropGuard<'a, T, A: Allocator>(&'a mut IntoIter<T, A>);
210
211        impl<T, A: Allocator> Drop for DropGuard<'_, T, A> {
212            fn drop(&mut self) {
213                unsafe {
214                    // `IntoIter::alloc` is not used anymore after this and will be dropped by RawVec
215                    let alloc = ManuallyDrop::take(&mut self.0.alloc);
216                    // RawVec handles deallocation
217                    let _ = RawVec::from_raw_parts_in(self.0.buf.as_ptr(), self.0.cap, alloc);
218                }
219            }
220        }
221
222        let guard = DropGuard(self);
223        // destroy the remaining elements
224        unsafe {
225            ptr::drop_in_place(guard.0.as_raw_mut_slice());
226        }
227        // now `guard` will be dropped and do the rest
228    }
229}