bitflags-lite 0.2.0

Lightweight generics-based bitflags
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
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
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
use core::any::type_name;
use core::borrow::Borrow;
use core::cmp::Ordering;
use core::fmt;
use core::hash::{Hash, Hasher};
use core::iter::{FromIterator, IntoIterator};
use core::marker::PhantomData;
use core::ops::{
    BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Not, Shl, Sub, SubAssign,
};
use core::str::FromStr;

use crate::{BitFlag, BitFlagsIter, BitFlagsSpec, NameMatcher, util};

/// A type-safe set of flags stored in an integer `T`.
///
/// The second type parameter `U` is a tag type that distinguishes flag sets
/// that share the same storage type.
/// When `U` implements `BitFlagsSpec`, it defines which bits are valid.
///
/// `BitFlags` is `#[repr(transparent)]` over `T`, so it has the same layout as
/// `T`.
///
/// # Invalid bits
///
/// A `BitFlags` value is not guaranteed to contain only valid bits.
/// [`BitFlags::from_bits_retain`] can create a value with any bit pattern of
/// `T`, and raw-bit operations such as [`BitFlags::insert`],
/// [`BitFlags::toggle`], [`BitFlags::union`], and bitwise operators preserve
/// invalid bits. Use [`BitFlags::truncate`], [`BitFlags::try_from_bits`], or
/// [`BitFlags::from_bits_truncate`] when a value must be restricted to
/// [`BitFlagsSpec::VALID_BITS_MASK`].
///
/// [`BitFlags::bits`] returns the raw stored bits, including any invalid bits
/// that are present.
///
/// # Examples
///
/// ```
/// use bitflags_lite::{BitFlags, BitFlagsSpec, NameMatcher};
///
/// struct PermissionsTag;
///
/// impl BitFlagsSpec<u32> for PermissionsTag {
///     const VALID_BITS_MASK: u32 = 0b111;
///     const FLAG_NAMES: &[&[&str]] = &[&["read"], &["write"], &["exec", "execute"]];
///     const COMBINED_NAMES: &[(u32, &str)] = &[(0, "none"), (0b111, "rwx")];
///     const DEFAULT_NAME_MATCHER: NameMatcher = NameMatcher::Exact;
/// }
///
/// type Permissions = BitFlags<u32, PermissionsTag>;
///
/// const READ: Permissions = Permissions::try_from_bits(1 << 0).unwrap();
/// const WRITE: Permissions = Permissions::try_from_bits(1 << 1).unwrap();
/// const EXEC: Permissions = Permissions::try_from_bits(1 << 2).unwrap();
///
/// let rw = READ | WRITE;
/// assert!(rw.contains(READ));
/// assert!(rw.contains(WRITE));
/// assert!(!rw.contains(EXEC));
/// ```
///
/// # Method summary
///
/// - [`empty()`](Self::empty): Return a set with no bits set.
/// - [`all_valid()`](Self::all_valid): Return a set with all valid bits set.
/// - [`from_bits_retain()`](Self::from_bits_retain): Convert from raw bits
///   without validation.
/// - [`from_bits_truncate()`](Self::from_bits_truncate): Convert from raw bits,
///   clearing invalid bits.
/// - [`try_from_bits()`](Self::try_from_bits): Convert from raw bits, rejecting
///   invalid bits.
/// - [`from_bit_retain()`](Self::from_bit_retain): Return a set with only the
///   bit at a given index, without validation.
/// - [`from_bit_truncate()`](Self::from_bit_truncate): Return a set with only
///   the bit at a given index, clearing it if invalid.
/// - [`try_from_bit()`](Self::try_from_bit): Return a set with only the bit at
///   a given index, rejecting it if invalid.
/// - [`from_flag()`](Self::from_flag): Convert from a single [`BitFlag`].
/// - [`try_from_str()`](Self::try_from_str): Parse from a separated string.
/// - [`bits()`](Self::bits): Return the raw stored bits.
/// - [`bits_mut()`](Self::bits_mut): Return a mutable reference to the raw
///   bits.
/// - [`into_bits()`](Self::into_bits): Consume the set and return the raw bits.
/// - [`iter()`](Self::iter): Return an iterator over the set bits.
/// - [`is_empty()`](Self::is_empty): Return `true` if no bits are set.
/// - [`is_valid()`](Self::is_valid): Return `true` if all set bits are valid
///   for the tag.
/// - [`intersects()`](Self::intersects): Return `true` if any bits are shared.
/// - [`contains()`](Self::contains): Return `true` if all bits of another set
///   are present.
/// - [`insert()`](Self::insert): Add all bits of another set.
/// - [`remove()`](Self::remove): Remove all bits of another set.
/// - [`toggle()`](Self::toggle): Flip all bits of another set.
/// - [`set()`](Self::set): Insert or remove bits based on a boolean.
/// - [`clear()`](Self::clear): Remove all bits, valid and invalid.
/// - [`truncate()`](Self::truncate): Remove all invalid bits.
/// - [`intersection()`](Self::intersection): Return the bits set in both sets.
/// - [`union()`](Self::union): Return the bits set in either set.
/// - [`difference()`](Self::difference): Return the bits set in `self` but not
///   in `other`.
/// - [`symmetric_difference()`](Self::symmetric_difference): Return the bits
///   set in exactly one set.
/// - [`complement()`](Self::complement): Return the valid bits not set in
///   `self`.
#[repr(transparent)]
pub struct BitFlags<T, U>(
    T,
    // PhantomData<fn() -> *const U> is Send + Sync and covariant over `U`,
    // and `U` is not required to be sized as pattern uses only its pointer.
    // See: https://doc.rust-lang.org/nomicon/phantom-data.html#table-of-phantomdata-patterns
    PhantomData<fn() -> *const U>,
)
where
    U: ?Sized;

