Skip to content

Commit 3a2e51d

Browse files
committed
Remove a function call from Vec::peek_mut construction
This style aligns with that of `BinaryHeap::peek_mut`.
1 parent 59708b4 commit 3a2e51d

File tree

2 files changed

+4
-7
lines changed

2 files changed

+4
-7
lines changed

library/alloc/src/vec/mod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -784,7 +784,7 @@ impl<T> Vec<T> {
784784
#[inline]
785785
#[unstable(feature = "vec_peek_mut", issue = "122742")]
786786
pub fn peek_mut(&mut self) -> Option<PeekMut<'_, T>> {
787-
PeekMut::new(self)
787+
if self.is_empty() { None } else { Some(PeekMut { vec: self }) }
788788
}
789789

790790
/// Decomposes a `Vec<T>` into its raw components: `(pointer, length, capacity)`.

library/alloc/src/vec/peek_mut.rs

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ pub struct PeekMut<
1717
T,
1818
#[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
1919
> {
20-
vec: &'a mut Vec<T, A>,
20+
pub(super) vec: &'a mut Vec<T, A>,
2121
}
2222

2323
#[unstable(feature = "vec_peek_mut", issue = "122742")]
@@ -28,10 +28,6 @@ impl<T: fmt::Debug> fmt::Debug for PeekMut<'_, T> {
2828
}
2929

3030
impl<'a, T> PeekMut<'a, T> {
31-
pub(crate) fn new(vec: &'a mut Vec<T>) -> Option<Self> {
32-
if vec.is_empty() { None } else { Some(Self { vec }) }
33-
}
34-
3531
/// Removes the peeked value from the vector and returns it.
3632
#[unstable(feature = "vec_peek_mut", issue = "122742")]
3733
pub fn pop(this: Self) -> T {
@@ -45,8 +41,9 @@ impl<'a, T> Deref for PeekMut<'a, T> {
4541
type Target = T;
4642

4743
fn deref(&self) -> &Self::Target {
44+
let idx = self.vec.len() - 1;
4845
// SAFETY: PeekMut is only constructed if the vec is non-empty
49-
unsafe { self.vec.get_unchecked(self.vec.len() - 1) }
46+
unsafe { self.vec.get_unchecked(idx) }
5047
}
5148
}
5249

0 commit comments

Comments
 (0)