summaryrefslogtreecommitdiff
path: root/book/src/using-bitfields.md
blob: 41e07ad70371b18984dc99653f7b75d5c54297e6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# Using the Bitfield Types Generated by Bindgen

## Bitfield Strategy Overview

As Rust does not support bitfields, Bindgen generates a struct for each with the following characteristics
* Immutable getter functions for each bitfield named ```<bitfield>```
* Setter functions for each contiguous block of bitfields named ```set_<bitfield>```
* Far each contiguous block of bitfields, Bindgen emits an opaque physical field that contains one or more logical bitfields
* A static constructor  ```new_bitfield_{1, 2, ...}``` with a parameter for each bitfield contained within the opaque physical field.

## Bitfield examples

For this discussion, we will use the following C type definitions and functions.
```c
typedef struct {
    unsigned int a: 1;
    unsigned int b: 1;
    unsigned int c: 2;
    
} StructWithBitfields;

// Create a default bitfield
StructWithBitfields create_bitfield();

// Print a bitfield
void print_bitfield(StructWithBitfields bfield);
```

Bindgen creates a set of field getters and setters for interacting with the bitset. For example, 

```rust,ignore
    let mut bfield = unsafe { create_bitfield() };
    
    bfield.set_a(1);
    println!("a set to {}", bfield.a());
    bfield.set_b(1);
    println!("b set to {}", bfield.b());
    bfield.set_c(3);
    println!("c set to {}", bfield.c());
    
    unsafe { print_bitfield(bfield) };
```

will print out

```text
a set to 1
b set to 1
c set to 3
StructWithBitfields: a:1, b:1, c:3
```

Overflowing a bitfield will result in the same behavior as in C/C++: the bitfield will be set to 0.

```rust,ignore
    let mut bfield = unsafe { create_bitfield() };
    bfield.set_a(1);
    bfield.set_b(1);
    bfield.set_c(12);
    println!("c set to {} due to overflow", bfield.c());
    
    unsafe { print_bitfield(bfield) };
```

will print out

```text
c set to 0 due to overflow
StructWithBitfields: a:1, b:1, c:0
```

To create a new bitfield in Rust, use the bitfield allocation unit constructor.

Note: This requires the Builder's derive_default to be set to true, otherwise the necessary Default functions won't be generated.

```rust,ignore
    let bfield = StructWithBitfields{
        _bitfield_1: StructWithBitfields::new_bitfield_1(0,0,0),
        ..Default::default()
    };
    
    unsafe { print_bitfield(bfield) };
```

This will print out

```text
StructWithBitfields: a:0, b:0, c:0
```