1
Fork 0

Rollup merge of #54422 - ljedrz:simplify_first_last, r=Mark-Simulacrum

Simplify slice's first(_mut) and last(_mut) with get

This change makes these functions easier to read and interpret. I haven't detected any difference in performance locally.

r? @Mark-Simulacrum
This commit is contained in:
Pietro Albini 2018-09-22 09:56:43 +02:00 committed by GitHub
commit 452d9d07a0
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -119,7 +119,7 @@ impl<T> [T] {
#[stable(feature = "rust1", since = "1.0.0")] #[stable(feature = "rust1", since = "1.0.0")]
#[inline] #[inline]
pub fn first(&self) -> Option<&T> { pub fn first(&self) -> Option<&T> {
if self.is_empty() { None } else { Some(&self[0]) } self.get(0)
} }
/// Returns a mutable pointer to the first element of the slice, or `None` if it is empty. /// Returns a mutable pointer to the first element of the slice, or `None` if it is empty.
@ -137,7 +137,7 @@ impl<T> [T] {
#[stable(feature = "rust1", since = "1.0.0")] #[stable(feature = "rust1", since = "1.0.0")]
#[inline] #[inline]
pub fn first_mut(&mut self) -> Option<&mut T> { pub fn first_mut(&mut self) -> Option<&mut T> {
if self.is_empty() { None } else { Some(&mut self[0]) } self.get_mut(0)
} }
/// Returns the first and all the rest of the elements of the slice, or `None` if it is empty. /// Returns the first and all the rest of the elements of the slice, or `None` if it is empty.
@ -239,7 +239,8 @@ impl<T> [T] {
#[stable(feature = "rust1", since = "1.0.0")] #[stable(feature = "rust1", since = "1.0.0")]
#[inline] #[inline]
pub fn last(&self) -> Option<&T> { pub fn last(&self) -> Option<&T> {
if self.is_empty() { None } else { Some(&self[self.len() - 1]) } let last_idx = self.len().checked_sub(1)?;
self.get(last_idx)
} }
/// Returns a mutable pointer to the last item in the slice. /// Returns a mutable pointer to the last item in the slice.
@ -257,9 +258,8 @@ impl<T> [T] {
#[stable(feature = "rust1", since = "1.0.0")] #[stable(feature = "rust1", since = "1.0.0")]
#[inline] #[inline]
pub fn last_mut(&mut self) -> Option<&mut T> { pub fn last_mut(&mut self) -> Option<&mut T> {
let len = self.len(); let last_idx = self.len().checked_sub(1)?;
if len == 0 { return None; } self.get_mut(last_idx)
Some(&mut self[len - 1])
} }
/// Returns a reference to an element or subslice depending on the type of /// Returns a reference to an element or subslice depending on the type of