bump_scope/bump_vec/drain.rs
1#![cfg(feature = "panic-on-alloc")]
2//! This is not part of public api.
3//!
4//! This exists solely for the implementation of [`Splice`](crate::bump_vec::Splice).
5
6use core::{
7 fmt::{self, Debug},
8 iter::FusedIterator,
9 mem,
10 ptr::{self, NonNull},
11 slice::{self},
12};
13
14use crate::{BumpAllocatorExt, BumpVec, SizedTypeProperties};
15
16/// A draining iterator for `BumpVec<T>`.
17///
18/// This `struct` is not directly created by any method.
19/// It is an implementation detail of `Splice`.
20///
21/// The implementation of `drain` does not need a pointer to the whole `BumpVec`
22/// (and all the generic parameters that come with it).
23/// That's why we return `owned_slice::Drain` from `BumpVec::drain`.
24///
25/// However just like the standard library we use a `Drain` implementation to implement
26/// `Splice`. For this particular case we *do* need a pointer to `BumpVec`.
27pub struct Drain<'a, T: 'a, A: BumpAllocatorExt> {
28 /// Index of tail to preserve
29 pub(super) tail_start: usize,
30 /// Length of tail
31 pub(super) tail_len: usize,
32 /// Current remaining range to remove
33 pub(super) iter: slice::Iter<'a, T>,
34 pub(super) vec: NonNull<BumpVec<T, A>>,
35}
36
37impl<T: Debug, A: BumpAllocatorExt> Debug for Drain<'_, T, A> {
38 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
39 f.debug_tuple("Drain").field(&self.iter.as_slice()).finish()
40 }
41}
42
43impl<T, A: BumpAllocatorExt> Drain<'_, T, A> {
44 /// Returns the remaining items of this iterator as a slice.
45 ///
46 /// # Examples
47 ///
48 /// ```
49 /// let mut vec = vec!['a', 'b', 'c'];
50 /// let mut drain = vec.drain(..);
51 /// assert_eq!(drain.as_slice(), &['a', 'b', 'c']);
52 /// let _ = drain.next().unwrap();
53 /// assert_eq!(drain.as_slice(), &['b', 'c']);
54 /// ```
55 #[must_use]
56 #[inline(always)]
57 pub fn as_slice(&self) -> &[T] {
58 self.iter.as_slice()
59 }
60}
61
62impl<T, A: BumpAllocatorExt> AsRef<[T]> for Drain<'_, T, A> {
63 #[inline(always)]
64 fn as_ref(&self) -> &[T] {
65 self.as_slice()
66 }
67}
68
69impl<T, A: BumpAllocatorExt> Iterator for Drain<'_, T, A> {
70 type Item = T;
71
72 #[inline(always)]
73 fn next(&mut self) -> Option<T> {
74 self.iter.next().map(|elt| unsafe { ptr::read(elt) })
75 }
76
77 #[inline(always)]
78 fn size_hint(&self) -> (usize, Option<usize>) {
79 self.iter.size_hint()
80 }
81}
82
83impl<T, A: BumpAllocatorExt> DoubleEndedIterator for Drain<'_, T, A> {
84 #[inline(always)]
85 fn next_back(&mut self) -> Option<T> {
86 self.iter.next_back().map(|elt| unsafe { ptr::read(elt) })
87 }
88}
89
90impl<T, A: BumpAllocatorExt> Drop for Drain<'_, T, A> {
91 #[inline]
92 fn drop(&mut self) {
93 /// Moves back the un-`Drain`ed elements to restore the original vector.
94 struct DropGuard<'r, 'a, T, A: BumpAllocatorExt>(&'r mut Drain<'a, T, A>);
95
96 impl<T, A: BumpAllocatorExt> Drop for DropGuard<'_, '_, T, A> {
97 fn drop(&mut self) {
98 if self.0.tail_len > 0 {
99 unsafe {
100 let source_vec = self.0.vec.as_mut();
101 // memmove back untouched tail, update to new length
102 let start = source_vec.len();
103 let tail = self.0.tail_start;
104 if tail != start {
105 let src = source_vec.as_ptr().add(tail);
106 let dst = source_vec.as_mut_ptr().add(start);
107 ptr::copy(src, dst, self.0.tail_len);
108 }
109 source_vec.set_len(start + self.0.tail_len);
110 }
111 }
112 }
113 }
114
115 let iter = mem::replace(&mut self.iter, [].iter());
116 let drop_len = iter.len();
117
118 let mut vec = self.vec;
119
120 if T::IS_ZST {
121 // ZSTs have no identity, so we don't need to move them around, we only need to drop the correct amount.
122 // this can be achieved by manipulating the vector length instead of moving values out from `iter`.
123 unsafe {
124 let vec = vec.as_mut();
125 let old_len = vec.len();
126 vec.set_len(old_len + drop_len + self.tail_len);
127 vec.truncate(old_len + self.tail_len);
128 }
129
130 return;
131 }
132
133 // ensure elements are moved back into their appropriate places, even when drop_in_place panics
134 let _guard = DropGuard(self);
135
136 if drop_len == 0 {
137 return;
138 }
139
140 // as_slice() must only be called when iter.len() is > 0 because
141 // vec::Splice modifies vec::Drain fields and may grow the vec which would invalidate
142 // the iterator's internal pointers. Creating a reference to deallocated memory
143 // is invalid even when it is zero-length
144 let drop_ptr = iter.as_slice().as_ptr();
145
146 #[expect(clippy::cast_sign_loss)]
147 unsafe {
148 // drop_ptr comes from a slice::Iter which only gives us a &[T] but for drop_in_place
149 // a pointer with mutable provenance is necessary. Therefore we must reconstruct
150 // it from the original vec but also avoid creating a &mut to the front since that could
151 // invalidate raw pointers to it which some unsafe code might rely on.
152 let vec_ptr = vec.as_mut().as_mut_ptr();
153 let drop_offset = drop_ptr.offset_from(vec_ptr) as usize;
154 let to_drop = ptr::slice_from_raw_parts_mut(vec_ptr.add(drop_offset), drop_len);
155 ptr::drop_in_place(to_drop);
156 }
157 }
158}
159
160impl<T, A: BumpAllocatorExt> ExactSizeIterator for Drain<'_, T, A> {}
161
162impl<T, A: BumpAllocatorExt> FusedIterator for Drain<'_, T, A> {}