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