1
Fork 0

Extract integer conversion into a function

This commit is contained in:
spore 2025-01-09 02:02:40 +08:00
parent 1517a41c57
commit c04e65dbc5

View file

@ -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
ty::Int(int) => {
let signed = literal_to_i128(val, negative).map(|v| Integer::fit_signed(v));
if negative {
signed.map(Integer::int_ty_str)
} else {
Some(Integer::fit_signed(val.wrapping_neg() as i128).int_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()
})
}
}
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()
}
} 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,