alloc/collections/vec_deque/splice.rs
1use core::alloc::Allocator;
2
3use crate::alloc::Global;
4use crate::collections::vec_deque::Drain;
5use crate::vec::Vec;
6
7/// A splicing iterator for `VecDeque`.
8///
9/// This struct is created by [`VecDeque::splice()`][super::VecDeque::splice].
10/// See its documentation for more.
11///
12/// # Example
13///
14/// ```
15/// # #![feature(deque_extend_front)]
16/// # use std::collections::VecDeque;
17///
18/// let mut v = VecDeque::from(vec![0, 1, 2]);
19/// let new = [7, 8];
20/// let iter: std::collections::vec_deque::Splice<'_, _> = v.splice(1.., new);
21/// ```
22#[unstable(feature = "deque_extend_front", issue = "146975")]
23#[derive(Debug)]
24pub struct Splice<
25 'a,
26 I: Iterator + 'a,
27 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator + 'a = Global,
28> {
29 pub(super) drain: Drain<'a, I::Item, A>,
30 pub(super) replace_with: I,
31}
32
33#[unstable(feature = "deque_extend_front", issue = "146975")]
34impl<I: Iterator, A: Allocator> Iterator for Splice<'_, I, A> {
35 type Item = I::Item;
36
37 fn next(&mut self) -> Option<Self::Item> {
38 self.drain.next()
39 }
40
41 fn size_hint(&self) -> (usize, Option<usize>) {
42 self.drain.size_hint()
43 }
44}
45
46#[unstable(feature = "deque_extend_front", issue = "146975")]
47impl<I: Iterator, A: Allocator> DoubleEndedIterator for Splice<'_, I, A> {
48 fn next_back(&mut self) -> Option<Self::Item> {
49 self.drain.next_back()
50 }
51}
52
53#[unstable(feature = "deque_extend_front", issue = "146975")]
54impl<I: Iterator, A: Allocator> ExactSizeIterator for Splice<'_, I, A> {}
55
56// See also: [`crate::vec::Splice`].
57#[unstable(feature = "deque_extend_front", issue = "146975")]
58impl<I: Iterator, A: Allocator> Drop for Splice<'_, I, A> {
59 fn drop(&mut self) {
60 // This will set drain.remaining to 0, so its drop won't try to read deallocated memory on
61 // drop.
62 self.drain.by_ref().for_each(drop);
63
64 // At this point draining is done and the only remaining tasks are splicing
65 // and moving things into the final place.
66
67 let tail_len = self.drain.tail_len; // #elements behind the drain
68
69 // ignore-tidy-undocumented-unsafe
70 unsafe {
71 if tail_len == 0 {
72 self.drain.deque.as_mut().extend(self.replace_with.by_ref());
73 return;
74 }
75
76 // First fill the range left by drain().
77 if !self.drain.fill(&mut self.replace_with) {
78 return;
79 }
80
81 // There may be more elements. Use the lower bound as an estimate.
82 // FIXME: Is the upper bound a better guess? Or something else?
83 let (lower_bound, _upper_bound) = self.replace_with.size_hint();
84 if lower_bound > 0 {
85 self.drain.move_tail(lower_bound);
86 if !self.drain.fill(&mut self.replace_with) {
87 return;
88 }
89 }
90
91 // Collect any remaining elements.
92 // This is a zero-length vector which does not allocate if `lower_bound` was exact.
93 let mut collected = self.replace_with.by_ref().collect::<Vec<I::Item>>().into_iter();
94 // Now we have an exact count.
95 if collected.len() > 0 {
96 self.drain.move_tail(collected.len());
97 let filled = self.drain.fill(&mut collected);
98 debug_assert!(filled);
99 debug_assert_eq!(collected.len(), 0);
100 }
101 }
102 // Let `Drain::drop` move the tail back if necessary and restore `deque.len`.
103 }
104}
105
106/// Private helper methods for `Splice::drop`
107impl<T, A: Allocator> Drain<'_, T, A> {
108 /// The range from `self.deque.len` to `self.deque.len + self.drain_len` contains elements that
109 /// have been moved out.
110 /// Fill that range as much as possible with new elements from the `replace_with` iterator.
111 /// Returns `true` if we filled the entire range. (`replace_with.next()` didn’t return `None`.)
112 ///
113 /// # Safety
114 ///
115 /// self.deque must be valid. self.deque.len and self.deque.len + self.drain_len must be less
116 /// than twice the deque's capacity.
117 unsafe fn fill<I: Iterator<Item = T>>(&mut self, replace_with: &mut I) -> bool {
118 // ignore-tidy-undocumented-unsafe
119 let deque = unsafe { self.deque.as_mut() };
120 let range_start = deque.len;
121 let range_end = range_start + self.drain_len;
122
123 for idx in range_start..range_end {
124 if let Some(new_item) = replace_with.next() {
125 let index = deque.to_wrapped_index(idx);
126 // ignore-tidy-undocumented-unsafe
127 unsafe { deque.buffer_write(index, new_item) };
128 deque.len += 1;
129 self.drain_len -= 1;
130 } else {
131 return false;
132 }
133 }
134 true
135 }
136
137 /// Makes room for inserting more elements before the tail.
138 ///
139 /// # Safety
140 ///
141 /// self.deque must be valid.
142 unsafe fn move_tail(&mut self, additional: usize) {
143 // SAFETY: Upheld by caller.
144 let deque = unsafe { self.deque.as_mut() };
145
146 // `Drain::new` modifies the deque's len (so does `Drain::fill` here)
147 // directly with the start bound of the range passed into
148 // `VecDeque::splice`. This causes a few different issue:
149 // - Most notably, there will be a hole at the end of the
150 // buffer when our buffer resizes in the case that our
151 // data wraps around.
152 // - We cannot use `VecDeque::reserve` directly because
153 // how it reserves more space and updates the `VecDeque`'s
154 // `head` field accordingly depends on the `VecDeque`'s
155 // actual `len`.
156 // - We cannot just directly modify `VecDeque`'s `len` and
157 // and call `VecDeque::reserve` afterward because if
158 // `VecDeque::reserve` panics on capacity overflow,
159 // well now our `VecDeque`'s head does not get updated
160 // and we still have a potential hole at the end of the
161 // buffer.
162 // Therefore, we manually reserve additional space (if necessary)
163 // based on calculating the actual `len` of the `VecDeque` and adjust
164 // `VecDeque`'s len right *after* the panicking region of `VecDeque::reserve`
165 // (that is `RawVec` `reserve()` call)
166
167 let drain_start = deque.len;
168 let tail_start = drain_start + self.drain_len;
169
170 // Actual VecDeque's len = drain_start + tail_len + drain_len
171 let actual_len = drain_start + self.tail_len + self.drain_len;
172 let new_cap = actual_len.checked_add(additional).expect("capacity overflow");
173 let old_cap = deque.capacity();
174
175 if new_cap > old_cap {
176 deque.buf.reserve(actual_len, additional);
177 // If new_cap doesn't panic, we can safely set the `VecDeque` len to its
178 // actual len; this needs to be done in order to set deque.head correctly
179 // on `VecDeque::handle_capacity_increase`
180 deque.len = actual_len;
181 // SAFETY: this cannot panic since our internal buffer's new_cap should
182 // be bigger than the passed in old_cap
183 unsafe {
184 deque.handle_capacity_increase(old_cap);
185 }
186 }
187
188 let new_tail_start = tail_start + additional;
189 // ignore-tidy-undocumented-unsafe
190 unsafe {
191 deque.wrap_copy(
192 deque.to_wrapped_index(tail_start),
193 deque.to_wrapped_index(new_tail_start),
194 self.tail_len,
195 );
196 }
197
198 // revert the `VecDeque` len to what it was before
199 deque.len = drain_start;
200 self.drain_len += additional;
201 }
202}