about summary refs log tree commit diff
diff options
context:
space:
mode:
authorPietro Albini <pietro@pietroalbini.org>2018-09-22 09:56:43 +0200
committerGitHub <noreply@github.com>2018-09-22 09:56:43 +0200
commit452d9d07a09a0dece5024eb6b4bd4d8dbb73774b (patch)
tree0585d367e0e51af6a38972233ae3e22f7064b5de
parent317b212fa1cc2941f0fcaa14eea6f2ab1514df56 (diff)
parent48f46056b7604acd1fb328e41792eb25d1d37163 (diff)
downloadrust-452d9d07a09a0dece5024eb6b4bd4d8dbb73774b.tar.gz
rust-452d9d07a09a0dece5024eb6b4bd4d8dbb73774b.zip
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
-rw-r--r--src/libcore/slice/mod.rs12
1 files changed, 6 insertions, 6 deletions
diff --git a/src/libcore/slice/mod.rs b/src/libcore/slice/mod.rs
index e4ac79a26d8..aed9020d9d1 100644
--- a/src/libcore/slice/mod.rs
+++ b/src/libcore/slice/mod.rs
@@ -119,7 +119,7 @@ impl<T> [T] {
     #[stable(feature = "rust1", since = "1.0.0")]
     #[inline]
     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.
@@ -137,7 +137,7 @@ impl<T> [T] {
     #[stable(feature = "rust1", since = "1.0.0")]
     #[inline]
     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.
@@ -239,7 +239,8 @@ impl<T> [T] {
     #[stable(feature = "rust1", since = "1.0.0")]
     #[inline]
     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.
@@ -257,9 +258,8 @@ impl<T> [T] {
     #[stable(feature = "rust1", since = "1.0.0")]
     #[inline]
     pub fn last_mut(&mut self) -> Option<&mut T> {
-        let len = self.len();
-        if len == 0 { return None; }
-        Some(&mut self[len - 1])
+        let last_idx = self.len().checked_sub(1)?;
+        self.get_mut(last_idx)
     }
 
     /// Returns a reference to an element or subslice depending on the type of