about summary refs log tree commit diff
path: root/src/libstd
diff options
context:
space:
mode:
authorJacob Kiesel <kieseljake@gmail.com>2017-08-26 00:06:13 -0600
committerJacob Kiesel <kieseljake@gmail.com>2017-08-26 10:21:17 -0600
commitc589f867f89d4e6e48c6602aed8e878208d4822f (patch)
treee75a84d4876d5286b95a04f1b3419656fd873537 /src/libstd
parent398aaffc94367ed59420f5ac0b0238c04c9e4fa5 (diff)
downloadrust-c589f867f89d4e6e48c6602aed8e878208d4822f.tar.gz
rust-c589f867f89d4e6e48c6602aed8e878208d4822f.zip
Add clamp functions
Diffstat (limited to 'src/libstd')
-rw-r--r--src/libstd/f32.rs20
-rw-r--r--src/libstd/f64.rs20
2 files changed, 40 insertions, 0 deletions
diff --git a/src/libstd/f32.rs b/src/libstd/f32.rs
index 0135cd0a588..18bc27faa82 100644
--- a/src/libstd/f32.rs
+++ b/src/libstd/f32.rs
@@ -1080,6 +1080,26 @@ impl f32 {
         0.5 * ((2.0 * self) / (1.0 - self)).ln_1p()
     }
 
+    /// Returns max if self is greater than max, and min if self is less than min.
+    /// Otherwise this returns self.  Panics if min > max, min equals NaN, or max equals NaN.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// assert!((-3.0f32).clamp(-2.0f32, 1.0f32) == -2.0f32);
+    /// assert!((0.0f32).clamp(-2.0f32, 1.0f32) == 0.0f32);
+    /// assert!((2.0f32).clamp(-2.0f32, 1.0f32) == 1.0f32);
+    /// ```
+    #[unstable(feature = "clamp", issue = "44095")]
+    #[inline]
+    pub fn clamp(self, min: f32, max: f32) -> f32 {
+        assert!(min <= max);
+        let mut x = self;
+        if x < min { x = min; }
+        if x > max { x = max; }
+        x
+    }
+
     /// Raw transmutation to `u32`.
     ///
     /// Converts the `f32` into its raw memory representation,
diff --git a/src/libstd/f64.rs b/src/libstd/f64.rs
index d73d7cd2c7b..b04ba9eabdb 100644
--- a/src/libstd/f64.rs
+++ b/src/libstd/f64.rs
@@ -970,6 +970,26 @@ impl f64 {
         0.5 * ((2.0 * self) / (1.0 - self)).ln_1p()
     }
 
+    /// Returns max if self is greater than max, and min if self is less than min.
+    /// Otherwise this returns self.  Panics if min > max, min equals NaN, or max equals NaN.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// assert!((-3.0f64).clamp(-2.0f64, 1.0f64) == -2.0f64);
+    /// assert!((0.0f64).clamp(-2.0f64, 1.0f64) == 0.0f64);
+    /// assert!((2.0f64).clamp(-2.0f64, 1.0f64) == 1.0f64);
+    /// ```
+    #[unstable(feature = "clamp", issue = "44095")]
+    #[inline]
+    pub fn clamp(self, min: f64, max: f64) -> f64 {
+        assert!(min <= max);
+        let mut x = self;
+        if x < min { x = min; }
+        if x > max { x = max; }
+        x
+    }
+
     // Solaris/Illumos requires a wrapper around log, log2, and log10 functions
     // because of their non-standard behavior (e.g. log(-n) returns -Inf instead
     // of expected NaN).