|
1 | 1 | use crate::alloc::Allocator;
|
2 | 2 | use crate::vec;
|
| 3 | +use core::iter::{ByRefSized, TrustedLen}; |
3 | 4 | use core::slice;
|
4 | 5 |
|
5 | 6 | use super::VecDeque;
|
|
34 | 35 | }
|
35 | 36 | }
|
36 | 37 |
|
| 38 | +impl<T, I, A: Allocator> SpecExtend<T, I> for VecDeque<T, A> |
| 39 | +where |
| 40 | + I: TrustedLen<Item = T>, |
| 41 | +{ |
| 42 | + default fn spec_extend(&mut self, mut iter: I) { |
| 43 | + // This is the case for a TrustedLen iterator. |
| 44 | + let (low, high) = iter.size_hint(); |
| 45 | + if let Some(additional) = high { |
| 46 | + debug_assert_eq!( |
| 47 | + low, |
| 48 | + additional, |
| 49 | + "TrustedLen iterator's size hint is not exact: {:?}", |
| 50 | + (low, high) |
| 51 | + ); |
| 52 | + self.reserve(additional); |
| 53 | + |
| 54 | + struct WrapAddOnDrop<'a, T, A: Allocator> { |
| 55 | + vec_deque: &'a mut VecDeque<T, A>, |
| 56 | + written: usize, |
| 57 | + } |
| 58 | + |
| 59 | + impl<'a, T, A: Allocator> Drop for WrapAddOnDrop<'a, T, A> { |
| 60 | + fn drop(&mut self) { |
| 61 | + self.vec_deque.head = |
| 62 | + self.vec_deque.wrap_add(self.vec_deque.head, self.written); |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | + let mut wrapper = WrapAddOnDrop { vec_deque: self, written: 0 }; |
| 67 | + |
| 68 | + let head_room = wrapper.vec_deque.cap() - wrapper.vec_deque.head; |
| 69 | + unsafe { |
| 70 | + wrapper.vec_deque.write_iter( |
| 71 | + wrapper.vec_deque.head, |
| 72 | + ByRefSized(&mut iter).take(head_room), |
| 73 | + &mut wrapper.written, |
| 74 | + ); |
| 75 | + |
| 76 | + if additional > head_room { |
| 77 | + wrapper.vec_deque.write_iter(0, iter, &mut wrapper.written); |
| 78 | + } |
| 79 | + } |
| 80 | + |
| 81 | + debug_assert_eq!( |
| 82 | + additional, wrapper.written, |
| 83 | + "The number of items written to VecDeque doesn't match the TrustedLen size hint" |
| 84 | + ); |
| 85 | + } else { |
| 86 | + // Per TrustedLen contract a `None` upper bound means that the iterator length |
| 87 | + // truly exceeds usize::MAX, which would eventually lead to a capacity overflow anyway. |
| 88 | + // Since the other branch already panics eagerly (via `reserve()`) we do the same here. |
| 89 | + // This avoids additional codegen for a fallback code path which would eventually |
| 90 | + // panic anyway. |
| 91 | + panic!("capacity overflow"); |
| 92 | + } |
| 93 | + } |
| 94 | +} |
| 95 | + |
37 | 96 | impl<T, A: Allocator> SpecExtend<T, vec::IntoIter<T>> for VecDeque<T, A> {
|
38 | 97 | fn spec_extend(&mut self, mut iterator: vec::IntoIter<T>) {
|
39 | 98 | let slice = iterator.as_slice();
|
|
0 commit comments