enum-as-inner-0.3.0/.gitignore010064400007650000024000000000361340231276300143770ustar0000000000000000/target **/*.rs.bk Cargo.lock enum-as-inner-0.3.0/.travis.yml010064400007650000024000000013771353331544200145330ustar0000000000000000sudo: required dist: xenial language: rust matrix: include: # parallel builds for tests - rust: stable env: NAME=stable RUST_BACKTRACE=full before_install: - rustup component add rustfmt script: - cargo test # parallel builds for tests - rust: nightly env: NAME=stable RUST_BACKTRACE=full before_install: - rustup component add rustfmt script: - cargo test # clippy - rust: stable env: NAME=clippy RUST_BACKTRACE=full before_install: - rustup component add clippy - rustup component add rustfmt script: - cargo clippy -- -D warnings script: - cargo test #after_success: scripts/run_kcov.sh enum-as-inner-0.3.0/Cargo.toml.orig010064400007650000024000000007161353331544200153050ustar0000000000000000[package] name = "enum-as-inner" version = "0.3.0" authors = ["Benjamin Fry "] edition = "2018" description = """ A proc-macro for deriving inner field accessor functions on enums. """ documentation = "https://docs.rs/enum-as-inner" repository = "https://github.com/bluejekyll/enum-as-inner" readme = "README.md" license = "MIT/Apache-2.0" [lib] proc-macro = true [dependencies] heck = "0.3" proc-macro2 = "1.0" quote = "1.0" syn = "1.0"enum-as-inner-0.3.0/Cargo.toml0000644000000020440000000000000115470ustar00# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies # # If you believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] edition = "2018" name = "enum-as-inner" version = "0.3.0" authors = ["Benjamin Fry "] description = "A proc-macro for deriving inner field accessor functions on enums.\n" documentation = "https://docs.rs/enum-as-inner" readme = "README.md" license = "MIT/Apache-2.0" repository = "https://github.com/bluejekyll/enum-as-inner" [lib] proc-macro = true [dependencies.heck] version = "0.3" [dependencies.proc-macro2] version = "1.0" [dependencies.quote] version = "1.0" [dependencies.syn] version = "1.0" enum-as-inner-0.3.0/CODE_OF_CONDUCT.md010064400007650000024000000062171340267425300152220ustar0000000000000000# Contributor Covenant Code of Conduct ## Our Pledge In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. ## Our Standards Examples of behavior that contributes to creating a positive environment include: * Using welcoming and inclusive language * Being respectful of differing viewpoints and experiences * Gracefully accepting constructive criticism * Focusing on what is best for the community * Showing empathy towards other community members Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery and unwelcome sexual attention or advances * Trolling, insulting/derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or electronic address, without explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Our Responsibilities Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. ## Scope This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at benjaminfry@me.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] [homepage]: http://contributor-covenant.org [version]: http://contributor-covenant.org/version/1/4/ enum-as-inner-0.3.0/copyright.txt010064400007650000024000000005421340267373600151740ustar0000000000000000// Copyright 2015-2018 Benjamin Fry // // Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be // copied, modified, or distributed except according to those terms. enum-as-inner-0.3.0/LICENSE-APACHE010064400007650000024000000261361340267361200143470ustar0000000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "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. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "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. "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). "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. "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." "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. 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. 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. 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: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) 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 (d) 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. 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. 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. 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. 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. 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. 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. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright {yyyy} {name of copyright owner} Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. enum-as-inner-0.3.0/LICENSE-MIT010064400007650000024000000021131340267361200140440ustar0000000000000000Copyright (c) 2015 The trust-dns Developers Copyright (c) 2017 Google LLC. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. enum-as-inner-0.3.0/README.md010064400007650000024000000037341353331560000136740ustar0000000000000000# enum-as-inner A deriving proc-macro for generating functions to automatically give access to the inner members of enum. ## Basic unnamed field case The basic case is meant for single item enums, like: ```rust #[macro_use] extern crate enum_as_inner; #[derive(Debug, EnumAsInner)] enum OneEnum { One(u32), } ``` where the inner item can be retrieved with the `as_*()` or with the `into_*()` functions: ```rust let one = OneEnum::One(1); assert_eq!(*one.as_one().unwrap(), 1); assert_eq!(one.into_one().unwrap(), 1); ``` where the result is either a reference for inner items or a tuple containing the inner items. ## Unit case This will return copy's of the value of the unit variant, as `isize`: ```rust #[macro_use] extern crate enum_as_inner; #[derive(EnumAsInner)] enum UnitVariants { Zero, One, Two, } ``` These are not references: ```rust let unit = UnitVariants::Two; assert_eq!(unit.as_two().unwrap(), ()); ``` Note that for unit enums there is no `into_*()` function generated. ## Mutliple, unnamed field case This will return a tuple of the inner types: ```rust #[macro_use] extern crate enum_as_inner; #[derive(Debug, EnumAsInner)] enum ManyVariants { One(u32), Two(u32, i32), Three(bool, u32, i64), } ``` And can be accessed like: ```rust let many = ManyVariants::Three(true, 1, 2); assert_eq!(many.as_three().unwrap(), (&true, &1_u32, &2_i64)); assert_eq!(many.into_three().unwrap(), (true, 1_u32, 2_i64)); ``` ## Multiple, named field case This will return a tuple of the inner types, like the unnamed option: ```rust #[macro_use] extern crate enum_as_inner; #[derive(Debug, EnumAsInner)] enum ManyVariants { One{ one: u32 }, Two{ one: u32, two: i32 }, Three{ one: bool, two: u32, three: i64 }, } ``` And can be accessed like: ```rust let many = ManyVariants::Three{ one: true, two: 1, three: 2 }; assert_eq!(many.as_three().unwrap(), (&true, &1_u32, &2_i64)); assert_eq!(many.into_three().unwrap(), (true, 1_u32, 2_i64)); ```enum-as-inner-0.3.0/src/lib.rs010064400007650000024000000252401353331560000143140ustar0000000000000000// Copyright 2015-2018 Benjamin Fry // // Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be // copied, modified, or distributed except according to those terms. //! # enum-as-inner //! //! A deriving proc-macro for generating functions to automatically give access to the inner members of enum. //! //! ## Basic unnamed field case //! //! The basic case is meant for single item enums, like: //! //! ```rust //! # #[macro_use] extern crate enum_as_inner; //! # fn main() { //! //! #[derive(Debug, EnumAsInner)] //! enum OneEnum { //! One(u32), //! } //! //! let one = OneEnum::One(1); //! //! assert_eq!(*one.as_one().unwrap(), 1); //! assert_eq!(one.into_one().unwrap(), 1); //! # } //! ``` //! //! where the result is either a reference for inner items or a tuple containing the inner items. //! //! ## Unit case //! //! This will return copy's of the value of the unit variant, as `isize`: //! //! ```rust //! # #[macro_use] extern crate enum_as_inner; //! # fn main() { //! //! #[derive(EnumAsInner)] //! enum UnitVariants { //! Zero, //! One, //! Two, //! } //! //! let unit = UnitVariants::Two; //! //! assert_eq!(unit.as_two().unwrap(), ()); //! # } //! ``` //! //! Note that for unit enums there is no `into_*()` function generated. //! //! ## Mutliple, unnamed field case //! //! This will return a tuple of the inner types: //! //! ```rust //! # #[macro_use] extern crate enum_as_inner; //! # fn main() { //! //! #[derive(Debug, EnumAsInner)] //! enum ManyVariants { //! One(u32), //! Two(u32, i32), //! Three(bool, u32, i64), //! } //! //! let many = ManyVariants::Three(true, 1, 2); //! //! assert_eq!(many.as_three().unwrap(), (&true, &1_u32, &2_i64)); //! assert_eq!(many.into_three().unwrap(), (true, 1_u32, 2_i64)); //! # } //! ``` //! //! ## Multiple, named field case //! //! This will return a tuple of the inner types, like the unnamed option: //! //! ```rust //! # #[macro_use] extern crate enum_as_inner; //! # fn main() { //! //! #[derive(Debug, EnumAsInner)] //! enum ManyVariants { //! One { one: u32 }, //! Two { one: u32, two: i32 }, //! Three { one: bool, two: u32, three: i64 }, //! } //! //! let many = ManyVariants::Three { one: true, two: 1, three: 2 }; //! //! assert_eq!(many.as_three().unwrap(), (&true, &1_u32, &2_i64)); //! assert_eq!(many.into_three().unwrap(), (true, 1_u32, 2_i64)); //! # } //! ``` extern crate proc_macro; extern crate proc_macro2; #[macro_use] extern crate syn; #[macro_use] extern crate quote; use heck::SnakeCase; use proc_macro2::{Ident, Span, TokenStream}; use syn::DeriveInput; /// returns first the types to return, the match names, and then tokens to the field accesses fn unit_fields_return( name: &syn::Ident, variant_name: &syn::Ident, function_name: &Ident, doc: &str, ) -> TokenStream { quote!( #[doc = #doc ] pub fn #function_name(&self) -> Option<()> { match self { #name::#variant_name => { Some(()) } _ => None } } ) } /// returns first the types to return, the match names, and then tokens to the field accesses fn unnamed_fields_return( name: &syn::Ident, variant_name: &syn::Ident, (function_name_ref, doc_ref): (&Ident, &str), (function_name_val, doc_val): (&Ident, &str), fields: &syn::FieldsUnnamed, ) -> TokenStream { let (returns_ref, returns_val, matches, accesses_ref, accesses_val) = match fields.unnamed.len() { 1 => { let field = fields.unnamed.first().expect("no fields on type"); let returns = &field.ty; let returns_ref = quote!(&#returns); let returns_val = quote!(#returns); let matches = quote!(inner); let accesses_ref = quote!(&inner); let accesses_val = quote!(inner); ( returns_ref, returns_val, matches, accesses_ref, accesses_val, ) } 0 => (quote!(()), quote!(()), quote!(), quote!(()), quote!(())), _ => { let mut returns_ref = TokenStream::new(); let mut returns_val = TokenStream::new(); let mut matches = TokenStream::new(); let mut accesses_ref = TokenStream::new(); let mut accesses_val = TokenStream::new(); for (i, field) in fields.unnamed.iter().enumerate() { let rt = &field.ty; let match_name = Ident::new(&format!("match_{}", i), Span::call_site()); returns_ref.extend(quote!(&#rt,)); returns_val.extend(quote!(#rt,)); matches.extend(quote!(#match_name,)); accesses_ref.extend(quote!(&#match_name,)); accesses_val.extend(quote!(#match_name,)); } ( quote!((#returns_ref)), quote!((#returns_val)), quote!(#matches), quote!((#accesses_ref)), quote!((#accesses_val)), ) } }; quote!( #[doc = #doc_ref ] pub fn #function_name_ref(&self) -> Option<#returns_ref> { match self { #name::#variant_name(#matches) => { Some(#accesses_ref) } _ => None } } #[doc = #doc_val ] pub fn #function_name_val(self) -> ::core::result::Result<#returns_val, Self> { match self { #name::#variant_name(#matches) => { Ok(#accesses_val) }, _ => Err(self) } } ) } /// returns first the types to return, the match names, and then tokens to the field accesses fn named_fields_return( name: &syn::Ident, variant_name: &syn::Ident, (function_name_ref, doc_ref): (&Ident, &str), (function_name_val, doc_val): (&Ident, &str), fields: &syn::FieldsNamed, ) -> TokenStream { let (returns_ref, returns_val, matches, accesses_ref, accesses_val) = match fields.named.len() { 1 => { let field = fields.named.first().expect("no fields on type"); let match_name = field.ident.as_ref().expect("expected a named field"); let returns = &field.ty; let returns_ref = quote!(&#returns); let returns_val = quote!(#returns); let matches = quote!(#match_name); let accesses_ref = quote!(&#match_name); let accesses_val = quote!(#match_name); ( returns_ref, returns_val, matches, accesses_ref, accesses_val, ) } 0 => (quote!(()), quote!(()), quote!(), quote!(()), quote!(())), _ => { let mut returns_ref = TokenStream::new(); let mut returns_val = TokenStream::new(); let mut matches = TokenStream::new(); let mut accesses_ref = TokenStream::new(); let mut accesses_val = TokenStream::new(); for field in fields.named.iter() { let rt = &field.ty; let match_name = field.ident.as_ref().expect("expected a named field"); returns_ref.extend(quote!(&#rt,)); returns_val.extend(quote!(#rt,)); matches.extend(quote!(#match_name,)); accesses_ref.extend(quote!(&#match_name,)); accesses_val.extend(quote!(#match_name,)); } ( quote!((#returns_ref)), quote!((#returns_val)), quote!(#matches), quote!((#accesses_ref)), quote!((#accesses_val)), ) } }; quote!( #[doc = #doc_ref ] pub fn #function_name_ref(&self) -> Option<#returns_ref> { match self { #name::#variant_name{ #matches } => { Some(#accesses_ref) } _ => None } } #[doc = #doc_val ] pub fn #function_name_val(self) -> ::core::result::Result<#returns_val, Self> { match self { #name::#variant_name{ #matches } => { Ok(#accesses_val) } _ => Err(self) } } ) } fn impl_all_as_fns(ast: &DeriveInput) -> TokenStream { let name = &ast.ident; let enum_data = if let syn::Data::Enum(data) = &ast.data { data } else { panic!("{} is not an enum", name); }; let mut stream = TokenStream::new(); for variant_data in &enum_data.variants { let variant_name = &variant_data.ident; let function_name_ref = Ident::new( &format!("as_{}", variant_name).to_snake_case(), Span::call_site(), ); let doc_ref = format!( "Optionally returns references to the inner fields if this is a `{}::{}`, otherwise `None`", name, variant_name, ); let function_name_val = Ident::new( &format!("into_{}", variant_name).to_snake_case(), Span::call_site(), ); let doc_val = format!( "Returns the inner fields if this is a `{}::{}`, otherwise returns back the enum in the `Err` case of the result", name, variant_name, ); let tokens = match &variant_data.fields { syn::Fields::Unit => { unit_fields_return(name, variant_name, &function_name_ref, &doc_ref) } syn::Fields::Unnamed(unnamed) => unnamed_fields_return( name, variant_name, (&function_name_ref, &doc_ref), (&function_name_val, &doc_val), &unnamed, ), syn::Fields::Named(named) => named_fields_return( name, variant_name, (&function_name_ref, &doc_ref), (&function_name_val, &doc_val), &named, ), }; stream.extend(tokens); } quote!( impl #name { #stream } ) } #[proc_macro_derive(EnumAsInner)] pub fn enum_as_inner(input: proc_macro::TokenStream) -> proc_macro::TokenStream { // get a usable token stream let ast: DeriveInput = parse_macro_input!(input as DeriveInput); // Build the impl let expanded: TokenStream = impl_all_as_fns(&ast); // Return the generated impl proc_macro::TokenStream::from(expanded) } enum-as-inner-0.3.0/tests/basic.rs010064400007650000024000000016041353331560000152000ustar0000000000000000use enum_as_inner::EnumAsInner; #[derive(Debug, EnumAsInner)] enum EmptyTest {} #[test] fn test_empty() { let empty = None::; assert!(empty.is_none()); } #[derive(Debug, EnumAsInner)] enum EmptyParendsTest { Empty(), } #[test] fn test_empty_parends() { let empty = EmptyParendsTest::Empty(); assert_eq!(empty.as_empty().unwrap(), ()); assert_eq!(empty.into_empty().unwrap(), ()); } #[derive(Debug, EnumAsInner)] enum OneTest { One(u32), } #[test] fn test_one() { let empty = OneTest::One(1); assert_eq!(*empty.as_one().unwrap(), 1); assert_eq!(empty.into_one().unwrap(), 1); } #[derive(Debug, EnumAsInner)] enum MultiTest { Multi(u32, u32), } #[test] fn test_multi() { let multi = MultiTest::Multi(1, 1); assert_eq!(multi.as_multi().unwrap(), (&1_u32, &1_u32)); assert_eq!(multi.into_multi().unwrap(), (1_u32, 1_u32)); } enum-as-inner-0.3.0/tests/named.rs010064400007650000024000000021551353331560000152050ustar0000000000000000use enum_as_inner::EnumAsInner; #[derive(Debug, EnumAsInner)] enum ManyVariants { One { one: u32 }, Two { one: u32, two: i32 }, Three { one: bool, two: u32, three: i64 }, } #[test] fn test_one_named() { let many = ManyVariants::One { one: 1 }; assert!(many.as_one().is_some()); assert!(many.as_two().is_none()); assert!(many.as_three().is_none()); assert_eq!(*many.as_one().unwrap(), 1_u32); } #[test] fn test_two_named() { let many = ManyVariants::Two { one: 1, two: 2 }; assert!(many.as_one().is_none()); assert!(many.as_two().is_some()); assert!(many.as_three().is_none()); assert_eq!(many.as_two().unwrap(), (&1_u32, &2_i32)); assert_eq!(many.into_two().unwrap(), (1_u32, 2_i32)); } #[test] fn test_three_named() { let many = ManyVariants::Three { one: true, two: 1, three: 2, }; assert!(many.as_one().is_none()); assert!(many.as_two().is_none()); assert!(many.as_three().is_some()); assert_eq!(many.as_three().unwrap(), (&true, &1_u32, &2_i64)); assert_eq!(many.into_three().unwrap(), (true, 1_u32, 2_i64)); } enum-as-inner-0.3.0/tests/snake_case.rs010064400007650000024000000022751353331560000162200ustar0000000000000000use enum_as_inner::EnumAsInner; #[derive(Debug, EnumAsInner)] enum MixedCaseVariants { XMLIsNotCool, #[allow(non_camel_case_types)] Rust_IsCoolThough(u32), YMCA { named: i16, }, } #[test] fn test_xml_unit() { let mixed = MixedCaseVariants::XMLIsNotCool; assert!(mixed.as_xml_is_not_cool().is_some()); assert!(mixed.as_rust_is_cool_though().is_none()); assert!(mixed.as_ymca().is_none()); assert_eq!(mixed.as_xml_is_not_cool().unwrap(), ()); } #[test] fn test_rust_unnamed() { let mixed = MixedCaseVariants::Rust_IsCoolThough(42); assert!(mixed.as_xml_is_not_cool().is_none()); assert!(mixed.as_rust_is_cool_though().is_some()); assert!(mixed.as_ymca().is_none()); assert_eq!(*mixed.as_rust_is_cool_though().unwrap(), 42); assert_eq!(mixed.into_rust_is_cool_though().unwrap(), 42); } #[test] fn test_ymca_named() { let mixed = MixedCaseVariants::YMCA { named: -32_768 }; assert!(mixed.as_xml_is_not_cool().is_none()); assert!(mixed.as_rust_is_cool_though().is_none()); assert!(mixed.as_ymca().is_some()); assert_eq!(*mixed.as_ymca().unwrap(), (-32_768)); assert_eq!(mixed.into_ymca().unwrap(), (-32_768)); } enum-as-inner-0.3.0/tests/unit.rs010064400007650000024000000014261353331544200151040ustar0000000000000000use enum_as_inner::EnumAsInner; #[derive(EnumAsInner)] enum UnitVariants { Zero, One, Two, } #[test] fn test_zero_unit() { let unit = UnitVariants::Zero; assert!(unit.as_zero().is_some()); assert!(unit.as_one().is_none()); assert!(unit.as_two().is_none()); assert_eq!(unit.as_zero().unwrap(), ()); } #[test] fn test_one_unit() { let unit = UnitVariants::One; assert!(unit.as_zero().is_none()); assert!(unit.as_one().is_some()); assert!(unit.as_two().is_none()); assert_eq!(unit.as_one().unwrap(), ()); } #[test] fn test_two_unit() { let unit = UnitVariants::Two; assert!(unit.as_zero().is_none()); assert!(unit.as_one().is_none()); assert!(unit.as_two().is_some()); assert_eq!(unit.as_two().unwrap(), ()); } enum-as-inner-0.3.0/tests/unnamed.rs010064400007650000024000000020651353331560000155500ustar0000000000000000use enum_as_inner::EnumAsInner; #[derive(Debug, EnumAsInner)] enum ManyVariants { One(u32), Two(u32, i32), Three(bool, u32, i64), } #[test] fn test_one_unnamed() { let many = ManyVariants::One(1); assert!(many.as_one().is_some()); assert!(many.as_two().is_none()); assert!(many.as_three().is_none()); assert_eq!(*many.as_one().unwrap(), 1_u32); assert_eq!(many.into_one().unwrap(), 1_u32); } #[test] fn test_two_unnamed() { let many = ManyVariants::Two(1, 2); assert!(many.as_one().is_none()); assert!(many.as_two().is_some()); assert!(many.as_three().is_none()); assert_eq!(many.as_two().unwrap(), (&1_u32, &2_i32)); assert_eq!(many.into_two().unwrap(), (1_u32, 2_i32)); } #[test] fn test_three_unnamed() { let many = ManyVariants::Three(true, 1, 2); assert!(many.as_one().is_none()); assert!(many.as_two().is_none()); assert!(many.as_three().is_some()); assert_eq!(many.as_three().unwrap(), (&true, &1_u32, &2_i64)); assert_eq!(many.into_three().unwrap(), (true, 1_u32, 2_i64)); } enum-as-inner-0.3.0/.cargo_vcs_info.json0000644000000001120000000000000135430ustar00{ "git": { "sha1": "eee073533034c2928fef8f5d12e28c8e4573d9a6" } }