@@ -376,17 +376,56 @@ pub fn clamp<T: PartialOrd>(input: T, min: T, max: T) -> T {
376
376
}
377
377
}
378
378
379
+ /// A value bounded by a minimum value
380
+ ///
381
+ /// If input is less than min then this returns min.
382
+ /// Otherwise this returns input.
383
+ /// `clamp_min(std::f32::NAN, 1.0)` preserves `NAN` different from `f32::min(std::f32::NAN, 1.0)`.
384
+ #[ inline]
385
+ pub fn clamp_min < T : PartialOrd > ( input : T , min : T ) -> T {
386
+ if input < min {
387
+ min
388
+ } else {
389
+ input
390
+ }
391
+ }
392
+
393
+ /// A value bounded by a maximum value
394
+ ///
395
+ /// If input is greater than max then this returns max.
396
+ /// Otherwise this returns input.
397
+ /// `clamp_max(std::f32::NAN, 1.0)` preserves `NAN` different from `f32::max(std::f32::NAN, 1.0)`.
398
+ #[ inline]
399
+ pub fn clamp_max < T : PartialOrd > ( input : T , max : T ) -> T {
400
+ if input > max {
401
+ max
402
+ } else {
403
+ input
404
+ }
405
+ }
406
+
379
407
#[ test]
380
408
fn clamp_test ( ) {
381
409
// Int test
382
410
assert_eq ! ( 1 , clamp( 1 , -1 , 2 ) ) ;
383
411
assert_eq ! ( -1 , clamp( -2 , -1 , 2 ) ) ;
384
412
assert_eq ! ( 2 , clamp( 3 , -1 , 2 ) ) ;
413
+ assert_eq ! ( 1 , clamp_min( 1 , -1 ) ) ;
414
+ assert_eq ! ( -1 , clamp_min( -2 , -1 ) ) ;
415
+ assert_eq ! ( -1 , clamp_max( 1 , -1 ) ) ;
416
+ assert_eq ! ( -2 , clamp_max( -2 , -1 ) ) ;
385
417
386
418
// Float test
387
419
assert_eq ! ( 1.0 , clamp( 1.0 , -1.0 , 2.0 ) ) ;
388
420
assert_eq ! ( -1.0 , clamp( -2.0 , -1.0 , 2.0 ) ) ;
389
421
assert_eq ! ( 2.0 , clamp( 3.0 , -1.0 , 2.0 ) ) ;
422
+ assert_eq ! ( 1.0 , clamp_min( 1.0 , -1.0 ) ) ;
423
+ assert_eq ! ( -1.0 , clamp_min( -2.0 , -1.0 ) ) ;
424
+ assert_eq ! ( -1.0 , clamp_max( 1.0 , -1.0 ) ) ;
425
+ assert_eq ! ( -2.0 , clamp_max( -2.0 , -1.0 ) ) ;
426
+ assert ! ( clamp( :: core:: f32 :: NAN , -1.0 , 1.0 ) . is_nan( ) ) ;
427
+ assert ! ( clamp_min( :: core:: f32 :: NAN , 1.0 ) . is_nan( ) ) ;
428
+ assert ! ( clamp_max( :: core:: f32 :: NAN , 1.0 ) . is_nan( ) ) ;
390
429
}
391
430
392
431
#[ test]
0 commit comments