bitfields_impl/lib.rs
1use generating::bitfield::bitfield_generator::generate_bitfield;
2use parsing::bitfields::bitfield::Bitfield;
3use parsing::bitfields::bitfield_parser::parse_bitfield_struct;
4
5use crate::generating::bitflag::bitflag_generator::generate_bitflag;
6use crate::parsing::bitflags::bitflag_parser::parse_bitflag_enum;
7
8mod generating;
9mod parsing;
10
11/// An error message to display when an internal error occurs.
12const INTERNAL_ERROR_MESSAGE: &str = "A major unexpected error has occurred. If possible, please file an issue with code reproducing the error to https://github.com/gregorygaines/bitfields-rs/issues";
13
14#[rustfmt::skip]
15/// <!-- rust-docs-start -->
16/// ### Bitfield Types
17///
18/// A primitive bitfield can represent the unsigned types (`u8`, `u16`, `u32`,
19/// `u64`, `u128`), the max being 128-bits. The bitfield field bits must add
20/// up to the exact number of bits of the bitfield type.
21///
22/// ```rust
23/// # use bitfields_impl as bitfields;
24/// use bitfields::bitfield;
25///
26/// #[bitfield(u8)]
27/// struct BitfieldU8 {
28/// a: u8,
29/// }
30///
31/// #[bitfield(u32)]
32/// struct BitfieldMultipleFields {
33/// a: u8,
34/// b: u8,
35/// c: u8,
36/// d: u8,
37/// }
38/// ```
39///
40/// ### Array Backed Bitfield
41///
42/// A bitfield can also be backed by an `[u8;N]` array type, which allows for
43/// bitfields larger than `u128`. Just like primitive bitfields, the bitfield
44/// field bits must add up to the exact number of bits of the bitfield type.
45///
46/// If you have an array backed bitfield that may overflow the stack, you can pass
47/// the optional argument `#[bitfield(array_heap = true)]` to the bitfield, which
48/// will box the array on the heap instead of the stack. Keep in mind that you
49/// **lose constant memory, zero-allocation, and no_std guarantees when using heap
50/// array bitfields**.
51///
52/// ```rust
53/// # use bitfields_impl as bitfields;
54/// use bitfields::bitfield;
55///
56/// #[bitfield([u8; 17])] /// 136 bits.
57/// struct ArrayBitfield {
58/// a: u128,
59/// b: u8,
60/// }
61///
62/// #[bitfield([u8; 96], array_heap = true
63/// )] /// Allocated on the heap, 768 bits (96 bytes).
64/// struct HeapArrayBitfield {
65/// a: u128,
66/// b: u128,
67/// c: u128,
68/// d: u128,
69/// e: u128,
70/// f: u128,
71/// }
72///
73/// fn main() {
74/// let array_bitfield = ArrayBitfield::new();
75/// let heap_array_bitfield = HeapArrayBitfield::new();
76/// }
77/// ```
78///
79/// ### Constructing a Bitfield
80///
81/// #### Bitfield Constructor
82///
83/// A bitfield can be initialized with the `new` and `new_without_defaults`
84/// constructors. The former initializes the bitfield to zero, but sets
85/// default values, while the latter initializes the bitfield to zero without
86/// setting any default values, except for reserved fields with default values,
87/// which always keep their defaults.
88///
89/// ```rust
90/// # use bitfields_impl as bitfields;
91/// use bitfields::bitfield;
92///
93/// #[bitfield(u32)]
94/// struct Bitfield {
95/// #[bits(default = 0x12)]
96/// a: u8,
97/// #[bits(default = 0x34)]
98/// b: u8,
99/// #[bits(default = 0x56)]
100/// c: u8,
101///
102/// /// Reserved field, keeps its default value even in `new_without_defaults`.
103/// #[bits(default = 0x78)]
104/// _d: u8,
105/// }
106///
107/// fn main() {
108/// let bitfield = Bitfield::new();
109/// assert_eq!(bitfield.a(), 0x12);
110/// assert_eq!(bitfield.b(), 0x34);
111/// assert_eq!(bitfield.c(), 0x56);
112/// assert_eq!(bitfield.into_bits(), 0x78563412);
113///
114/// let bitfield_without_defaults = Bitfield::new_without_defaults();
115/// assert_eq!(bitfield_without_defaults.a(), 0);
116/// assert_eq!(bitfield_without_defaults.b(), 0);
117/// assert_eq!(bitfield_without_defaults.c(), 0);
118/// assert_eq!(bitfield_without_defaults.into_bits(), 0x78000000);
119/// }
120/// ```
121///
122/// #### Bitfield Builder
123///
124/// A bitfield can also be constructed using a fluent builder pattern using the
125/// `<Bitfield>Builder::new` and `<Bitfield>Builder::new_without_defaults`
126/// constructors. They operate the same as the `new` and `new_without_defaults`,
127/// but allow you to set fields using a fluent builder pattern.
128///
129/// ```rust
130/// # use bitfields_impl as bitfields;
131/// use bitfields::bitfield;
132///
133/// #[bitfield(u32)]
134/// struct Bitfield {
135/// #[bits(default = 0x12)]
136/// a: u8,
137/// #[bits(default = 0x34)]
138/// b: u8,
139/// #[bits(default = 0x56)]
140/// c: u8,
141/// #[bits(default = 0x78)]
142/// _reserved: u8,
143/// }
144///
145/// fn main() {
146/// let builder = BitfieldBuilder::new()
147/// .with_a(0x12)
148/// .with_b(0x34)
149/// .with_c(0x56)
150/// // with_reserved() /// Compile error, reserved fields are inaccessible.
151/// .build();
152/// assert_eq!(builder.a(), 0x12);
153/// assert_eq!(builder.b(), 0x34);
154/// assert_eq!(builder.c(), 0x56);
155/// assert_eq!(builder.into_bits(), 0x78563412);
156/// }
157/// ```
158///
159/// ### Bitfield Field Types
160///
161/// A bitfield field can be any unsigned (`u8`, `u16`, `u32`, `u64`, `u128`).
162///
163/// Fields can be annotated with the `#[bits]` attribute to specify the number of
164/// bits the field occupies, a default value, or access. If the `#[bits]` attribute
165/// is omitted, the field will occupy the number of bits of its type. For example,
166/// a `u8` field will occupy 8 bits.
167///
168/// Fields can have a default value, which must fit in the field type or the
169/// specified bits of the field. A default value must be a const variable or
170/// a const function. Just be aware that const function and variable
171/// defaults lose their compile-time field size checks, so it's
172/// up to you to make sure they fit.
173///
174/// ```rust
175/// # use bitfields_impl as bitfields;
176/// use bitfields::bitfield;
177///
178/// /// A constant variable can be used as a default value.
179/// const CONST_VAR: u8 = 0x2;
180///
181/// /// A const function can be used as a default value.
182/// const fn answer_to_life() -> u8 {
183/// 0x1
184/// }
185///
186/// #[bitfield(u32)]
187/// struct Bitfield {
188/// /// No bits attribute, so it defaults to the size of the field type,
189/// /// which is 8 bits for a `u8` type.
190/// #[bits(default = 0xFF)]
191/// a: u8,
192///
193/// /// ❌ No compile time default value size checks for const variables.
194/// #[bits(2, default = CONST_VAR)]
195/// const_var_default: u8,
196///
197/// /// ❌ No compile time default value size checks for const functions.
198/// #[bits(2, default = answer_to_life())]
199/// const_fn_default: u8,
200///
201/// #[bits(20)]
202/// _reserved: u32,
203/// }
204///
205/// fn main() {
206/// let bitfield = Bitfield::new();
207/// assert_eq!(bitfield.a(), 0xFF);
208/// assert_eq!(bitfield.const_var_default(), 0x2);
209/// assert_eq!(bitfield.const_fn_default(), 0x1);
210/// }
211/// ```
212///
213/// #### Signed Bitfield Fields
214///
215/// A bitfield can have signed (`i8`, `i16`, `i32`, `i64`, `i128`) types. Signed
216/// types are treated as 2's complement data types, where the most significant bit
217/// representing the sign bit. For example, if you had a field with 5 bits, the value
218/// range would be `-16` to `15`. The more bits you include, the larger the range!
219///
220/// ```rust
221/// # use bitfields_impl as bitfields;
222/// use bitfields::bitfield;
223///
224/// #[bitfield(u16)]
225/// struct Bitfield {
226/// #[bits(default = -127)]
227/// a: i8,
228///
229/// /// Sign-extended by the most significant bit of 4 bits. Also treated as 2's
230/// /// complement, meaning this field with 4 bits has the value range of
231/// /// `-8` to `7`. You can add more bits to increase this range!
232/// #[bits(4, default = 9)]
233/// b_sign_extended: i8,
234///
235/// #[bits(4)]
236/// _reserved: u8,
237/// }
238///
239/// fn main() {
240/// let bitfield = Bitfield::new();
241/// assert_eq!(bitfield.a(), -127);
242/// assert_eq!(bitfield.b_sign_extended(), -7);
243/// }
244/// ```
245///
246/// #### Array Bitfield Fields
247///
248/// Bitfield fields can also be `[u8;N]` array types, which are useful
249/// for representing fields that are larger than 128 bits.
250///
251/// ```rust
252/// # use bitfields_impl as bitfields;
253/// use bitfields::bitfield;
254///
255/// #[bitfield(u32)]
256/// struct Packet {
257/// header: [u8; 2],
258/// #[bits(16)]
259/// payload: [u8; 16], // 128 bits
260/// }
261///
262/// fn main() {
263/// let mut packet = Packet::new();
264/// packet.set_header([0u8; 2]);
265/// packet.set_payload([0xFFu8; 16]);
266///
267/// assert_eq!(packet.header(), [0u8; 2]);
268/// assert_eq!(packet.payload(), [0xFFu8, 0xFFu8, 0, 0, 0,
269/// 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
270/// }
271/// ```
272///
273/// #### Checked Setters
274///
275/// Normally, when fields are set, the provided value is truncated to the number of
276/// bits of the field. Fields also have checked setters that returns an error if
277/// the value overflows the bits of the field.
278///
279/// ```rust
280/// # use bitfields_impl as bitfields;
281/// use bitfields::bitfield;
282///
283/// #[bitfield(u16)]
284/// struct Bitfield {
285/// a: u8,
286/// #[bits(4)]
287/// b: u8,
288/// #[bits(4)]
289/// _reserved: u8,
290/// }
291///
292/// fn main() {
293/// let mut bitfield = Bitfield::new();
294/// bitfield.set_a(0xFF);
295/// bitfield.set_b(0x12); // Truncated to 4 bits.
296/// assert_eq!(bitfield.a(), 0xFF);
297/// assert_eq!(bitfield.b(), 0x2);
298///
299/// let res = bitfield.checked_set_b(0x12); // Error, value overflows bits.
300/// assert!(res.is_err());
301/// }
302/// ```
303///
304/// #### Field Access
305///
306/// Field access can be controlled by specifying the `#[bits(access = N)]` arg on a
307/// field. There are four access levels:
308///
309/// - `rw` - Read and write access (default).
310///
311/// - `ro` - Read-only access, only set during construction or from bits conversion.
312///
313/// - `wo` - Write-only access, can only be set but not read. A use case for
314/// write-only
315/// fields is for fields that trigger an action when set, but their value is not
316/// stored.
317/// You can write your own setters for `wo` fields to trigger the action you want
318/// when
319/// the field is set.
320///
321/// - `na` - No access, the field is inaccessible, functioning similarly to reserved
322/// fields. But use a **reserved field** when you want to pad/fill bits that have
323/// no user-facing identity (hardware reserved bits, alignment gaps). Use
324/// **`access = na`** when the field is a real, named field that you want to
325/// completely lock down from the API while still keeping it distinguishable
326/// by name. Later on, if you want to expose the field, you can just change
327/// the access level without having to change the field name.
328///
329/// ```rust
330/// # use bitfields_impl as bitfields;
331/// use bitfields::bitfield;
332///
333/// #[bitfield(u32)]
334/// struct Bitfield {
335/// read_write: u8,
336///
337/// #[bits(access = ro)]
338/// read_only: u8,
339///
340/// #[bits(access = wo)]
341/// write_only: u8,
342///
343/// #[bits(default = 0xFF, access = na)]
344/// no_access: u8,
345/// }
346///
347/// impl Bitfield {
348/// /// Custom setter for the write-only field that triggers an action when set.
349/// fn custom_set_write_only(&mut self, value: u8) {
350/// // Trigger some action here when the write-only field is set.
351/// println!("Write-only field set to: {}", value);
352///
353/// // Using the generated constants, you can manipulate the bits of the
354/// // write-only field even though it's inaccessible from the API.
355/// self.0 = (self.0 & !(0xFF << Self::WRITE_ONLY_OFFSET)) |
356/// ((value as u32) << Self::WRITE_ONLY_OFFSET);
357/// }
358/// }
359///
360/// fn main() {
361/// let mut bitfield = BitfieldBuilder::new()
362/// .with_read_write(0x12)
363/// .with_read_only(0x34) // Read-only fields only set during construction or from bits.
364/// .with_write_only(0x56)
365/// // .with_no_access(0x78) // Compile error, no-access field can't be set.
366/// .build();
367/// bitfield.set_read_write(0x12);
368/// // bitfield.set_read_only(1); // Compile error, read-only field can't be set.
369/// bitfield.set_write_only(0x56);
370/// // bitfield.set_no_access(0x78); // Compile error, no-access field can't be set.
371///
372/// assert_eq!(bitfield.read_write(), 0x12);
373/// assert_eq!(bitfield.read_only(), 0x34);
374/// // assert_eq!(bitfield.write_only(), 0x56); // Compile error, write-only can't be read.
375/// // assert_eq!(bitfield.no_access(), 0xFF); // Compile error, no-access field can't be accessed.
376/// assert_eq!(bitfield.into_bits(), 0xFF563412); // All fields exposed when converted to bits.
377///
378/// bitfield.custom_set_write_only(0xAB); // Custom setter for write-only field that triggers an action when set.
379/// assert_eq!(bitfield.into_bits(), 0xFFAB3412); // All fields exposed when converted to bits,
380/// // including the write-only field that was set
381/// // using a custom setter.
382/// }
383/// ```
384///
385/// #### Custom Types
386///
387/// A bitfield field can be a user-defined custom types, but the bits of the field
388/// must be specified since the macro has no way of knowing how many bits the custom
389/// type occupies. To interface with a bitfield, the custom types must implement the
390/// const functions `from_bits` and `into_bits`.
391///
392/// ```rust
393/// # use bitfields_impl as bitfields;
394/// use bitfields::bitflag;
395/// use bitfields::bitfield;
396///
397/// const DEFAULT_PLAYER_STATE: PlayerState = PlayerState {
398/// health: 15,
399/// mana: 3,
400/// stamina: 1,
401/// };
402///
403/// #[bitfield(u16)]
404/// struct GameStatus {
405/// /// ❌ No compile time default value size checks for const variables.
406/// #[bits(8, default = DEFAULT_PLAYER_STATE)]
407/// player_state: PlayerState,
408///
409/// /// ❌ No compile time default value size checks for enum types.
410/// #[bits(8, default = GameState::Playing)]
411/// game_state: GameState
412/// }
413///
414/// /// A struct can be a custom type, but must implement the `from_bits`
415/// /// and `into_bits` const functions to convert to and from bits.
416/// #[derive(Debug, PartialEq)]
417/// struct PlayerState {
418/// health: u8,
419/// mana: u8,
420/// stamina: u8,
421/// }
422///
423/// impl PlayerState {
424/// /// The from_bits takes in the bits of the field and converts
425/// /// it into the custom type.
426/// const fn from_bits(bits: u8) -> Self {
427/// Self {
428/// health: bits & 0b0000_1111, // First 4 bits for health
429/// mana: (bits >> 4) & 0b0000_0011, // Next 2 bits for mana
430/// stamina: (bits >> 6) & 0b0000_0001, // Last bit for stamina
431/// }
432/// }
433///
434/// /// The into_bits converts the custom type into a packed bits
435/// /// representation. The only requirement is that the return type
436/// /// is a primitive type.
437/// const fn into_bits(self) -> u8 {
438/// (self.health & 0b0000_1111) |
439/// ((self.mana & 0b0000_0011) << 4) |
440/// ((self.stamina & 0b0000_0001) << 6)
441/// }
442/// }
443///
444/// /// Enums can also be custom types as long as they implement the
445/// /// `from_bits` and `into_bits` const functions.
446/// ///
447/// /// Instead of writing custom enum types by hand, you can also
448/// /// use the `#[bitflag]` attribute to generate these functions
449/// /// for you.
450/// #[derive(Debug, PartialEq)]
451/// enum GameState {
452/// Playing = 0,
453/// Paused = 1,
454/// GameOver = 2,
455/// }
456///
457/// impl GameState {
458/// /// The from_bits takes in the bits of the field and converts
459/// /// it into the custom type.
460/// const fn from_bits(bits: u8) -> Self {
461/// match bits {
462/// 0 => Self::Playing,
463/// 1 => Self::Paused,
464/// 2 => Self::GameOver,
465/// _ => unreachable!(),
466/// }
467/// }
468///
469/// /// The into_bits converts the custom type into a packed bits'
470/// /// representation. The only requirement is that the return
471/// /// type is a primitive type.
472/// const fn into_bits(self) -> u8 {
473/// self as u8
474/// }
475/// }
476///
477/// /// Bitflags are enums but the `from_bits` and `into_bits` functions
478/// /// are generated for you. The only requirement is that one of the
479/// /// variants must be annotated with `#[base]` which represents the
480/// /// base value of the bitflag.
481/// #[bitflag(u8)]
482/// #[derive(Debug, PartialEq)]
483/// enum GameStateBitflag {
484/// #[base]
485/// Playing = 0,
486/// Paused = 1,
487/// GameOver = 2,
488/// }
489///
490/// /// The code that's generated for the `GameStateBitflag` by the
491/// /// `#[bitflag]` attribute saving you the trouble of writing
492/// /// the `from_bits` and `into_bits` functions yourself.
493/// // impl GameState {
494/// // const fn from_bits(bits: u8) -> Self {
495/// // match bits {
496/// // 0 => Self::Playing,
497/// // 1 => Self::Paused,
498/// // 2 => Self::GameOver,
499/// // _ => unreachable!(),
500/// // }
501/// // }
502/// //
503/// // const fn into_bits(self) -> u8 {
504/// // self as u8
505/// // }
506/// // }
507///
508/// fn main() {
509/// let game_status = GameStatus::new();
510/// assert_eq!(game_status.player_state(), DEFAULT_PLAYER_STATE);
511/// assert_eq!(game_status.player_state().health, 15);
512/// assert_eq!(game_status.player_state().mana, 3);
513/// assert_eq!(game_status.player_state().stamina, 1);
514/// assert_eq!(game_status.game_state(), GameState::Playing);
515/// }
516/// ```
517///
518/// #### Nested Bitfields
519///
520/// Bitfields can be nested within other bitfields, but the bits of the nested
521/// bitfield must be specified since the macro has no way of knowing how many bits
522/// the nested bitfield occupies.
523///
524/// ```rust
525/// # use bitfields_impl as bitfields;
526/// use bitfields::bitfield;
527///
528/// #[bitfield(u32)]
529/// struct GameWorld {
530/// /// ❌ No compile time default value size checks for const functions.
531/// #[bits(32, default = GameMap::new())]
532/// game_map: GameMap,
533/// }
534///
535/// #[bitfield(u32)]
536/// struct GameMap {
537/// #[bits(default = 0x11)]
538/// num_trees: u8,
539/// #[bits(default = 0x22)]
540/// num_players: u8,
541/// #[bits(default = 0x33)]
542/// num_monsters: u8,
543/// #[bits(default = 0x44)]
544/// num_items: u8,
545/// }
546///
547/// fn main() {
548/// let game_world = GameWorld::new();
549/// assert_eq!(game_world.game_map().num_items(), 0x44);
550/// assert_eq!(game_world.game_map().num_monsters(), 0x33);
551/// assert_eq!(game_world.game_map().num_players(), 0x22);
552/// assert_eq!(game_world.game_map().num_trees(), 0x11);
553/// assert_eq!(game_world.into_bits(), 0x44332211);
554/// }
555/// ```
556///
557/// #### Reserved Fields
558///
559/// Fields prefixed with an underscore `_` are reserved fields, which are
560/// inaccessible. Meaning the field is always 0, false, or a default value.
561/// They are useful for reserving the bits of the bitfield, padding fields,
562/// or for values that are always constant.
563///
564/// If you don't want to give the reserved fields a name, you can use
565/// `__` as the name for all reserved fields.
566///
567/// ```rust
568/// # use bitfields_impl as bitfields;
569/// use bitfields::bitfield;
570///
571/// #[bitfield(u16)]
572/// struct Bitfield {
573/// a: u8,
574///
575/// /// Fills the remaining bits of the u16.
576/// #[bits(default = 0xFF)]
577/// _reserved: u8,
578/// }
579///
580/// #[bitfield(u16)]
581/// struct ReservedBitfield {
582/// a: u8,
583///
584/// /// Fills the middle bits of the u16.
585/// #[bits(4, default = 0xF)]
586/// __: u8,
587///
588/// /// Fils the end bits of the u16.
589/// #[bits(4, default = 0xF)]
590/// __: u8,
591/// }
592///
593/// fn main() {
594/// let bitfield = Bitfield::new();
595/// assert_eq!(bitfield.a(), 0);
596/// // assert_eq!(bitfield._reserved(), 0xFF00); // Compile error, reserved inaccessible.
597/// // bitfield.set__reserved(0xFF); // Compile error, reserved fields are inaccessible.
598/// assert_eq!(bitfield.into_bits(), 0xFF00); // All fields exposed when converted
599/// // to bits.
600///
601/// let reserved_bitfield = ReservedBitfield::new();
602/// assert_eq!(reserved_bitfield.a(), 0);
603/// // assert_eq!(reserved_bitfield.__(), 0xFF0); // Compile error, reserved inaccessible.
604/// // reserved_bitfield.set__(0xFF); // Compile error, reserved fields are inaccessible.
605/// assert_eq!(reserved_bitfield.into_bits(), 0xFF00); // All fields exposed when
606/// // converted to bits.
607/// }
608/// ```
609///
610/// <!-- rust-bitflags-docs-start -->
611///
612/// ### Bitflags
613///
614/// There are times when you just want to define a bitflag, which are just enums
615/// that map to bits. Instead of defining a custom type, you can take advantage of
616/// the `#[bitflag]` attribute which generates `from_bits` and `into_bits` for enums
617/// automatically.
618///
619/// Bitflags only supports unsigned types (`u8`, `u16`, `u32`, `u64`, `u128`) and
620/// the one of the variants must be annotated with `#[base]` or `#[default]` which represents the
621/// base value of the bitflag. If `#[base]` and `#[default]` are both present, `#[base]` takes precedence.
622///
623/// ```rust
624/// # use bitfields_impl as bitfields;
625/// use bitfields::bitfield;
626/// use bitfields::bitflag;
627///
628/// /// Annotate an enum with the `#[bitflag]` attribute to automatically generate
629/// /// the `from_bits` and `into_bits` functions for you! One variant must be annotated
630/// /// with `#[base]` which represents the base value of the bitflag.
631/// #[bitflag(u8)]
632/// #[derive(Debug, PartialEq)]
633/// enum RenderMode {
634/// #[base]
635/// Normal = 0,
636/// Mirror = 1,
637/// Flip = 2,
638/// // #[default] - Default can be specified but base takes
639/// // precedence if both are present.
640/// Hidden = 3,
641/// }
642///
643/// /// The code that's generated for the `RenderMode` by the
644/// /// `#[bitflag]` attribute saving you the trouble of writing
645/// /// the `from_bits` and `into_bits` functions yourself.
646/// // impl RenderMode {
647/// // const fn from_bits(bits: u8) -> Self {
648/// // match bits {
649/// // 0 => Self::Normal,
650/// // 1 => Self::Mirror,
651/// // 2 => Self::Flip,
652/// // 3 => Self::Hidden,
653/// // _ => unreachable!(),
654/// // }
655/// // }
656/// //
657/// // const fn into_bits(self) -> u8 {
658/// // self as u8
659/// // }
660/// // }
661///
662/// /// Annotate an enum with the `#[bitflag]` attribute to automatically generate
663/// /// the `from_bits` and `into_bits` functions for you! One variant must be annotated
664/// /// with `#[base]` which represents the base value of the bitflag.
665/// #[bitflag(u8)]
666/// #[derive(Debug, PartialEq)]
667/// enum AudioMode {
668/// #[base]
669/// Stereo = 0,
670/// Mono = 1,
671/// Mute = 2,
672/// Surround = 3,
673/// }
674///
675/// #[bitfield(u8)]
676/// struct DisplayControl {
677/// /// Must have the `#[bits]` attribute since the macro has
678/// /// no way of knowing how many bits the custom type occupies.
679/// #[bits(4, default = RenderMode::Normal)]
680/// render_mode: RenderMode,
681/// /// Must have the `#[bits]` attribute since the macro has
682/// /// no way of knowing how many bits the custom type occupies.
683/// #[bits(4, default = AudioMode::Stereo)]
684/// audio_mode: AudioMode,
685/// }
686///
687/// fn main() {
688/// let display = DisplayControlBuilder::new()
689/// .with_render_mode(RenderMode::Mirror)
690/// .with_audio_mode(AudioMode::Mute)
691/// .build();
692///
693/// assert_eq!(display.render_mode(), RenderMode::Mirror);
694/// assert_eq!(display.audio_mode(), AudioMode::Mute);
695/// }
696/// ```
697///
698/// #### Bitflag Configuration
699///
700/// Bitflags can be configured with arguments passed to the `#[bitflag(...)]` attribute (the first argument is always the backing unsigned integer type):
701///
702/// | Argument | Values | Default | Description |
703/// |------------------|-----------------------------------|----------|------------------------------------------------------------------------------------------------------|
704/// | `<backing type>` | `u8`, `u16`, `u32`, `u64`, `u128` | Required | The storage used by the generated bitflag. Primitive backing types support bitfields up to 128 bits. |
705/// | `from_endian` | `big`, `little` | `big` | Default endianness used by the generated `from_bits` function. |
706/// | `into_endian` | `big`, `little` | `big` | Default endianness used by the generated `into_bits` function. |
707/// | `copy` | `true`, `false` | `true` | Determines whether to derive `Copy` and `Clone` automatically for the enum. |
708///
709/// <!-- rust-bitflags-docs-end -->
710///
711/// ### Field Constants
712///
713/// Fields with read or write access have constants generated for their number of
714/// bits and offset in the bitfield.
715///
716/// ```rust
717/// # use bitfields_impl as bitfields;
718/// use bitfields::bitfield;
719///
720/// #[bitfield(u32)]
721/// struct Bitfield {
722/// #[bits(default = 0x12)]
723/// a: u8,
724/// #[bits(default = 0x34)]
725/// b: u8,
726/// #[bits(default = 0x56)]
727/// c: u8,
728/// #[bits(default = 0x78)]
729/// d: u8,
730/// }
731///
732/// fn main() {
733/// assert_eq!(Bitfield::A_BITS, 8); // Number of bits of the a field.
734/// assert_eq!(Bitfield::A_OFFSET, 0); // The offset of the a field in the bitfield.
735/// assert_eq!(Bitfield::B_BITS, 8); // Number of bits of the b field.
736/// assert_eq!(Bitfield::B_OFFSET, 8); // The offset of the b field in the bitfield.
737/// assert_eq!(Bitfield::C_BITS, 8); // Number of bits of the c field.
738/// assert_eq!(Bitfield::C_OFFSET, 16); // The offset of the c field in the bitfield.
739/// assert_eq!(Bitfield::D_BITS, 8); // Number of bits of the d field.
740/// assert_eq!(Bitfield::D_OFFSET, 24); // The offset of the d field in the bitfield.
741/// }
742/// ```
743///
744/// ### Field Order
745///
746/// The order of the bitfield determines whether from top to bottom struct fields
747/// are ordered from the least significant bit (lsb) to the most significant bit (
748/// msb). By default, fields are ordered from the least significant bit (lsb) to the
749/// most significant bit (msb).
750///
751/// The order can be changed by specifying the `#[bitfield(order = N)]` arg on the
752/// bitfield struct, with the options `lsb` or `msb`.
753///
754/// ```rust
755/// # use bitfields_impl as bitfields;
756/// use bitfields::bitfield;
757///
758/// /// Field layout (LSB → MSB):
759/// ///
760/// /// | 31 24 | 23 16 | 15 8 | 7 0 |
761/// /// +----------+---------+-------------+-----------+
762/// /// | checksum | reading | status_code | sensor_id |
763/// /// +----------+---------+-------------+-----------+
764/// ///
765/// /// Field mapping:
766/// /// - sensor_id: bits 7..=0
767/// /// - status_code: bits 15..=8
768/// /// - reading: bits 23..=16
769/// /// - checksum: bits 31..=24
770/// #[bitfield(u32)] // LSB by default.
771/// struct TelemetryFrameLsb {
772/// #[bits(default = 0x12)] /// sensor_id occupies bits 7..=0 (LSB).
773/// sensor_id: u8,
774/// #[bits(default = 0x34)] /// status_code occupies bits 15..=8.
775/// status_code: u8,
776/// #[bits(default = 0x56)] /// reading occupies bits 23..=16.
777/// reading: u8,
778/// #[bits(default = 0x78)] /// checksum occupies bits 31..=24 (MSB).
779/// checksum: u8,
780/// }
781///
782/// /// Bit layout (MSB → LSB):
783/// ///
784/// /// | 31 24 | 23 16 | 15 8 | 7 0 |
785/// /// +----------+---------------+-----------+------------+
786/// /// | sensor_id| status_code | reading | checksum |
787/// /// +----------+---------------+-----------+------------+
788/// ///
789/// /// Field mapping:
790/// /// - sensor_id: bits 31..=24
791/// /// - status_code: bits 23..=16
792/// /// - reading: bits 15..=8
793/// /// - checksum: bits 7..=0
794/// #[bitfield(u32, order = msb)]
795/// struct TelemetryFrameMsb {
796/// #[bits(default = 0x12)]
797/// sensor_id: u8,
798/// #[bits(default = 0x34)]
799/// status_code: u8,
800/// #[bits(default = 0x56)]
801/// reading: u8,
802/// #[bits(default = 0x78)]
803/// checksum: u8,
804/// }
805///
806/// fn main() {
807/// let frame_lsb = TelemetryFrameLsb::new();
808/// assert_eq!(frame_lsb.sensor_id(), 0x12);
809/// assert_eq!(frame_lsb.status_code(), 0x34);
810/// assert_eq!(frame_lsb.reading(), 0x56);
811/// assert_eq!(frame_lsb.checksum(), 0x78);
812/// let val = frame_lsb.into_bits();
813///
814/// // .- checksum
815/// // | .- reading
816/// // | | .- status_code
817/// // | | | .- sensor_id
818/// assert_eq!(val, 0x78_56_34_12);
819/// assert_eq!(TelemetryFrameLsb::SENSOR_ID_OFFSET, 0); // Offset in LSB order.
820///
821/// let frame_msb = TelemetryFrameMsb::new();
822/// assert_eq!(frame_msb.sensor_id(), 0x12);
823/// assert_eq!(frame_msb.status_code(), 0x34);
824/// assert_eq!(frame_msb.reading(), 0x56);
825/// assert_eq!(frame_msb.checksum(), 0x78);
826/// let val = frame_msb.into_bits();
827///
828/// // .- sensor_id
829/// // | .- status_code
830/// // | | .- reading
831/// // | | | .- checksum
832/// assert_eq!(val, 0x12_34_56_78);
833/// assert_eq!(TelemetryFrameMsb::SENSOR_ID_OFFSET, 24); // Offset in MSB order.
834/// }
835/// ```
836///
837/// ### Bitfield Conversions
838///
839/// A bitfield can be converted into and from bits using multiple functions.
840///
841/// #### From Bits
842///
843/// A bitfield can be converted from bits using the following from APIs:
844///
845/// **Primitive Bitfield**:
846///
847/// | Method | Endianness | Description |
848/// |---------------------------------------|----------------------------------------------|--------------------------------------------------------------------------------------------------------------|
849/// | `from_bits(bits: N)` | Determined by `#[bitfield(from_endian = N)]` | Creates a new bitfield instance from the given raw bits, ignoring field defaults. (Default is `big`). |
850/// | `from_bits_with_defaults(bits: N)` | Determined by `#[bitfield(from_endian = N)]` | Creates a new bitfield instance from the given raw bits, while respecting/applying field defaults. |
851/// | `from_le_bits(bits: N)` | Little-endian | Creates a new bitfield instance from the given little-endian bits, ignoring field defaults. |
852/// | `from_le_bits_with_defaults(bits: N)` | Little-endian | Creates a new bitfield instance from the given little-endian bits, while respecting/applying field defaults. |
853/// | `from_be_bits(bits: N)` | Big-endian | Creates a new bitfield instance from the given big-endian bits, ignoring field defaults. |
854/// | `from_be_bits_with_defaults(bits: N)` | Big-endian | Creates a new bitfield instance from the given big-endian bits, while respecting/applying field defaults. |
855///
856/// ```rust
857/// # use bitfields_impl as bitfields;
858/// use bitfields::bitfield;
859///
860/// #[bitfield(u32)]
861/// struct Bitfield {
862/// #[bits(default = 0x12)]
863/// a: u8,
864/// #[bits(default = 0x34)]
865/// b: u8,
866/// #[bits(default = 0x56)]
867/// c: u8,
868/// #[bits(default = 0x78)]
869/// _reserved: u8,
870/// }
871///
872/// fn main() {
873/// // from_bits - Creates a bitfield from raw bits, ignoring defaults.
874/// // Default endian is big.
875/// let from_bits = Bitfield::from_bits(0x11_22_33_44);
876/// assert_eq!(from_bits.a(), 0x44);
877/// assert_eq!(from_bits.b(), 0x33);
878/// assert_eq!(from_bits.c(), 0x22);
879/// assert_eq!(from_bits.into_bits(), 0x11223344);
880///
881/// // from_bits_with_defaults - Creates a bitfield from raw bits, respecting
882/// // default values. Fields with defaults are set to their default values.
883/// let from_bits_with_defaults = Bitfield::from_bits_with_defaults(0x11_22_33_44);
884/// assert_eq!(from_bits_with_defaults.a(), 0x12);
885/// assert_eq!(from_bits_with_defaults.b(), 0x34);
886/// assert_eq!(from_bits_with_defaults.c(), 0x56);
887/// assert_eq!(from_bits_with_defaults.into_bits(), 0x78563412);
888///
889/// // from_le_bits - Creates a bitfield from bits assumed to be in
890/// // little-endian order, ignoring defaults.
891/// let from_le_bits = Bitfield::from_le_bits(0x11_22_33_44);
892/// assert_eq!(from_le_bits.into_bits(), 0x44_33_22_11);
893///
894/// // from_le_bits_with_defaults - Creates a bitfield from bits assumed to be
895/// // in little-endian order, respecting default values.
896/// let from_le_bits_with_defaults = Bitfield::from_le_bits_with_defaults(0x11_22_33_44);
897/// assert_eq!(
898/// from_le_bits_with_defaults.into_bits(),
899/// 0x78_56_34_12
900/// );
901///
902/// // from_be_bits - Creates a bitfield from bits assumed to be in
903/// // big-endian order, ignoring defaults.
904/// let from_be_bits = Bitfield::from_be_bits(0x11_22_33_44);
905/// assert_eq!(from_be_bits.into_bits(), 0x11_22_33_44);
906///
907/// // from_be_bits_with_defaults - Creates a bitfield from bits assumed to be
908/// // in big-endian order, respecting default values.
909/// let from_be_bits_with_defaults = Bitfield::from_be_bits_with_defaults(0x11_22_33_44);
910/// assert_eq!(
911/// from_be_bits_with_defaults.into_bits(),
912/// 0x78_56_34_12,
913/// );
914/// }
915/// ```
916///
917/// **Array Backed Bitfield**:
918///
919/// | Method | Endianness | Description |
920/// |---------------------------------------------------------------------------|----------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------|
921/// | `from_bytes(bytes: [u8; N])` | Determined by `#[bitfield(from_endian = N)]` | Creates a new bitfield instance from the given bytes, ignoring field defaults. (Default is `big`). |
922/// | `from_bytes_with_defaults(bytes: [u8; N])` | Determined by `#[bitfield(from_endian = N)]` | Creates a new bitfield instance from the given bytes, while respecting/applying field defaults. |
923/// | `from_le_bytes(bytes: [u8; N])` | Little-endian | Creates a new bitfield instance from the given little-endian bytes, ignoring field defaults. |
924/// | `from_le_bytes_with_defaults(bytes: [u8; N])` | Little-endian | Creates a new bitfield instance from the given little-endian bytes, while respecting/applying field defaults. |
925/// | `from_be_bytes(bytes: [u8; N])` | Big-endian | Creates a new bitfield instance from the given big-endian bytes, ignoring field defaults. |
926/// | `from_be_bytes_with_defaults(bytes: [u8; N])` | Big-endian | Creates a new bitfield instance from the given big-endian bytes, while respecting/applying field defaults. |
927/// | `from_slice(slice: &[u8])` | Determined by `#[bitfield(from_endian = N)]` | Creates a new bitfield instance from a byte slice. Shorter slices are padded with zero. |
928/// | `from_slice_with_defaults(slice: &[u8])` | Determined by `#[bitfield(from_endian = N)]` | Creates a new bitfield instance from a byte slice, while respecting/applying field defaults. Shorter slices are padded with zero. |
929/// | `checked_from_slice(slice: &[u8]) -> Result<Self, &str>` | Determined by `#[bitfield(from_endian = N)]` | Creates a new bitfield instance from a byte slice. Returns an error if the slice is too small to fill the bitfield. |
930/// | `checked_from_slice_with_defaults(slice: &[u8]) -> Result<Self, &str>` | Determined by `#[bitfield(from_endian = N)]` | Creates a new bitfield instance from a byte slice, while respecting/applying field defaults. Returns an error if the slice is too small. |
931/// | `from_le_slice(slice: &[u8])` | Little-endian | Creates a new bitfield instance from a little-endian byte slice. Shorter slices are padded with zero. |
932/// | `from_le_slice_with_defaults(slice: &[u8])` | Little-endian | Creates a new bitfield instance from a little-endian byte slice, while respecting/applying field defaults. Shorter slices are padded with zero. |
933/// | `checked_from_le_slice(slice: &[u8]) -> Result<Self, &str>` | Little-endian | Creates a new bitfield instance from a little-endian byte slice. Returns an error if the slice is too small to fill the bitfield. |
934/// | `checked_from_le_slice_with_defaults(slice: &[u8]) -> Result<Self, &str>` | Little-endian | Creates a new bitfield instance from a little-endian byte slice, while respecting/applying field defaults. Returns an error if the slice is too small. |
935/// | `from_be_slice(slice: &[u8])` | Big-endian | Creates a new bitfield instance from a big-endian byte slice. Shorter slices are padded with zero. |
936/// | `from_be_slice_with_defaults(slice: &[u8])` | Big-endian | Creates a new bitfield instance from a big-endian byte slice, while respecting/applying field defaults. Shorter slices are padded with zero. |
937/// | `checked_from_be_slice(slice: &[u8]) -> Result<Self, &str>` | Big-endian | Creates a new bitfield instance from a big-endian byte slice. Returns an error if the slice is too small to fill the bitfield. |
938/// | `checked_from_be_slice_with_defaults(slice: &[u8]) -> Result<Self, &str>` | Big-endian | Creates a new bitfield instance from a big-endian byte slice, while respecting/applying field defaults. Returns an error if the slice is too small. |
939///
940/// ```rust
941/// # use bitfields_impl as bitfields;
942/// use bitfields::bitfield;
943///
944/// #[bitfield([u8; 4])]
945/// struct Packet {
946/// #[bits(default = 0x12)]
947/// a: u8,
948/// #[bits(default = 0x34)]
949/// b: u8,
950/// #[bits(default = 0x56)]
951/// c: u8,
952/// #[bits(default = 0x78)]
953/// _reserved: u8,
954/// }
955///
956/// fn main() {
957/// // from_bytes — default endian is big, ignoring field defaults.
958/// // In big-endian layout the last byte maps to the lowest bits (field `a`).
959/// let p = Packet::from_bytes([0x11, 0x22, 0x33, 0x44]);
960/// assert_eq!(p.a(), 0x44);
961/// assert_eq!(p.b(), 0x33);
962/// assert_eq!(p.c(), 0x22);
963/// assert_eq!(p.into_bytes(), [0x11, 0x22, 0x33, 0x44]);
964///
965/// // from_bytes_with_defaults — fields that have defaults keep their defaults.
966/// let p_defaults = Packet::from_bytes_with_defaults([0x11, 0x22, 0x33, 0x44]);
967/// assert_eq!(p_defaults.a(), 0x12);
968/// assert_eq!(p_defaults.b(), 0x34);
969/// assert_eq!(p_defaults.c(), 0x56);
970///
971/// // from_le_bytes — treats the byte array as little-endian.
972/// let p_le = Packet::from_le_bytes([0x44, 0x33, 0x22, 0x11]);
973/// assert_eq!(p_le.a(), 0x44);
974/// assert_eq!(p_le.b(), 0x33);
975/// assert_eq!(p_le.c(), 0x22);
976///
977/// // from_be_bytes — treats the byte array as big-endian (same as from_bytes default).
978/// let p_be = Packet::from_be_bytes([0x11, 0x22, 0x33, 0x44]);
979/// assert_eq!(p_be.a(), 0x44);
980///
981/// // from_slice — shorter slices are zero-padded; same endian rules as from_bytes.
982/// let p_slice = Packet::from_slice(&[0x11, 0x22, 0x33, 0x44]);
983/// assert_eq!(p_slice.a(), 0x44);
984///
985/// // checked_from_slice — returns an error when the slice is too small.
986/// assert!(Packet::checked_from_slice(&[0x11, 0x22]).is_err());
987/// assert!(Packet::checked_from_slice(&[0x11, 0x22, 0x33, 0x44]).is_ok());
988/// }
989/// ```
990///
991/// #### Into Bits
992///
993/// A bitfield can be converted into bits using the following APIs:
994///
995/// **Primitive Bitfield**:
996///
997/// | Method | Endianness | Description |
998/// |-----------------------|----------------------------------------------|------------------------------------------------------------------------|
999/// | `into_bits() -> N` | Determined by `#[bitfield(into_endian = N)]` | Returns the raw bits of the bitfield (default `into_endian` is `big`). |
1000/// | `into_le_bits() -> N` | Little-endian | Returns the bits of the bitfield in little-endian order. |
1001/// | `into_be_bits() -> N` | Big-endian | Returns the bits of the bitfield in big-endian order. |
1002///
1003/// ```rust
1004/// # use bitfields_impl as bitfields;
1005/// use bitfields::bitfield;
1006///
1007/// #[bitfield(u32)]
1008/// struct Bitfield {
1009/// #[bits(default = 0x12)]
1010/// a: u8,
1011/// #[bits(default = 0x34)]
1012/// b: u8,
1013/// #[bits(default = 0x56)]
1014/// c: u8,
1015/// #[bits(default = 0x78)]
1016/// d: u8,
1017/// }
1018///
1019/// fn main() {
1020/// let bitfield = Bitfield::new();
1021///
1022/// // into_bits: default into_endian (big) — most-significant field at the top byte.
1023/// assert_eq!(bitfield.into_bits(), 0x78_56_34_12);
1024///
1025/// // into_le_bits: byte-swaps the raw bits into little-endian order.
1026/// assert_eq!(bitfield.into_le_bits(), 0x12_34_56_78);
1027///
1028/// // into_be_bits: big-endian order (same as into_bits when into_endian defaults to big).
1029/// assert_eq!(bitfield.into_be_bits(), 0x78_56_34_12);
1030/// }
1031/// ```
1032///
1033/// **Array Backed Bitfield**:
1034///
1035/// | Method | Endianness | Description |
1036/// |---------------------------------------------------------------|----------------------------------------------|-----------------------------------------------------------------------------------------------------------------------|
1037/// | `into_bytes() -> [u8; N]` | Determined by `#[bitfield(into_endian = N)]` | Returns the bytes of the bitfield as a `[u8; N]` array. Default is `big`. |
1038/// | `into_le_bytes() -> [u8; N]` | Little-endian | Returns the bytes of the bitfield in little-endian order. |
1039/// | `into_be_bytes() -> [u8; N]` | Big-endian | Returns the bytes of the bitfield in big-endian order. |
1040/// | `into_slice(slice: &mut [u8])` | Determined by `#[bitfield(into_endian = N)]` | Writes the bitfield bytes into the provided slice. If the slice is shorter, only the bytes that fit are written. |
1041/// | `checked_into_slice(slice: &mut [u8]) -> Result<(), &str>` | Determined by `#[bitfield(into_endian = N)]` | Writes the bitfield bytes into the provided slice. Returns an error if the slice is too small. |
1042/// | `into_le_slice(slice: &mut [u8])` | Little-endian | Writes the bitfield bytes in little-endian order into the provided slice. |
1043/// | `checked_into_le_slice(slice: &mut [u8]) -> Result<(), &str>` | Little-endian | Writes the bitfield bytes in little-endian order into the provided slice. Returns an error if the slice is too small. |
1044/// | `into_be_slice(slice: &mut [u8])` | Big-endian | Writes the bitfield bytes in big-endian order into the provided slice. |
1045/// | `checked_into_be_slice(slice: &mut [u8]) -> Result<(), &str>` | Big-endian | Writes the bitfield bytes in big-endian order into the provided slice. Returns an error if the slice is too small. |
1046///
1047/// ```rust
1048/// # use bitfields_impl as bitfields;
1049/// use bitfields::bitfield;
1050///
1051/// #[bitfield([u8; 4])]
1052/// struct Packet {
1053/// #[bits(default = 0x12)]
1054/// a: u8,
1055/// #[bits(default = 0x34)]
1056/// b: u8,
1057/// #[bits(default = 0x56)]
1058/// c: u8,
1059/// #[bits(default = 0x78)]
1060/// d: u8,
1061/// }
1062///
1063/// fn main() {
1064/// let packet = Packet::new();
1065///
1066/// // into_bytes: default into_endian (big) — most-significant byte first.
1067/// assert_eq!(packet.into_bytes(), [0x78, 0x56, 0x34, 0x12]);
1068///
1069/// // into_le_bytes: least-significant byte first.
1070/// assert_eq!(packet.into_le_bytes(), [0x12, 0x34, 0x56, 0x78]);
1071///
1072/// // into_be_bytes: most-significant byte first (same as default).
1073/// assert_eq!(packet.into_be_bytes(), [0x78, 0x56, 0x34, 0x12]);
1074///
1075/// // into_slice: writes up to slice.len() bytes.
1076/// let mut buf = [0u8; 4];
1077/// packet.into_slice(&mut buf);
1078/// assert_eq!(buf, [0x78, 0x56, 0x34, 0x12]);
1079///
1080/// // checked_into_slice: returns Err when the slice is too small.
1081/// let mut small = [0u8; 2];
1082/// assert!(packet.checked_into_slice(&mut small).is_err());
1083///
1084/// // into_le_slice / into_be_slice work the same but with explicit endian.
1085/// let mut le_buf = [0u8; 4];
1086/// packet.into_le_slice(&mut le_buf);
1087/// assert_eq!(le_buf, [0x12, 0x34, 0x56, 0x78]);
1088///
1089/// let mut be_buf = [0u8; 4];
1090/// packet.into_be_slice(&mut be_buf);
1091/// assert_eq!(be_buf, [0x78, 0x56, 0x34, 0x12]);
1092/// }
1093/// ```
1094///
1095/// #### Conversion Endian
1096///
1097/// Sometimes the outside world is outside our control, like the endianness of how
1098/// systems export data. Luckily, the endianness of the bitfield conversions can
1099/// be controlled by specifying the `#[bitfield(from_endian = N, into_endian = N)]`
1100/// args. The possible endianness options are `little` or `big`. By default, the endianness
1101/// of both is `big`.
1102///
1103/// This arg controls the endianness of the `from`, `into`, and `From` trait
1104/// conversions.
1105///
1106/// ```rust
1107/// # use bitfields_impl as bitfields;
1108/// use bitfields::bitfield;
1109///
1110/// #[bitfield(u32, from_endian = little, into_endian = big)]
1111/// struct Header {
1112/// version: u8,
1113/// flags: u8,
1114/// size: u8,
1115/// tag: u8,
1116/// }
1117///
1118/// fn main() {
1119/// // Device gave us bytes in little-endian order:
1120/// // [0x11, 0x22, 0x33, 0x44]
1121/// let h = Header::from_bits(0x1122_3344);
1122///
1123/// // from_endian = little means fields decode as:
1124/// assert_eq!(h.version(), 0x11);
1125/// assert_eq!(h.flags(), 0x22);
1126/// assert_eq!(h.size(), 0x33);
1127/// assert_eq!(h.tag(), 0x44);
1128///
1129/// // into_endian = big means output is big-endian representation.
1130/// assert_eq!(h.into_bits(), 0x4433_2211);
1131///
1132/// // Explicit conversion helpers still work:
1133/// let x = Header::from_le_bits(0xAABB_CCDD);
1134/// assert_eq!(x.version(), 0xAA);
1135/// assert_eq!(x.flags(), 0xBB);
1136/// assert_eq!(x.size(), 0xCC);
1137/// assert_eq!(x.tag(), 0xDD);
1138///
1139/// assert_eq!(x.into_be_bits(), 0xDDCC_BBAA);
1140/// assert_eq!(x.into_le_bits(), 0xAABB_CCDD);
1141/// }
1142/// ```
1143///
1144/// ```rust
1145/// # use bitfields_impl as bitfields;
1146/// use bitfields::bitfield;
1147///
1148/// #[bitfield([u8; 4], from_endian = little, into_endian = big)]
1149/// struct Header {
1150/// version: u8,
1151/// flags: u8,
1152/// size: u8,
1153/// tag: u8,
1154/// }
1155///
1156/// fn main() {
1157/// // Device gave us bytes in little-endian order:
1158/// // [0x11, 0x22, 0x33, 0x44]
1159/// let h = Header::from_bytes([0x11, 0x22, 0x33, 0x44]);
1160///
1161/// // from_endian = little means fields decode as:
1162/// assert_eq!(h.version(), 0x11);
1163/// assert_eq!(h.flags(), 0x22);
1164/// assert_eq!(h.size(), 0x33);
1165/// assert_eq!(h.tag(), 0x44);
1166///
1167/// // into_endian = big means output is big-endian representation.
1168/// assert_eq!(h.into_bytes(), [0x44, 0x33, 0x22, 0x11]);
1169///
1170/// // Explicit conversion helpers still work:
1171/// let x = Header::from_le_bytes([0xDD, 0xCC, 0xBB, 0xAA]);
1172/// assert_eq!(x.version(), 0xDD);
1173/// assert_eq!(x.flags(), 0xCC);
1174/// assert_eq!(x.size(), 0xBB);
1175/// assert_eq!(x.tag(), 0xAA);
1176///
1177/// assert_eq!(x.into_be_bytes(), [0xAA, 0xBB, 0xCC, 0xDD]);
1178/// assert_eq!(x.into_le_bytes(), [0xDD, 0xCC, 0xBB, 0xAA]);
1179/// }
1180/// ```
1181///
1182/// ### Bit Operations
1183///
1184/// The bitfield generates bitwise operations that make it easy to manipulate,
1185/// read, reset, and invert the backing bits without manually writing masks and
1186/// shifts.
1187///
1188/// #### Write Bits
1189///
1190/// Write bits allows you to write data to the writable bits of
1191/// the bitfield.
1192///
1193/// **Primitive Bitfield**:
1194///
1195/// | Function | Endianness | Description |
1196/// |----------------------------------------|-----------------------------------------------|----------------------------------------------------------------|
1197/// | `write_bits(bits: N)` | Determined by `#[bitfield(write_endian = N)]` | Writes raw bits using `write_endian` (default is `big`). |
1198/// | `write_bits_with_defaults(bits: N)` | Determined by `#[bitfield(write_endian = N)]` | Writes raw bits, then reapplies defaults. |
1199/// | `write_le_bits(bits: N)` | Little-endian | Writes explicitly little-endian bits. |
1200/// | `write_le_bits_with_defaults(bits: N)` | Little-endian | Writes explicitly little-endian bits, then reapplies defaults. |
1201/// | `write_be_bits(bits: N)` | Big-endian | Writes explicitly big-endian bits. |
1202/// | `write_be_bits_with_defaults(bits: N)` | Big-endian | Writes explicitly big-endian bits, then reapplies defaults. |
1203/// | `write_defaults()` | N/A | Reapplies field defaults without replacing the whole bitfield. |
1204///
1205/// ```rust
1206/// # use bitfields_impl as bitfields;
1207/// use bitfields::bitfield;
1208///
1209/// #[bitfield(u32)]
1210/// struct Register {
1211/// #[bits(default = 0x12)]
1212/// low: u8,
1213/// data: u8,
1214/// #[bits(default = 0x78)]
1215/// _reserved: u8,
1216/// high: u8,
1217/// }
1218///
1219/// fn main() {
1220/// let mut reg = Register::new();
1221/// assert_eq!(reg.into_bits(), 0x00780012);
1222///
1223/// // write_bits — replaces all writable bits; reserved/read-only fields are preserved.
1224/// reg.write_bits(0xAA_BB_CC_DD);
1225/// assert_eq!(reg.low(), 0xDD);
1226/// assert_eq!(reg.data(), 0xCC);
1227/// assert_eq!(reg.high(), 0xAA);
1228/// // layout: high=0xAA | _reserved=0x78 | data=0xCC | low=0xDD
1229/// assert_eq!(reg.into_bits(), 0xAA78CCDD);
1230///
1231/// // write_bits_with_defaults — writes the new bits then reapplies field defaults.
1232/// reg.write_bits_with_defaults(0xAA_BB_CC_DD);
1233/// assert_eq!(reg.low(), 0x12); // default restored
1234/// assert_eq!(reg.data(), 0xCC); // no default, comes from the written value
1235/// // layout: high=0xAA | _reserved=0x78 | data=0xCC | low=0x12
1236/// assert_eq!(reg.into_bits(), 0xAA78CC12);
1237///
1238/// // write_le_bits — writes bits interpreted as little-endian.
1239/// reg.write_le_bits(0x11_22_33_44);
1240/// assert_eq!(reg.low(), 0x11);
1241/// assert_eq!(reg.data(), 0x22);
1242/// assert_eq!(reg.high(), 0x44);
1243///
1244/// // write_defaults — reapplies only field defaults without overwriting other fields.
1245/// reg.write_defaults();
1246/// assert_eq!(reg.low(), 0x12);
1247/// }
1248/// ```
1249///
1250/// **Array Backed Bitfield**:
1251///
1252/// | Function | Endianness | Description |
1253/// |------------------------------------------------|-----------------------------------------------|-----------------------------------------------------------------|
1254/// | `write_bytes(bytes: [u8; N])` | Determined by `#[bitfield(write_endian = N)]` | Writes raw bytes using `write_endian` (default is `big`). |
1255/// | `write_bytes_with_defaults(bytes: [u8; N])` | Determined by `#[bitfield(write_endian = N)]` | Writes raw bytes, then reapplies defaults. |
1256/// | `write_le_bytes(bytes: [u8; N])` | Little-endian | Writes explicitly little-endian bytes. |
1257/// | `write_le_bytes_with_defaults(bytes: [u8; N])` | Little-endian | Writes explicitly little-endian bytes, then reapplies defaults. |
1258/// | `write_be_bytes(bytes: [u8; N])` | Big-endian | Writes explicitly big-endian bytes. |
1259/// | `write_be_bytes_with_defaults(bytes: [u8; N])` | Big-endian | Writes explicitly big-endian bytes, then reapplies defaults. |
1260/// | `write_defaults()` | N/A | Reapplies field defaults without replacing the whole bitfield. |
1261///
1262/// ```rust
1263/// # use bitfields_impl as bitfields;
1264/// use bitfields::bitfield;
1265///
1266/// #[bitfield(u32)]
1267/// struct Register {
1268/// #[bits(default = 0x12)]
1269/// low: u8,
1270/// #[bits(default = 0x34, access = ro)]
1271/// status: u8,
1272/// data: u8,
1273/// #[bits(default = 0x78)]
1274/// _reserved: u8,
1275/// }
1276///
1277/// fn main() {
1278/// let mut register = Register::new();
1279/// assert_eq!(register.into_bits(), 0x78003412);
1280///
1281/// register.write_bits(0x11223344);
1282///
1283/// // Writable fields are updated from the incoming bits.
1284/// assert_eq!(register.low(), 0x44);
1285/// assert_eq!(register.data(), 0x22);
1286///
1287/// // Read-only and reserved fields keep their original/default values.
1288/// assert_eq!(register.status(), 0x34);
1289/// assert_eq!(register.into_bits(), 0x78223444);
1290///
1291/// // `write_bits_with_defaults` writes first, then restores fields that have
1292/// // defaults. `low`, `status`, and `_reserved` all keep their defaults.
1293/// register.write_bits_with_defaults(0xAABBCCDD);
1294/// assert_eq!(register.low(), 0x12);
1295/// assert_eq!(register.status(), 0x34);
1296/// assert_eq!(register.data(), 0xBB);
1297/// assert_eq!(register.into_bits(), 0x78BB3412);
1298/// }
1299/// ```
1300///
1301/// Use `write_endian` to configure the default endian used by `write_bits` or
1302/// `write_bytes`. The explicit helpers always use the endian in their name.
1303///
1304/// ```rust
1305/// # use bitfields_impl as bitfields;
1306/// use bitfields::bitfield;
1307///
1308/// #[bitfield(u32, write_endian = little)]
1309/// struct Header {
1310/// version: u8,
1311/// flags: u8,
1312/// size: u8,
1313/// tag: u8,
1314/// }
1315///
1316/// fn main() {
1317/// let mut header = Header::new();
1318///
1319/// // `write_endian = little` makes `write_bits` interpret the input as
1320/// // little-endian. This is equivalent to calling `write_le_bits`.
1321/// header.write_bits(0x1122_3344);
1322/// assert_eq!(header.version(), 0x11);
1323/// assert_eq!(header.flags(), 0x22);
1324/// assert_eq!(header.size(), 0x33);
1325/// assert_eq!(header.tag(), 0x44);
1326///
1327/// // Explicit endian helpers ignore the configured default.
1328/// header.write_be_bits(0xAABB_CCDD);
1329/// assert_eq!(header.version(), 0xDD);
1330/// assert_eq!(header.flags(), 0xCC);
1331/// assert_eq!(header.size(), 0xBB);
1332/// assert_eq!(header.tag(), 0xAA);
1333/// }
1334/// ```
1335///
1336/// #### Get/Set Bits
1337///
1338/// Single-bit helpers let you read or write one bit at a time. These helpers behave
1339/// the same for both primitive and array-backed bitfields.
1340///
1341/// **Primitive & Array Backed Bitfields**:
1342///
1343/// | Function | Checked / Unchecked | Description |
1344/// |---------------------------------------------------------------|---------------------|-------------------------------------------------------------------------------------------------------------------|
1345/// | `get_bit(offset: u32) -> bool` | Unchecked | Reads a single bit at the given offset. Returns false if offset is out of bounds or field is inaccessible. |
1346/// | `checked_get_bit(offset: u32) -> Result<bool, &str>` | Checked | Reads a single bit at the given offset. Returns an error if the offset is out of bounds or field is inaccessible. |
1347/// | `set_bit(offset: u32, bit: bool)` | Unchecked | Writes a single bit at the given offset. No-op if offset is out of bounds or field is protected. |
1348/// | `checked_set_bit(offset: u32, bit: bool) -> Result<(), &str>` | Checked | Writes a single bit at the given offset. Returns an error if the offset is out of bounds or field is protected. |
1349///
1350/// Unchecked helpers are convenient for quick probing. Checked helpers are better
1351/// when invalid offsets or inaccessible fields should be treated as errors.
1352///
1353/// ```rust
1354/// # use bitfields_impl as bitfields;
1355/// use bitfields::bitfield;
1356///
1357/// #[bitfield(u8, bit_ops = true)]
1358/// struct Control {
1359/// #[bits(2, default = 0b11)]
1360/// mode: u8,
1361///
1362/// #[bits(2)]
1363/// flags: u8,
1364///
1365/// #[bits(2, default = 0b10, access = wo)]
1366/// command: u8,
1367///
1368/// #[bits(2, default = 0b01)]
1369/// _reserved: u8,
1370/// }
1371///
1372/// fn main() {
1373/// let mut control = Control::new();
1374///
1375/// assert!(control.get_bit(Control::MODE_OFFSET));
1376/// assert!(control.get_bit(Control::MODE_OFFSET + 1));
1377/// assert!(!control.get_bit(Control::FLAGS_OFFSET));
1378///
1379/// // `command` is write-only, so unchecked reads return false and checked
1380/// // reads return an error.
1381/// assert!(!control.get_bit(Control::COMMAND_OFFSET));
1382/// assert!(control.checked_get_bit(Control::COMMAND_OFFSET).is_err());
1383///
1384/// control.set_bit(Control::FLAGS_OFFSET, true);
1385/// control.set_bit(Control::FLAGS_OFFSET + 1, true);
1386/// assert_eq!(control.flags(), 0b11);
1387///
1388/// // Reserved bits are not writable. Unchecked writes are no-ops, while
1389/// // checked writes return an error.
1390/// control.set_bit(6, false);
1391/// assert!(control.get_bit(6));
1392/// assert!(control.checked_set_bit(6, false).is_err());
1393///
1394/// // Out-of-bounds unchecked reads return false; checked reads return an error.
1395/// assert!(!control.get_bit(99));
1396/// assert!(control.checked_get_bit(99).is_err());
1397/// }
1398/// ```
1399///
1400/// **Primitive Bitfield range helpers**:
1401///
1402/// | Function | Checked / Unchecked | Description |
1403/// |-------------------------------------------------------------------------------|---------------------|-------------------------------------------------------------------------------------------------------------|
1404/// | `get_bits_range(offset: u32, len: u32) -> N` | Unchecked | Reads a range of bits and shifts the result to bit 0. Returns 0 if invalid. |
1405/// | `checked_get_bits_range(offset: u32, len: u32) -> Result<N, &str>` | Checked | Reads a range of bits and shifts them to bit 0. Returns an error on out of bounds. |
1406/// | `set_bits_range(offset: u32, len: u32, value: N)` | Unchecked | Sets a range of bits to the given shifted value. No-op if out of bounds or protected. |
1407/// | `checked_set_bits_range(offset: u32, len: u32, value: N) -> Result<(), &str>` | Checked | Sets a range of bits to the given shifted value. Returns an error if any bit is out of bounds or protected. |
1408///
1409/// ```rust
1410/// # use bitfields_impl as bitfields;
1411/// use bitfields::bitfield;
1412///
1413/// #[bitfield(u16, bit_ops = true)]
1414/// struct Flags {
1415/// #[bits(4)]
1416/// mode: u8,
1417///
1418/// #[bits(4, default = 0xA)]
1419/// status: u8,
1420///
1421/// #[bits(4, access = ro)]
1422/// control: u8,
1423///
1424/// #[bits(4)]
1425/// extra: u8,
1426/// }
1427///
1428/// fn main() {
1429/// let mut flags = Flags::new();
1430///
1431/// // set_bits_range — sets `len` bits starting at `offset` to the given value.
1432/// flags.set_bits_range(Flags::MODE_OFFSET, Flags::MODE_BITS, 0x5);
1433/// assert_eq!(flags.mode(), 0x5);
1434///
1435/// // get_bits_range — reads `len` bits starting at `offset`, shifted to bit 0.
1436/// assert_eq!(flags.get_bits_range(Flags::MODE_OFFSET, Flags::MODE_BITS), 0x5);
1437/// assert_eq!(flags.get_bits_range(Flags::STATUS_OFFSET, Flags::STATUS_BITS), 0xA);
1438///
1439/// // Unchecked range writes silently skip protected (read-only) bits.
1440/// flags.set_bits_range(Flags::CONTROL_OFFSET, 8, 0xFF);
1441/// assert_eq!(flags.extra(), 0xF); // extra bits written
1442/// assert_eq!(flags.control(), 0x0); // read-only bits are unchanged
1443///
1444/// // checked_set_bits_range — returns an error if any bit in the range is protected.
1445/// assert!(flags.checked_set_bits_range(Flags::CONTROL_OFFSET, 8, 0xFF).is_err());
1446///
1447/// // checked_get_bits_range — returns an error if the range is out of bounds.
1448/// assert!(flags.checked_get_bits_range(12, 8).is_err());
1449/// }
1450/// ```
1451///
1452/// **Array Backed Bitfield range helpers**:
1453///
1454/// | Function | Checked / Unchecked | Description |
1455/// |--------------------------------------------------------------------------------------|---------------------|---------------------------------------------------------------------------------------------------------------|
1456/// | `get_bytes_range(offset: u32, len: u32) -> [u8; N]` | Unchecked | Reads a range of bits and shifts the result into a byte array starting at bit 0. |
1457/// | `checked_get_bytes_range(offset: u32, len: u32) -> Result<[u8; N], &str>` | Checked | Reads a range of bits and shifts them into a byte array starting at bit 0. Returns an error on out of bounds. |
1458/// | `set_bytes_range(offset: u32, len: u32, value: [u8; N])` | Unchecked | Sets a range of bits using values starting at bit 0 of the input array. |
1459/// | `checked_set_bytes_range(offset: u32, len: u32, value: [u8; N]) -> Result<(), &str>` | Checked | Sets a range of bits using the input array. Returns an error if any bit is out of bounds or protected. |
1460///
1461/// ```rust
1462/// # use bitfields_impl as bitfields;
1463/// use bitfields::bitfield;
1464///
1465/// #[bitfield(u16, bit_ops = true)]
1466/// struct PacketWord {
1467/// low: u8,
1468///
1469/// #[bits(4)]
1470/// counter: u8,
1471///
1472/// #[bits(4, default = 0xF, access = ro)]
1473/// status: u8,
1474/// }
1475///
1476/// fn main() {
1477/// let mut packet = PacketWord::new();
1478///
1479/// packet.set_bits_range(PacketWord::LOW_OFFSET, PacketWord::LOW_BITS, 0xAB);
1480/// packet.set_bits_range(PacketWord::COUNTER_OFFSET, PacketWord::COUNTER_BITS, 0x5);
1481///
1482/// assert_eq!(packet.low(), 0xAB);
1483/// assert_eq!(packet.counter(), 0x5);
1484/// assert_eq!(packet.get_bits_range(PacketWord::LOW_OFFSET, PacketWord::LOW_BITS), 0xAB);
1485/// assert_eq!(packet.into_bits(), 0xF5AB);
1486///
1487/// // Unchecked range writes skip protected bits.
1488/// packet.set_bits_range(PacketWord::COUNTER_OFFSET, 8, 0x00);
1489/// assert_eq!(packet.counter(), 0x0);
1490/// assert_eq!(packet.status(), 0xF);
1491///
1492/// // Checked range writes fail if any bit in the range is protected.
1493/// assert!(packet.checked_set_bits_range(PacketWord::COUNTER_OFFSET, 8, 0x00).is_err());
1494/// }
1495/// ```
1496///
1497/// For array-backed bitfields, range values are packed starting at bit `0` of the
1498/// provided or returned array.
1499///
1500/// ```rust
1501/// # use bitfields_impl as bitfields;
1502/// use bitfields::bitfield;
1503///
1504/// #[bitfield([u8; 2], bit_ops = true)]
1505/// struct PacketBytes {
1506/// low: u8,
1507/// high: u8,
1508/// }
1509///
1510/// fn main() {
1511/// let mut packet = PacketBytes::new();
1512///
1513/// packet.set_bytes_range(PacketBytes::LOW_OFFSET, 12, [0xBC, 0x0A]);
1514///
1515/// assert_eq!(packet.low(), 0xBC);
1516/// assert_eq!(packet.high(), 0x0A);
1517/// assert_eq!(packet.get_bytes_range(PacketBytes::LOW_OFFSET, 12), [0xBC, 0x0A]);
1518/// assert_eq!(packet.into_le_bytes(), [0xBC, 0x0A]);
1519/// }
1520/// ```
1521///
1522/// #### Clear Bits
1523///
1524/// Clear helpers reset either the whole bitfield or individual writable fields.
1525///
1526/// **Primitive Bitfield**:
1527///
1528/// | Function | Description |
1529/// |------------------------------|--------------------------------------------------------------------------------------------|
1530/// | `clear_bits()` | Resets the bitfield to its zero representation (except reserved fields with defaults). |
1531/// | `clear_bits_with_defaults()` | Resets the bitfield and then restores all field defaults. |
1532/// | `clear_<field>()` | Clears the specific writable field to zero. (Generated per writable field) |
1533/// | `clear_<field>_to_default()` | Restores the specific writable field's default value. (Generated per field with a default) |
1534///
1535/// ```rust
1536/// # use bitfields_impl as bitfields;
1537/// use bitfields::bitfield;
1538///
1539/// #[bitfield(u32)]
1540/// struct Flags {
1541/// #[bits(default = 0x12)]
1542/// enabled: u8,
1543///
1544/// count: u8,
1545///
1546/// #[bits(default = 0x56)]
1547/// priority: u8,
1548///
1549/// #[bits(default = 0x78)]
1550/// _reserved: u8,
1551/// }
1552///
1553/// fn main() {
1554/// let mut flags = FlagsBuilder::new()
1555/// .with_enabled(0xFF)
1556/// .with_count(0x34)
1557/// .with_priority(0xAB)
1558/// .build();
1559/// assert_eq!(flags.into_bits(), 0x78AB34FF);
1560///
1561/// // clear_<field> — zeroes out a single writable field.
1562/// flags.clear_count();
1563/// assert_eq!(flags.count(), 0);
1564///
1565/// // clear_<field>_to_default — restores a single field to its default value.
1566/// flags.clear_enabled_to_default();
1567/// assert_eq!(flags.enabled(), 0x12);
1568///
1569/// // clear_bits — zeroes all writable bits; reserved fields keep their defaults.
1570/// flags.clear_bits();
1571/// assert_eq!(flags.enabled(), 0);
1572/// assert_eq!(flags.count(), 0);
1573/// assert_eq!(flags.priority(), 0);
1574/// assert_eq!(flags.into_bits(), 0x78000000); // _reserved keeps its default
1575///
1576/// // clear_bits_with_defaults — zeroes everything then restores field defaults.
1577/// flags.set_count(0x99);
1578/// flags.clear_bits_with_defaults();
1579/// assert_eq!(flags.enabled(), 0x12);
1580/// assert_eq!(flags.count(), 0);
1581/// assert_eq!(flags.priority(), 0x56);
1582/// assert_eq!(flags.into_bits(), 0x78560012);
1583/// }
1584/// ```
1585///
1586/// **Array Backed Bitfield**:
1587///
1588/// | Function | Description |
1589/// |-------------------------------|--------------------------------------------------------------------------------------------|
1590/// | `clear_bytes()` | Resets the bitfield bytes to zero (except reserved fields with defaults). |
1591/// | `clear_bytes_with_defaults()` | Resets the bitfield bytes and then restores all field defaults. |
1592/// | `clear_<field>()` | Clears the specific writable field to zero. (Generated per writable field) |
1593/// | `clear_<field>_to_default()` | Restores the specific writable field's default value. (Generated per field with a default) |
1594///
1595/// ```rust
1596/// # use bitfields_impl as bitfields;
1597/// use bitfields::bitfield;
1598///
1599/// #[bitfield([u8; 4])]
1600/// struct Flags {
1601/// #[bits(default = 0x12)]
1602/// enabled: u8,
1603///
1604/// count: u8,
1605///
1606/// #[bits(default = 0x56, access = ro)]
1607/// status: u8,
1608///
1609/// #[bits(default = 0x78)]
1610/// _reserved: u8,
1611/// }
1612///
1613/// fn main() {
1614/// let mut flags = FlagsBuilder::new().with_count(0x34).build();
1615/// assert_eq!(flags.into_bytes(), [0x78, 0x56, 0x34, 0x12]);
1616///
1617/// flags.clear_enabled();
1618/// assert_eq!(flags.enabled(), 0);
1619///
1620/// flags.clear_enabled_to_default();
1621/// assert_eq!(flags.enabled(), 0x12);
1622///
1623/// flags.clear_bytes();
1624/// assert_eq!(flags.enabled(), 0);
1625/// assert_eq!(flags.count(), 0);
1626/// assert_eq!(flags.status(), 0);
1627/// assert_eq!(flags.into_bytes(), [0x78, 0, 0, 0]);
1628///
1629/// flags.clear_bytes_with_defaults();
1630/// assert_eq!(flags.enabled(), 0x12);
1631/// assert_eq!(flags.count(), 0);
1632/// assert_eq!(flags.status(), 0x56);
1633/// assert_eq!(flags.into_bytes(), [0x78, 0x56, 0, 0x12]);
1634/// }
1635/// ```
1636///
1637/// #### Invert Bits
1638///
1639/// Invert helpers flip writable bits while preserving protected bits. They are
1640/// useful for toggling flags, building masks, and inspecting the complement of a
1641/// field without manually calculating a field-sized mask.
1642///
1643/// **Primitive Bitfield**:
1644///
1645/// | Function | Description |
1646/// |---------------------------|---------------------------------------------------------------------------------------------------------------|
1647/// | `invert_bits()` | Flips every writable bit in the primitive bitfield (read-only and reserved fields are untouched). |
1648/// | `invert_<field>()` | Mutates a writable field by flipping only its bits. (Generated per writable field) |
1649/// | `<field>_inverted() -> T` | Returns the field value with its bits inverted, without mutating the bitfield. (Generated per readable field) |
1650///
1651/// ```rust
1652/// # use bitfields_impl as bitfields;
1653/// use bitfields::bitfield;
1654///
1655/// #[bitfield(u16, bit_ops = true)]
1656/// struct Control {
1657/// #[bits(4, default = 0b0101)]
1658/// mode: u8,
1659///
1660/// #[bits(4, default = 0b1010)]
1661/// flags: u8,
1662///
1663/// #[bits(8, default = 0xA5, access = ro)]
1664/// checksum: u8,
1665/// }
1666///
1667/// fn main() {
1668/// let mut control = Control::new();
1669///
1670/// // <field>_inverted() — returns the inverted value without mutating the bitfield.
1671/// assert_eq!(control.mode_inverted(), 0b1010); // inverted within 4 bits
1672/// assert_eq!(control.flags_inverted(), 0b0101);
1673/// assert_eq!(control.mode(), 0b0101); // original value unchanged
1674///
1675/// // invert_<field>() — flips only the bits of a single writable field.
1676/// control.invert_mode();
1677/// assert_eq!(control.mode(), 0b1010);
1678///
1679/// // invert_bits() — flips all writable bits; read-only fields are preserved.
1680/// control.invert_bits();
1681/// assert_eq!(control.mode(), 0b0101); // back to original
1682/// assert_eq!(control.flags(), 0b0101); // also inverted
1683/// assert_eq!(control.checksum(), 0xA5); // read-only, untouched
1684/// }
1685/// ```
1686///
1687/// **Array Backed Bitfield**:
1688///
1689/// | Function | Description |
1690/// |---------------------------|---------------------------------------------------------------------------------------------------------------|
1691/// | `invert_bytes()` | Flips every writable bit in the array-backed bitfield (read-only and reserved fields are untouched). |
1692/// | `invert_<field>()` | Mutates a writable field by flipping only its bits. (Generated per writable field) |
1693/// | `<field>_inverted() -> T` | Returns the field value with its bits inverted, without mutating the bitfield. (Generated per readable field) |
1694///
1695/// The inversion is limited to the field width. For example, inverting a 5-bit
1696/// field value `0b01100` returns `0b10011`, not an 8-bit `0b11110011`.
1697///
1698/// ```rust
1699/// # use bitfields_impl as bitfields;
1700/// use bitfields::bitfield;
1701///
1702/// #[bitfield([u8; 2], bit_ops = true)]
1703/// struct Mask {
1704/// #[bits(5, default = 0b0_1100)]
1705/// pattern: u8,
1706///
1707/// #[bits(1, default = true)]
1708/// enabled: bool,
1709///
1710/// #[bits(2)]
1711/// flags: u8,
1712///
1713/// #[bits(8, default = 0xA5, access = ro)]
1714/// checksum: u8,
1715/// }
1716///
1717/// fn main() {
1718/// let mut mask = Mask::new();
1719///
1720/// assert_eq!(mask.pattern(), 0b0_1100);
1721/// assert_eq!(mask.pattern_inverted(), 0b1_0011);
1722/// assert!(!mask.enabled_inverted());
1723///
1724/// mask.invert_pattern();
1725/// assert_eq!(mask.pattern(), 0b1_0011);
1726///
1727/// mask.invert_enabled();
1728/// assert!(!mask.enabled());
1729///
1730/// mask.invert_bytes();
1731///
1732/// // Writable fields are inverted.
1733/// assert_eq!(mask.pattern(), 0b0_1100);
1734/// assert!(mask.enabled());
1735/// assert_eq!(mask.flags(), 0b11);
1736///
1737/// // Read-only fields are preserved.
1738/// assert_eq!(mask.checksum(), 0xA5);
1739/// }
1740/// ```
1741///
1742/// ### Passing Attributes
1743///
1744/// Attributes below the `#[bitfield]` attribute are passed to the generated struct.
1745///
1746/// ```rust
1747/// # use bitfields_impl as bitfields;
1748/// use bitfields::bitfield;
1749///
1750/// #[bitfield(u32)]
1751/// #[derive(Hash)]
1752/// struct Bitfield {
1753/// a: u32,
1754/// }
1755/// ```
1756///
1757/// ### Ignored Fields
1758///
1759/// Fields with the `#[bits(ignore = true)]` are ignored and not included
1760/// in the bitfield. This is useful for when you are building a custom
1761/// bitfield, but want to wrap bitfield in a parent struct to add additional
1762/// non-bitfield fields.
1763///
1764/// All ignored fields must implement the `Default` trait. Ignored fields
1765/// are accessible, and you can control their visibility like normal fields.
1766///
1767/// Take note that using ignored fields removes some constant guarantees.
1768///
1769/// ```rust
1770/// # use bitfields_impl as bitfields;
1771/// use bitfields::bitfield;
1772///
1773/// #[bitfield(u16)]
1774/// struct Bitfield {
1775/// a: u8,
1776/// b: u8,
1777/// #[bits(ignore = true)] /// Ignored field.
1778/// field_id: u8,
1779/// #[bits(ignore = true)] /// Ignored field.
1780/// pub(crate) custom_type: CustomType,
1781/// }
1782///
1783/// #[derive(Debug, Default, Clone, Copy, PartialEq)]
1784/// enum CustomType {
1785/// #[default]
1786/// A,
1787/// B,
1788/// }
1789///
1790/// fn main() {
1791/// let bitfield = Bitfield::new();
1792///
1793/// assert_eq!(bitfield.field_id, 0); // Ignored fields can be accessed directly.
1794/// assert_eq!(bitfield.custom_type, CustomType::A); // Ignored fields can be
1795/// // accessed directly.
1796/// }
1797/// ```
1798///
1799/// ### Visibility
1800///
1801/// Visibility applied to structs and fields determine the visibility of the
1802/// generated struct and field accessors.
1803///
1804/// ```rust
1805/// # use bitfields_impl as bitfields;
1806/// use bitfields::bitfield;
1807///
1808/// #[bitfield(u16)]
1809/// pub struct Bitfield { // The struct is public, so `Bitfield` is public.
1810/// pub a: u8, // `a` is public, so `a()` is public.
1811/// b: u8, // `b` is private, so `b()` is private.
1812/// }
1813/// ```
1814///
1815/// ### Default Implementations
1816///
1817/// #### Debug Trait
1818///
1819/// A debug implementation is generated for the bitfield, which prints the fields
1820/// and their values.
1821///
1822/// ```rust
1823/// # use bitfields_impl as bitfields;
1824/// use bitfields::bitfield;
1825///
1826/// #[bitfield(u32)]
1827/// struct Bitfield {
1828/// #[bits(default = 0x12)]
1829/// a: u8,
1830/// #[bits(default = 0x34)]
1831/// b: u8,
1832/// #[bits(default = 0x56)]
1833/// c: u8,
1834/// #[bits(default = 0x78)]
1835/// d: u8,
1836/// }
1837///
1838/// fn main() {
1839/// let bitfield = Bitfield::new();
1840///
1841/// assert_eq!(format!("{:?}", bitfield), "Bitfield { a: 18, b: 52, c: 86, d: 120 }");
1842/// }
1843/// ```
1844///
1845/// #### Default Trait
1846///
1847/// A default implementation is generated for the bitfield, which initializes the
1848/// bitfield to zero and sets default values. This can be disabled by specifying
1849/// `#[bitfield(default = false)]` on the bitfield.
1850///
1851/// ```rust
1852/// # use bitfields_impl as bitfields;
1853/// use bitfields::bitfield;
1854///
1855/// #[bitfield(u16)]
1856/// struct Bitfield {
1857/// #[bits(default = 0x12)]
1858/// a: u8,
1859/// b: u8,
1860/// }
1861///
1862/// fn main() {
1863/// let bitfield = Bitfield::default();
1864///
1865/// assert_eq!(bitfield.a(), 0x12);
1866/// assert_eq!(bitfield.b(), 0);
1867/// }
1868/// ```
1869///
1870/// #### From/Into Trait
1871///
1872/// From and Into trait implementations are generated for the bitfield, which
1873/// convert to and from the bitfield type. This can be disabled by specifying
1874/// `#[bitfield(from_traits = false)]` on the bitfield.
1875///
1876/// ```rust
1877/// # use bitfields_impl as bitfields;
1878/// use bitfields::bitfield;
1879///
1880/// #[bitfield(u16)] /// From<u16> and Into<u16> are generated for this bitfield.
1881/// struct Bitfield {
1882/// low: u8,
1883/// high: u8,
1884/// }
1885///
1886/// fn main() {
1887/// // `From<u16> for Bitfield`
1888/// let bitfield = Bitfield::from(0xABCD_u16);
1889/// assert_eq!(bitfield.low(), 0xCD);
1890/// assert_eq!(bitfield.high(), 0xAB);
1891///
1892/// // `From<Bitfield> for u16`
1893/// let bits = u16::from(bitfield);
1894/// assert_eq!(bits, 0xABCD);
1895///
1896/// // Equivalent `Into` usage
1897/// let bitfield_from_into: Bitfield = 0x1234_u16.into();
1898/// let bits_from_into: u16 = bitfield_from_into.into();
1899/// assert_eq!(bits_from_into, 0x1234);
1900/// }
1901/// ```
1902///
1903/// ```rust
1904/// # use bitfields_impl as bitfields;
1905/// use bitfields::bitfield;
1906///
1907/// #[bitfield([u8; 2]
1908/// )] /// From<[u8; 2]> and Into<[u8; 2]> are generated for this bitfield.
1909/// struct Bitfield {
1910/// low: u8,
1911/// high: u8,
1912/// }
1913///
1914/// fn main() {
1915/// // `From<[u8; 2]> for Bitfield`
1916/// let bitfield = Bitfield::from([0xAB, 0xCD]);
1917/// assert_eq!(bitfield.low(), 0xCD);
1918/// assert_eq!(bitfield.high(), 0xAB);
1919///
1920/// // `From<Bitfield> for [u8; 2]`
1921/// let bytes = <[u8; 2]>::from(bitfield);
1922/// assert_eq!(bytes, [0xAB, 0xCD]);
1923///
1924/// // Equivalent `Into` usage
1925/// let bitfield_from_into: Bitfield = [0x12, 0x34].into();
1926/// let bytes_from_into: [u8; 2] = bitfield_from_into.into();
1927/// assert_eq!(bytes_from_into, [0x12, 0x34]);
1928/// }
1929/// ```
1930///
1931/// ### Bitfield Internal Value
1932///
1933/// The internal value of the bitfield is stored as either a tuple struct where it's
1934/// the first parameter, or as a field named `val` if ignored fields are present.
1935/// This allows you to access the internal value of the bitfield directly if needed,
1936/// but it is recommended to use the provided APIs to access and modify the
1937/// bitfield.
1938///
1939/// ```rust
1940/// # use bitfields_impl as bitfields;
1941/// use bitfields::bitfield;
1942///
1943/// #[bitfield(u16)]
1944/// struct TupleBitfield {
1945/// low: u8,
1946/// high: u8,
1947/// }
1948///
1949/// #[bitfield(u16)]
1950/// struct ValBitfield {
1951/// low: u8,
1952/// high: u8,
1953/// #[bits(ignore = true)]
1954/// tag: u8,
1955/// }
1956///
1957/// fn main() {
1958/// let tuple_bf = TupleBitfield::new();
1959/// println!("{}", tuple_bf.0);
1960///
1961/// let val_bf = ValBitfield::new();
1962/// println!("{:?}", val_bf.val);
1963/// }
1964/// ```
1965///
1966/// ### Configuration
1967///
1968/// Bitfields can be configured with arguments passed to the `#[bitfield(...)]`
1969/// attribute. The first argument is always the backing storage type; every other
1970/// argument is named.
1971///
1972/// Boolean arguments accept `true` or `false`. The defaults below are the defaults
1973/// when no Cargo feature overrides are enabled. Per-bitfield attribute arguments
1974/// override Cargo feature defaults.
1975///
1976/// ```rust,ignore
1977/// # use bitfields_impl as bitfields;
1978/// use bitfields::bitfield;
1979///
1980/// #[bitfield(
1981/// u32,
1982/// order = lsb,
1983/// from_endian = big,
1984/// into_endian = big,
1985/// write_endian = big,
1986/// new = true,
1987/// from_into_bits = true,
1988/// from_traits = true,
1989/// default = true,
1990/// debug = true,
1991/// copy = true,
1992/// builder = true,
1993/// bit_ops = true,
1994/// write_bit_ops = true,
1995/// clear_bit_ops = true,
1996/// set_get_bit_ops = true,
1997/// invert_bit_ops = true,
1998/// toggle_bit_ops = true,
1999/// array_heap = false,
2000/// )]
2001/// struct Example {
2002/// a: u32,
2003/// }
2004/// ```
2005///
2006/// | Argument | Values | Default | Description |
2007/// |-------------------|-------------------------------------------------|----------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
2008/// | `<backing type>` | `u8`, `u16`, `u32`, `u64`, `u128`, or `[u8; N]` | Required | The storage used by the generated bitfield. Primitive backing types support bitfields up to 128 bits. `[u8; N]` creates an array-backed bitfield for larger layouts. Field bit widths, excluding ignored fields, must add up exactly to the backing storage size. |
2009/// | `order` | `lsb`, `msb` | `lsb` | Controls how struct fields are assigned to bit offsets. `lsb` assigns the first non-ignored field to the least-significant bits. `msb` assigns the first non-ignored field to the most-significant bits. |
2010/// | `from_endian` | `big`, `little` | `big` | Default endian used by `from_bits`, `from_bytes`, `from_slice`, and `From<Backing> for Bitfield`. Explicit helpers such as `from_le_bits` and `from_be_bytes` ignore this setting. |
2011/// | `into_endian` | `big`, `little` | `big` | Default endian used by `into_bits`, `into_bytes`, `into_slice`, and `From<Bitfield> for Backing`. Explicit helpers such as `into_le_bits` and `into_be_bytes` ignore this setting. |
2012/// | `write_endian` | `big`, `little` | `big` | Default endian used by whole-bitfield write helpers such as `write_bits` and `write_bytes`. Explicit helpers such as `write_le_bits` and `write_be_bytes` ignore this setting. |
2013/// | `new` | `true`, `false` | `true` | Generates `new()` and `new_without_defaults()` constructors. Other generated features that need construction logic, such as `Default` and the builder, still inline equivalent initialization logic when this is disabled. |
2014/// | `from_into_bits` | `true`, `false` | `true` | Generates backing-data conversion functions. Primitive bitfields get `from_bits`, `from_bits_with_defaults`, endian-specific `from_*_bits` helpers, `into_bits`, and endian-specific `into_*_bits` helpers. Array-backed bitfields get the corresponding `bytes` and `slice` APIs. |
2015/// | `from_traits` | `true`, `false` | `true` | Generates `From<Backing> for Bitfield` and `From<Bitfield> for Backing`. These conversions use `from_endian` and `into_endian`. |
2016/// | `default` | `true`, `false` | `true` | Generates `Default` for the bitfield. The default value is equivalent to `new()`: zero-initialized storage with field defaults applied. |
2017/// | `debug` | `true`, `false` | `true` | Generates `core::fmt::Debug` for the bitfield. The implementation prints readable fields and their values. |
2018/// | `copy` | `true`, `false` | `true` | Derives `Copy` and `Clone` for primitive and stack array-backed bitfields. Heap array-backed bitfields derive `Clone` only because `Box<[u8; N]>` is not `Copy`. |
2019/// | `builder` | `true`, `false` | `true` | Generates the `<Bitfield>Builder` type, `new`, `new_without_defaults`, `with_<field>`, `checked_with_<field>`, and `build`. Reserved fields do not get builder setters. |
2020/// | `bit_ops` | `true`, `false` | `true` | Master switch for bit operation groups. When `false`, all bit operation groups are disabled unless a specific bit operation group is explicitly set to `true`. |
2021/// | `write_bit_ops` | `true`, `false` | `true` | Generates whole-bitfield write helpers such as `write_bits`, `write_bits_with_defaults`, `write_le_bits`, `write_be_bits`, and `write_defaults` for primitive bitfields, or the corresponding `bytes` helpers for array-backed bitfields. |
2022/// | `clear_bit_ops` | `true`, `false` | `true` | Generates whole-bitfield clear helpers such as `clear_bits` / `clear_bytes`, `clear_bits_with_defaults` / `clear_bytes_with_defaults`, plus per-field helpers like `clear_<field>()` and `clear_<field>_to_default()`. |
2023/// | `set_get_bit_ops` | `true`, `false` | `true` | Generates individual bit helpers (`get_bit`, `checked_get_bit`, `set_bit`, `checked_set_bit`) and range helpers (`get_bits_range` / `set_bits_range` for primitive bitfields, `get_bytes_range` / `set_bytes_range` for array-backed bitfields, plus checked variants). |
2024/// | `invert_bit_ops` | `true`, `false` | `true` | Generates inversion helpers such as `invert_bits` / `invert_bytes`, per-field `invert_<field>()`, and readable-field `<field>_inverted()` getters. |
2025/// | `toggle_bit_ops` | `true`, `false` | `true` | Accepted as a bit-operation group flag for configuration compatibility. In this version, there are no separate `toggle_*` APIs; use the generated invert helpers to toggle bits. |
2026/// | `array_heap` | `true`, `false` | `false` | For array-backed bitfields only, stores the backing `[u8; N]` in a `Box` instead of inline in the struct. This helps avoid large stack values but requires heap allocation and therefore gives up the zero-allocation and `no_std` guarantees for that bitfield. It has no effect on primitive-backed bitfields. |
2027///
2028/// ```rust
2029/// # use bitfields_impl as bitfields;
2030/// use bitfields::bitfield;
2031///
2032/// // Demonstrates a selection of configuration arguments.
2033/// #[bitfield(
2034/// u32,
2035/// order = msb, // first struct field occupies the most-significant bits
2036/// from_endian = little, // from_bits / From<u32> treat raw bits as little-endian
2037/// into_endian = big, // into_bits / From<Bitfield> emit big-endian bits
2038/// default = true, // generate Default impl
2039/// debug = true, // generate Debug impl
2040/// builder = true, // generate <Struct>Builder
2041/// bit_ops = false, // disable all bit-operation helpers
2042/// )]
2043/// struct Config {
2044/// #[bits(default = 0x12)]
2045/// tag: u8,
2046/// #[bits(default = 0x34)]
2047/// flags: u8,
2048/// #[bits(default = 0x56)]
2049/// size: u8,
2050/// #[bits(default = 0x78)]
2051/// checksum: u8,
2052/// }
2053///
2054/// fn main() {
2055/// // With order = msb, `tag` occupies bits 31..=24 and `checksum` occupies bits 7..=0.
2056/// let cfg = Config::new();
2057/// assert_eq!(cfg.tag(), 0x12);
2058/// assert_eq!(cfg.flags(), 0x34);
2059/// assert_eq!(cfg.size(), 0x56);
2060/// assert_eq!(cfg.checksum(), 0x78);
2061///
2062/// // into_endian = big: the raw u32 is big-endian (tag at top byte).
2063/// assert_eq!(cfg.into_bits(), 0x12_34_56_78);
2064///
2065/// // from_endian = little: raw bits are interpreted as little-endian before decoding.
2066/// let cfg2 = Config::from_bits(0x12_34_56_78);
2067/// assert_eq!(cfg2.checksum(), 0x12); // 0x12 is now the LSB (checksum field in msb order)
2068/// }
2069/// ```
2070///
2071/// #### Bit Operations Config
2072///
2073/// The `bit_ops` argument is a master switch for the bit-operation groups:
2074///
2075/// - `#[bitfield(u32, bit_ops = false)]` disables all bit operations.
2076/// - `#[bitfield(u32, bit_ops = true, set_get_bit_ops = false)]` enables bit
2077/// operations except the set/get bit group.
2078/// - `#[bitfield(u32, bit_ops = false, set_get_bit_ops = true)]` disables the
2079/// master switch but explicitly opts the set/get bit group back in.
2080///
2081/// This lets you generate only the bit-operation APIs you need.
2082///
2083/// #### Global Cargo Feature Flags
2084///
2085/// If you find yourself applying the same configuration arguments to many bitfields
2086/// in your codebase, you can set those defaults globally by **disabling default
2087/// features** and enabling the corresponding Cargo features:
2088///
2089/// - Constructors: `generate_new` / `disable_new`
2090/// - From/into functions: `generate_from_into_bits` /
2091/// `disable_from_into_bits`
2092/// - From traits: `generate_from_traits` / `disable_from_traits`
2093/// - Default trait: `generate_default` / `disable_default`
2094/// - Debug trait: `generate_debug` / `disable_debug`
2095/// - Copy/Clone derives: `derive_copy` / `disable_copy`
2096/// - Builder: `generate_builder` / `disable_builder`
2097/// - All bit operations: `generate_bit_ops` / `disable_bit_ops`
2098/// - Write bit operations: `generate_write_bit_ops` /
2099/// `disable_write_bit_ops`
2100/// - Clear bit operations: `generate_clear_bit_ops` /
2101/// `disable_clear_bit_ops`
2102/// - Set/get bit operations: `generate_set_get_bit_ops` /
2103/// `disable_set_get_bit_ops`
2104/// - Invert bit operations: `generate_invert_bit_ops` /
2105/// `disable_invert_bit_ops`
2106/// - Toggle bit operations: `generate_toggle_bit_ops` /
2107/// `disable_toggle_bit_ops`
2108/// - Array heap storage: `enable_array_heap` / `disable_array_heap`
2109///
2110/// Endian and order defaults have dedicated feature names:
2111///
2112/// - Bitfield field order: `order_lsb` / `order_msb`
2113/// - Bitfield From operations endian: `from_endian_little` / `from_endian_big`
2114/// - Bitfield Into operations endian: `into_endian_little` / `into_endian_big`
2115/// - Bitfield Write endian: `write_endian_little` / `write_endian_big`
2116///
2117/// Bitflags can also be configured globally with the following defaults:
2118///
2119/// - from_bits endian: `bitflag_from_endian_little` / `bitflag_from_endian_big`
2120/// - into_bits endian: `bitflag_into_endian_little` / `bitflag_into_endian_big`
2121/// - Copy and Clone: `bitflag_derive_copy` / `bitflag_disable_copy`
2122///
2123/// ```toml
2124/// [dependencies]
2125/// bitfields = {
2126/// version = "2.0.8",
2127/// # Default features must be disabled.
2128/// default-features = false,
2129/// features = [
2130/// "generate_builder",
2131/// "generate_set_get_bit_ops",
2132/// "order_msb",
2133/// "from_endian_little",
2134/// "into_endian_big"
2135/// ]
2136/// }
2137/// ```
2138/// <!-- rust-docs-end -->
2139#[proc_macro_attribute]
2140pub fn bitfield(
2141 args: proc_macro::TokenStream,
2142 input: proc_macro::TokenStream,
2143) -> proc_macro::TokenStream {
2144 catch_panics(|| start_bitfield_generation(args, input))
2145}
2146
2147/// Entry for starting the bitfield generation.
2148fn start_bitfield_generation(
2149 args: proc_macro::TokenStream,
2150 input: proc_macro::TokenStream,
2151) -> proc_macro::TokenStream {
2152 let parsed_bitfield = match parse_bitfield_struct(args.into(), input.into()) {
2153 Ok(bitfield) => bitfield,
2154 Err(err) => return err.into_compile_error().into(),
2155 };
2156 check_force_panic(&parsed_bitfield);
2157 generate_bitfield(&parsed_bitfield).into()
2158}
2159
2160/// Forces a panic if argument is enabled.
2161fn check_force_panic(bitfield: &Bitfield) {
2162 assert!(!bitfield.arguments().force_panic(), "Forced panic for testing purposes");
2163}
2164
2165#[rustfmt::skip]
2166/// <!-- rust-bitflags-docs-start -->
2167/// ### Bitflags
2168///
2169/// There are times when you just want to define a bitflag, which are just enums
2170/// that map to bits. Instead of defining a custom type, you can take advantage of
2171/// the `#[bitflag]` attribute which generates `from_bits` and `into_bits` for enums
2172/// automatically.
2173///
2174/// Bitflags only supports unsigned types (`u8`, `u16`, `u32`, `u64`, `u128`) and
2175/// the one of the variants must be annotated with `#[base]` or `#[default]` which represents the
2176/// base value of the bitflag. If `#[base]` and `#[default]` are both present, `#[base]` takes precedence.
2177///
2178/// ```rust
2179/// # use bitfields_impl as bitfields;
2180/// use bitfields::bitfield;
2181/// use bitfields::bitflag;
2182///
2183/// /// Annotate an enum with the `#[bitflag]` attribute to automatically generate
2184/// /// the `from_bits` and `into_bits` functions for you! One variant must be annotated
2185/// /// with `#[base]` which represents the base value of the bitflag.
2186/// #[bitflag(u8)]
2187/// #[derive(Debug, PartialEq)]
2188/// enum RenderMode {
2189/// #[base]
2190/// Normal = 0,
2191/// Mirror = 1,
2192/// Flip = 2,
2193/// // #[default] - Default can be specified but base takes
2194/// // precedence if both are present.
2195/// Hidden = 3,
2196/// }
2197///
2198/// /// The code that's generated for the `RenderMode` by the
2199/// /// `#[bitflag]` attribute saving you the trouble of writing
2200/// /// the `from_bits` and `into_bits` functions yourself.
2201/// // impl RenderMode {
2202/// // const fn from_bits(bits: u8) -> Self {
2203/// // match bits {
2204/// // 0 => Self::Normal,
2205/// // 1 => Self::Mirror,
2206/// // 2 => Self::Flip,
2207/// // 3 => Self::Hidden,
2208/// // _ => unreachable!(),
2209/// // }
2210/// // }
2211/// //
2212/// // const fn into_bits(self) -> u8 {
2213/// // self as u8
2214/// // }
2215/// // }
2216///
2217/// /// Annotate an enum with the `#[bitflag]` attribute to automatically generate
2218/// /// the `from_bits` and `into_bits` functions for you! One variant must be annotated
2219/// /// with `#[base]` which represents the base value of the bitflag.
2220/// #[bitflag(u8)]
2221/// #[derive(Debug, PartialEq)]
2222/// enum AudioMode {
2223/// #[base]
2224/// Stereo = 0,
2225/// Mono = 1,
2226/// Mute = 2,
2227/// Surround = 3,
2228/// }
2229///
2230/// #[bitfield(u8)]
2231/// struct DisplayControl {
2232/// /// Must have the `#[bits]` attribute since the macro has
2233/// /// no way of knowing how many bits the custom type occupies.
2234/// #[bits(4, default = RenderMode::Normal)]
2235/// render_mode: RenderMode,
2236/// /// Must have the `#[bits]` attribute since the macro has
2237/// /// no way of knowing how many bits the custom type occupies.
2238/// #[bits(4, default = AudioMode::Stereo)]
2239/// audio_mode: AudioMode,
2240/// }
2241///
2242/// fn main() {
2243/// let display = DisplayControlBuilder::new()
2244/// .with_render_mode(RenderMode::Mirror)
2245/// .with_audio_mode(AudioMode::Mute)
2246/// .build();
2247///
2248/// assert_eq!(display.render_mode(), RenderMode::Mirror);
2249/// assert_eq!(display.audio_mode(), AudioMode::Mute);
2250/// }
2251/// ```
2252///
2253/// #### Bitflag Configuration
2254///
2255/// Bitflags can be configured with arguments passed to the `#[bitflag(...)]` attribute (the first argument is always the backing unsigned integer type):
2256///
2257/// | Argument | Values | Default | Description |
2258/// |------------------|-----------------------------------|----------|------------------------------------------------------------------------------------------------------|
2259/// | `<backing type>` | `u8`, `u16`, `u32`, `u64`, `u128` | Required | The storage used by the generated bitflag. Primitive backing types support bitfields up to 128 bits. |
2260/// | `from_endian` | `big`, `little` | `big` | Default endianness used by the generated `from_bits` function. |
2261/// | `into_endian` | `big`, `little` | `big` | Default endianness used by the generated `into_bits` function. |
2262/// | `copy` | `true`, `false` | `true` | Determines whether to derive `Copy` and `Clone` automatically for the enum. |
2263/// <!-- rust-bitflags-docs-end -->
2264#[proc_macro_attribute]
2265pub fn bitflag(
2266 args: proc_macro::TokenStream,
2267 input: proc_macro::TokenStream,
2268) -> proc_macro::TokenStream {
2269 catch_panics(|| start_bitflag_generation(args, input))
2270}
2271
2272/// Entry for starting the bitflag generation.
2273fn start_bitflag_generation(
2274 args: proc_macro::TokenStream,
2275 input: proc_macro::TokenStream,
2276) -> proc_macro::TokenStream {
2277 let parsed_bitflag = match parse_bitflag_enum(args.into(), input.into()) {
2278 Ok(bitflag) => bitflag,
2279 Err(err) => return err.into_compile_error().into(),
2280 };
2281
2282 generate_bitflag(&parsed_bitflag).into()
2283}
2284
2285/// Wraps and converts any unexpected panics into a compile error at the call
2286/// site.
2287fn catch_panics(macro_fn: impl FnOnce() -> proc_macro::TokenStream) -> proc_macro::TokenStream {
2288 std::panic::catch_unwind(std::panic::AssertUnwindSafe(macro_fn)).unwrap_or_else(|panic| {
2289 let panic_msg =
2290 panic.downcast_ref::<&str>().copied().unwrap_or("unable to parse panic payload");
2291 syn::Error::new(
2292 proc_macro2::Span::call_site(),
2293 format!("{INTERNAL_ERROR_MESSAGE}: {panic_msg}"),
2294 )
2295 .to_compile_error()
2296 .into()
2297 })
2298}