Skip to content

Commit

Permalink
Avoid underflow
Browse files Browse the repository at this point in the history
  • Loading branch information
timvermeulen committed Sep 22, 2020
1 parent e375c8d commit a7faf20
Showing 1 changed file with 4 additions and 2 deletions.
6 changes: 4 additions & 2 deletions library/core/src/slice/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3271,7 +3271,8 @@ impl<T> [T] {
#[inline]
#[unstable(feature = "slice_take", issue = "62280")]
pub fn take_last<'a>(self: &mut &'a Self) -> Option<&'a T> {
self.take((self.len() - 1)..).map(|res| &res[0])
let i = self.len().checked_sub(1)?;
self.take(i..).map(|res| &res[0])
}

/// Returns a mutable reference to the last element of the slice,
Expand All @@ -3294,7 +3295,8 @@ impl<T> [T] {
#[inline]
#[unstable(feature = "slice_take", issue = "62280")]
pub fn take_last_mut<'a>(self: &mut &'a mut Self) -> Option<&'a mut T> {
self.take_mut((self.len() - 1)..).map(|res| &mut res[0])
let i = self.len().checked_sub(1)?;
self.take_mut(i..).map(|res| &mut res[0])
}
}

Expand Down

0 comments on commit a7faf20

Please sign in to comment.