1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
//! More ergonomic bitflags

#![deny(missing_docs)]

/// Generates a bitflags type, wrapping a given primitive integer type.
///
/// # Example
///
/// The following macro invocation will create a `struct Foo`:
///
/// ```ignore
/// #[macro_use] extern crate new_bitflags;
///
/// new_bitflags!{
///     pub flags Foo: u32 {
///         const flag_a = 1 << 0;
///         const flag_b = 1 << 1;
///         const flag_c = 1 << 2;
///     }
/// }
///
/// impl Foo {
///     pub fn flag_abc() -> Foo {
///         Foo::flag_a() |
///         Foo::flag_b() |
///         Foo::flag_c()
///     }
/// }
///
/// fn main() {
///     let f1 = Foo::flag_a() | Foo::flag_c();
///     let f2 = Foo::flag_b() | Foo::flag_c();
///
///     assert_eq!((f1 | f2), Foo::flag_abc()); // union
///     assert_eq!((f1 & f2), Foo::flag_c());   // intersection
///     assert_eq!((f1 - f2), Foo::flag_a());   // difference
///     assert_eq!(!f2,       Foo::flag_a());   // complement
/// }
/// ```
///
/// The generated `struct` can be extended with type and trait `impl`s.
///
/// ```ignore
/// impl Foo {
///     pub fn is_flag_a(&self) -> bool {
///         self.contains(Foo::flag_a())
///     }
/// }
/// ```
///
/// # Visibility
///
/// The visibility of the generated `struct` can be controlled within the
/// invocation of `new_bitflags!`
///
/// ```ignore
/// #[macro_use] extern crate new_bitflags;
///
/// mod example {
///     // `struct Public` will be visible outside this module.
///     new_bitflags!{
///         pub flags Public: u32 {
///             // ...
///         }
///     }
///
///     // `struct Private` will not be visible outside this module.
///     new_bitflags!{
///         flags Private: u32 {
///             // ...
///         }
///     }
/// }
/// ```
///
/// # Trait implementations
///
/// Generated `struct` types will have derived implementations of the following
/// traits: `Copy`, `Clone`, `Hash`, `PartialEq`, `Eq`, `PartialOrd`, and `Ord`.
///
/// The traits `Extend` and `FromIterator` are implemented for sequences of
/// `Self` and `&Self`.
///
/// The `Debug` trait implementation will display the set of named flags contained
/// in a set.
///
/// # Operators
///
/// The following operators are implemented for generated `struct` types:
///
/// * `BitOr` and `BitOrAssign` perform union
/// * `BitAnd` and `BitAndAssign` perform intersection
/// * `BitXor` and `BitXorAssign` perform toggle
/// * `Sub` and `SubAssign` perform set difference
/// * `Not` performs set complement
///
/// # Methods
///
/// The following methods are implemented for generated `struct` types:
///
/// * `fn from_bits(bits) -> Option<Self>` converts from underlying bits,
///    checking that all bits correspond to defined flags.
/// * `fn from_bits_truncate(bits) -> Option<Self>` converts from underlying bits,
///   truncating any bits that do not correspond to defined flags.
/// * `fn bits(&self) -> bits` returns the underlying bits
/// * `fn contains(&self, other: Self) -> bool` returns whether the set
///   contains all flags present in `other`
/// * `fn clear(&mut self)` clears all flags on the set
/// * `fn all() -> Self` returns all defined flags
/// * `fn empty() -> Self` returns an empty set
/// * `fn is_all(&self) -> bool` returns whether the set contains all flags
/// * `fn is_empty(&self) -> bool` returns whether the set is empty
/// * `fn intersects(&self, other: Self) -> bool` returns whether any flags
///   are common between `self` and `other`.
/// * `fn insert(&mut self, other: Self)` inserts all flags in `other`
/// * `fn remove(&mut self, other: Self)` removes all flags in `other`
/// * `fn toggle(&mut self, other: Self)` toggles all flags in `other`
/// * `fn set(&mut self, other: Self, value: bool)` sets or removes all flags
///   in `other`, depending on boolean `value`
///
/// Additionally, for each defined flag, a static method of signature
/// `fn() -> Self` is defined, returning a set containing only the named flag.
#[macro_export]
macro_rules! new_bitflags {
    ( $(#[$attr:meta])* pub flags $name:ident : $inner:ty
            { $( $(#[$flag_attr:meta])* const $flag:ident = $value:expr ; )* } ) => {
        #[derive(Copy, Clone, Hash, Eq, PartialEq, Ord, PartialOrd)]
        $(#[$attr])*
        pub struct $name($inner);

        new_bitflags!{ @_impl $name : $inner
            { $( $(#[$flag_attr])* const $flag = $value ; )* } }
    };
    ( $(#[$attr:meta])* flags $name:ident : $inner:ty
            { $( $(#[$flag_attr:meta])* const $flag:ident = $value:expr ; )* } ) => {
        #[derive(Copy, Clone, Hash, Eq, PartialEq, Ord, PartialOrd)]
        $(#[$attr])*
        struct $name($inner);

        new_bitflags!{ @_impl $name : $inner
            { $( $(#[$flag_attr])* const $flag = $value ; )* } }
    };
    ( @_impl $name:ident : $inner:ty
            { $( $(#[$flag_attr:meta])* const $flag:ident = $value:expr ; )* } ) => {
        #[allow(dead_code)]
        impl $name {
            /// Converts from a set of bits, only if all set bits correspond
            /// to defined flags.
            #[inline]
            pub fn from_bits(bits: $inner) -> ::std::option::Option<$name> {
                if (bits & !$name::all().bits()) == 0 {
                    Some($name(bits))
                } else {
                    None
                }
            }

            /// Converts from a set of bits, truncating any invalid bits.
            #[inline]
            pub fn from_bits_truncate(bits: $inner) -> $name {
                $name(bits) & $name::all()
            }

            /// Returns the underlying bits.
            #[inline]
            pub fn bits(&self) -> $inner {
                self.0
            }

            /// Returns whether the given flags are set in `self`.
            #[inline]
            pub fn contains(&self, flag: $name) -> bool {
                *self & flag == flag
            }

            /// Zeroes all bits.
            #[inline]
            pub fn clear(&mut self) {
                self.0 = 0;
            }

            /// Returns the set of all defined flags.
            #[inline]
            pub fn all() -> $name {
                $name(0 $( | $value )*)
            }

            /// Returns an empty set.
            #[inline]
            pub fn empty() -> $name {
                $name(0)
            }

            /// Returns whether all defined flags are set in `self`.
            #[inline]
            pub fn is_all(&self) -> bool {
                self == $name::all()
            }

            /// Returns whether no defined flags are set in `self`.
            #[inline]
            pub fn is_empty(&self) -> bool {
                self.bits() == 0
            }

            /// Returns whether any flags contained in `other` are also
            /// contained in `self`.
            #[inline]
            pub fn intersects(&self, other: $name) -> bool {
                !(*self & other).is_empty()
            }

            /// Inserts a set of flags in-place.
            #[inline]
            pub fn insert(&mut self, other: $name) {
                self.0 |= other.0;
            }

            /// Removes a set of flags in-place.
            #[inline]
            pub fn remove(&mut self, other: $name) {
                self.0 &= !other.0;
            }

            /// Toggles a set of flags in-place.
            #[inline]
            pub fn toggle(&mut self, other: $name) {
                self.0 ^= other.0;
            }

            /// Inserts or removes the given set of flags.
            #[inline]
            pub fn set(&mut self, other: $name, value: bool) {
                if value {
                    self.insert(other);
                } else {
                    self.remove(other);
                }
            }

            $( $(#[$flag_attr])*
            #[inline]
            pub fn $flag() -> $name {
                $name($value)
            } )*
        }

        impl ::std::fmt::Debug for $name {
            fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
                let mut flags = *self;
                let mut _first = true;

                f.write_str(concat!(stringify!($name), "("))?;

                $( if !$name::$flag().is_empty() && flags.contains($name::$flag()) {
                    if !_first {
                        f.write_str(" | ")?;
                    }
                    _first = false;

                    flags.remove($name::$flag());
                    f.write_str(stringify!($flag))?;
                } )*

                f.write_str(")")
            }
        }

        impl ::std::iter::Extend<$name> for $name {
            fn extend<I: ::std::iter::IntoIterator<Item=$name>>(&mut self, iter: I) {
                for flag in iter {
                    self.insert(flag);
                }
            }
        }

        impl<'a> ::std::iter::Extend<&'a $name> for $name {
            fn extend<I: ::std::iter::IntoIterator<Item=&'a $name>>(&mut self, iter: I) {
                for flag in iter {
                    self.insert(*flag);
                }
            }
        }

        impl ::std::iter::FromIterator<$name> for $name {
            fn from_iter<I: IntoIterator<Item=$name>>(iter: I) -> $name {
                let mut flags = $name::empty();
                flags.extend(iter);
                flags
            }
        }

        impl<'a> ::std::iter::FromIterator<&'a $name> for $name {
            fn from_iter<I: IntoIterator<Item=&'a $name>>(iter: I) -> $name {
                let mut flags = $name::empty();
                flags.extend(iter);
                flags
            }
        }

        impl ::std::ops::BitOr for $name {
            type Output = $name;

            #[inline]
            fn bitor(self, rhs: $name) -> $name {
                $name(self.0 | rhs.0)
            }
        }

        impl ::std::ops::BitOrAssign for $name {
            #[inline]
            fn bitor_assign(&mut self, rhs: $name) {
                self.0 |= rhs.0;
            }
        }

        impl ::std::ops::BitAnd for $name {
            type Output = $name;

            #[inline]
            fn bitand(self, rhs: $name) -> $name {
                $name(self.0 & rhs.0)
            }
        }

        impl ::std::ops::BitAndAssign for $name {
            #[inline]
            fn bitand_assign(&mut self, rhs: $name) {
                self.0 &= rhs.0;
            }
        }

        impl ::std::ops::BitXor for $name {
            type Output = $name;

            #[inline]
            fn bitxor(self, rhs: $name) -> $name {
                $name(self.0 ^ rhs.0)
            }
        }

        impl ::std::ops::BitXorAssign for $name {
            #[inline]
            fn bitxor_assign(&mut self, rhs: $name) {
                self.0 ^= rhs.0;
            }
        }

        impl ::std::ops::Not for $name {
            type Output = $name;

            #[inline]
            fn not(self) -> $name {
                self ^ $name::all()
            }
        }

        impl ::std::ops::Sub for $name {
            type Output = $name;

            #[inline]
            fn sub(mut self, rhs: $name) -> $name {
                self.remove(rhs);
                self
            }
        }

        impl ::std::ops::SubAssign for $name {
            #[inline]
            fn sub_assign(&mut self, rhs: $name) {
                self.remove(rhs);
            }
        }

        impl<'a> PartialEq<&'a $name> for $name {
            #[inline]
            fn eq(&self, rhs: &&$name) -> bool { *self == **rhs }
            #[inline]
            fn ne(&self, rhs: &&$name) -> bool { *self != **rhs }
        }

        impl<'a> PartialEq<$name> for &'a $name {
            #[inline]
            fn eq(&self, rhs: &$name) -> bool { **self == *rhs }
            #[inline]
            fn ne(&self, rhs: &$name) -> bool { **self != *rhs }
        }
    }
}