]> git.proxmox.com Git - rustc.git/blob - src/vendor/bitflags/src/lib.rs
New upstream version 1.19.0+dfsg1
[rustc.git] / src / vendor / bitflags / src / 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 //! A typesafe bitmask flag generator useful for sets of C-style bitmask flags.
12 //! It can be used for creating typesafe wrappers around C APIs.
13 //!
14 //! The `bitflags!` macro generates a `struct` that manages a set of flags. The
15 //! flags should only be defined for integer types, otherwise unexpected type
16 //! errors may occur at compile time.
17 //!
18 //! # Example
19 //!
20 //! ```
21 //! #[macro_use]
22 //! extern crate bitflags;
23 //!
24 //! bitflags! {
25 //! struct 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_eq!((e1 | e2), FLAG_ABC); // union
39 //! assert_eq!((e1 & e2), FLAG_C); // intersection
40 //! assert_eq!((e1 - e2), FLAG_A); // set difference
41 //! assert_eq!(!e2, FLAG_A); // set complement
42 //! }
43 //! ```
44 //!
45 //! See [`example_generated::Flags`](./example_generated/struct.Flags.html) for documentation of code
46 //! generated by the above `bitflags!` expansion.
47 //!
48 //! The generated `struct`s can also be extended with type and trait
49 //! implementations:
50 //!
51 //! ```
52 //! #[macro_use]
53 //! extern crate bitflags;
54 //!
55 //! use std::fmt;
56 //!
57 //! bitflags! {
58 //! struct Flags: u32 {
59 //! const FLAG_A = 0b00000001;
60 //! const FLAG_B = 0b00000010;
61 //! }
62 //! }
63 //!
64 //! impl Flags {
65 //! pub fn clear(&mut self) {
66 //! self.bits = 0; // The `bits` field can be accessed from within the
67 //! // same module where the `bitflags!` macro was invoked.
68 //! }
69 //! }
70 //!
71 //! impl fmt::Display for Flags {
72 //! fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
73 //! write!(f, "hi!")
74 //! }
75 //! }
76 //!
77 //! fn main() {
78 //! let mut flags = FLAG_A | FLAG_B;
79 //! flags.clear();
80 //! assert!(flags.is_empty());
81 //! assert_eq!(format!("{}", flags), "hi!");
82 //! assert_eq!(format!("{:?}", FLAG_A | FLAG_B), "FLAG_A | FLAG_B");
83 //! assert_eq!(format!("{:?}", FLAG_B), "FLAG_B");
84 //! }
85 //! ```
86 //!
87 //! # Visibility
88 //!
89 //! The generated struct and its associated flag constants are not exported
90 //! out of the current module by default. A definition can be exported out of
91 //! the current module by adding `pub` before `flags`:
92 //!
93 //! ```ignore
94 //! #[macro_use]
95 //! extern crate bitflags;
96 //!
97 //! mod example {
98 //! bitflags! {
99 //! pub struct Flags1: u32 {
100 //! const FLAG_A = 0b00000001;
101 //! }
102 //! }
103 //! bitflags! {
104 //! struct Flags2: u32 {
105 //! const FLAG_B = 0b00000010;
106 //! }
107 //! }
108 //! }
109 //!
110 //! fn main() {
111 //! let flag1 = example::FLAG_A;
112 //! let flag2 = example::FLAG_B; // error: const `FLAG_B` is private
113 //! }
114 //! ```
115 //!
116 //! # Attributes
117 //!
118 //! Attributes can be attached to the generated `struct` by placing them
119 //! before the `flags` keyword.
120 //!
121 //! # Trait implementations
122 //!
123 //! The `Copy`, `Clone`, `PartialEq`, `Eq`, `PartialOrd`, `Ord` and `Hash`
124 //! traits automatically derived for the `struct` using the `derive` attribute.
125 //! Additional traits can be derived by providing an explicit `derive`
126 //! attribute on `flags`.
127 //!
128 //! The `Extend` and `FromIterator` traits are implemented for the `struct`,
129 //! too: `Extend` adds the union of the instances of the `struct` iterated over,
130 //! while `FromIterator` calculates the union.
131 //!
132 //! The `Binary`, `Debug`, `LowerExp`, `Octal` and `UpperExp` trait is also
133 //! implemented by displaying the bits value of the internal struct.
134 //!
135 //! ## Operators
136 //!
137 //! The following operator traits are implemented for the generated `struct`:
138 //!
139 //! - `BitOr` and `BitOrAssign`: union
140 //! - `BitAnd` and `BitAndAssign`: intersection
141 //! - `BitXor` and `BitXorAssign`: toggle
142 //! - `Sub` and `SubAssign`: set difference
143 //! - `Not`: set complement
144 //!
145 //! # Methods
146 //!
147 //! The following methods are defined for the generated `struct`:
148 //!
149 //! - `empty`: an empty set of flags
150 //! - `all`: the set of all flags
151 //! - `bits`: the raw value of the flags currently stored
152 //! - `from_bits`: convert from underlying bit representation, unless that
153 //! representation contains bits that do not correspond to a flag
154 //! - `from_bits_truncate`: convert from underlying bit representation, dropping
155 //! any bits that do not correspond to flags
156 //! - `is_empty`: `true` if no flags are currently stored
157 //! - `is_all`: `true` if all flags are currently set
158 //! - `intersects`: `true` if there are flags common to both `self` and `other`
159 //! - `contains`: `true` all of the flags in `other` are contained within `self`
160 //! - `insert`: inserts the specified flags in-place
161 //! - `remove`: removes the specified flags in-place
162 //! - `toggle`: the specified flags will be inserted if not present, and removed
163 //! if they are.
164 //!
165 //! ## Default
166 //!
167 //! The `Default` trait is not automatically implemented for the generated struct.
168 //!
169 //! If your default value is equal to `0` (which is the same value as calling `empty()`
170 //! on the generated struct), you can simply derive `Default`:
171 //!
172 //! ```
173 //! #[macro_use]
174 //! extern crate bitflags;
175 //!
176 //! bitflags! {
177 //! // Results in default value with bits: 0
178 //! #[derive(Default)]
179 //! struct Flags: u32 {
180 //! const FLAG_A = 0b00000001;
181 //! const FLAG_B = 0b00000010;
182 //! const FLAG_C = 0b00000100;
183 //! }
184 //! }
185 //!
186 //! fn main() {
187 //! let derived_default: Flags = Default::default();
188 //! assert_eq!(derived_default.bits(), 0);
189 //! }
190 //! ```
191 //!
192 //! If your default value is not equal to `0` you need to implement `Default` yourself:
193 //!
194 //! ```
195 //! #[macro_use]
196 //! extern crate bitflags;
197 //!
198 //! bitflags! {
199 //! struct Flags: u32 {
200 //! const FLAG_A = 0b00000001;
201 //! const FLAG_B = 0b00000010;
202 //! const FLAG_C = 0b00000100;
203 //! }
204 //! }
205 //!
206 //! // explicit `Default` implementation
207 //! impl Default for Flags {
208 //! fn default() -> Flags {
209 //! FLAG_A | FLAG_C
210 //! }
211 //! }
212 //!
213 //! fn main() {
214 //! let implemented_default: Flags = Default::default();
215 //! assert_eq!(implemented_default, (FLAG_A | FLAG_C));
216 //! }
217 //! ```
218
219 #![no_std]
220
221 #![doc(html_root_url = "https://docs.rs/bitflags/0.9.1")]
222 // When compiled for the rustc compiler itself we want to make sure that this is
223 // an unstable crate.
224 #![cfg_attr(rustbuild, feature(staged_api))]
225 #![cfg_attr(rustbuild, unstable(feature = "rustc_private", issue = "27812"))]
226
227 #[cfg(test)]
228 #[macro_use]
229 extern crate std;
230
231 // Re-export libstd/libcore using an alias so that the macros can work in no_std
232 // crates while remaining compatible with normal crates.
233 #[doc(hidden)]
234 pub extern crate core as _core;
235
236 /// The macro used to generate the flag structure.
237 ///
238 /// See the [crate level docs](../bitflags/index.html) for complete documentation.
239 ///
240 /// # Example
241 ///
242 /// ```
243 /// #[macro_use]
244 /// extern crate bitflags;
245 ///
246 /// bitflags! {
247 /// struct Flags: u32 {
248 /// const FLAG_A = 0b00000001;
249 /// const FLAG_B = 0b00000010;
250 /// const FLAG_C = 0b00000100;
251 /// const FLAG_ABC = FLAG_A.bits
252 /// | FLAG_B.bits
253 /// | FLAG_C.bits;
254 /// }
255 /// }
256 ///
257 /// fn main() {
258 /// let e1 = FLAG_A | FLAG_C;
259 /// let e2 = FLAG_B | FLAG_C;
260 /// assert_eq!((e1 | e2), FLAG_ABC); // union
261 /// assert_eq!((e1 & e2), FLAG_C); // intersection
262 /// assert_eq!((e1 - e2), FLAG_A); // set difference
263 /// assert_eq!(!e2, FLAG_A); // set complement
264 /// }
265 /// ```
266 ///
267 /// The generated `struct`s can also be extended with type and trait
268 /// implementations:
269 ///
270 /// ```
271 /// #[macro_use]
272 /// extern crate bitflags;
273 ///
274 /// use std::fmt;
275 ///
276 /// bitflags! {
277 /// struct Flags: u32 {
278 /// const FLAG_A = 0b00000001;
279 /// const FLAG_B = 0b00000010;
280 /// }
281 /// }
282 ///
283 /// impl Flags {
284 /// pub fn clear(&mut self) {
285 /// self.bits = 0; // The `bits` field can be accessed from within the
286 /// // same module where the `bitflags!` macro was invoked.
287 /// }
288 /// }
289 ///
290 /// impl fmt::Display for Flags {
291 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
292 /// write!(f, "hi!")
293 /// }
294 /// }
295 ///
296 /// fn main() {
297 /// let mut flags = FLAG_A | FLAG_B;
298 /// flags.clear();
299 /// assert!(flags.is_empty());
300 /// assert_eq!(format!("{}", flags), "hi!");
301 /// assert_eq!(format!("{:?}", FLAG_A | FLAG_B), "FLAG_A | FLAG_B");
302 /// assert_eq!(format!("{:?}", FLAG_B), "FLAG_B");
303 /// }
304 /// ```
305 #[macro_export]
306 macro_rules! bitflags {
307 ($(#[$attr:meta])* pub struct $BitFlags:ident: $T:ty {
308 $($(#[$Flag_attr:meta])* const $Flag:ident = $value:expr;)+
309 }) => {
310 #[derive(Copy, PartialEq, Eq, Clone, PartialOrd, Ord, Hash)]
311 $(#[$attr])*
312 pub struct $BitFlags {
313 bits: $T,
314 }
315
316 $($(#[$Flag_attr])* pub const $Flag: $BitFlags = $BitFlags { bits: $value };)+
317
318 __impl_bitflags! {
319 struct $BitFlags: $T {
320 $($(#[$Flag_attr])* const $Flag = $value;)+
321 }
322 }
323 };
324 ($(#[$attr:meta])* struct $BitFlags:ident: $T:ty {
325 $($(#[$Flag_attr:meta])* const $Flag:ident = $value:expr;)+
326 }) => {
327 #[derive(Copy, PartialEq, Eq, Clone, PartialOrd, Ord, Hash)]
328 $(#[$attr])*
329 struct $BitFlags {
330 bits: $T,
331 }
332
333 $($(#[$Flag_attr])* const $Flag: $BitFlags = $BitFlags { bits: $value };)+
334
335 __impl_bitflags! {
336 struct $BitFlags: $T {
337 $($(#[$Flag_attr])* const $Flag = $value;)+
338 }
339 }
340
341 };
342 }
343
344 #[macro_export]
345 #[doc(hidden)]
346 macro_rules! __impl_bitflags {
347 (struct $BitFlags:ident: $T:ty {
348 $($(#[$Flag_attr:meta])* const $Flag:ident = $value:expr;)+
349 }) => {
350 impl $crate::_core::fmt::Debug for $BitFlags {
351 fn fmt(&self, f: &mut $crate::_core::fmt::Formatter) -> $crate::_core::fmt::Result {
352 // This convoluted approach is to handle #[cfg]-based flag
353 // omission correctly. For example it needs to support:
354 //
355 // #[cfg(unix)] const A: Flag = /* ... */;
356 // #[cfg(windows)] const B: Flag = /* ... */;
357
358 // Unconditionally define a check for every flag, even disabled
359 // ones.
360 #[allow(non_snake_case)]
361 trait __BitFlags {
362 $(
363 fn $Flag(&self) -> bool { false }
364 )+
365 }
366
367 // Conditionally override the check for just those flags that
368 // are not #[cfg]ed away.
369 impl __BitFlags for $BitFlags {
370 $(
371 $(#[$Flag_attr])*
372 fn $Flag(&self) -> bool {
373 self.bits & $Flag.bits == $Flag.bits
374 }
375 )+
376 }
377
378 let mut first = true;
379 $(
380 if <$BitFlags as __BitFlags>::$Flag(self) {
381 if !first {
382 try!(f.write_str(" | "));
383 }
384 first = false;
385 try!(f.write_str(stringify!($Flag)));
386 }
387 )+
388 if first {
389 try!(f.write_str("(empty)"));
390 }
391 Ok(())
392 }
393 }
394 impl $crate::_core::fmt::Binary for $BitFlags {
395 fn fmt(&self, f: &mut $crate::_core::fmt::Formatter) -> $crate::_core::fmt::Result {
396 $crate::_core::fmt::Binary::fmt(&self.bits, f)
397 }
398 }
399 impl $crate::_core::fmt::Octal for $BitFlags {
400 fn fmt(&self, f: &mut $crate::_core::fmt::Formatter) -> $crate::_core::fmt::Result {
401 $crate::_core::fmt::Octal::fmt(&self.bits, f)
402 }
403 }
404 impl $crate::_core::fmt::LowerHex for $BitFlags {
405 fn fmt(&self, f: &mut $crate::_core::fmt::Formatter) -> $crate::_core::fmt::Result {
406 $crate::_core::fmt::LowerHex::fmt(&self.bits, f)
407 }
408 }
409 impl $crate::_core::fmt::UpperHex for $BitFlags {
410 fn fmt(&self, f: &mut $crate::_core::fmt::Formatter) -> $crate::_core::fmt::Result {
411 $crate::_core::fmt::UpperHex::fmt(&self.bits, f)
412 }
413 }
414
415 #[allow(dead_code)]
416 impl $BitFlags {
417 /// Returns an empty set of flags.
418 #[inline]
419 pub fn empty() -> $BitFlags {
420 $BitFlags { bits: 0 }
421 }
422
423 /// Returns the set containing all flags.
424 #[inline]
425 pub fn all() -> $BitFlags {
426 // See `Debug::fmt` for why this approach is taken.
427 #[allow(non_snake_case)]
428 trait __BitFlags {
429 $(
430 fn $Flag() -> $T { 0 }
431 )+
432 }
433 impl __BitFlags for $BitFlags {
434 $(
435 $(#[$Flag_attr])*
436 fn $Flag() -> $T { $Flag.bits }
437 )+
438 }
439 $BitFlags { bits: $(<$BitFlags as __BitFlags>::$Flag())|+ }
440 }
441
442 /// Returns the raw value of the flags currently stored.
443 #[inline]
444 pub fn bits(&self) -> $T {
445 self.bits
446 }
447
448 /// Convert from underlying bit representation, unless that
449 /// representation contains bits that do not correspond to a flag.
450 #[inline]
451 pub fn from_bits(bits: $T) -> $crate::_core::option::Option<$BitFlags> {
452 if (bits & !$BitFlags::all().bits()) == 0 {
453 $crate::_core::option::Option::Some($BitFlags { bits: bits })
454 } else {
455 $crate::_core::option::Option::None
456 }
457 }
458
459 /// Convert from underlying bit representation, dropping any bits
460 /// that do not correspond to flags.
461 #[inline]
462 pub fn from_bits_truncate(bits: $T) -> $BitFlags {
463 $BitFlags { bits: bits } & $BitFlags::all()
464 }
465
466 /// Returns `true` if no flags are currently stored.
467 #[inline]
468 pub fn is_empty(&self) -> bool {
469 *self == $BitFlags::empty()
470 }
471
472 /// Returns `true` if all flags are currently set.
473 #[inline]
474 pub fn is_all(&self) -> bool {
475 *self == $BitFlags::all()
476 }
477
478 /// Returns `true` if there are flags common to both `self` and `other`.
479 #[inline]
480 pub fn intersects(&self, other: $BitFlags) -> bool {
481 !(*self & other).is_empty()
482 }
483
484 /// Returns `true` all of the flags in `other` are contained within `self`.
485 #[inline]
486 pub fn contains(&self, other: $BitFlags) -> bool {
487 (*self & other) == other
488 }
489
490 /// Inserts the specified flags in-place.
491 #[inline]
492 pub fn insert(&mut self, other: $BitFlags) {
493 self.bits |= other.bits;
494 }
495
496 /// Removes the specified flags in-place.
497 #[inline]
498 pub fn remove(&mut self, other: $BitFlags) {
499 self.bits &= !other.bits;
500 }
501
502 /// Toggles the specified flags in-place.
503 #[inline]
504 pub fn toggle(&mut self, other: $BitFlags) {
505 self.bits ^= other.bits;
506 }
507
508 /// Inserts or removes the specified flags depending on the passed value.
509 #[inline]
510 pub fn set(&mut self, other: $BitFlags, value: bool) {
511 if value {
512 self.insert(other);
513 } else {
514 self.remove(other);
515 }
516 }
517 }
518
519 impl $crate::_core::ops::BitOr for $BitFlags {
520 type Output = $BitFlags;
521
522 /// Returns the union of the two sets of flags.
523 #[inline]
524 fn bitor(self, other: $BitFlags) -> $BitFlags {
525 $BitFlags { bits: self.bits | other.bits }
526 }
527 }
528
529 impl $crate::_core::ops::BitOrAssign for $BitFlags {
530
531 /// Adds the set of flags.
532 #[inline]
533 fn bitor_assign(&mut self, other: $BitFlags) {
534 self.bits |= other.bits;
535 }
536 }
537
538 impl $crate::_core::ops::BitXor for $BitFlags {
539 type Output = $BitFlags;
540
541 /// Returns the left flags, but with all the right flags toggled.
542 #[inline]
543 fn bitxor(self, other: $BitFlags) -> $BitFlags {
544 $BitFlags { bits: self.bits ^ other.bits }
545 }
546 }
547
548 impl $crate::_core::ops::BitXorAssign for $BitFlags {
549
550 /// Toggles the set of flags.
551 #[inline]
552 fn bitxor_assign(&mut self, other: $BitFlags) {
553 self.bits ^= other.bits;
554 }
555 }
556
557 impl $crate::_core::ops::BitAnd for $BitFlags {
558 type Output = $BitFlags;
559
560 /// Returns the intersection between the two sets of flags.
561 #[inline]
562 fn bitand(self, other: $BitFlags) -> $BitFlags {
563 $BitFlags { bits: self.bits & other.bits }
564 }
565 }
566
567 impl $crate::_core::ops::BitAndAssign for $BitFlags {
568
569 /// Disables all flags disabled in the set.
570 #[inline]
571 fn bitand_assign(&mut self, other: $BitFlags) {
572 self.bits &= other.bits;
573 }
574 }
575
576 impl $crate::_core::ops::Sub for $BitFlags {
577 type Output = $BitFlags;
578
579 /// Returns the set difference of the two sets of flags.
580 #[inline]
581 fn sub(self, other: $BitFlags) -> $BitFlags {
582 $BitFlags { bits: self.bits & !other.bits }
583 }
584 }
585
586 impl $crate::_core::ops::SubAssign for $BitFlags {
587
588 /// Disables all flags enabled in the set.
589 #[inline]
590 fn sub_assign(&mut self, other: $BitFlags) {
591 self.bits &= !other.bits;
592 }
593 }
594
595 impl $crate::_core::ops::Not for $BitFlags {
596 type Output = $BitFlags;
597
598 /// Returns the complement of this set of flags.
599 #[inline]
600 fn not(self) -> $BitFlags {
601 $BitFlags { bits: !self.bits } & $BitFlags::all()
602 }
603 }
604
605 impl $crate::_core::iter::Extend<$BitFlags> for $BitFlags {
606 fn extend<T: $crate::_core::iter::IntoIterator<Item=$BitFlags>>(&mut self, iterator: T) {
607 for item in iterator {
608 self.insert(item)
609 }
610 }
611 }
612
613 impl $crate::_core::iter::FromIterator<$BitFlags> for $BitFlags {
614 fn from_iter<T: $crate::_core::iter::IntoIterator<Item=$BitFlags>>(iterator: T) -> $BitFlags {
615 let mut result = Self::empty();
616 result.extend(iterator);
617 result
618 }
619 }
620 };
621 }
622
623 #[cfg(feature = "example_generated")]
624 pub mod example_generated;
625
626 #[cfg(test)]
627 #[allow(non_upper_case_globals, dead_code)]
628 mod tests {
629 use std::hash::{Hash, Hasher};
630 use std::collections::hash_map::DefaultHasher;
631
632 bitflags! {
633 #[doc = "> The first principle is that you must not fool yourself — and"]
634 #[doc = "> you are the easiest person to fool."]
635 #[doc = "> "]
636 #[doc = "> - Richard Feynman"]
637 struct Flags: u32 {
638 const FlagA = 0b00000001;
639 #[doc = "<pcwalton> macros are way better at generating code than trans is"]
640 const FlagB = 0b00000010;
641 const FlagC = 0b00000100;
642 #[doc = "* cmr bed"]
643 #[doc = "* strcat table"]
644 #[doc = "<strcat> wait what?"]
645 const FlagABC = FlagA.bits
646 | FlagB.bits
647 | FlagC.bits;
648 }
649 }
650
651 bitflags! {
652 struct _CfgFlags: u32 {
653 #[cfg(windows)]
654 const _CfgA = 0b01;
655 #[cfg(unix)]
656 const _CfgB = 0b01;
657 #[cfg(windows)]
658 const _CfgC = _CfgA.bits | 0b10;
659 }
660 }
661
662 bitflags! {
663 struct AnotherSetOfFlags: i8 {
664 const AnotherFlag = -1_i8;
665 }
666 }
667
668 bitflags! {
669 struct LongFlags: u32 {
670 const LongFlagA = 0b1111111111111111;
671 }
672 }
673
674 #[test]
675 fn test_bits(){
676 assert_eq!(Flags::empty().bits(), 0b00000000);
677 assert_eq!(FlagA.bits(), 0b00000001);
678 assert_eq!(FlagABC.bits(), 0b00000111);
679
680 assert_eq!(AnotherSetOfFlags::empty().bits(), 0b00);
681 assert_eq!(AnotherFlag.bits(), !0_i8);
682 }
683
684 #[test]
685 fn test_from_bits() {
686 assert_eq!(Flags::from_bits(0), Some(Flags::empty()));
687 assert_eq!(Flags::from_bits(0b1), Some(FlagA));
688 assert_eq!(Flags::from_bits(0b10), Some(FlagB));
689 assert_eq!(Flags::from_bits(0b11), Some(FlagA | FlagB));
690 assert_eq!(Flags::from_bits(0b1000), None);
691
692 assert_eq!(AnotherSetOfFlags::from_bits(!0_i8), Some(AnotherFlag));
693 }
694
695 #[test]
696 fn test_from_bits_truncate() {
697 assert_eq!(Flags::from_bits_truncate(0), Flags::empty());
698 assert_eq!(Flags::from_bits_truncate(0b1), FlagA);
699 assert_eq!(Flags::from_bits_truncate(0b10), FlagB);
700 assert_eq!(Flags::from_bits_truncate(0b11), (FlagA | FlagB));
701 assert_eq!(Flags::from_bits_truncate(0b1000), Flags::empty());
702 assert_eq!(Flags::from_bits_truncate(0b1001), FlagA);
703
704 assert_eq!(AnotherSetOfFlags::from_bits_truncate(0_i8), AnotherSetOfFlags::empty());
705 }
706
707 #[test]
708 fn test_is_empty(){
709 assert!(Flags::empty().is_empty());
710 assert!(!FlagA.is_empty());
711 assert!(!FlagABC.is_empty());
712
713 assert!(!AnotherFlag.is_empty());
714 }
715
716 #[test]
717 fn test_is_all() {
718 assert!(Flags::all().is_all());
719 assert!(!FlagA.is_all());
720 assert!(FlagABC.is_all());
721
722 assert!(AnotherFlag.is_all());
723 }
724
725 #[test]
726 fn test_two_empties_do_not_intersect() {
727 let e1 = Flags::empty();
728 let e2 = Flags::empty();
729 assert!(!e1.intersects(e2));
730
731 assert!(AnotherFlag.intersects(AnotherFlag));
732 }
733
734 #[test]
735 fn test_empty_does_not_intersect_with_full() {
736 let e1 = Flags::empty();
737 let e2 = FlagABC;
738 assert!(!e1.intersects(e2));
739 }
740
741 #[test]
742 fn test_disjoint_intersects() {
743 let e1 = FlagA;
744 let e2 = FlagB;
745 assert!(!e1.intersects(e2));
746 }
747
748 #[test]
749 fn test_overlapping_intersects() {
750 let e1 = FlagA;
751 let e2 = FlagA | FlagB;
752 assert!(e1.intersects(e2));
753 }
754
755 #[test]
756 fn test_contains() {
757 let e1 = FlagA;
758 let e2 = FlagA | FlagB;
759 assert!(!e1.contains(e2));
760 assert!(e2.contains(e1));
761 assert!(FlagABC.contains(e2));
762
763 assert!(AnotherFlag.contains(AnotherFlag));
764 }
765
766 #[test]
767 fn test_insert(){
768 let mut e1 = FlagA;
769 let e2 = FlagA | FlagB;
770 e1.insert(e2);
771 assert_eq!(e1, e2);
772
773 let mut e3 = AnotherSetOfFlags::empty();
774 e3.insert(AnotherFlag);
775 assert_eq!(e3, AnotherFlag);
776 }
777
778 #[test]
779 fn test_remove(){
780 let mut e1 = FlagA | FlagB;
781 let e2 = FlagA | FlagC;
782 e1.remove(e2);
783 assert_eq!(e1, FlagB);
784
785 let mut e3 = AnotherFlag;
786 e3.remove(AnotherFlag);
787 assert_eq!(e3, AnotherSetOfFlags::empty());
788 }
789
790 #[test]
791 fn test_operators() {
792 let e1 = FlagA | FlagC;
793 let e2 = FlagB | FlagC;
794 assert_eq!((e1 | e2), FlagABC); // union
795 assert_eq!((e1 & e2), FlagC); // intersection
796 assert_eq!((e1 - e2), FlagA); // set difference
797 assert_eq!(!e2, FlagA); // set complement
798 assert_eq!(e1 ^ e2, FlagA | FlagB); // toggle
799 let mut e3 = e1;
800 e3.toggle(e2);
801 assert_eq!(e3, FlagA | FlagB);
802
803 let mut m4 = AnotherSetOfFlags::empty();
804 m4.toggle(AnotherSetOfFlags::empty());
805 assert_eq!(m4, AnotherSetOfFlags::empty());
806 }
807
808 #[test]
809 fn test_set() {
810 let mut e1 = FlagA | FlagC;
811 e1.set(FlagB, true);
812 e1.set(FlagC, false);
813
814 assert_eq!(e1, FlagA | FlagB);
815 }
816
817 #[test]
818 fn test_assignment_operators() {
819 let mut m1 = Flags::empty();
820 let e1 = FlagA | FlagC;
821 // union
822 m1 |= FlagA;
823 assert_eq!(m1, FlagA);
824 // intersection
825 m1 &= e1;
826 assert_eq!(m1, FlagA);
827 // set difference
828 m1 -= m1;
829 assert_eq!(m1, Flags::empty());
830 // toggle
831 m1 ^= e1;
832 assert_eq!(m1, e1);
833 }
834
835 #[test]
836 fn test_extend() {
837 let mut flags;
838
839 flags = Flags::empty();
840 flags.extend([].iter().cloned());
841 assert_eq!(flags, Flags::empty());
842
843 flags = Flags::empty();
844 flags.extend([FlagA, FlagB].iter().cloned());
845 assert_eq!(flags, FlagA | FlagB);
846
847 flags = FlagA;
848 flags.extend([FlagA, FlagB].iter().cloned());
849 assert_eq!(flags, FlagA | FlagB);
850
851 flags = FlagB;
852 flags.extend([FlagA, FlagABC].iter().cloned());
853 assert_eq!(flags, FlagABC);
854 }
855
856 #[test]
857 fn test_from_iterator() {
858 assert_eq!([].iter().cloned().collect::<Flags>(), Flags::empty());
859 assert_eq!([FlagA, FlagB].iter().cloned().collect::<Flags>(), FlagA | FlagB);
860 assert_eq!([FlagA, FlagABC].iter().cloned().collect::<Flags>(), FlagABC);
861 }
862
863 #[test]
864 fn test_lt() {
865 let mut a = Flags::empty();
866 let mut b = Flags::empty();
867
868 assert!(!(a < b) && !(b < a));
869 b = FlagB;
870 assert!(a < b);
871 a = FlagC;
872 assert!(!(a < b) && b < a);
873 b = FlagC | FlagB;
874 assert!(a < b);
875 }
876
877 #[test]
878 fn test_ord() {
879 let mut a = Flags::empty();
880 let mut b = Flags::empty();
881
882 assert!(a <= b && a >= b);
883 a = FlagA;
884 assert!(a > b && a >= b);
885 assert!(b < a && b <= a);
886 b = FlagB;
887 assert!(b > a && b >= a);
888 assert!(a < b && a <= b);
889 }
890
891 fn hash<T: Hash>(t: &T) -> u64 {
892 let mut s = DefaultHasher::new();
893 t.hash(&mut s);
894 s.finish()
895 }
896
897 #[test]
898 fn test_hash() {
899 let mut x = Flags::empty();
900 let mut y = Flags::empty();
901 assert_eq!(hash(&x), hash(&y));
902 x = Flags::all();
903 y = FlagABC;
904 assert_eq!(hash(&x), hash(&y));
905 }
906
907 #[test]
908 fn test_debug() {
909 assert_eq!(format!("{:?}", FlagA | FlagB), "FlagA | FlagB");
910 assert_eq!(format!("{:?}", Flags::empty()), "(empty)");
911 assert_eq!(format!("{:?}", FlagABC), "FlagA | FlagB | FlagC | FlagABC");
912 }
913
914 #[test]
915 fn test_binary() {
916 assert_eq!(format!("{:b}", FlagABC), "111");
917 assert_eq!(format!("{:#b}", FlagABC), "0b111");
918 }
919
920 #[test]
921 fn test_octal() {
922 assert_eq!(format!("{:o}", LongFlagA), "177777");
923 assert_eq!(format!("{:#o}", LongFlagA), "0o177777");
924 }
925
926 #[test]
927 fn test_lowerhex() {
928 assert_eq!(format!("{:x}", LongFlagA), "ffff");
929 assert_eq!(format!("{:#x}", LongFlagA), "0xffff");
930 }
931
932 #[test]
933 fn test_upperhex() {
934 assert_eq!(format!("{:X}", LongFlagA), "FFFF");
935 assert_eq!(format!("{:#X}", LongFlagA), "0xFFFF");
936 }
937
938 mod submodule {
939 bitflags! {
940 pub struct PublicFlags: i8 {
941 const FlagX = 0;
942 }
943 }
944 bitflags! {
945 struct PrivateFlags: i8 {
946 const FlagY = 0;
947 }
948 }
949
950 #[test]
951 fn test_private() {
952 let _ = FlagY;
953 }
954 }
955
956 #[test]
957 fn test_public() {
958 let _ = submodule::FlagX;
959 }
960
961 mod t1 {
962 mod foo {
963 pub type Bar = i32;
964 }
965
966 bitflags! {
967 /// baz
968 struct Flags: foo::Bar {
969 const A = 0b00000001;
970 #[cfg(foo)]
971 const B = 0b00000010;
972 #[cfg(foo)]
973 const C = 0b00000010;
974 }
975 }
976 }
977
978 #[test]
979 fn test_in_function() {
980 bitflags! {
981 struct Flags: u8 {
982 const A = 1;
983 #[cfg(any())] // false
984 const B = 2;
985 }
986 }
987 assert_eq!(Flags::all(), A);
988 assert_eq!(format!("{:?}", A), "A");
989 }
990 }