• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Using the Bitfield Types Generated by Bindgen
2
3## Bitfield Strategy Overview
4
5As Rust does not support bitfields, Bindgen generates a struct for each with the following characteristics
6* Immutable getter functions for each bitfield named ```<bitfield>```
7* Setter functions for each contiguous block of bitfields named ```set_<bitfield>```
8* For each contiguous block of bitfields, Bindgen emits an opaque physical field that contains one or more logical bitfields
9* A static constructor  ```new_bitfield_{1, 2, ...}``` with a parameter for each bitfield contained within the opaque physical field.
10
11To keep bindgen from generating the bitfield unit struct, it can be blocklisted like any
12other type, i.e. `--blocklist-type "__BindgenBitfieldUnit"`. This may be useful if
13you want to define a custom implementation, or your generated bindings import a
14pre-existing definition for the bitfield unit type.
15
16## Bitfield examples
17
18For this discussion, we will use the following C type definitions and functions.
19```c
20typedef struct {
21    unsigned int a: 1;
22    unsigned int b: 1;
23    unsigned int c: 2;
24
25} StructWithBitfields;
26
27// Create a default bitfield
28StructWithBitfields create_bitfield();
29
30// Print a bitfield
31void print_bitfield(StructWithBitfields bfield);
32```
33
34Bindgen creates a set of field getters and setters for interacting with the bitset. For example,
35
36```rust,ignore
37    let mut bfield = unsafe { create_bitfield() };
38
39    bfield.set_a(1);
40    println!("a set to {}", bfield.a());
41    bfield.set_b(1);
42    println!("b set to {}", bfield.b());
43    bfield.set_c(3);
44    println!("c set to {}", bfield.c());
45
46    unsafe { print_bitfield(bfield) };
47```
48
49will print out
50
51```text
52a set to 1
53b set to 1
54c set to 3
55StructWithBitfields: a:1, b:1, c:3
56```
57
58Overflowing a bitfield will result in the same behavior as in C/C++: the bitfield will be set to 0.
59
60```rust,ignore
61    let mut bfield = unsafe { create_bitfield() };
62    bfield.set_a(1);
63    bfield.set_b(1);
64    bfield.set_c(12);
65    println!("c set to {} due to overflow", bfield.c());
66
67    unsafe { print_bitfield(bfield) };
68```
69
70will print out
71
72```text
73c set to 0 due to overflow
74StructWithBitfields: a:1, b:1, c:0
75```
76
77To create a new bitfield in Rust, use the bitfield allocation unit constructor.
78
79Note: This requires the Builder's derive_default to be set to true, otherwise the necessary Default functions won't be generated.
80
81```rust,ignore
82    let bfield = StructWithBitfields{
83        _bitfield_1: StructWithBitfields::new_bitfield_1(0,0,0),
84        ..Default::default()
85    };
86
87    unsafe { print_bitfield(bfield) };
88```
89
90This will print out
91
92```text
93StructWithBitfields: a:0, b:0, c:0
94```
95