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
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
//! # Enum Flags
//! `enumflags2` implements the classic bitflags datastructure. Annotate an enum
//! with `#[bitflags]`, and `BitFlags<YourEnum>` will be able to hold arbitrary combinations
//! of your enum within the space of a single integer.
//!
//! ## Example
//! ```
//! use enumflags2::{bitflags, make_bitflags, BitFlags};
//!
//! #[bitflags]
//! #[repr(u8)]
//! #[derive(Copy, Clone, Debug, PartialEq)]
//! enum Test {
//!     A = 0b0001,
//!     B = 0b0010,
//!     C, // unspecified variants pick unused bits automatically
//!     D = 0b1000,
//! }
//!
//! // Flags can be combined with |, this creates a BitFlags of your type:
//! let a_b: BitFlags<Test> = Test::A | Test::B;
//! let a_c = Test::A | Test::C;
//! let b_c_d = make_bitflags!(Test::{B | C | D});
//!
//! // The debug output lets you inspect both the numeric value and
//! // the actual flags:
//! assert_eq!(format!("{:?}", a_b), "BitFlags<Test>(0b11, A | B)");
//!
//! // But if you'd rather see only one of those, that's available too:
//! assert_eq!(format!("{}", a_b), "A | B");
//! assert_eq!(format!("{:04b}", a_b), "0011");
//!
//! // Iterate over the flags like a normal set
//! assert_eq!(a_b.iter().collect::<Vec<_>>(), &[Test::A, Test::B]);
//!
//! // Query the contents with contains and intersects
//! assert!(a_b.contains(Test::A));
//! assert!(b_c_d.contains(Test::B | Test::C));
//! assert!(!(b_c_d.contains(a_b)));
//!
//! assert!(a_b.intersects(a_c));
//! assert!(!(a_b.intersects(Test::C | Test::D)));
//! ```
//!
//! ## Optional Feature Flags
//!
//! - [`serde`](https://serde.rs/) implements `Serialize` and `Deserialize`
//!   for `BitFlags<T>`.
//! - `std` implements `std::error::Error` for `FromBitsError`.
//!
//! ## `const fn`-compatible APIs
//!
//! **Background:** The subset of `const fn` features currently stabilized is pretty limited.
//! Most notably, [const traits are still at the RFC stage][const-trait-rfc],
//! which makes it impossible to use any overloaded operators in a const
//! context.
//!
//! **Naming convention:** If a separate, more limited function is provided
//! for usage in a `const fn`, the name is suffixed with `_c`.
//!
//! **Blanket implementations:** If you attempt to write a `const fn` ranging
//! over `T: BitFlag`, you will be met with an error explaining that currently,
//! the only allowed trait bound for a `const fn` is `?Sized`. You will probably
//! want to write a separate implementation for `BitFlags<T, u8>`,
//! `BitFlags<T, u16>`, etc — probably generated by a macro.
//! This strategy is often used by `enumflags2` itself; to avoid clutter, only
//! one of the copies is shown in the documentation.
//!
//! ## Customizing `Default`
//!
//! By default, creating an instance of `BitFlags<T>` with `Default` will result in an empty
//! set. If that's undesirable, you may customize this:
//!
//! ```
//! # use enumflags2::{BitFlags, bitflags};
//! #[bitflags(default = B | C)]
//! #[repr(u8)]
//! #[derive(Copy, Clone, Debug, PartialEq)]
//! enum Test {
//!     A = 0b0001,
//!     B = 0b0010,
//!     C = 0b0100,
//!     D = 0b1000,
//! }
//!
//! assert_eq!(BitFlags::default(), Test::B | Test::C);
//! ```
//!
//! [const-trait-rfc]: https://github.com/rust-lang/rfcs/pull/2632
#![warn(missing_docs)]
#![cfg_attr(all(not(test), not(feature = "std")), no_std)]

use core::iter::{FromIterator, FusedIterator};
use core::marker::PhantomData;
use core::{cmp, ops};

#[allow(unused_imports)]
#[macro_use]
extern crate enumflags2_derive;

