dyn-clone-1.0.16/.cargo_vcs_info.json0000644000000001360000000000100130110ustar { "git": { "sha1": "f2f0a02f1f7190048153e5ea8f554db7377a50a9" }, "path_in_vcs": "" }dyn-clone-1.0.16/.github/FUNDING.yml000064400000000000000000000000201046102023000147460ustar 00000000000000github: dtolnay dyn-clone-1.0.16/.github/workflows/ci.yml000064400000000000000000000037341046102023000163230ustar 00000000000000name: CI on: push: pull_request: workflow_dispatch: schedule: [cron: "40 1 * * *"] permissions: contents: read env: RUSTFLAGS: -Dwarnings jobs: pre_ci: uses: dtolnay/.github/.github/workflows/pre_ci.yml@master test: name: Rust ${{matrix.rust}} needs: pre_ci if: needs.pre_ci.outputs.continue runs-on: ubuntu-latest strategy: fail-fast: false matrix: rust: [nightly, beta, stable, 1.56.0] timeout-minutes: 45 steps: - uses: actions/checkout@v4 - uses: dtolnay/rust-toolchain@master with: toolchain: ${{matrix.rust}} - name: Enable type layout randomization run: echo RUSTFLAGS=${RUSTFLAGS}\ -Zrandomize-layout >> $GITHUB_ENV if: matrix.rust == 'nightly' - run: cargo test msrv: name: Rust 1.46.0 needs: pre_ci if: needs.pre_ci.outputs.continue runs-on: ubuntu-latest timeout-minutes: 45 steps: - uses: actions/checkout@v4 - uses: dtolnay/rust-toolchain@1.46.0 - run: cargo check doc: name: Documentation needs: pre_ci if: needs.pre_ci.outputs.continue runs-on: ubuntu-latest timeout-minutes: 45 env: RUSTDOCFLAGS: -Dwarnings steps: - uses: actions/checkout@v4 - uses: dtolnay/rust-toolchain@nightly - uses: dtolnay/install@cargo-docs-rs - run: cargo docs-rs miri: name: Miri needs: pre_ci if: needs.pre_ci.outputs.continue runs-on: ubuntu-latest timeout-minutes: 45 steps: - uses: actions/checkout@v4 - uses: dtolnay/rust-toolchain@miri - run: cargo miri setup - run: cargo miri test env: MIRIFLAGS: -Zmiri-strict-provenance clippy: name: Clippy runs-on: ubuntu-latest if: github.event_name != 'pull_request' timeout-minutes: 45 steps: - uses: actions/checkout@v4 - uses: dtolnay/rust-toolchain@clippy - run: cargo clippy --tests -- -Dclippy::all -Dclippy::pedantic dyn-clone-1.0.16/.gitignore000064400000000000000000000000401046102023000135630ustar 00000000000000 /target/ **/*.rs.bk Cargo.lock dyn-clone-1.0.16/Cargo.lock0000644000000110750000000000100107700ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 3 [[package]] name = "basic-toml" version = "0.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2f2139706359229bfa8f19142ac1155b4b80beafb7a60471ac5dd109d4a19778" dependencies = [ "serde", ] [[package]] name = "dissimilar" version = "1.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "86e3bdc80eee6e16b2b6b0f87fbc98c04bee3455e35174c0de1a125d0688c632" [[package]] name = "dyn-clone" version = "1.0.16" dependencies = [ "rustversion", "trybuild", ] [[package]] name = "glob" version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d2fabcfbdc87f4758337ca535fb41a6d701b65693ce38287d856d1674551ec9b" [[package]] name = "itoa" version = "1.0.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "af150ab688ff2122fcef229be89cb50dd66af9e01a4ff320cc137eecc9bacc38" [[package]] name = "once_cell" version = "1.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dd8b5dd2ae5ed71462c540258bedcb51965123ad7e7ccf4b9a8cafaa4a63576d" [[package]] name = "proc-macro2" version = "1.0.69" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "134c189feb4956b20f6f547d2cf727d4c0fe06722b20a0eec87ed445a97f92da" dependencies = [ "unicode-ident", ] [[package]] name = "quote" version = "1.0.33" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5267fca4496028628a95160fc423a33e8b2e6af8a5302579e322e4b520293cae" dependencies = [ "proc-macro2", ] [[package]] name = "rustversion" version = "1.0.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7ffc183a10b4478d04cbbbfc96d0873219d962dd5accaff2ffbd4ceb7df837f4" [[package]] name = "ryu" version = "1.0.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ad4cc8da4ef723ed60bced201181d83791ad433213d8c24efffda1eec85d741" [[package]] name = "serde" version = "1.0.190" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "91d3c334ca1ee894a2c6f6ad698fe8c435b76d504b13d436f0685d648d6d96f7" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" version = "1.0.190" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "67c5609f394e5c2bd7fc51efda478004ea80ef42fee983d5c67a65e34f32c0e3" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "serde_json" version = "1.0.108" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3d1c7e3eac408d115102c4c24ad393e0821bb3a5df4d506a80f85f7a742a526b" dependencies = [ "itoa", "ryu", "serde", ] [[package]] name = "syn" version = "2.0.38" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e96b79aaa137db8f61e26363a0c9b47d8b4ec75da28b7d1d614c2303e232408b" dependencies = [ "proc-macro2", "quote", "unicode-ident", ] [[package]] name = "termcolor" version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6093bad37da69aab9d123a8091e4be0aa4a03e4d601ec641c327398315f62b64" dependencies = [ "winapi-util", ] [[package]] name = "trybuild" version = "1.0.85" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "196a58260a906cedb9bf6d8034b6379d0c11f552416960452f267402ceeddff1" dependencies = [ "basic-toml", "dissimilar", "glob", "once_cell", "serde", "serde_derive", "serde_json", "termcolor", ] [[package]] name = "unicode-ident" version = "1.0.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b" [[package]] name = "winapi" version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" dependencies = [ "winapi-i686-pc-windows-gnu", "winapi-x86_64-pc-windows-gnu", ] [[package]] name = "winapi-i686-pc-windows-gnu" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" [[package]] name = "winapi-util" version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f29e6f9198ba0d26b4c9f07dbe6f9ed633e1f3d5b8b414090084349e46a52596" dependencies = [ "winapi", ] [[package]] name = "winapi-x86_64-pc-windows-gnu" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" dyn-clone-1.0.16/Cargo.toml0000644000000022260000000000100110110ustar # 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" rust-version = "1.45" name = "dyn-clone" version = "1.0.16" authors = ["David Tolnay "] description = "Clone trait that is object-safe" documentation = "https://docs.rs/dyn-clone" readme = "README.md" keywords = [ "dyn", "clone", "trait-object", ] categories = [ "rust-patterns", "no-std", ] license = "MIT OR Apache-2.0" repository = "https://github.com/dtolnay/dyn-clone" [package.metadata.docs.rs] rustdoc-args = ["--generate-link-to-definition"] targets = ["x86_64-unknown-linux-gnu"] [lib] doc-scrape-examples = false [dev-dependencies.rustversion] version = "1.0" [dev-dependencies.trybuild] version = "1.0.66" features = ["diff"] dyn-clone-1.0.16/Cargo.toml.orig000064400000000000000000000011771046102023000144760ustar 00000000000000[package] name = "dyn-clone" version = "1.0.16" authors = ["David Tolnay "] categories = ["rust-patterns", "no-std"] description = "Clone trait that is object-safe" documentation = "https://docs.rs/dyn-clone" edition = "2018" keywords = ["dyn", "clone", "trait-object"] license = "MIT OR Apache-2.0" repository = "https://github.com/dtolnay/dyn-clone" rust-version = "1.45" [dev-dependencies] rustversion = "1.0" trybuild = { version = "1.0.66", features = ["diff"] } [lib] doc-scrape-examples = false [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] rustdoc-args = ["--generate-link-to-definition"] dyn-clone-1.0.16/LICENSE-APACHE000064400000000000000000000227731046102023000135400ustar 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 dyn-clone-1.0.16/LICENSE-MIT000064400000000000000000000017771046102023000132510ustar 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. dyn-clone-1.0.16/README.md000064400000000000000000000052521046102023000130640ustar 00000000000000Clone trait that is object-safe =============================== [github](https://github.com/dtolnay/dyn-clone) [crates.io](https://crates.io/crates/dyn-clone) [docs.rs](https://docs.rs/dyn-clone) [build status](https://github.com/dtolnay/dyn-clone/actions?query=branch%3Amaster) This crate provides a `DynClone` trait that can be used in trait objects, and a `clone_box` function that can clone any sized or dynamically sized implementation of `DynClone`. Types that implement the standard library's [`std::clone::Clone`] trait are automatically usable by a `DynClone` trait object. [`std::clone::Clone`]: https://doc.rust-lang.org/std/clone/trait.Clone.html The signature of `clone_box` is: ```rust fn clone_box(t: &T) -> Box where T: ?Sized + DynClone ``` ## Example ```rust use dyn_clone::DynClone; trait MyTrait: DynClone { fn recite(&self); } impl MyTrait for String { fn recite(&self) { println!("{} ♫", self); } } fn main() { let line = "The slithy structs did gyre and gimble the namespace"; // Build a trait object holding a String. // This requires String to implement MyTrait and std::clone::Clone. let x: Box = Box::new(String::from(line)); x.recite(); // The type of x2 is a Box cloned from x. let x2 = dyn_clone::clone_box(&*x); x2.recite(); } ``` This crate includes a macro for generating the implementation `impl std::clone::Clone for Box` in terms of `dyn_clone::clone_box`: ```rust // As before. trait MyTrait: DynClone { /* ... */ } dyn_clone::clone_trait_object!(MyTrait); // Now data structures containing Box can derive Clone: #[derive(Clone)] struct Container { trait_object: Box, } ```
#### License Licensed under either of Apache License, Version 2.0 or MIT license at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this crate by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. dyn-clone-1.0.16/examples/readme.rs000064400000000000000000000010701046102023000152200ustar 00000000000000use dyn_clone::DynClone; trait MyTrait: DynClone { fn recite(&self); } impl MyTrait for String { fn recite(&self) { println!("{} ♫", self); } } fn main() { let line = "The slithy structs did gyre and gimble the namespace"; // Build a trait object holding a String. // This requires String to implement MyTrait and std::clone::Clone. let x: Box = Box::new(String::from(line)); x.recite(); // The type of x2 is a Box cloned from x. let x2 = dyn_clone::clone_box(&*x); x2.recite(); } dyn-clone-1.0.16/src/lib.rs000064400000000000000000000137201046102023000135070ustar 00000000000000//! [![github]](https://github.com/dtolnay/dyn-clone) [![crates-io]](https://crates.io/crates/dyn-clone) [![docs-rs]](https://docs.rs/dyn-clone) //! //! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github //! [crates-io]: https://img.shields.io/badge/crates.io-fc8d62?style=for-the-badge&labelColor=555555&logo=rust //! [docs-rs]: https://img.shields.io/badge/docs.rs-66c2a5?style=for-the-badge&labelColor=555555&logo=docs.rs //! //!
//! //! This crate provides a [`DynClone`] trait that can be used in trait objects, //! and a [`clone_box`] function that can clone any sized or dynamically sized //! implementation of `DynClone`. Types that implement the standard library's //! [`std::clone::Clone`] trait are automatically usable by a `DynClone` trait //! object. //! //! # Example //! //! ``` //! use dyn_clone::DynClone; //! //! trait MyTrait: DynClone { //! fn recite(&self); //! } //! //! impl MyTrait for String { //! fn recite(&self) { //! println!("{} ♫", self); //! } //! } //! //! fn main() { //! let line = "The slithy structs did gyre and gimble the namespace"; //! //! // Build a trait object holding a String. //! // This requires String to implement MyTrait and std::clone::Clone. //! let x: Box = Box::new(String::from(line)); //! //! x.recite(); //! //! // The type of x2 is a Box cloned from x. //! let x2 = dyn_clone::clone_box(&*x); //! //! x2.recite(); //! } //! ``` //! //! This crate includes a macro for concisely implementing `impl //! std::clone::Clone for Box` in terms of `dyn_clone::clone_box`. //! //! ``` //! # use dyn_clone::DynClone; //! # //! // As before. //! trait MyTrait: DynClone { //! /* ... */ //! } //! //! dyn_clone::clone_trait_object!(MyTrait); //! //! // Now data structures containing Box can derive Clone: //! #[derive(Clone)] //! struct Container { //! trait_object: Box, //! } //! ``` //! //! The `clone_trait_object!` macro expands to just the following, which you can //! handwrite instead if you prefer: //! //! ``` //! # use dyn_clone::DynClone; //! # //! # trait MyTrait: DynClone {} //! # //! impl Clone for Box { //! fn clone(&self) -> Self { //! dyn_clone::clone_box(&**self) //! } //! } //! //! // and similar for Box, Box, Box //! ``` #![doc(html_root_url = "https://docs.rs/dyn-clone/1.0.16")] #![no_std] #![allow( clippy::missing_panics_doc, clippy::needless_doctest_main, clippy::ptr_as_ptr )] extern crate alloc; #[cfg(doc)] extern crate core as std; #[macro_use] mod macros; // Not public API. #[doc(hidden)] pub mod __private { #[doc(hidden)] pub use core::clone::Clone; #[doc(hidden)] pub use core::marker::{Send, Sync}; #[doc(hidden)] pub type Box = alloc::boxed::Box; } mod sealed { pub trait Sealed {} impl Sealed for T {} impl Sealed for str {} impl Sealed for [T] {} pub struct Private; } use crate::sealed::{Private, Sealed}; use alloc::boxed::Box; use alloc::rc::Rc; use alloc::sync::Arc; /// This trait is implemented by any type that implements [`std::clone::Clone`]. pub trait DynClone: Sealed { // Not public API #[doc(hidden)] fn __clone_box(&self, _: Private) -> *mut (); } /// `&T` —▸ `T` pub fn clone(t: &T) -> T where T: DynClone, { unsafe { *Box::from_raw(::__clone_box(t, Private) as *mut T) } } /// `&T` —▸ `Box` pub fn clone_box(t: &T) -> Box where T: ?Sized + DynClone, { let mut fat_ptr = t as *const T; unsafe { let data_ptr = &mut fat_ptr as *mut *const T as *mut *mut (); assert_eq!(*data_ptr as *const (), t as *const T as *const ()); *data_ptr = ::__clone_box(t, Private); } unsafe { Box::from_raw(fat_ptr as *mut T) } } /// `&mut Arc` —▸ `&mut T` pub fn arc_make_mut(arc: &mut Arc) -> &mut T where T: ?Sized + DynClone, { // Atomic. Find out whether the Arc in the argument is the single holder of // a reference count (strong or weak) on the target object. If yes, it is // guaranteed to remain that way throughout the rest of this function // because no other threads could bump the reference count through any other // Arc (because no others exist) or through this Arc (because the current // thread holds an exclusive borrow of it). let is_unique = Arc::get_mut(arc).is_some(); if !is_unique { // Non-atomic. let clone = Arc::from(clone_box(&**arc)); // Atomic. Check the reference counts again to find out whether the old // object needs to be dropped. Probably not, but it can happen if all // the other holders of a reference count went away during the time that // the clone operation took. *arc = clone; } // Non-atomic. TODO: replace with Arc::get_mut_unchecked when stable. let ptr = Arc::as_ptr(arc) as *mut T; unsafe { &mut *ptr } } /// `&mut Rc` —▸ `&mut T` pub fn rc_make_mut(rc: &mut Rc) -> &mut T where T: ?Sized + DynClone, { let is_unique = Rc::get_mut(rc).is_some(); if !is_unique { let clone = Rc::from(clone_box(&**rc)); *rc = clone; } let ptr = Rc::as_ptr(rc) as *mut T; unsafe { &mut *ptr } } impl DynClone for T where T: Clone, { fn __clone_box(&self, _: Private) -> *mut () { Box::::into_raw(Box::new(self.clone())) as *mut () } } impl DynClone for str { fn __clone_box(&self, _: Private) -> *mut () { Box::::into_raw(Box::from(self)) as *mut () } } impl DynClone for [T] where T: Clone, { fn __clone_box(&self, _: Private) -> *mut () { Box::<[T]>::into_raw(self.iter().cloned().collect()) as *mut () } } dyn-clone-1.0.16/src/macros.rs000064400000000000000000000075001046102023000142240ustar 00000000000000use crate::DynClone; /// Implement the standard library `Clone` for a trait object that has /// `DynClone` as a supertrait. /// /// ``` /// use dyn_clone::DynClone; /// /// trait MyTrait: DynClone { /// /* ... */ /// } /// /// dyn_clone::clone_trait_object!(MyTrait); /// /// // Now data structures containing Box can derive Clone. /// #[derive(Clone)] /// struct Container { /// trait_object: Box, /// } /// ``` /// /// The macro supports traits that have type parameters and/or `where` clauses. /// /// ``` /// use dyn_clone::DynClone; /// use std::io::Read; /// /// trait Difficult: DynClone where R: Read { /// /* ... */ /// } /// /// dyn_clone::clone_trait_object!( Difficult where R: Read); /// ``` #[macro_export] macro_rules! clone_trait_object { ($($path:tt)+) => { $crate::__internal_clone_trait_object!(begin $($path)+); }; } #[doc(hidden)] #[macro_export] macro_rules! __internal_clone_trait_object { // Invocation started with `<`, parse generics. (begin < $($rest:tt)*) => { $crate::__internal_clone_trait_object!(generics () () $($rest)*); }; // Invocation did not start with `<`. (begin $first:tt $($rest:tt)*) => { $crate::__internal_clone_trait_object!(path () ($first) $($rest)*); }; // End of generics. (generics ($($generics:tt)*) () > $($rest:tt)*) => { $crate::__internal_clone_trait_object!(path ($($generics)*) () $($rest)*); }; // Generics open bracket. (generics ($($generics:tt)*) ($($brackets:tt)*) < $($rest:tt)*) => { $crate::__internal_clone_trait_object!(generics ($($generics)* <) ($($brackets)* <) $($rest)*); }; // Generics close bracket. (generics ($($generics:tt)*) (< $($brackets:tt)*) > $($rest:tt)*) => { $crate::__internal_clone_trait_object!(generics ($($generics)* >) ($($brackets)*) $($rest)*); }; // Token inside of generics. (generics ($($generics:tt)*) ($($brackets:tt)*) $first:tt $($rest:tt)*) => { $crate::__internal_clone_trait_object!(generics ($($generics)* $first) ($($brackets)*) $($rest)*); }; // End with `where` clause. (path ($($generics:tt)*) ($($path:tt)*) where $($rest:tt)*) => { $crate::__internal_clone_trait_object!(impl ($($generics)*) ($($path)*) ($($rest)*)); }; // End without `where` clause. (path ($($generics:tt)*) ($($path:tt)*)) => { $crate::__internal_clone_trait_object!(impl ($($generics)*) ($($path)*) ()); }; // Token inside of path. (path ($($generics:tt)*) ($($path:tt)*) $first:tt $($rest:tt)*) => { $crate::__internal_clone_trait_object!(path ($($generics)*) ($($path)* $first) $($rest)*); }; // The impl. (impl ($($generics:tt)*) ($($path:tt)*) ($($bound:tt)*)) => { impl<'clone, $($generics)*> $crate::__private::Clone for $crate::__private::Box where $($bound)* { fn clone(&self) -> Self { $crate::clone_box(&**self) } } impl<'clone, $($generics)*> $crate::__private::Clone for $crate::__private::Box where $($bound)* { fn clone(&self) -> Self { $crate::clone_box(&**self) } } impl<'clone, $($generics)*> $crate::__private::Clone for $crate::__private::Box where $($bound)* { fn clone(&self) -> Self { $crate::clone_box(&**self) } } impl<'clone, $($generics)*> $crate::__private::Clone for $crate::__private::Box where $($bound)* { fn clone(&self) -> Self { $crate::clone_box(&**self) } } }; } clone_trait_object!(DynClone); dyn-clone-1.0.16/tests/compiletest.rs000064400000000000000000000002461046102023000156430ustar 00000000000000#[rustversion::attr(not(nightly), ignore)] #[cfg_attr(miri, ignore)] #[test] fn ui() { let t = trybuild::TestCases::new(); t.compile_fail("tests/ui/*.rs"); } dyn-clone-1.0.16/tests/macros.rs000064400000000000000000000021121046102023000145710ustar 00000000000000#![allow(clippy::extra_unused_type_parameters)] use dyn_clone::{clone_trait_object, DynClone}; fn assert_clone() {} #[test] fn test_plain() { trait Trait: DynClone {} clone_trait_object!(Trait); assert_clone::>(); assert_clone::>(); assert_clone::>(); assert_clone::>(); } #[test] fn test_type_parameter() { trait Trait: DynClone {} clone_trait_object!( Trait); assert_clone::>>(); } #[test] fn test_generic_bound() { trait Trait, U>: DynClone {} clone_trait_object!(, U> Trait); assert_clone::>>(); } #[test] fn test_where_clause() { trait Trait: DynClone where T: Clone, { } clone_trait_object!( Trait where T: Clone); assert_clone::>>(); } #[test] fn test_lifetime() { trait Trait<'a>: DynClone {} clone_trait_object!(<'a> Trait<'a>); assert_clone::>(); } dyn-clone-1.0.16/tests/trait.rs000064400000000000000000000027061046102023000144410ustar 00000000000000use dyn_clone::DynClone; use std::fmt::{self, Display}; use std::sync::{Arc, Mutex}; struct Log { id: u64, events: Arc>>, } impl Clone for Log { fn clone(&self) -> Self { Log { id: self.id + 1, events: self.events.clone(), } } } impl Display for Log { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write!(formatter, "id={}", self.id) } } impl Drop for Log { fn drop(&mut self) { self.events .lock() .unwrap() .push(format!("dropping {}", self)); } } #[test] fn clone_sized() { let arc = Arc::new(0); assert_eq!(Arc::strong_count(&arc), 1); let c = dyn_clone::clone(&arc); assert_eq!(Arc::strong_count(&arc), 2); drop(c); assert_eq!(Arc::strong_count(&arc), 1); } #[test] fn clone_trait_object() { trait MyTrait: Display + Sync + DynClone {} impl MyTrait for Log {} let events = Arc::new(Mutex::new(Vec::new())); let mut expected = Vec::new(); { let b11: Box = Box::new(Log { id: 11, events: events.clone(), }); let b12 = dyn_clone::clone_box(&*b11); assert_eq!(b11.to_string(), "id=11"); assert_eq!(b12.to_string(), "id=12"); expected.push("dropping id=12".to_owned()); expected.push("dropping id=11".to_owned()); } assert_eq!(*events.lock().unwrap(), expected); } dyn-clone-1.0.16/tests/ui/missing-supertrait.rs000064400000000000000000000001151046102023000175740ustar 00000000000000pub trait MyTrait {} dyn_clone::clone_trait_object!(MyTrait); fn main() {} dyn-clone-1.0.16/tests/ui/missing-supertrait.stderr000064400000000000000000000075571046102023000204740ustar 00000000000000error[E0277]: the trait bound `dyn MyTrait: Clone` is not satisfied --> tests/ui/missing-supertrait.rs:3:1 | 3 | dyn_clone::clone_trait_object!(MyTrait); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | | | the trait `Clone` is not implemented for `dyn MyTrait` | required by a bound introduced by this call | = help: the following other types implement trait `DynClone`: str [T] = note: required for `dyn MyTrait` to implement `DynClone` note: required by a bound in `clone_box` --> src/lib.rs | | pub fn clone_box(t: &T) -> Box | --------- required by a bound in this function | where | T: ?Sized + DynClone, | ^^^^^^^^ required by this bound in `clone_box` = note: this error originates in the macro `$crate::__internal_clone_trait_object` which comes from the expansion of the macro `dyn_clone::clone_trait_object` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: the trait bound `dyn MyTrait + Send: Clone` is not satisfied --> tests/ui/missing-supertrait.rs:3:1 | 3 | dyn_clone::clone_trait_object!(MyTrait); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | | | the trait `Clone` is not implemented for `dyn MyTrait + Send` | required by a bound introduced by this call | = help: the following other types implement trait `DynClone`: str [T] = note: required for `dyn MyTrait + Send` to implement `DynClone` note: required by a bound in `clone_box` --> src/lib.rs | | pub fn clone_box(t: &T) -> Box | --------- required by a bound in this function | where | T: ?Sized + DynClone, | ^^^^^^^^ required by this bound in `clone_box` = note: this error originates in the macro `$crate::__internal_clone_trait_object` which comes from the expansion of the macro `dyn_clone::clone_trait_object` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: the trait bound `dyn MyTrait + Sync: Clone` is not satisfied --> tests/ui/missing-supertrait.rs:3:1 | 3 | dyn_clone::clone_trait_object!(MyTrait); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | | | the trait `Clone` is not implemented for `dyn MyTrait + Sync` | required by a bound introduced by this call | = help: the following other types implement trait `DynClone`: str [T] = note: required for `dyn MyTrait + Sync` to implement `DynClone` note: required by a bound in `clone_box` --> src/lib.rs | | pub fn clone_box(t: &T) -> Box | --------- required by a bound in this function | where | T: ?Sized + DynClone, | ^^^^^^^^ required by this bound in `clone_box` = note: this error originates in the macro `$crate::__internal_clone_trait_object` which comes from the expansion of the macro `dyn_clone::clone_trait_object` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: the trait bound `dyn MyTrait + Send + Sync: Clone` is not satisfied --> tests/ui/missing-supertrait.rs:3:1 | 3 | dyn_clone::clone_trait_object!(MyTrait); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | | | the trait `Clone` is not implemented for `dyn MyTrait + Send + Sync` | required by a bound introduced by this call | = help: the following other types implement trait `DynClone`: str [T] = note: required for `dyn MyTrait + Send + Sync` to implement `DynClone` note: required by a bound in `clone_box` --> src/lib.rs | | pub fn clone_box(t: &T) -> Box | --------- required by a bound in this function | where | T: ?Sized + DynClone, | ^^^^^^^^ required by this bound in `clone_box` = note: this error originates in the macro `$crate::__internal_clone_trait_object` which comes from the expansion of the macro `dyn_clone::clone_trait_object` (in Nightly builds, run with -Z macro-backtrace for more info)