/// Serde visitor for deserializing [`BitFlags`] from a string.
///
/// The accepted format is the same as [`BitFlags`]'s
/// [`FromStr`](core::str::FromStr) implementation: an empty string, a
/// `|`-separated list of named flags, and/or `0x`-prefixed hexadecimal flags.
/// Named flags are matched according to
/// [`BitFlagsSpec::DEFAULT_NAME_MATCHER`].
///
/// Deserialization does not validate the parsed bits against
/// [`BitFlagsSpec::VALID_BITS_MASK`].
/// The resulting value may contain invalid bits.
#[cfg(feature = "serde")]
struct BitFlagsVisitor<T, U>(PhantomData<T>, PhantomData<fn() -> *const U>)
where
    U: ?Sized;

impl<T, U> BitFlags<T, U>
where
    U: ?Sized,
{
    /// Creates a flag set with no bits set (zero bits).
    ///
    /// This is equivalent to `from_bits_retain(0)`.
    #[inline]
    #[must_use]
    pub const fn empty() -> Self
    where
        T: util::IntOpsExt,
    {
        Self(T::ZERO, PhantomData)
    }

    /// Creates a flag set containing all valid bits for this tag.
    ///
    /// This returns exactly [`BitFlagsSpec::VALID_BITS_MASK`]. Invalid bits
    /// are never set.
    ///
    /// The method is named `all_valid` rather than `all` because a
    /// `BitFlags` value can contain invalid bits after
    /// [`BitFlags::from_bits_retain`].
    /// In that case, "all" would be ambiguous: all bits of the storage
    /// type, all bits currently set, or all valid bits?
    ///
    /// `all_valid` makes the meaning explicit.
    #[doc(alias = "all")]
    #[inline]
    #[must_use]
    pub const fn all_valid() -> Self
    where
        T: 'static,
        U: BitFlagsSpec<T>,
    {
        Self(U::VALID_BITS_MASK, PhantomData)
    }

    /// Creates a flag set from raw bits without validation.
    ///
    /// The resulting value may contain bits not present in
    /// [`BitFlagsSpec::VALID_BITS_MASK`].
    /// Such invalid bits are preserved by this constructor and by
    /// raw-bit operations unless an operation clears them, such as
    /// [`BitFlags::truncate`], [`BitFlags::complement`],
    /// [`BitFlags::from_bits_truncate`], or [`Not`](core::ops::Not).
    #[inline]
    #[must_use]
    pub const fn from_bits_retain(bits: T) -> Self {
        Self(bits, PhantomData)
    }

    /// Returns the raw bits stored in this flag set.
    ///
    /// The returned value may contain invalid bits if this value was
    /// created with [`BitFlags::from_bits_retain`] and has not since
    /// been passed through an operation that clears invalid bits, such
    /// as [`BitFlags::truncate`] or [`BitFlags::complement`].
    #[inline]
    #[must_use]
    pub const fn bits(&self) -> T
    where
        T: Copy,
    {
        self.0
    }

    /// Returns a mutable reference to the raw bits stored in this flag set.
    ///
    /// Mutating the returned value can introduce invalid bits.
    /// Use [`BitFlags::truncate`] afterwards if the value must contain only
    /// valid bits.
    #[inline]
    #[must_use]
    pub const fn bits_mut(&mut self) -> &mut T {
        &mut self.0
    }

    /// Consumes this flag set and returns the raw bits.
    ///
    /// This is the consuming counterpart to [`BitFlags::bits`].
    /// Like [`BitFlags::bits`], the returned value may contain bits not present
    /// in [`BitFlagsSpec::VALID_BITS_MASK`].
    ///
    /// This method does not require `T: Copy`, so it is available for storage
    /// types that are not `Copy`.
    #[inline]
    #[must_use]
    pub fn into_bits(self) -> T {
        self.0
    }

    /// Returns an iterator over the individual set bits in this flag set.
    ///
    /// The iterator yields [`BitFlag`] values from the least significant bit to
    /// the most significant bit.
    /// It includes invalid bits if they are present.
    #[inline]
    pub const fn iter(self) -> BitFlagsIter<T, U>
    where
        T: Copy + Not<Output = T> + BitAndAssign<T> + util::IntOpsExt,
    {
        BitFlagsIter::new(self)
    }

    /// Parses a flag set from a string.
    ///
    /// The input may be empty, which returns [`BitFlags::empty`].
    /// Otherwise it is split on given `separator`, and each part is trimmed and
    /// matched against the names in [`BitFlagsSpec::FLAG_NAMES`].
    /// Match behavior is specified by `name_matcher`.
    /// A part may also be a hexadecimal flag with a `0x` prefix.
    ///
    /// This method does not validate or truncate the parsed bits against
    /// [`BitFlagsSpec::VALID_BITS_MASK`].
    /// The returned value may contain invalid bits.
    ///
    /// Note that if `separator` is an empty string, the method would split into
    /// individual characters, which is almost certainly not intended.
    ///
    /// # Errors
    ///
    /// Returns [`BitFlagsParseError`] if `input` is not a `separator`-separated
    /// list of named flags or hexadecimal flags.
    #[inline]
    pub fn try_from_str(
        input: &str,
        separator: &'static str,
        name_matcher: NameMatcher,
    ) -> Result<Self, BitFlagsParseError>
    where
        T: 'static + Copy + BitOrAssign<T> + util::IntOpsExt,
        U: BitFlagsSpec<T>,
    {
        if input.trim().is_empty() {
            return Ok(Self::empty());
        }

        let mut this = Self::empty();
        let input = input.split(separator);
        'a: for input in input {
            let input = input.trim();

            let flag = BitFlag::from_name_opt(input, name_matcher);
            if let Some(flag) = flag {
                this |= flag;
                continue;
            }

            for (flags, name) in U::COMBINED_NAMES {
                if input == *name {
                    this |= Self::from_bits_retain(*flags);
                    continue 'a;
                }
            }

            if let Some(maybe_hex_flag) = input.strip_prefix("0x") {
                // `from_str_radix` allows optional `+` prefix.
                // Parsing here should prohibit it.
                if !maybe_hex_flag.starts_with('+') {
                    let bits = T::from_str_radix(maybe_hex_flag, 16);
                    if let Ok(bits) = bits {
                        this |= Self::from_bits_retain(bits);
                        continue;
                    }
                }
            }

            #[cfg(feature = "alloc")]
            let given = alloc::string::ToString::to_string(input);
            #[cfg(not(feature = "alloc"))]
            let given = ();
            let expected = U::FLAG_NAMES;
            return Err(BitFlagsParseError {
                given,
                separator,
                expected,
            });
        }

        Ok(this)
    }
}

