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