immunant / c2rust

Migrate C code to Rust
https://c2rust.com/
Other
3.79k stars 219 forks source link

`c2rust-bitfields-derive`: Support `const` initialization #1027

Open kkysen opened 9 months ago

kkysen commented 9 months ago

In rav1d, we need const initialization of bitfield structs to initialization statics. Otherwise, the static has to be mut, which is unsafe to access (or else you have to pay a runtime cost). For example, see this code: https://github.com/memorysafety/rav1d/blob/4029b17b6762d3dcf75c8ac7a592666d483ba78d/src/ipred_prepare_tmpl_8.rs#L273

Since const fns can't have &muts, the setter fns generated can't be made const, but we can add with setters that return an updated struct, and these can be made const. And we might as well make all of the getters const fns, too.

It seems like the relevant code is around here: https://github.com/immunant/c2rust/blob/0ba4903f3b8050e958496420a721f3c764360bbd/c2rust-bitfields-derive/src/lib.rs#L233-L258.

kkysen commented 9 months ago

Changing the generated code to create const fns is non-trivial since it uses a lot of traits, and traits don't allow const fns. Thus, I rolled my own version in https://github.com/memorysafety/rav1d/pull/497, and it was actually really simple. I'm not sure why the implementation here needs traits at all, since the logic is pretty simple.