#[doc(hidden)]
pub use enumflags2_derive::bitflags_internal as bitflags;

// Internal macro: expand into a separate copy for each supported numeric type.
macro_rules! for_each_uint {
    ( $d:tt $tyvar:ident $dd:tt $docattr:ident => $($input:tt)* ) => {
        macro_rules! implement {
            ( $d $tyvar:ty => $d($d $docattr:meta)? ) => {
                $($input)*
            }
        }

        implement! { u8 => }
        implement! { u16 => doc(hidden) }
        implement! { u32 => doc(hidden) }
        implement! { u64 => doc(hidden) }
        implement! { u128 => doc(hidden) }
    }
}

/// A trait automatically implemented by `#[bitflags]` to make the enum
/// a valid type parameter for `BitFlags<T>`.
pub trait BitFlag: Copy + Clone + 'static + _internal::RawBitFlags {
    /// Create a `BitFlags` with no flags set (in other words, with a value of 0).
    ///
    /// This is a convenience reexport of [`BitFlags::empty`]. It can be called with
    /// `MyFlag::empty()`, thus bypassing the need for type hints in some situations.
    ///
    /// ```
    /// # use enumflags2::{bitflags, BitFlags};
    /// #[bitflags]
    /// #[repr(u8)]
    /// #[derive(Clone, Copy, PartialEq, Eq)]
    /// enum MyFlag {
    ///     One = 1 << 0,
    ///     Two = 1 << 1,
    ///     Three = 1 << 2,
    /// }
    ///
    /// use enumflags2::BitFlag;
    ///
    /// let empty = MyFlag::empty();
    /// assert!(empty.is_empty());
    /// assert_eq!(empty.contains(MyFlag::One), false);
    /// assert_eq!(empty.contains(MyFlag::Two), false);
    /// assert_eq!(empty.contains(MyFlag::Three), false);
    /// ```
    #[inline]
    fn empty() -> BitFlags<Self> {
        BitFlags::empty()
    }

    /// Create a `BitFlags` with all flags set.
    ///
    /// This is a convenience reexport of [`BitFlags::all`]. It can be called with
    /// `MyFlag::all()`, thus bypassing the need for type hints in some situations.
    ///
    /// ```
    /// # use enumflags2::{bitflags, BitFlags};
    /// #[bitflags]
    /// #[repr(u8)]
    /// #[derive(Clone, Copy, PartialEq, Eq)]
    /// enum MyFlag {
    ///     One = 1 << 0,
    ///     Two = 1 << 1,
    ///     Three = 1 << 2,
    /// }
    ///
    /// use enumflags2::BitFlag;
    ///
    /// let empty = MyFlag::all();
    /// assert!(empty.is_all());
    /// assert_eq!(empty.contains(MyFlag::One), true);
    /// assert_eq!(empty.contains(MyFlag::Two), true);
    /// assert_eq!(empty.contains(MyFlag::Three), true);
    /// ```
    #[inline]
    fn all() -> BitFlags<Self> {
        BitFlags::all()
    }
}

/// While the module is public, this is only the case because it needs to be
/// accessed by the macro. Do not use this directly. Stability guarantees
/// don't apply.
#[doc(hidden)]
pub mod _internal {
    /// A trait automatically implemented by `#[bitflags]` to make the enum
    /// a valid type parameter for `BitFlags<T>`.
    ///
    /// # Safety
    ///
    /// The values should reflect reality, like they do if the implementation
    /// is generated by the procmacro.
    pub unsafe trait RawBitFlags: Copy + Clone + 'static {
        /// The underlying integer type.
        type Numeric: BitFlagNum;

        /// A value with no bits set.
        const EMPTY: Self::Numeric;

        /// The value used by the Default implementation. Equivalent to EMPTY, unless
        /// customized.
        const DEFAULT: Self::Numeric;

        /// A value with all flag bits set.
        const ALL_BITS: Self::Numeric;

        /// The name of the type for debug formatting purposes.
        ///
        /// This is typically `BitFlags<EnumName>`
        const BITFLAGS_TYPE_NAME: &'static str;

