@@ -493,6 +493,43 @@ macro_rules! nonzero_unsigned_operations {
493
493
pub const fn ilog10( self ) -> u32 {
494
494
super :: int_log10:: $Int( self . 0 )
495
495
}
496
+
497
+ /// Calculates the middle point of `self` and `rhs`.
498
+ ///
499
+ /// `midpoint(a, b)` is `(a + b) >> 1` as if it were performed in a
500
+ /// sufficiently-large signed integral type. This implies that the result is
501
+ /// always rounded towards negative infinity and that no overflow will ever occur.
502
+ ///
503
+ /// # Examples
504
+ ///
505
+ /// ```
506
+ /// #![feature(num_midpoint)]
507
+ #[ doc = concat!( "# use std::num::" , stringify!( $Ty) , ";" ) ]
508
+ ///
509
+ /// # fn main() { test().unwrap(); }
510
+ /// # fn test() -> Option<()> {
511
+ #[ doc = concat!( "let one = " , stringify!( $Ty) , "::new(1)?;" ) ]
512
+ #[ doc = concat!( "let two = " , stringify!( $Ty) , "::new(2)?;" ) ]
513
+ #[ doc = concat!( "let four = " , stringify!( $Ty) , "::new(4)?;" ) ]
514
+ ///
515
+ /// assert_eq!(one.midpoint(four), two);
516
+ /// assert_eq!(four.midpoint(one), two);
517
+ /// # Some(())
518
+ /// # }
519
+ /// ```
520
+ #[ unstable( feature = "num_midpoint" , issue = "110840" ) ]
521
+ #[ rustc_const_unstable( feature = "const_num_midpoint" , issue = "110840" ) ]
522
+ #[ rustc_allow_const_fn_unstable( const_num_midpoint) ]
523
+ #[ must_use = "this returns the result of the operation, \
524
+ without modifying the original"]
525
+ #[ inline]
526
+ pub const fn midpoint( self , rhs: Self ) -> Self {
527
+ // SAFETY: The only way to get `0` with midpoint is to have two opposite or
528
+ // near opposite numbers: (-5, 5), (0, 1), (0, 0) which is impossible because
529
+ // of the unsignedness of this number and also because $Ty is guaranteed to
530
+ // never being 0.
531
+ unsafe { $Ty:: new_unchecked( self . get( ) . midpoint( rhs. get( ) ) ) }
532
+ }
496
533
}
497
534
) +
498
535
}
0 commit comments