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