// Const traits are not stable yet, so the const methods are implemented for
// each integer type separately via a macro.
// See: https://github.com/rust-lang/rust/issues/143874
macro_rules! impl_bit_flags {
    ($ty:ty) => {
        impl<U> BitFlags<$ty, U>
        where
            U: ?Sized,
        {
            /// Creates a flag set from a single [`BitFlag`].
            ///
            /// The bit index is not validated against
            /// [`BitFlagsSpec::VALID_BITS_MASK`].
            /// The resulting value may contain an invalid bit.
            ///
            /// If the flag's index is outside the width of `T`, the result is
            /// [`BitFlags::empty`].
            #[inline]
            #[must_use]
            pub const fn from_flag(flag: BitFlag<$ty, U>) -> Self {
                Self::from_bit_retain(flag.bit())
            }

            /// Creates a flag set with only the bit at index `bit` set.
            ///
            /// The bit index is not validated against
            /// [`BitFlagsSpec::VALID_BITS_MASK`].
            /// The resulting value may contain an invalid bit.
            /// Use [`BitFlags::try_from_bit`] or
            /// [`BitFlags::from_bits_truncate`] when validation or truncation
            /// is required.
            ///
            /// If `bit` is outside the width of `T`, the result is
            /// [`BitFlags::empty`].
            #[inline]
            #[must_use]
            pub const fn from_bit_retain(bit: u8) -> Self {
                #[expect(clippy::as_conversions, reason = "supported in const functions")]
                let bit = bit as u32;
                if bit < <$ty>::BITS {
                    Self::from_bits_retain(1 << bit)
                } else {
                    Self::empty()
                }
            }

            /// Creates a flag set with only the bit at index `bit` set,
            /// clearing the bit if it is not valid for the tag.
            ///
            /// This is the bit-index counterpart to
            /// [`BitFlags::from_bits_truncate`].
            /// If `bit` is outside the width of `T`, or if the corresponding
            /// bit is not present in [`BitFlagsSpec::VALID_BITS_MASK`], the
            /// result is [`BitFlags::empty`].
            ///
            /// The result always contains either exactly one bit or no bits.
            ///
            /// Use [`BitFlags::try_from_bit`] when the caller needs to
            /// distinguish a valid index from an invalid one.
            #[inline]
            #[must_use]
            pub const fn from_bit_truncate(bit: u8) -> Self
            where
                U: BitFlagsSpec<$ty>,
            {
                #[expect(clippy::as_conversions, reason = "supported in const functions")]
                let bit = bit as u32;
                if bit < <$ty>::BITS {
                    Self::from_bits_truncate(1 << bit)
                } else {
                    Self::empty()
                }
            }

            /// Creates a flag set from bit index `bit` if that bit is valid.
            ///
            /// Returns `None` if `bit` is outside the width of `T` or if the
            /// resulting bit is not present in
            /// [`BitFlagsSpec::VALID_BITS_MASK`].
            #[inline]
            #[must_use]
            pub const fn try_from_bit(bit: u8) -> Option<Self>
            where
                U: BitFlagsSpec<$ty>,
            {
                #[expect(clippy::as_conversions, reason = "supported in const functions")]
                let bit = bit as u32;
                if bit < <$ty>::BITS {
                    Self::try_from_bits(1 << bit)
                } else {
                    None
                }
            }

            /// Creates a flag set from raw bits if all set bits are valid.
            ///
            /// Returns `None` if `bits` contains any bit not present in
            /// [`BitFlagsSpec::VALID_BITS_MASK`].
            ///
            /// Use [`BitFlags::from_bits_retain`] to keep invalid bits, or
            /// [`BitFlags::from_bits_truncate`] to clear them.
            #[doc(alias = "from_bits")]
            #[inline]
            #[must_use]
            pub const fn try_from_bits(bits: $ty) -> Option<Self>
            where
                U: BitFlagsSpec<$ty>,
            {
                if bits & !U::VALID_BITS_MASK == 0 {
                    Some(Self(bits, PhantomData))
                } else {
                    None
                }
            }

            /// Creates a flag set from raw bits, clearing any bits not present in
            /// [`BitFlagsSpec::VALID_BITS_MASK`].
            ///
            /// This always succeeds and never stores invalid bits.
            #[inline]
            #[must_use]
            pub const fn from_bits_truncate(bits: $ty) -> Self
            where
                U: BitFlagsSpec<$ty>,
            {
                Self(bits & U::VALID_BITS_MASK, PhantomData)
            }

            /// Returns `true` if no bits are set.
            ///
            /// This checks the raw stored bits.
            /// A value containing only invalid bits is not empty.
            #[inline]
            #[must_use]
            pub const fn is_empty(&self) -> bool {
                self.0 == 0
            }

            /// Returns `true` if all set bits in `self` are valid for this tag.
            ///
            /// A `BitFlags` value can contain bits not present in
            /// [`BitFlagsSpec::VALID_BITS_MASK`] after construction with
            /// [`BitFlags::from_bits_retain`] or after raw-bit operations such as
            /// [`BitFlags::insert`], [`BitFlags::toggle`], and [`BitFlags::union`].
            /// This method returns `false` for such values.
            ///
            /// Use [`BitFlags::truncate`] or [`BitFlags::from_bits_truncate`] to
            /// restrict a value to its valid bits.
            #[doc(alias = "is_all")]
            #[inline]
            #[must_use]
            pub const fn is_valid(&self) -> bool
            where
                U: BitFlagsSpec<$ty>,
            {
                self.bits() & !U::VALID_BITS_MASK == 0
            }

            /// Returns `true` if `self` and `other` have at least one set bit in
            /// common.
            ///
            /// This compares raw bits.
            /// Invalid bits participate in the comparison if they are present.
            #[inline]
            #[must_use]
            pub const fn intersects(&self, other: Self) -> bool {
                (self.0 & other.0) != 0
            }

            /// Returns `true` if all bits set in `other` are also set in `self`.
            ///
            /// This compares raw bits.
            /// Invalid bits participate in the comparison if they are present.
            #[inline]
            #[must_use]
            pub const fn contains(&self, other: Self) -> bool {
                (self.0 & other.0) == other.0
            }

            /// Inserts all bits from `other`.
            ///
            /// This is a raw-bit operation.
            /// It does not validate or clear invalid bits.
            /// Inserting `other` can introduce invalid bits into `self`.
            #[inline]
            pub const fn insert(&mut self, other: Self) {
                self.0 |= other.0;
            }

            /// Removes all bits from `self`, including any invalid bits.
            ///
            /// This is equivalent to assigning [`BitFlags::empty`] to `self`.
            #[inline]
            pub const fn clear(&mut self) {
                self.0 = 0;
            }

            /// Clears all bits not present in
            /// [`BitFlagsSpec::VALID_BITS_MASK`].
            ///
            /// This leaves `self` unchanged if it already contains only valid
            /// bits.
            #[inline]
            pub const fn truncate(&mut self)
            where
                U: BitFlagsSpec<$ty>,
            {
                self.0 &= U::VALID_BITS_MASK
            }

            /// Removes all bits from `other`.
            ///
            /// This is a raw-bit operation.
            /// It cannot introduce new bits, but it does not clear any other
            /// invalid bits that may already be present.
            #[inline]
            pub const fn remove(&mut self, other: Self) {
                self.0 &= !other.0;
            }

            /// Toggles all bits from `other`.
            ///
            /// This is a raw-bit operation.
            /// It does not validate or clear invalid bits.
            /// Toggling `other` can introduce invalid bits into `self`.
            #[inline]
            pub const fn toggle(&mut self, other: Self) {
                self.0 ^= other.0;
            }

            /// Inserts `other` if `value` is `true`, or removes `other` if
            /// `value` is `false`.
            ///
            /// This is a raw-bit operation and follows the same invalid-bit
            /// behavior as [`BitFlags::insert`] and [`BitFlags::remove`].
            #[inline]
            pub const fn set(&mut self, other: Self, value: bool) {
                if value {
                    self.insert(other)
                } else {
                    self.remove(other)
                }
            }

            /// Returns the intersection of `self` and `other`.
            ///
            /// This is a raw-bit operation.
            /// Invalid bits in either operand are preserved when they are set
            /// in both operands.
            #[inline]
            #[must_use]
            pub const fn intersection(self, other: Self) -> Self {
                Self(self.0 & other.0, PhantomData)
            }

            /// Returns the union of `self` and `other`.
            ///
            /// This is a raw-bit operation.
            /// Invalid bits in either operand are preserved.
            #[inline]
            #[must_use]
            pub const fn union(self, other: Self) -> Self {
                Self(self.0 | other.0, PhantomData)
            }

            /// Returns the difference of `self` and `other`.
            ///
            /// The result contains bits that are set in `self` but not in
            /// `other`.
            /// This is a raw-bit operation.
            /// Invalid bits already present in `self` are preserved unless they
            /// are also set in `other`.
            #[inline]
            #[must_use]
            pub const fn difference(self, other: Self) -> Self {
                Self(self.0 & !other.0, PhantomData)
            }

            /// Returns the symmetric difference of `self` and `other`.
            ///
            /// The result contains bits that are set in exactly one of `self`
            /// or `other`.
            /// This is a raw-bit operation.
            /// Invalid bits participate and may be preserved.
            #[inline]
            #[must_use]
            pub const fn symmetric_difference(self, other: Self) -> Self {
                Self(self.0 ^ other.0, PhantomData)
            }

            /// Returns the complement of `self`.
            ///
            /// All valid bits not set in `self` become set, and all invalid
            /// bits become unset.
            /// The result always contains only valid bits.
            #[inline]
            #[must_use]
            pub const fn complement(self) -> Self
            where
                U: BitFlagsSpec<$ty>,
            {
                Self(!self.0 & U::VALID_BITS_MASK, PhantomData)
            }
        }

        impl<U> From<BitFlags<$ty, U>> for $ty
        where
            U: ?Sized,
        {
            #[inline]
            fn from(flags: BitFlags<$ty, U>) -> Self {
                flags.0
            }
        }
    };
}

