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