mirror of
https://github.com/rust-lang/rust.git
synced 2025-04-28 02:57:37 +00:00
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 :)
This commit is contained in:
commit
a5c16a5381
@ -1282,15 +1282,14 @@ impl f32 {
|
||||
#[must_use = "method returns a new number and does not mutate the original value"]
|
||||
#[stable(feature = "clamp", since = "1.50.0")]
|
||||
#[inline]
|
||||
pub fn clamp(self, min: f32, max: f32) -> f32 {
|
||||
pub fn clamp(mut self, min: f32, max: f32) -> f32 {
|
||||
assert!(min <= max);
|
||||
let mut x = self;
|
||||
if x < min {
|
||||
x = min;
|
||||
if self < min {
|
||||
self = min;
|
||||
}
|
||||
if x > max {
|
||||
x = max;
|
||||
if self > max {
|
||||
self = max;
|
||||
}
|
||||
x
|
||||
self
|
||||
}
|
||||
}
|
||||
|
@ -1280,15 +1280,14 @@ impl f64 {
|
||||
#[must_use = "method returns a new number and does not mutate the original value"]
|
||||
#[stable(feature = "clamp", since = "1.50.0")]
|
||||
#[inline]
|
||||
pub fn clamp(self, min: f64, max: f64) -> f64 {
|
||||
pub fn clamp(mut self, min: f64, max: f64) -> f64 {
|
||||
assert!(min <= max);
|
||||
let mut x = self;
|
||||
if x < min {
|
||||
x = min;
|
||||
if self < min {
|
||||
self = min;
|
||||
}
|
||||
if x > max {
|
||||
x = max;
|
||||
if self > max {
|
||||
self = max;
|
||||
}
|
||||
x
|
||||
self
|
||||
}
|
||||
}
|
||||
|
25
src/test/assembly/x86_64-floating-point-clamp.rs
Normal file
25
src/test/assembly/x86_64-floating-point-clamp.rs
Normal file
@ -0,0 +1,25 @@
|
||||
// Floating-point clamp is designed to be implementable as max+min,
|
||||
// so check to make sure that's what it's actually emitting.
|
||||
|
||||
// assembly-output: emit-asm
|
||||
// compile-flags: --crate-type=lib -O -C llvm-args=-x86-asm-syntax=intel
|
||||
// only-x86_64
|
||||
|
||||
// CHECK-LABEL: clamp_demo:
|
||||
#[no_mangle]
|
||||
pub fn clamp_demo(a: f32, x: f32, y: f32) -> f32 {
|
||||
// CHECK: maxss
|
||||
// CHECK: minss
|
||||
a.clamp(x, y)
|
||||
}
|
||||
|
||||
// CHECK-LABEL: clamp12_demo:
|
||||
#[no_mangle]
|
||||
pub fn clamp12_demo(a: f32) -> f32 {
|
||||
// CHECK: movss xmm1
|
||||
// CHECK-NEXT: maxss xmm1, xmm0
|
||||
// CHECK-NEXT: movss xmm0
|
||||
// CHECK-NEXT: minss xmm0, xmm1
|
||||
// CHECK: ret
|
||||
a.clamp(1.0, 2.0)
|
||||
}
|
Loading…
Reference in New Issue
Block a user