- Feature Name:
- Start Date: 2023-02-15
- RFC PR: rust-lang/rfcs#3391
- Rust Issue: rust-lang/rust#110503
This RFC gives specific layout and ABI guarantees when wrapping "non-zero" data types from
Result. This allows those data types to be used directly in FFI, in place of the primitive form of the data (eg:
Result<(), NonZeroI32> instead of
Rust often needs to interact with foreign code. However, foreign function type signatures don't normally support any of Rust's rich type system. Particular function inputs and outputs will simply use 0 (or null) as a sentinel value and the programmer has to remember when that's happening.
Though it's common for "raw bindings" crates to also have "high level wrapper" crates that go with them (eg:
sdl2, etc), someone still has to write those wrapper crates which use the foreign functions directly. Allowing Rust programmers to use more detailed types with foreign functions makes their work easier.
I'm not sure how to write a "guide" portion of this that's any simpler than the "reference" portion, which is already quite short.
When either of these two
Result<T, E>where either
Emeet all of the following conditions:
- Is a zero-sized type with alignment 1 (a "1-ZST").
- Has no fields.
- Does not have the
Is combined with a non-zero or non-null type (see the chart), the combination has the same layout (size and alignment) and the same ABI as the primitive form of the data.
|Example combined Type||Primitive Type|
fn()is listed just once in the above table, this rule applies to all
fntypes (regardless of ABI, arguments, and return type).
For simplicity the table listing only uses
Result<_, ()>, but swapping the
E types, or using
Option<T>, is also valid.
What changes are the implied semantics:
Result<NonZeroI32, ()>is "a non-zero success value"
Result<(), NonZeroI32>is "a non-zero error value"
Option<NonZeroI32>is "a non-zero value is present"
- they all pass over FFI as if they were an
Which type you should use with a particular FFI function signature still depends on the function. Rust can't solve that part for you. However, once you've decided on the type you want to use, the compiler's normal type checks can guide you everywhere else in the code.
- The compiler has less flexibility with respect to discriminant computation and pattern matching optimizations when a type is niche-optimized.
It's always possible to not strengthen the guarantees of the language.
The compiler already supports
Option being combined with specific non-zero types, this RFC mostly expands the list of guaranteed support.
None at this time.
- This could be expanded to include ControlFlow and Poll.
- This could be extended to all similar enums in the future. However, without a way to opt-in to the special layout and ABI guarantees (eg: a trait or attribute) it becomes yet another semver hazard for library authors. The RFC is deliberately limited in scope to avoid bikesheding.