diff --git a/library/alloc/src/vec/spec_extend.rs b/library/alloc/src/vec/spec_extend.rs index e132befcfa5..db19d739ff8 100644 --- a/library/alloc/src/vec/spec_extend.rs +++ b/library/alloc/src/vec/spec_extend.rs @@ -1,5 +1,5 @@ use crate::alloc::Allocator; -use core::iter::TrustedLen; +use core::iter::{TrustedLen, TrustedRandomAccess}; use core::ptr::{self}; use core::slice::{self}; @@ -11,6 +11,49 @@ pub(super) trait SpecExtend { } impl SpecExtend for Vec +where + I: Iterator, +{ + default fn spec_extend(&mut self, iter: I) { + SpecExtendInner::spec_extend(self, iter); + } +} + +impl SpecExtend> for Vec { + fn spec_extend(&mut self, mut iterator: IntoIter) { + unsafe { + self.append_elements(iterator.as_slice() as _); + } + iterator.ptr = iterator.end; + } +} + +impl<'a, T: 'a, I, A: Allocator + 'a> SpecExtend<&'a T, I> for Vec +where + I: Iterator, + T: Clone, +{ + default fn spec_extend(&mut self, iterator: I) { + SpecExtend::spec_extend(self, iterator.cloned()) + } +} + +impl<'a, T: 'a, A: Allocator + 'a> SpecExtend<&'a T, slice::Iter<'a, T>> for Vec +where + T: Copy, +{ + fn spec_extend(&mut self, iterator: slice::Iter<'a, T>) { + let slice = iterator.as_slice(); + unsafe { self.append_elements(slice) }; + } +} + +// Helper trait to disambiguate overlapping specializations +trait SpecExtendInner { + fn spec_extend(&mut self, iter: I); +} + +impl SpecExtendInner for Vec where I: Iterator, { @@ -19,7 +62,7 @@ where } } -impl SpecExtend for Vec +impl SpecExtendInner for Vec where I: TrustedLen, { @@ -57,31 +100,22 @@ where } } -impl SpecExtend> for Vec { - fn spec_extend(&mut self, mut iterator: IntoIter) { +impl SpecExtendInner for Vec +where + I: TrustedLen + TrustedRandomAccess, +{ + default fn spec_extend(&mut self, mut iterator: I) { + let size = iterator.size(); + self.reserve(size); + + // SAFETY: reserve ensured that there is sufficient capacity for the additional items. + // The loop upholds the TRA requirements by accessing each element only once. unsafe { - self.append_elements(iterator.as_slice() as _); + let sink = self.as_mut_ptr().add(self.len()); + for i in 0..size { + ptr::write(sink.add(i), iterator.__iterator_get_unchecked(i)); + self.set_len(self.len() + 1); + } } - iterator.ptr = iterator.end; - } -} - -impl<'a, T: 'a, I, A: Allocator + 'a> SpecExtend<&'a T, I> for Vec -where - I: Iterator, - T: Clone, -{ - default fn spec_extend(&mut self, iterator: I) { - self.spec_extend(iterator.cloned()) - } -} - -impl<'a, T: 'a, A: Allocator + 'a> SpecExtend<&'a T, slice::Iter<'a, T>> for Vec -where - T: Copy, -{ - fn spec_extend(&mut self, iterator: slice::Iter<'a, T>) { - let slice = iterator.as_slice(); - unsafe { self.append_elements(slice) }; } } diff --git a/library/core/src/iter/adapters/zip.rs b/library/core/src/iter/adapters/zip.rs index 2f8f504d8fc..4f6ef24be1b 100644 --- a/library/core/src/iter/adapters/zip.rs +++ b/library/core/src/iter/adapters/zip.rs @@ -416,6 +416,10 @@ impl ZipFmt