@@ -2235,6 +2235,46 @@ macro_rules! int_impl {
2235
2235
}
2236
2236
}
2237
2237
2238
+ /// Computes the absolute difference between `self` and `other`.
2239
+ ///
2240
+ /// This function always returns the correct answer without overflow or
2241
+ /// panics by returning an unsigned integer.
2242
+ ///
2243
+ /// # Examples
2244
+ ///
2245
+ /// Basic usage:
2246
+ ///
2247
+ /// ```
2248
+ /// #![feature(int_abs_diff)]
2249
+ #[ doc = concat!( "assert_eq!(100" , stringify!( $SelfT) , ".abs_diff(80), 20" , stringify!( $UnsignedT) , ");" ) ]
2250
+ #[ doc = concat!( "assert_eq!(100" , stringify!( $SelfT) , ".abs_diff(110), 10" , stringify!( $UnsignedT) , ");" ) ]
2251
+ #[ doc = concat!( "assert_eq!((-100" , stringify!( $SelfT) , ").abs_diff(80), 180" , stringify!( $UnsignedT) , ");" ) ]
2252
+ #[ doc = concat!( "assert_eq!((-100" , stringify!( $SelfT) , ").abs_diff(-120), 20" , stringify!( $UnsignedT) , ");" ) ]
2253
+ #[ doc = concat!( "assert_eq!(" , stringify!( $SelfT) , "::MIN.abs_diff(" , stringify!( $SelfT) , "::MAX), " , stringify!( $UnsignedT) , "::MAX);" ) ]
2254
+ /// ```
2255
+ #[ unstable( feature = "int_abs_diff" , issue = "89492" ) ]
2256
+ #[ inline]
2257
+ pub const fn abs_diff( self , other: Self ) -> $UnsignedT {
2258
+ if self < other {
2259
+ // Converting a non-negative x from signed to unsigned by using
2260
+ // `x as U` is left unchanged, but a negative x is converted
2261
+ // to value x + 2^N. Thus if `s` and `o` are binary variables
2262
+ // respectively indicating whether `self` and `other` are
2263
+ // negative, we are computing the mathematical value:
2264
+ //
2265
+ // (other + o*2^N) - (self + s*2^N) mod 2^N
2266
+ // other - self + (o-s)*2^N mod 2^N
2267
+ // other - self mod 2^N
2268
+ //
2269
+ // Finally, taking the mod 2^N of the mathematical value of
2270
+ // `other - self` does not change it as it already is
2271
+ // in the range [0, 2^N).
2272
+ ( other as $UnsignedT) . wrapping_sub( self as $UnsignedT)
2273
+ } else {
2274
+ ( self as $UnsignedT) . wrapping_sub( other as $UnsignedT)
2275
+ }
2276
+ }
2277
+
2238
2278
/// Returns a number representing sign of `self`.
2239
2279
///
2240
2280
/// - `0` if the number is zero
0 commit comments