1use core::alloc::Allocator;
23use crate::alloc::Global;
4use crate::collections::vec_deque::Drain;
5use crate::vec::Vec;
67/// 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(#[automatically_derived]
#[unstable(feature = "deque_extend_front", issue = "146975")]
impl<'a, I: ::core::fmt::Debug + Iterator + 'a, A: ::core::fmt::Debug +
Allocator + 'a> ::core::fmt::Debug for Splice<'a, I, A> where
I::Item: ::core::fmt::Debug {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f, "Splice",
"drain", &self.drain, "replace_with", &&self.replace_with)
}
}Debug)]
24pub struct Splice<
25'a,
26 I: Iterator + 'a,
27#[unstable(feature = "allocator_api", issue = "32838")] A: Allocator + 'a = Global,
28> {
29pub(super) drain: Drain<'a, I::Item, A>,
30pub(super) replace_with: I,
31}
3233#[unstable(feature = "deque_extend_front", issue = "146975")]
34impl<I: Iterator, A: Allocator> Iteratorfor Splice<'_, I, A> {
35type Item = I::Item;
3637fn next(&mut self) -> Option<Self::Item> {
38self.drain.next()
39 }
4041fn size_hint(&self) -> (usize, Option<usize>) {
42self.drain.size_hint()
43 }
44}
4546#[unstable(feature = "deque_extend_front", issue = "146975")]
47impl<I: Iterator, A: Allocator> DoubleEndedIteratorfor Splice<'_, I, A> {
48fn next_back(&mut self) -> Option<Self::Item> {
49self.drain.next_back()
50 }
51}
5253#[unstable(feature = "deque_extend_front", issue = "146975")]
54impl<I: Iterator, A: Allocator> ExactSizeIteratorfor Splice<'_, I, A> {}
5556// See also: [`crate::vec::Splice`].
57#[unstable(feature = "deque_extend_front", issue = "146975")]
58impl<I: Iterator, A: Allocator> Dropfor Splice<'_, I, A> {
59fn drop(&mut self) {
60// This will set drain.remaining to 0, so its drop won't try to read deallocated memory on
61 // drop.
62self.drain.by_ref().for_each(drop);
6364// At this point draining is done and the only remaining tasks are splicing
65 // and moving things into the final place.
6667 // ignore-tidy-undocumented-unsafe
68unsafe {
69let tail_len = self.drain.tail_len; // #elements behind the drain
7071if tail_len == 0 {
72self.drain.deque.as_mut().extend(self.replace_with.by_ref());
73return;
74 }
7576// First fill the range left by drain().
77if !self.drain.fill(&mut self.replace_with) {
78return;
79 }
8081// There may be more elements. Use the lower bound as an estimate.
82 // FIXME: Is the upper bound a better guess? Or something else?
83let (lower_bound, _upper_bound) = self.replace_with.size_hint();
84if lower_bound > 0 {
85self.drain.move_tail(lower_bound);
86if !self.drain.fill(&mut self.replace_with) {
87return;
88 }
89 }
9091// Collect any remaining elements.
92 // This is a zero-length vector which does not allocate if `lower_bound` was exact.
93let mut collected = self.replace_with.by_ref().collect::<Vec<I::Item>>().into_iter();
94// Now we have an exact count.
95if collected.len() > 0 {
96self.drain.move_tail(collected.len());
97let filled = self.drain.fill(&mut collected);
98if true {
if !filled { ::core::panicking::panic("assertion failed: filled") };
};debug_assert!(filled);
99if true {
{
match (&collected.len(), &0) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
};debug_assert_eq!(collected.len(), 0);
100 }
101 }
102// Let `Drain::drop` move the tail back if necessary and restore `deque.len`.
103}
104}
105106/// 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.
117unsafe fn fill<I: Iterator<Item = T>>(&mut self, replace_with: &mut I) -> bool {
118// ignore-tidy-undocumented-unsafe
119let deque = unsafe { self.deque.as_mut() };
120let range_start = deque.len;
121let range_end = range_start + self.drain_len;
122123for idx in range_start..range_end {
124if let Some(new_item) = replace_with.next() {
125let index = deque.to_wrapped_index(idx);
126// ignore-tidy-undocumented-unsafe
127unsafe { deque.buffer_write(index, new_item) };
128 deque.len += 1;
129self.drain_len -= 1;
130 } else {
131return false;
132 }
133 }
134true
135}
136137/// Makes room for inserting more elements before the tail.
138 ///
139 /// # Safety
140 ///
141 /// self.deque must be valid.
142unsafe fn move_tail(&mut self, additional: usize) {
143// SAFETY: Upheld by caller.
144let deque = unsafe { self.deque.as_mut() };
145146// `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)
166167let drain_start = deque.len;
168let tail_start = drain_start + self.drain_len;
169170// Actual VecDeque's len = drain_start + tail_len + drain_len
171let actual_len = drain_start + self.tail_len + self.drain_len;
172let new_cap = actual_len.checked_add(additional).expect("capacity overflow");
173let old_cap = deque.capacity();
174175if new_cap > old_cap {
176deque.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`
180deque.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
183unsafe {
184deque.handle_capacity_increase(old_cap);
185 }
186 }
187188let new_tail_start = tail_start + additional;
189// ignore-tidy-undocumented-unsafe
190unsafe {
191deque.wrap_copy(
192deque.to_wrapped_index(tail_start),
193deque.to_wrapped_index(new_tail_start),
194self.tail_len,
195 );
196 }
197198// revert the `VecDeque` len to what it was before
199deque.len = drain_start;
200self.drain_len += additional;
201 }
202}