C2Rust-Bitfields Crate

C2Rust-Bitfields enables you to write structs containing bitfields. It has three primary goals:

  • Byte compatibility with equivalent C bitfield structs
  • The ability to take references/pointers to non bitfield fields
  • Provide methods to read from and write to bitfields

We currently provides a single custom derive, BitfieldStruct, as well as a dependent field attribute bitfield.

Requirements

  • Rust 1.30+
  • Rust Stable, Beta, or Nightly
  • Little Endian Architecture

Example

Suppose you want to write a super compact date struct which only takes up three bytes. In C this would look like this:

  1. struct date {
  2. unsigned char day: 5;
  3. unsigned char month: 4;
  4. unsigned short year: 15;
  5. } __attribute__((packed));

Clang helpfully provides us with this information:

  1. *** Dumping AST Record Layout
  2. 0 | struct date
  3. 0:0-4 | unsigned char day
  4. 0:5-8 | unsigned char month
  5. 1:1-15 | unsigned short year
  6. | [sizeof=3, align=1]

And this is enough to build our rust struct:

  1. extern crate libc;
  2. #[repr(C, align(1))]
  3. #[derive(BitfieldStruct)]
  4. struct Date {
  5. #[bitfield(name = "day", ty = "libc::c_uchar", bits = "0..=4")]
  6. #[bitfield(name = "month", ty = "libc::c_uchar", bits = "5..=8")]
  7. #[bitfield(name = "year", ty = "libc::c_ushort", bits = "9..=23")]
  8. day_month_year: [u8; 3]
  9. }
  10. fn main() {
  11. let mut date = Date {
  12. day_month_year: [0; 3]
  13. };
  14. date.set_day(18);
  15. date.set_month(7);
  16. date.set_year(2000);
  17. assert_eq!(date.day(), 18);
  18. assert_eq!(date.month(), 7);
  19. assert_eq!(date.year(), 2000);
  20. }

Furthermore, C bitfield rules for overflow and signed integers are taken into account.

This crate can generate no_std compatible code when the no_std feature flagis provided.

Tests

Since rust doesn't support a build.rs exclusively for tests, you must manually compile the c test code and link it in.

  1. $ clang tests/bitfields.c -c -fPIC -o tests/bitfields.o
  2. $ ar -rc tests/libtest.a tests/bitfields.o
  3. $ RUSTFLAGS="-L `pwd`/tests" cargo test

Acknowledgements

This crate is inspired by the rust-bitfield, packed_struct, and bindgen crates.