Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Clamp Function for f32 and f64 #100556

Merged
merged 3 commits into from
Aug 21, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 6 additions & 7 deletions library/core/src/num/f32.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}
13 changes: 6 additions & 7 deletions library/core/src/num/f64.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 changes: 25 additions & 0 deletions src/test/assembly/x86_64-floating-point-clamp.rs
Original file line number Diff line number Diff line change
@@ -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-NEXT: movss xmm1
Alex-Velez marked this conversation as resolved.
Show resolved Hide resolved
// CHECK-NEXT: maxss xmm1, xmm0
// CHECK-NEXT: movss xmm0
// CHECK-NEXT: minss xmm0, xmm1
// CHECK-NEXT: ret
scottmcm marked this conversation as resolved.
Show resolved Hide resolved
a.clamp(1.0, 2.0)
}