impl_bit_flags!(u8);
impl_bit_flags!(u16);
impl_bit_flags!(u32);
impl_bit_flags!(u64);
impl_bit_flags!(u128);
impl_bit_flags!(usize);

impl_bit_flags!(i8);
impl_bit_flags!(i16);
impl_bit_flags!(i32);
impl_bit_flags!(i64);
impl_bit_flags!(i128);
impl_bit_flags!(isize);

impl<T, U> Copy for BitFlags<T, U>
where
    T: Copy,
    U: ?Sized,
{
}

impl<T, U> Clone for BitFlags<T, U>
where
    T: Clone,
    U: ?Sized,
{
    #[inline]
    fn clone(&self) -> Self {
        Self(self.0.clone(), PhantomData)
    }
}

impl<T, U> Eq for BitFlags<T, U>
where
    T: Eq,
    U: ?Sized,
{
}

impl<T, U> PartialEq for BitFlags<T, U>
where
    T: PartialEq,
    U: ?Sized,
{
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.0 == other.0
    }
}

impl<T, U> PartialEq<BitFlag<T, U>> for BitFlags<T, U>
where
    T: Copy + PartialEq + util::IntOpsExt,
    U: ?Sized,
{
    #[inline]
    fn eq(&self, other: &BitFlag<T, U>) -> bool {
        self.eq(&Self::from(*other))
    }
}

