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.
14 //! A typesafe bitmask flag generator.
16 /// The `bitflags!` macro generates a `struct` that holds a set of C-style
17 /// bitmask flags. It is useful for creating typesafe wrappers for C APIs.
19 /// The flags should only be defined for integer types, otherwise unexpected
20 /// type errors may occur at compile time.
26 /// flags Flags: u32 {
27 /// const FLAG_A = 0b00000001,
28 /// const FLAG_B = 0b00000010,
29 /// const FLAG_C = 0b00000100,
30 /// const FLAG_ABC = FLAG_A.bits
37 /// let e1 = FLAG_A | FLAG_C;
38 /// let e2 = FLAG_B | FLAG_C;
39 /// assert!((e1 | e2) == FLAG_ABC); // union
40 /// assert!((e1 & e2) == FLAG_C); // intersection
41 /// assert!((e1 - e2) == FLAG_A); // set difference
42 /// assert!(!e2 == FLAG_A); // set complement
46 /// The generated `struct`s can also be extended with type and trait implementations:
52 /// flags Flags: u32 {
53 /// const FLAG_A = 0b00000001,
54 /// const FLAG_B = 0b00000010,
59 /// pub fn clear(&mut self) {
60 /// self.bits = 0; // The `bits` field can be accessed from within the
61 /// // same module where the `bitflags!` macro was invoked.
65 /// impl fmt::Show for Flags {
66 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
72 /// let mut flags = FLAG_A | FLAG_B;
74 /// assert!(flags.is_empty());
75 /// assert_eq!(format!("{}", flags).as_slice(), "hi!");
81 /// Attributes can be attached to the generated `struct` by placing them
82 /// before the `flags` keyword.
86 /// The `PartialEq` and `Clone` traits are automatically derived for the `struct` using
87 /// the `deriving` attribute. Additional traits can be derived by providing an
88 /// explicit `deriving` attribute on `flags`.
92 /// The following operator traits are implemented for the generated `struct`:
95 /// - `BitAnd`: intersection
96 /// - `BitXor`: toggle
97 /// - `Sub`: set difference
98 /// - `Not`: set complement
102 /// The following methods are defined for the generated `struct`:
104 /// - `empty`: an empty set of flags
105 /// - `all`: the set of all flags
106 /// - `bits`: the raw value of the flags currently stored
107 /// - `from_bits`: convert from underlying bit representation, unless that
108 /// representation contains bits that do not correspond to a flag
109 /// - `from_bits_truncate`: convert from underlying bit representation, dropping
110 /// any bits that do not correspond to flags
111 /// - `is_empty`: `true` if no flags are currently stored
112 /// - `is_all`: `true` if all flags are currently set
113 /// - `intersects`: `true` if there are flags common to both `self` and `other`
114 /// - `contains`: `true` all of the flags in `other` are contained within `self`
115 /// - `insert`: inserts the specified flags in-place
116 /// - `remove`: removes the specified flags in-place
117 /// - `toggle`: the specified flags will be inserted if not present, and removed
120 macro_rules! bitflags {
121 ($(#[$attr:meta])* flags $BitFlags:ident: $T:ty {
122 $($(#[$Flag_attr:meta])* const $Flag:ident = $value:expr),+
124 #[deriving(Copy, PartialEq, Eq, Clone, PartialOrd, Ord, Hash)]
126 pub struct $BitFlags {
130 $($(#[$Flag_attr])* pub const $Flag: $BitFlags = $BitFlags { bits: $value };)+
133 /// Returns an empty set of flags.
135 pub fn empty() -> $BitFlags {
136 $BitFlags { bits: 0 }
139 /// Returns the set containing all flags.
141 pub fn all() -> $BitFlags {
142 $BitFlags { bits: $($value)|+ }
145 /// Returns the raw value of the flags currently stored.
147 pub fn bits(&self) -> $T {
151 /// Convert from underlying bit representation, unless that
152 /// representation contains bits that do not correspond to a flag.
154 pub fn from_bits(bits: $T) -> ::std::option::Option<$BitFlags> {
155 if (bits & !$BitFlags::all().bits()) != 0 {
156 ::std::option::Option::None
158 ::std::option::Option::Some($BitFlags { bits: bits })
162 /// Convert from underlying bit representation, dropping any bits
163 /// that do not correspond to flags.
165 pub fn from_bits_truncate(bits: $T) -> $BitFlags {
166 $BitFlags { bits: bits } & $BitFlags::all()
169 /// Returns `true` if no flags are currently stored.
171 pub fn is_empty(&self) -> bool {
172 *self == $BitFlags::empty()
175 /// Returns `true` if all flags are currently set.
177 pub fn is_all(&self) -> bool {
178 *self == $BitFlags::all()
181 /// Returns `true` if there are flags common to both `self` and `other`.
183 pub fn intersects(&self, other: $BitFlags) -> bool {
184 !(*self & other).is_empty()
187 /// Returns `true` all of the flags in `other` are contained within `self`.
189 pub fn contains(&self, other: $BitFlags) -> bool {
190 (*self & other) == other
193 /// Inserts the specified flags in-place.
195 pub fn insert(&mut self, other: $BitFlags) {
196 self.bits |= other.bits;
199 /// Removes the specified flags in-place.
201 pub fn remove(&mut self, other: $BitFlags) {
202 self.bits &= !other.bits;
205 /// Toggles the specified flags in-place.
207 pub fn toggle(&mut self, other: $BitFlags) {
208 self.bits ^= other.bits;
212 impl ::std::ops::BitOr for $BitFlags {
213 type Output = $BitFlags;
215 /// Returns the union of the two sets of flags.
217 fn bitor(self, other: $BitFlags) -> $BitFlags {
218 $BitFlags { bits: self.bits | other.bits }
222 impl ::std::ops::BitXor for $BitFlags {
223 type Output = $BitFlags;
225 /// Returns the left flags, but with all the right flags toggled.
227 fn bitxor(self, other: $BitFlags) -> $BitFlags {
228 $BitFlags { bits: self.bits ^ other.bits }
232 impl ::std::ops::BitAnd for $BitFlags {
233 type Output = $BitFlags;
235 /// Returns the intersection between the two sets of flags.
237 fn bitand(self, other: $BitFlags) -> $BitFlags {
238 $BitFlags { bits: self.bits & other.bits }
242 impl ::std::ops::Sub for $BitFlags {
243 type Output = $BitFlags;
245 /// Returns the set difference of the two sets of flags.
247 fn sub(self, other: $BitFlags) -> $BitFlags {
248 $BitFlags { bits: self.bits & !other.bits }
252 impl ::std::ops::Not for $BitFlags {
253 type Output = $BitFlags;
255 /// Returns the complement of this set of flags.
257 fn not(self) -> $BitFlags {
258 $BitFlags { bits: !self.bits } & $BitFlags::all()
262 ($(#[$attr:meta])* flags $BitFlags:ident: $T:ty {
263 $($(#[$Flag_attr:meta])* const $Flag:ident = $value:expr),+,
267 flags $BitFlags: $T {
268 $($(#[$Flag_attr])* const $Flag = $value),+
275 #[allow(non_upper_case_globals)]
278 use option::Option::{Some, None};
281 #[doc = "> The first principle is that you must not fool yourself — and"]
282 #[doc = "> you are the easiest person to fool."]
284 #[doc = "> - Richard Feynman"]
286 const FlagA = 0b00000001,
287 #[doc = "<pcwalton> macros are way better at generating code than trans is"]
288 const FlagB = 0b00000010,
289 const FlagC = 0b00000100,
291 #[doc = "* strcat table"]
292 #[doc = "<strcat> wait what?"]
293 const FlagABC = FlagA.bits
300 flags AnotherSetOfFlags: i8 {
301 const AnotherFlag = -1_i8,
307 assert_eq!(Flags::empty().bits(), 0b00000000);
308 assert_eq!(FlagA.bits(), 0b00000001);
309 assert_eq!(FlagABC.bits(), 0b00000111);
311 assert_eq!(AnotherSetOfFlags::empty().bits(), 0b00);
312 assert_eq!(AnotherFlag.bits(), !0_i8);
316 fn test_from_bits() {
317 assert!(Flags::from_bits(0) == Some(Flags::empty()));
318 assert!(Flags::from_bits(0b1) == Some(FlagA));
319 assert!(Flags::from_bits(0b10) == Some(FlagB));
320 assert!(Flags::from_bits(0b11) == Some(FlagA | FlagB));
321 assert!(Flags::from_bits(0b1000) == None);
323 assert!(AnotherSetOfFlags::from_bits(!0_i8) == Some(AnotherFlag));
327 fn test_from_bits_truncate() {
328 assert!(Flags::from_bits_truncate(0) == Flags::empty());
329 assert!(Flags::from_bits_truncate(0b1) == FlagA);
330 assert!(Flags::from_bits_truncate(0b10) == FlagB);
331 assert!(Flags::from_bits_truncate(0b11) == (FlagA | FlagB));
332 assert!(Flags::from_bits_truncate(0b1000) == Flags::empty());
333 assert!(Flags::from_bits_truncate(0b1001) == FlagA);
335 assert!(AnotherSetOfFlags::from_bits_truncate(0_i8) == AnotherSetOfFlags::empty());
340 assert!(Flags::empty().is_empty());
341 assert!(!FlagA.is_empty());
342 assert!(!FlagABC.is_empty());
344 assert!(!AnotherFlag.is_empty());
349 assert!(Flags::all().is_all());
350 assert!(!FlagA.is_all());
351 assert!(FlagABC.is_all());
353 assert!(AnotherFlag.is_all());
357 fn test_two_empties_do_not_intersect() {
358 let e1 = Flags::empty();
359 let e2 = Flags::empty();
360 assert!(!e1.intersects(e2));
362 assert!(AnotherFlag.intersects(AnotherFlag));
366 fn test_empty_does_not_intersect_with_full() {
367 let e1 = Flags::empty();
369 assert!(!e1.intersects(e2));
373 fn test_disjoint_intersects() {
376 assert!(!e1.intersects(e2));
380 fn test_overlapping_intersects() {
382 let e2 = FlagA | FlagB;
383 assert!(e1.intersects(e2));
389 let e2 = FlagA | FlagB;
390 assert!(!e1.contains(e2));
391 assert!(e2.contains(e1));
392 assert!(FlagABC.contains(e2));
394 assert!(AnotherFlag.contains(AnotherFlag));
400 let e2 = FlagA | FlagB;
404 let mut e3 = AnotherSetOfFlags::empty();
405 e3.insert(AnotherFlag);
406 assert!(e3 == AnotherFlag);
411 let mut e1 = FlagA | FlagB;
412 let e2 = FlagA | FlagC;
414 assert!(e1 == FlagB);
416 let mut e3 = AnotherFlag;
417 e3.remove(AnotherFlag);
418 assert!(e3 == AnotherSetOfFlags::empty());
422 fn test_operators() {
423 let e1 = FlagA | FlagC;
424 let e2 = FlagB | FlagC;
425 assert!((e1 | e2) == FlagABC); // union
426 assert!((e1 & e2) == FlagC); // intersection
427 assert!((e1 - e2) == FlagA); // set difference
428 assert!(!e2 == FlagA); // set complement
429 assert!(e1 ^ e2 == FlagA | FlagB); // toggle
432 assert!(e3 == FlagA | FlagB);
434 let mut m4 = AnotherSetOfFlags::empty();
435 m4.toggle(AnotherSetOfFlags::empty());
436 assert!(m4 == AnotherSetOfFlags::empty());
441 let mut a = Flags::empty();
442 let mut b = Flags::empty();
444 assert!(!(a < b) && !(b < a));
448 assert!(!(a < b) && b < a);
455 let mut a = Flags::empty();
456 let mut b = Flags::empty();
458 assert!(a <= b && a >= b);
460 assert!(a > b && a >= b);
461 assert!(b < a && b <= a);
463 assert!(b > a && b >= a);
464 assert!(a < b && a <= b);
469 let mut x = Flags::empty();
470 let mut y = Flags::empty();
471 assert!(hash::hash(&x) == hash::hash(&y));
474 assert!(hash::hash(&x) == hash::hash(&y));