derive_destructure2-0.1.3/.cargo_vcs_info.json0000644000000001360000000000100150260ustar { "git": { "sha1": "796f0562600976b53a5b91f71be89b2effebf95c" }, "path_in_vcs": "" }derive_destructure2-0.1.3/.github/dependabot.yml000064400000000000000000000006221046102023000200060ustar 00000000000000version: 2 updates: - package-ecosystem: "github-actions" # Workflow files stored in the # default location of `.github/workflows` directory: "/" schedule: interval: "daily" - package-ecosystem: "cargo" directory: "/" schedule: interval: "daily" - package-ecosystem: "cargo" directory: "/derive_destructure2_examples" schedule: interval: "daily" derive_destructure2-0.1.3/.github/workflows/publish.yml000064400000000000000000000004231046102023000214030ustar 00000000000000on: push: tags: - '*' jobs: publish: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Publish to crates.io run: | cargo publish env: CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }} derive_destructure2-0.1.3/.github/workflows/rust.yml000064400000000000000000000026361046102023000207420ustar 00000000000000name: Rust env: CARGO_TERM_COLOR: always on: push: paths-ignore: - 'README.md' - 'LICENSE' - '.gitignore' pull_request: paths-ignore: - 'README.md' - 'LICENSE' - '.gitignore' jobs: check: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/cache@v3 with: path: | ~/.cargo/bin/ ~/.cargo/registry/index/ ~/.cargo/registry/cache/ ~/.cargo/git/db/ target/ key: ${{ github.event.repository.name }}-${{ runner.os }}-cargo-check-v2 - name: Run check run: | cargo check --all cargo clippy --all check_format: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Check format run: cargo fmt --all -- --check build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Install latest nightly uses: actions-rs/toolchain@v1 with: toolchain: nightly override: true components: miri - uses: actions/cache@v3 with: path: | ~/.cargo/bin/ ~/.cargo/registry/index/ ~/.cargo/registry/cache/ ~/.cargo/git/db/ target/ key: ${{ github.event.repository.name }}-${{ runner.os }}-cargo-test-v2 - name: Run tests run: | cargo test cargo +nightly miri test derive_destructure2-0.1.3/.gitignore000064400000000000000000000005001046102023000156010ustar 00000000000000# Generated by Cargo # will have compiled files and executables /target/ # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries # More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html Cargo.lock # These are backup files generated by rustfmt **/*.rs.bk derive_destructure2-0.1.3/.travis.yml000064400000000000000000000001431046102023000157250ustar 00000000000000language: rust rust: - stable - beta - nightly matrix: allow_failures: - rust: nightly derive_destructure2-0.1.3/Cargo.toml0000644000000020270000000000100130250ustar # 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 are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2018" name = "derive_destructure2" version = "0.1.3" authors = ["Jiahao XU "] description = "Destructure structs that implement Drop" readme = "README.md" keywords = [ "derive", "destructure", "drop", "E0509", "remove_trait_impls", ] categories = [ "no-std", "rust-patterns", ] license = "MIT OR Apache-2.0" repository = "https://github.com/NobodyXu/derive_destructure2" [lib] proc-macro = true [dependencies.proc-macro2] version = "1" [dependencies.quote] version = "1" [dependencies.syn] version = "2" derive_destructure2-0.1.3/Cargo.toml.orig000064400000000000000000000010261046102023000165040ustar 00000000000000[package] name = "derive_destructure2" version = "0.1.3" edition = "2018" authors = ["Jiahao XU "] license = "MIT OR Apache-2.0" description = "Destructure structs that implement Drop" repository = "https://github.com/NobodyXu/derive_destructure2" keywords = ["derive", "destructure", "drop", "E0509", "remove_trait_impls"] categories = ["no-std", "rust-patterns"] [lib] proc-macro = true [workspace] members = [ "derive_destructure2_examples" ] [dependencies] proc-macro2 = "1" syn = "2" quote = "1" derive_destructure2-0.1.3/LICENSE-APACHE000064400000000000000000000251371046102023000155520ustar 00000000000000 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. derive_destructure2-0.1.3/LICENSE-MIT000064400000000000000000000017761046102023000152650ustar 00000000000000Permission 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.derive_destructure2-0.1.3/README.md000064400000000000000000000071141046102023000151000ustar 00000000000000# derive_destructure2 **(no-std)** [![Rust](https://github.com/NobodyXu/derive_destructure2/actions/workflows/rust.yml/badge.svg)](https://github.com/NobodyXu/derive_destructure2/actions/workflows/rust.yml) [![crate.io downloads](https://img.shields.io/crates/d/derive_destructure2)](https://crates.io/crates/derive_destructure2) [![crate.io version](https://img.shields.io/crates/v/derive_destructure2)](https://crates.io/crates/derive_destructure2) [![docs](https://docs.rs/derive_destructure2/badge.svg)](https://docs.rs/derive_destructure2) **[examples](https://docs.rs/derive_destructure2_examples)** This crate allows you to destructure structs that implement `Drop`. If you've ever struggled with error E0509 "cannot move out of type `T`, which implements the `Drop` trait" then this crate may be for you. To use this crate, put this in your `lib.rs` or `main.rs` for rust < 1.30: ```ignore #[macro_use] extern crate derive_destructure2; ``` For rust >= 1.30, just import it as a regular item: ```ignore use derive_destructure2::{destructure, remove_trait_impls}; ``` Then you have 2 ways to use this crate: ## Option 1: `#[derive(destructure)]` If you mark a struct with `#[derive(destructure)]`, then you can destructure it using from your crate ```rust let (field_1, field_2, ...) = my_struct.destructure(); ``` This turns the struct into a tuple of its fields **without running the struct's `drop()` method**. You can then happily move elements out of this tuple. Note: in Rust, a tuple of 1 element is denoted as `(x,)`, not `(x)`. __**`destructure` is implemented as a private associated function.**__ ## Option 2: `#[derive(remove_trait_impls)]` If you mark your struct with `#[derive(remove_trait_impls)]`, then you can do from your crate ```rust let my_struct = my_struct.remove_trait_impls(); ``` The result is a struct with the same fields, but it implements no traits (except automatically-implemented traits like `Sync` and `Send`). In particular, it doesn't implement `Drop`, so you can move fields out of it. The name of the resulting struct is the original name plus the suffix `WithoutTraitImpls`. For example, `Foo` becomes `FooWithoutTraitImpls`. But you usually don't need to write out this name. `#[derive(remove_trait_impls)]` works on enums too. __**`remove_trait_impls` is a private associated function.**__ ## Example: ```rust use derive_destructure2::*; #[derive(destructure, remove_trait_impls)] struct ImplementsDrop { some_str: String, some_int: i32 } impl Drop for ImplementsDrop { fn drop(&mut self) { panic!("We don't want to drop this"); } } fn main() { // Using destructure(): let x = ImplementsDrop { some_str: "foo".to_owned(), some_int: 4 }; let (some_str, some_int) = x.destructure(); // x's drop() method never gets called // Using remove_trait_impls(): let x = ImplementsDrop { some_str: "foo".to_owned(), some_int: 4 }; let x = x.remove_trait_impls(); // this x doesn't implement drop, // so we can move fields out of it drop(x.some_str); println!("{}", x.some_int); } ``` ## License Licensed under either of * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or https://www.apache.org/licenses/LICENSE-2.0) * MIT license ([LICENSE-MIT](LICENSE-MIT) or https://opensource.org/licenses/MIT) at your option. ### Contribution Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. derive_destructure2-0.1.3/src/lib.rs000064400000000000000000000360031046102023000155230ustar 00000000000000//! **[examples](https://docs.rs/derive_destructure2_examples)** //! //! This crate allows you to destructure structs that implement `Drop`. //! //! If you've ever struggled with error E0509 //! "cannot move out of type `T`, which implements the `Drop` trait" //! then this crate may be for you. //! //! To use this crate, put this in your `lib.rs` or `main.rs` for rust < 1.30: //! //! ```ignore //! #[macro_use] //! extern crate derive_destructure2; //! ``` //! //! For rust >= 1.30, just import it as a regular item: //! //! ```rust //! use derive_destructure2::{destructure, remove_trait_impls}; //! ``` //! //! Then you have 2 ways to use this crate: //! //! # Option 1: `#[derive(destructure)]` //! //! If you mark a struct with `#[derive(destructure)]`, then you can destructure it using //! from your crate //! //! ```rust //! use derive_destructure2::destructure; //! //! #[derive(destructure)] //! struct S { //! field_1: u32, //! field_2: i32 //! } //! //! let val = S { //! field_1: 1, //! field_2: 2, //! }; //! let (field_1, field_2) = val.destructure(); //! ``` //! //! This turns the struct into a tuple of its fields **without running the struct's `drop()` //! method**. You can then happily move elements out of this tuple. //! //! Note: in Rust, a tuple of 1 element is denoted as `(x,)`, not `(x)`. //! //! __**`destructure` is implemented as a private associated function.**__ //! //! # Option 2: `#[derive(remove_trait_impls)]` //! //! If you mark your struct with `#[derive(remove_trait_impls)]`, then you can do //! from your crate //! //! ```rust //! use derive_destructure2::remove_trait_impls; //! //! #[derive(remove_trait_impls)] //! struct S { //! field_1: u32, //! field_2: i32 //! } //! impl Drop for S { //! fn drop(&mut self) { //! panic!("Dropped!"); //! } //! } //! //! let val = S { //! field_1: 1, //! field_2: 2, //! }; //! let val = val.remove_trait_impls(); //! //! // Dropping val no longer calls `S::drop`. //! drop(val); //! ``` //! //! The result is a struct with the same fields, but it implements no traits //! (except automatically-implemented traits like `Sync` and `Send`). //! In particular, it doesn't implement `Drop`, so you can move fields out of it. //! //! The name of the resulting struct is the original name plus the suffix //! `WithoutTraitImpls`. //! //! For example, `Foo` becomes `FooWithoutTraitImpls`. But you usually don't need to write //! out this name. //! //! `#[derive(remove_trait_impls)]` works on enums too. //! //! __**`remove_trait_impls` is a private associated function.**__ //! //! # Example: //! //! ```rust //! use derive_destructure2::*; //! //! #[derive(destructure, remove_trait_impls)] //! struct ImplementsDrop { //! some_str: String, //! some_int: i32 //! } //! //! impl Drop for ImplementsDrop { //! fn drop(&mut self) { //! panic!("We don't want to drop this"); //! } //! } //! //! # fn main() { //! // Using destructure(): //! let x = ImplementsDrop { //! some_str: "foo".to_owned(), //! some_int: 4 //! }; //! let (some_str, some_int) = x.destructure(); //! // x's drop() method never gets called //! //! // Using remove_trait_impls(): //! let x = ImplementsDrop { //! some_str: "foo".to_owned(), //! some_int: 4 //! }; //! let x = x.remove_trait_impls(); //! // this x doesn't implement drop, //! // so we can move fields out of it //! drop(x.some_str); //! println!("{}", x.some_int); //! # } //! ``` // The `quote!` macro requires deep recursion. #![recursion_limit = "512"] use proc_macro2::{Ident, Span}; use quote::{quote, quote_spanned}; use syn::spanned::Spanned; use syn::{parse_macro_input, Data, DeriveInput, Fields, Index}; #[proc_macro_derive(destructure)] pub fn derive_destructure(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = parse_macro_input!(input as DeriveInput); let name = input.ident; let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); let output = match input.data { Data::Struct(ref data) => { match data.fields { Fields::Named(ref fields) => { let field_types = fields.named.iter().map(|f| { let ty = &f.ty; quote_spanned! {f.span()=> #ty } }); let field_reads = fields.named.iter().map(|f| { let ident = &f.ident; quote_spanned! {f.span()=> ::core::ptr::read(&self_ref.#ident) } }); quote! { impl #impl_generics #name #ty_generics #where_clause { #[inline(always)] fn destructure(self) -> (#(#field_types,)*) { let maybe_uninit = ::core::mem::MaybeUninit::new(self); unsafe { let self_ref = &*maybe_uninit.as_ptr(); (#(#field_reads,)*) } } } } } Fields::Unnamed(ref fields) => { let field_types = fields.unnamed.iter().map(|f| { let ty = &f.ty; quote_spanned! {f.span()=> #ty } }); let field_reads = fields.unnamed.iter().enumerate().map(|(i,f)| { let index = Index::from(i); quote_spanned! {f.span()=> ::core::ptr::read(&self_ref.#index) } }); quote! { impl #impl_generics #name #ty_generics #where_clause { #[inline(always)] fn destructure(self) -> (#(#field_types,)*) { let maybe_uninit = ::core::mem::MaybeUninit::new(self); unsafe { let self_ref = &*maybe_uninit.as_ptr(); (#(#field_reads,)*) } } } } } Fields::Unit => { quote! { impl #impl_generics #name #ty_generics #where_clause { #[inline(always)] fn destructure(self) { let _ = ::core::mem::MaybeUninit::new(self); } } } } } } Data::Enum(_) => panic!("#[derive(destructure)] doesn't work on enums, use #[derive(remove_trait_impls)] instead."), Data::Union(_) => panic!("#[derive(destructure)] doesn't work on unions."), }; proc_macro::TokenStream::from(output) } #[proc_macro_derive(remove_trait_impls)] pub fn derive_remove_trait_impls(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = parse_macro_input!(input as DeriveInput); let name = input.ident; let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); let new_type_name = Ident::new(&(name.to_string() + "WithoutTraitImpls"), Span::call_site()); let output = match input.data { Data::Struct(ref data) => match data.fields { Fields::Named(ref fields) => { let fields_iter = fields.named.iter().map(|f| { let ident = &f.ident; let ty = &f.ty; quote_spanned! {f.span()=> #ident: #ty } }); let field_reads_iter = fields.named.iter().map(|f| { let ident = &f.ident; quote_spanned! {f.span()=> #ident: ::core::ptr::read(&self_ref.#ident) } }); quote! { #[must_use] struct #new_type_name #ty_generics #where_clause { #(#fields_iter,)* } impl #impl_generics #name #ty_generics #where_clause { #[inline(always)] fn remove_trait_impls(self) -> #new_type_name #ty_generics { let maybe_uninit = ::core::mem::MaybeUninit::new(self); unsafe { let self_ref = &*maybe_uninit.as_ptr(); #new_type_name { #(#field_reads_iter,)* } } } } } } Fields::Unnamed(ref fields) => { let fields_iter = fields.unnamed.iter().map(|f| { let ty = &f.ty; quote_spanned! {f.span()=> #ty } }); let field_reads_iter = fields.unnamed.iter().enumerate().map(|(i, f)| { let index = Index::from(i); quote_spanned! {f.span()=> ::core::ptr::read(&self_ref.#index) } }); quote! { #[must_use] struct #new_type_name #ty_generics #where_clause (#(#fields_iter,)*); impl #impl_generics #name #ty_generics #where_clause { #[inline(always)] fn remove_trait_impls(self) -> #new_type_name #ty_generics { let maybe_uninit = ::core::mem::MaybeUninit::new(self); unsafe { let self_ref = &*maybe_uninit.as_ptr(); #new_type_name(#(#field_reads_iter,)*) } } } } } Fields::Unit => { quote! { #[must_use] struct #new_type_name #ty_generics #where_clause; impl #impl_generics #name #ty_generics #where_clause { #[inline(always)] fn remove_trait_impls(self) -> #new_type_name #ty_generics { let _ = ::core::mem::MaybeUninit::new(self); #new_type_name } } } } }, Data::Enum(ref data) => { let variants_iter = data.variants.iter().map(|variant| { let variant_ident = &variant.ident; match variant.fields { Fields::Named(ref fields) => { let fields_iter = fields.named.iter().map(|f| { let ident = &f.ident; let ty = &f.ty; quote_spanned! {f.span()=> #ident: #ty } }); quote! { #variant_ident { #(#fields_iter,)* } } } Fields::Unnamed(ref fields) => { let fields_iter = fields.unnamed.iter().map(|f| { let ty = &f.ty; quote_spanned! {f.span()=> #ty } }); quote! { #variant_ident(#(#fields_iter,)*) } } Fields::Unit => { quote!(#variant_ident) } } }); let match_arms_iter = data.variants.iter().map(|variant| { let variant_ident = &variant.ident; match variant.fields { Fields::Named(ref fields) => { let fields_iter = fields.named.iter().map(|f| { let ident = &f.ident; quote_spanned! {f.span()=> ref #ident } }); let field_reads_iter = fields.named.iter().map(|f| { let ident = &f.ident; quote_spanned! {f.span()=> #ident: ::core::ptr::read(#ident) } }); quote! { #name::#variant_ident { #(#fields_iter,)* } => #new_type_name::#variant_ident { #(#field_reads_iter,)* } } } Fields::Unnamed(ref fields) => { let fields_iter = fields.unnamed.iter().enumerate().map(|(i,f)| { let index = Ident::new(&format!("__{}", i), f.span()); quote_spanned! {f.span()=> ref #index } }); let field_reads_iter = fields.unnamed.iter().enumerate().map(|(i,f)| { let index = Ident::new(&format!("__{}", i), f.span()); quote_spanned! {f.span()=> ::core::ptr::read(#index) } }); quote! { #name::#variant_ident(#(#fields_iter,)*) => #new_type_name::#variant_ident(#(#field_reads_iter,)*) } } Fields::Unit => { quote!{ #name::#variant_ident => #new_type_name::#variant_ident } } } }); quote! { enum #new_type_name #ty_generics #where_clause { #(#variants_iter,)* } impl #impl_generics #name #ty_generics #where_clause { #[inline(always)] fn remove_trait_impls(self) -> #new_type_name #ty_generics { let maybe_uninit = ::core::mem::MaybeUninit::new(self); unsafe { match &*maybe_uninit.as_ptr() { #(#match_arms_iter,)* } } } } } } Data::Union(_) => panic!("#[derive(remove_trait_impls)] doesn't work on unions."), }; proc_macro::TokenStream::from(output) } derive_destructure2-0.1.3/tests/droptest.rs000064400000000000000000000025761046102023000172040ustar 00000000000000#[macro_use] extern crate derive_destructure2; use std::cell::Cell; use std::rc::Rc; #[derive(destructure, remove_trait_impls)] struct DropChecker(Rc>); impl DropChecker { fn new() -> Self { DropChecker(Rc::new(Cell::new(false))) } } impl Drop for DropChecker { fn drop(&mut self) { let dropped = &self.0; if dropped.get() { panic!("Dropped twice!"); } dropped.set(true) } } #[test] fn test_droptest_normal_drop() { let drop_checker = DropChecker::new(); let dropped_rc_clone = Rc::clone(&drop_checker.0); assert_eq!(dropped_rc_clone.get(), false); drop(drop_checker); assert_eq!(dropped_rc_clone.get(), true); } #[test] fn test_droptest_destructure() { let drop_checker = DropChecker::new(); let dropped_rc_clone = Rc::clone(&drop_checker.0); assert_eq!(dropped_rc_clone.get(), false); let (dropped_rc,) = drop_checker.destructure(); assert_eq!(dropped_rc.get(), false); assert_eq!(dropped_rc_clone.get(), false); } #[test] fn test_droptest_remove_trait_impls() { let drop_checker = DropChecker::new(); let dropped_rc_clone = Rc::clone(&drop_checker.0); assert_eq!(dropped_rc_clone.get(), false); let custom_drop_removed = drop_checker.remove_trait_impls(); assert_eq!(custom_drop_removed.0.get(), false); assert_eq!(dropped_rc_clone.get(), false); } derive_destructure2-0.1.3/tests/enum.rs000064400000000000000000000032011046102023000162660ustar 00000000000000#[macro_use] extern crate derive_destructure2; #[derive(remove_trait_impls)] pub enum Simple { A, B, C, } impl Drop for Simple { fn drop(&mut self) { panic!("We shouldn't drop this!"); } } #[test] fn test_simple() { let simple = Simple::A; let simple = simple.remove_trait_impls(); if let SimpleWithoutTraitImpls::A = simple { } else { panic!(); } } pub trait SomeTrait {} impl SomeTrait for i32 {} #[derive(remove_trait_impls)] pub enum GenericEnum { A(T), B(T, f64), C { x: String, y: T }, D, } impl Drop for GenericEnum { fn drop(&mut self) { panic!("We shouldn't drop this!"); } } #[test] fn test_generic_a() { let e = GenericEnum::A(5); let e = e.remove_trait_impls(); if let GenericEnumWithoutTraitImpls::A(x) = e { assert_eq!(x, 5); } else { panic!(); } } #[test] fn test_generic_b() { let e = GenericEnum::B(7, 8.9); let e = e.remove_trait_impls(); if let GenericEnumWithoutTraitImpls::B(x, y) = e { assert_eq!(x, 7); assert_eq!(y, 8.9); } else { panic!(); } } #[test] fn test_generic_c() { let e = GenericEnum::C { x: "foo".to_owned(), y: 7, }; let e = e.remove_trait_impls(); if let GenericEnumWithoutTraitImpls::C { x, y } = e { assert_eq!(x, "foo"); assert_eq!(y, 7); } else { panic!(); } } #[test] fn test_generic_d() { let e = GenericEnum::::D; let e = e.remove_trait_impls(); if let GenericEnumWithoutTraitImpls::D = e { } else { panic!(); } } derive_destructure2-0.1.3/tests/generic.rs000064400000000000000000000041521046102023000167440ustar 00000000000000#[macro_use] extern crate derive_destructure2; #[derive(destructure, remove_trait_impls)] struct Foo<'a, 'b, T> { some_ref: &'a i64, some_ref_mut: &'b mut i32, some_val: T, } impl<'a, 'b, T> Drop for Foo<'a, 'b, T> { fn drop(&mut self) { panic!("Shouldn't drop this"); } } #[test] fn test_simple_destructure() { let x = 3; let mut y = 4; let foo = Foo { some_ref: &x, some_ref_mut: &mut y, some_val: 5.6, }; let (x, y, z) = foo.destructure(); assert_eq!(*x, 3); assert_eq!(*y, 4); *y = 5; assert_eq!(*y, 5); assert_eq!(z, 5.6); } #[test] fn test_simple_remove_trait_impls() { let x = 3; let mut y = 4; let foo = Foo { some_ref: &x, some_ref_mut: &mut y, some_val: 5.6, }; let foo = foo.remove_trait_impls(); assert_eq!(*foo.some_ref, 3); assert_eq!(*foo.some_ref_mut, 4); *foo.some_ref_mut = 5; assert_eq!(*foo.some_ref_mut, 5); assert_eq!(foo.some_val, 5.6); } trait SomeTrait {} impl SomeTrait for i32 {} #[derive(destructure, remove_trait_impls)] struct TraitBounded(T); impl Drop for TraitBounded { fn drop(&mut self) { panic!("Shouldn't drop this"); } } #[derive(destructure, remove_trait_impls)] struct TraitBounded2<'a, 'b, T: SomeTrait + 'b> where 'b: 'a, { r: &'a &'b T, } impl<'a, 'b: 'a, T: SomeTrait + 'b> Drop for TraitBounded2<'a, 'b, T> { fn drop(&mut self) { panic!("Shouldn't drop this"); } } #[test] fn test_trait_bounded_destructure() { let x = TraitBounded(7); let (x,) = x.destructure(); assert_eq!(x, 7); } #[test] fn test_trait_bounded_remove_trait_impls() { let x = TraitBounded(7); let x = x.remove_trait_impls(); assert_eq!(x.0, 7); } #[test] fn test_trait_bounded2_destructure() { let i = 7; let x = TraitBounded2 { r: &&i }; let (r,) = x.destructure(); assert_eq!(**r, 7); } #[test] fn test_trait_bounded2_remove_trait_impls() { let i = 7; let x = TraitBounded2 { r: &&i }; let x = x.remove_trait_impls(); assert_eq!(**x.r, 7); } derive_destructure2-0.1.3/tests/simple.rs000064400000000000000000000010711046102023000166160ustar 00000000000000#[macro_use] extern crate derive_destructure2; #[derive(destructure, remove_trait_impls)] struct Foo { x: i64, y: f32, } impl Drop for Foo { fn drop(&mut self) { panic!("We don't want to drop this"); } } #[test] fn test_simple_destructure() { let foo = Foo { x: 7, y: 8.9 }; let (x, y) = foo.destructure(); assert_eq!(x, 7); assert_eq!(y, 8.9); } #[test] fn test_simple_remove_trait_impls() { let foo = Foo { x: 7, y: 8.9 }; let foo = foo.remove_trait_impls(); assert_eq!(foo.x, 7); assert_eq!(foo.y, 8.9); } derive_destructure2-0.1.3/tests/unit.rs000064400000000000000000000022361046102023000163100ustar 00000000000000#[macro_use] extern crate derive_destructure2; // This is perhaps rather pointless, as you can just use std::mem::forget instead... // Oh well. #[derive(destructure, remove_trait_impls)] struct Foo; impl Drop for Foo { fn drop(&mut self) { panic!("We don't want to drop this"); } } #[derive(destructure, remove_trait_impls)] struct Bar(); impl Drop for Bar { fn drop(&mut self) { panic!("We don't want to drop this"); } } #[derive(destructure, remove_trait_impls)] struct Baz {} impl Drop for Baz { fn drop(&mut self) { panic!("We don't want to drop this"); } } #[test] fn test_foo_destructure() { let x = Foo; let () = x.destructure(); } #[test] fn test_foo_remove_trait_impls() { let x = Foo; let _ = x.remove_trait_impls(); } #[test] fn test_bar_destructure() { let x = Bar(); let () = x.destructure(); } #[test] fn test_bar_remove_trait_impls() { let x = Bar(); let _ = x.remove_trait_impls(); } #[test] fn test_baz_destructure() { let x = Baz {}; let () = x.destructure(); } #[test] fn test_baz_remove_trait_impls() { let x = Baz {}; let _ = x.remove_trait_impls(); }