        /// Return the bits as a number type.
        fn bits(self) -> Self::Numeric;
    }

    use ::core::cmp::PartialOrd;
    use ::core::fmt;
    use ::core::ops::{BitAnd, BitOr, BitXor, Not, Sub};

    pub trait BitFlagNum:
        Default
        + BitOr<Self, Output = Self>
        + BitAnd<Self, Output = Self>
        + BitXor<Self, Output = Self>
        + Sub<Self, Output = Self>
        + Not<Output = Self>
        + PartialOrd<Self>
        + fmt::Debug
        + fmt::Binary
        + Copy
        + Clone
    {
        const ONE: Self;

        fn is_power_of_two(self) -> bool;
        fn count_ones(self) -> u32;
        fn wrapping_neg(self) -> Self;
    }

    for_each_uint! { $ty $hide_docs =>
        impl BitFlagNum for $ty {
            const ONE: Self = 1;

            fn is_power_of_two(self) -> bool {
                <$ty>::is_power_of_two(self)
            }

            fn count_ones(self) -> u32 {
                <$ty>::count_ones(self)
            }

            fn wrapping_neg(self) -> Self {
                <$ty>::wrapping_neg(self)
            }
        }
    }

    // Re-export libcore so the macro doesn't inject "extern crate" downstream.
    pub mod core {
        pub use core::{convert, ops, option};
    }

    pub struct AssertionSucceeded;
    pub struct AssertionFailed;
    pub trait ExactlyOneBitSet {
        type X;
    }
    impl ExactlyOneBitSet for AssertionSucceeded {
        type X = ();
    }

    pub trait AssertionHelper {
        type Status;
    }

    impl AssertionHelper for [(); 1] {
        type Status = AssertionSucceeded;
    }

    impl AssertionHelper for [(); 0] {
        type Status = AssertionFailed;
    }

    pub const fn next_bit(x: u128) -> u128 {
        1 << x.trailing_ones()
    }
}

use _internal::BitFlagNum;

// Internal debug formatting implementations
mod formatting;

// impl TryFrom<T::Numeric> for BitFlags<T>
mod fallible;
pub use crate::fallible::FromBitsError;

/// Represents a set of flags of some type `T`.
/// `T` must have the `#[bitflags]` attribute applied.
///
/// A `BitFlags<T>` is as large as the `T` itself,
/// and stores one flag per bit.
///
/// ## Memory layout
///
/// `BitFlags<T>` is marked with the `#[repr(transparent)]` trait, meaning
/// it can be safely transmuted into the corresponding numeric type.
///
/// Usually, the same can be achieved by using [`BitFlags::from_bits`],
/// [`BitFlags::from_bits_truncate`] or [`BitFlags::from_bits_unchecked`],
/// but transmuting might still be useful if, for example, you're dealing with
/// an entire array of `BitFlags`.
///
/// Transmuting from a numeric type into `BitFlags` may also be done, but
/// care must be taken to make sure that each set bit in the value corresponds
/// to an existing flag
/// (cf. [`from_bits_unchecked`][BitFlags::from_bits_unchecked]).
///
/// For example:
///
/// ```
/// # use enumflags2::{BitFlags, bitflags};
/// #[bitflags]
/// #[repr(u8)] // <-- the repr determines the numeric type
/// #[derive(Copy, Clone)]
/// enum TransmuteMe {
///     One = 1 << 0,
///     Two = 1 << 1,
/// }
///
/// # use std::slice;
/// // NOTE: we use a small, self-contained function to handle the slice
/// // conversion to make sure the lifetimes are right.
/// fn transmute_slice<'a>(input: &'a [BitFlags<TransmuteMe>]) -> &'a [u8] {
///     unsafe {
///         slice::from_raw_parts(input.as_ptr() as *const u8, input.len())
///     }
/// }
///
/// let many_flags = &[
///     TransmuteMe::One.into(),
///     TransmuteMe::One | TransmuteMe::Two,
/// ];
///
/// let as_nums = transmute_slice(many_flags);
/// assert_eq!(as_nums, &[0b01, 0b11]);
/// ```
///
/// ## Implementation notes
///
/// You might expect this struct to be defined as
///
/// ```ignore
/// struct BitFlags<T: BitFlag> {
///     value: T::Numeric
/// }
/// ```
///
/// Ideally, that would be the case. However, because `const fn`s cannot
/// have trait bounds in current Rust, this would prevent us from providing
/// most `const fn` APIs. As a workaround, we define `BitFlags` with two
/// type parameters, with a default for the second one:
///
/// ```ignore
/// struct BitFlags<T, N = <T as BitFlag>::Numeric> {
///     value: N,
///     marker: PhantomData<T>,
/// }
/// ```
///
/// The types substituted for `T` and `N` must always match, creating a
/// `BitFlags` value where that isn't the case is only possible with
/// incorrect unsafe code.
#[derive(Copy, Clone, Eq)]
#[repr(transparent)]
pub struct BitFlags<T, N = <T as _internal::RawBitFlags>::Numeric> {
    val: N,
    marker: PhantomData<T>,
}

