Skip to content

Commit 8dda5c4

Browse files
committed
Avoid underflow
1 parent 5d6272a commit 8dda5c4

File tree

1 file changed

+4
-2
lines changed

1 file changed

+4
-2
lines changed

library/core/src/slice/mod.rs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3381,7 +3381,8 @@ impl<T> [T] {
33813381
#[inline]
33823382
#[unstable(feature = "slice_take", issue = "62280")]
33833383
pub fn take_last<'a>(self: &mut &'a Self) -> Option<&'a T> {
3384-
self.take((self.len() - 1)..).map(|res| &res[0])
3384+
let i = self.len().checked_sub(1)?;
3385+
self.take(i..).map(|res| &res[0])
33853386
}
33863387

33873388
/// Returns a mutable reference to the last element of the slice,
@@ -3404,7 +3405,8 @@ impl<T> [T] {
34043405
#[inline]
34053406
#[unstable(feature = "slice_take", issue = "62280")]
34063407
pub fn take_last_mut<'a>(self: &mut &'a mut Self) -> Option<&'a mut T> {
3407-
self.take_mut((self.len() - 1)..).map(|res| &mut res[0])
3408+
let i = self.len().checked_sub(1)?;
3409+
self.take_mut(i..).map(|res| &mut res[0])
34083410
}
34093411
}
34103412

0 commit comments

Comments
 (0)