hexga_bitflags 0.0.11-beta.53

Bitflags utilities
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
//! 🚧 **Warning: Experimental Crate!** 🚧
//!
//! This crate is currently in **beta** and **experimental**.
//! It is subject to **breaking changes** in future releases.
//! Use it at your own risk, and keep in mind that the API may change in future versions.
//!
//! # Hexga BitFlags
//!
//! A bitflags crate, mainly inspired by [`enumflags2`](https://crates.io/crates/enumflags2).
//!
//!
//! Provide a `#[bit_index]` attribute macro that can be applied to **enum** `X` to automatically generate a corresponding **bitflags struct** `XFlags` and implement various bitwise operations, conversions, and utility methods for working with sets of enum variants as bitflags.
//!
//! The `#[bit_index]` macro interprets each enum variant as defining the position of a bit in the generated flags type.
//!
//! ## Features
//!
//! - **Automatic Bitflag Generation:** Annotate your enum `X` with `#[bit_index]` to generate a corresponding `XFlags` structure with the associated constant.
//!
//! - **Custom Discriminant Value:** Supports enums with explicit discriminants and non-contiguous values.
//!
//! - **Type Safe Flags:** The `Flags` structure contains only valid bit. Unused `enum` bit index will always be zero, when when calling not `!flags`.
//!
//!
//! - **Common Binary Operations:** Use `|`, `&`, `^`, and `!` operators directly on enum variants and the bitflags structure.
//! - **Iteration:** iterate over the enabled bits or retrieve enum variants from a flag set.
//! - **Serde Support:** Optional serialization/deserialization via the `serde` feature.
//! - **Simple API:** Includes methods for insertion, remove, toggling bits...
//!
//!
//! ## Example
//!
//! ```ignore
//! use hexga_bitflags::*;
//!
//! #[bit_index]
//! #[repr(u8)]
//! enum Color
//! {
//!     Red,
//!     Green,
//!     Blue = 5,
//!     Yellow, // = 6
//!     RedAndBlue = Color::Red | Self::Blue, // only defined in ColorFlags
//!     Purple, // 7
//!     GreenAndYellowAndPurple = ((Color::Yellow | Self::Purple)) | Self::Green, // only defined in ColorFlags
//! }
//!
//! fn main()
//! {
//!     let mut flags = Color::Red | Color::Blue;
//!     assert_eq!(flags, ColorFlags::RedAndBlue);
//!     assert_eq!(flags, ColorFlags::Red | ColorFlags::Blue);
//!
//!     assert!(flags.contains(Color::Red));
//!
//!     for color in ColorFlags::GreenAndYellowAndPurple
//!     {
//!         println!("{:?}", color);
//!     }
//!
//!     flags.remove(Color::Red);
//!     let blue = Color::try_from(flags).unwrap();
//! }
//! ```
//!
//! The generated code behind `#[bit_index]` will look like:
//!
//! ```ignore
//! #[repr(u8)]
//! #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] // The derive are also generated by `#[bit_index]`
//! pub enum Color {
//!     Red    = 0,
//!     Green  = 1,
//!     Blue   = 5,
//!     Yellow = 6,
//!     Purple = 7,
//! }
//!
//! #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
//! pub struct ColorFlags
//! {
//!     #[doc(hidden)]
//!     _bits_do_not_use_it: u8,
//! }
//!
//! impl ColorFlags
//! {
//!     pub const Red   : Self = Self {
//!         _bits_do_not_use_it: 1 << (Color::Red as u8),
//!     };
//!
//!     pub const Green : Self = ...;
//!     pub const Blue  : Self = ...;
//!     pub const Yellow: Self = ...;
//!
//!     pub const RedAndBlue: Self = Self {
//!         _bits_do_not_use_it: (Color::Red.bits() | Self::Blue.bits()),
//!     };
//!
//!     pub const Purple: Self = ...;
//!
//!     pub const GreenAndYellowAndPurple: Self = Self {
//!         _bits_do_not_use_it: ((Color::Yellow.bits() | Self::Purple.bits()) | Self::Green.bits()),
//!     };
//! }
//! ```
//!
//! \+ some other methods and trait implementations.
//!
//! ## Inspiration & Motivation
//!
//! This crate was mainly inspired by
//!
//! - [`enumflags2`](https://crates.io/crates/enumflags2) while also wanting a way to defined all the constant and constant combination inside the flags structure.
//!
//!
//! - Also check [`bitflags`](https://crates.io/crates/bitflags) if you are looking for a popular crate for defining bitflags (without enum).

