Skip to content

Commit

Permalink
Implement take_first methods in terms of split_first methods
Browse files Browse the repository at this point in the history
  • Loading branch information
timvermeulen committed Nov 6, 2020
1 parent e35ba52 commit 81b8edc
Showing 1 changed file with 12 additions and 6 deletions.
18 changes: 12 additions & 6 deletions library/core/src/slice/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3335,7 +3335,9 @@ impl<T> [T] {
#[inline]
#[unstable(feature = "slice_take", issue = "62280")]
pub fn take_first<'a>(self: &mut &'a Self) -> Option<&'a T> {
self.take(..=0).map(|res| &res[0])
let (first, rem) = self.split_first()?;
*self = rem;
Some(first)
}

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

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

/// Returns a mutable reference to the last element of the slice,
Expand All @@ -3404,8 +3409,9 @@ 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> {
let i = self.len().checked_sub(1)?;
self.take_mut(i..).map(|res| &mut res[0])
let (last, rem) = mem::take(self).split_last_mut()?;
*self = rem;
Some(last)
}
}

Expand Down

0 comments on commit 81b8edc

Please sign in to comment.