Rust-bindgen: Constified to Rustified Converter

Created on 3 Dec 2018  路  3Comments  路  Source: rust-lang/rust-bindgen

Defaulting to using constified enums makes sense when dealing with C libraries, given that Rust has undefined behavior in the event of the C library expanding its enum.

However, when doing development on the rust end, it is nice to be able to have facilities like #[derive(Debug)] or exhaustive match.

I'd like to request an option to generate both a Rustified enum and a constified enum, use the constified representation in the library interface, and provide EnumName::from_constified(k: u32) -> Option<EnumName> or similar function to represent a possibly failing (if the const is out of range) translation to a Rustified enum.

I think this could get us the best of both worlds. It avoids undefined behavior, but still allows the use of a more Rust-like data structure with an explicit place to catch the error.

(I'd tag this Enhancement if I could, it's not a bug)

enhancement help wanted

All 3 comments

Yeah, I'd think of generating something like the following:

#[derive(Debug, FromPrimitive)]
#[repr(u8)]
pub enum MyEnum {
    Foo,
    Bar,
    Baz,
}

impl MyEnum {
    type RAW = u8;
}

So that functions use MyEnum::RAW, but you can use MyEnum::from_u8(value).unwrap(), for example.

Relevant code is in src/codegen/mod.rs. Probably a new EnumVariation should be added, and hook in to the options like the rest.

Started to look at this because we'd like get FromPrimitive on some things.

I get the feeling that if we create another enum type we'll end up needing all the different possible combinations of derive traits. Add one more and things get inflexible quick.

Instead of that, we could expand the API that applies traits. Problem with that is all the functions are currently "opt-out" (no_hash(), no_copy(), etc.) where the trait is applied by default. We want to "opt-in" to FromPrimitive.

Started making changes in this direction; adding Builder::fromprimitive() adding another check to CannotDerive::constrain_type(), etc. And decided I'd better check how people feel about doing it this way....

Was this page helpful?
0 / 5 - 0 ratings