Skip to main content

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/// ```rust
565/// # use bitfields_impl as bitfields;
566/// use bitfields::bitfield;
567///
568/// #[bitfield(u16)]
569/// struct Bitfield {
570///     a: u8,
571///
572///     /// Fills the remaining bits of the u16.
573///     #[bits(default = 0xFF)]
574///     _reserved: u8,
575/// }
576///
577/// fn main() {
578///     let bitfield = Bitfield::new();
579///     assert_eq!(bitfield.a(), 0);
580///     // assert_eq!(bitfield._reserved(), 0xFF00); // Compile error, reserved inaccessible.
581///     // bitfield.set__reserved(0xFF); // Compile error, reserved fields are inaccessible.
582///     assert_eq!(bitfield.into_bits(), 0xFF00); // All fields exposed when converted 
583///     // to bits.
584/// }
585/// ```
586///
587/// <!-- rust-bitflags-docs-start -->
588///
589/// ### Bitflags
590///
591/// There are times when you just want to define a bitflag, which are just enums
592/// that map to bits. Instead of defining a custom type, you can take advantage of
593/// the `#[bitflag]` attribute which generates `from_bits` and `into_bits` for enums
594/// automatically.
595///
596/// Bitflags only supports unsigned types (`u8`, `u16`, `u32`, `u64`, `u128`) and
597/// the one of the variants must be annotated with `#[base]` or `#[default]` which represents the
598/// base value of the bitflag. If `#[base]` and `#[default]` are both present, `#[base]` takes precedence.
599///
600/// ```rust
601/// # use bitfields_impl as bitfields;
602/// use bitfields::bitfield;
603/// use bitfields::bitflag;
604///
605/// /// Annotate an enum with the `#[bitflag]` attribute to automatically generate
606/// /// the `from_bits` and `into_bits` functions for you! One variant must be annotated
607/// /// with `#[base]` which represents the base value of the bitflag.
608/// #[bitflag(u8)]
609/// #[derive(Debug, PartialEq)]
610/// enum RenderMode {
611///     #[base]
612///     Normal = 0,
613///     Mirror = 1,
614///     Flip = 2,
615///     // #[default] - Default can be specified but base takes 
616///     // precedence if both are present.
617///     Hidden = 3,
618/// }
619///
620/// /// The code that's generated for the `RenderMode` by the
621/// /// `#[bitflag]` attribute saving you the trouble of writing 
622/// /// the `from_bits` and `into_bits` functions yourself.
623/// // impl RenderMode {
624/// //     const fn from_bits(bits: u8) -> Self {
625/// //         match bits {
626/// //             0 => Self::Normal,
627/// //             1 => Self::Mirror,
628/// //             2 => Self::Flip,
629/// //             3 => Self::Hidden,
630/// //             _ => unreachable!(),
631/// //         }
632/// //     }
633/// //
634/// //     const fn into_bits(self) -> u8 {
635/// //         self as u8
636/// //     }
637/// // }
638///
639/// /// Annotate an enum with the `#[bitflag]` attribute to automatically generate
640/// /// the `from_bits` and `into_bits` functions for you! One variant must be annotated
641/// /// with `#[base]` which represents the base value of the bitflag.
642/// #[bitflag(u8)]
643/// #[derive(Debug, PartialEq)]
644/// enum AudioMode {
645///     #[base]
646///     Stereo = 0,
647///     Mono = 1,
648///     Mute = 2,
649///     Surround = 3,
650/// }
651///
652/// #[bitfield(u8)]
653/// struct DisplayControl {
654///     /// Must have the `#[bits]` attribute since the macro has 
655///     /// no way of knowing how many bits the custom type occupies.
656///     #[bits(4, default = RenderMode::Normal)]
657///     render_mode: RenderMode,
658///     /// Must have the `#[bits]` attribute since the macro has 
659///     /// no way of knowing how many bits the custom type occupies.
660///     #[bits(4, default = AudioMode::Stereo)]
661///     audio_mode: AudioMode,
662/// }
663///
664/// fn main() {
665///     let display = DisplayControlBuilder::new()
666///         .with_render_mode(RenderMode::Mirror)
667///         .with_audio_mode(AudioMode::Mute)
668///         .build();
669///
670///     assert_eq!(display.render_mode(), RenderMode::Mirror);
671///     assert_eq!(display.audio_mode(), AudioMode::Mute);
672/// }
673/// ```
674///
675/// #### Bitflag Configuration
676///
677/// Bitflags can be configured with arguments passed to the `#[bitflag(...)]` attribute (the first argument is always the backing unsigned integer type):
678///
679/// | Argument         | Values                            | Default  | Description                                                                                          |
680/// |------------------|-----------------------------------|----------|------------------------------------------------------------------------------------------------------|
681/// | `<backing type>` | `u8`, `u16`, `u32`, `u64`, `u128` | Required | The storage used by the generated bitflag. Primitive backing types support bitfields up to 128 bits. |
682/// | `from_endian`    | `big`, `little`                   | `big`    | Default endianness used by the generated `from_bits` function.                                       |
683/// | `into_endian`    | `big`, `little`                   | `big`    | Default endianness used by the generated `into_bits` function.                                       |
684/// | `copy`           | `true`, `false`                   | `true`   | Determines whether to derive `Copy` and `Clone` automatically for the enum.                          |
685///
686/// <!-- rust-bitflags-docs-end -->
687///
688/// ### Field Constants
689///
690/// Fields with read or write access have constants generated for their number of
691/// bits and offset in the bitfield.
692///
693/// ```rust
694/// # use bitfields_impl as bitfields;
695/// use bitfields::bitfield;
696///
697/// #[bitfield(u32)]
698/// struct Bitfield {
699///     #[bits(default = 0x12)]
700///     a: u8,
701///     #[bits(default = 0x34)]
702///     b: u8,
703///     #[bits(default = 0x56)]
704///     c: u8,
705///     #[bits(default = 0x78)]
706///     d: u8,
707/// }
708///
709/// fn main() {
710///     assert_eq!(Bitfield::A_BITS, 8); // Number of bits of the a field.
711///     assert_eq!(Bitfield::A_OFFSET, 0); // The offset of the a field in the bitfield.
712///     assert_eq!(Bitfield::B_BITS, 8); // Number of bits of the b field.
713///     assert_eq!(Bitfield::B_OFFSET, 8); // The offset of the b field in the bitfield.
714///     assert_eq!(Bitfield::C_BITS, 8); // Number of bits of the c field.
715///     assert_eq!(Bitfield::C_OFFSET, 16); // The offset of the c field in the bitfield.
716///     assert_eq!(Bitfield::D_BITS, 8); // Number of bits of the d field.
717///     assert_eq!(Bitfield::D_OFFSET, 24); // The offset of the d field in the bitfield.
718/// }
719/// ```
720///
721/// ### Field Order
722///
723/// The order of the bitfield determines whether from top to bottom struct fields
724/// are ordered from the least significant bit (lsb) to the most significant bit (
725/// msb). By default, fields are ordered from the least significant bit (lsb) to the
726/// most significant bit (msb).
727///
728/// The order can be changed by specifying the `#[bitfield(order = N)]` arg on the
729/// bitfield struct, with the options `lsb` or `msb`.
730///
731/// ```rust
732/// # use bitfields_impl as bitfields;
733/// use bitfields::bitfield;
734///
735/// /// Field layout (LSB → MSB):
736/// ///
737/// /// | 31    24 | 23   16 | 15        8 | 7       0 |
738/// /// +----------+---------+-------------+-----------+
739/// /// | checksum | reading | status_code | sensor_id |
740/// /// +----------+---------+-------------+-----------+
741/// ///
742/// /// Field mapping:
743/// /// - sensor_id:   bits 7..=0
744/// /// - status_code: bits 15..=8
745/// /// - reading:     bits 23..=16
746/// /// - checksum:    bits 31..=24
747/// #[bitfield(u32)] // LSB by default.
748/// struct TelemetryFrameLsb {
749///     #[bits(default = 0x12)] /// sensor_id occupies bits 7..=0 (LSB).
750///     sensor_id: u8,
751///     #[bits(default = 0x34)] /// status_code occupies bits 15..=8.
752///     status_code: u8,
753///     #[bits(default = 0x56)] /// reading occupies bits 23..=16.
754///     reading: u8,
755///     #[bits(default = 0x78)] /// checksum occupies bits 31..=24 (MSB).
756///     checksum: u8,
757/// }
758///
759/// /// Bit layout (MSB → LSB):
760/// ///
761/// /// | 31    24 | 23          16 | 15      8 | 7       0 |
762/// /// +----------+---------------+-----------+------------+
763/// /// | sensor_id|  status_code  |  reading  |  checksum  |
764/// /// +----------+---------------+-----------+------------+
765/// ///
766/// /// Field mapping:
767/// /// - sensor_id:   bits 31..=24
768/// /// - status_code: bits 23..=16
769/// /// - reading:     bits 15..=8
770/// /// - checksum:    bits 7..=0
771/// #[bitfield(u32, order = msb)]
772/// struct TelemetryFrameMsb {
773///     #[bits(default = 0x12)]
774///     sensor_id: u8,
775///     #[bits(default = 0x34)]
776///     status_code: u8,
777///     #[bits(default = 0x56)]
778///     reading: u8,
779///     #[bits(default = 0x78)]
780///     checksum: u8,
781/// }
782///
783/// fn main() {
784///     let frame_lsb = TelemetryFrameLsb::new();
785///     assert_eq!(frame_lsb.sensor_id(), 0x12);
786///     assert_eq!(frame_lsb.status_code(), 0x34);
787///     assert_eq!(frame_lsb.reading(), 0x56);
788///     assert_eq!(frame_lsb.checksum(), 0x78);
789///     let val = frame_lsb.into_bits();
790///
791///     //                .- checksum
792///     //                |  .- reading
793///     //                |  |  .- status_code
794///     //                |  |  |  .- sensor_id
795///     assert_eq!(val, 0x78_56_34_12);
796///     assert_eq!(TelemetryFrameLsb::SENSOR_ID_OFFSET, 0); // Offset in LSB order.
797///
798///     let frame_msb = TelemetryFrameMsb::new();
799///     assert_eq!(frame_msb.sensor_id(), 0x12);
800///     assert_eq!(frame_msb.status_code(), 0x34);
801///     assert_eq!(frame_msb.reading(), 0x56);
802///     assert_eq!(frame_msb.checksum(), 0x78);
803///     let val = frame_msb.into_bits();
804///
805///     //                .- sensor_id
806///     //                |  .- status_code
807///     //                |  |  .- reading
808///     //                |  |  |  .- checksum
809///     assert_eq!(val, 0x12_34_56_78);
810///     assert_eq!(TelemetryFrameMsb::SENSOR_ID_OFFSET, 24); // Offset in MSB order.
811/// }
812/// ```
813///
814/// ### Bitfield Conversions
815///
816/// A bitfield can be converted into and from bits using multiple functions.
817///
818/// #### From Bits
819///
820/// A bitfield can be converted from bits using the following from APIs:
821///
822/// **Primitive Bitfield**:
823///
824/// | Method                                | Endianness                                   | Description                                                                                                  |
825/// |---------------------------------------|----------------------------------------------|--------------------------------------------------------------------------------------------------------------|
826/// | `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`).        |
827/// | `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.           |
828/// | `from_le_bits(bits: N)`               | Little-endian                                | Creates a new bitfield instance from the given little-endian bits, ignoring field defaults.                  |
829/// | `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. |
830/// | `from_be_bits(bits: N)`               | Big-endian                                   | Creates a new bitfield instance from the given big-endian bits, ignoring field defaults.                     |
831/// | `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.    |
832///
833/// ```rust
834/// # use bitfields_impl as bitfields;
835/// use bitfields::bitfield;
836///
837/// #[bitfield(u32)]
838/// struct Bitfield {
839///     #[bits(default = 0x12)]
840///     a: u8,
841///     #[bits(default = 0x34)]
842///     b: u8,
843///     #[bits(default = 0x56)]
844///     c: u8,
845///     #[bits(default = 0x78)]
846///     _reserved: u8,
847/// }
848///
849/// fn main() {
850///     // from_bits - Creates a bitfield from raw bits, ignoring defaults. 
851///     // Default endian is big.
852///     let from_bits = Bitfield::from_bits(0x11_22_33_44);
853///     assert_eq!(from_bits.a(), 0x44);
854///     assert_eq!(from_bits.b(), 0x33);
855///     assert_eq!(from_bits.c(), 0x22);
856///     assert_eq!(from_bits.into_bits(), 0x11223344);
857///
858///     // from_bits_with_defaults - Creates a bitfield from raw bits, respecting 
859///     // default values. Fields with defaults are set to their default values.
860///     let from_bits_with_defaults = Bitfield::from_bits_with_defaults(0x11_22_33_44);
861///     assert_eq!(from_bits_with_defaults.a(), 0x12);
862///     assert_eq!(from_bits_with_defaults.b(), 0x34);
863///     assert_eq!(from_bits_with_defaults.c(), 0x56);
864///     assert_eq!(from_bits_with_defaults.into_bits(), 0x78563412);
865///
866///     // from_le_bits - Creates a bitfield from bits assumed to be in 
867///     // little-endian order, ignoring defaults.
868///     let from_le_bits = Bitfield::from_le_bits(0x11_22_33_44);
869///     assert_eq!(from_le_bits.into_bits(), 0x44_33_22_11);
870///
871///     // from_le_bits_with_defaults - Creates a bitfield from bits assumed to be 
872///     // in little-endian order, respecting default values.
873///     let from_le_bits_with_defaults = Bitfield::from_le_bits_with_defaults(0x11_22_33_44);
874///     assert_eq!(
875///         from_le_bits_with_defaults.into_bits(),
876///         0x78_56_34_12
877///     );
878///
879///     // from_be_bits - Creates a bitfield from bits assumed to be in 
880///     // big-endian order, ignoring defaults.
881///     let from_be_bits = Bitfield::from_be_bits(0x11_22_33_44);
882///     assert_eq!(from_be_bits.into_bits(), 0x11_22_33_44);
883///
884///     // from_be_bits_with_defaults - Creates a bitfield from bits assumed to be 
885///     // in big-endian order, respecting default values.
886///     let from_be_bits_with_defaults = Bitfield::from_be_bits_with_defaults(0x11_22_33_44);
887///     assert_eq!(
888///         from_be_bits_with_defaults.into_bits(),
889///         0x78_56_34_12,
890///     );
891/// }
892/// ```
893///
894/// **Array Backed Bitfield**:
895///
896/// | Method                                                                    | Endianness                                   | Description                                                                                                                                            |
897/// |---------------------------------------------------------------------------|----------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------|
898/// | `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`).                                                     |
899/// | `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.                                                        |
900/// | `from_le_bytes(bytes: [u8; N])`                                           | Little-endian                                | Creates a new bitfield instance from the given little-endian bytes, ignoring field defaults.                                                           |
901/// | `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.                                          |
902/// | `from_be_bytes(bytes: [u8; N])`                                           | Big-endian                                   | Creates a new bitfield instance from the given big-endian bytes, ignoring field defaults.                                                              |
903/// | `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.                                             |
904/// | `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.                                                                |
905/// | `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.                      |
906/// | `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.                                    |
907/// | `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.               |
908/// | `from_le_slice(slice: &[u8])`                                             | Little-endian                                | Creates a new bitfield instance from a little-endian byte slice. Shorter slices are padded with zero.                                                  |
909/// | `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.        |
910/// | `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.                      |
911/// | `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. |
912/// | `from_be_slice(slice: &[u8])`                                             | Big-endian                                   | Creates a new bitfield instance from a big-endian byte slice. Shorter slices are padded with zero.                                                     |
913/// | `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.           |
914/// | `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.                         |
915/// | `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.    |
916///
917/// ```rust
918/// # use bitfields_impl as bitfields;
919/// use bitfields::bitfield;
920///
921/// #[bitfield([u8; 4])]
922/// struct Packet {
923///     #[bits(default = 0x12)]
924///     a: u8,
925///     #[bits(default = 0x34)]
926///     b: u8,
927///     #[bits(default = 0x56)]
928///     c: u8,
929///     #[bits(default = 0x78)]
930///     _reserved: u8,
931/// }
932///
933/// fn main() {
934///     // from_bytes — default endian is big, ignoring field defaults.
935///     // In big-endian layout the last byte maps to the lowest bits (field `a`).
936///     let p = Packet::from_bytes([0x11, 0x22, 0x33, 0x44]);
937///     assert_eq!(p.a(), 0x44);
938///     assert_eq!(p.b(), 0x33);
939///     assert_eq!(p.c(), 0x22);
940///     assert_eq!(p.into_bytes(), [0x11, 0x22, 0x33, 0x44]);
941///
942///     // from_bytes_with_defaults — fields that have defaults keep their defaults.
943///     let p_defaults = Packet::from_bytes_with_defaults([0x11, 0x22, 0x33, 0x44]);
944///     assert_eq!(p_defaults.a(), 0x12);
945///     assert_eq!(p_defaults.b(), 0x34);
946///     assert_eq!(p_defaults.c(), 0x56);
947///
948///     // from_le_bytes — treats the byte array as little-endian.
949///     let p_le = Packet::from_le_bytes([0x44, 0x33, 0x22, 0x11]);
950///     assert_eq!(p_le.a(), 0x44);
951///     assert_eq!(p_le.b(), 0x33);
952///     assert_eq!(p_le.c(), 0x22);
953///
954///     // from_be_bytes — treats the byte array as big-endian (same as from_bytes default).
955///     let p_be = Packet::from_be_bytes([0x11, 0x22, 0x33, 0x44]);
956///     assert_eq!(p_be.a(), 0x44);
957///
958///     // from_slice — shorter slices are zero-padded; same endian rules as from_bytes.
959///     let p_slice = Packet::from_slice(&[0x11, 0x22, 0x33, 0x44]);
960///     assert_eq!(p_slice.a(), 0x44);
961///
962///     // checked_from_slice — returns an error when the slice is too small.
963///     assert!(Packet::checked_from_slice(&[0x11, 0x22]).is_err());
964///     assert!(Packet::checked_from_slice(&[0x11, 0x22, 0x33, 0x44]).is_ok());
965/// }
966/// ```
967///
968/// #### Into Bits
969///
970/// A bitfield can be converted into bits using the following APIs:
971///
972/// **Primitive Bitfield**:
973///
974/// | Method                | Endianness                                   | Description                                                            |
975/// |-----------------------|----------------------------------------------|------------------------------------------------------------------------|
976/// | `into_bits() -> N`    | Determined by `#[bitfield(into_endian = N)]` | Returns the raw bits of the bitfield (default `into_endian` is `big`). |
977/// | `into_le_bits() -> N` | Little-endian                                | Returns the bits of the bitfield in little-endian order.               |
978/// | `into_be_bits() -> N` | Big-endian                                   | Returns the bits of the bitfield in big-endian order.                  |
979///
980/// ```rust
981/// # use bitfields_impl as bitfields;
982/// use bitfields::bitfield;
983///
984/// #[bitfield(u32)]
985/// struct Bitfield {
986///     #[bits(default = 0x12)]
987///     a: u8,
988///     #[bits(default = 0x34)]
989///     b: u8,
990///     #[bits(default = 0x56)]
991///     c: u8,
992///     #[bits(default = 0x78)]
993///     d: u8,
994/// }
995///
996/// fn main() {
997///     let bitfield = Bitfield::new();
998///
999///     // into_bits: default into_endian (big) — most-significant field at the top byte.
1000///     assert_eq!(bitfield.into_bits(), 0x78_56_34_12);
1001///
1002///     // into_le_bits: byte-swaps the raw bits into little-endian order.
1003///     assert_eq!(bitfield.into_le_bits(), 0x12_34_56_78);
1004///
1005///     // into_be_bits: big-endian order (same as into_bits when into_endian defaults to big).
1006///     assert_eq!(bitfield.into_be_bits(), 0x78_56_34_12);
1007/// }
1008/// ```
1009///
1010/// **Array Backed Bitfield**:
1011///
1012/// | Method                                                        | Endianness                                   | Description                                                                                                           |
1013/// |---------------------------------------------------------------|----------------------------------------------|-----------------------------------------------------------------------------------------------------------------------|
1014/// | `into_bytes() -> [u8; N]`                                     | Determined by `#[bitfield(into_endian = N)]` | Returns the bytes of the bitfield as a `[u8; N]` array. Default is `big`.                                             |
1015/// | `into_le_bytes() -> [u8; N]`                                  | Little-endian                                | Returns the bytes of the bitfield in little-endian order.                                                             |
1016/// | `into_be_bytes() -> [u8; N]`                                  | Big-endian                                   | Returns the bytes of the bitfield in big-endian order.                                                                |
1017/// | `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.      |
1018/// | `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.                        |
1019/// | `into_le_slice(slice: &mut [u8])`                             | Little-endian                                | Writes the bitfield bytes in little-endian order into the provided slice.                                             |
1020/// | `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. |
1021/// | `into_be_slice(slice: &mut [u8])`                             | Big-endian                                   | Writes the bitfield bytes in big-endian order into the provided slice.                                                |
1022/// | `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.    |
1023///
1024/// ```rust
1025/// # use bitfields_impl as bitfields;
1026/// use bitfields::bitfield;
1027///
1028/// #[bitfield([u8; 4])]
1029/// struct Packet {
1030///     #[bits(default = 0x12)]
1031///     a: u8,
1032///     #[bits(default = 0x34)]
1033///     b: u8,
1034///     #[bits(default = 0x56)]
1035///     c: u8,
1036///     #[bits(default = 0x78)]
1037///     d: u8,
1038/// }
1039///
1040/// fn main() {
1041///     let packet = Packet::new();
1042///
1043///     // into_bytes: default into_endian (big) — most-significant byte first.
1044///     assert_eq!(packet.into_bytes(), [0x78, 0x56, 0x34, 0x12]);
1045///
1046///     // into_le_bytes: least-significant byte first.
1047///     assert_eq!(packet.into_le_bytes(), [0x12, 0x34, 0x56, 0x78]);
1048///
1049///     // into_be_bytes: most-significant byte first (same as default).
1050///     assert_eq!(packet.into_be_bytes(), [0x78, 0x56, 0x34, 0x12]);
1051///
1052///     // into_slice: writes up to slice.len() bytes.
1053///     let mut buf = [0u8; 4];
1054///     packet.into_slice(&mut buf);
1055///     assert_eq!(buf, [0x78, 0x56, 0x34, 0x12]);
1056///
1057///     // checked_into_slice: returns Err when the slice is too small.
1058///     let mut small = [0u8; 2];
1059///     assert!(packet.checked_into_slice(&mut small).is_err());
1060///
1061///     // into_le_slice / into_be_slice work the same but with explicit endian.
1062///     let mut le_buf = [0u8; 4];
1063///     packet.into_le_slice(&mut le_buf);
1064///     assert_eq!(le_buf, [0x12, 0x34, 0x56, 0x78]);
1065///
1066///     let mut be_buf = [0u8; 4];
1067///     packet.into_be_slice(&mut be_buf);
1068///     assert_eq!(be_buf, [0x78, 0x56, 0x34, 0x12]);
1069/// }
1070/// ```
1071///
1072/// #### Conversion Endian
1073///
1074/// Sometimes the outside world is outside our control, like the endianness of how
1075/// systems export data. Luckily, the endianness of the bitfield conversions can
1076/// be controlled by specifying the `#[bitfield(from_endian = N, into_endian = N)]`
1077/// args. The possible endianness options are `little` or `big`. By default, the endianness
1078/// of both is `big`.
1079///
1080/// This arg controls the endianness of the `from`, `into`, and `From` trait
1081/// conversions.
1082///
1083/// ```rust
1084/// # use bitfields_impl as bitfields;
1085/// use bitfields::bitfield;
1086///
1087/// #[bitfield(u32, from_endian = little, into_endian = big)]
1088/// struct Header {
1089///     version: u8,
1090///     flags: u8,
1091///     size: u8,
1092///     tag: u8,
1093/// }
1094///
1095/// fn main() {
1096///     // Device gave us bytes in little-endian order:
1097///     // [0x11, 0x22, 0x33, 0x44]
1098///     let h = Header::from_bits(0x1122_3344);
1099///
1100///     // from_endian = little means fields decode as:
1101///     assert_eq!(h.version(), 0x11);
1102///     assert_eq!(h.flags(), 0x22);
1103///     assert_eq!(h.size(), 0x33);
1104///     assert_eq!(h.tag(), 0x44);
1105///
1106///     // into_endian = big means output is big-endian representation.
1107///     assert_eq!(h.into_bits(), 0x4433_2211);
1108///
1109///     // Explicit conversion helpers still work:
1110///     let x = Header::from_le_bits(0xAABB_CCDD);
1111///     assert_eq!(x.version(), 0xAA);
1112///     assert_eq!(x.flags(), 0xBB);
1113///     assert_eq!(x.size(), 0xCC);
1114///     assert_eq!(x.tag(), 0xDD);
1115///
1116///     assert_eq!(x.into_be_bits(), 0xDDCC_BBAA);
1117///     assert_eq!(x.into_le_bits(), 0xAABB_CCDD);
1118/// }
1119/// ```
1120///
1121/// ```rust
1122/// # use bitfields_impl as bitfields;
1123/// use bitfields::bitfield;
1124///
1125/// #[bitfield([u8; 4], from_endian = little, into_endian = big)]
1126/// struct Header {
1127///     version: u8,
1128///     flags: u8,
1129///     size: u8,
1130///     tag: u8,
1131/// }
1132///
1133/// fn main() {
1134///     // Device gave us bytes in little-endian order:
1135///     // [0x11, 0x22, 0x33, 0x44]
1136///     let h = Header::from_bytes([0x11, 0x22, 0x33, 0x44]);
1137///
1138///     // from_endian = little means fields decode as:
1139///     assert_eq!(h.version(), 0x11);
1140///     assert_eq!(h.flags(), 0x22);
1141///     assert_eq!(h.size(), 0x33);
1142///     assert_eq!(h.tag(), 0x44);
1143///
1144///     // into_endian = big means output is big-endian representation.
1145///     assert_eq!(h.into_bytes(), [0x44, 0x33, 0x22, 0x11]);
1146///
1147///     // Explicit conversion helpers still work:
1148///     let x = Header::from_le_bytes([0xDD, 0xCC, 0xBB, 0xAA]);
1149///     assert_eq!(x.version(), 0xDD);
1150///     assert_eq!(x.flags(), 0xCC);
1151///     assert_eq!(x.size(), 0xBB);
1152///     assert_eq!(x.tag(), 0xAA);
1153///
1154///     assert_eq!(x.into_be_bytes(), [0xAA, 0xBB, 0xCC, 0xDD]);
1155///     assert_eq!(x.into_le_bytes(), [0xDD, 0xCC, 0xBB, 0xAA]);
1156/// }
1157/// ```
1158///
1159/// ### Bit Operations
1160///
1161/// The bitfield generates bitwise operations that make it easy to manipulate,
1162/// read, reset, and invert the backing bits without manually writing masks and
1163/// shifts.
1164///
1165/// #### Write Bits
1166///
1167/// Write bits allows you to write data to the writable bits of
1168/// the bitfield.
1169///
1170/// **Primitive Bitfield**:
1171///
1172/// | Function                               | Endianness                                    | Description                                                    |
1173/// |----------------------------------------|-----------------------------------------------|----------------------------------------------------------------|
1174/// | `write_bits(bits: N)`                  | Determined by `#[bitfield(write_endian = N)]` | Writes raw bits using `write_endian` (default is `big`).       |
1175/// | `write_bits_with_defaults(bits: N)`    | Determined by `#[bitfield(write_endian = N)]` | Writes raw bits, then reapplies defaults.                      |
1176/// | `write_le_bits(bits: N)`               | Little-endian                                 | Writes explicitly little-endian bits.                          |
1177/// | `write_le_bits_with_defaults(bits: N)` | Little-endian                                 | Writes explicitly little-endian bits, then reapplies defaults. |
1178/// | `write_be_bits(bits: N)`               | Big-endian                                    | Writes explicitly big-endian bits.                             |
1179/// | `write_be_bits_with_defaults(bits: N)` | Big-endian                                    | Writes explicitly big-endian bits, then reapplies defaults.    |
1180/// | `write_defaults()`                     | N/A                                           | Reapplies field defaults without replacing the whole bitfield. |
1181///
1182/// ```rust
1183/// # use bitfields_impl as bitfields;
1184/// use bitfields::bitfield;
1185///
1186/// #[bitfield(u32)]
1187/// struct Register {
1188///     #[bits(default = 0x12)]
1189///     low: u8,
1190///     data: u8,
1191///     #[bits(default = 0x78)]
1192///     _reserved: u8,
1193///     high: u8,
1194/// }
1195///
1196/// fn main() {
1197///     let mut reg = Register::new();
1198///     assert_eq!(reg.into_bits(), 0x00780012);
1199///
1200///     // write_bits — replaces all writable bits; reserved/read-only fields are preserved.
1201///     reg.write_bits(0xAA_BB_CC_DD);
1202///     assert_eq!(reg.low(), 0xDD);
1203///     assert_eq!(reg.data(), 0xCC);
1204///     assert_eq!(reg.high(), 0xAA);
1205///     // layout: high=0xAA | _reserved=0x78 | data=0xCC | low=0xDD
1206///     assert_eq!(reg.into_bits(), 0xAA78CCDD);
1207///
1208///     // write_bits_with_defaults — writes the new bits then reapplies field defaults.
1209///     reg.write_bits_with_defaults(0xAA_BB_CC_DD);
1210///     assert_eq!(reg.low(), 0x12); // default restored
1211///     assert_eq!(reg.data(), 0xCC); // no default, comes from the written value
1212///     // layout: high=0xAA | _reserved=0x78 | data=0xCC | low=0x12
1213///     assert_eq!(reg.into_bits(), 0xAA78CC12);
1214///
1215///     // write_le_bits — writes bits interpreted as little-endian.
1216///     reg.write_le_bits(0x11_22_33_44);
1217///     assert_eq!(reg.low(), 0x11);
1218///     assert_eq!(reg.data(), 0x22);
1219///     assert_eq!(reg.high(), 0x44);
1220///
1221///     // write_defaults — reapplies only field defaults without overwriting other fields.
1222///     reg.write_defaults();
1223///     assert_eq!(reg.low(), 0x12);
1224/// }
1225/// ```
1226///
1227/// **Array Backed Bitfield**:
1228///
1229/// | Function                                       | Endianness                                    | Description                                                     |
1230/// |------------------------------------------------|-----------------------------------------------|-----------------------------------------------------------------|
1231/// | `write_bytes(bytes: [u8; N])`                  | Determined by `#[bitfield(write_endian = N)]` | Writes raw bytes using `write_endian` (default is `big`).       |
1232/// | `write_bytes_with_defaults(bytes: [u8; N])`    | Determined by `#[bitfield(write_endian = N)]` | Writes raw bytes, then reapplies defaults.                      |
1233/// | `write_le_bytes(bytes: [u8; N])`               | Little-endian                                 | Writes explicitly little-endian bytes.                          |
1234/// | `write_le_bytes_with_defaults(bytes: [u8; N])` | Little-endian                                 | Writes explicitly little-endian bytes, then reapplies defaults. |
1235/// | `write_be_bytes(bytes: [u8; N])`               | Big-endian                                    | Writes explicitly big-endian bytes.                             |
1236/// | `write_be_bytes_with_defaults(bytes: [u8; N])` | Big-endian                                    | Writes explicitly big-endian bytes, then reapplies defaults.    |
1237/// | `write_defaults()`                             | N/A                                           | Reapplies field defaults without replacing the whole bitfield.  |
1238///
1239/// ```rust
1240/// # use bitfields_impl as bitfields;
1241/// use bitfields::bitfield;
1242///
1243/// #[bitfield(u32)]
1244/// struct Register {
1245///     #[bits(default = 0x12)]
1246///     low: u8,
1247///     #[bits(default = 0x34, access = ro)]
1248///     status: u8,
1249///     data: u8,
1250///     #[bits(default = 0x78)]
1251///     _reserved: u8,
1252/// }
1253///
1254/// fn main() {
1255///     let mut register = Register::new();
1256///     assert_eq!(register.into_bits(), 0x78003412);
1257///
1258///     register.write_bits(0x11223344);
1259///
1260///     // Writable fields are updated from the incoming bits.
1261///     assert_eq!(register.low(), 0x44);
1262///     assert_eq!(register.data(), 0x22);
1263///
1264///     // Read-only and reserved fields keep their original/default values.
1265///     assert_eq!(register.status(), 0x34);
1266///     assert_eq!(register.into_bits(), 0x78223444);
1267///
1268///     // `write_bits_with_defaults` writes first, then restores fields that have
1269///     // defaults. `low`, `status`, and `_reserved` all keep their defaults.
1270///     register.write_bits_with_defaults(0xAABBCCDD);
1271///     assert_eq!(register.low(), 0x12);
1272///     assert_eq!(register.status(), 0x34);
1273///     assert_eq!(register.data(), 0xBB);
1274///     assert_eq!(register.into_bits(), 0x78BB3412);
1275/// }
1276/// ```
1277///
1278/// Use `write_endian` to configure the default endian used by `write_bits` or
1279/// `write_bytes`. The explicit helpers always use the endian in their name.
1280///
1281/// ```rust
1282/// # use bitfields_impl as bitfields;
1283/// use bitfields::bitfield;
1284///
1285/// #[bitfield(u32, write_endian = little)]
1286/// struct Header {
1287///     version: u8,
1288///     flags: u8,
1289///     size: u8,
1290///     tag: u8,
1291/// }
1292///
1293/// fn main() {
1294///     let mut header = Header::new();
1295///
1296///     // `write_endian = little` makes `write_bits` interpret the input as
1297///     // little-endian. This is equivalent to calling `write_le_bits`.
1298///     header.write_bits(0x1122_3344);
1299///     assert_eq!(header.version(), 0x11);
1300///     assert_eq!(header.flags(), 0x22);
1301///     assert_eq!(header.size(), 0x33);
1302///     assert_eq!(header.tag(), 0x44);
1303///
1304///     // Explicit endian helpers ignore the configured default.
1305///     header.write_be_bits(0xAABB_CCDD);
1306///     assert_eq!(header.version(), 0xDD);
1307///     assert_eq!(header.flags(), 0xCC);
1308///     assert_eq!(header.size(), 0xBB);
1309///     assert_eq!(header.tag(), 0xAA);
1310/// }
1311/// ```
1312///
1313/// #### Get/Set Bits
1314///
1315/// Single-bit helpers let you read or write one bit at a time. These helpers behave
1316/// the same for both primitive and array-backed bitfields.
1317///
1318/// **Primitive & Array Backed Bitfields**:
1319///
1320/// | Function                                                      | Checked / Unchecked | Description                                                                                                       |
1321/// |---------------------------------------------------------------|---------------------|-------------------------------------------------------------------------------------------------------------------|
1322/// | `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.        |
1323/// | `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. |
1324/// | `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.                  |
1325/// | `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.   |
1326///
1327/// Unchecked helpers are convenient for quick probing. Checked helpers are better
1328/// when invalid offsets or inaccessible fields should be treated as errors.
1329///
1330/// ```rust
1331/// # use bitfields_impl as bitfields;
1332/// use bitfields::bitfield;
1333///
1334/// #[bitfield(u8, bit_ops = true)]
1335/// struct Control {
1336///     #[bits(2, default = 0b11)]
1337///     mode: u8,
1338///
1339///     #[bits(2)]
1340///     flags: u8,
1341///
1342///     #[bits(2, default = 0b10, access = wo)]
1343///     command: u8,
1344///
1345///     #[bits(2, default = 0b01)]
1346///     _reserved: u8,
1347/// }
1348///
1349/// fn main() {
1350///     let mut control = Control::new();
1351///
1352///     assert!(control.get_bit(Control::MODE_OFFSET));
1353///     assert!(control.get_bit(Control::MODE_OFFSET + 1));
1354///     assert!(!control.get_bit(Control::FLAGS_OFFSET));
1355///
1356///     // `command` is write-only, so unchecked reads return false and checked
1357///     // reads return an error.
1358///     assert!(!control.get_bit(Control::COMMAND_OFFSET));
1359///     assert!(control.checked_get_bit(Control::COMMAND_OFFSET).is_err());
1360///
1361///     control.set_bit(Control::FLAGS_OFFSET, true);
1362///     control.set_bit(Control::FLAGS_OFFSET + 1, true);
1363///     assert_eq!(control.flags(), 0b11);
1364///
1365///     // Reserved bits are not writable. Unchecked writes are no-ops, while
1366///     // checked writes return an error.
1367///     control.set_bit(6, false);
1368///     assert!(control.get_bit(6));
1369///     assert!(control.checked_set_bit(6, false).is_err());
1370///
1371///     // Out-of-bounds unchecked reads return false; checked reads return an error.
1372///     assert!(!control.get_bit(99));
1373///     assert!(control.checked_get_bit(99).is_err());
1374/// }
1375/// ```
1376///
1377/// **Primitive Bitfield range helpers**:
1378///
1379/// | Function                                                                      | Checked / Unchecked | Description                                                                                                 |
1380/// |-------------------------------------------------------------------------------|---------------------|-------------------------------------------------------------------------------------------------------------|
1381/// | `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.                                 |
1382/// | `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.                          |
1383/// | `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.                       |
1384/// | `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. |
1385///
1386/// ```rust
1387/// # use bitfields_impl as bitfields;
1388/// use bitfields::bitfield;
1389///
1390/// #[bitfield(u16, bit_ops = true)]
1391/// struct Flags {
1392///     #[bits(4)]
1393///     mode: u8,
1394///
1395///     #[bits(4, default = 0xA)]
1396///     status: u8,
1397///
1398///     #[bits(4, access = ro)]
1399///     control: u8,
1400///
1401///     #[bits(4)]
1402///     extra: u8,
1403/// }
1404///
1405/// fn main() {
1406///     let mut flags = Flags::new();
1407///
1408///     // set_bits_range — sets `len` bits starting at `offset` to the given value.
1409///     flags.set_bits_range(Flags::MODE_OFFSET, Flags::MODE_BITS, 0x5);
1410///     assert_eq!(flags.mode(), 0x5);
1411///
1412///     // get_bits_range — reads `len` bits starting at `offset`, shifted to bit 0.
1413///     assert_eq!(flags.get_bits_range(Flags::MODE_OFFSET, Flags::MODE_BITS), 0x5);
1414///     assert_eq!(flags.get_bits_range(Flags::STATUS_OFFSET, Flags::STATUS_BITS), 0xA);
1415///
1416///     // Unchecked range writes silently skip protected (read-only) bits.
1417///     flags.set_bits_range(Flags::CONTROL_OFFSET, 8, 0xFF);
1418///     assert_eq!(flags.extra(), 0xF); // extra bits written
1419///     assert_eq!(flags.control(), 0x0); // read-only bits are unchanged
1420///
1421///     // checked_set_bits_range — returns an error if any bit in the range is protected.
1422///     assert!(flags.checked_set_bits_range(Flags::CONTROL_OFFSET, 8, 0xFF).is_err());
1423///
1424///     // checked_get_bits_range — returns an error if the range is out of bounds.
1425///     assert!(flags.checked_get_bits_range(12, 8).is_err());
1426/// }
1427/// ```
1428///
1429/// **Array Backed Bitfield range helpers**:
1430///
1431/// | Function                                                                             | Checked / Unchecked | Description                                                                                                   |
1432/// |--------------------------------------------------------------------------------------|---------------------|---------------------------------------------------------------------------------------------------------------|
1433/// | `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.                              |
1434/// | `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. |
1435/// | `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.                                       |
1436/// | `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.        |
1437///
1438/// ```rust
1439/// # use bitfields_impl as bitfields;
1440/// use bitfields::bitfield;
1441///
1442/// #[bitfield(u16, bit_ops = true)]
1443/// struct PacketWord {
1444///     low: u8,
1445///
1446///     #[bits(4)]
1447///     counter: u8,
1448///
1449///     #[bits(4, default = 0xF, access = ro)]
1450///     status: u8,
1451/// }
1452///
1453/// fn main() {
1454///     let mut packet = PacketWord::new();
1455///
1456///     packet.set_bits_range(PacketWord::LOW_OFFSET, PacketWord::LOW_BITS, 0xAB);
1457///     packet.set_bits_range(PacketWord::COUNTER_OFFSET, PacketWord::COUNTER_BITS, 0x5);
1458///
1459///     assert_eq!(packet.low(), 0xAB);
1460///     assert_eq!(packet.counter(), 0x5);
1461///     assert_eq!(packet.get_bits_range(PacketWord::LOW_OFFSET, PacketWord::LOW_BITS), 0xAB);
1462///     assert_eq!(packet.into_bits(), 0xF5AB);
1463///
1464///     // Unchecked range writes skip protected bits.
1465///     packet.set_bits_range(PacketWord::COUNTER_OFFSET, 8, 0x00);
1466///     assert_eq!(packet.counter(), 0x0);
1467///     assert_eq!(packet.status(), 0xF);
1468///
1469///     // Checked range writes fail if any bit in the range is protected.
1470///     assert!(packet.checked_set_bits_range(PacketWord::COUNTER_OFFSET, 8, 0x00).is_err());
1471/// }
1472/// ```
1473///
1474/// For array-backed bitfields, range values are packed starting at bit `0` of the
1475/// provided or returned array.
1476///
1477/// ```rust
1478/// # use bitfields_impl as bitfields;
1479/// use bitfields::bitfield;
1480///
1481/// #[bitfield([u8; 2], bit_ops = true)]
1482/// struct PacketBytes {
1483///     low: u8,
1484///     high: u8,
1485/// }
1486///
1487/// fn main() {
1488///     let mut packet = PacketBytes::new();
1489///
1490///     packet.set_bytes_range(PacketBytes::LOW_OFFSET, 12, [0xBC, 0x0A]);
1491///
1492///     assert_eq!(packet.low(), 0xBC);
1493///     assert_eq!(packet.high(), 0x0A);
1494///     assert_eq!(packet.get_bytes_range(PacketBytes::LOW_OFFSET, 12), [0xBC, 0x0A]);
1495///     assert_eq!(packet.into_le_bytes(), [0xBC, 0x0A]);
1496/// }
1497/// ```
1498///
1499/// #### Clear Bits
1500///
1501/// Clear helpers reset either the whole bitfield or individual writable fields.
1502///
1503/// **Primitive Bitfield**:
1504///
1505/// | Function                     | Description                                                                                |
1506/// |------------------------------|--------------------------------------------------------------------------------------------|
1507/// | `clear_bits()`               | Resets the bitfield to its zero representation (except reserved fields with defaults).     |
1508/// | `clear_bits_with_defaults()` | Resets the bitfield and then restores all field defaults.                                  |
1509/// | `clear_<field>()`            | Clears the specific writable field to zero. (Generated per writable field)                 |
1510/// | `clear_<field>_to_default()` | Restores the specific writable field's default value. (Generated per field with a default) |
1511///
1512/// ```rust
1513/// # use bitfields_impl as bitfields;
1514/// use bitfields::bitfield;
1515///
1516/// #[bitfield(u32)]
1517/// struct Flags {
1518///     #[bits(default = 0x12)]
1519///     enabled: u8,
1520///
1521///     count: u8,
1522///
1523///     #[bits(default = 0x56)]
1524///     priority: u8,
1525///
1526///     #[bits(default = 0x78)]
1527///     _reserved: u8,
1528/// }
1529///
1530/// fn main() {
1531///     let mut flags = FlagsBuilder::new()
1532///         .with_enabled(0xFF)
1533///         .with_count(0x34)
1534///         .with_priority(0xAB)
1535///         .build();
1536///     assert_eq!(flags.into_bits(), 0x78AB34FF);
1537///
1538///     // clear_<field> — zeroes out a single writable field.
1539///     flags.clear_count();
1540///     assert_eq!(flags.count(), 0);
1541///
1542///     // clear_<field>_to_default — restores a single field to its default value.
1543///     flags.clear_enabled_to_default();
1544///     assert_eq!(flags.enabled(), 0x12);
1545///
1546///     // clear_bits — zeroes all writable bits; reserved fields keep their defaults.
1547///     flags.clear_bits();
1548///     assert_eq!(flags.enabled(), 0);
1549///     assert_eq!(flags.count(), 0);
1550///     assert_eq!(flags.priority(), 0);
1551///     assert_eq!(flags.into_bits(), 0x78000000); // _reserved keeps its default
1552///
1553///     // clear_bits_with_defaults — zeroes everything then restores field defaults.
1554///     flags.set_count(0x99);
1555///     flags.clear_bits_with_defaults();
1556///     assert_eq!(flags.enabled(), 0x12);
1557///     assert_eq!(flags.count(), 0);
1558///     assert_eq!(flags.priority(), 0x56);
1559///     assert_eq!(flags.into_bits(), 0x78560012);
1560/// }
1561/// ```
1562///
1563/// **Array Backed Bitfield**:
1564///
1565/// | Function                      | Description                                                                                |
1566/// |-------------------------------|--------------------------------------------------------------------------------------------|
1567/// | `clear_bytes()`               | Resets the bitfield bytes to zero (except reserved fields with defaults).                  |
1568/// | `clear_bytes_with_defaults()` | Resets the bitfield bytes and then restores all field defaults.                            |
1569/// | `clear_<field>()`             | Clears the specific writable field to zero. (Generated per writable field)                 |
1570/// | `clear_<field>_to_default()`  | Restores the specific writable field's default value. (Generated per field with a default) |
1571///
1572/// ```rust
1573/// # use bitfields_impl as bitfields;
1574/// use bitfields::bitfield;
1575///
1576/// #[bitfield([u8; 4])]
1577/// struct Flags {
1578///     #[bits(default = 0x12)]
1579///     enabled: u8,
1580///
1581///     count: u8,
1582///
1583///     #[bits(default = 0x56, access = ro)]
1584///     status: u8,
1585///
1586///     #[bits(default = 0x78)]
1587///     _reserved: u8,
1588/// }
1589///
1590/// fn main() {
1591///     let mut flags = FlagsBuilder::new().with_count(0x34).build();
1592///     assert_eq!(flags.into_bytes(), [0x78, 0x56, 0x34, 0x12]);
1593///
1594///     flags.clear_enabled();
1595///     assert_eq!(flags.enabled(), 0);
1596///
1597///     flags.clear_enabled_to_default();
1598///     assert_eq!(flags.enabled(), 0x12);
1599///
1600///     flags.clear_bytes();
1601///     assert_eq!(flags.enabled(), 0);
1602///     assert_eq!(flags.count(), 0);
1603///     assert_eq!(flags.status(), 0);
1604///     assert_eq!(flags.into_bytes(), [0x78, 0, 0, 0]);
1605///
1606///     flags.clear_bytes_with_defaults();
1607///     assert_eq!(flags.enabled(), 0x12);
1608///     assert_eq!(flags.count(), 0);
1609///     assert_eq!(flags.status(), 0x56);
1610///     assert_eq!(flags.into_bytes(), [0x78, 0x56, 0, 0x12]);
1611/// }
1612/// ```
1613///
1614/// #### Invert Bits
1615///
1616/// Invert helpers flip writable bits while preserving protected bits. They are
1617/// useful for toggling flags, building masks, and inspecting the complement of a
1618/// field without manually calculating a field-sized mask.
1619///
1620/// **Primitive Bitfield**:
1621///
1622/// | Function                  | Description                                                                                                   |
1623/// |---------------------------|---------------------------------------------------------------------------------------------------------------|
1624/// | `invert_bits()`           | Flips every writable bit in the primitive bitfield (read-only and reserved fields are untouched).             |
1625/// | `invert_<field>()`        | Mutates a writable field by flipping only its bits. (Generated per writable field)                            |
1626/// | `<field>_inverted() -> T` | Returns the field value with its bits inverted, without mutating the bitfield. (Generated per readable field) |
1627///
1628/// ```rust
1629/// # use bitfields_impl as bitfields;
1630/// use bitfields::bitfield;
1631///
1632/// #[bitfield(u16, bit_ops = true)]
1633/// struct Control {
1634///     #[bits(4, default = 0b0101)]
1635///     mode: u8,
1636///
1637///     #[bits(4, default = 0b1010)]
1638///     flags: u8,
1639///
1640///     #[bits(8, default = 0xA5, access = ro)]
1641///     checksum: u8,
1642/// }
1643///
1644/// fn main() {
1645///     let mut control = Control::new();
1646///
1647///     // <field>_inverted() — returns the inverted value without mutating the bitfield.
1648///     assert_eq!(control.mode_inverted(), 0b1010); // inverted within 4 bits
1649///     assert_eq!(control.flags_inverted(), 0b0101);
1650///     assert_eq!(control.mode(), 0b0101); // original value unchanged
1651///
1652///     // invert_<field>() — flips only the bits of a single writable field.
1653///     control.invert_mode();
1654///     assert_eq!(control.mode(), 0b1010);
1655///
1656///     // invert_bits() — flips all writable bits; read-only fields are preserved.
1657///     control.invert_bits();
1658///     assert_eq!(control.mode(), 0b0101);   // back to original
1659///     assert_eq!(control.flags(), 0b0101);  // also inverted
1660///     assert_eq!(control.checksum(), 0xA5); // read-only, untouched
1661/// }
1662/// ```
1663///
1664/// **Array Backed Bitfield**:
1665///
1666/// | Function                  | Description                                                                                                   |
1667/// |---------------------------|---------------------------------------------------------------------------------------------------------------|
1668/// | `invert_bytes()`          | Flips every writable bit in the array-backed bitfield (read-only and reserved fields are untouched).          |
1669/// | `invert_<field>()`        | Mutates a writable field by flipping only its bits. (Generated per writable field)                            |
1670/// | `<field>_inverted() -> T` | Returns the field value with its bits inverted, without mutating the bitfield. (Generated per readable field) |
1671///
1672/// The inversion is limited to the field width. For example, inverting a 5-bit
1673/// field value `0b01100` returns `0b10011`, not an 8-bit `0b11110011`.
1674///
1675/// ```rust
1676/// # use bitfields_impl as bitfields;
1677/// use bitfields::bitfield;
1678///
1679/// #[bitfield([u8; 2], bit_ops = true)]
1680/// struct Mask {
1681///     #[bits(5, default = 0b0_1100)]
1682///     pattern: u8,
1683///
1684///     #[bits(1, default = true)]
1685///     enabled: bool,
1686///
1687///     #[bits(2)]
1688///     flags: u8,
1689///
1690///     #[bits(8, default = 0xA5, access = ro)]
1691///     checksum: u8,
1692/// }
1693///
1694/// fn main() {
1695///     let mut mask = Mask::new();
1696///
1697///     assert_eq!(mask.pattern(), 0b0_1100);
1698///     assert_eq!(mask.pattern_inverted(), 0b1_0011);
1699///     assert!(!mask.enabled_inverted());
1700///
1701///     mask.invert_pattern();
1702///     assert_eq!(mask.pattern(), 0b1_0011);
1703///
1704///     mask.invert_enabled();
1705///     assert!(!mask.enabled());
1706///
1707///     mask.invert_bytes();
1708///
1709///     // Writable fields are inverted.
1710///     assert_eq!(mask.pattern(), 0b0_1100);
1711///     assert!(mask.enabled());
1712///     assert_eq!(mask.flags(), 0b11);
1713///
1714///     // Read-only fields are preserved.
1715///     assert_eq!(mask.checksum(), 0xA5);
1716/// }
1717/// ```
1718///
1719/// ### Passing Attributes
1720///
1721/// Attributes below the `#[bitfield]` attribute are passed to the generated struct.
1722///
1723/// ```rust
1724/// # use bitfields_impl as bitfields;
1725/// use bitfields::bitfield;
1726///
1727/// #[bitfield(u32)]
1728/// #[derive(Hash)]
1729/// struct Bitfield {
1730///     a: u32,
1731/// }
1732/// ```
1733///
1734/// ### Ignored Fields
1735///
1736/// Fields with the `#[bits(ignore = true)]` are ignored and not included
1737/// in the bitfield. This is useful for when you are building a custom
1738/// bitfield, but want to wrap bitfield in a parent struct to add additional
1739/// non-bitfield fields.
1740///
1741/// All ignored fields must implement the `Default` trait. Ignored fields
1742/// are accessible, and you can control their visibility like normal fields.
1743///
1744/// Take note that using ignored fields removes some constant guarantees.
1745///
1746/// ```rust
1747/// # use bitfields_impl as bitfields;
1748/// use bitfields::bitfield;
1749///
1750/// #[bitfield(u16)]
1751/// struct Bitfield {
1752///     a: u8,
1753///     b: u8,
1754///     #[bits(ignore = true)] /// Ignored field.
1755///     field_id: u8,
1756///     #[bits(ignore = true)] /// Ignored field.
1757///     pub(crate) custom_type: CustomType,
1758/// }
1759///
1760/// #[derive(Debug, Default, Clone, Copy, PartialEq)]
1761/// enum CustomType {
1762///     #[default]
1763///     A,
1764///     B,
1765/// }
1766///
1767/// fn main() {
1768///     let bitfield = Bitfield::new();
1769///
1770///     assert_eq!(bitfield.field_id, 0); // Ignored fields can be accessed directly.
1771///     assert_eq!(bitfield.custom_type, CustomType::A); // Ignored fields can be
1772///     // accessed directly.
1773/// }
1774/// ```
1775///
1776/// ### Visibility
1777///
1778/// Visibility applied to structs and fields determine the visibility of the
1779/// generated struct and field accessors.
1780///
1781/// ```rust
1782/// # use bitfields_impl as bitfields;
1783/// use bitfields::bitfield;
1784///
1785/// #[bitfield(u16)]
1786/// pub struct Bitfield { // The struct is public, so `Bitfield` is public.
1787///     pub a: u8, // `a` is public, so `a()` is public.
1788///     b: u8,     // `b` is private, so `b()` is private.
1789/// }
1790/// ```
1791///
1792/// ### Default Implementations
1793///
1794/// #### Debug Trait
1795///
1796/// A debug implementation is generated for the bitfield, which prints the fields
1797/// and their values.
1798///
1799/// ```rust
1800/// # use bitfields_impl as bitfields;
1801/// use bitfields::bitfield;
1802///
1803/// #[bitfield(u32)]
1804/// struct Bitfield {
1805///     #[bits(default = 0x12)]
1806///     a: u8,
1807///     #[bits(default = 0x34)]
1808///     b: u8,
1809///     #[bits(default = 0x56)]
1810///     c: u8,
1811///     #[bits(default = 0x78)]
1812///     d: u8,
1813/// }
1814///
1815/// fn main() {
1816///     let bitfield = Bitfield::new();
1817///
1818///     assert_eq!(format!("{:?}", bitfield), "Bitfield { a: 18, b: 52, c: 86, d: 120 }");
1819/// }
1820/// ```
1821///
1822/// #### Default Trait
1823///
1824/// A default implementation is generated for the bitfield, which initializes the
1825/// bitfield to zero and sets default values. This can be disabled by specifying
1826/// `#[bitfield(default = false)]` on the bitfield.
1827///
1828/// ```rust
1829/// # use bitfields_impl as bitfields;
1830/// use bitfields::bitfield;
1831///
1832/// #[bitfield(u16)]
1833/// struct Bitfield {
1834///     #[bits(default = 0x12)]
1835///     a: u8,
1836///     b: u8,
1837/// }
1838///
1839/// fn main() {
1840///     let bitfield = Bitfield::default();
1841///
1842///     assert_eq!(bitfield.a(), 0x12);
1843///     assert_eq!(bitfield.b(), 0);
1844/// }
1845/// ```
1846///
1847/// #### From/Into Trait
1848///
1849/// From and Into trait implementations are generated for the bitfield, which
1850/// convert to and from the bitfield type. This can be disabled by specifying
1851/// `#[bitfield(from_traits = false)]` on the bitfield.
1852///
1853/// ```rust
1854/// # use bitfields_impl as bitfields;
1855/// use bitfields::bitfield;
1856///
1857/// #[bitfield(u16)] /// From<u16> and Into<u16> are generated for this bitfield.
1858/// struct Bitfield {
1859///     low: u8,
1860///     high: u8,
1861/// }
1862///
1863/// fn main() {
1864///     // `From<u16> for Bitfield`
1865///     let bitfield = Bitfield::from(0xABCD_u16);
1866///     assert_eq!(bitfield.low(), 0xCD);
1867///     assert_eq!(bitfield.high(), 0xAB);
1868///
1869///     // `From<Bitfield> for u16`
1870///     let bits = u16::from(bitfield);
1871///     assert_eq!(bits, 0xABCD);
1872///
1873///     // Equivalent `Into` usage
1874///     let bitfield_from_into: Bitfield = 0x1234_u16.into();
1875///     let bits_from_into: u16 = bitfield_from_into.into();
1876///     assert_eq!(bits_from_into, 0x1234);
1877/// }
1878/// ```
1879///
1880/// ```rust
1881/// # use bitfields_impl as bitfields;
1882/// use bitfields::bitfield;
1883///
1884/// #[bitfield([u8; 2]
1885/// )] /// From<[u8; 2]> and Into<[u8; 2]> are generated for this bitfield.
1886/// struct Bitfield {
1887///     low: u8,
1888///     high: u8,
1889/// }
1890///
1891/// fn main() {
1892///     // `From<[u8; 2]> for Bitfield`
1893///     let bitfield = Bitfield::from([0xAB, 0xCD]);
1894///     assert_eq!(bitfield.low(), 0xCD);
1895///     assert_eq!(bitfield.high(), 0xAB);
1896///
1897///     // `From<Bitfield> for [u8; 2]`
1898///     let bytes = <[u8; 2]>::from(bitfield);
1899///     assert_eq!(bytes, [0xAB, 0xCD]);
1900///
1901///     // Equivalent `Into` usage
1902///     let bitfield_from_into: Bitfield = [0x12, 0x34].into();
1903///     let bytes_from_into: [u8; 2] = bitfield_from_into.into();
1904///     assert_eq!(bytes_from_into, [0x12, 0x34]);
1905/// }
1906/// ```
1907///
1908/// ### Bitfield Internal Value
1909///
1910/// The internal value of the bitfield is stored as either a tuple struct where it's
1911/// the first parameter, or as a field named `val` if ignored fields are present.
1912/// This allows you to access the internal value of the bitfield directly if needed,
1913/// but it is recommended to use the provided APIs to access and modify the
1914/// bitfield.
1915///
1916/// ```rust
1917/// # use bitfields_impl as bitfields;
1918/// use bitfields::bitfield;
1919///
1920/// #[bitfield(u16)]
1921/// struct TupleBitfield {
1922///     low: u8,
1923///     high: u8,
1924/// }
1925///
1926/// #[bitfield(u16)]
1927/// struct ValBitfield {
1928///     low: u8,
1929///     high: u8,
1930///     #[bits(ignore = true)]
1931///     tag: u8,
1932/// }
1933///
1934/// fn main() {
1935///     let tuple_bf = TupleBitfield::new();
1936///     println!("{}", tuple_bf.0);
1937///
1938///     let val_bf = ValBitfield::new();
1939///     println!("{:?}", val_bf.val);
1940/// }
1941/// ```
1942///
1943/// ### Configuration
1944///
1945/// Bitfields can be configured with arguments passed to the `#[bitfield(...)]`
1946/// attribute. The first argument is always the backing storage type; every other
1947/// argument is named.
1948///
1949/// Boolean arguments accept `true` or `false`. The defaults below are the defaults
1950/// when no Cargo feature overrides are enabled. Per-bitfield attribute arguments
1951/// override Cargo feature defaults.
1952///
1953/// ```rust,ignore
1954/// # use bitfields_impl as bitfields;
1955/// use bitfields::bitfield;
1956///
1957/// #[bitfield(
1958///     u32,
1959///     order = lsb,
1960///     from_endian = big,
1961///     into_endian = big,
1962///     write_endian = big,
1963///     new = true,
1964///     from_into_bits = true,
1965///     from_traits = true,
1966///     default = true,
1967///     debug = true,
1968///     copy = true,
1969///     builder = true,
1970///     bit_ops = true,
1971///     write_bit_ops = true,
1972///     clear_bit_ops = true,
1973///     set_get_bit_ops = true,
1974///     invert_bit_ops = true,
1975///     toggle_bit_ops = true,
1976///     array_heap = false,
1977/// )]
1978/// struct Example {
1979///     a: u32,
1980/// }
1981/// ```
1982///
1983/// | Argument          | Values                                          | Default  | Description                                                                                                                                                                                                                                                                                                      |
1984/// |-------------------|-------------------------------------------------|----------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
1985/// | `<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.                                                |
1986/// | `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.                                                                                                         |
1987/// | `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.                                                                                                                               |
1988/// | `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.                                                                                                                               |
1989/// | `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.                                                                                                                                   |
1990/// | `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.                                                                                       |
1991/// | `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.                               |
1992/// | `from_traits`     | `true`, `false`                                 | `true`   | Generates `From<Backing> for Bitfield` and `From<Bitfield> for Backing`. These conversions use `from_endian` and `into_endian`.                                                                                                                                                                                  |
1993/// | `default`         | `true`, `false`                                 | `true`   | Generates `Default` for the bitfield. The default value is equivalent to `new()`: zero-initialized storage with field defaults applied.                                                                                                                                                                          |
1994/// | `debug`           | `true`, `false`                                 | `true`   | Generates `core::fmt::Debug` for the bitfield. The implementation prints readable fields and their values.                                                                                                                                                                                                       |
1995/// | `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`.                                                                                                                                                 |
1996/// | `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.                                                                                                                                          |
1997/// | `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`.                                                                                                                                                   |
1998/// | `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.                                                                        |
1999/// | `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()`.                                                                                           |
2000/// | `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).                                          |
2001/// | `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.                                                                                                                                                               |
2002/// | `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.                                                                                                                                 |
2003/// | `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. |
2004///
2005/// ```rust
2006/// # use bitfields_impl as bitfields;
2007/// use bitfields::bitfield;
2008///
2009/// // Demonstrates a selection of configuration arguments.
2010/// #[bitfield(
2011///     u32,
2012///     order = msb,           // first struct field occupies the most-significant bits
2013///     from_endian = little,  // from_bits / From<u32> treat raw bits as little-endian
2014///     into_endian = big,     // into_bits / From<Bitfield> emit big-endian bits
2015///     default = true,        // generate Default impl
2016///     debug = true,          // generate Debug impl
2017///     builder = true,        // generate <Struct>Builder
2018///     bit_ops = false,       // disable all bit-operation helpers
2019/// )]
2020/// struct Config {
2021///     #[bits(default = 0x12)]
2022///     tag: u8,
2023///     #[bits(default = 0x34)]
2024///     flags: u8,
2025///     #[bits(default = 0x56)]
2026///     size: u8,
2027///     #[bits(default = 0x78)]
2028///     checksum: u8,
2029/// }
2030///
2031/// fn main() {
2032///     // With order = msb, `tag` occupies bits 31..=24 and `checksum` occupies bits 7..=0.
2033///     let cfg = Config::new();
2034///     assert_eq!(cfg.tag(), 0x12);
2035///     assert_eq!(cfg.flags(), 0x34);
2036///     assert_eq!(cfg.size(), 0x56);
2037///     assert_eq!(cfg.checksum(), 0x78);
2038///
2039///     // into_endian = big: the raw u32 is big-endian (tag at top byte).
2040///     assert_eq!(cfg.into_bits(), 0x12_34_56_78);
2041///
2042///     // from_endian = little: raw bits are interpreted as little-endian before decoding.
2043///     let cfg2 = Config::from_bits(0x12_34_56_78);
2044///     assert_eq!(cfg2.checksum(), 0x12); // 0x12 is now the LSB (checksum field in msb order)
2045/// }
2046/// ```
2047///
2048/// #### Bit Operations Config
2049///
2050/// The `bit_ops` argument is a master switch for the bit-operation groups:
2051///
2052/// - `#[bitfield(u32, bit_ops = false)]` disables all bit operations.
2053/// - `#[bitfield(u32, bit_ops = true, set_get_bit_ops = false)]` enables bit
2054///   operations except the set/get bit group.
2055/// - `#[bitfield(u32, bit_ops = false, set_get_bit_ops = true)]` disables the
2056///   master switch but explicitly opts the set/get bit group back in.
2057///
2058/// This lets you generate only the bit-operation APIs you need.
2059///
2060/// #### Global Cargo Feature Flags
2061///
2062/// If you find yourself applying the same configuration arguments to many bitfields
2063/// in your codebase,
2064/// you can set those defaults globally with Cargo features:
2065///
2066/// - Constructors: `generate_new` / `disable_new`
2067/// - From/into functions: `generate_from_into_bits` /
2068///   `disable_from_into_bits`
2069/// - From traits: `generate_from_traits` / `disable_from_traits`
2070/// - Default trait: `generate_default` / `disable_default`
2071/// - Debug trait: `generate_debug` / `disable_debug`
2072/// - Copy/Clone derives: `derive_copy` / `disable_copy`
2073/// - Builder: `generate_builder` / `disable_builder`
2074/// - All bit operations: `generate_bit_ops` / `disable_bit_ops`
2075/// - Write bit operations: `generate_write_bit_ops` /
2076///   `disable_write_bit_ops`
2077/// - Clear bit operations: `generate_clear_bit_ops` /
2078///   `disable_clear_bit_ops`
2079/// - Set/get bit operations: `generate_set_get_bit_ops` /
2080///   `disable_set_get_bit_ops`
2081/// - Invert bit operations: `generate_invert_bit_ops` /
2082///   `disable_invert_bit_ops`
2083/// - Toggle bit operations: `generate_toggle_bit_ops` /
2084///   `disable_toggle_bit_ops`
2085///
2086/// Endian and order defaults have dedicated feature names:
2087///
2088/// - `order_lsb` / `order_msb`
2089/// - `from_endian_little` / `from_endian_big`
2090/// - `into_endian_little` / `into_endian_big`
2091/// - `write_endian_little` / `write_endian_big`
2092///
2093/// Bitflags can also be configured globally with the following defaults:
2094///
2095/// - `bitflag_from_endian_little` / `bitflag_from_endian_big`
2096/// - `bitflag_into_endian_little` / `bitflag_into_endian_big`
2097/// - `bitflag_derive_copy` / `bitflag_disable_copy`
2098///
2099/// Array heap storage can be controlled globally with `enable_array_heap` and
2100/// `disable_array_heap`.
2101///
2102/// ```toml
2103/// [dependencies]
2104/// bitfields = {
2105///     version = "0.1",
2106///     features = [
2107///         "generate_builder",
2108///         "generate_set_get_bit_ops",
2109///         "order_msb",
2110///         "from_endian_little",
2111///         "into_endian_big"
2112///     ]
2113/// }
2114/// ```
2115/// <!-- rust-docs-end -->
2116#[proc_macro_attribute]
2117pub fn bitfield(
2118    args: proc_macro::TokenStream,
2119    input: proc_macro::TokenStream,
2120) -> proc_macro::TokenStream {
2121    catch_panics(|| start_bitfield_generation(args, input))
2122}
2123
2124/// Entry for starting the bitfield generation.
2125fn start_bitfield_generation(
2126    args: proc_macro::TokenStream,
2127    input: proc_macro::TokenStream,
2128) -> proc_macro::TokenStream {
2129    let parsed_bitfield = match parse_bitfield_struct(args.into(), input.into()) {
2130        Ok(bitfield) => bitfield,
2131        Err(err) => return err.into_compile_error().into(),
2132    };
2133    check_force_panic(&parsed_bitfield);
2134    generate_bitfield(&parsed_bitfield).into()
2135}
2136
2137/// Forces a panic if argument is enabled.
2138fn check_force_panic(bitfield: &Bitfield) {
2139    assert!(!bitfield.arguments().force_panic(), "Forced panic for testing purposes");
2140}
2141
2142#[rustfmt::skip]
2143/// <!-- rust-bitflags-docs-start -->
2144/// ### Bitflags
2145///
2146/// There are times when you just want to define a bitflag, which are just enums
2147/// that map to bits. Instead of defining a custom type, you can take advantage of
2148/// the `#[bitflag]` attribute which generates `from_bits` and `into_bits` for enums
2149/// automatically.
2150///
2151/// Bitflags only supports unsigned types (`u8`, `u16`, `u32`, `u64`, `u128`) and
2152/// the one of the variants must be annotated with `#[base]` or `#[default]` which represents the
2153/// base value of the bitflag. If `#[base]` and `#[default]` are both present, `#[base]` takes precedence.
2154///
2155/// ```rust
2156/// # use bitfields_impl as bitfields;
2157/// use bitfields::bitfield;
2158/// use bitfields::bitflag;
2159///
2160/// /// Annotate an enum with the `#[bitflag]` attribute to automatically generate
2161/// /// the `from_bits` and `into_bits` functions for you! One variant must be annotated
2162/// /// with `#[base]` which represents the base value of the bitflag.
2163/// #[bitflag(u8)]
2164/// #[derive(Debug, PartialEq)]
2165/// enum RenderMode {
2166///     #[base]
2167///     Normal = 0,
2168///     Mirror = 1,
2169///     Flip = 2,
2170///     // #[default] - Default can be specified but base takes 
2171///     // precedence if both are present.
2172///     Hidden = 3,
2173/// }
2174///
2175/// /// The code that's generated for the `RenderMode` by the
2176/// /// `#[bitflag]` attribute saving you the trouble of writing 
2177/// /// the `from_bits` and `into_bits` functions yourself.
2178/// // impl RenderMode {
2179/// //     const fn from_bits(bits: u8) -> Self {
2180/// //         match bits {
2181/// //             0 => Self::Normal,
2182/// //             1 => Self::Mirror,
2183/// //             2 => Self::Flip,
2184/// //             3 => Self::Hidden,
2185/// //             _ => unreachable!(),
2186/// //         }
2187/// //     }
2188/// //
2189/// //     const fn into_bits(self) -> u8 {
2190/// //         self as u8
2191/// //     }
2192/// // }
2193///
2194/// /// Annotate an enum with the `#[bitflag]` attribute to automatically generate
2195/// /// the `from_bits` and `into_bits` functions for you! One variant must be annotated
2196/// /// with `#[base]` which represents the base value of the bitflag.
2197/// #[bitflag(u8)]
2198/// #[derive(Debug, PartialEq)]
2199/// enum AudioMode {
2200///     #[base]
2201///     Stereo = 0,
2202///     Mono = 1,
2203///     Mute = 2,
2204///     Surround = 3,
2205/// }
2206///
2207/// #[bitfield(u8)]
2208/// struct DisplayControl {
2209///     /// Must have the `#[bits]` attribute since the macro has 
2210///     /// no way of knowing how many bits the custom type occupies.
2211///     #[bits(4, default = RenderMode::Normal)]
2212///     render_mode: RenderMode,
2213///     /// Must have the `#[bits]` attribute since the macro has 
2214///     /// no way of knowing how many bits the custom type occupies.
2215///     #[bits(4, default = AudioMode::Stereo)]
2216///     audio_mode: AudioMode,
2217/// }
2218///
2219/// fn main() {
2220///     let display = DisplayControlBuilder::new()
2221///         .with_render_mode(RenderMode::Mirror)
2222///         .with_audio_mode(AudioMode::Mute)
2223///         .build();
2224///
2225///     assert_eq!(display.render_mode(), RenderMode::Mirror);
2226///     assert_eq!(display.audio_mode(), AudioMode::Mute);
2227/// }
2228/// ```
2229///
2230/// #### Bitflag Configuration
2231///
2232/// Bitflags can be configured with arguments passed to the `#[bitflag(...)]` attribute (the first argument is always the backing unsigned integer type):
2233///
2234/// | Argument         | Values                            | Default  | Description                                                                                          |
2235/// |------------------|-----------------------------------|----------|------------------------------------------------------------------------------------------------------|
2236/// | `<backing type>` | `u8`, `u16`, `u32`, `u64`, `u128` | Required | The storage used by the generated bitflag. Primitive backing types support bitfields up to 128 bits. |
2237/// | `from_endian`    | `big`, `little`                   | `big`    | Default endianness used by the generated `from_bits` function.                                       |
2238/// | `into_endian`    | `big`, `little`                   | `big`    | Default endianness used by the generated `into_bits` function.                                       |
2239/// | `copy`           | `true`, `false`                   | `true`   | Determines whether to derive `Copy` and `Clone` automatically for the enum.                          |
2240/// <!-- rust-bitflags-docs-end -->
2241#[proc_macro_attribute]
2242pub fn bitflag(
2243    args: proc_macro::TokenStream,
2244    input: proc_macro::TokenStream,
2245) -> proc_macro::TokenStream {
2246    catch_panics(|| start_bitflag_generation(args, input))
2247}
2248
2249/// Entry for starting the bitflag generation.
2250fn start_bitflag_generation(
2251    args: proc_macro::TokenStream,
2252    input: proc_macro::TokenStream,
2253) -> proc_macro::TokenStream {
2254    let parsed_bitflag = match parse_bitflag_enum(args.into(), input.into()) {
2255        Ok(bitflag) => bitflag,
2256        Err(err) => return err.into_compile_error().into(),
2257    };
2258
2259    generate_bitflag(&parsed_bitflag).into()
2260}
2261
2262/// Wraps and converts any unexpected panics into a compile error at the call
2263/// site.
2264fn catch_panics(macro_fn: impl FnOnce() -> proc_macro::TokenStream) -> proc_macro::TokenStream {
2265    std::panic::catch_unwind(std::panic::AssertUnwindSafe(macro_fn)).unwrap_or_else(|panic| {
2266        let panic_msg =
2267            panic.downcast_ref::<&str>().copied().unwrap_or("unable to parse panic payload");
2268        syn::Error::new(
2269            proc_macro2::Span::call_site(),
2270            format!("{INTERNAL_ERROR_MESSAGE}: {panic_msg}"),
2271        )
2272        .to_compile_error()
2273        .into()
2274    })
2275}