@@ -3855,5 +3855,33 @@ macro_rules! int_impl {
38553855 pub const fn max_value( ) -> Self {
38563856 Self :: MAX
38573857 }
3858+
3859+ /// Clamps this number to a symmetric range centred around zero.
3860+ ///
3861+ /// The method clamps the number's magnitude (absolute value) to be at most `limit`.
3862+ ///
3863+ /// This is functionally equivalent to `self.clamp(-limit, limit)`, but is more
3864+ /// explicit about the intent.
3865+ ///
3866+ /// # Examples
3867+ ///
3868+ /// ```
3869+ /// #![feature(clamp_magnitude)]
3870+ #[ doc = concat!( "assert_eq!(120" , stringify!( $SelfT) , ".clamp_magnitude(100), 100);" ) ]
3871+ #[ doc = concat!( "assert_eq!(-120" , stringify!( $SelfT) , ".clamp_magnitude(100), -100);" ) ]
3872+ #[ doc = concat!( "assert_eq!(80" , stringify!( $SelfT) , ".clamp_magnitude(100), 80);" ) ]
3873+ #[ doc = concat!( "assert_eq!(-80" , stringify!( $SelfT) , ".clamp_magnitude(100), -80);" ) ]
3874+ /// ```
3875+ #[ must_use = "this returns the clamped value and does not modify the original" ]
3876+ #[ unstable( feature = "clamp_magnitude" , issue = "148519" ) ]
3877+ #[ inline]
3878+ pub fn clamp_magnitude( self , limit: $UnsignedT) -> Self {
3879+ // Use try_into to handle cases where `limit` is larger than `Self::MAX`.
3880+ let positive_limit = limit. try_into( ) . unwrap_or( Self :: MAX ) ;
3881+ // By capping `positive_limit` at `Self::MAX`, we ensure the range is symmetric.
3882+ // `-positive_limit` is thus always representable.
3883+ let negative_limit = -positive_limit;
3884+ self . clamp( negative_limit, positive_limit)
3885+ }
38583886 }
38593887}
0 commit comments