Skip to content

Commit a5c16a5

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 4b695f7 + 0314647 commit a5c16a5

File tree

3 files changed

+37
-14
lines changed

3 files changed

+37
-14
lines changed

library/core/src/num/f32.rs

+6-7
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
}

library/core/src/num/f64.rs

+6-7
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
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
// Floating-point clamp is designed to be implementable as max+min,
2+
// so check to make sure that's what it's actually emitting.
3+
4+
// assembly-output: emit-asm
5+
// compile-flags: --crate-type=lib -O -C llvm-args=-x86-asm-syntax=intel
6+
// only-x86_64
7+
8+
// CHECK-LABEL: clamp_demo:
9+
#[no_mangle]
10+
pub fn clamp_demo(a: f32, x: f32, y: f32) -> f32 {
11+
// CHECK: maxss
12+
// CHECK: minss
13+
a.clamp(x, y)
14+
}
15+
16+
// CHECK-LABEL: clamp12_demo:
17+
#[no_mangle]
18+
pub fn clamp12_demo(a: f32) -> f32 {
19+
// CHECK: movss xmm1
20+
// CHECK-NEXT: maxss xmm1, xmm0
21+
// CHECK-NEXT: movss xmm0
22+
// CHECK-NEXT: minss xmm0, xmm1
23+
// CHECK: ret
24+
a.clamp(1.0, 2.0)
25+
}

0 commit comments

Comments
 (0)