impl<T, U> PartialEq<BitFlags<T, U>> for BitFlag<T, U>
where
    T: Copy + PartialEq + util::IntOpsExt,
    U: ?Sized,
{
    #[inline]
    fn eq(&self, other: &BitFlags<T, U>) -> bool {
        BitFlags::from(*self).eq(other)
    }
}

impl<T, U> Ord for BitFlags<T, U>
where
    T: Ord,
    U: ?Sized,
{
    #[inline]
    fn cmp(&self, other: &Self) -> Ordering {
        self.0.cmp(&other.0)
    }
}

impl<T, U> PartialOrd for BitFlags<T, U>
where
    T: PartialOrd,
    U: ?Sized,
{
    #[inline]
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        self.0.partial_cmp(&other.0)
    }
}

impl<T, U> PartialOrd<BitFlag<T, U>> for BitFlags<T, U>
where
    T: Copy + PartialOrd + util::IntOpsExt,
    U: ?Sized,
{
    #[inline]
    fn partial_cmp(&self, other: &BitFlag<T, U>) -> Option<Ordering> {
        self.partial_cmp(&Self::from(*other))
    }
}

impl<T, U> PartialOrd<BitFlags<T, U>> for BitFlag<T, U>
where
    T: Copy + PartialOrd + util::IntOpsExt,
    U: ?Sized,
{
    #[inline]
    fn partial_cmp(&self, other: &BitFlags<T, U>) -> Option<Ordering> {
        BitFlags::from(*self).partial_cmp(other)
    }
}

impl<T, U> Hash for BitFlags<T, U>
where
    T: Hash,
    U: ?Sized,
{
    #[inline]
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.0.hash(state);
    }
}

impl<T, U> Default for BitFlags<T, U>
where
    T: Default,
    U: ?Sized,
{
    #[inline]
    fn default() -> Self {
        Self(T::default(), PhantomData)
    }
}

impl<T, U> From<BitFlag<T, U>> for BitFlags<T, U>
where
    T: util::IntOpsExt,
    U: ?Sized,
{
    #[inline]
    fn from(flag: BitFlag<T, U>) -> Self {
        let bit = flag.bit();
        T::ONE
            .checked_shl(u32::from(bit))
            .map_or_else(Self::empty, Self::from_bits_retain)
    }
}

impl<T, U> AsRef<T> for BitFlags<T, U>
where
    U: ?Sized,
{
    #[inline]
    fn as_ref(&self) -> &T {
        &self.0
    }
}

impl<T, U> Borrow<T> for BitFlags<T, U>
where
    U: ?Sized,
{
    #[inline]
    fn borrow(&self) -> &T {
        &self.0
    }
}

impl<T, U> BitAnd<Self> for BitFlags<T, U>
where
    T: BitAnd<T, Output = T>,
    U: ?Sized,
{
    type Output = Self;

    #[inline]
    fn bitand(self, rhs: Self) -> Self::Output {
        Self(self.0 & rhs.0, PhantomData)
    }
}

impl<T, U> BitAnd<BitFlag<T, U>> for BitFlags<T, U>
where
    T: BitAnd<T, Output = T> + util::IntOpsExt,
    U: ?Sized,
{
    type Output = Self;

    #[inline]
    fn bitand(self, rhs: BitFlag<T, U>) -> Self::Output {
        self.bitand(Self::from(rhs))
    }
}

impl<T, U> BitAnd<BitFlags<T, U>> for BitFlag<T, U>
where
    T: BitAnd<T, Output = T> + util::IntOpsExt,
    U: ?Sized,
{
    type Output = BitFlags<T, U>;

    #[inline]
    fn bitand(self, rhs: BitFlags<T, U>) -> Self::Output {
        BitFlags::from(self).bitand(rhs)
    }
}

