Skip to content

Commit

Permalink
Detect overflow when the literal is negative
Browse files Browse the repository at this point in the history
  • Loading branch information
s-cerevisiae committed Jan 8, 2025
1 parent be23697 commit 330be17
Showing 1 changed file with 7 additions and 1 deletion.
8 changes: 7 additions & 1 deletion compiler/rustc_lint/src/types/literal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,13 @@ fn get_type_suggestion(t: Ty<'_>, val: u128, negative: bool) -> Option<&'static
match t.kind() {
ty::Uint(ty::UintTy::Usize) | ty::Int(ty::IntTy::Isize) => None,
ty::Uint(_) => Some(Integer::fit_unsigned(val).uint_ty_str()),
ty::Int(_) if negative => Some(Integer::fit_signed(-(val as i128)).int_ty_str()),
ty::Int(_) if negative => {
if val > i128::MAX as u128 + 1 {
None
} else {
Some(Integer::fit_signed(val.wrapping_neg() as i128).int_ty_str())
}
}
ty::Int(int) => {
let unsigned = Integer::fit_unsigned(val);
Some(if let Ok(signed) = i128::try_from(val).map(Integer::fit_signed) {
Expand Down

0 comments on commit 330be17

Please sign in to comment.