@@ -617,17 +617,26 @@ impl Add<u8> for AsciiChar {
617
617
/// Calculates sum of the ASCII value and given offset.
618
618
///
619
619
/// In debug builds, panics if result is greater than largest ASCII value.
620
- ///
621
620
/// In release builds wraps the value (i.e. masks out the most significant
622
621
/// bit) so the output is a valid ASCII character.
623
622
///
623
+ /// # Examples
624
+ ///
624
625
/// ```
625
626
/// #![feature(ascii_char, ascii_char_variants)]
626
627
/// use core::ascii::Char;
627
628
///
628
629
/// assert_eq!(Char::Digit8, Char::Digit0 + 8);
629
630
/// ```
631
+ ///
632
+ /// ```should_panic
633
+ /// #![feature(ascii_char, ascii_char_variants)]
634
+ /// use core::ascii::Char;
635
+ ///
636
+ /// let _ = Char::Digit0 + 100;
637
+ /// ```
630
638
#[ inline]
639
+ #[ rustc_inherit_overflow_checks]
631
640
fn add ( self , rhs : u8 ) -> Self :: Output {
632
641
add_impl ( self , rhs)
633
642
}
@@ -638,6 +647,7 @@ impl Add<AsciiChar> for u8 {
638
647
type Output = AsciiChar ;
639
648
640
649
#[ inline]
650
+ #[ rustc_inherit_overflow_checks]
641
651
fn add ( self , rhs : AsciiChar ) -> Self :: Output {
642
652
add_impl ( rhs, self )
643
653
}
@@ -646,6 +656,7 @@ impl Add<AsciiChar> for u8 {
646
656
#[ unstable( feature = "ascii_char" , issue = "110998" ) ]
647
657
impl AddAssign < u8 > for AsciiChar {
648
658
#[ inline]
659
+ #[ rustc_inherit_overflow_checks]
649
660
fn add_assign ( & mut self , rhs : u8 ) {
650
661
* self = add_impl ( * self , rhs)
651
662
}
@@ -656,12 +667,11 @@ forward_ref_binop! { impl Add, add for u8, AsciiChar }
656
667
forward_ref_op_assign ! { impl AddAssign , add_assign for AsciiChar , u8 }
657
668
658
669
#[ inline]
670
+ #[ rustc_inherit_overflow_checks]
659
671
fn add_impl ( chr : AsciiChar , rhs : u8 ) -> AsciiChar {
660
- let sum = u16:: from ( u8:: from ( chr) ) + u16:: from ( rhs) ;
661
- if !cfg ! ( debug_assertions) || sum < 128 {
662
- // SAFETY: `& 127` limits the sum to a valid ASCII value.
663
- unsafe { AsciiChar :: from_u8_unchecked ( ( sum as u8 ) & 127 ) }
664
- } else {
665
- panic ! ( "{} + {} overflows ASCII value" , u8 :: from( chr) , rhs)
666
- }
672
+ // Make sure we overflow if chr + rhs ≥ 128. Since we inherit overflow
673
+ // checks, we’re wrap in release and panic in debug builds.
674
+ let sum = u8:: from ( chr) + 128 + rhs;
675
+ // SAFETY: `sum & 127` limits the sum to a valid ASCII value.
676
+ unsafe { AsciiChar :: from_u8_unchecked ( sum & 127 ) }
667
677
}
0 commit comments