/// `make_bitflags!` provides a succint syntax for creating instances of
/// `BitFlags<T>`. Instead of repeating the name of your type for each flag
/// you want to add, try `make_bitflags!(Flags::{Foo | Bar})`.
/// ```
/// use enumflags2::{bitflags, make_bitflags};
/// #[bitflags]
/// #[repr(u8)]
/// #[derive(Clone, Copy, Debug)]
/// enum Test {
///     A = 1 << 0,
///     B = 1 << 1,
///     C = 1 << 2,
/// }
/// let x = make_bitflags!(Test::{A | C});
/// assert_eq!(x, Test::A | Test::C);
/// ```
#[macro_export]
macro_rules! make_bitflags {
    ( $enum:ident ::{ $($variant:ident)|* } ) => {
        {
            let mut n = 0;
            $(
                {
                    let flag: $enum = $enum::$variant;
                    n |= flag as <$enum as $crate::_internal::RawBitFlags>::Numeric;
                }
            )*
            // SAFETY: The value has been created from numeric values of the underlying
            // enum, so only valid bits are set.
            unsafe { $crate::BitFlags::<$enum>::from_bits_unchecked_c(
                    n, $crate::BitFlags::CONST_TOKEN) }
        }
    }
}

/// The default value returned is one with all flags unset, i. e. [`empty`][Self::empty],
/// unless [customized](index.html#customizing-default).
impl<T> Default for BitFlags<T>
where
    T: BitFlag,
{
    #[inline(always)]
    fn default() -> Self {
        BitFlags {
            val: T::DEFAULT,
            marker: PhantomData,
        }
    }
}

impl<T: BitFlag> From<T> for BitFlags<T> {
    #[inline(always)]
    fn from(t: T) -> BitFlags<T> {
        Self::from_flag(t)
    }
}

/// Workaround for `const fn` limitations.
///
/// Some `const fn`s in this crate will need an instance of this type
/// for some type-level information usually provided by traits.
/// For an example of usage, see [`not_c`][BitFlags::not_c].
pub struct ConstToken<T, N>(BitFlags<T, N>);

