Skip to content

Commit

Permalink
Extract integer conversion into a function
Browse files Browse the repository at this point in the history
  • Loading branch information
s-cerevisiae committed Jan 8, 2025
1 parent 1517a41 commit c04e65d
Showing 1 changed file with 22 additions and 16 deletions.
38 changes: 22 additions & 16 deletions compiler/rustc_lint/src/types/literal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -204,29 +204,35 @@ 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 => {
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) {
if Some(unsigned.size().bits()) == int.bit_width() {
unsigned.uint_ty_str()
} else {
signed.int_ty_str()
}
let signed = literal_to_i128(val, negative).map(|v| Integer::fit_signed(v));
if negative {
signed.map(Integer::int_ty_str)
} else {
unsigned.uint_ty_str()
})
let unsigned = Integer::fit_unsigned(val);
Some(if let Some(signed) = signed {
if Some(unsigned.size().bits()) == int.bit_width() {
unsigned.uint_ty_str()
} else {
signed.int_ty_str()
}
} else {
unsigned.uint_ty_str()
})
}
}
_ => None,
}
}

fn literal_to_i128(val: u128, negative: bool) -> Option<i128> {
if negative {
(val <= i128::MAX as u128 + 1).then(|| val.wrapping_neg() as i128)
} else {
val.try_into().ok()
}
}

fn lint_int_literal<'tcx>(
cx: &LateContext<'tcx>,
type_limits: &TypeLimits,
Expand Down

0 comments on commit c04e65d

Please sign in to comment.