News for hackers. Stuff that matters.
Re:Linux Rust Support by gpm on Tuesday July 06, 2021 @03:49PM (#27753379)
It would be correct, up to the size of the integer. As far as the abi is concerned a C enum is just an integer. As far as the abi is concerned a struct containing a single integer field, is also just an integer.

If there are any values that don't fit in a u32, I would need to use a different int type. C enums automatically use bigger int types if they don't fit in the smaller ones.

If I was on an architecture where int was smaller than 32 bits it would also be incorrect (except by coincidence that 32 bits was the smallest type that could hold all the values). I could "solve" that by using libc::c_int instead, but that only sort of solves the issue because if libc::c_int is 8 bits, and the enum has a value 257, it's just not correct anymore.

I suppose it's possible that some abi treats a struct containing an int differently from an int, I doubt it though. If that's the case, #[repr(transparent)] instead of #[repr(C)] would be slightly more correct.

Re:Linux Rust Support by jlokier on Tuesday July 06, 2021 @07:16PM (#27755546)
> As far as the abi is concerned a C enum is just an integer

In some ABIs this is not true, a C enum is a char if the constants fit. Your code that assumes enums are stored and passed around as 32-bit integers is not entirely portable.

Re:Linux Rust Support by gpm on Tuesday July 06, 2021 @08:33PM (#27756068)
Yes, I agree.

Ultimately, at least at the time, there was no other option that had better compatibility. Now I suppose you could use MaybeUninit<#[repr(C)] enum> or something. Realistically I don't have much confidence in rustc properly matching enum sizes with C implementations that don't follow the typical behaviour here, so I doubt that would be worth it.

I guess the linux kernel is generic enough that it might end up on some such platforms, I guess in that context I'd just bite the bullet and accept undefined behavior if passed an unexpected enum variant, it's not like that should happen in a coherent system like the linux kernel (vs my use case which was wrapping some library that definitely might chose to add enum variants).