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.
12 // Do not remove on snapshot creation. Needed for bootstrap. (Issue #22364)
13 #![cfg_attr(stage0, feature(custom_attribute))]
14 #![crate_name = "rustc_bitflags"]
15 #![feature(associated_consts)]
16 #![feature(staged_api)]
17 #![cfg_attr(stage0, staged_api)]
18 #![crate_type = "rlib"]
19 #![cfg_attr(stage0, feature(no_std))]
21 #![unstable(feature = "rustc_private", issue = "27812")]
23 //! A typesafe bitmask flag generator.
29 /// The `bitflags!` macro generates a `struct` that holds a set of C-style
30 /// bitmask flags. It is useful for creating typesafe wrappers for C APIs.
32 /// The flags should only be defined for integer types, otherwise unexpected
33 /// type errors may occur at compile time.
38 /// #![feature(rustc_private)]
39 /// #![feature(associated_consts)]
40 /// #[macro_use] extern crate rustc_bitflags;
43 /// flags Flags: u32 {
44 /// const FLAG_A = 0b00000001,
45 /// const FLAG_B = 0b00000010,
46 /// const FLAG_C = 0b00000100,
47 /// const FLAG_ABC = Flags::FLAG_A.bits
48 /// | Flags::FLAG_B.bits
49 /// | Flags::FLAG_C.bits,
54 /// let e1 = Flags::FLAG_A | Flags::FLAG_C;
55 /// let e2 = Flags::FLAG_B | Flags::FLAG_C;
56 /// assert!((e1 | e2) == Flags::FLAG_ABC); // union
57 /// assert!((e1 & e2) == Flags::FLAG_C); // intersection
58 /// assert!((e1 - e2) == Flags::FLAG_A); // set difference
59 /// assert!(!e2 == Flags::FLAG_A); // set complement
63 /// The generated `struct`s can also be extended with type and trait implementations:
66 /// #![feature(rustc_private)]
67 /// #[macro_use] extern crate rustc_bitflags;
72 /// flags Flags: u32 {
73 /// const FLAG_A = 0b00000001,
74 /// const FLAG_B = 0b00000010,
79 /// pub fn clear(&mut self) {
80 /// self.bits = 0; // The `bits` field can be accessed from within the
81 /// // same module where the `bitflags!` macro was invoked.
85 /// impl fmt::Debug for Flags {
86 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
92 /// let mut flags = Flags::FLAG_A | Flags::FLAG_B;
94 /// assert!(flags.is_empty());
95 /// assert_eq!(format!("{:?}", flags), "hi!");
101 /// Attributes can be attached to the generated `struct` by placing them
102 /// before the `flags` keyword.
106 /// The `PartialEq` and `Clone` traits are automatically derived for the `struct` using
107 /// the `deriving` attribute. Additional traits can be derived by providing an
108 /// explicit `deriving` attribute on `flags`.
112 /// The following operator traits are implemented for the generated `struct`:
115 /// - `BitAnd`: intersection
116 /// - `BitXor`: toggle
117 /// - `Sub`: set difference
118 /// - `Not`: set complement
122 /// The following methods are defined for the generated `struct`:
124 /// - `empty`: an empty set of flags
125 /// - `all`: the set of all flags
126 /// - `bits`: the raw value of the flags currently stored
127 /// - `from_bits`: convert from underlying bit representation, unless that
128 /// representation contains bits that do not correspond to a flag
129 /// - `from_bits_truncate`: convert from underlying bit representation, dropping
130 /// any bits that do not correspond to flags
131 /// - `is_empty`: `true` if no flags are currently stored
132 /// - `is_all`: `true` if all flags are currently set
133 /// - `intersects`: `true` if there are flags common to both `self` and `other`
134 /// - `contains`: `true` all of the flags in `other` are contained within `self`
135 /// - `insert`: inserts the specified flags in-place
136 /// - `remove`: removes the specified flags in-place
137 /// - `toggle`: the specified flags will be inserted if not present, and removed
140 macro_rules! bitflags {
141 ($(#[$attr:meta])* flags $BitFlags:ident: $T:ty {
142 $($(#[$Flag_attr:meta])* const $Flag:ident = $value:expr),+
144 #[derive(Copy, PartialEq, Eq, Clone, PartialOrd, Ord, Hash)]
146 pub struct $BitFlags {
151 $($(#[$Flag_attr])* pub const $Flag: $BitFlags = $BitFlags { bits: $value };)+
153 /// Returns an empty set of flags.
155 pub fn empty() -> $BitFlags {
156 $BitFlags { bits: 0 }
159 /// Returns the set containing all flags.
161 pub fn all() -> $BitFlags {
162 $BitFlags { bits: $($value)|+ }
165 /// Returns the raw value of the flags currently stored.
167 pub fn bits(&self) -> $T {
171 /// Convert from underlying bit representation, unless that
172 /// representation contains bits that do not correspond to a flag.
174 pub fn from_bits(bits: $T) -> ::std::option::Option<$BitFlags> {
175 if (bits & !$BitFlags::all().bits()) != 0 {
176 ::std::option::Option::None
178 ::std::option::Option::Some($BitFlags { bits: bits })
182 /// Convert from underlying bit representation, dropping any bits
183 /// that do not correspond to flags.
185 pub fn from_bits_truncate(bits: $T) -> $BitFlags {
186 $BitFlags { bits: bits } & $BitFlags::all()
189 /// Returns `true` if no flags are currently stored.
191 pub fn is_empty(&self) -> bool {
192 *self == $BitFlags::empty()
195 /// Returns `true` if all flags are currently set.
197 pub fn is_all(&self) -> bool {
198 *self == $BitFlags::all()
201 /// Returns `true` if there are flags common to both `self` and `other`.
203 pub fn intersects(&self, other: $BitFlags) -> bool {
204 !(*self & other).is_empty()
207 /// Returns `true` all of the flags in `other` are contained within `self`.
209 pub fn contains(&self, other: $BitFlags) -> bool {
210 (*self & other) == other
213 /// Inserts the specified flags in-place.
215 pub fn insert(&mut self, other: $BitFlags) {
216 self.bits |= other.bits;
219 /// Removes the specified flags in-place.
221 pub fn remove(&mut self, other: $BitFlags) {
222 self.bits &= !other.bits;
225 /// Toggles the specified flags in-place.
227 pub fn toggle(&mut self, other: $BitFlags) {
228 self.bits ^= other.bits;
232 impl ::std::ops::BitOr for $BitFlags {
233 type Output = $BitFlags;
235 /// Returns the union of the two sets of flags.
237 fn bitor(self, other: $BitFlags) -> $BitFlags {
238 $BitFlags { bits: self.bits | other.bits }
242 impl ::std::ops::BitXor for $BitFlags {
243 type Output = $BitFlags;
245 /// Returns the left flags, but with all the right flags toggled.
247 fn bitxor(self, other: $BitFlags) -> $BitFlags {
248 $BitFlags { bits: self.bits ^ other.bits }
252 impl ::std::ops::BitAnd for $BitFlags {
253 type Output = $BitFlags;
255 /// Returns the intersection between the two sets of flags.
257 fn bitand(self, other: $BitFlags) -> $BitFlags {
258 $BitFlags { bits: self.bits & other.bits }
262 impl ::std::ops::Sub for $BitFlags {
263 type Output = $BitFlags;
265 /// Returns the set difference of the two sets of flags.
267 fn sub(self, other: $BitFlags) -> $BitFlags {
268 $BitFlags { bits: self.bits & !other.bits }
272 impl ::std::ops::Not for $BitFlags {
273 type Output = $BitFlags;
275 /// Returns the complement of this set of flags.
277 fn not(self) -> $BitFlags {
278 $BitFlags { bits: !self.bits } & $BitFlags::all()
282 ($(#[$attr:meta])* flags $BitFlags:ident: $T:ty {
283 $($(#[$Flag_attr:meta])* const $Flag:ident = $value:expr),+,
287 flags $BitFlags: $T {
288 $($(#[$Flag_attr])* const $Flag = $value),+
295 #[allow(non_upper_case_globals)]
297 use std::hash::{Hasher, Hash, SipHasher};
298 use std::option::Option::{Some, None};
301 #[doc = "> The first principle is that you must not fool yourself — and"]
302 #[doc = "> you are the easiest person to fool."]
304 #[doc = "> - Richard Feynman"]
306 const FlagA = 0b00000001,
307 #[doc = "<pcwalton> macros are way better at generating code than trans is"]
308 const FlagB = 0b00000010,
309 const FlagC = 0b00000100,
311 #[doc = "* strcat table"]
312 #[doc = "<strcat> wait what?"]
313 const FlagABC = Flags::FlagA.bits
320 flags AnotherSetOfFlags: i8 {
321 const AnotherFlag = -1,
327 assert_eq!(Flags::empty().bits(), 0b00000000);
328 assert_eq!(Flags::FlagA.bits(), 0b00000001);
329 assert_eq!(Flags::FlagABC.bits(), 0b00000111);
331 assert_eq!(AnotherSetOfFlags::empty().bits(), 0b00);
332 assert_eq!(AnotherSetOfFlags::AnotherFlag.bits(), !0);
336 fn test_from_bits() {
337 assert!(Flags::from_bits(0) == Some(Flags::empty()));
338 assert!(Flags::from_bits(0b1) == Some(Flags::FlagA));
339 assert!(Flags::from_bits(0b10) == Some(Flags::FlagB));
340 assert!(Flags::from_bits(0b11) == Some(Flags::FlagA | Flags::FlagB));
341 assert!(Flags::from_bits(0b1000) == None);
343 assert!(AnotherSetOfFlags::from_bits(!0) == Some(AnotherSetOfFlags::AnotherFlag));
347 fn test_from_bits_truncate() {
348 assert!(Flags::from_bits_truncate(0) == Flags::empty());
349 assert!(Flags::from_bits_truncate(0b1) == Flags::FlagA);
350 assert!(Flags::from_bits_truncate(0b10) == Flags::FlagB);
351 assert!(Flags::from_bits_truncate(0b11) == (Flags::FlagA | Flags::FlagB));
352 assert!(Flags::from_bits_truncate(0b1000) == Flags::empty());
353 assert!(Flags::from_bits_truncate(0b1001) == Flags::FlagA);
355 assert!(AnotherSetOfFlags::from_bits_truncate(0) == AnotherSetOfFlags::empty());
360 assert!(Flags::empty().is_empty());
361 assert!(!Flags::FlagA.is_empty());
362 assert!(!Flags::FlagABC.is_empty());
364 assert!(!AnotherSetOfFlags::AnotherFlag.is_empty());
369 assert!(Flags::all().is_all());
370 assert!(!Flags::FlagA.is_all());
371 assert!(Flags::FlagABC.is_all());
373 assert!(AnotherSetOfFlags::AnotherFlag.is_all());
377 fn test_two_empties_do_not_intersect() {
378 let e1 = Flags::empty();
379 let e2 = Flags::empty();
380 assert!(!e1.intersects(e2));
382 assert!(AnotherSetOfFlags::AnotherFlag.intersects(AnotherSetOfFlags::AnotherFlag));
386 fn test_empty_does_not_intersect_with_full() {
387 let e1 = Flags::empty();
388 let e2 = Flags::FlagABC;
389 assert!(!e1.intersects(e2));
393 fn test_disjoint_intersects() {
394 let e1 = Flags::FlagA;
395 let e2 = Flags::FlagB;
396 assert!(!e1.intersects(e2));
400 fn test_overlapping_intersects() {
401 let e1 = Flags::FlagA;
402 let e2 = Flags::FlagA | Flags::FlagB;
403 assert!(e1.intersects(e2));
408 let e1 = Flags::FlagA;
409 let e2 = Flags::FlagA | Flags::FlagB;
410 assert!(!e1.contains(e2));
411 assert!(e2.contains(e1));
412 assert!(Flags::FlagABC.contains(e2));
414 assert!(AnotherSetOfFlags::AnotherFlag.contains(AnotherSetOfFlags::AnotherFlag));
419 let mut e1 = Flags::FlagA;
420 let e2 = Flags::FlagA | Flags::FlagB;
424 let mut e3 = AnotherSetOfFlags::empty();
425 e3.insert(AnotherSetOfFlags::AnotherFlag);
426 assert!(e3 == AnotherSetOfFlags::AnotherFlag);
431 let mut e1 = Flags::FlagA | Flags::FlagB;
432 let e2 = Flags::FlagA | Flags::FlagC;
434 assert!(e1 == Flags::FlagB);
436 let mut e3 = AnotherSetOfFlags::AnotherFlag;
437 e3.remove(AnotherSetOfFlags::AnotherFlag);
438 assert!(e3 == AnotherSetOfFlags::empty());
442 fn test_operators() {
443 let e1 = Flags::FlagA | Flags::FlagC;
444 let e2 = Flags::FlagB | Flags::FlagC;
445 assert!((e1 | e2) == Flags::FlagABC); // union
446 assert!((e1 & e2) == Flags::FlagC); // intersection
447 assert!((e1 - e2) == Flags::FlagA); // set difference
448 assert!(!e2 == Flags::FlagA); // set complement
449 assert!(e1 ^ e2 == Flags::FlagA | Flags::FlagB); // toggle
452 assert!(e3 == Flags::FlagA | Flags::FlagB);
454 let mut m4 = AnotherSetOfFlags::empty();
455 m4.toggle(AnotherSetOfFlags::empty());
456 assert!(m4 == AnotherSetOfFlags::empty());
461 let mut a = Flags::empty();
462 let mut b = Flags::empty();
464 assert!(!(a < b) && !(b < a));
468 assert!(!(a < b) && b < a);
469 b = Flags::FlagC | Flags::FlagB;
475 let mut a = Flags::empty();
476 let mut b = Flags::empty();
478 assert!(a <= b && a >= b);
480 assert!(a > b && a >= b);
481 assert!(b < a && b <= a);
483 assert!(b > a && b >= a);
484 assert!(a < b && a <= b);
489 let mut x = Flags::empty();
490 let mut y = Flags::empty();
491 assert!(hash(&x) == hash(&y));
494 assert!(hash(&x) == hash(&y));
497 fn hash<T: Hash>(t: &T) -> u64 {
498 let mut s = SipHasher::new();