diff --git a/library/alloc/src/vec/mod.rs b/library/alloc/src/vec/mod.rs index 45d6c28e186e4..dc610d7b46741 100644 --- a/library/alloc/src/vec/mod.rs +++ b/library/alloc/src/vec/mod.rs @@ -2564,8 +2564,8 @@ impl Vec { let _ = self.push_mut(value); } - /// Appends an element if there is sufficient spare capacity, otherwise an error is returned - /// with the element. + /// Appends an element and returns a reference to it if there is sufficient spare capacity, + /// otherwise an error is returned with the element. /// /// Unlike [`push`] this method will not reallocate when there's insufficient capacity. /// The caller should use [`reserve`] or [`try_reserve`] to ensure that there is enough capacity. @@ -2601,8 +2601,20 @@ impl Vec { /// Takes *O*(1) time. #[inline] #[unstable(feature = "vec_push_within_capacity", issue = "100486")] - pub fn push_within_capacity(&mut self, value: T) -> Result<(), T> { - self.push_mut_within_capacity(value).map(|_| ()) + // #[unstable(feature = "push_mut", issue = "135974")] + pub fn push_within_capacity(&mut self, value: T) -> Result<&mut T, T> { + if self.len == self.buf.capacity() { + return Err(value); + } + + unsafe { + let end = self.as_mut_ptr().add(self.len); + ptr::write(end, value); + self.len += 1; + + // SAFETY: We just wrote a value to the pointer that will live the lifetime of the reference. + Ok(&mut *end) + } } /// Appends an element to the back of a collection, returning a reference to it. @@ -2654,36 +2666,6 @@ impl Vec { } } - /// Appends an element and returns a reference to it if there is sufficient spare capacity, - /// otherwise an error is returned with the element. - /// - /// Unlike [`push_mut`] this method will not reallocate when there's insufficient capacity. - /// The caller should use [`reserve`] or [`try_reserve`] to ensure that there is enough capacity. - /// - /// [`push_mut`]: Vec::push_mut - /// [`reserve`]: Vec::reserve - /// [`try_reserve`]: Vec::try_reserve - /// - /// # Time complexity - /// - /// Takes *O*(1) time. - #[unstable(feature = "push_mut", issue = "135974")] - // #[unstable(feature = "vec_push_within_capacity", issue = "100486")] - #[inline] - #[must_use = "if you don't need a reference to the value, use `Vec::push_within_capacity` instead"] - pub fn push_mut_within_capacity(&mut self, value: T) -> Result<&mut T, T> { - if self.len == self.buf.capacity() { - return Err(value); - } - unsafe { - let end = self.as_mut_ptr().add(self.len); - ptr::write(end, value); - self.len += 1; - // SAFETY: We just wrote a value to the pointer that will live the lifetime of the reference. - Ok(&mut *end) - } - } - /// Removes the last element from a vector and returns it, or [`None`] if it /// is empty. ///