impl<T, U> BitAndAssign<Self> for BitFlags<T, U>
where
    T: BitAndAssign<T>,
    U: ?Sized,
{
    #[inline]
    fn bitand_assign(&mut self, rhs: Self) {
        self.0 &= rhs.0;
    }
}

impl<T, U> BitAndAssign<BitFlag<T, U>> for BitFlags<T, U>
where
    T: BitAndAssign<T> + util::IntOpsExt,
    U: ?Sized,
{
    #[inline]
    fn bitand_assign(&mut self, rhs: BitFlag<T, U>) {
        self.bitand_assign(Self::from(rhs));
    }
}

impl<T, U> BitOr<Self> for BitFlags<T, U>
where
    T: BitOr<T, Output = T>,
    U: ?Sized,
{
    type Output = Self;

    #[inline]
    fn bitor(self, rhs: Self) -> Self::Output {
        Self(self.0 | rhs.0, PhantomData)
    }
}

impl<T, U> BitOr<BitFlag<T, U>> for BitFlags<T, U>
where
    T: BitOr<T, Output = T> + util::IntOpsExt,
    U: ?Sized,
{
    type Output = Self;

    #[inline]
    fn bitor(self, rhs: BitFlag<T, U>) -> Self::Output {
        self.bitor(Self::from(rhs))
    }
}

impl<T, U> BitOr<BitFlags<T, U>> for BitFlag<T, U>
where
    T: BitOr<T, Output = T> + util::IntOpsExt,
    U: ?Sized,
{
    type Output = BitFlags<T, U>;

    #[inline]
    fn bitor(self, rhs: BitFlags<T, U>) -> Self::Output {
        BitFlags::from(self).bitor(rhs)
    }
}

impl<T, U> BitOrAssign<Self> for BitFlags<T, U>
where
    T: BitOrAssign<T>,
    U: ?Sized,
{
    #[inline]
    fn bitor_assign(&mut self, rhs: Self) {
        self.0 |= rhs.0;
    }
}

impl<T, U> BitOrAssign<BitFlag<T, U>> for BitFlags<T, U>
where
    T: BitOrAssign<T> + util::IntOpsExt,
    U: ?Sized,
{
    #[inline]
    fn bitor_assign(&mut self, rhs: BitFlag<T, U>) {
        self.bitor_assign(Self::from(rhs));
    }
}

impl<T, U> BitXor<Self> for BitFlags<T, U>
where
    T: BitXor<T, Output = T>,
    U: ?Sized,
{
    type Output = Self;

    #[inline]
    fn bitxor(self, rhs: Self) -> Self::Output {
        Self(self.0 ^ rhs.0, PhantomData)
    }
}

impl<T, U> BitXor<BitFlag<T, U>> for BitFlags<T, U>
where
    T: BitXor<T, Output = T> + util::IntOpsExt,
    U: ?Sized,
{
    type Output = Self;

    #[inline]
    fn bitxor(self, rhs: BitFlag<T, U>) -> Self::Output {
        self.bitxor(Self::from(rhs))
    }
}

impl<T, U> BitXor<BitFlags<T, U>> for BitFlag<T, U>
where
    T: BitXor<T, Output = T> + util::IntOpsExt,
    U: ?Sized,
{
    type Output = BitFlags<T, U>;

    #[inline]
    fn bitxor(self, rhs: BitFlags<T, U>) -> Self::Output {
        BitFlags::from(self).bitxor(rhs)
    }
}

impl<T, U> BitXorAssign<Self> for BitFlags<T, U>
where
    T: BitXorAssign<T>,
    U: ?Sized,
{
    #[inline]
    fn bitxor_assign(&mut self, rhs: Self) {
        self.0 ^= rhs.0;
    }
}

impl<T, U> BitXorAssign<BitFlag<T, U>> for BitFlags<T, U>
where
    T: BitXorAssign<T> + util::IntOpsExt,
    U: ?Sized,
{
    #[inline]
    fn bitxor_assign(&mut self, rhs: BitFlag<T, U>) {
        self.bitxor_assign(Self::from(rhs));
    }
}

impl<T, U> Sub<Self> for BitFlags<T, U>
where
    T: Not<Output = T> + BitAnd<T, Output = T>,
    U: ?Sized,
{
    type Output = Self;

    #[inline]
    fn sub(self, rhs: Self) -> Self::Output {
        Self(self.0 & !rhs.0, PhantomData)
    }
}

impl<T, U> Sub<BitFlag<T, U>> for BitFlags<T, U>
where
    T: Not<Output = T> + BitAnd<T, Output = T> + util::IntOpsExt,
    U: ?Sized,
{
    type Output = Self;

    #[inline]
    fn sub(self, rhs: BitFlag<T, U>) -> Self::Output {
        self.sub(Self::from(rhs))
    }
}

impl<T, U> Sub<BitFlags<T, U>> for BitFlag<T, U>
where
    T: Not<Output = T> + BitAnd<T, Output = T> + util::IntOpsExt,
    U: ?Sized,
{
    type Output = BitFlags<T, U>;

    #[inline]
    fn sub(self, rhs: BitFlags<T, U>) -> Self::Output {
        BitFlags::from(self).sub(rhs)
    }
}

impl<T, U> SubAssign<Self> for BitFlags<T, U>
where
    T: Not<Output = T> + BitAndAssign<T>,
    U: ?Sized,
{
    #[inline]
    fn sub_assign(&mut self, rhs: Self) {
        self.0 &= !rhs.0;
    }
}