impl<T> BitFlags<T>
where
    T: BitFlag,
{
    /// Returns a `BitFlags<T>` if the raw value provided does not contain
    /// any illegal flags.
    #[inline]
    pub fn from_bits(bits: T::Numeric) -> Result<Self, FromBitsError<T>> {
        let flags = Self::from_bits_truncate(bits);
        if flags.bits() == bits {
            Ok(flags)
        } else {
            Err(FromBitsError {
                flags,
                invalid: bits & !flags.bits(),
            })
        }
    }

    /// Create a `BitFlags<T>` from an underlying bitwise value. If any
    /// invalid bits are set, ignore them.
    #[must_use]
    #[inline(always)]
    pub fn from_bits_truncate(bits: T::Numeric) -> Self {
        // SAFETY: We're truncating out all the invalid bits, so the remaining
        // ones must be valid.
        unsafe { BitFlags::from_bits_unchecked(bits & T::ALL_BITS) }
    }

    /// Create a new BitFlags unsafely, without checking if the bits form
    /// a valid bit pattern for the type.
    ///
    /// Consider using [`from_bits`][BitFlags::from_bits]
    /// or [`from_bits_truncate`][BitFlags::from_bits_truncate] instead.
    ///
    /// # Safety
    ///
    /// All bits set in `val` must correspond to a value of the enum.
    #[must_use]
    #[inline(always)]
    pub unsafe fn from_bits_unchecked(val: T::Numeric) -> Self {
        BitFlags {
            val,
            marker: PhantomData,
        }
    }

    /// Turn a `T` into a `BitFlags<T>`. Also available as `flag.into()`.
    #[must_use]
    #[inline(always)]
    pub fn from_flag(flag: T) -> Self {
        // SAFETY: A value of the underlying enum is valid by definition.
        unsafe { Self::from_bits_unchecked(flag.bits()) }
    }

    /// Create a `BitFlags` with no flags set (in other words, with a value of `0`).
    ///
    /// See also: [`BitFlag::empty`], a convenience reexport;
    /// [`BitFlags::EMPTY`], the same functionality available
    /// as a constant for `const fn` code.
    ///
    /// ```
    /// # use enumflags2::{bitflags, BitFlags};
    /// #[bitflags]
    /// #[repr(u8)]
    /// #[derive(Clone, Copy, PartialEq, Eq)]
    /// enum MyFlag {
    ///     One = 1 << 0,
    ///     Two = 1 << 1,
    ///     Three = 1 << 2,
    /// }
    ///
    /// let empty: BitFlags<MyFlag> = BitFlags::empty();
    /// assert!(empty.is_empty());
    /// assert_eq!(empty.contains(MyFlag::One), false);
    /// assert_eq!(empty.contains(MyFlag::Two), false);
    /// assert_eq!(empty.contains(MyFlag::Three), false);
    /// ```
    #[inline(always)]
    pub fn empty() -> Self {
        Self::EMPTY
    }

    /// Create a `BitFlags` with all flags set.
    ///
    /// See also: [`BitFlag::all`], a convenience reexport;
    /// [`BitFlags::ALL`], the same functionality available
    /// as a constant for `const fn` code.
    ///
    /// ```
    /// # use enumflags2::{bitflags, BitFlags};
    /// #[bitflags]
    /// #[repr(u8)]
    /// #[derive(Clone, Copy, PartialEq, Eq)]
    /// enum MyFlag {
    ///     One = 1 << 0,
    ///     Two = 1 << 1,
    ///     Three = 1 << 2,
    /// }
    ///
    /// let empty: BitFlags<MyFlag> = BitFlags::all();
    /// assert!(empty.is_all());
    /// assert_eq!(empty.contains(MyFlag::One), true);
    /// assert_eq!(empty.contains(MyFlag::Two), true);
    /// assert_eq!(empty.contains(MyFlag::Three), true);
    /// ```
    #[inline(always)]
    pub fn all() -> Self {
        Self::ALL
    }

    /// An empty `BitFlags`. Equivalent to [`empty()`][BitFlags::empty],
    /// but works in a const context.
    pub const EMPTY: Self = BitFlags {
        val: T::EMPTY,
        marker: PhantomData,
    };

    /// A `BitFlags` with all flags set. Equivalent to [`all()`][BitFlags::all],
    /// but works in a const context.
    pub const ALL: Self = BitFlags {
        val: T::ALL_BITS,
        marker: PhantomData,
    };

    /// A [`ConstToken`] for this type of flag.
    pub const CONST_TOKEN: ConstToken<T, T::Numeric> = ConstToken(Self::ALL);

    /// Returns true if all flags are set
    #[inline(always)]
    pub fn is_all(self) -> bool {
        self.val == T::ALL_BITS
    }

    /// Returns true if no flag is set
    #[inline(always)]
    pub fn is_empty(self) -> bool {
        self.val == T::EMPTY
    }

    /// Returns the number of flags set.
    #[inline(always)]
    pub fn len(self) -> usize {
        self.val.count_ones() as usize
    }

    /// If exactly one flag is set, the flag is returned. Otherwise, returns `None`.
    ///
    /// See also [`Itertools::exactly_one`](https://docs.rs/itertools/latest/itertools/trait.Itertools.html#method.exactly_one).
    #[inline(always)]
    pub fn exactly_one(self) -> Option<T> {
        if self.val.is_power_of_two() {
            // SAFETY: By the invariant of the BitFlags type, all bits are valid
            // in isolation for the underlying enum.
            Some(unsafe { core::mem::transmute_copy(&self.val) })
        } else {
            None
        }
    }

    /// Returns the underlying bitwise value.
    ///
    /// ```
    /// # use enumflags2::{bitflags, BitFlags};
    /// #[bitflags]
    /// #[repr(u8)]
    /// #[derive(Clone, Copy)]
    /// enum Flags {
    ///     Foo = 1 << 0,
    ///     Bar = 1 << 1,
    /// }
    ///
    /// let both_flags = Flags::Foo | Flags::Bar;
    /// assert_eq!(both_flags.bits(), 0b11);
    /// ```
    #[inline(always)]
    pub fn bits(self) -> T::Numeric {
        self.val
    }

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

    /// Returns true if all flags are contained.
    #[inline(always)]
    pub fn contains<B: Into<BitFlags<T>>>(self, other: B) -> bool {
        let other = other.into();
        (self.bits() & other.bits()) == other.bits()
    }

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

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

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

    /// Returns an iterator that yields each set flag
    #[inline]
    pub fn iter(self) -> Iter<T> {
        Iter {
            rest: self,
        }
    }
}

