What's the current recommended practice for emulating bitfields?


It appears there is no way to have bitfields in Rust (I could be missing something) which means I would have to manually emulate them with shifts, masks, etc which is error prone and tedious.

What is the current recommended practice for emulating bitfields in Rust?

Context: I’m (attempting to) map hardware memory into Rust data structures. More often than not, the hardware breaks down words into different bit ranges, where different ranges control different functionality. This is relatively easy to handle in C, since you can just define a structure that mirrors this layout (obviously taking care to handle endienness etc) and then manipulate using reads / writes of the structure field.



Will this get you what you need? https://crates.io/crates/bitflags

No shifts but looks like it has the rest. For shifts you could read the bits value, shift that and write it back with from_bits()


Thanks for the pointer. At least from a quick glance, it doesn’t allow the type of bit-precise struct-field definitions I want.

This package seems to do what I wanted, will give it a shot:



I hope you find this crate useful. Any feedback or issue you have will be greatly appreciated.

As you talk abut using it for hardware memory, I’d like to mention svd2rust. This a tool transform an SVD file to rust code. This can be useful if you want to access the register on a ARM CORTEX-M microcontroller.