impl<T, U> SubAssign<BitFlag<T, U>> for BitFlags<T, U>
where
    T: Not<Output = T> + BitAndAssign<T> + util::IntOpsExt,
    U: ?Sized,
{
    #[inline]
    fn sub_assign(&mut self, rhs: BitFlag<T, U>) {
        self.sub_assign(Self::from(rhs));
    }
}

impl<T, U> Not for BitFlags<T, U>
where
    T: 'static + Not<Output = T> + BitAnd<T, Output = T>,
    U: ?Sized + BitFlagsSpec<T>,
{
    type Output = Self;

    #[inline]
    fn not(self) -> Self::Output {
        Self(!self.0 & U::VALID_BITS_MASK, PhantomData)
    }
}

impl<T, U> fmt::Display for BitFlags<T, U>
where
    T: 'static
        + Copy
        + PartialEq
        + Not<Output = T>
        + BitAnd<T, Output = T>
        + Shl<usize, Output = T>
        + fmt::LowerHex
        + util::IntOpsExt,
    U: ?Sized + BitFlagsSpec<T>,
{
    #[expect(clippy::missing_inline_in_public_items, reason = "bloats binary size")]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut separator = "";
        let mut this = self.0;
        for (i, names) in U::FLAG_NAMES.iter().enumerate() {
            let Some(i) = u32::try_from(i).ok() else {
                break; // `FLAG_NAMES` with more than `u32::MAX` entries.
            };
            let Some(mask) = T::ONE.checked_shl(i) else {
                break;
            };
            if let Some(name) = names.first() {
                let new_this = this & !mask;
                if this != new_this {
                    write!(f, "{separator}{name}")?;
                    separator = " | ";
                }
                this = new_this;
            }
        }
        if this != T::ZERO {
            write!(f, "{separator}{this:#x}")?;
        }
        Ok(())
    }
}

impl<T, U> fmt::Debug for BitFlags<T, U>
where
    T: fmt::LowerHex,
    U: ?Sized,
{
    #[expect(clippy::missing_inline_in_public_items, reason = "bloats binary size")]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "BitFlags({:#x}, PhantomData<{}>)",
            self.0,
            type_name::<U>()
        )
    }
}

impl<T, U> fmt::Binary for BitFlags<T, U>
where
    T: fmt::Binary,
    U: ?Sized,
{
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Binary::fmt(&self.0, f)
    }
}

impl<T, U> fmt::Octal for BitFlags<T, U>
where
    T: fmt::Octal,
    U: ?Sized,
{
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Octal::fmt(&self.0, f)
    }
}

impl<T, U> fmt::LowerHex for BitFlags<T, U>
where
    T: fmt::LowerHex,
    U: ?Sized,
{
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::LowerHex::fmt(&self.0, f)
    }
}

impl<T, U> fmt::UpperHex for BitFlags<T, U>
where
    T: fmt::UpperHex,
    U: ?Sized,
{
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::UpperHex::fmt(&self.0, f)
    }
}

impl<T, U> FromStr for BitFlags<T, U>
where
    T: 'static + Copy + BitOrAssign<T> + util::IntOpsExt,
    U: ?Sized + BitFlagsSpec<T>,
{
    type Err = BitFlagsParseError;

    #[inline]
    fn from_str(input: &str) -> Result<Self, Self::Err> {
        Self::try_from_str(input, "|", U::DEFAULT_NAME_MATCHER)
    }
}

impl<T, U> IntoIterator for BitFlags<T, U>
where
    T: Copy + Not<Output = T> + BitAndAssign<T> + util::IntOpsExt,
    U: ?Sized,
{
    type IntoIter = BitFlagsIter<T, U>;
    type Item = BitFlag<T, U>;

    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        BitFlagsIter::new(self)
    }
}

impl<T, U> IntoIterator for &BitFlags<T, U>
where
    T: Copy + Not<Output = T> + BitAndAssign<T> + util::IntOpsExt,
    U: ?Sized,
{
    type IntoIter = BitFlagsIter<T, U>;
    type Item = BitFlag<T, U>;

    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        BitFlagsIter::new(*self)
    }
}

#[expect(
    clippy::into_iter_without_iter,
    reason = "`iter` and `iter_mut` are the same"
)]
impl<T, U> IntoIterator for &mut BitFlags<T, U>
where
    T: Copy + Not<Output = T> + BitAndAssign<T> + util::IntOpsExt,
    U: ?Sized,
{
    type IntoIter = BitFlagsIter<T, U>;
    type Item = BitFlag<T, U>;

    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        BitFlagsIter::new(*self)
    }
}

impl<T, U> Extend<Self> for BitFlags<T, U>
where
    T: BitOrAssign<T>,
    U: ?Sized,
{
    #[inline]
    fn extend<I>(&mut self, iter: I)
    where
        I: IntoIterator<Item = Self>,
    {
        for other in iter {
            self.0 |= other.0;
        }
    }
}

impl<T, U> Extend<BitFlag<T, U>> for BitFlags<T, U>
where
    T: BitOrAssign<T> + util::IntOpsExt,
    U: ?Sized,
{
    #[inline]
    fn extend<I>(&mut self, iter: I)
    where
        I: IntoIterator<Item = BitFlag<T, U>>,
    {
        for other in iter {
            *self |= Self::from(other);
        }
    }
}

impl<T, U> FromIterator<Self> for BitFlags<T, U>
where
    T: BitOrAssign<T> + util::IntOpsExt,
    U: ?Sized,
{
    #[inline]
    fn from_iter<I>(iter: I) -> Self
    where
        I: IntoIterator<Item = Self>,
    {
        let mut this = Self(T::ZERO, PhantomData);
        for other in iter {
            this.0 |= other.0;
        }
        this
    }
}

