├── .gitignore ├── README.md ├── .travis.yml ├── Cargo.toml ├── deploy-docs.sh ├── LICENSE-MIT ├── LICENSE-APACHE └── src └── lib.rs /.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | A structure for holding a set of enum variants. 2 | 3 | Documentation is available at https://contain-rs.github.io/enum-set/enum_set. 4 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: rust 2 | sudo: false 3 | script: 4 | - cargo build 5 | - cargo test 6 | - cargo doc --no-deps 7 | after_success: | 8 | [ $TRAVIS_BRANCH = master ] && 9 | [ $TRAVIS_PULL_REQUEST = false ] && 10 | bash deploy-docs.sh 11 | notifications: 12 | webhooks: http://huon.me:54857/travis 13 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | 3 | name = "enum-set" 4 | version = "0.0.7" 5 | license = "MIT/Apache-2.0" 6 | description = "A structure for holding a set of enum variants" 7 | authors = [ 8 | "Stepan Koltsov ", 9 | ] 10 | 11 | repository = "https://github.com/contain-rs/enum-set" 12 | homepage = "https://github.com/contain-rs/enum-set" 13 | documentation = "https://contain-rs.github.io/enum-set/enum_set" 14 | keywords = ["data-structures"] 15 | readme = "README.md" 16 | -------------------------------------------------------------------------------- /deploy-docs.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -o errexit -o nounset 4 | 5 | rev=$(git rev-parse --short HEAD) 6 | 7 | cd target/doc 8 | 9 | git init 10 | git config user.email 'FlashCat@users.noreply.github.com' 11 | git config user.name 'FlashCat' 12 | git remote add upstream "https://${GH_TOKEN}@github.com/${TRAVIS_REPO_SLUG}.git" 13 | git fetch upstream gh-pages 14 | git reset upstream/gh-pages 15 | 16 | touch . 17 | 18 | git add -A . 19 | git commit -m "rebuild pages at ${rev}" 20 | git push -q upstream HEAD:gh-pages 21 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2015 The Rust Project Developers 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 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2012 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 or the MIT license 7 | // , at your 8 | // option. This file may not be copied, modified, or distributed 9 | // except according to those terms. 10 | 11 | //! A structure for holding a set of enum variants. 12 | //! 13 | //! This module defines a container which uses an efficient bit mask 14 | //! representation to hold C-like enum variants. 15 | 16 | use std::fmt; 17 | use std::hash; 18 | use std::marker::PhantomData; 19 | use std::iter; 20 | use std::ops; 21 | 22 | #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord)] 23 | /// A specialized set implementation to use enum types. 24 | pub struct EnumSet { 25 | // We must maintain the invariant that no bits are set 26 | // for which no variant exists 27 | bits: u32, 28 | phantom: PhantomData, 29 | } 30 | 31 | impl fmt::Debug for EnumSet { 32 | fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { 33 | fmt.debug_set().entries(self).finish() 34 | } 35 | } 36 | 37 | impl hash::Hash for EnumSet { 38 | fn hash(&self, state: &mut H) { 39 | self.bits.hash(state); 40 | } 41 | } 42 | 43 | /// An interface for casting C-like enum to `u32` and back. 44 | /// 45 | /// The returned value must be no more than 31: `EnumSet` does not support more cases than this. 46 | /// 47 | /// A typical implementation can be seen below: 48 | /// 49 | /// ``` 50 | /// use enum_set::CLike; 51 | /// use std::mem; 52 | /// 53 | /// #[derive(Clone, Copy)] 54 | /// #[repr(u32)] 55 | /// enum Foo { 56 | /// A, B, C 57 | /// } 58 | /// 59 | /// impl CLike for Foo { 60 | /// fn to_u32(&self) -> u32 { 61 | /// *self as u32 62 | /// } 63 | /// 64 | /// unsafe fn from_u32(v: u32) -> Foo { 65 | /// mem::transmute(v) 66 | /// } 67 | /// } 68 | /// ``` 69 | pub trait CLike { 70 | /// Converts a C-like enum to a `u32`. The value must be `<= 31`. 71 | fn to_u32(&self) -> u32; 72 | 73 | /// Converts a `u32` to a C-like enum. This method only needs to be safe 74 | /// for possible return values of `to_u32` of this trait. 75 | unsafe fn from_u32(u32) -> Self; 76 | } 77 | 78 | fn bit(e: &E) -> u32 { 79 | let value = e.to_u32(); 80 | assert!(value < 32, "EnumSet only supports up to {} variants.", 31); 81 | 1 << value 82 | } 83 | 84 | impl EnumSet { 85 | /// Returns an empty `EnumSet`. 86 | pub fn new() -> Self { 87 | Self::new_with_bits(0) 88 | } 89 | 90 | fn new_with_bits(bits: u32) -> Self { 91 | EnumSet { bits: bits, phantom: PhantomData } 92 | } 93 | 94 | /// Returns the number of elements in the set. 95 | pub fn len(&self) -> usize { 96 | self.bits.count_ones() as usize 97 | } 98 | 99 | /// Checks if the set is empty. 100 | pub fn is_empty(&self) -> bool { 101 | self.bits == 0 102 | } 103 | 104 | /// Removes all elements from the set. 105 | pub fn clear(&mut self) { 106 | self.bits = 0; 107 | } 108 | 109 | /// Returns `true` if the set has no elements in common with `other`. 110 | /// 111 | /// This is equivalent to checking for an empty intersection. 112 | pub fn is_disjoint(&self, other: &Self) -> bool { 113 | (self.bits & other.bits) == 0 114 | } 115 | 116 | /// Returns `true` if the set is a superset of `other`. 117 | pub fn is_superset(&self, other: &Self) -> bool { 118 | (self.bits & other.bits) == other.bits 119 | } 120 | 121 | /// Returns `true` if the set is a subset of `other`. 122 | pub fn is_subset(&self, other: &Self) -> bool { 123 | other.is_superset(self) 124 | } 125 | 126 | /// Returns the union of the set and `other`. 127 | pub fn union(&self, other: Self) -> Self { 128 | Self::new_with_bits(self.bits | other.bits) 129 | } 130 | 131 | /// Returns the intersection of the set and `other`. 132 | pub fn intersection(&self, other: Self) -> Self { 133 | Self::new_with_bits(self.bits & other.bits) 134 | } 135 | 136 | /// Returns the difference between the set and `other`. 137 | pub fn difference(&self, other: Self) -> Self { 138 | Self::new_with_bits(self.bits & !other.bits) 139 | } 140 | 141 | /// Returns the symmetric difference between the set and `other`. 142 | pub fn symmetric_difference(&self, other: Self) -> Self { 143 | Self::new_with_bits(self.bits ^ other.bits) 144 | } 145 | 146 | /// Adds the given value to the set. 147 | /// 148 | /// Returns `true` if the value was not already present in the set. 149 | pub fn insert(&mut self, value: E) -> bool { 150 | let result = !self.contains(&value); 151 | self.bits |= bit(&value); 152 | result 153 | } 154 | 155 | /// Removes a value from the set. 156 | /// 157 | /// Returns `true` if the value was present in the set. 158 | pub fn remove(&mut self, value: &E) -> bool { 159 | let result = self.contains(value); 160 | self.bits &= !bit(value); 161 | result 162 | } 163 | 164 | /// Returns `true` if the set contains the given value. 165 | pub fn contains(&self, value: &E) -> bool { 166 | (self.bits & bit(value)) != 0 167 | } 168 | 169 | /// Returns an iterator over the set's elements. 170 | pub fn iter(&self) -> Iter { 171 | Iter { index: 0, bits: self.bits, phantom: PhantomData } 172 | } 173 | } 174 | 175 | impl ops::Sub for EnumSet { 176 | type Output = Self; 177 | 178 | fn sub(self, other: Self) -> Self { 179 | self.difference(other) 180 | } 181 | } 182 | 183 | impl ops::BitOr for EnumSet { 184 | type Output = Self; 185 | 186 | fn bitor(self, other: Self) -> Self { 187 | self.union(other) 188 | } 189 | } 190 | 191 | impl ops::BitAnd for EnumSet { 192 | type Output = Self; 193 | 194 | fn bitand(self, other: Self) -> Self { 195 | self.intersection(other) 196 | } 197 | } 198 | 199 | impl ops::BitXor for EnumSet { 200 | type Output = Self; 201 | 202 | fn bitxor(self, other: Self) -> Self { 203 | self.symmetric_difference(other) 204 | } 205 | } 206 | 207 | impl ops::SubAssign for EnumSet { 208 | fn sub_assign(&mut self, other: Self) { 209 | self.bits &= !other.bits; 210 | } 211 | } 212 | 213 | impl ops::BitOrAssign for EnumSet { 214 | fn bitor_assign(&mut self, other: Self) { 215 | self.bits |= other.bits; 216 | } 217 | } 218 | 219 | impl ops::BitAndAssign for EnumSet { 220 | fn bitand_assign(&mut self, other: Self) { 221 | self.bits &= other.bits; 222 | } 223 | } 224 | 225 | impl ops::BitXorAssign for EnumSet { 226 | fn bitxor_assign(&mut self, other: Self) { 227 | self.bits ^= other.bits; 228 | } 229 | } 230 | 231 | #[derive(Clone)] 232 | /// An iterator over an `EnumSet`. 233 | pub struct Iter { 234 | index: u32, 235 | bits: u32, 236 | phantom: PhantomData<*mut E>, 237 | } 238 | 239 | impl Iterator for Iter { 240 | type Item = E; 241 | 242 | fn next(&mut self) -> Option { 243 | if self.bits == 0 { 244 | return None; 245 | } 246 | 247 | while (self.bits & 1) == 0 { 248 | self.index += 1; 249 | self.bits >>= 1; 250 | } 251 | 252 | // Safe because of the invariant that only valid bits are set (see 253 | // comment on the `bit` member of this struct). 254 | let elem = unsafe { CLike::from_u32(self.index) }; 255 | self.index += 1; 256 | self.bits >>= 1; 257 | Some(elem) 258 | } 259 | 260 | fn size_hint(&self) -> (usize, Option) { 261 | let exact = self.bits.count_ones() as usize; 262 | (exact, Some(exact)) 263 | } 264 | } 265 | 266 | impl ExactSizeIterator for Iter {} 267 | 268 | impl Default for EnumSet { 269 | fn default() -> Self { 270 | Self::new() 271 | } 272 | } 273 | 274 | impl iter::FromIterator for EnumSet { 275 | fn from_iter>(iterator: I) -> Self { 276 | let mut ret = Self::new(); 277 | ret.extend(iterator); 278 | ret 279 | } 280 | } 281 | 282 | impl Extend for EnumSet { 283 | fn extend>(&mut self, iter: I) { 284 | for element in iter { 285 | self.insert(element); 286 | } 287 | } 288 | } 289 | 290 | impl<'a, E: CLike> IntoIterator for &'a EnumSet { 291 | type Item = E; 292 | type IntoIter = Iter; 293 | fn into_iter(self) -> Iter { self.iter() } 294 | } 295 | 296 | #[cfg(test)] 297 | mod tests { 298 | use self::Foo::*; 299 | use std::mem; 300 | 301 | use super::{EnumSet, CLike}; 302 | 303 | #[derive(Copy, Clone, PartialEq, Debug)] 304 | #[repr(u32)] 305 | enum Foo { 306 | A, B, C 307 | } 308 | 309 | impl CLike for Foo { 310 | fn to_u32(&self) -> u32 { 311 | *self as u32 312 | } 313 | 314 | unsafe fn from_u32(v: u32) -> Foo { 315 | mem::transmute(v) 316 | } 317 | } 318 | 319 | #[test] 320 | fn test_new() { 321 | let e: EnumSet = EnumSet::new(); 322 | assert!(e.is_empty()); 323 | } 324 | 325 | #[test] 326 | fn test_debug() { 327 | let mut e = EnumSet::new(); 328 | assert_eq!("{}", format!("{:?}", e)); 329 | e.insert(A); 330 | assert_eq!("{A}", format!("{:?}", e)); 331 | e.insert(C); 332 | assert_eq!("{A, C}", format!("{:?}", e)); 333 | } 334 | 335 | #[test] 336 | fn test_len() { 337 | let mut e = EnumSet::new(); 338 | assert_eq!(e.len(), 0); 339 | e.insert(A); 340 | e.insert(B); 341 | e.insert(C); 342 | assert_eq!(e.len(), 3); 343 | e.remove(&A); 344 | assert_eq!(e.len(), 2); 345 | e.clear(); 346 | assert_eq!(e.len(), 0); 347 | } 348 | 349 | /////////////////////////////////////////////////////////////////////////// 350 | // intersect 351 | 352 | #[test] 353 | fn test_two_empties_do_not_intersect() { 354 | let e1: EnumSet = EnumSet::new(); 355 | let e2: EnumSet = EnumSet::new(); 356 | assert!(e1.is_disjoint(&e2)); 357 | } 358 | 359 | #[test] 360 | fn test_empty_does_not_intersect_with_full() { 361 | let e1: EnumSet = EnumSet::new(); 362 | 363 | let mut e2: EnumSet = EnumSet::new(); 364 | e2.insert(A); 365 | e2.insert(B); 366 | e2.insert(C); 367 | 368 | assert!(e1.is_disjoint(&e2)); 369 | } 370 | 371 | #[test] 372 | fn test_disjoint_intersects() { 373 | let mut e1: EnumSet = EnumSet::new(); 374 | e1.insert(A); 375 | 376 | let mut e2: EnumSet = EnumSet::new(); 377 | e2.insert(B); 378 | 379 | assert!(e1.is_disjoint(&e2)); 380 | } 381 | 382 | #[test] 383 | fn test_overlapping_intersects() { 384 | let mut e1: EnumSet = EnumSet::new(); 385 | e1.insert(A); 386 | 387 | let mut e2: EnumSet = EnumSet::new(); 388 | e2.insert(A); 389 | e2.insert(B); 390 | 391 | assert!(!e1.is_disjoint(&e2)); 392 | } 393 | 394 | /////////////////////////////////////////////////////////////////////////// 395 | // contains and contains_elem 396 | 397 | #[test] 398 | fn test_superset() { 399 | let mut e1: EnumSet = EnumSet::new(); 400 | e1.insert(A); 401 | 402 | let mut e2: EnumSet = EnumSet::new(); 403 | e2.insert(A); 404 | e2.insert(B); 405 | 406 | let mut e3: EnumSet = EnumSet::new(); 407 | e3.insert(C); 408 | 409 | assert!(e1.is_subset(&e2)); 410 | assert!(e2.is_superset(&e1)); 411 | assert!(!e3.is_superset(&e2)); 412 | assert!(!e2.is_superset(&e3)); 413 | } 414 | 415 | #[test] 416 | fn test_contains() { 417 | let mut e1: EnumSet = EnumSet::new(); 418 | e1.insert(A); 419 | assert!(e1.contains(&A)); 420 | assert!(!e1.contains(&B)); 421 | assert!(!e1.contains(&C)); 422 | 423 | e1.insert(A); 424 | e1.insert(B); 425 | assert!(e1.contains(&A)); 426 | assert!(e1.contains(&B)); 427 | assert!(!e1.contains(&C)); 428 | } 429 | 430 | /////////////////////////////////////////////////////////////////////////// 431 | // iter 432 | 433 | #[test] 434 | fn test_iterator() { 435 | let mut e1: EnumSet = EnumSet::new(); 436 | 437 | let elems: Vec = e1.iter().collect(); 438 | assert!(elems.is_empty()); 439 | 440 | e1.insert(A); 441 | let elems: Vec<_> = e1.iter().collect(); 442 | assert_eq!(vec![A], elems); 443 | 444 | e1.insert(C); 445 | let elems: Vec<_> = e1.iter().collect(); 446 | assert_eq!(vec![A,C], elems); 447 | 448 | e1.insert(C); 449 | let elems: Vec<_> = e1.iter().collect(); 450 | assert_eq!(vec![A,C], elems); 451 | 452 | e1.insert(B); 453 | let elems: Vec<_> = e1.iter().collect(); 454 | assert_eq!(vec![A,B,C], elems); 455 | } 456 | 457 | #[test] 458 | fn test_clone_iterator() { 459 | let mut e: EnumSet = EnumSet::new(); 460 | e.insert(A); 461 | e.insert(B); 462 | e.insert(C); 463 | 464 | let mut iter1 = e.iter(); 465 | let first_elem = iter1.next(); 466 | assert_eq!(Some(A), first_elem); 467 | 468 | let iter2 = iter1.clone(); 469 | let elems1: Vec<_> = iter1.collect(); 470 | assert_eq!(vec![B, C], elems1); 471 | 472 | let elems2: Vec<_> = iter2.collect(); 473 | assert_eq!(vec![B, C], elems2); 474 | } 475 | 476 | /////////////////////////////////////////////////////////////////////////// 477 | // operators 478 | 479 | #[test] 480 | fn test_operators() { 481 | let mut e1: EnumSet = EnumSet::new(); 482 | e1.insert(A); 483 | e1.insert(C); 484 | 485 | let mut e2: EnumSet = EnumSet::new(); 486 | e2.insert(B); 487 | e2.insert(C); 488 | 489 | let e_union = e1 | e2; 490 | let elems: Vec<_> = e_union.iter().collect(); 491 | assert_eq!(vec![A,B,C], elems); 492 | 493 | let e_intersection = e1 & e2; 494 | let elems: Vec<_> = e_intersection.iter().collect(); 495 | assert_eq!(vec![C], elems); 496 | 497 | // Another way to express intersection 498 | let e_intersection = e1 - (e1 - e2); 499 | let elems: Vec<_> = e_intersection.iter().collect(); 500 | assert_eq!(vec![C], elems); 501 | 502 | let e_subtract = e1 - e2; 503 | let elems: Vec<_> = e_subtract.iter().collect(); 504 | assert_eq!(vec![A], elems); 505 | 506 | // Bitwise XOR of two sets, aka symmetric difference 507 | let e_symmetric_diff = e1 ^ e2; 508 | let elems: Vec<_> = e_symmetric_diff.iter().collect(); 509 | assert_eq!(vec![A,B], elems); 510 | 511 | // Another way to express symmetric difference 512 | let e_symmetric_diff = (e1 - e2) | (e2 - e1); 513 | let elems: Vec<_> = e_symmetric_diff.iter().collect(); 514 | assert_eq!(vec![A,B], elems); 515 | 516 | // Yet another way to express symmetric difference 517 | let e_symmetric_diff = (e1 | e2) - (e1 & e2); 518 | let elems: Vec<_> = e_symmetric_diff.iter().collect(); 519 | assert_eq!(vec![A,B], elems); 520 | } 521 | 522 | #[test] 523 | fn test_assign_operators() { 524 | let mut e1: EnumSet = EnumSet::new(); 525 | e1.insert(A); 526 | e1.insert(C); 527 | 528 | let mut e2: EnumSet = EnumSet::new(); 529 | e2.insert(B); 530 | e2.insert(C); 531 | 532 | let mut e_union = e1.clone(); 533 | e_union |= e2; 534 | let elems: Vec<_> = e_union.iter().collect(); 535 | assert_eq!(vec![A,B,C], elems); 536 | 537 | let mut e_intersection = e1.clone(); 538 | e_intersection &= e2; 539 | let elems: Vec<_> = e_intersection.iter().collect(); 540 | assert_eq!(vec![C], elems); 541 | 542 | let mut e_subtract = e1.clone(); 543 | e_subtract -= e2; 544 | let elems: Vec<_> = e_subtract.iter().collect(); 545 | assert_eq!(vec![A], elems); 546 | 547 | // Bitwise XOR of two sets, aka symmetric difference 548 | let mut e_symmetric_diff = e1.clone(); 549 | e_symmetric_diff ^= e2; 550 | let elems: Vec<_> = e_symmetric_diff.iter().collect(); 551 | assert_eq!(vec![A,B], elems); 552 | } 553 | 554 | #[test] 555 | #[should_panic] 556 | fn test_overflow() { 557 | #[allow(dead_code)] 558 | #[repr(u32)] 559 | #[derive(Clone, Copy)] 560 | enum Bar { 561 | V00, V01, V02, V03, V04, V05, V06, V07, V08, V09, 562 | V10, V11, V12, V13, V14, V15, V16, V17, V18, V19, 563 | V20, V21, V22, V23, V24, V25, V26, V27, V28, V29, 564 | V30, V31, V32, V33, V34, V35, V36, V37, V38, V39, 565 | } 566 | 567 | impl CLike for Bar { 568 | fn to_u32(&self) -> u32 { 569 | *self as u32 570 | } 571 | 572 | unsafe fn from_u32(v: u32) -> Bar { 573 | mem::transmute(v) 574 | } 575 | } 576 | 577 | let mut set = EnumSet::new(); 578 | set.insert(Bar::V32); 579 | } 580 | } 581 | --------------------------------------------------------------------------------