// TODO fix the serde feature flags warnings...
#![allow(unexpected_cfgs)]

extern crate proc_macro;

use proc_macro::TokenStream;
use quote::{ToTokens, format_ident, quote};
use syn::{Ident, ItemEnum, parse_macro_input};

#[allow(unexpected_cfgs)]
#[cfg(feature = "serde")]
fn emit_serde_code(
    repr_type: &Ident,
    struct_name: &Ident,
) -> (
    proc_macro2::TokenStream,
    proc_macro2::TokenStream,
    proc_macro2::TokenStream,
)
{
    (
        quote! {
            #[allow(unexpected_cfgs)]
            #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
        },
        quote! {
            #[allow(unexpected_cfgs)]
            #[cfg_attr(feature = "serde", derive(Serialize), serde(transparent))]
        },
        quote! {
            #[allow(unexpected_cfgs)]
            #[cfg(feature = "serde")]
            impl<'de> ::serde::Deserialize<'de> for #struct_name {
                fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
                where
                D: ::serde::Deserializer<'de>,
                {
                    let bits = <#repr_type as serde::Deserialize>::deserialize(deserializer)?;
                    Self::try_from_bits(bits).map_err(|invalid_bits| {
                        <D::Error as ::serde::de::Error>::invalid_value(
                            ::serde::de::Unexpected::Unsigned(invalid_bits as u64),
                            &"a valid bitflag value",
                        )
                    })
                }
            }
        },
    )
}

#[allow(unexpected_cfgs)]
#[cfg(not(feature = "serde"))]
fn emit_serde_code(
    _: &Ident,
    _: &Ident,
) -> (
    proc_macro2::TokenStream,
    proc_macro2::TokenStream,
    proc_macro2::TokenStream,
)
{
    (quote! {}, quote! {}, quote! {})
}