impl<T, U> FromIterator<BitFlag<T, U>> for BitFlags<T, U>
where
    T: BitOrAssign<T> + util::IntOpsExt,
    U: ?Sized,
{
    #[inline]
    fn from_iter<I>(iter: I) -> Self
    where
        I: IntoIterator<Item = BitFlag<T, U>>,
    {
        let mut this = Self(T::ZERO, PhantomData);
        for other in iter {
            this |= Self::from(other);
        }
        this
    }
}

#[cfg(feature = "arbitrary")]
#[cfg_attr(docsrs, doc(cfg(feature = "arbitrary")))]
impl<'a, T, U> arbitrary::Arbitrary<'a> for BitFlags<T, U>
where
    T: arbitrary::Arbitrary<'a>,
    U: ?Sized,
{
    #[inline]
    fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
        T::arbitrary(u).map(|u| Self(u, PhantomData))
    }

    #[inline]
    fn size_hint(depth: usize) -> (usize, Option<usize>) {
        T::size_hint(depth)
    }
}

#[cfg(feature = "bytemuck")]
#[cfg_attr(docsrs, doc(cfg(feature = "bytemuck")))]
// SAFETY: All fields are valid when their memory is entirely zeroed out.
unsafe impl<T, U> bytemuck::Zeroable for BitFlags<T, U>
where
    T: bytemuck::Zeroable,
    U: ?Sized,
{
}

#[cfg(feature = "bytemuck")]
#[cfg_attr(docsrs, doc(cfg(feature = "bytemuck")))]
// SAFETY: The type is Copy, Zeroable, has no padding bytes, and any
// bit pattern of the correct size is a valid instance of this type.
unsafe impl<T, U> bytemuck::Pod for BitFlags<T, U>
where
    T: bytemuck::Pod,
    U: 'static + ?Sized,
{
}

#[cfg(feature = "serde")]
#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
impl<T, U> serde::Serialize for BitFlags<T, U>
where
    T: 'static
        + Copy
        + PartialEq
        + Not<Output = T>
        + BitAnd<T, Output = T>
        + Shl<usize, Output = T>
        + fmt::LowerHex
        + util::IntOpsExt,
    U: ?Sized + BitFlagsSpec<T>,
{
    #[inline]
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        // Replicates the behavior of `bitflags`-based implementation.
        serializer.collect_str(&self)
    }
}

#[cfg(feature = "serde")]
#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
impl<'de, T, U> serde::Deserialize<'de> for BitFlags<T, U>
where
    T: 'static + Copy + BitOrAssign<T> + util::IntOpsExt,
    U: ?Sized + BitFlagsSpec<T>,
{
    #[inline]
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        deserializer.deserialize_str(BitFlagsVisitor::<T, U>(PhantomData, PhantomData))
    }
}

#[cfg(feature = "serde")]
#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
impl<T, U> serde::de::Visitor<'_> for BitFlagsVisitor<T, U>
where
    T: 'static + Copy + BitOrAssign<T> + util::IntOpsExt,
    U: ?Sized + BitFlagsSpec<T>,
{
    type Value = BitFlags<T, U>;

    fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt_expected(f, "|", U::FLAG_NAMES)
    }

    #[inline]
    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        Self::Value::from_str(value).map_err(E::custom)
    }
}

/// An error encountered while parsing flags from text.
#[cfg_attr(
    not(feature = "alloc"),
    expect(
        missing_copy_implementations,
        reason = "the payload is feature-dependent"
    )
)]
#[derive(Clone, Debug)]
pub struct BitFlagsParseError {
    #[cfg(not(feature = "alloc"))]
    given: (),
    #[cfg(feature = "alloc")]
    given: alloc::string::String,

    separator: &'static str,
    expected: &'static [&'static [&'static str]],
}

impl fmt::Display for BitFlagsParseError {
    #[expect(clippy::missing_inline_in_public_items, reason = "bloats binary size")]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let named_flags = self
            .expected
            .iter()
            .filter(|variants| !variants.is_empty())
            .count();

        if named_flags == 0 {
            write!(f, "unrecognized hex flag, ")?;
        } else {
            write!(f, "unrecognized named flag or hex flag, ")?;
        }
        #[cfg(feature = "alloc")]
        write!(f, "given: \"{}\", expected ", self.given)?;
        #[cfg(not(feature = "alloc"))]
        write!(f, "expected ")?;
        fmt_expected(f, self.separator, self.expected)?;

        #[cfg(not(feature = "alloc"))]
        let () = self.given;

        Ok(())
    }
}

impl core::error::Error for BitFlagsParseError {}

/// Writes the expected flag format for [`BitFlagsParseError`] and serde
/// visitors.
#[inline]
fn fmt_expected(
    f: &mut fmt::Formatter<'_>,
    separator: &'static str,
    expected: &'static [&'static [&'static str]],
) -> fmt::Result {
    let named_flags = expected
        .iter()
        .filter(|variants| !variants.is_empty())
        .count();

    if named_flags == 0 {
        write!(f, "a valid hex flag with \"0x\" prefix")?;
    } else {
        write!(f, "\"\", or a \"{separator}\"-separated set of")?;

        let mut separator = " ";
        for names in expected {
            if let Some(name) = names.first() {
                write!(f, "{separator}\"{name}\"")?;
                separator = ", ";
            }
        }
        write!(f, ", or a valid hex flag with \"0x\" prefix")?;
    }
    Ok(())
}