@@ -970,6 +970,32 @@ impl f64 {
970970 0.5 * ( ( 2.0 * self ) / ( 1.0 - self ) ) . ln_1p ( )
971971 }
972972
973+ /// Returns max if self is greater than max, and min if self is less than min.
974+ /// Otherwise this returns self.
975+ ///
976+ /// # Examples
977+ ///
978+ /// ```
979+ /// #![feature(clamp)]
980+ /// use std::f64::NAN;
981+ /// assert!((-3.0f64).clamp(-2.0f64, 1.0f64) == -2.0f64);
982+ /// assert!((0.0f64).clamp(-2.0f64, 1.0f64) == 0.0f64);
983+ /// assert!((2.0f64).clamp(-2.0f64, 1.0f64) == 1.0f64);
984+ /// assert!((NAN).clamp(-2.0f64, 1.0f64).is_nan());
985+ /// ```
986+ ///
987+ /// # Panics
988+ /// Panics if min > max, min is NaN, or max is NaN.
989+ #[ unstable( feature = "clamp" , issue = "44095" ) ]
990+ #[ inline]
991+ pub fn clamp ( self , min : f64 , max : f64 ) -> f64 {
992+ assert ! ( min <= max) ;
993+ let mut x = self ;
994+ if x < min { x = min; }
995+ if x > max { x = max; }
996+ x
997+ }
998+
973999 // Solaris/Illumos requires a wrapper around log, log2, and log10 functions
9741000 // because of their non-standard behavior (e.g. log(-n) returns -Inf instead
9751001 // of expected NaN).
@@ -1642,4 +1668,22 @@ mod tests {
16421668 assert_approx_eq ! ( f64 :: from_bits( 0x4094e40000000000 ) , 1337.0 ) ;
16431669 assert_approx_eq ! ( f64 :: from_bits( 0xc02c800000000000 ) , -14.25 ) ;
16441670 }
1671+
1672+ #[ test]
1673+ #[ should_panic]
1674+ fn test_clamp_min_greater_than_max ( ) {
1675+ 1.0f64 . clamp ( 3.0 , 1.0 ) ;
1676+ }
1677+
1678+ #[ test]
1679+ #[ should_panic]
1680+ fn test_clamp_min_is_nan ( ) {
1681+ 1.0f64 . clamp ( NAN , 1.0 ) ;
1682+ }
1683+
1684+ #[ test]
1685+ #[ should_panic]
1686+ fn test_clamp_max_is_nan ( ) {
1687+ 1.0f64 . clamp ( 3.0 , NAN ) ;
1688+ }
16451689}
0 commit comments