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