Skip to content

transpile: Use try_from to detect overflow builtin result truncation#1879

Open
thedataking wants to merge 1 commit into
perl/overflow-builtin-typesfrom
perl/overflow-try-from
Open

transpile: Use try_from to detect overflow builtin result truncation#1879
thedataking wants to merge 1 commit into
perl/overflow-builtin-typesfrom
perl/overflow-try-from

Conversation

@thedataking

Copy link
Copy Markdown
Contributor

Follow-up to #1863 addressing @ahomescu's review feedback: emit result_ty::try_from(result).is_err() instead of casting the narrowed result back up to i128 and comparing. The checks are equivalent; try_from reads better in the generated code:

let (c2rust_result, c2rust_overflowed) = (a as i128).overflowing_add(b as i128);
let c2rust_result_narrow = c2rust_result as ::core::ffi::c_ulonglong;
*out = c2rust_result_narrow;
return (c2rust_overflowed || ::core::ffi::c_ulonglong::try_from(c2rust_result).is_err())
    as ::core::ffi::c_int;

The try_from path is derived from the already-converted result type, so crate-local aliases (size_t) and absolute paths (::core::ffi::c_int) both come out right. A new overflow_mixed.c snapshot pins the generated idiom.

Based on #1863; will retarget to master when that merges.

Emitting result_ty::try_from(result).is_err() states the intent more
clearly in the generated code than casting the narrowed result back up
to i128 and comparing.
mut out: *mut ::core::ffi::c_int,
) -> ::core::ffi::c_int {
let (c2rust_result, c2rust_overflowed) = (a as i128).overflowing_mul(b as i128);
let c2rust_result_narrow = c2rust_result as ::core::ffi::c_int;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you're using try_from below, you don't need this cast here because Ok(x) is what you want.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants