Rust: Manual reimplementation of C unions and layout testing
Hello all,
As you might know, I'm working on the Rust side of the I2C subsystem, and currently looking into representing struct i2c_algorithm.
In C, this struct contains two anonymous unions for callbacks. bindgen generates rather awkward names for them, which makes the Rust bindings less readable and less stable.
I'm considering declaring this structure manually in i2c.rs, effectively
copying the layout that bindgen would generate but renaming the union
fields for clarity. To avoid accidental ABI drift, I could add compile-time assertions to ensure the Rust and C layouts remain compatible.
Would that be an acceptable approach?
Any thoughts or preferences on how such layout checks should be done in-tree?
Best regards,
Igor Korotin
Quoted 7 lines · Igor Korotin
Hello all,
As you might know, I'm working on the Rust side of the I2C subsystem, and currently looking into representing
struct i2c_algorithm.In C, this struct contains two anonymous unions for callbacks.
In the specific case of struct i2c_algorithm, all the unions are solely for the sake of supporting both a deprecated name and a new name, e.g.master_xfer (deprecated) vs xfer (current). Since the Rust bindings should never need to reference the deprecated name, you could consider proposing an #ifdef __BINDGEN__ which removes the union and *only* includes the new name.
Quoted 2 lines
bindgen generates rather awkward names for them, which makes the Rust bindings less readable and less stable.
You should only need to reference the bindings name in exactly one location, when translating from your Rust representation to the bindings C representation or vice versa. You could also apply a wrapper struct and create accessors if you really don't want to be proxying between two types.
Quoted 5 lines
I'm considering declaring this structure manually in
i2c.rs, effectively copying the layout that bindgen would generate but renaming the union fields for clarity. To avoid accidental ABI drift, I could add compile-time assertions to ensure the Rust and C layouts remain compatible.
The problem is that those compile-time assertions will require to to reference the bindgen struct, or invoke some kind of C parser on the header or debug information, which is much more complex than just referencing the field.
Quoted 4 lines
Would that be an acceptable approach?
Any thoughts or preferences on how such layout checks should be done in-tree?
tl;dr: Such layout checks should be done by bindgen, and I don't think that unions where you only ever need to reference one arm ought to be considered complex enough that we try to implement custom layout checks.
Quoted 4 lines
Best regards,
Igor Korotin