]> git.lizzy.rs Git - rust.git/blob - src/libstd/bitflags.rs
rollup merge of #19577: aidancully/master
[rust.git] / src / libstd / bitflags.rs
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.
4 //
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.
10
11 #![experimental]
12 #![macro_escape]
13
14 //! A typesafe bitmask flag generator.
15
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.
18 ///
19 /// The flags should only be defined for integer types, otherwise unexpected
20 /// type errors may occur at compile time.
21 ///
22 /// # Example
23 ///
24 /// ```{.rust}
25 /// bitflags! {
26 ///     flags Flags: u32 {
27 ///         const FLAG_A       = 0x00000001,
28 ///         const FLAG_B       = 0x00000010,
29 ///         const FLAG_C       = 0x00000100,
30 ///         const FLAG_ABC     = FLAG_A.bits
31 ///                            | FLAG_B.bits
32 ///                            | FLAG_C.bits,
33 ///     }
34 /// }
35 ///
36 /// impl Copy for Flags {}
37 ///
38 /// fn main() {
39 ///     let e1 = FLAG_A | FLAG_C;
40 ///     let e2 = FLAG_B | FLAG_C;
41 ///     assert!((e1 | e2) == FLAG_ABC);   // union
42 ///     assert!((e1 & e2) == FLAG_C);     // intersection
43 ///     assert!((e1 - e2) == FLAG_A);     // set difference
44 ///     assert!(!e2 == FLAG_A);           // set complement
45 /// }
46 /// ```
47 ///
48 /// The generated `struct`s can also be extended with type and trait implementations:
49 ///
50 /// ```{.rust}
51 /// use std::fmt;
52 ///
53 /// bitflags! {
54 ///     flags Flags: u32 {
55 ///         const FLAG_A   = 0x00000001,
56 ///         const FLAG_B   = 0x00000010,
57 ///     }
58 /// }
59 ///
60 /// impl Copy for Flags {}
61 ///
62 /// impl Flags {
63 ///     pub fn clear(&mut self) {
64 ///         self.bits = 0;  // The `bits` field can be accessed from within the
65 ///                         // same module where the `bitflags!` macro was invoked.
66 ///     }
67 /// }
68 ///
69 /// impl fmt::Show for Flags {
70 ///     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
71 ///         write!(f, "hi!")
72 ///     }
73 /// }
74 ///
75 /// fn main() {
76 ///     let mut flags = FLAG_A | FLAG_B;
77 ///     flags.clear();
78 ///     assert!(flags.is_empty());
79 ///     assert_eq!(format!("{}", flags).as_slice(), "hi!");
80 /// }
81 /// ```
82 ///
83 /// # Attributes
84 ///
85 /// Attributes can be attached to the generated `struct` by placing them
86 /// before the `flags` keyword.
87 ///
88 /// # Derived traits
89 ///
90 /// The `PartialEq` and `Clone` traits are automatically derived for the `struct` using
91 /// the `deriving` attribute. Additional traits can be derived by providing an
92 /// explicit `deriving` attribute on `flags`.
93 ///
94 /// # Operators
95 ///
96 /// The following operator traits are implemented for the generated `struct`:
97 ///
98 /// - `BitOr`: union
99 /// - `BitAnd`: intersection
100 /// - `BitXor`: toggle
101 /// - `Sub`: set difference
102 /// - `Not`: set complement
103 ///
104 /// # Methods
105 ///
106 /// The following methods are defined for the generated `struct`:
107 ///
108 /// - `empty`: an empty set of flags
109 /// - `all`: the set of all flags
110 /// - `bits`: the raw value of the flags currently stored
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
118 ///             if they are.
119 #[macro_export]
120 macro_rules! bitflags {
121     ($(#[$attr:meta])* flags $BitFlags:ident: $T:ty {
122         $($(#[$Flag_attr:meta])* const $Flag:ident = $value:expr),+
123     }) => {
124         #[deriving(PartialEq, Eq, Clone, PartialOrd, Ord, Hash)]
125         $(#[$attr])*
126         pub struct $BitFlags {
127             bits: $T,
128         }
129
130         $($(#[$Flag_attr])* pub const $Flag: $BitFlags = $BitFlags { bits: $value };)+
131
132         impl $BitFlags {
133             /// Returns an empty set of flags.
134             #[inline]
135             pub fn empty() -> $BitFlags {
136                 $BitFlags { bits: 0 }
137             }
138
139             /// Returns the set containing all flags.
140             #[inline]
141             pub fn all() -> $BitFlags {
142                 $BitFlags { bits: $($value)|+ }
143             }
144
145             /// Returns the raw value of the flags currently stored.
146             #[inline]
147             pub fn bits(&self) -> $T {
148                 self.bits
149             }
150
151             /// Convert from underlying bit representation, unless that
152             /// representation contains bits that do not correspond to a flag.
153             #[inline]
154             pub fn from_bits(bits: $T) -> ::std::option::Option<$BitFlags> {
155                 if (bits & !$BitFlags::all().bits()) != 0 {
156                     ::std::option::Option::None
157                 } else {
158                     ::std::option::Option::Some($BitFlags { bits: bits })
159                 }
160             }
161
162             /// Convert from underlying bit representation, dropping any bits
163             /// that do not correspond to flags.
164             #[inline]
165             pub fn from_bits_truncate(bits: $T) -> $BitFlags {
166                 $BitFlags { bits: bits } & $BitFlags::all()
167             }
168
169             /// Returns `true` if no flags are currently stored.
170             #[inline]
171             pub fn is_empty(&self) -> bool {
172                 *self == $BitFlags::empty()
173             }
174
175             /// Returns `true` if all flags are currently set.
176             #[inline]
177             pub fn is_all(&self) -> bool {
178                 *self == $BitFlags::all()
179             }
180
181             /// Returns `true` if there are flags common to both `self` and `other`.
182             #[inline]
183             pub fn intersects(&self, other: $BitFlags) -> bool {
184                 !(*self & other).is_empty()
185             }
186
187             /// Returns `true` all of the flags in `other` are contained within `self`.
188             #[inline]
189             pub fn contains(&self, other: $BitFlags) -> bool {
190                 (*self & other) == other
191             }
192
193             /// Inserts the specified flags in-place.
194             #[inline]
195             pub fn insert(&mut self, other: $BitFlags) {
196                 self.bits |= other.bits;
197             }
198
199             /// Removes the specified flags in-place.
200             #[inline]
201             pub fn remove(&mut self, other: $BitFlags) {
202                 self.bits &= !other.bits;
203             }
204
205             /// Toggles the specified flags in-place.
206             #[inline]
207             pub fn toggle(&mut self, other: $BitFlags) {
208                 self.bits ^= other.bits;
209             }
210         }
211
212         impl BitOr<$BitFlags, $BitFlags> for $BitFlags {
213             /// Returns the union of the two sets of flags.
214             #[inline]
215             fn bitor(&self, other: &$BitFlags) -> $BitFlags {
216                 $BitFlags { bits: self.bits | other.bits }
217             }
218         }
219
220         impl BitXor<$BitFlags, $BitFlags> for $BitFlags {
221             /// Returns the left flags, but with all the right flags toggled.
222             #[inline]
223             fn bitxor(&self, other: &$BitFlags) -> $BitFlags {
224                 $BitFlags { bits: self.bits ^ other.bits }
225             }
226         }
227
228         impl BitAnd<$BitFlags, $BitFlags> for $BitFlags {
229             /// Returns the intersection between the two sets of flags.
230             #[inline]
231             fn bitand(&self, other: &$BitFlags) -> $BitFlags {
232                 $BitFlags { bits: self.bits & other.bits }
233             }
234         }
235
236         impl Sub<$BitFlags, $BitFlags> for $BitFlags {
237             /// Returns the set difference of the two sets of flags.
238             #[inline]
239             fn sub(&self, other: &$BitFlags) -> $BitFlags {
240                 $BitFlags { bits: self.bits & !other.bits }
241             }
242         }
243
244         impl Not<$BitFlags> for $BitFlags {
245             /// Returns the complement of this set of flags.
246             #[inline]
247             fn not(&self) -> $BitFlags {
248                 $BitFlags { bits: !self.bits } & $BitFlags::all()
249             }
250         }
251     };
252     ($(#[$attr:meta])* flags $BitFlags:ident: $T:ty {
253         $($(#[$Flag_attr:meta])* const $Flag:ident = $value:expr),+,
254     }) => {
255         bitflags! {
256             $(#[$attr])*
257             flags $BitFlags: $T {
258                 $($(#[$Flag_attr])* const $Flag = $value),+
259             }
260         }
261     };
262 }
263
264 #[cfg(test)]
265 #[allow(non_upper_case_globals)]
266 mod tests {
267     use kinds::Copy;
268     use hash;
269     use option::Option::{Some, None};
270     use ops::{BitOr, BitAnd, BitXor, Sub, Not};
271
272     bitflags! {
273         #[doc = "> The first principle is that you must not fool yourself — and"]
274         #[doc = "> you are the easiest person to fool."]
275         #[doc = "> "]
276         #[doc = "> - Richard Feynman"]
277         flags Flags: u32 {
278             const FlagA       = 0x00000001,
279             #[doc = "<pcwalton> macros are way better at generating code than trans is"]
280             const FlagB       = 0x00000010,
281             const FlagC       = 0x00000100,
282             #[doc = "* cmr bed"]
283             #[doc = "* strcat table"]
284             #[doc = "<strcat> wait what?"]
285             const FlagABC     = FlagA.bits
286                                | FlagB.bits
287                                | FlagC.bits,
288         }
289     }
290
291     impl Copy for Flags {}
292
293     bitflags! {
294         flags AnotherSetOfFlags: i8 {
295             const AnotherFlag = -1_i8,
296         }
297     }
298
299     impl Copy for AnotherSetOfFlags {}
300
301     #[test]
302     fn test_bits(){
303         assert_eq!(Flags::empty().bits(), 0x00000000);
304         assert_eq!(FlagA.bits(), 0x00000001);
305         assert_eq!(FlagABC.bits(), 0x00000111);
306
307         assert_eq!(AnotherSetOfFlags::empty().bits(), 0x00);
308         assert_eq!(AnotherFlag.bits(), !0_i8);
309     }
310
311     #[test]
312     fn test_from_bits() {
313         assert!(Flags::from_bits(0) == Some(Flags::empty()));
314         assert!(Flags::from_bits(0x1) == Some(FlagA));
315         assert!(Flags::from_bits(0x10) == Some(FlagB));
316         assert!(Flags::from_bits(0x11) == Some(FlagA | FlagB));
317         assert!(Flags::from_bits(0x1000) == None);
318
319         assert!(AnotherSetOfFlags::from_bits(!0_i8) == Some(AnotherFlag));
320     }
321
322     #[test]
323     fn test_from_bits_truncate() {
324         assert!(Flags::from_bits_truncate(0) == Flags::empty());
325         assert!(Flags::from_bits_truncate(0x1) == FlagA);
326         assert!(Flags::from_bits_truncate(0x10) == FlagB);
327         assert!(Flags::from_bits_truncate(0x11) == (FlagA | FlagB));
328         assert!(Flags::from_bits_truncate(0x1000) == Flags::empty());
329         assert!(Flags::from_bits_truncate(0x1001) == FlagA);
330
331         assert!(AnotherSetOfFlags::from_bits_truncate(0_i8) == AnotherSetOfFlags::empty());
332     }
333
334     #[test]
335     fn test_is_empty(){
336         assert!(Flags::empty().is_empty());
337         assert!(!FlagA.is_empty());
338         assert!(!FlagABC.is_empty());
339
340         assert!(!AnotherFlag.is_empty());
341     }
342
343     #[test]
344     fn test_is_all() {
345         assert!(Flags::all().is_all());
346         assert!(!FlagA.is_all());
347         assert!(FlagABC.is_all());
348
349         assert!(AnotherFlag.is_all());
350     }
351
352     #[test]
353     fn test_two_empties_do_not_intersect() {
354         let e1 = Flags::empty();
355         let e2 = Flags::empty();
356         assert!(!e1.intersects(e2));
357
358         assert!(AnotherFlag.intersects(AnotherFlag));
359     }
360
361     #[test]
362     fn test_empty_does_not_intersect_with_full() {
363         let e1 = Flags::empty();
364         let e2 = FlagABC;
365         assert!(!e1.intersects(e2));
366     }
367
368     #[test]
369     fn test_disjoint_intersects() {
370         let e1 = FlagA;
371         let e2 = FlagB;
372         assert!(!e1.intersects(e2));
373     }
374
375     #[test]
376     fn test_overlapping_intersects() {
377         let e1 = FlagA;
378         let e2 = FlagA | FlagB;
379         assert!(e1.intersects(e2));
380     }
381
382     #[test]
383     fn test_contains() {
384         let e1 = FlagA;
385         let e2 = FlagA | FlagB;
386         assert!(!e1.contains(e2));
387         assert!(e2.contains(e1));
388         assert!(FlagABC.contains(e2));
389
390         assert!(AnotherFlag.contains(AnotherFlag));
391     }
392
393     #[test]
394     fn test_insert(){
395         let mut e1 = FlagA;
396         let e2 = FlagA | FlagB;
397         e1.insert(e2);
398         assert!(e1 == e2);
399
400         let mut e3 = AnotherSetOfFlags::empty();
401         e3.insert(AnotherFlag);
402         assert!(e3 == AnotherFlag);
403     }
404
405     #[test]
406     fn test_remove(){
407         let mut e1 = FlagA | FlagB;
408         let e2 = FlagA | FlagC;
409         e1.remove(e2);
410         assert!(e1 == FlagB);
411
412         let mut e3 = AnotherFlag;
413         e3.remove(AnotherFlag);
414         assert!(e3 == AnotherSetOfFlags::empty());
415     }
416
417     #[test]
418     fn test_operators() {
419         let e1 = FlagA | FlagC;
420         let e2 = FlagB | FlagC;
421         assert!((e1 | e2) == FlagABC);     // union
422         assert!((e1 & e2) == FlagC);       // intersection
423         assert!((e1 - e2) == FlagA);       // set difference
424         assert!(!e2 == FlagA);             // set complement
425         assert!(e1 ^ e2 == FlagA | FlagB); // toggle
426         let mut e3 = e1;
427         e3.toggle(e2);
428         assert!(e3 == FlagA | FlagB);
429
430         let mut m4 = AnotherSetOfFlags::empty();
431         m4.toggle(AnotherSetOfFlags::empty());
432         assert!(m4 == AnotherSetOfFlags::empty());
433     }
434
435     #[test]
436     fn test_lt() {
437         let mut a = Flags::empty();
438         let mut b = Flags::empty();
439
440         assert!(!(a < b) && !(b < a));
441         b = FlagB;
442         assert!(a < b);
443         a = FlagC;
444         assert!(!(a < b) && b < a);
445         b = FlagC | FlagB;
446         assert!(a < b);
447     }
448
449     #[test]
450     fn test_ord() {
451         let mut a = Flags::empty();
452         let mut b = Flags::empty();
453
454         assert!(a <= b && a >= b);
455         a = FlagA;
456         assert!(a > b && a >= b);
457         assert!(b < a && b <= a);
458         b = FlagB;
459         assert!(b > a && b >= a);
460         assert!(a < b && a <= b);
461     }
462
463     #[test]
464     fn test_hash() {
465       let mut x = Flags::empty();
466       let mut y = Flags::empty();
467       assert!(hash::hash(&x) == hash::hash(&y));
468       x = Flags::all();
469       y = FlagABC;
470       assert!(hash::hash(&x) == hash::hash(&y));
471     }
472 }