Skip to content

Commit 81b8edc

Browse files
committed
Implement take_first methods in terms of split_first methods
1 parent e35ba52 commit 81b8edc

File tree

1 file changed

+12
-6
lines changed

1 file changed

+12
-6
lines changed

library/core/src/slice/mod.rs

+12-6
Original file line numberDiff line numberDiff line change
@@ -3335,7 +3335,9 @@ impl<T> [T] {
33353335
#[inline]
33363336
#[unstable(feature = "slice_take", issue = "62280")]
33373337
pub fn take_first<'a>(self: &mut &'a Self) -> Option<&'a T> {
3338-
self.take(..=0).map(|res| &res[0])
3338+
let (first, rem) = self.split_first()?;
3339+
*self = rem;
3340+
Some(first)
33393341
}
33403342

33413343
/// Returns a mutable reference to the first element of the slice,
@@ -3358,7 +3360,9 @@ impl<T> [T] {
33583360
#[inline]
33593361
#[unstable(feature = "slice_take", issue = "62280")]
33603362
pub fn take_first_mut<'a>(self: &mut &'a mut Self) -> Option<&'a mut T> {
3361-
self.take_mut(..=0).map(|res| &mut res[0])
3363+
let (first, rem) = mem::take(self).split_first_mut()?;
3364+
*self = rem;
3365+
Some(first)
33623366
}
33633367

33643368
/// Returns a reference to the last element of the slice,
@@ -3380,8 +3384,9 @@ impl<T> [T] {
33803384
#[inline]
33813385
#[unstable(feature = "slice_take", issue = "62280")]
33823386
pub fn take_last<'a>(self: &mut &'a Self) -> Option<&'a T> {
3383-
let i = self.len().checked_sub(1)?;
3384-
self.take(i..).map(|res| &res[0])
3387+
let (last, rem) = self.split_last()?;
3388+
*self = rem;
3389+
Some(last)
33853390
}
33863391

33873392
/// Returns a mutable reference to the last element of the slice,
@@ -3404,8 +3409,9 @@ impl<T> [T] {
34043409
#[inline]
34053410
#[unstable(feature = "slice_take", issue = "62280")]
34063411
pub fn take_last_mut<'a>(self: &mut &'a mut Self) -> Option<&'a mut T> {
3407-
let i = self.len().checked_sub(1)?;
3408-
self.take_mut(i..).map(|res| &mut res[0])
3412+
let (last, rem) = mem::take(self).split_last_mut()?;
3413+
*self = rem;
3414+
Some(last)
34093415
}
34103416
}
34113417

0 commit comments

Comments
 (0)