impl<T: BitFlag> IntoIterator for BitFlags<T> {
    type IntoIter = Iter<T>;
    type Item = T;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

/// Iterator that yields each set flag.
#[derive(Clone, Debug)]
pub struct Iter<T: BitFlag> {
    rest: BitFlags<T>,
}

impl<T> Iterator for Iter<T>
where
    T: BitFlag,
{
    type Item = T;

    fn next(&mut self) -> Option<Self::Item> {
        if self.rest.is_empty() {
            None
        } else {
            // SAFETY: `flag` will be a single bit, because
            // x & -x = x & (~x + 1), and the increment causes only one 0 -> 1 transition.
            // The invariant of `from_bits_unchecked` is satisfied, because bits & x
            // is a subset of bits, which we know are the valid bits.
            unsafe {
                let bits = self.rest.bits();
                let flag: T::Numeric = bits & bits.wrapping_neg();
                let flag: T = core::mem::transmute_copy(&flag);
                self.rest = BitFlags::from_bits_unchecked(bits & (bits - BitFlagNum::ONE));
                Some(flag)
            }
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let l = self.rest.len();
        (l, Some(l))
    }
}

impl<T> ExactSizeIterator for Iter<T>
where
    T: BitFlag,
{
    fn len(&self) -> usize {
        self.rest.len()
    }
}

impl<T: BitFlag> FusedIterator for Iter<T> {}

for_each_uint! { $ty $hide_docs =>
    impl<T> BitFlags<T, $ty> {
        /// Create a new BitFlags unsafely, without checking if the bits form
        /// a valid bit pattern for the type.
        ///
        /// Const variant of
        /// [`from_bits_unchecked`][BitFlags::from_bits_unchecked].
        ///
        /// Consider using
        /// [`from_bits_truncate_c`][BitFlags::from_bits_truncate_c] instead.
        ///
        /// # Safety
        ///
        /// All bits set in `val` must correspond to a value of the enum.
        #[must_use]
        #[inline(always)]
        $(#[$hide_docs])?
        pub const unsafe fn from_bits_unchecked_c(
            val: $ty, const_token: ConstToken<T, $ty>
        ) -> Self {
            let _ = const_token;
            BitFlags {
                val,
                marker: PhantomData,
            }
        }

        /// Create a `BitFlags<T>` from an underlying bitwise value. If any
        /// invalid bits are set, ignore them.
        ///
        /// ```
        /// # use enumflags2::{bitflags, BitFlags};
        /// #[bitflags]
        /// #[repr(u8)]
        /// #[derive(Clone, Copy, Debug, PartialEq, Eq)]
        /// enum MyFlag {
        ///     One = 1 << 0,
        ///     Two = 1 << 1,
        ///     Three = 1 << 2,
        /// }
        ///
        /// const FLAGS: BitFlags<MyFlag> =
        ///     BitFlags::<MyFlag>::from_bits_truncate_c(0b10101010, BitFlags::CONST_TOKEN);
        /// assert_eq!(FLAGS, MyFlag::Two);
        /// ```
        #[must_use]
        #[inline(always)]
        $(#[$hide_docs])?
        pub const fn from_bits_truncate_c(
            bits: $ty, const_token: ConstToken<T, $ty>
        ) -> Self {
            BitFlags {
                val: bits & const_token.0.val,
                marker: PhantomData,
            }
        }

        /// Bitwise OR — return value contains flag if either argument does.
        ///
        /// Also available as `a | b`, but operator overloads are not usable
        /// in `const fn`s at the moment.
        #[must_use]
        #[inline(always)]
        $(#[$hide_docs])?
        pub const fn union_c(self, other: Self) -> Self {
            BitFlags {
                val: self.val | other.val,
                marker: PhantomData,
            }
        }

        /// Bitwise AND — return value contains flag if both arguments do.
        ///
        /// Also available as `a & b`, but operator overloads are not usable
        /// in `const fn`s at the moment.
        #[must_use]
        #[inline(always)]
        $(#[$hide_docs])?
        pub const fn intersection_c(self, other: Self) -> Self {
            BitFlags {
                val: self.val & other.val,
                marker: PhantomData,
            }
        }

        /// Bitwise NOT — return value contains flag if argument doesn't.
        ///
        /// Also available as `!a`, but operator overloads are not usable
        /// in `const fn`s at the moment.
        ///
        /// Moreover, due to `const fn` limitations, `not_c` needs a
        /// [`ConstToken`] as an argument.
        ///
        /// ```
        /// # use enumflags2::{bitflags, BitFlags, make_bitflags};
        /// #[bitflags]
        /// #[repr(u8)]
        /// #[derive(Clone, Copy, Debug, PartialEq, Eq)]
        /// enum MyFlag {
        ///     One = 1 << 0,
        ///     Two = 1 << 1,
        ///     Three = 1 << 2,
        /// }
        ///
        /// const FLAGS: BitFlags<MyFlag> = make_bitflags!(MyFlag::{One | Two});
        /// const NEGATED: BitFlags<MyFlag> = FLAGS.not_c(BitFlags::CONST_TOKEN);
        /// assert_eq!(NEGATED, MyFlag::Three);
        /// ```
        #[must_use]
        #[inline(always)]
        $(#[$hide_docs])?
        pub const fn not_c(self, const_token: ConstToken<T, $ty>) -> Self {
            BitFlags {
                val: !self.val & const_token.0.val,
                marker: PhantomData,
            }
        }

        /// Returns the underlying bitwise value.
        ///
        /// `const` variant of [`bits`][BitFlags::bits].
        #[inline(always)]
        $(#[$hide_docs])?
        pub const fn bits_c(self) -> $ty {
            self.val
        }
    }
}

impl<T, N: PartialEq> cmp::PartialEq for BitFlags<T, N> {
    #[inline(always)]
    fn eq(&self, other: &Self) -> bool {
        self.val == other.val
    }
}

// Clippy complains when Hash is derived while PartialEq is implemented manually
impl<T, N: core::hash::Hash> core::hash::Hash for BitFlags<T, N> {
    #[inline(always)]
    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
        self.val.hash(state)
    }
}

impl<T> cmp::PartialEq<T> for BitFlags<T>
where
    T: BitFlag,
{
    #[inline(always)]
    fn eq(&self, other: &T) -> bool {
        self.bits() == Into::<Self>::into(*other).bits()
    }
}

impl<T, B> ops::BitOr<B> for BitFlags<T>
where
    T: BitFlag,
    B: Into<BitFlags<T>>,
{
    type Output = BitFlags<T>;
    #[inline(always)]
    fn bitor(self, other: B) -> BitFlags<T> {
        // SAFETY: The two operands are known to be composed of valid bits,
        // and 0 | 0 = 0 in the columns of the invalid bits.
        unsafe { BitFlags::from_bits_unchecked(self.bits() | other.into().bits()) }
    }
}

impl<T, B> ops::BitAnd<B> for BitFlags<T>
where
    T: BitFlag,
    B: Into<BitFlags<T>>,
{
    type Output = BitFlags<T>;
    #[inline(always)]
    fn bitand(self, other: B) -> BitFlags<T> {
        // SAFETY: The two operands are known to be composed of valid bits,
        // and 0 & 0 = 0 in the columns of the invalid bits.
        unsafe { BitFlags::from_bits_unchecked(self.bits() & other.into().bits()) }
    }
}

impl<T, B> ops::BitXor<B> for BitFlags<T>
where
    T: BitFlag,
    B: Into<BitFlags<T>>,
{
    type Output = BitFlags<T>;
    #[inline(always)]
    fn bitxor(self, other: B) -> BitFlags<T> {
        // SAFETY: The two operands are known to be composed of valid bits,
        // and 0 ^ 0 = 0 in the columns of the invalid bits.
        unsafe { BitFlags::from_bits_unchecked(self.bits() ^ other.into().bits()) }
    }
}

impl<T, B> ops::BitOrAssign<B> for BitFlags<T>
where
    T: BitFlag,
    B: Into<BitFlags<T>>,
{
    #[inline(always)]
    fn bitor_assign(&mut self, other: B) {
        *self = *self | other;
    }
}

impl<T, B> ops::BitAndAssign<B> for BitFlags<T>
where
    T: BitFlag,
    B: Into<BitFlags<T>>,
{
    #[inline(always)]
    fn bitand_assign(&mut self, other: B) {
        *self = *self & other;
    }
}
impl<T, B> ops::BitXorAssign<B> for BitFlags<T>
where
    T: BitFlag,
    B: Into<BitFlags<T>>,
{
    #[inline(always)]
    fn bitxor_assign(&mut self, other: B) {
        *self = *self ^ other;
    }
}

impl<T> ops::Not for BitFlags<T>
where
    T: BitFlag,
{
    type Output = BitFlags<T>;
    #[inline(always)]
    fn not(self) -> BitFlags<T> {
        BitFlags::from_bits_truncate(!self.bits())
    }
}

impl<T, B> FromIterator<B> for BitFlags<T>
where
    T: BitFlag,
    B: Into<BitFlags<T>>,
{
    #[inline]
    fn from_iter<I>(it: I) -> BitFlags<T>
    where
        I: IntoIterator<Item = B>,
    {
        it.into_iter()
            .fold(BitFlags::empty(), |acc, flag| acc | flag)
    }
}

impl<T, B> Extend<B> for BitFlags<T>
where
    T: BitFlag,
    B: Into<BitFlags<T>>,
{
    #[inline]
    fn extend<I>(&mut self, it: I)
    where
        I: IntoIterator<Item = B>,
    {
        *self = it.into_iter().fold(*self, |acc, flag| acc | flag)
    }
}

#[cfg(feature = "serde")]
mod impl_serde {
    use super::{BitFlag, BitFlags};
    use serde::de::{Error, Unexpected};
    use serde::{Deserialize, Serialize};

    impl<'a, T> Deserialize<'a> for BitFlags<T>
    where
        T: BitFlag,
        T::Numeric: Deserialize<'a> + Into<u64>,
    {
        fn deserialize<D: serde::Deserializer<'a>>(d: D) -> Result<Self, D::Error> {
            let val = T::Numeric::deserialize(d)?;
            Self::from_bits(val).map_err(|_| {
                D::Error::invalid_value(
                    Unexpected::Unsigned(val.into()),
                    &"valid bit representation",
                )
            })
        }
    }

    impl<T> Serialize for BitFlags<T>
    where
        T: BitFlag,
        T::Numeric: Serialize,
    {
        fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
            T::Numeric::serialize(&self.val, s)
        }
    }
}