1 // SPDX-License-Identifier: Apache-2.0 OR MIT
3 use crate::alloc::{Allocator, Global};
5 use core::iter::{FusedIterator, TrustedLen};
7 use core::ptr::{self, NonNull};
8 use core::slice::{self};
12 /// A draining iterator for `Vec<T>`.
14 /// This `struct` is created by [`Vec::drain`].
15 /// See its documentation for more.
20 /// let mut v = vec![0, 1, 2];
21 /// let iter: std::vec::Drain<_> = v.drain(..);
23 #[stable(feature = "drain", since = "1.6.0")]
27 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator + 'a = Global,
29 /// Index of tail to preserve
30 pub(super) tail_start: usize,
32 pub(super) tail_len: usize,
33 /// Current remaining range to remove
34 pub(super) iter: slice::Iter<'a, T>,
35 pub(super) vec: NonNull<Vec<T, A>>,
38 #[stable(feature = "collection_debug", since = "1.17.0")]
39 impl<T: fmt::Debug, A: Allocator> fmt::Debug for Drain<'_, T, A> {
40 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
41 f.debug_tuple("Drain").field(&self.iter.as_slice()).finish()
45 impl<'a, T, A: Allocator> Drain<'a, T, A> {
46 /// Returns the remaining items of this iterator as a slice.
51 /// let mut vec = vec!['a', 'b', 'c'];
52 /// let mut drain = vec.drain(..);
53 /// assert_eq!(drain.as_slice(), &['a', 'b', 'c']);
54 /// let _ = drain.next().unwrap();
55 /// assert_eq!(drain.as_slice(), &['b', 'c']);
58 #[stable(feature = "vec_drain_as_slice", since = "1.46.0")]
59 pub fn as_slice(&self) -> &[T] {
63 /// Returns a reference to the underlying allocator.
64 #[unstable(feature = "allocator_api", issue = "32838")]
67 pub fn allocator(&self) -> &A {
68 unsafe { self.vec.as_ref().allocator() }
72 #[stable(feature = "vec_drain_as_slice", since = "1.46.0")]
73 impl<'a, T, A: Allocator> AsRef<[T]> for Drain<'a, T, A> {
74 fn as_ref(&self) -> &[T] {
79 #[stable(feature = "drain", since = "1.6.0")]
80 unsafe impl<T: Sync, A: Sync + Allocator> Sync for Drain<'_, T, A> {}
81 #[stable(feature = "drain", since = "1.6.0")]
82 unsafe impl<T: Send, A: Send + Allocator> Send for Drain<'_, T, A> {}
84 #[stable(feature = "drain", since = "1.6.0")]
85 impl<T, A: Allocator> Iterator for Drain<'_, T, A> {
89 fn next(&mut self) -> Option<T> {
90 self.iter.next().map(|elt| unsafe { ptr::read(elt as *const _) })
93 fn size_hint(&self) -> (usize, Option<usize>) {
98 #[stable(feature = "drain", since = "1.6.0")]
99 impl<T, A: Allocator> DoubleEndedIterator for Drain<'_, T, A> {
101 fn next_back(&mut self) -> Option<T> {
102 self.iter.next_back().map(|elt| unsafe { ptr::read(elt as *const _) })
106 #[stable(feature = "drain", since = "1.6.0")]
107 impl<T, A: Allocator> Drop for Drain<'_, T, A> {
109 /// Moves back the un-`Drain`ed elements to restore the original `Vec`.
110 struct DropGuard<'r, 'a, T, A: Allocator>(&'r mut Drain<'a, T, A>);
112 impl<'r, 'a, T, A: Allocator> Drop for DropGuard<'r, 'a, T, A> {
114 if self.0.tail_len > 0 {
116 let source_vec = self.0.vec.as_mut();
117 // memmove back untouched tail, update to new length
118 let start = source_vec.len();
119 let tail = self.0.tail_start;
121 let src = source_vec.as_ptr().add(tail);
122 let dst = source_vec.as_mut_ptr().add(start);
123 ptr::copy(src, dst, self.0.tail_len);
125 source_vec.set_len(start + self.0.tail_len);
131 let iter = mem::replace(&mut self.iter, (&mut []).iter());
132 let drop_len = iter.len();
134 let mut vec = self.vec;
136 if mem::size_of::<T>() == 0 {
137 // ZSTs have no identity, so we don't need to move them around, we only need to drop the correct amount.
138 // this can be achieved by manipulating the Vec length instead of moving values out from `iter`.
140 let vec = vec.as_mut();
141 let old_len = vec.len();
142 vec.set_len(old_len + drop_len + self.tail_len);
143 vec.truncate(old_len + self.tail_len);
149 // ensure elements are moved back into their appropriate places, even when drop_in_place panics
150 let _guard = DropGuard(self);
156 // as_slice() must only be called when iter.len() is > 0 because
157 // vec::Splice modifies vec::Drain fields and may grow the vec which would invalidate
158 // the iterator's internal pointers. Creating a reference to deallocated memory
159 // is invalid even when it is zero-length
160 let drop_ptr = iter.as_slice().as_ptr();
163 // drop_ptr comes from a slice::Iter which only gives us a &[T] but for drop_in_place
164 // a pointer with mutable provenance is necessary. Therefore we must reconstruct
165 // it from the original vec but also avoid creating a &mut to the front since that could
166 // invalidate raw pointers to it which some unsafe code might rely on.
167 let vec_ptr = vec.as_mut().as_mut_ptr();
168 let drop_offset = drop_ptr.sub_ptr(vec_ptr);
169 let to_drop = ptr::slice_from_raw_parts_mut(vec_ptr.add(drop_offset), drop_len);
170 ptr::drop_in_place(to_drop);
175 #[stable(feature = "drain", since = "1.6.0")]
176 impl<T, A: Allocator> ExactSizeIterator for Drain<'_, T, A> {
177 fn is_empty(&self) -> bool {
182 #[unstable(feature = "trusted_len", issue = "37572")]
183 unsafe impl<T, A: Allocator> TrustedLen for Drain<'_, T, A> {}
185 #[stable(feature = "fused", since = "1.26.0")]
186 impl<T, A: Allocator> FusedIterator for Drain<'_, T, A> {}