Skip to content

Commit

Permalink
Document custom representations and endianness
Browse files Browse the repository at this point in the history
Signed-off-by: Martin Kröning <[email protected]>
  • Loading branch information
mkroening authored and wrenger committed Jun 4, 2024
1 parent bf90072 commit ed3b3be
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 0 deletions.
7 changes: 7 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,6 @@ proc-macro = true
quote = "1.0"
syn = { version = "2.0", features = ["full"] }
proc-macro2 = "1.0"

[dev-dependencies]
endian-num = { version = "0.1", features = ["linux-types"] }
54 changes: 54 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -314,6 +314,60 @@ let my_byte_msb = MyMsbByte::new()
assert!(my_byte_msb.0 == 0b1010_0_10_1);
```

## Custom Representation and Endianness

The macro supports custom types for the representation of the bitfield struct.
This can be an endian-defining type like in the following examples (from [`endian-num`]) or any other struct that can be converted to and from the main bitfield type.

The representation and its conversion functions can be specified with the following `#[bitfield]` parameters:
- `repr` specifies the bitfield's representation in memory
- `from` to specify a conversion function from repr to the bitfield's integer type
- `into` to specify a conversion function from the bitfield's integer type to repr

[`endian-num`]: https://docs.rs/endian-num

This example has a little-endian byte order even on big-endian machines:

```rust
use bitfield_struct::bitfield;
use endian_num::le16;

#[bitfield(u16, repr = le16, from = le16::from_ne, into = le16::to_ne)]
struct MyLeBitfield {
#[bits(4)]
first_nibble: u8,
#[bits(12)]
other: u16,
}

let my_be_bitfield = MyLeBitfield::new()
.with_first_nibble(0x1)
.with_other(0x234);

assert_eq!(my_be_bitfield.into_bits().to_le_bytes(), [0x41, 0x23]);
```

This example has a big-endian byte order even on little-endian machines:

```rust
use bitfield_struct::bitfield;
use endian_num::be16;

#[bitfield(u16, repr = be16, from = be16::from_ne, into = be16::to_ne)]
struct MyBeBitfield {
#[bits(4)]
first_nibble: u8,
#[bits(12)]
other: u16,
}

let my_be_bitfield = MyBeBitfield::new()
.with_first_nibble(0x1)
.with_other(0x234);

assert_eq!(my_be_bitfield.into_bits().to_be_bytes(), [0x23, 0x41]);
```

## `fmt::Debug` and `Default`

This macro automatically creates a suitable `fmt::Debug` and `Default` implementations similar to the ones created for normal structs by `#[derive(Debug, Default)]`.
Expand Down

0 comments on commit ed3b3be

Please sign in to comment.