You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Use Result with stable size, alignment, and ABI guarantees ? #1035
Since RFC 3391 (rust-lang/rfcs#3391) the Result type's documentation has a Representation section that describes conditions where Result<T, E> can have the same size, alignment and ABI guarantees as Option<U>.
E.g.
For example, NonZeroI32 qualifies for the Option representation guarantees, and () is a zero-sized type with alignment 1, no fields, and it isn’t non_exhaustive. This means that both Result<NonZeroI32, ()> and Result<(), NonZeroI32> have the same size, alignment, and ABI guarantees as Option<NonZeroI32>. The only difference is the implied semantics:
Option<NonZeroI32> is “a non-zero i32 might be present” Result<NonZeroI32, ()> is “a non-zero i32 success result, if any” Result<(), NonZeroI32> is “a non-zero i32 error result, if any”
I'm trying to lean on this guarantee to implement FFI for a Rust function that wants to use the implied semantics of returning Result<(), NonZeroU32> to mean "a non-zero u32 error result, if any":
If I change may_fail to return Option<NonZeroU32>, I get the results I expected, but I've lost the implied semantics I want to maintain on the Rust-side:
Is there a workaround I could use to get cbindgen to play nice with "stable representation" Result instances? Is my understanding flawed in some other way?
A quick follow-up: the current handling of Option doesn't account for repr(transparent), which is also a valid case for null pointer optimization. Given that there are multiple open PRs addressing it (the most recent being #1183 and #1029), I won't account for it either - I'll build upon general try_NPO-like function and hopefully extend it once PRs are merged
Activity
emilio commentedon Jan 1, 2025
No, I think what you want to do should ideally just work, but it isn't implemented.
fresheed commentedon Sep 22, 2026
I would like to work on that issue
fresheed commentedon Sep 23, 2026
A quick follow-up: the current handling of
Optiondoesn't account forrepr(transparent), which is also a valid case for null pointer optimization. Given that there are multiple open PRs addressing it (the most recent being #1183 and #1029), I won't account for it either - I'll build upon generaltry_NPO-like function and hopefully extend it once PRs are merged