#[proc_macro_attribute]
pub fn bit_index(_attr: TokenStream, item: TokenStream) -> TokenStream
{
    let input = parse_macro_input!(item as ItemEnum);
    let repr_type = find_repr_type(&input.attrs).unwrap_or_else(|| syn::parse_quote!(u8));

    let mut enum_variants = Vec::new();
    let mut enum_variants_name = Vec::new();
    let mut struct_non_composite_const = Vec::new();
    let mut struct_composite_const = Vec::new();
    let mut index: usize = 0;
    let visibility = &input.vis;

    let enum_name = &input.ident;
    let struct_name = format_ident!("{enum_name}Flags");

    let max_bits = match repr_type.to_string().as_str()
    {
        "u8" => 8,
        "u16" => 16,
        "u32" => 32,
        "u64" => 64,
        _ => panic!("Unsupported repr type: {}", repr_type),
    };

    for variant in &input.variants
    {
        let var_ident = &variant.ident;
        let flag_ident = var_ident.clone();

        // Check if the variant has a custom discriminant
        // Can probably be abused `Self::Red | 0b01`
        if let Some((_, expr)) = &variant.discriminant
        {
            index = match syn::Expr::clone(expr)
            {
                syn::Expr::Lit(syn::ExprLit {
                    lit: syn::Lit::Int(ref lit_int),
                    ..
                }) => lit_int.base10_parse().unwrap(),
                _ =>
                {
                    let tt = add_bits_field(expr);
                    struct_composite_const.push(quote! {
                        #[allow(non_upper_case_globals)]
                        pub const #flag_ident: #struct_name = #struct_name { _bits_do_not_use_it: #tt };
                    });
                    continue;
                }
            };
        }

        struct_non_composite_const.push(quote! { pub const #flag_ident: #struct_name = #struct_name { _bits_do_not_use_it: 1 << (#enum_name::#flag_ident as #repr_type) }; });
        enum_variants_name.push(flag_ident.clone());
        let value = quote! {
            #index as #repr_type
        };

        if index >= max_bits
        {
            return syn::Error::new_spanned(
                var_ident,
                format!(
                    "Too many enum variants for {}: {} exceeds max bits ({}) for repr type {}",
                    enum_name, index, max_bits, repr_type
                ),
            )
            .to_compile_error()
            .into();
        }

        enum_variants.push(quote! {
            #flag_ident = #value,
        });

        index += 1;
    }

    let nb_variant = enum_variants.len();

    let (serde_serialize_deserialize, serde_serialize_transparent, serde_deserialiaze_flags) =
        emit_serde_code(&repr_type, &struct_name);

    let output = quote! {

        #serde_serialize_deserialize
        #[repr(#repr_type)]
        #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
        #visibility enum #enum_name
        {
            #(#enum_variants)*
        }

        impl ::std::cmp::PartialEq<#struct_name> for #enum_name { fn eq(&self, other: &#struct_name) -> bool { self.flags() == *other }}

        impl #enum_name
        {
            /// Can't be indexed with `Self::X as usize` because all the used bit flags are not necessary contiguous
            pub const ALL: [Self; #nb_variant] = [
                #(Self::#enum_variants_name,)*
            ];

            /// Can't be indexed with `Self::X as usize` because all the used bit flags are not necessary contiguous
            pub const BITS: [#struct_name; #nb_variant] = [
                #(#struct_name { _bits_do_not_use_it: 1 << Self::#enum_variants_name as #repr_type },
                )*
            ];

            #(#struct_composite_const)*

            /// The bit index
            pub const fn index(self) -> usize { self as #repr_type as usize }
            pub const fn flags(self) -> #struct_name { #struct_name { _bits_do_not_use_it: self.bits() } }
            pub const fn bits(self) -> #repr_type
            {
                match self
                {
                    #(Self::#enum_variants_name => (1 << Self::#enum_variants_name as #repr_type) as #repr_type,)*
                }
            }

            pub fn from_index(index: #repr_type) -> Option<Self>
            {
                match index {
                    #(
                        x if x == Self::#enum_variants_name as #repr_type => Some(Self::#enum_variants_name),
                    )*
                    _ => None,
                }
            }
            pub unsafe fn from_index_unchecked(index: #repr_type) -> Option<Self>
            {
                unsafe { ::std::mem::transmute_copy(&index) }
            }

            pub fn from_flags(flags: #struct_name) -> Option<Self>
            {
                Self::from_bits(flags.bits())
            }
            pub unsafe fn from_flags_unchecked(flags: #struct_name) -> Self
            {
                unsafe { Self::from_bits_unchecked(flags.bits()) }
            }

            pub fn from_bits(bits: #repr_type) -> Option<Self>
            {
                match bits
                {
                    #( x if x == Self::#enum_variants_name.bits() => Some(Self::#enum_variants_name), )*
                    _ => None,
                }
            }
            pub unsafe fn from_bits_unchecked(bits: #repr_type) -> Self
            {
                match bits
                {
                    #( x if x == Self::#enum_variants_name.bits() => Self::#enum_variants_name, )*
                    _ => unreachable!(),
                }
            }
        }


        impl<T> std::ops::BitOr<T> for #enum_name where T: Into<#struct_name>
        {
            type Output = #struct_name; fn bitor(self, other: T) -> Self::Output { self.flags().bitor(other) }
        }
        impl<T> std::ops::BitAnd<T> for #enum_name where T: Into<#struct_name>
        {
            type Output = #struct_name; fn bitand(self, other: T) -> Self::Output { self.flags().bitand(other) }
        }
        impl<T> std::ops::BitXor<T> for #enum_name where T: Into<#struct_name>
        {
            type Output = #struct_name; fn bitxor(self, other: T) -> Self::Output { self.flags().bitxor(other) }
        }
        impl std::ops::Not for #enum_name
        {
            type Output = #struct_name;
            fn not(self) -> Self::Output { self.flags().not() }
        }

        impl TryFrom<#struct_name> for #enum_name
        {
            type Error = ();
            fn try_from(value: #struct_name) -> Result<Self, Self::Error>
            {
                Self::from_flags(value).ok_or(())
            }
        }

        impl From<#enum_name> for #struct_name
        {
            fn from(value: #enum_name) -> Self { value.flags() }
        }

        #serde_serialize_transparent
        #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
        #visibility struct #struct_name
        {
            #[doc(hidden)]
            _bits_do_not_use_it: #repr_type
        }

        impl ::std::cmp::PartialEq<#enum_name> for #struct_name { fn eq(&self, other: &#enum_name) -> bool { *self == other.flags() }}

        #serde_deserialiaze_flags

        impl ::std::fmt::Debug for #struct_name
        {
            fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result
            {
                f.write_str(stringify!(#struct_name))?;
                write!(f, "({:#b}", self._bits_do_not_use_it)?;

                if self.is_not_empty()
                {
                    write!(f, ", ")?;
                    let mut it = self.iter().peekable();
                    while let Some(v) = it.next()
                    {
                        write!(f, "{:?}", v)?;
                        if it.peek().is_some()
                        {
                            write!(f, " | ")?;
                        }
                    }
                }
                write!(f, ")")
            }
        }
        impl ::std::fmt::Binary for #struct_name
        {
            fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
                ::std::fmt::Binary::fmt(&self._bits_do_not_use_it, f)
            }
        }
        impl ::std::fmt::LowerHex for #struct_name {
            fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
                ::std::fmt::LowerHex::fmt(&self._bits_do_not_use_it, f)
            }
        }
        impl ::std::fmt::UpperHex for #struct_name {
            fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
                ::std::fmt::UpperHex::fmt(&self._bits_do_not_use_it, f)
            }
        }
        impl ::std::fmt::LowerExp for #struct_name {
            fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
                ::std::fmt::LowerExp::fmt(&self._bits_do_not_use_it, f)
            }
        }
        impl ::std::fmt::UpperExp for #struct_name {
            fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
                ::std::fmt::UpperExp::fmt(&self._bits_do_not_use_it, f)
            }
        }
        impl ::std::fmt::Octal for #struct_name {
            fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
                ::std::fmt::Octal::fmt(&self._bits_do_not_use_it, f)
            }
        }

        impl TryFrom<#repr_type> for #struct_name
        {
            type Error = #repr_type;
            fn try_from(bits: #repr_type) -> Result<Self, Self::Error>
            {
                Self::try_from_bits(bits)
            }
        }

        #[allow(non_upper_case_globals)]
        impl #struct_name
        {
            #(#struct_non_composite_const)*
            #(#struct_composite_const)*


            /// A constant with all the valid bit set to `1` (non used bit are still `0`)
            pub const ALL: Self = Self { _bits_do_not_use_it: #( #enum_name::#enum_variants_name.bits() |)* 0 };

            pub const EMPTY: Self = Self { _bits_do_not_use_it: 0 };
            pub const ZERO : Self = Self::EMPTY;
        }

        impl #struct_name
        {
            #[inline(always)]
            pub const fn bits(self) -> #repr_type { self._bits_do_not_use_it }

            pub const unsafe fn from_bits_unchecked(bits: #repr_type) -> Self { Self { _bits_do_not_use_it: bits} }
            /// Clear the illegal bit with the mask Self::ALL
            pub const fn from_bits(bits: #repr_type) -> Self { unsafe { Self::from_bits_unchecked(bits & Self::ALL._bits_do_not_use_it) } }

            /// Try to create the flags from the bits, or return the illegal bit
            pub fn try_from_bits(bits: #repr_type) -> Result<Self, #repr_type>
            {
                if bits == (bits & Self::ALL.bits())
                {
                    Ok(unsafe { Self::from_bits_unchecked(bits) })
                }else
                {
                    Err(bits & (!Self::ALL.bits()))
                }
            }


            #[inline(always)]
            pub const fn is_empty(self) -> bool { self.bits() == 0 }
            #[inline(always)]
            pub const fn is_not_empty(self) -> bool { self.bits() != 0 }
            #[inline(always)]
            pub const fn len(self) -> usize { self.bits().count_ones() as usize }

            pub fn iter(self) -> Self { self }


            // Similar fn to [`enumflags2`](https://docs.rs/enumflags2/0.7.12/src/enumflags2/lib.rs.html#843-845) :

            /*
            #[must_use]
            #[inline(always)]
            pub fn union<T>(self, other: T) -> Self where T: Into<Self> { self | other }
            #[must_use]
            #[inline(always)]
            pub fn intersection<T>(self, other: T) -> Self where T: Into<Self> { self & other }
            #[must_use]
            #[inline(always)]
            pub fn complement(self) -> Self { !self }
            */

            #[must_use]
            #[inline(always)]
            pub const fn union(self, other: Self) -> Self { #struct_name { _bits_do_not_use_it: self.bits() | (other.bits()) } }
            #[must_use]
            #[inline(always)]
            pub const fn intersection(self, other: Self) -> Self { #struct_name { _bits_do_not_use_it: self.bits() & (other.bits()) } }
            #[must_use]
            #[inline(always)]
            pub const fn complement(self) -> Self { #struct_name { _bits_do_not_use_it: !self.bits() & Self::ALL.bits() } } // Each 1 bit correspond to a variant that can be used, no illegal 1 bit

            /// Returns true if at least one flag is shared.
            #[inline(always)]
            pub fn intersects<T>(self, other: T) -> bool where T: Into<Self> { self & other != Self::EMPTY }

            /// Returns true if all flags are contained.
            #[inline(always)]
            pub fn contains<T>(self, other: T) -> bool where T: Into<Self> { self.contains_all(other) }

            /// Returns true if all flags are contained.
            #[inline(always)]
            pub fn contains_all<T>(self, other: T) -> bool where T: Into<Self> { let other = other.into(); self & other == other }
            /// Returns true if at least one flags is contained.
            #[inline(always)]
            pub fn contains_any<T>(self, other: T) -> bool where T: Into<Self> { let other = other.into(); (self & other).is_not_empty() }

            /// Toggles the matching bits
            #[must_use]
            #[inline(always)]
            pub fn toggled<T>(self, other: T) -> Self where T: Into<Self> { self ^ other }

            /// Toggles the matching bits
            #[inline(always)]
            pub fn toggle<T>(&mut self, other: T) -> &mut Self where T: Into<Self> { *self ^= other; self }


            /// Inserts the flags into the BitFlag
            #[must_use]
            #[inline(always)]
            pub fn inserted<T>(self, other: T) -> Self where T: Into<Self> { self | other }

            /// Inserts the flags into the BitFlag
            #[inline(always)]
            pub fn insert<T>(&mut self, other: T) -> &mut Self where T: Into<Self> { *self |= other; self }


            /// Removes the matching flags
            #[must_use]
            #[inline(always)]
            pub fn removed<T>(self, other: T) -> Self where T: Into<Self> { self & other }

            /// Removes the matching flags
            #[inline(always)]
            pub fn remove<T>(&mut self, other: T) -> &mut Self where T: Into<Self> { *self &= !other.into(); self }


            /// Conditionnaly insert or remove some flags
            #[must_use]
            #[inline(always)]
            pub fn with<T>(self, other: T, insert: bool) -> Self where T: Into<Self> { if insert { self.inserted(other) } else { self.removed(other) } }
            /// Conditionnaly insert or remove some flags
            #[inline(always)]
            pub fn set<T>(&mut self, other: T, insert: bool) -> &mut Self where T: Into<Self> { if insert { self.insert(other) } else { self.remove(other) } }

            /// Unsets all bits in the flags to 0.
            pub fn clear(&mut self) { *self = Self::EMPTY; }
        }

        impl<T> std::ops::BitOr<T> for #struct_name where T: Into<Self>
        {
            type Output = Self; fn bitor(self, other: T) -> Self::Output { #struct_name { _bits_do_not_use_it: self.bits().bitor(other.into().bits()) } }
        }

        impl<T> std::ops::BitOrAssign<T> for #struct_name where T: Into<Self>
        {
            fn bitor_assign(&mut self, other: T) { *self = <Self as ::std::ops::BitOr<T>>::bitor(*self, other); }
        }

        impl<T> std::ops::BitXor<T> for #struct_name where T: Into<Self>
        {
            type Output = Self; fn bitxor(self, other: T) -> Self::Output { #struct_name { _bits_do_not_use_it: self.bits().bitxor(other.into().bits()) } }
        }

        impl<T> std::ops::BitXorAssign<T> for #struct_name where T: Into<Self>
        {
            fn bitxor_assign(&mut self, other: T) { *self = <Self as ::std::ops::BitXor<T>>::bitxor(*self, other); }
        }

        impl<T> std::ops::BitAnd<T> for #struct_name where T: Into<Self>
        {
            type Output = Self; fn bitand(self, other: T) -> Self::Output { #struct_name { _bits_do_not_use_it: self.bits().bitand(other.into().bits()) } }
        }

        impl<T> std::ops::BitAndAssign<T> for #struct_name where T: Into<Self>
        {
            fn bitand_assign(&mut self, other: T) { *self = <Self as ::std::ops::BitAnd<T>>::bitand(*self, other); }
        }

        impl std::ops::Not for #struct_name
        {
            type Output = Self;
            fn not(self) -> Self::Output
            {
                Self
                {
                    _bits_do_not_use_it:
                        self.bits().not() & Self::ALL.bits() // Each 1 bit correspond to a variant that can be used, no illegal 1 bit
                }
            }
        }


        impl ::std::iter::Iterator for #struct_name
        {
            type Item = #enum_name;

            fn next(&mut self) -> Option<Self::Item>
            {
                if self.is_not_empty()
                {
                    let bits = self.bits();
                    let lsb = bits & bits.wrapping_neg(); // isolate least significant 1 bit
                    let rest = bits & !lsb; // the rest of the bits
                    self._bits_do_not_use_it = rest;
                    Some(unsafe{#enum_name::from_bits_unchecked(lsb)})
                }
                else
                {
                    None
                }
            }
        }
    };

    output.into()
}

fn add_bits_field(expr: &syn::Expr) -> proc_macro2::TokenStream
{
    match expr
    {
        syn::Expr::Path(path) => quote! { #path.bits() },
        syn::Expr::Binary(bin) =>
        {
            let left = add_bits_field(&bin.left);
            let right = add_bits_field(&bin.right);
            let op = bin.op.to_token_stream();
            quote! { (#left #op #right) }
        }
        syn::Expr::Paren(paren) =>
        {
            let inner = add_bits_field(&paren.expr);
            quote! { (#inner) }
        }
        syn::Expr::Unary(unary) => quote! { (#unary.expr).bits() },
        _ => quote! { #expr },
    }
}

fn find_repr_type(attrs: &[syn::Attribute]) -> Option<syn::Ident>
{
    for attr in attrs
    {
        if attr.path().is_ident("repr")
        {
            let parser =
                syn::punctuated::Punctuated::<syn::Ident, syn::Token![,]>::parse_terminated;
            if let Ok(idents) = attr.parse_args_with(parser)
            {
                return idents.first().cloned();
            }
        }
    }
    None
}