Debian Codegraph @

third_party/rust/flagset/src/lib.rs

raw
1 //
2 // Copyright 2019 Red Hat, Inc.
3 //
4 // Author: Nathaniel McCallum <[email protected]>
5 //
6 // Licensed under the Apache License, Version 2.0 (the "License");
7 // you may not use this file except in compliance with the License.
8 // You may obtain a copy of the License at
9 //
10 // http://www.apache.org/licenses/LICENSE-2.0
11 //
12 // Unless required by applicable law or agreed to in writing, software
13 // distributed under the License is distributed on an "AS IS" BASIS,
14 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 // See the License for the specific language governing permissions and
16 // limitations under the License.
17 //
18
19 //! # Welcome to FlagSet!
20 //!
21 //! FlagSet is a new, ergonomic approach to handling flags that combines the
22 //! best of existing crates like `bitflags` and `enumflags` without their
23 //! downsides.
24 //!
25 //! ## Existing Implementations
26 //!
27 //! The `bitflags` crate has long been part of the Rust ecosystem.
28 //! Unfortunately, it doesn't feel like natural Rust. The `bitflags` crate
29 //! uses a wierd struct format to define flags. Flags themselves are just
30 //! integers constants, so there is little type-safety involved. But it doesn't
31 //! have any dependencies. It also allows you to define implied flags (otherwise
32 //! known as overlapping flags).
33 //!
34 //! The `enumflags` crate tried to improve on `bitflags` by using enumerations
35 //! to define flags. This was a big improvement to the natural feel of the code.
36 //! Unfortunately, there are some design flaws. To generate the flags,
37 //! procedural macros were used. This implied two separate crates plus
38 //! additional dependencies. Further, `enumflags` specifies the size of the
39 //! flags using a `repr($size)` attribute. Unfortunately, this attribute
40 //! cannot resolve type aliases, such as `c_int`. This makes `enumflags` a
41 //! poor fit for FFI, which is the most important place for a flags library.
42 //! The `enumflags` crate also disallows overlapping flags and is not
43 //! maintained.
44 //!
45 //! FlagSet improves on both of these by adopting the `enumflags` natural feel
46 //! and the `bitflags` mode of flag generation; as well as additional API usage
47 //! niceties. FlagSet has no dependencies and is extensively documented and
48 //! tested. It also tries very hard to prevent you from making mistakes by
49 //! avoiding external usage of the integer types. FlagSet is also a zero-cost
50 //! abstraction: all functions are inlineable and should reduce to the core
51 //! integer operations. FlagSet also does not depend on stdlib, so it can be
52 //! used in `no_std` libraries and applications.
53 //!
54 //! ## Defining Flags
55 //!
56 //! Flags are defined using the `flags!` macro:
57 //!
58 //! ```
59 //! use flagset::{FlagSet, flags};
60 //! use std::os::raw::c_int;
61 //!
62 //! flags! {
63 //! enum FlagsA: u8 {
64 //! Foo,
65 //! Bar,
66 //! Baz,
67 //! }
68 //!
69 //! enum FlagsB: c_int {
70 //! Foo,
71 //! Bar,
72 //! Baz,
73 //! }
74 //! }
75 //! ```
76 //!
77 //! Notice that a flag definition looks just like a regular enumeration, with
78 //! the addition of the field-size type. The field-size type is required and
79 //! can be either a type or a type alias. Both examples are given above.
80 //!
81 //! Also note that the field-size type specifies the size of the corresponding
82 //! `FlagSet` type, not size of the enumeration itself. To specify the size of
83 //! the enumeration, use the `repr($size)` attribute as specified below.
84 //!
85 //! ## Flag Values
86 //!
87 //! Flags often need values assigned to them. This can be done implicitly,
88 //! where the value depends on the order of the flags:
89 //!
90 //! ```
91 //! use flagset::{FlagSet, flags};
92 //!
93 //! flags! {
94 //! enum Flags: u16 {
95 //! Foo, // Implicit Value: 0b0001
96 //! Bar, // Implicit Value: 0b0010
97 //! Baz, // Implicit Value: 0b0100
98 //! }
99 //! }
100 //! ```
101 //!
102 //! Alternatively, flag values can be defined explicitly, by specifying any
103 //! `const` expression:
104 //!
105 //! ```
106 //! use flagset::{FlagSet, flags};
107 //!
108 //! flags! {
109 //! enum Flags: u16 {
110 //! Foo = 0x01, // Explicit Value: 0b0001
111 //! Bar = 2, // Explicit Value: 0b0010
112 //! Baz = 0b0100, // Explicit Value: 0b0100
113 //! }
114 //! }
115 //! ```
116 //!
117 //! Flags can also overlap or "imply" other flags:
118 //!
119 //! ```
120 //! use flagset::{FlagSet, flags};
121 //!
122 //! flags! {
123 //! enum Flags: u16 {
124 //! Foo = 0b0001,
125 //! Bar = 0b0010,
126 //! Baz = 0b0110, // Implies Bar
127 //! All = (Flags::Foo | Flags::Bar | Flags::Baz).bits(),
128 //! }
129 //! }
130 //! ```
131 //!
132 //! ## Specifying Attributes
133 //!
134 //! Attributes can be used on the enumeration itself or any of the values:
135 //!
136 //! ```
137 //! use flagset::{FlagSet, flags};
138 //!
139 //! flags! {
140 //! #[derive(PartialOrd, Ord)]
141 //! enum Flags: u8 {
142 //! Foo,
143 //! #[deprecated]
144 //! Bar,
145 //! Baz,
146 //! }
147 //! }
148 //! ```
149 //!
150 //! ## Collections of Flags
151 //!
152 //! A collection of flags is a `FlagSet<T>`. If you are storing the flags in
153 //! memory, the raw `FlagSet<T>` type should be used. However, if you want to
154 //! receive flags as an input to a function, you should use
155 //! `impl Into<FlagSet<T>>`. This allows for very ergonomic APIs:
156 //!
157 //! ```
158 //! use flagset::{FlagSet, flags};
159 //!
160 //! flags! {
161 //! enum Flags: u8 {
162 //! Foo,
163 //! Bar,
164 //! Baz,
165 //! }
166 //! }
167 //!
168 //! struct Container(FlagSet<Flags>);
169 //!
170 //! impl Container {
171 //! fn new(flags: impl Into<FlagSet<Flags>>) -> Container {
172 //! Container(flags.into())
173 //! }
174 //! }
175 //!
176 //! assert_eq!(Container::new(Flags::Foo | Flags::Bar).0.bits(), 0b011);
177 //! assert_eq!(Container::new(Flags::Foo).0.bits(), 0b001);
178 //! assert_eq!(Container::new(None).0.bits(), 0b000);
179 //! ```
180 //!
181 //! ## Operations
182 //!
183 //! Operations can be performed on a `FlagSet<F>` or on individual flags:
184 //!
185 //! | Operator | Assignment Operator | Meaning |
186 //! |----------|---------------------|------------------------|
187 //! | \| | \|= | Union |
188 //! | & | &= | Intersection |
189 //! | ^ | ^= | Toggle specified flags |
190 //! | - | -= | Difference |
191 //! | % | %= | Symmetric difference |
192 //! | ! | | Toggle all flags |
193 //!
194 #![cfg_attr(
195 feature = "serde",
196 doc = r#"
197
198 ## Optional Serde support
199
200 [Serde] support can be enabled with the 'serde' feature flag. You can then serialize and
201 deserialize `FlagSet<T>` to and from any of the [supported formats]:
202
203 ```
204 use flagset::{FlagSet, flags};
205
206 flags! {
207 enum Flags: u8 {
208 Foo,
209 Bar,
210 }
211 }
212
213 let flagset = Flags::Foo | Flags::Bar;
214 let json = serde_json::to_string(&flagset).unwrap();
215 let flagset: FlagSet<Flags> = serde_json::from_str(&json).unwrap();
216 assert_eq!(flagset.bits(), 0b011);
217 ```
218
219 For serialization and deserialization of flags enum itself, you can use the [`serde_repr`] crate
220 (or implement `serde::ser::Serialize` and `serde:de::Deserialize` manually), combined with the
221 appropriate `repr` attribute:
222
223 ```
224 use flagset::{FlagSet, flags};
225 use serde_repr::{Serialize_repr, Deserialize_repr};
226
227 flags! {
228 #[repr(u8)]
229 #[derive(Deserialize_repr, Serialize_repr)]
230 enum Flags: u8 {
231 Foo,
232 Bar,
233 }
234 }
235
236 let json = serde_json::to_string(&Flags::Foo).unwrap();
237 let flag: Flags = serde_json::from_str(&json).unwrap();
238 assert_eq!(flag, Flags::Foo);
239 ```
240
241 [Serde]: https://serde.rs/
242 [supported formats]: https://serde.rs/#data-formats
243 [`serde_repr`]: https://crates.io/crates/serde_repr
244 "#
245 )]
246 #![allow(unknown_lints)]
247 #![warn(clippy::all)]
248 #![no_std]
249
250 use core::fmt::{Debug, Formatter, Result};
251 use core::ops::*;
252
253 /// Error type returned when creating a new flagset from bits is invalid or undefined.
254 /// ```
255 /// use flagset::{FlagSet, flags};
256 ///
257 /// flags! {
258 /// pub enum Flag: u16 {
259 /// Foo = 0b0001,
260 /// Bar = 0b0010,
261 /// Baz = 0b0100,
262 /// Qux = 0b1010, // Implies Bar
263 /// }
264 /// }
265 ///
266 /// assert_eq!(FlagSet::<Flag>::new(0b01101), Err(flagset::InvalidBits)); // Invalid
267 /// assert_eq!(FlagSet::<Flag>::new(0b10101), Err(flagset::InvalidBits)); // Unknown
268 /// ```
269 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
270 pub struct InvalidBits;
271
272 impl core::fmt::Display for InvalidBits {
273 #[inline]
274 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
275 write!(f, "invalid bits")
276 }
277 }
278
279 #[doc(hidden)]
280 pub trait Flags:
281 Copy
282 + Clone
283 + Debug
284 + PartialEq
285 + Eq
286 + BitAnd<Self, Output = FlagSet<Self>>
287 + BitOr<Self, Output = FlagSet<Self>>
288 + BitXor<Self, Output = FlagSet<Self>>
289 + Sub<Self, Output = FlagSet<Self>>
290 + Rem<Self, Output = FlagSet<Self>>
291 + Not<Output = FlagSet<Self>>
292 + Into<FlagSet<Self>>
293 + 'static
294 {
295 type Type: Copy
296 + Clone
297 + Debug
298 + PartialEq
299 + Eq
300 + Default
301 + BitAnd<Self::Type, Output = Self::Type>
302 + BitAndAssign<Self::Type>
303 + BitOr<Self::Type, Output = Self::Type>
304 + BitOrAssign<Self::Type>
305 + BitXor<Self::Type, Output = Self::Type>
306 + BitXorAssign<Self::Type>
307 + Not<Output = Self::Type>;
308
309 /// A slice containing all the possible flag values.
310 const LIST: &'static [Self];
311
312 /// Creates an empty `FlagSet` of this type
313 #[inline]
314 fn none() -> FlagSet<Self> {
315 FlagSet::default()
316 }
317 }
318
319 #[derive(Copy, Clone, Eq)]
320 pub struct FlagSet<F: Flags>(F::Type);
321
322 #[doc(hidden)]
323 #[derive(Copy, Clone)]
324 pub struct Iter<F: Flags>(FlagSet<F>, usize);
325
326 impl<F: Flags> Iterator for Iter<F> {
327 type Item = F;
328
329 #[inline]
330 fn next(&mut self) -> Option<Self::Item> {
331 while self.1 < F::LIST.len() {
332 let next = F::LIST[self.1];
333 self.1 += 1;
334
335 if self.0.contains(next) {
336 return Some(next);
337 }
338 }
339
340 None
341 }
342 }
343
344 impl<F: Flags> IntoIterator for FlagSet<F> {
345 type Item = F;
346 type IntoIter = Iter<F>;
347
348 /// Iterate over the flags in the set.
349 ///
350 /// **NOTE**: The order in which the flags are iterated is undefined.
351 ///
352 /// ```
353 /// use flagset::{FlagSet, flags};
354 ///
355 /// flags! {
356 /// enum Flag: u8 {
357 /// Foo = 0b001,
358 /// Bar = 0b010,
359 /// Baz = 0b100
360 /// }
361 /// }
362 ///
363 /// let set = Flag::Foo | Flag::Bar;
364 /// let mut iter = set.into_iter();
365 /// assert_eq!(iter.next(), Some(Flag::Foo));
366 /// assert_eq!(iter.next(), Some(Flag::Bar));
367 /// assert_eq!(iter.next(), None);
368 /// ```
369 #[inline]
370 fn into_iter(self) -> Self::IntoIter {
371 Iter(self, 0)
372 }
373 }
374
375 impl<F: Flags> Debug for FlagSet<F> {
376 #[inline]
377 fn fmt(&self, f: &mut Formatter) -> Result {
378 write!(f, "FlagSet(")?;
379 for (i, flag) in self.into_iter().enumerate() {
380 write!(f, "{}{:?}", if i > 0 { " | " } else { "" }, flag)?;
381 }
382 write!(f, ")")
383 }
384 }
385
386 impl<F: Flags, R: Copy + Into<FlagSet<F>>> PartialEq<R> for FlagSet<F> {
387 #[inline]
388 fn eq(&self, rhs: &R) -> bool {
389 self.0 == (*rhs).into().0
390 }
391 }
392
393 impl<F: Flags> AsRef<F::Type> for FlagSet<F> {
394 #[inline]
395 fn as_ref(&self) -> &F::Type {
396 &self.0
397 }
398 }
399
400 impl<F: Flags> From<Option<FlagSet<F>>> for FlagSet<F> {
401 /// Converts from `Option<FlagSet<F>>` to `FlagSet<F>`.
402 ///
403 /// Most notably, this allows for the use of `None` in many places to
404 /// substitute for manually creating an empty `FlagSet<F>`. See below.
405 ///
406 /// ```
407 /// use flagset::{FlagSet, flags};
408 ///
409 /// flags! {
410 /// enum Flag: u8 {
411 /// Foo = 0b001,
412 /// Bar = 0b010,
413 /// Baz = 0b100
414 /// }
415 /// }
416 ///
417 /// fn convert(v: impl Into<FlagSet<Flag>>) -> u8 {
418 /// v.into().bits()
419 /// }
420 ///
421 /// assert_eq!(convert(Flag::Foo | Flag::Bar), 0b011);
422 /// assert_eq!(convert(Flag::Foo), 0b001);
423 /// assert_eq!(convert(None), 0b000);
424 /// ```
425 #[inline]
426 fn from(value: Option<FlagSet<F>>) -> FlagSet<F> {
427 value.unwrap_or_default()
428 }
429 }
430
431 impl<F: Flags> Default for FlagSet<F> {
432 /// Creates a new, empty FlagSet.
433 ///
434 /// ```
435 /// use flagset::{FlagSet, flags};
436 ///
437 /// flags! {
438 /// enum Flag: u8 {
439 /// Foo = 0b001,
440 /// Bar = 0b010,
441 /// Baz = 0b100
442 /// }
443 /// }
444 ///
445 /// let set = FlagSet::<Flag>::default();
446 /// assert!(set.is_empty());
447 /// assert!(!set.is_full());
448 /// assert!(!set.contains(Flag::Foo));
449 /// assert!(!set.contains(Flag::Bar));
450 /// assert!(!set.contains(Flag::Baz));
451 /// ```
452 #[inline]
453 fn default() -> Self {
454 FlagSet(F::Type::default())
455 }
456 }
457
458 impl<F: Flags> Not for FlagSet<F> {
459 type Output = Self;
460
461 /// Calculates the complement of the current set.
462 ///
463 /// In common parlance, this returns the set of all possible flags that are
464 /// not in the current set.
465 ///
466 /// ```
467 /// use flagset::{FlagSet, flags};
468 ///
469 /// flags! {
470 /// #[derive(PartialOrd, Ord)]
471 /// enum Flag: u8 {
472 /// Foo = 1 << 0,
473 /// Bar = 1 << 1,
474 /// Baz = 1 << 2
475 /// }
476 /// }
477 ///
478 /// let set = !FlagSet::from(Flag::Foo);
479 /// assert!(!set.is_empty());
480 /// assert!(!set.is_full());
481 /// assert!(!set.contains(Flag::Foo));
482 /// assert!(set.contains(Flag::Bar));
483 /// assert!(set.contains(Flag::Baz));
484 /// ```
485 #[inline]
486 fn not(self) -> Self {
487 FlagSet(!self.0)
488 }
489 }
490
491 impl<F: Flags, R: Into<FlagSet<F>>> BitAnd<R> for FlagSet<F> {
492 type Output = Self;
493
494 /// Calculates the intersection of the current set and the specified flags.
495 ///
496 /// ```
497 /// use flagset::{FlagSet, flags};
498 ///
499 /// flags! {
500 /// #[derive(PartialOrd, Ord)]
501 /// pub enum Flag: u8 {
502 /// Foo = 0b001,
503 /// Bar = 0b010,
504 /// Baz = 0b100
505 /// }
506 /// }
507 ///
508 /// let set0 = Flag::Foo | Flag::Bar;
509 /// let set1 = Flag::Baz | Flag::Bar;
510 /// assert_eq!(set0 & set1, Flag::Bar);
511 /// assert_eq!(set0 & Flag::Foo, Flag::Foo);
512 /// assert_eq!(set1 & Flag::Baz, Flag::Baz);
513 /// ```
514 #[inline]
515 fn bitand(self, rhs: R) -> Self {
516 FlagSet(self.0 & rhs.into().0)
517 }
518 }
519
520 impl<F: Flags, R: Into<FlagSet<F>>> BitAndAssign<R> for FlagSet<F> {
521 /// Assigns the intersection of the current set and the specified flags.
522 ///
523 /// ```
524 /// use flagset::{FlagSet, flags};
525 ///
526 /// flags! {
527 /// enum Flag: u64 {
528 /// Foo = 0b001,
529 /// Bar = 0b010,
530 /// Baz = 0b100
531 /// }
532 /// }
533 ///
534 /// let mut set0 = Flag::Foo | Flag::Bar;
535 /// let mut set1 = Flag::Baz | Flag::Bar;
536 ///
537 /// set0 &= set1;
538 /// assert_eq!(set0, Flag::Bar);
539 ///
540 /// set1 &= Flag::Baz;
541 /// assert_eq!(set0, Flag::Bar);
542 /// ```
543 #[inline]
544 fn bitand_assign(&mut self, rhs: R) {
545 self.0 &= rhs.into().0
546 }
547 }
548
549 impl<F: Flags, R: Into<FlagSet<F>>> BitOr<R> for FlagSet<F> {
550 type Output = Self;
551
552 /// Calculates the union of the current set with the specified flags.
553 ///
554 /// ```
555 /// use flagset::{FlagSet, flags};
556 ///
557 /// flags! {
558 /// #[derive(PartialOrd, Ord)]
559 /// pub enum Flag: u8 {
560 /// Foo = 0b001,
561 /// Bar = 0b010,
562 /// Baz = 0b100
563 /// }
564 /// }
565 ///
566 /// let set0 = Flag::Foo | Flag::Bar;
567 /// let set1 = Flag::Baz | Flag::Bar;
568 /// assert_eq!(set0 | set1, FlagSet::full());
569 /// ```
570 #[inline]
571 fn bitor(self, rhs: R) -> Self {
572 FlagSet(self.0 | rhs.into().0)
573 }
574 }
575
576 impl<F: Flags, R: Into<FlagSet<F>>> BitOrAssign<R> for FlagSet<F> {
577 /// Assigns the union of the current set with the specified flags.
578 ///
579 /// ```
580 /// use flagset::{FlagSet, flags};
581 ///
582 /// flags! {
583 /// enum Flag: u64 {
584 /// Foo = 0b001,
585 /// Bar = 0b010,
586 /// Baz = 0b100
587 /// }
588 /// }
589 ///
590 /// let mut set0 = Flag::Foo | Flag::Bar;
591 /// let mut set1 = Flag::Bar | Flag::Baz;
592 ///
593 /// set0 |= set1;
594 /// assert_eq!(set0, FlagSet::full());
595 ///
596 /// set1 |= Flag::Baz;
597 /// assert_eq!(set1, Flag::Bar | Flag::Baz);
598 /// ```
599 #[inline]
600 fn bitor_assign(&mut self, rhs: R) {
601 self.0 |= rhs.into().0
602 }
603 }
604
605 impl<F: Flags, R: Into<FlagSet<F>>> BitXor<R> for FlagSet<F> {
606 type Output = Self;
607
608 /// Calculates the current set with the specified flags toggled.
609 ///
610 /// This is commonly known as toggling the presence
611 ///
612 /// ```
613 /// use flagset::{FlagSet, flags};
614 ///
615 /// flags! {
616 /// enum Flag: u32 {
617 /// Foo = 0b001,
618 /// Bar = 0b010,
619 /// Baz = 0b100
620 /// }
621 /// }
622 ///
623 /// let set0 = Flag::Foo | Flag::Bar;
624 /// let set1 = Flag::Baz | Flag::Bar;
625 /// assert_eq!(set0 ^ set1, Flag::Foo | Flag::Baz);
626 /// assert_eq!(set0 ^ Flag::Foo, Flag::Bar);
627 /// ```
628 #[inline]
629 fn bitxor(self, rhs: R) -> Self {
630 FlagSet(self.0 ^ rhs.into().0)
631 }
632 }
633
634 impl<F: Flags, R: Into<FlagSet<F>>> BitXorAssign<R> for FlagSet<F> {
635 /// Assigns the current set with the specified flags toggled.
636 ///
637 /// ```
638 /// use flagset::{FlagSet, flags};
639 ///
640 /// flags! {
641 /// enum Flag: u16 {
642 /// Foo = 0b001,
643 /// Bar = 0b010,
644 /// Baz = 0b100
645 /// }
646 /// }
647 ///
648 /// let mut set0 = Flag::Foo | Flag::Bar;
649 /// let mut set1 = Flag::Baz | Flag::Bar;
650 ///
651 /// set0 ^= set1;
652 /// assert_eq!(set0, Flag::Foo | Flag::Baz);
653 ///
654 /// set1 ^= Flag::Baz;
655 /// assert_eq!(set1, Flag::Bar);
656 /// ```
657 #[inline]
658 fn bitxor_assign(&mut self, rhs: R) {
659 self.0 ^= rhs.into().0
660 }
661 }
662
663 impl<F: Flags, R: Into<FlagSet<F>>> Sub<R> for FlagSet<F> {
664 type Output = Self;
665
666 /// Calculates set difference (the current set without the specified flags).
667 ///
668 /// ```
669 /// use flagset::{FlagSet, flags};
670 ///
671 /// flags! {
672 /// pub enum Flag: u8 {
673 /// Foo = 1,
674 /// Bar = 2,
675 /// Baz = 4
676 /// }
677 /// }
678 ///
679 /// let set0 = Flag::Foo | Flag::Bar;
680 /// let set1 = Flag::Baz | Flag::Bar;
681 /// assert_eq!(set0 - set1, Flag::Foo);
682 /// ```
683 #[inline]
684 fn sub(self, rhs: R) -> Self {
685 self & !rhs.into()
686 }
687 }
688
689 impl<F: Flags, R: Into<FlagSet<F>>> SubAssign<R> for FlagSet<F> {
690 /// Assigns set difference (the current set without the specified flags).
691 ///
692 /// ```
693 /// use flagset::{FlagSet, flags};
694 ///
695 /// flags! {
696 /// pub enum Flag: u8 {
697 /// Foo = 1,
698 /// Bar = 2,
699 /// Baz = 4
700 /// }
701 /// }
702 ///
703 /// let mut set0 = Flag::Foo | Flag::Bar;
704 /// set0 -= Flag::Baz | Flag::Bar;
705 /// assert_eq!(set0, Flag::Foo);
706 /// ```
707 #[inline]
708 fn sub_assign(&mut self, rhs: R) {
709 *self &= !rhs.into();
710 }
711 }
712
713 impl<F: Flags, R: Into<FlagSet<F>>> Rem<R> for FlagSet<F> {
714 type Output = Self;
715
716 /// Calculates the symmetric difference between two sets.
717 ///
718 /// The symmetric difference between two sets is the set of all flags
719 /// that appear in one set or the other, but not both.
720 ///
721 /// ```
722 /// use flagset::{FlagSet, flags};
723 ///
724 /// flags! {
725 /// pub enum Flag: u8 {
726 /// Foo = 1,
727 /// Bar = 2,
728 /// Baz = 4
729 /// }
730 /// }
731 ///
732 /// let set0 = Flag::Foo | Flag::Bar;
733 /// let set1 = Flag::Baz | Flag::Bar;
734 /// assert_eq!(set0 % set1, Flag::Foo | Flag::Baz);
735 /// ```
736 #[inline]
737 fn rem(self, rhs: R) -> Self {
738 let rhs = rhs.into();
739 (self - rhs) | (rhs - self)
740 }
741 }
742
743 impl<F: Flags, R: Into<FlagSet<F>>> RemAssign<R> for FlagSet<F> {
744 /// Assigns the symmetric difference between two sets.
745 ///
746 /// The symmetric difference between two sets is the set of all flags
747 /// that appear in one set or the other, but not both.
748 ///
749 /// ```
750 /// use flagset::{FlagSet, flags};
751 ///
752 /// flags! {
753 /// pub enum Flag: u8 {
754 /// Foo = 1,
755 /// Bar = 2,
756 /// Baz = 4
757 /// }
758 /// }
759 ///
760 /// let mut set0 = Flag::Foo | Flag::Bar;
761 /// let set1 = Flag::Baz | Flag::Bar;
762 /// set0 %= set1;
763 /// assert_eq!(set0, Flag::Foo | Flag::Baz);
764 /// ```
765 #[inline]
766 fn rem_assign(&mut self, rhs: R) {
767 *self = *self % rhs
768 }
769 }
770
771 impl<F: Flags> FlagSet<F> {
772 /// Creates a new set from bits; returning `Err(InvalidBits)` on invalid/unknown bits.
773 ///
774 /// ```
775 /// use flagset::{FlagSet, flags};
776 ///
777 /// flags! {
778 /// pub enum Flag: u16 {
779 /// Foo = 0b0001,
780 /// Bar = 0b0010,
781 /// Baz = 0b0100,
782 /// Qux = 0b1010, // Implies Bar
783 /// }
784 /// }
785 ///
786 /// assert_eq!(FlagSet::<Flag>::new(0b00101), Ok(Flag::Foo | Flag::Baz));
787 /// assert_eq!(FlagSet::<Flag>::new(0b01101), Err(flagset::InvalidBits)); // Invalid
788 /// assert_eq!(FlagSet::<Flag>::new(0b10101), Err(flagset::InvalidBits)); // Unknown
789 /// ```
790 #[inline]
791 pub fn new(bits: F::Type) -> core::result::Result<Self, InvalidBits> {
792 if Self::new_truncated(bits).0 == bits {
793 return Ok(FlagSet(bits));
794 }
795
796 Err(InvalidBits)
797 }
798
799 /// Creates a new set from bits; truncating invalid/unknown bits.
800 ///
801 /// ```
802 /// use flagset::{FlagSet, flags};
803 ///
804 /// flags! {
805 /// pub enum Flag: u16 {
806 /// Foo = 0b0001,
807 /// Bar = 0b0010,
808 /// Baz = 0b0100,
809 /// Qux = 0b1010, // Implies Bar
810 /// }
811 /// }
812 ///
813 /// let set = FlagSet::new_truncated(0b11101); // Has invalid and unknown.
814 /// assert_eq!(set, Flag::Foo | Flag::Baz);
815 /// assert_eq!(set.bits(), 0b00101); // Has neither.
816 /// ```
817 #[inline]
818 pub fn new_truncated(bits: F::Type) -> Self {
819 let mut set = Self::default();
820
821 for flag in FlagSet::<F>(bits) {
822 set |= flag;
823 }
824
825 set
826 }
827
828 /// Creates a new set from bits; use of invalid/unknown bits is undefined.
829 ///
830 /// ```
831 /// use flagset::{FlagSet, flags};
832 ///
833 /// flags! {
834 /// pub enum Flag: u16 {
835 /// Foo = 0b0001,
836 /// Bar = 0b0010,
837 /// Baz = 0b0100,
838 /// Qux = 0b1010, // Implies Bar
839 /// }
840 /// }
841 ///
842 /// // Unknown and invalid bits are retained. Behavior is undefined.
843 /// let set = unsafe { FlagSet::<Flag>::new_unchecked(0b11101) };
844 /// assert_eq!(set.bits(), 0b11101);
845 /// ```
846 ///
847 /// # Safety
848 ///
849 /// This constructor doesn't check that the bits are valid. If you pass
850 /// undefined flags, undefined behavior may result.
851 #[inline]
852 pub unsafe fn new_unchecked(bits: F::Type) -> Self {
853 FlagSet(bits)
854 }
855
856 /// Creates a new FlagSet containing all possible flags.
857 ///
858 /// ```
859 /// use flagset::{FlagSet, flags};
860 ///
861 /// flags! {
862 /// pub enum Flag: u8 {
863 /// Foo = 1,
864 /// Bar = 2,
865 /// Baz = 4
866 /// }
867 /// }
868 ///
869 /// let set = FlagSet::full();
870 /// assert!(!set.is_empty());
871 /// assert!(set.is_full());
872 /// assert!(set.contains(Flag::Foo));
873 /// assert!(set.contains(Flag::Bar));
874 /// assert!(set.contains(Flag::Baz));
875 /// ```
876 #[inline]
877 pub fn full() -> Self {
878 let mut set = Self::default();
879 for f in F::LIST {
880 set |= *f
881 }
882 set
883 }
884
885 /// Returns the raw bits of the set.
886 ///
887 /// ```
888 /// use flagset::{FlagSet, flags};
889 ///
890 /// flags! {
891 /// pub enum Flag: u16 {
892 /// Foo = 0b0001,
893 /// Bar = 0b0010,
894 /// Baz = 0b0100,
895 /// }
896 /// }
897 ///
898 /// let set = Flag::Foo | Flag::Baz;
899 /// assert_eq!(set.bits(), 0b0101u16);
900 /// ```
901 #[inline]
902 pub fn bits(self) -> F::Type {
903 self.0
904 }
905
906 /// Returns true if the FlagSet contains no flags.
907 ///
908 /// ```
909 /// use flagset::{FlagSet, flags};
910 ///
911 /// flags! {
912 /// pub enum Flag: u8 {
913 /// Foo = 1,
914 /// Bar = 2,
915 /// Baz = 4
916 /// }
917 /// }
918 ///
919 /// let mut set = Flag::Foo | Flag::Bar;
920 /// assert!(!set.is_empty());
921 ///
922 /// set &= Flag::Baz;
923 /// assert!(set.is_empty());
924 /// ```
925 #[inline]
926 pub fn is_empty(self) -> bool {
927 self == Self::default()
928 }
929
930 /// Returns true if the FlagSet contains all possible flags.
931 ///
932 /// ```
933 /// use flagset::{FlagSet, flags};
934 ///
935 /// flags! {
936 /// pub enum Flag: u8 {
937 /// Foo = 1,
938 /// Bar = 2,
939 /// Baz = 4
940 /// }
941 /// }
942 ///
943 /// let mut set = Flag::Foo | Flag::Bar;
944 /// assert!(!set.is_full());
945 ///
946 /// set |= Flag::Baz;
947 /// assert!(set.is_full());
948 /// ```
949 #[inline]
950 pub fn is_full(self) -> bool {
951 self == Self::full()
952 }
953
954 /// Returns true if the two `FlagSet`s do not share any flags.
955 ///
956 /// ```
957 /// use flagset::{FlagSet, flags};
958 ///
959 /// flags! {
960 /// pub enum Flag: u8 {
961 /// Foo = 1,
962 /// Bar = 2,
963 /// Baz = 4
964 /// }
965 /// }
966 ///
967 /// let set = Flag::Foo | Flag::Bar;
968 /// assert!(!set.is_disjoint(Flag::Foo));
969 /// assert!(!set.is_disjoint(Flag::Foo | Flag::Baz));
970 /// assert!(set.is_disjoint(Flag::Baz));
971 /// ```
972 #[inline]
973 pub fn is_disjoint(self, rhs: impl Into<FlagSet<F>>) -> bool {
974 self & rhs == Self::default()
975 }
976
977 /// Returns true if this FlagSet is a superset of the specified flags.
978 ///
979 /// ```
980 /// use flagset::{FlagSet, flags};
981 ///
982 /// flags! {
983 /// pub enum Flag: u8 {
984 /// Foo = 1,
985 /// Bar = 2,
986 /// Baz = 4
987 /// }
988 /// }
989 ///
990 /// let set = Flag::Foo | Flag::Bar;
991 /// assert!(set.contains(Flag::Foo));
992 /// assert!(set.contains(Flag::Foo | Flag::Bar));
993 /// assert!(!set.contains(Flag::Foo | Flag::Bar | Flag::Baz));
994 /// ```
995 #[inline]
996 pub fn contains(self, rhs: impl Into<FlagSet<F>>) -> bool {
997 let rhs = rhs.into();
998 self & rhs == rhs
999 }
1000
1001 /// Removes all flags from the FlagSet.
1002 ///
1003 /// ```
1004 /// use flagset::{FlagSet, flags};
1005 ///
1006 /// flags! {
1007 /// pub enum Flag: u8 {
1008 /// Foo = 1,
1009 /// Bar = 2,
1010 /// Baz = 4
1011 /// }
1012 /// }
1013 ///
1014 /// let mut set = Flag::Foo | Flag::Bar;
1015 /// assert!(!set.is_empty());
1016 ///
1017 /// set.clear();
1018 /// assert!(set.is_empty());
1019 /// ```
1020 #[inline]
1021 pub fn clear(&mut self) {
1022 *self = Self::default();
1023 }
1024
1025 /// Clears the current set and returns an iterator of all removed flags.
1026 ///
1027 /// ```
1028 /// use flagset::{FlagSet, flags};
1029 ///
1030 /// flags! {
1031 /// pub enum Flag: u8 {
1032 /// Foo = 1,
1033 /// Bar = 2,
1034 /// Baz = 4
1035 /// }
1036 /// }
1037 ///
1038 /// let mut set = Flag::Foo | Flag::Bar;
1039 /// let mut iter = set.drain();
1040 /// assert!(set.is_empty());
1041 /// assert_eq!(iter.next(), Some(Flag::Foo));
1042 /// assert_eq!(iter.next(), Some(Flag::Bar));
1043 /// assert_eq!(iter.next(), None);
1044 /// ```
1045 #[inline]
1046 pub fn drain(&mut self) -> Iter<F> {
1047 let iter = self.into_iter();
1048 *self = Self::default();
1049 iter
1050 }
1051
1052 /// Retain only the flags flags specified by the predicate.
1053 ///
1054 /// ```
1055 /// use flagset::{FlagSet, flags};
1056 ///
1057 /// flags! {
1058 /// pub enum Flag: u8 {
1059 /// Foo = 1,
1060 /// Bar = 2,
1061 /// Baz = 4
1062 /// }
1063 /// }
1064 ///
1065 /// let mut set0 = Flag::Foo | Flag::Bar;
1066 /// set0.retain(|f| f != Flag::Foo);
1067 /// assert_eq!(set0, Flag::Bar);
1068 /// ```
1069 #[inline]
1070 pub fn retain(&mut self, func: impl Fn(F) -> bool) {
1071 for f in self.into_iter() {
1072 if !func(f) {
1073 *self -= f
1074 }
1075 }
1076 }
1077 }
1078
1079 #[cfg(feature = "serde")]
1080 impl<F: Flags> serde::Serialize for FlagSet<F>
1081 where
1082 F::Type: serde::ser::Serialize,
1083 {
1084 #[inline]
1085 fn serialize<S>(&self, serializer: S) -> core::result::Result<S::Ok, S::Error>
1086 where
1087 S: serde::ser::Serializer,
1088 {
1089 self.0.serialize(serializer)
1090 }
1091 }
1092
1093 #[cfg(feature = "serde")]
1094 impl<'de, F: Flags> serde::Deserialize<'de> for FlagSet<F>
1095 where
1096 F::Type: serde::de::Deserialize<'de>,
1097 {
1098 #[inline]
1099 fn deserialize<D>(deserializer: D) -> core::result::Result<Self, D::Error>
1100 where
1101 D: serde::de::Deserializer<'de>,
1102 {
1103 Ok(FlagSet(F::Type::deserialize(deserializer)?))
1104 }
1105 }
1106
1107 /// Define flag value using the `enum` syntax. See below for details.
1108 ///
1109 /// Each enumeration value **MUST** have a specified value.
1110 ///
1111 /// The width of the bitfield **MUST** also be specified by its integer type.
1112 ///
1113 /// It is important to note that the size of the flag enumeration itself is
1114 /// unrelated to the size of the corresponding `FlagSet` instance.
1115 ///
1116 /// It is also worth noting that this macro automatically implements a variety
1117 /// of standard traits including:
1118 /// * Copy
1119 /// * Clone
1120 /// * Debug
1121 /// * PartialEq
1122 /// * Eq
1123 /// * From<$enum> for $integer
1124 /// * Not
1125 /// * BitAnd
1126 /// * BitOr
1127 /// * BitXor
1128 /// * Sub
1129 /// * Rem
1130 ///
1131 /// ```
1132 /// use std::mem::{align_of, size_of};
1133 /// use flagset::{FlagSet, flags};
1134 ///
1135 /// flags! {
1136 /// enum FlagEmpty: u32 {}
1137 ///
1138 /// enum Flag8: u8 {
1139 /// Foo = 0b001,
1140 /// Bar = 0b010,
1141 /// Baz = 0b100
1142 /// }
1143 ///
1144 /// pub enum Flag16: u16 {
1145 /// Foo,
1146 /// Bar,
1147 /// #[deprecated]
1148 /// Baz,
1149 /// }
1150 ///
1151 /// #[derive(PartialOrd, Ord)]
1152 /// enum Flag32: u32 {
1153 /// Foo = 0b001,
1154 /// #[deprecated]
1155 /// Bar = 0b010,
1156 /// Baz = 0b100
1157 /// }
1158 ///
1159 /// #[repr(u64)]
1160 /// enum Flag64: u64 {
1161 /// Foo = 0b001,
1162 /// Bar = 0b010,
1163 /// Baz = 0b100
1164 /// }
1165 ///
1166 /// #[repr(u32)]
1167 /// enum Flag128: u128 {
1168 /// Foo = 0b001,
1169 /// Bar = 0b010,
1170 /// Baz = 0b100
1171 /// }
1172 /// }
1173 ///
1174 /// assert_eq!(size_of::<Flag8>(), 1);
1175 /// assert_eq!(size_of::<Flag16>(), 1);
1176 /// assert_eq!(size_of::<Flag32>(), 1);
1177 /// assert_eq!(size_of::<Flag64>(), 8);
1178 /// assert_eq!(size_of::<Flag128>(), 4);
1179 ///
1180 /// assert_eq!(align_of::<Flag8>(), 1);
1181 /// assert_eq!(align_of::<Flag16>(), 1);
1182 /// assert_eq!(align_of::<Flag32>(), 1);
1183 /// assert_eq!(align_of::<Flag64>(), align_of::<u64>());
1184 /// assert_eq!(align_of::<Flag128>(), align_of::<u32>());
1185 ///
1186 /// assert_eq!(size_of::<FlagSet<Flag8>>(), size_of::<u8>());
1187 /// assert_eq!(size_of::<FlagSet<Flag16>>(), size_of::<u16>());
1188 /// assert_eq!(size_of::<FlagSet<Flag32>>(), size_of::<u32>());
1189 /// assert_eq!(size_of::<FlagSet<Flag64>>(), size_of::<u64>());
1190 /// assert_eq!(size_of::<FlagSet<Flag128>>(), size_of::<u128>());
1191 ///
1192 /// assert_eq!(align_of::<FlagSet<Flag8>>(), align_of::<u8>());
1193 /// assert_eq!(align_of::<FlagSet<Flag16>>(), align_of::<u16>());
1194 /// assert_eq!(align_of::<FlagSet<Flag32>>(), align_of::<u32>());
1195 /// assert_eq!(align_of::<FlagSet<Flag64>>(), align_of::<u64>());
1196 /// assert_eq!(align_of::<FlagSet<Flag128>>(), align_of::<u128>());
1197 /// ```
1198 #[macro_export]
1199 macro_rules! flags {
1200 () => {};
1201
1202 // Entry point for enumerations without values.
1203 ($(#[$m:meta])* $p:vis enum $n:ident: $t:ty { $($(#[$a:meta])* $k:ident),+ $(,)* } $($next:tt)*) => {
1204 $crate::flags! { $(#[$m])* $p enum $n: $t { $($(#[$a])* $k = (1 << $n::$k as $t)),+ } $($next)* }
1205 };
1206
1207 // Entrypoint for enumerations with values.
1208 ($(#[$m:meta])* $p:vis enum $n:ident: $t:ty { $($(#[$a:meta])*$k:ident = $v:expr),* $(,)* } $($next:tt)*) => {
1209 $(#[$m])*
1210 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
1211 $p enum $n { $($(#[$a])* $k),* }
1212
1213 impl $crate::Flags for $n {
1214 type Type = $t;
1215
1216 const LIST: &'static [Self] = &[$($n::$k),*];
1217 }
1218
1219 impl core::convert::From<$n> for $crate::FlagSet<$n> {
1220 #[inline]
1221 fn from(value: $n) -> Self {
1222 unsafe {
1223 match value {
1224 $($n::$k => Self::new_unchecked($v)),*
1225 }
1226 }
1227 }
1228 }
1229
1230 impl core::ops::Not for $n {
1231 type Output = $crate::FlagSet<$n>;
1232
1233 #[inline]
1234 fn not(self) -> Self::Output {
1235 !$crate::FlagSet::from(self)
1236 }
1237 }
1238
1239 impl<R: core::convert::Into<$crate::FlagSet<$n>>> core::ops::BitAnd<R> for $n {
1240 type Output = $crate::FlagSet<$n>;
1241
1242 #[inline]
1243 fn bitand(self, rhs: R) -> Self::Output {
1244 $crate::FlagSet::from(self) & rhs
1245 }
1246 }
1247
1248 impl<R: core::convert::Into<$crate::FlagSet<$n>>> core::ops::BitOr<R> for $n {
1249 type Output = $crate::FlagSet<$n>;
1250
1251 #[inline]
1252 fn bitor(self, rhs: R) -> Self::Output {
1253 $crate::FlagSet::from(self) | rhs
1254 }
1255 }
1256
1257 impl<R: core::convert::Into<$crate::FlagSet<$n>>> core::ops::BitXor<R> for $n {
1258 type Output = $crate::FlagSet<$n>;
1259
1260 #[inline]
1261 fn bitxor(self, rhs: R) -> Self::Output {
1262 $crate::FlagSet::from(self) ^ rhs
1263 }
1264 }
1265
1266 impl<R: core::convert::Into<$crate::FlagSet<$n>>> core::ops::Sub<R> for $n {
1267 type Output = $crate::FlagSet<$n>;
1268
1269 #[inline]
1270 fn sub(self, rhs: R) -> Self::Output {
1271 $crate::FlagSet::from(self) - rhs
1272 }
1273 }
1274
1275 impl<R: core::convert::Into<$crate::FlagSet<$n>>> core::ops::Rem<R> for $n {
1276 type Output = $crate::FlagSet<$n>;
1277
1278 #[inline]
1279 fn rem(self, rhs: R) -> Self::Output {
1280 $crate::FlagSet::from(self) % rhs
1281 }
1282 }
1283
1284 $crate::flags! { $($next)* }
1285 };
1286 }