From c04e65dbc5f936fdd4dc53ba7b7a058165aad157 Mon Sep 17 00:00:00 2001 From: spore Date: Thu, 9 Jan 2025 02:02:40 +0800 Subject: [PATCH] Extract integer conversion into a function --- compiler/rustc_lint/src/types/literal.rs | 38 ++++++++++++++---------- 1 file changed, 22 insertions(+), 16 deletions(-) diff --git a/compiler/rustc_lint/src/types/literal.rs b/compiler/rustc_lint/src/types/literal.rs index 13eca89fba67b..4faf345bcd58f 100644 --- a/compiler/rustc_lint/src/types/literal.rs +++ b/compiler/rustc_lint/src/types/literal.rs @@ -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 { + 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,