|
| 1 | +// Our design for #[bitfield] (see the readme) involves marker types B1 through |
| 2 | +// B64 to indicate the bit width of each field. |
| 3 | +// |
| 4 | +// It would be possible to implement this without having any actual types B1 |
| 5 | +// through B64 -- the attribute macro could recognize the names "B1" through |
| 6 | +// "B64" and deduce the bit width from the number in the name. But this hurts |
| 7 | +// composability! Later we'll want to make bitfield members out of other things, |
| 8 | +// like enums or type aliases which won't necessarily have a width in their |
| 9 | +// name: |
| 10 | +// |
| 11 | +// #[bitfield] |
| 12 | +// struct RedirectionTableEntry { |
| 13 | +// vector: B8, |
| 14 | +// dest_mode: DestinationMode, |
| 15 | +// trigger_mode: TriggerMode, |
| 16 | +// destination: Destination, |
| 17 | +// } |
| 18 | +// |
| 19 | +// #[bitfield] |
| 20 | +// enum DestinationMode { |
| 21 | +// Physical = 0, |
| 22 | +// Logical = 1, |
| 23 | +// } |
| 24 | +// |
| 25 | +// #[bitfield] |
| 26 | +// enum TriggerMode { |
| 27 | +// Edge = 0, |
| 28 | +// Level = 1, |
| 29 | +// } |
| 30 | +// |
| 31 | +// #[target_pointer_width = "64"] |
| 32 | +// type Destination = B30; |
| 33 | +// |
| 34 | +// #[target_pointer_width = "32"] |
| 35 | +// type Destination = B22; |
| 36 | +// |
| 37 | +// So instead of parsing a bit width from the type name, the approach we will |
| 38 | +// follow will hold bit widths in an associated constant of a trait that is |
| 39 | +// implemented for legal bitfield specifier types, including B1 through B64. |
| 40 | +// |
| 41 | +// Create a trait called bitfield::Specifier with an associated constant BITS, |
| 42 | +// and write a function-like procedural macro to define some types B1 through |
| 43 | +// B64 with corresponding impls of the Specifier trait. |
| 44 | +// |
| 45 | +// Be aware that crates that have the "proc-macro" crate type are not allowed to |
| 46 | +// export anything other than procedural macros. The project skeleton for this |
| 47 | +// project has been set up with two crates, one for procedural macros and the |
| 48 | +// other an ordinary library crate for the Specifier trait and B types which |
| 49 | +// also re-exports from the procedural macro crate so that users can get |
| 50 | +// everything through one library. |
| 51 | + |
| 52 | +use bitfield::*; |
| 53 | + |
| 54 | +//#[bitfield] |
| 55 | +pub struct MyFourBytes { |
| 56 | + a: B1, |
| 57 | + b: B3, |
| 58 | + c: B4, |
| 59 | + d: B24, |
| 60 | +} |
| 61 | + |
| 62 | +fn main() { |
| 63 | + assert_eq!(<B24 as Specifier>::BITS, 24); |
| 64 | +} |
0 commit comments