1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
13 //! A typesafe bitmask flag generator.
15 /// The `bitflags!` macro generates a `struct` that holds a set of C-style
16 /// bitmask flags. It is useful for creating typesafe wrappers for C APIs.
18 /// The flags should only be defined for integer types, otherwise unexpected
19 /// type errors may occur at compile time.
25 /// flags Flags: u32 {
26 /// const FLAG_A = 0b00000001,
27 /// const FLAG_B = 0b00000010,
28 /// const FLAG_C = 0b00000100,
29 /// const FLAG_ABC = FLAG_A.bits
36 /// let e1 = FLAG_A | FLAG_C;
37 /// let e2 = FLAG_B | FLAG_C;
38 /// assert!((e1 | e2) == FLAG_ABC); // union
39 /// assert!((e1 & e2) == FLAG_C); // intersection
40 /// assert!((e1 - e2) == FLAG_A); // set difference
41 /// assert!(!e2 == FLAG_A); // set complement
45 /// The generated `struct`s can also be extended with type and trait implementations:
51 /// flags Flags: u32 {
52 /// const FLAG_A = 0b00000001,
53 /// const FLAG_B = 0b00000010,
58 /// pub fn clear(&mut self) {
59 /// self.bits = 0; // The `bits` field can be accessed from within the
60 /// // same module where the `bitflags!` macro was invoked.
64 /// impl fmt::Show for Flags {
65 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
71 /// let mut flags = FLAG_A | FLAG_B;
73 /// assert!(flags.is_empty());
74 /// assert_eq!(format!("{}", flags).as_slice(), "hi!");
80 /// Attributes can be attached to the generated `struct` by placing them
81 /// before the `flags` keyword.
85 /// The `PartialEq` and `Clone` traits are automatically derived for the `struct` using
86 /// the `deriving` attribute. Additional traits can be derived by providing an
87 /// explicit `deriving` attribute on `flags`.
91 /// The following operator traits are implemented for the generated `struct`:
94 /// - `BitAnd`: intersection
95 /// - `BitXor`: toggle
96 /// - `Sub`: set difference
97 /// - `Not`: set complement
101 /// The following methods are defined for the generated `struct`:
103 /// - `empty`: an empty set of flags
104 /// - `all`: the set of all flags
105 /// - `bits`: the raw value of the flags currently stored
106 /// - `from_bits`: convert from underlying bit representation, unless that
107 /// representation contains bits that do not correspond to a flag
108 /// - `from_bits_truncate`: convert from underlying bit representation, dropping
109 /// any bits that do not correspond to flags
110 /// - `is_empty`: `true` if no flags are currently stored
111 /// - `is_all`: `true` if all flags are currently set
112 /// - `intersects`: `true` if there are flags common to both `self` and `other`
113 /// - `contains`: `true` all of the flags in `other` are contained within `self`
114 /// - `insert`: inserts the specified flags in-place
115 /// - `remove`: removes the specified flags in-place
116 /// - `toggle`: the specified flags will be inserted if not present, and removed
119 macro_rules! bitflags {
120 ($(#[$attr:meta])* flags $BitFlags:ident: $T:ty {
121 $($(#[$Flag_attr:meta])* const $Flag:ident = $value:expr),+
123 #[derive(Copy, PartialEq, Eq, Clone, PartialOrd, Ord, Hash)]
125 pub struct $BitFlags {
129 $($(#[$Flag_attr])* pub const $Flag: $BitFlags = $BitFlags { bits: $value };)+
132 /// Returns an empty set of flags.
134 pub fn empty() -> $BitFlags {
135 $BitFlags { bits: 0 }
138 /// Returns the set containing all flags.
140 pub fn all() -> $BitFlags {
141 $BitFlags { bits: $($value)|+ }
144 /// Returns the raw value of the flags currently stored.
146 pub fn bits(&self) -> $T {
150 /// Convert from underlying bit representation, unless that
151 /// representation contains bits that do not correspond to a flag.
153 pub fn from_bits(bits: $T) -> ::std::option::Option<$BitFlags> {
154 if (bits & !$BitFlags::all().bits()) != 0 {
155 ::std::option::Option::None
157 ::std::option::Option::Some($BitFlags { bits: bits })
161 /// Convert from underlying bit representation, dropping any bits
162 /// that do not correspond to flags.
164 pub fn from_bits_truncate(bits: $T) -> $BitFlags {
165 $BitFlags { bits: bits } & $BitFlags::all()
168 /// Returns `true` if no flags are currently stored.
170 pub fn is_empty(&self) -> bool {
171 *self == $BitFlags::empty()
174 /// Returns `true` if all flags are currently set.
176 pub fn is_all(&self) -> bool {
177 *self == $BitFlags::all()
180 /// Returns `true` if there are flags common to both `self` and `other`.
182 pub fn intersects(&self, other: $BitFlags) -> bool {
183 !(*self & other).is_empty()
186 /// Returns `true` all of the flags in `other` are contained within `self`.
188 pub fn contains(&self, other: $BitFlags) -> bool {
189 (*self & other) == other
192 /// Inserts the specified flags in-place.
194 pub fn insert(&mut self, other: $BitFlags) {
195 self.bits |= other.bits;
198 /// Removes the specified flags in-place.
200 pub fn remove(&mut self, other: $BitFlags) {
201 self.bits &= !other.bits;
204 /// Toggles the specified flags in-place.
206 pub fn toggle(&mut self, other: $BitFlags) {
207 self.bits ^= other.bits;
211 impl ::std::ops::BitOr for $BitFlags {
212 type Output = $BitFlags;
214 /// Returns the union of the two sets of flags.
216 fn bitor(self, other: $BitFlags) -> $BitFlags {
217 $BitFlags { bits: self.bits | other.bits }
221 impl ::std::ops::BitXor for $BitFlags {
222 type Output = $BitFlags;
224 /// Returns the left flags, but with all the right flags toggled.
226 fn bitxor(self, other: $BitFlags) -> $BitFlags {
227 $BitFlags { bits: self.bits ^ other.bits }
231 impl ::std::ops::BitAnd for $BitFlags {
232 type Output = $BitFlags;
234 /// Returns the intersection between the two sets of flags.
236 fn bitand(self, other: $BitFlags) -> $BitFlags {
237 $BitFlags { bits: self.bits & other.bits }
241 impl ::std::ops::Sub for $BitFlags {
242 type Output = $BitFlags;
244 /// Returns the set difference of the two sets of flags.
246 fn sub(self, other: $BitFlags) -> $BitFlags {
247 $BitFlags { bits: self.bits & !other.bits }
251 impl ::std::ops::Not for $BitFlags {
252 type Output = $BitFlags;
254 /// Returns the complement of this set of flags.
256 fn not(self) -> $BitFlags {
257 $BitFlags { bits: !self.bits } & $BitFlags::all()
261 ($(#[$attr:meta])* flags $BitFlags:ident: $T:ty {
262 $($(#[$Flag_attr:meta])* const $Flag:ident = $value:expr),+,
266 flags $BitFlags: $T {
267 $($(#[$Flag_attr])* const $Flag = $value),+
274 #[allow(non_upper_case_globals)]
277 use option::Option::{Some, None};
280 #[doc = "> The first principle is that you must not fool yourself — and"]
281 #[doc = "> you are the easiest person to fool."]
283 #[doc = "> - Richard Feynman"]
285 const FlagA = 0b00000001,
286 #[doc = "<pcwalton> macros are way better at generating code than trans is"]
287 const FlagB = 0b00000010,
288 const FlagC = 0b00000100,
290 #[doc = "* strcat table"]
291 #[doc = "<strcat> wait what?"]
292 const FlagABC = FlagA.bits
299 flags AnotherSetOfFlags: i8 {
300 const AnotherFlag = -1_i8,
306 assert_eq!(Flags::empty().bits(), 0b00000000);
307 assert_eq!(FlagA.bits(), 0b00000001);
308 assert_eq!(FlagABC.bits(), 0b00000111);
310 assert_eq!(AnotherSetOfFlags::empty().bits(), 0b00);
311 assert_eq!(AnotherFlag.bits(), !0_i8);
315 fn test_from_bits() {
316 assert!(Flags::from_bits(0) == Some(Flags::empty()));
317 assert!(Flags::from_bits(0b1) == Some(FlagA));
318 assert!(Flags::from_bits(0b10) == Some(FlagB));
319 assert!(Flags::from_bits(0b11) == Some(FlagA | FlagB));
320 assert!(Flags::from_bits(0b1000) == None);
322 assert!(AnotherSetOfFlags::from_bits(!0_i8) == Some(AnotherFlag));
326 fn test_from_bits_truncate() {
327 assert!(Flags::from_bits_truncate(0) == Flags::empty());
328 assert!(Flags::from_bits_truncate(0b1) == FlagA);
329 assert!(Flags::from_bits_truncate(0b10) == FlagB);
330 assert!(Flags::from_bits_truncate(0b11) == (FlagA | FlagB));
331 assert!(Flags::from_bits_truncate(0b1000) == Flags::empty());
332 assert!(Flags::from_bits_truncate(0b1001) == FlagA);
334 assert!(AnotherSetOfFlags::from_bits_truncate(0_i8) == AnotherSetOfFlags::empty());
339 assert!(Flags::empty().is_empty());
340 assert!(!FlagA.is_empty());
341 assert!(!FlagABC.is_empty());
343 assert!(!AnotherFlag.is_empty());
348 assert!(Flags::all().is_all());
349 assert!(!FlagA.is_all());
350 assert!(FlagABC.is_all());
352 assert!(AnotherFlag.is_all());
356 fn test_two_empties_do_not_intersect() {
357 let e1 = Flags::empty();
358 let e2 = Flags::empty();
359 assert!(!e1.intersects(e2));
361 assert!(AnotherFlag.intersects(AnotherFlag));
365 fn test_empty_does_not_intersect_with_full() {
366 let e1 = Flags::empty();
368 assert!(!e1.intersects(e2));
372 fn test_disjoint_intersects() {
375 assert!(!e1.intersects(e2));
379 fn test_overlapping_intersects() {
381 let e2 = FlagA | FlagB;
382 assert!(e1.intersects(e2));
388 let e2 = FlagA | FlagB;
389 assert!(!e1.contains(e2));
390 assert!(e2.contains(e1));
391 assert!(FlagABC.contains(e2));
393 assert!(AnotherFlag.contains(AnotherFlag));
399 let e2 = FlagA | FlagB;
403 let mut e3 = AnotherSetOfFlags::empty();
404 e3.insert(AnotherFlag);
405 assert!(e3 == AnotherFlag);
410 let mut e1 = FlagA | FlagB;
411 let e2 = FlagA | FlagC;
413 assert!(e1 == FlagB);
415 let mut e3 = AnotherFlag;
416 e3.remove(AnotherFlag);
417 assert!(e3 == AnotherSetOfFlags::empty());
421 fn test_operators() {
422 let e1 = FlagA | FlagC;
423 let e2 = FlagB | FlagC;
424 assert!((e1 | e2) == FlagABC); // union
425 assert!((e1 & e2) == FlagC); // intersection
426 assert!((e1 - e2) == FlagA); // set difference
427 assert!(!e2 == FlagA); // set complement
428 assert!(e1 ^ e2 == FlagA | FlagB); // toggle
431 assert!(e3 == FlagA | FlagB);
433 let mut m4 = AnotherSetOfFlags::empty();
434 m4.toggle(AnotherSetOfFlags::empty());
435 assert!(m4 == AnotherSetOfFlags::empty());
440 let mut a = Flags::empty();
441 let mut b = Flags::empty();
443 assert!(!(a < b) && !(b < a));
447 assert!(!(a < b) && b < a);
454 let mut a = Flags::empty();
455 let mut b = Flags::empty();
457 assert!(a <= b && a >= b);
459 assert!(a > b && a >= b);
460 assert!(b < a && b <= a);
462 assert!(b > a && b >= a);
463 assert!(a < b && a <= b);
468 let mut x = Flags::empty();
469 let mut y = Flags::empty();
470 assert!(hash::hash(&x) == hash::hash(&y));
473 assert!(hash::hash(&x) == hash::hash(&y));