Skip to content

Commit c04e65d

Browse files
committed
Extract integer conversion into a function
1 parent 1517a41 commit c04e65d

File tree

1 file changed

+22
-16
lines changed

1 file changed

+22
-16
lines changed

compiler/rustc_lint/src/types/literal.rs

Lines changed: 22 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -204,29 +204,35 @@ fn get_type_suggestion(t: Ty<'_>, val: u128, negative: bool) -> Option<&'static
204204
match t.kind() {
205205
ty::Uint(ty::UintTy::Usize) | ty::Int(ty::IntTy::Isize) => None,
206206
ty::Uint(_) => Some(Integer::fit_unsigned(val).uint_ty_str()),
207-
ty::Int(_) if negative => {
208-
if val > i128::MAX as u128 + 1 {
209-
None
210-
} else {
211-
Some(Integer::fit_signed(val.wrapping_neg() as i128).int_ty_str())
212-
}
213-
}
214207
ty::Int(int) => {
215-
let unsigned = Integer::fit_unsigned(val);
216-
Some(if let Ok(signed) = i128::try_from(val).map(Integer::fit_signed) {
217-
if Some(unsigned.size().bits()) == int.bit_width() {
218-
unsigned.uint_ty_str()
219-
} else {
220-
signed.int_ty_str()
221-
}
208+
let signed = literal_to_i128(val, negative).map(|v| Integer::fit_signed(v));
209+
if negative {
210+
signed.map(Integer::int_ty_str)
222211
} else {
223-
unsigned.uint_ty_str()
224-
})
212+
let unsigned = Integer::fit_unsigned(val);
213+
Some(if let Some(signed) = signed {
214+
if Some(unsigned.size().bits()) == int.bit_width() {
215+
unsigned.uint_ty_str()
216+
} else {
217+
signed.int_ty_str()
218+
}
219+
} else {
220+
unsigned.uint_ty_str()
221+
})
222+
}
225223
}
226224
_ => None,
227225
}
228226
}
229227

228+
fn literal_to_i128(val: u128, negative: bool) -> Option<i128> {
229+
if negative {
230+
(val <= i128::MAX as u128 + 1).then(|| val.wrapping_neg() as i128)
231+
} else {
232+
val.try_into().ok()
233+
}
234+
}
235+
230236
fn lint_int_literal<'tcx>(
231237
cx: &LateContext<'tcx>,
232238
type_limits: &TypeLimits,

0 commit comments

Comments
 (0)