├── enumflags ├── tests │ └── bitflag_test.rs ├── Cargo.toml ├── LICENSE-MIT ├── src │ └── lib.rs └── LICENSE-APACHE ├── .gitignore ├── README.md ├── Cargo.toml ├── test_suite ├── Cargo.toml └── tests │ └── bitflag_tests.rs ├── example ├── Cargo.toml └── src │ └── main.rs └── enumflags_derive ├── Cargo.toml └── src └── lib.rs /enumflags/tests/bitflag_test.rs: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | Cargo.lock 3 | *~ 4 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Closed 2 | 3 | ## You can find an active fork here: [enumflags2](https://github.com/NieDzejkob/enumflags2). 4 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [workspace] 2 | members = [ 3 | "enumflags", 4 | "enumflags_derive", 5 | "example", 6 | "test_suite", 7 | ] -------------------------------------------------------------------------------- /test_suite/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "bitflags-test-suite" 3 | version = "0.0.0" 4 | publish = false 5 | 6 | [dev-dependencies] 7 | 8 | enumflags = {path = "../enumflags"} 9 | enumflags_derive = {path = "../enumflags_derive"} 10 | -------------------------------------------------------------------------------- /example/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "example" 3 | version = "0.1.0" 4 | authors = ["maik klein "] 5 | 6 | [dependencies] 7 | 8 | enumflags = {path = "../enumflags"} 9 | enumflags_derive = {path = "../enumflags_derive"} 10 | -------------------------------------------------------------------------------- /enumflags/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "enumflags" 3 | version = "0.4.2" 4 | authors = ["maik klein "] 5 | description = "Bitflags" 6 | license = "MIT" 7 | repository = "https://github.com/MaikKlein/enumflags" 8 | readme = "../README.md" 9 | keywords = ["enum", "bitflag", "flag", "bitflags"] 10 | documentation = "https://docs.rs/enumflags" 11 | 12 | [features] 13 | default = [] 14 | nostd = [] 15 | -------------------------------------------------------------------------------- /enumflags_derive/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "enumflags_derive" 3 | version = "0.4.1" 4 | authors = ["maik klein "] 5 | description = "Bitflags" 6 | license = "MIT" 7 | repository = "https://github.com/MaikKlein/enumflags" 8 | keywords = ["enum", "bitflag", "flag", "bitflags"] 9 | 10 | [dependencies] 11 | syn = {version = "0.12.5", features = ["extra-traits"]} 12 | quote = "0.4" 13 | proc-macro2 = "0.2" 14 | 15 | [lib] 16 | proc-macro = true 17 | 18 | [features] 19 | default = [] 20 | nostd = [] 21 | -------------------------------------------------------------------------------- /enumflags/LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2017 Maik Klein 2 | 3 | Permission is hereby granted, free of charge, to any 4 | person obtaining a copy of this software and associated 5 | documentation files (the "Software"), to deal in the 6 | Software without restriction, including without 7 | limitation the rights to use, copy, modify, merge, 8 | publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software 10 | is furnished to do so, subject to the following 11 | conditions: 12 | 13 | The above copyright notice and this permission notice 14 | shall be included in all copies or substantial portions 15 | of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 18 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 19 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 21 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 22 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 23 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 24 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 25 | DEALINGS IN THE SOFTWARE. 26 | -------------------------------------------------------------------------------- /example/src/main.rs: -------------------------------------------------------------------------------- 1 | extern crate enumflags; 2 | #[macro_use] 3 | extern crate enumflags_derive; 4 | use enumflags::*; 5 | #[derive(EnumFlags, Copy, Clone)] 6 | #[repr(u8)] 7 | pub enum Test { 8 | A = 0b0001, 9 | B = 0b0010, 10 | C = 0b0100, 11 | D = 0b1000, 12 | } 13 | 14 | fn print_test>>(bitflag: B) { 15 | println!("{:?}", bitflag.into()); 16 | } 17 | 18 | fn main() { 19 | // BitFlags { 0b1111, Flags::[A, B, C, D] } 20 | print_test(BitFlags::::all()); 21 | 22 | // BitFlags { 0b1111, Flags::[A, B, C, D] } 23 | print_test(BitFlags::all()); 24 | 25 | // BitFlags { 0b0, Flags::[] } 26 | print_test(BitFlags::empty()); 27 | 28 | // BitFlags { 0b101, Flags::[A, C] } 29 | print_test(BitFlags::from_bits_truncate(5)); 30 | 31 | // BitFlags { 0b100, Flags::[C] } 32 | print_test(BitFlags::from_bits_truncate(4)); 33 | 34 | // BitFlags { 0b0, Flags::[] } 35 | print_test(BitFlags::from_bits(16).unwrap_or(BitFlags::empty())); 36 | 37 | // BitFlags { 0b100, Flags::[C] } 38 | print_test(BitFlags::from_bits(4).unwrap()); 39 | 40 | // BitFlags { 0b11111110, Flags::[B, C, D] } 41 | print_test(!Test::A); 42 | 43 | // BitFlags { 0b11, Flags::[A, B] } 44 | let flag1 = Test::A | Test::B; 45 | //println!("Flags {:?}", Test::from_bitflag(flag1)); 46 | print_test(flag1); 47 | 48 | // BitFlags { 0b1100, Flags::[C, D] } 49 | let flag2 = Test::C | Test::D; 50 | print_test(flag2); 51 | 52 | // BitFlags { 0b1001, Flags::[A, D] } 53 | let flag3 = Test::A | Test::D; 54 | print_test(flag3); 55 | 56 | // BitFlags { 0b0, Flags::[] } 57 | print_test(flag1 & flag2); 58 | 59 | // BitFlags { 0b1111, Flags::[A, B, C, D] } 60 | print_test(flag1 | flag2); 61 | 62 | // false 63 | println!("{}", flag1.intersects(flag2)); 64 | 65 | // true 66 | println!("{}", flag1.intersects(flag3)); 67 | 68 | // true 69 | println!("{}", flag1.contains(Test::A | Test::B)); 70 | 71 | // false 72 | println!("{}", flag1.contains(Test::A | Test::B | Test::C)); 73 | 74 | // true 75 | println!("{}", flag1.contains(Test::A)); 76 | } 77 | -------------------------------------------------------------------------------- /test_suite/tests/bitflag_tests.rs: -------------------------------------------------------------------------------- 1 | extern crate enumflags; 2 | #[macro_use] 3 | extern crate enumflags_derive; 4 | 5 | #[derive(EnumFlags, Copy, Clone, Debug)] 6 | #[repr(u8)] 7 | enum Test { 8 | A = 1 << 0, 9 | B = 1 << 1, 10 | C = 1 << 2, 11 | D = 1 << 3, 12 | } 13 | #[derive(EnumFlags, Copy, Clone, Debug)] 14 | #[repr(u8)] 15 | enum Test1 { 16 | A = 1 << 0, 17 | B = 1 << 1, 18 | C = 1 << 2, 19 | D = 1 << 3, 20 | } 21 | 22 | #[test] 23 | fn module() { 24 | mod some_modules { 25 | #[derive(EnumFlags, Copy, Clone, Debug)] 26 | #[repr(u8)] 27 | enum Test2 { 28 | A = 1 << 0, 29 | B = 1 << 1, 30 | C = 1 << 2, 31 | D = 1 << 3, 32 | } 33 | } 34 | } 35 | #[test] 36 | fn test_foo() { 37 | use enumflags::BitFlags; 38 | assert_eq!( 39 | BitFlags::::all(), 40 | Test::A | Test::B | Test::C | Test::D 41 | ); 42 | assert_eq!(BitFlags::::all() & Test::A, Test::A); 43 | assert_eq!(!Test::A, Test::B | Test::C | Test::D); 44 | assert_eq!((Test::A | Test::C) ^ (Test::C | Test::B), Test::A | Test::B); 45 | assert_eq!(BitFlags::::from_bits_truncate(4), Test::C); 46 | assert_eq!(BitFlags::::from_bits_truncate(5), Test::A | Test::C); 47 | assert_eq!( 48 | BitFlags::::from_bits_truncate(16), 49 | BitFlags::::empty() 50 | ); 51 | assert_eq!(BitFlags::::from_bits_truncate(17), Test::A); 52 | assert_eq!(BitFlags::::from_bits(17), None); 53 | assert_eq!( 54 | BitFlags::::from_bits(15), 55 | Some(BitFlags::::all()) 56 | ); 57 | { 58 | let mut b = Test::A | Test::B; 59 | b.insert(Test::C); 60 | assert_eq!(b, Test::A | Test::B | Test::C); 61 | } 62 | assert!((Test::A | Test::B).intersects(Test::B)); 63 | assert!(!(Test::A | Test::B).intersects(Test::C)); 64 | assert!((Test::A | Test::B | Test::C).contains(Test::A | Test::B)); 65 | assert!(!(Test::A | Test::B | Test::C).contains(Test::A | Test::D)); 66 | assert_eq!(!(Test::A | Test::B), Test::C | Test::D); 67 | assert_eq!((Test::A | Test::B).bits(), 3); 68 | assert_eq!((Test::A | Test::B).not().bits(), 12); 69 | assert_eq!(BitFlags::::all().bits(), 15); 70 | { 71 | let mut b = Test::A | Test::B | Test::C; 72 | b.remove(Test::B); 73 | assert_eq!(b, Test::A | Test::C); 74 | } 75 | assert_eq!((Test::A ^ Test::B), Test::A | Test::B); 76 | } 77 | 78 | #[test] 79 | fn assign_ops() { 80 | let mut x = Test::A | Test::B; 81 | x |= Test::C; 82 | assert_eq!(x, Test::A | Test::B | Test::C); 83 | 84 | let mut x = Test::A | Test::B; 85 | x &= Test::B | Test::C; 86 | assert_eq!(x, Test::B); 87 | 88 | let mut x = Test::A | Test::B; 89 | x ^= Test::B | Test::C; 90 | assert_eq!(x, Test::A | Test::C); 91 | } 92 | -------------------------------------------------------------------------------- /enumflags/src/lib.rs: -------------------------------------------------------------------------------- 1 | #![no_std] 2 | #[cfg(not(feature = "nostd"))] 3 | extern crate std; 4 | #[cfg(feature = "nostd")] 5 | extern crate core as std; 6 | 7 | use std::ops::{BitAnd, BitOr, BitXor, Not}; 8 | use std::cmp::PartialOrd; 9 | use std::fmt::{self, Formatter}; 10 | use std::iter::FromIterator; 11 | 12 | pub trait BitFlagNum 13 | : Default 14 | + BitOr 15 | + BitAnd 16 | + BitXor 17 | + Not 18 | + PartialOrd 19 | + Copy 20 | + Clone { 21 | } 22 | 23 | impl BitFlagNum for u8 {} 24 | impl BitFlagNum for u16 {} 25 | impl BitFlagNum for u32 {} 26 | impl BitFlagNum for u64 {} 27 | impl BitFlagNum for usize {} 28 | 29 | pub trait BitFlagsFmt 30 | where 31 | Self: RawBitFlags, 32 | { 33 | fn fmt(flags: BitFlags, f: &mut Formatter) -> fmt::Result; 34 | } 35 | 36 | pub trait RawBitFlags: Copy + Clone { 37 | type Type: BitFlagNum; 38 | fn all() -> Self::Type; 39 | fn bits(self) -> Self::Type; 40 | } 41 | 42 | #[derive(Copy, Clone)] 43 | pub struct BitFlags { 44 | val: T::Type, 45 | } 46 | 47 | impl ::std::fmt::Debug for BitFlags 48 | where 49 | T: RawBitFlags + BitFlagsFmt, 50 | { 51 | fn fmt(&self, fmt: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { 52 | T::fmt(self.clone(), fmt) 53 | } 54 | } 55 | 56 | impl BitFlags 57 | where 58 | T: RawBitFlags, 59 | { 60 | /// Create a new BitFlags unsafely. Consider using `from_bits` or `from_bits_truncate`. 61 | pub unsafe fn new(val: T::Type) -> Self { 62 | BitFlags { val } 63 | } 64 | } 65 | 66 | impl From for BitFlags { 67 | fn from(t: T) -> BitFlags { 68 | BitFlags { val: t.bits() } 69 | } 70 | } 71 | 72 | impl BitFlags 73 | where 74 | T: RawBitFlags, 75 | { 76 | /// Create an empty BitFlags. Empty means `0`. 77 | pub fn empty() -> Self { 78 | unsafe { BitFlags::new(T::Type::default()) } 79 | } 80 | 81 | /// Sets all flags. 82 | pub fn all() -> Self { 83 | unsafe { BitFlags::new(T::all()) } 84 | } 85 | 86 | /// Returns true if all flags are set 87 | pub fn is_all(self) -> bool { 88 | self.val == T::all() 89 | } 90 | 91 | /// Returns true if no flag is set 92 | pub fn is_empty(self) -> bool { 93 | self.val == Self::empty().bits() 94 | } 95 | 96 | /// Returns the underlying type value 97 | pub fn bits(self) -> T::Type { 98 | self.val 99 | } 100 | 101 | /// Returns true if at least one flag is shared. 102 | pub fn intersects>>(self, other: B) -> bool { 103 | (self.bits() & other.into().bits()) > Self::empty().bits() 104 | } 105 | 106 | /// Returns true iff all flags are contained. 107 | pub fn contains>>(self, other: B) -> bool { 108 | let other = other.into(); 109 | (self.bits() & other.bits()) == other.bits() 110 | } 111 | 112 | /// Flips all flags 113 | pub fn not(self) -> Self { 114 | unsafe { BitFlags::new(!self.bits() & T::all()) } 115 | } 116 | 117 | /// Returns a BitFlags iff the bits value does not contain any illegal flags. 118 | pub fn from_bits(bits: T::Type) -> Option { 119 | if bits & !Self::all().bits() == Self::empty().bits() { 120 | unsafe { Some(BitFlags::new(bits)) } 121 | } else { 122 | None 123 | } 124 | } 125 | 126 | /// Truncates flags that are illegal 127 | pub fn from_bits_truncate(bits: T::Type) -> Self { 128 | unsafe { BitFlags::new(bits & T::all()) } 129 | } 130 | 131 | /// Toggles the matching bits 132 | pub fn toggle>>(&mut self, other: B) { 133 | *self = *self ^ other.into(); 134 | } 135 | 136 | /// Inserts the flags into the BitFlag 137 | pub fn insert>>(&mut self, other: B) { 138 | *self = *self | other.into(); 139 | } 140 | 141 | /// Removes the matching flags 142 | pub fn remove>>(&mut self, other: B) { 143 | *self = *self & !other.into(); 144 | } 145 | } 146 | 147 | impl std::cmp::PartialEq for BitFlags 148 | where 149 | T: RawBitFlags, 150 | B: Into> + Copy, 151 | { 152 | fn eq(&self, other: &B) -> bool { 153 | self.bits() == Into::::into(*other).bits() 154 | } 155 | } 156 | 157 | impl std::ops::BitOr for BitFlags 158 | where 159 | T: RawBitFlags, 160 | B: Into>, 161 | { 162 | type Output = BitFlags; 163 | fn bitor(self, other: B) -> BitFlags { 164 | unsafe { BitFlags::new(self.bits() | other.into().bits()) } 165 | } 166 | } 167 | 168 | impl std::ops::BitAnd for BitFlags 169 | where 170 | T: RawBitFlags, 171 | B: Into>, 172 | { 173 | type Output = BitFlags; 174 | fn bitand(self, other: B) -> BitFlags { 175 | unsafe { BitFlags::new(self.bits() & other.into().bits()) } 176 | } 177 | } 178 | 179 | impl std::ops::BitXor for BitFlags 180 | where 181 | T: RawBitFlags, 182 | B: Into>, 183 | { 184 | type Output = BitFlags; 185 | fn bitxor(self, other: B) -> BitFlags { 186 | unsafe { BitFlags::new((self.bits() ^ other.into().bits()) & T::all()) } 187 | } 188 | } 189 | 190 | impl std::ops::BitOrAssign for BitFlags 191 | where 192 | T: RawBitFlags, 193 | B: Into>, 194 | { 195 | fn bitor_assign(&mut self, other: B) { 196 | *self = *self | other; 197 | } 198 | } 199 | 200 | impl std::ops::BitAndAssign for BitFlags 201 | where 202 | T: RawBitFlags, 203 | B: Into>, 204 | { 205 | fn bitand_assign(&mut self, other: B) { 206 | *self = *self & other; 207 | } 208 | } 209 | impl std::ops::BitXorAssign for BitFlags 210 | where 211 | T: RawBitFlags, 212 | B: Into>, 213 | { 214 | fn bitxor_assign(&mut self, other: B) { 215 | *self = *self ^ other; 216 | } 217 | } 218 | 219 | impl std::ops::Not for BitFlags 220 | where 221 | T: RawBitFlags, 222 | { 223 | type Output = BitFlags; 224 | fn not(self) -> BitFlags { 225 | self.not() 226 | } 227 | } 228 | 229 | impl FromIterator for BitFlags 230 | where 231 | T: RawBitFlags, 232 | B: Into> 233 | { 234 | fn from_iter(it: I) -> BitFlags 235 | where 236 | I: IntoIterator 237 | { 238 | let mut flags = BitFlags::empty(); 239 | for flag in it { 240 | flags |= flag.into(); 241 | } 242 | flags 243 | } 244 | } 245 | -------------------------------------------------------------------------------- /enumflags/LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | 3 | Version 2.0, January 2004 4 | 5 | http://www.apache.org/licenses/ 6 | 7 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 8 | 9 | 1. Definitions. 10 | 11 | "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. 16 | 17 | "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. 18 | 19 | "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. 20 | 21 | "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. 22 | 23 | "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). 24 | 25 | "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. 26 | 27 | "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." 28 | 29 | "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 30 | 31 | 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 32 | 33 | 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 34 | 35 | 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: 36 | 37 | You must give any other recipients of the Work or Derivative Works a copy of this License; and 38 | You must cause any modified files to carry prominent notices stating that You changed the files; and 39 | You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and 40 | If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. 41 | 42 | You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 43 | 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 44 | 45 | 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 46 | 47 | 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 48 | 49 | 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 50 | 51 | 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. 52 | 53 | END OF TERMS AND CONDITIONS 54 | 55 | 56 | Copyright [2017] [Maik Klein] 57 | 58 | Licensed under the Apache License, Version 2.0 (the "License"); 59 | you may not use this file except in compliance with the License. 60 | You may obtain a copy of the License at 61 | 62 | http://www.apache.org/licenses/LICENSE-2.0 63 | 64 | Unless required by applicable law or agreed to in writing, software 65 | distributed under the License is distributed on an "AS IS" BASIS, 66 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 67 | See the License for the specific language governing permissions and 68 | limitations under the License. 69 | -------------------------------------------------------------------------------- /enumflags_derive/src/lib.rs: -------------------------------------------------------------------------------- 1 | #![recursion_limit = "2048"] 2 | extern crate proc_macro; 3 | #[macro_use] 4 | extern crate quote; 5 | extern crate proc_macro2; 6 | extern crate syn; 7 | use proc_macro::TokenStream; 8 | use proc_macro2::Span; 9 | use quote::Tokens; 10 | use std::convert::From; 11 | use syn::{Data, DataEnum, DeriveInput, Ident}; 12 | 13 | #[proc_macro_derive(EnumFlags, attributes(EnumFlags))] 14 | pub fn derive_enum_flags(input: TokenStream) -> TokenStream { 15 | let ast: DeriveInput = syn::parse(input).unwrap(); 16 | 17 | #[cfg(not(feature = "nostd"))] 18 | let gen_std = true; 19 | #[cfg(feature = "nostd")] 20 | let gen_std = false; 21 | let quote_tokens = match ast.data { 22 | Data::Enum(ref data) => gen_enumflags(&ast.ident, &ast, data, gen_std), 23 | _ => panic!("`derive(EnumFlags)` may only be applied to enums"), 24 | }; 25 | quote_tokens.into() 26 | } 27 | 28 | fn max_value_of(ty: &str) -> Option { 29 | match ty { 30 | "u8" => Some(u8::max_value() as usize), 31 | "u16" => Some(u16::max_value() as usize), 32 | "u32" => Some(u32::max_value() as usize), 33 | "u64" => Some(u64::max_value() as usize), 34 | "usize" => Some(usize::max_value()), 35 | _ => None, 36 | } 37 | } 38 | 39 | fn fold_expr(expr: &syn::Expr) -> u64 { 40 | use syn::Expr; 41 | match expr { 42 | &Expr::Lit(ref expr_lit) => match expr_lit.lit { 43 | syn::Lit::Int(ref lit_int) => lit_int.value(), 44 | _ => panic!("Only Int literals are supported"), 45 | }, 46 | &Expr::Binary(ref expr_binary) => { 47 | let l = fold_expr(&expr_binary.left); 48 | let r = fold_expr(&expr_binary.right); 49 | match expr_binary.op { 50 | syn::BinOp::Shl(_) => l << r, 51 | op => panic!("{:?} not supported", op), 52 | } 53 | } 54 | _ => panic!("Only literals are supported"), 55 | } 56 | } 57 | 58 | fn extract_repr(attrs: &[syn::Attribute]) -> Option { 59 | attrs 60 | .iter() 61 | .filter_map(|a| { 62 | if let syn::Meta::List(ref meta) = a.interpret_meta().expect("Metalist") { 63 | if meta.ident.as_ref() == "repr" { 64 | return meta 65 | .nested 66 | .iter() 67 | .filter_map(|mi| { 68 | if let &syn::NestedMeta::Meta(syn::Meta::Word(ref ident)) = mi { 69 | return Some(ident.clone()); 70 | } 71 | None 72 | }) 73 | .nth(0); 74 | } 75 | } 76 | None 77 | }) 78 | .nth(0) 79 | } 80 | fn gen_enumflags(ident: &Ident, item: &DeriveInput, data: &DataEnum, gen_std: bool) -> Tokens { 81 | let span = Span::call_site(); 82 | let variants: Vec<_> = data.variants.iter().map(|v| v.ident.clone()).collect(); 83 | let variants_ref = &variants; 84 | let flag_values: Vec<_> = data 85 | .variants 86 | .iter() 87 | .map(|v| { 88 | v.discriminant 89 | .as_ref() 90 | .map(|d| fold_expr(&d.1)) 91 | .expect("No discriminant") 92 | }) 93 | .collect(); 94 | assert!( 95 | flag_values.iter().find(|&&v| v == 0).is_none(), 96 | "Null flag is not allowed" 97 | ); 98 | let flag_values_ref1 = &flag_values; 99 | let flag_value_names: &Vec<_> = &flag_values 100 | .iter() 101 | .map(|val| syn::Index::from(*val as usize)) 102 | .collect(); 103 | let names: Vec<_> = flag_values.iter().map(|_| ident.clone()).collect(); 104 | let names_ref = &names; 105 | assert!( 106 | variants.len() == flag_values.len(), 107 | "At least one variant was not initialized explicity with a value." 108 | ); 109 | let ty = extract_repr(&item.attrs).unwrap_or(Ident::new("usize", span)); 110 | let max_flag_value = flag_values.iter().max().unwrap(); 111 | let max_allowed_value = max_value_of(ty.as_ref()).expect(&format!("{} is not supported", ty)); 112 | assert!( 113 | *max_flag_value as usize <= max_allowed_value, 114 | "Value '0b{val:b}' is too big for an {ty}", 115 | val = max_flag_value, 116 | ty = ty 117 | ); 118 | let wrong_flag_values: &Vec<_> = &flag_values 119 | .iter() 120 | .enumerate() 121 | .map(|(i, &val)| { 122 | ( 123 | i, 124 | flag_values 125 | .iter() 126 | .enumerate() 127 | .fold(0u32, |acc, (other_i, &other_val)| { 128 | if other_i == i || other_val > 0 && other_val & val == 0 { 129 | acc 130 | } else { 131 | acc + 1 132 | } 133 | }), 134 | ) 135 | }) 136 | .filter(|&(_, count)| count > 0) 137 | .map(|(index, _)| { 138 | format!( 139 | "{name}::{variant} = 0b{value:b}", 140 | name = ident, 141 | variant = variants_ref[index], 142 | value = flag_values[index] 143 | ) 144 | }) 145 | .collect(); 146 | assert!( 147 | wrong_flag_values.is_empty(), 148 | "The following flags are not unique: {data:?}", 149 | data = wrong_flag_values 150 | ); 151 | #[cfg(not(feature = "nostd"))] 152 | let std_path = Ident::new("std", span); 153 | #[cfg(feature = "nostd")] 154 | let std_path = Ident::new("core", span); 155 | let std: quote::Tokens = if gen_std { 156 | quote_spanned! { 157 | span => 158 | impl #ident{ 159 | #[allow(dead_code)] 160 | pub fn from_bitflag(bitflag: ::enumflags::BitFlags<#ident>) -> Vec<#ident> { 161 | [#(#flag_values_ref1,)*].iter().filter_map(|val|{ 162 | let val = *val as #ty & bitflag.bits(); 163 | match val { 164 | #(#flag_value_names => Some(#names_ref :: #variants_ref),)* 165 | _ => None 166 | } 167 | }).collect() 168 | } 169 | } 170 | } 171 | } else { 172 | quote! {} 173 | }; 174 | let scope_ident = Ident::new( 175 | &format!("__scope_enumderive_{}", item.ident.as_ref().to_lowercase()), 176 | span, 177 | ); 178 | quote_spanned! { 179 | span => 180 | mod #scope_ident { 181 | extern crate #std_path; 182 | 183 | // We're inside a new module named '#scope_ident', 184 | // so we need to import the original type definition 185 | // from the parent 186 | use super::#ident; 187 | 188 | impl #std_path::ops::Not for #ident{ 189 | type Output = ::enumflags::BitFlags<#ident>; 190 | fn not(self) -> Self::Output { 191 | use ::enumflags::{BitFlags, RawBitFlags}; 192 | unsafe { BitFlags::new(self.bits()).not() } 193 | } 194 | } 195 | 196 | impl #std_path::ops::BitOr for #ident{ 197 | type Output = ::enumflags::BitFlags<#ident>; 198 | fn bitor(self, other: Self) -> Self::Output { 199 | use ::enumflags::{BitFlags, RawBitFlags}; 200 | unsafe { BitFlags::new(self.bits() | other.bits())} 201 | } 202 | } 203 | 204 | impl #std_path::ops::BitAnd for #ident{ 205 | type Output = ::enumflags::BitFlags<#ident>; 206 | fn bitand(self, other: Self) -> Self::Output { 207 | use ::enumflags::{BitFlags, RawBitFlags}; 208 | unsafe { BitFlags::new(self.bits() & other.bits())} 209 | } 210 | } 211 | 212 | impl #std_path::ops::BitXor for #ident{ 213 | type Output = ::enumflags::BitFlags<#ident>; 214 | fn bitxor(self, other: Self) -> Self::Output { 215 | Into::::into(self) ^ Into::::into(other) 216 | } 217 | } 218 | 219 | impl ::enumflags::BitFlagsFmt for #ident { 220 | fn fmt(flags: ::enumflags::BitFlags<#ident>, 221 | fmt: &mut #std_path::fmt::Formatter) 222 | -> #std_path::fmt::Result { 223 | use ::enumflags::RawBitFlags; 224 | let v:Vec<&str> = 225 | [#((#names_ref :: #variants_ref).bits(),)*] 226 | .iter() 227 | .filter_map(|val|{ 228 | let val: #ty = *val as #ty & flags.bits(); 229 | match val { 230 | #(#flag_value_names => Some(stringify!(#variants_ref)),)* 231 | _ => None 232 | } 233 | }) 234 | .collect(); 235 | write!(fmt, "BitFlags<{}>(0b{:b}, [{}]) ", 236 | stringify!(#ident), 237 | flags.bits(), 238 | v.join(", ")) 239 | } 240 | } 241 | 242 | impl ::enumflags::RawBitFlags for #ident { 243 | type Type = #ty; 244 | 245 | fn all() -> Self::Type { 246 | (#(#flag_values_ref1)|*) as #ty 247 | } 248 | 249 | fn bits(self) -> Self::Type { 250 | self as #ty 251 | } 252 | } 253 | 254 | #std 255 | } 256 | } 257 | } 258 | --------------------------------------------------------------------------------