Skip to content

Commit 452d9d0

Browse files
authored
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
2 parents 317b212 + 48f4605 commit 452d9d0

File tree

1 file changed

+6
-6
lines changed

1 file changed

+6
-6
lines changed

src/libcore/slice/mod.rs

+6-6
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,7 @@ impl<T> [T] {
119119
#[stable(feature = "rust1", since = "1.0.0")]
120120
#[inline]
121121
pub fn first(&self) -> Option<&T> {
122-
if self.is_empty() { None } else { Some(&self[0]) }
122+
self.get(0)
123123
}
124124

125125
/// Returns a mutable pointer to the first element of the slice, or `None` if it is empty.
@@ -137,7 +137,7 @@ impl<T> [T] {
137137
#[stable(feature = "rust1", since = "1.0.0")]
138138
#[inline]
139139
pub fn first_mut(&mut self) -> Option<&mut T> {
140-
if self.is_empty() { None } else { Some(&mut self[0]) }
140+
self.get_mut(0)
141141
}
142142

143143
/// 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] {
239239
#[stable(feature = "rust1", since = "1.0.0")]
240240
#[inline]
241241
pub fn last(&self) -> Option<&T> {
242-
if self.is_empty() { None } else { Some(&self[self.len() - 1]) }
242+
let last_idx = self.len().checked_sub(1)?;
243+
self.get(last_idx)
243244
}
244245

245246
/// Returns a mutable pointer to the last item in the slice.
@@ -257,9 +258,8 @@ impl<T> [T] {
257258
#[stable(feature = "rust1", since = "1.0.0")]
258259
#[inline]
259260
pub fn last_mut(&mut self) -> Option<&mut T> {
260-
let len = self.len();
261-
if len == 0 { return None; }
262-
Some(&mut self[len - 1])
261+
let last_idx = self.len().checked_sub(1)?;
262+
self.get_mut(last_idx)
263263
}
264264

265265
/// Returns a reference to an element or subslice depending on the type of

0 commit comments

Comments
 (0)