Skip to content

Commit 54178b4

Browse files
authored
Rollup merge of #100556 - Alex-Velez:patch-1, r=scottmcm
Clamp Function for f32 and f64 I thought the clamp function could use a little improvement for readability purposes. The function now returns early in order to skip the extra bound checks. If there was a reason for binding `self` to `x` or if this code is incorrect, please correct me :)
2 parents 0e5ce8c + 96c7a44 commit 54178b4

File tree

2 files changed

+12
-14
lines changed

2 files changed

+12
-14
lines changed

core/src/num/f32.rs

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1282,15 +1282,14 @@ impl f32 {
12821282
#[must_use = "method returns a new number and does not mutate the original value"]
12831283
#[stable(feature = "clamp", since = "1.50.0")]
12841284
#[inline]
1285-
pub fn clamp(self, min: f32, max: f32) -> f32 {
1285+
pub fn clamp(mut self, min: f32, max: f32) -> f32 {
12861286
assert!(min <= max);
1287-
let mut x = self;
1288-
if x < min {
1289-
x = min;
1287+
if self < min {
1288+
self = min;
12901289
}
1291-
if x > max {
1292-
x = max;
1290+
if self > max {
1291+
self = max;
12931292
}
1294-
x
1293+
self
12951294
}
12961295
}

core/src/num/f64.rs

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1280,15 +1280,14 @@ impl f64 {
12801280
#[must_use = "method returns a new number and does not mutate the original value"]
12811281
#[stable(feature = "clamp", since = "1.50.0")]
12821282
#[inline]
1283-
pub fn clamp(self, min: f64, max: f64) -> f64 {
1283+
pub fn clamp(mut self, min: f64, max: f64) -> f64 {
12841284
assert!(min <= max);
1285-
let mut x = self;
1286-
if x < min {
1287-
x = min;
1285+
if self < min {
1286+
self = min;
12881287
}
1289-
if x > max {
1290-
x = max;
1288+
if self > max {
1289+
self = max;
12911290
}
1292-
x
1291+
self
12931292
}
12941293
}

0 commit comments

Comments
 (0)