├── .gitignore ├── .mergify.yml ├── .rustfmt.toml ├── Cargo.toml ├── LICENSE-APACHE.txt ├── LICENSE-MIT.txt ├── README.md ├── azure-pipelines.yml └── src └── lib.rs /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | **/*.rs.bk 3 | Cargo.lock 4 | -------------------------------------------------------------------------------- /.mergify.yml: -------------------------------------------------------------------------------- 1 | pull_request_rules: 2 | - name: automatic merge 3 | conditions: 4 | - base=master 5 | - status-success=tests 6 | - "label!=work in progress" 7 | - "#approved-reviews-by>=1" 8 | - "#review-requested=0" 9 | - "#changes-requested-reviews-by=0" 10 | actions: 11 | merge: 12 | method: merge 13 | strict: smart 14 | delete_head_branch: {} 15 | - name: automatic merge 16 | conditions: 17 | - base=master 18 | - status-success=tests 19 | - "label!=work in progress" 20 | - author=alecmocatta # https://github.com/Mergifyio/mergify-engine/issues/451 21 | - "#review-requested=0" 22 | - "#changes-requested-reviews-by=0" 23 | actions: 24 | merge: 25 | method: merge 26 | strict: smart 27 | delete_head_branch: {} 28 | - name: dismiss reviews 29 | conditions: [] 30 | actions: 31 | dismiss_reviews: {} 32 | - name: auto add wip label 33 | conditions: 34 | - "title~=^WIP: .*" 35 | actions: 36 | label: 37 | add: ["work in progress"] 38 | - name: auto remove wip label 39 | conditions: 40 | - "-title~=^WIP: .*" 41 | actions: 42 | label: 43 | remove: ["work in progress"] 44 | -------------------------------------------------------------------------------- /.rustfmt.toml: -------------------------------------------------------------------------------- 1 | hard_tabs = true 2 | imports_layout = "Horizontal" 3 | merge_imports = true 4 | fn_args_layout = "Compressed" 5 | use_field_init_shorthand = true 6 | 7 | # To enable when stable 8 | # wrap_comments = true # https://github.com/rust-lang/rustfmt/issues/3347 9 | # reorder_impl_items = true # https://github.com/rust-lang/rustfmt/issues/3363 10 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "replace_with" 3 | version = "0.1.8" 4 | license = "MIT OR Apache-2.0" 5 | authors = ["Alec Mocatta "] 6 | categories = ["rust-patterns"] 7 | keywords = ["mutability"] 8 | description = """ 9 | Temporarily take ownership of a value at a mutable location, and replace it with a new value based on the old one. 10 | """ 11 | repository = "https://github.com/alecmocatta/replace_with" 12 | homepage = "https://github.com/alecmocatta/replace_with" 13 | documentation = "https://docs.rs/replace_with" 14 | readme = "README.md" 15 | edition = "2018" 16 | 17 | [badges] 18 | azure-devops = { project = "alecmocatta/replace_with", pipeline = "tests", build = "11" } 19 | maintenance = { status = "actively-developed" } 20 | 21 | [features] 22 | default = ["std"] 23 | std = [] 24 | nightly = [] 25 | panic_abort = [] 26 | -------------------------------------------------------------------------------- /LICENSE-APACHE.txt: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-MIT.txt: -------------------------------------------------------------------------------- 1 | Permission is hereby granted, free of charge, to any 2 | person obtaining a copy of this software and associated 3 | documentation files (the "Software"), to deal in the 4 | Software without restriction, including without 5 | limitation the rights to use, copy, modify, merge, 6 | publish, distribute, sublicense, and/or sell copies of 7 | the Software, and to permit persons to whom the Software 8 | is furnished to do so, subject to the following 9 | conditions: 10 | 11 | The above copyright notice and this permission notice 12 | shall be included in all copies or substantial portions 13 | of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 16 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 17 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 18 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 19 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 20 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 21 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 22 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 23 | DEALINGS IN THE SOFTWARE. 24 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # replace_with 2 | 3 | [![Crates.io](https://img.shields.io/crates/v/replace_with.svg?maxAge=86400)](https://crates.io/crates/replace_with) 4 | [![MIT / Apache 2.0 licensed](https://img.shields.io/crates/l/replace_with.svg?maxAge=2592000)](#License) 5 | [![Build Status](https://dev.azure.com/alecmocatta/replace_with/_apis/build/status/tests?branchName=master)](https://dev.azure.com/alecmocatta/replace_with/_build?definitionId=11) 6 | 7 | [📖 Docs](https://docs.rs/replace_with) | [💬 Chat](https://constellation.zulipchat.com/#narrow/stream/213236-subprojects) 8 | 9 | Temporarily take ownership of a value at a mutable location, and replace it with a new value based on the old one. 10 | 11 | This crate provides the function [`replace_with()`](https://docs.rs/replace_with/0.1/replace_with/fn.replace_with.html), which is like [`std::mem::replace()`](https://doc.rust-lang.org/std/mem/fn.replace.html) except it allows the replacement value to be mapped from the original value. 12 | 13 | See [RFC 1736](https://github.com/rust-lang/rfcs/pull/1736) for a lot of discussion as to its merits. It was never merged, and the desired ability to temporarily move out of `&mut T` doesn't exist yet, so this crate is my interim solution. 14 | 15 | It's very akin to [`take_mut`](https://github.com/Sgeo/take_mut), though uses `Drop` instead of [`std::panic::catch_unwind()`](https://doc.rust-lang.org/std/panic/fn.catch_unwind.html) to react to unwinding, which avoids the optimisation barrier of calling the `extern "C" __rust_maybe_catch_panic()`. As such it's up to ∞x faster. The API also attempts to make slightly more explicit the behavior on panic – [`replace_with()`](https://docs.rs/replace_with/0.1/replace_with/fn.replace_with.html) accepts two closures such that aborting in the "standard case" where the mapping closure (`FnOnce(T) -> T`) panics (as [`take_mut::take()`](https://docs.rs/take_mut/0.2.2/take_mut/fn.take.html) does) is avoided. If the second closure (`FnOnce() -> T`) panics, however, then it does indeed abort. The "abort on first panic" behaviour is available with [`replace_with_or_abort()`](https://docs.rs/replace_with/0.1/replace_with/fn.replace_with_or_abort.html). 16 | 17 | ## Example 18 | 19 | Consider this motivating example: 20 | 21 | ```rust 22 | enum States { 23 | A(String), 24 | B(String), 25 | } 26 | 27 | impl States { 28 | fn poll(&mut self) { 29 | // error[E0507]: cannot move out of borrowed content 30 | *self = match *self { 31 | // ^^^^^ cannot move out of borrowed content 32 | States::A(a) => States::B(a), 33 | States::B(a) => States::A(a), 34 | }; 35 | } 36 | } 37 | ``` 38 | 39 | Depending on context this can be quite tricky to work around. With this crate, however: 40 | 41 | ```rust 42 | enum States { 43 | A(String), 44 | B(String), 45 | } 46 | 47 | impl States { 48 | fn poll(&mut self) { 49 | replace_with_or_abort(self, |self_| match self_ { 50 | States::A(a) => States::B(a), 51 | States::B(a) => States::A(a), 52 | }); 53 | } 54 | } 55 | ``` 56 | 57 | Huzzah! 58 | 59 | ## `no_std` 60 | 61 | To use `replace_with` with `no_std` you have to disable the `std` feature, which is active by default, by specifying your dependency to it like this: 62 | 63 | ```toml 64 | # Cargo.toml 65 | 66 | replace_with = { version = "0.1", default-features = false } 67 | ``` 68 | 69 | The `nightly` feature can be enabled to use [`core::intrinsics::abort()`](https://doc.rust-lang.org/core/intrinsics/fn.abort.html) instead of triggering an abort via [`std::process::abort()`](https://doc.rust-lang.org/std/process/fn.abort.html) or [`extern "C" fn abort() { panic!() } abort()`](https://doc.rust-lang.org/reference/items/functions.html#r-items.fn.extern.abort). 70 | 71 | ## License 72 | Licensed under either of 73 | 74 | * Apache License, Version 2.0, ([LICENSE-APACHE.txt](LICENSE-APACHE.txt) or http://www.apache.org/licenses/LICENSE-2.0) 75 | * MIT license ([LICENSE-MIT.txt](LICENSE-MIT.txt) or http://opensource.org/licenses/MIT) 76 | 77 | at your option. 78 | 79 | 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. 80 | -------------------------------------------------------------------------------- /azure-pipelines.yml: -------------------------------------------------------------------------------- 1 | trigger: ["master"] 2 | pr: ["master"] 3 | 4 | resources: 5 | repositories: 6 | - repository: templates 7 | type: github 8 | name: alecmocatta/azure-pipeline-templates 9 | endpoint: alecmocatta 10 | 11 | jobs: 12 | - template: rust.yml@templates 13 | parameters: 14 | endpoint: alecmocatta 15 | default: 16 | rust_toolchain: 1.21.0 stable beta nightly 17 | rust_lint_toolchain: nightly-2020-07-12 18 | rust_flags: '' 19 | rust_features: ';default;all' 20 | rust_target_check: '' 21 | rust_target_build: '' 22 | rust_target_run: '' 23 | matrix: 24 | windows: 25 | imageName: 'windows-latest' 26 | rust_target_run: 'x86_64-pc-windows-msvc' 27 | mac: 28 | imageName: 'macos-latest' 29 | rust_target_run: 'x86_64-apple-darwin' 30 | linux: 31 | imageName: 'ubuntu-latest' 32 | rust_target_run: 'x86_64-unknown-linux-gnu' 33 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! Temporarily take ownership of a value at a mutable location, and replace it with a new value 2 | //! based on the old one. 3 | //! 4 | //!

5 | //! 📦  Crates.io  │  📑  GitHub  │  💬  Chat 6 | //!

7 | //! 8 | //! This crate provides the function [`replace_with()`], which is like [`std::mem::replace()`] 9 | //! except it allows the replacement value to be mapped from the original value. 10 | //! 11 | //! See [RFC 1736](https://github.com/rust-lang/rfcs/pull/1736) for a lot of discussion as to its 12 | //! merits. It was never merged, and the desired ability to temporarily move out of `&mut T` doesn't 13 | //! exist yet, so this crate is my interim solution. 14 | //! 15 | //! It's very akin to [`take_mut`](https://github.com/Sgeo/take_mut), though uses `Drop` instead of 16 | //! [`std::panic::catch_unwind()`] to react to unwinding, which avoids the optimisation barrier of 17 | //! calling the `extern "C" __rust_maybe_catch_panic()`. As such it's up to ∞x faster. The API also 18 | //! attempts to make slightly more explicit the behavior on panic – [`replace_with()`] accepts two 19 | //! closures such that aborting in the "standard case" where the mapping closure (`FnOnce(T) -> T`) 20 | //! panics (as [`take_mut::take()`](https://docs.rs/take_mut/0.2.2/take_mut/fn.take.html) does) is 21 | //! avoided. If the second closure (`FnOnce() -> T`) panics, however, then it does indeed abort. 22 | //! The "abort on first panic" behaviour is available with [`replace_with_or_abort()`]. 23 | //! 24 | //! # Example 25 | //! 26 | //! Consider this motivating example: 27 | //! 28 | //! ```compile_fail 29 | //! # use replace_with::*; 30 | //! enum States { 31 | //! A(String), 32 | //! B(String), 33 | //! } 34 | //! 35 | //! impl States { 36 | //! fn poll(&mut self) { 37 | //! // error[E0507]: cannot move out of borrowed content 38 | //! *self = match *self { 39 | //! // ^^^^^ cannot move out of borrowed content 40 | //! States::A(a) => States::B(a), 41 | //! States::B(a) => States::A(a), 42 | //! }; 43 | //! } 44 | //! } 45 | //! ``` 46 | //! 47 | //! Depending on context this can be quite tricky to work around. With this crate, however: 48 | //! 49 | //! ``` 50 | //! # use replace_with::*; 51 | //! enum States { 52 | //! A(String), 53 | //! B(String), 54 | //! } 55 | //! 56 | //! # #[cfg(any(feature = "std", feature = "nightly"))] 57 | //! impl States { 58 | //! fn poll(&mut self) { 59 | //! replace_with_or_abort(self, |self_| match self_ { 60 | //! States::A(a) => States::B(a), 61 | //! States::B(a) => States::A(a), 62 | //! }); 63 | //! } 64 | //! } 65 | //! ``` 66 | //! 67 | //! Huzzah! 68 | //! 69 | //! # `no_std` 70 | //! 71 | //! To use `replace_with` with `no_std` you have to disable the `std` feature, which is active by 72 | //! default, by specifying your dependency to it like this: 73 | //! 74 | //! ```toml 75 | //! # Cargo.toml 76 | //! 77 | //! replace_with = { version = "0.1", default-features = false } 78 | //! ``` 79 | //! 80 | //! The `nightly` feature can be enabled to use [`core::intrinsics::abort()`](https://doc.rust-lang.org/core/intrinsics/fn.abort.html) 81 | //! instead of triggering an abort via [`std::process::abort()`](https://doc.rust-lang.org/std/process/fn.abort.html) 82 | //! or [`extern "C" fn abort() { panic!() } abort()`](https://doc.rust-lang.org/reference/items/functions.html#r-items.fn.extern.abort). 83 | 84 | #![cfg_attr(not(feature = "std"), no_std)] 85 | #![cfg_attr(feature = "nightly", feature(core_intrinsics))] 86 | #![doc(html_root_url = "https://docs.rs/replace_with/0.1.8")] 87 | #![warn( 88 | missing_copy_implementations, 89 | missing_debug_implementations, 90 | missing_docs, 91 | trivial_casts, 92 | trivial_numeric_casts, 93 | unused_import_braces, 94 | unused_qualifications, 95 | unused_results, 96 | // clippy::pedantic 97 | )] 98 | // #![allow(clippy::inline_always)] 99 | 100 | #[cfg(not(feature = "std"))] 101 | use core as std; 102 | 103 | use std::{mem, ptr}; 104 | 105 | #[cfg(feature = "nightly")] 106 | #[inline(always)] 107 | fn abort() -> ! { 108 | unsafe { std::intrinsics::abort() } 109 | } 110 | 111 | #[cfg(all(not(feature = "nightly"), feature = "std"))] 112 | use std::process::abort; 113 | 114 | // TODO: https://github.com/rust-lang/rfcs/issues/2512 115 | #[cfg(all(not(feature = "nightly"), not(feature = "std")))] 116 | #[inline(always)] 117 | fn abort() -> ! { 118 | if cfg!(panic = "abort") { 119 | panic!() 120 | } else { 121 | // https://doc.rust-lang.org/reference/items/functions.html#r-items.fn.extern.abort 122 | #[inline(always)] 123 | extern "C" fn abort() -> ! { 124 | panic!(); 125 | } 126 | on_unwind(|| abort(), || loop {}) 127 | } 128 | } 129 | 130 | // TODO: https://github.com/rust-lang/rust/issues/130338 131 | #[inline(always)] 132 | fn abort_unwind R, R>(f: F) -> R { 133 | on_unwind(f, || abort()) 134 | } 135 | 136 | struct OnDrop(mem::ManuallyDrop); 137 | impl Drop for OnDrop { 138 | #[inline(always)] 139 | fn drop(&mut self) { 140 | (unsafe { ptr::read(&*self.0) })(); 141 | } 142 | } 143 | 144 | #[inline(always)] 145 | fn on_unwind_inner T, T, P: FnOnce()>(f: F, p: P) -> (T, P) { 146 | if cfg!(panic = "abort") { 147 | return (f(), p); 148 | } 149 | let p = OnDrop(mem::ManuallyDrop::new(p)); 150 | let t = f(); 151 | let mut p = mem::ManuallyDrop::new(p); 152 | (t, unsafe { mem::ManuallyDrop::take(&mut p.0) }) 153 | } 154 | 155 | #[doc(hidden)] 156 | #[inline(always)] 157 | pub fn on_unwind T, T, P: FnOnce()>(f: F, p: P) -> T { 158 | on_unwind_inner(f, p).0 159 | } 160 | 161 | #[doc(hidden)] 162 | #[inline(always)] 163 | pub fn on_return_or_unwind T, T, P: FnOnce()>(f: F, p: P) -> T { 164 | let _p = OnDrop(mem::ManuallyDrop::new(p)); 165 | f() 166 | } 167 | 168 | /// Temporarily takes ownership of a value at a mutable location, and replace it with a new value 169 | /// based on the old one. 170 | /// 171 | /// We move out of the reference temporarily, to apply a closure `f`, returning a new value, which 172 | /// is then placed at the original value's location. 173 | /// 174 | /// # An important note 175 | /// 176 | /// On panic (or to be more precise, unwinding) of the closure `f`, `default` will be called to 177 | /// provide a replacement value. `default` should not panic – doing so will abort the process. 178 | /// 179 | /// # Example 180 | /// 181 | /// ``` 182 | /// # use replace_with::*; 183 | /// enum States { 184 | /// A(String), 185 | /// B(String), 186 | /// } 187 | /// 188 | /// impl States { 189 | /// fn poll(&mut self) { 190 | /// replace_with( 191 | /// self, 192 | /// || States::A(String::new()), 193 | /// |self_| match self_ { 194 | /// States::A(a) => States::B(a), 195 | /// States::B(a) => States::A(a), 196 | /// }, 197 | /// ); 198 | /// } 199 | /// } 200 | /// ``` 201 | #[inline] 202 | pub fn replace_with T, F: FnOnce(T) -> T>(dest: &mut T, default: D, f: F) { 203 | unsafe { 204 | let old = ptr::read(dest); 205 | let (new, _default) = 206 | on_unwind_inner(move || f(old), || ptr::write(dest, abort_unwind(default))); 207 | ptr::write(dest, new); 208 | } 209 | } 210 | 211 | /// Temporarily takes ownership of a value at a mutable location, and replace it with a new value 212 | /// based on the old one. Replaces with [`Default::default()`] on panic. 213 | /// 214 | /// We move out of the reference temporarily, to apply a closure `f`, returning a new value, which 215 | /// is then placed at the original value's location. 216 | /// 217 | /// # An important note 218 | /// 219 | /// On panic (or to be more precise, unwinding) of the closure `f`, `T::default()` will be called to 220 | /// provide a replacement value. `T::default()` should not panic – doing so will abort the process. 221 | /// 222 | /// Equivalent to `replace_with(dest, T::default, f)`. 223 | /// 224 | /// Differs from `*dest = mem::replace(dest, Default::default())` in that `Default::default()` will 225 | /// only be called on panic. 226 | /// 227 | /// # Example 228 | /// 229 | /// ``` 230 | /// # use replace_with::*; 231 | /// enum States { 232 | /// A(String), 233 | /// B(String), 234 | /// } 235 | /// 236 | /// impl Default for States { 237 | /// fn default() -> Self { 238 | /// States::A(String::new()) 239 | /// } 240 | /// } 241 | /// 242 | /// impl States { 243 | /// fn poll(&mut self) { 244 | /// replace_with_or_default(self, |self_| match self_ { 245 | /// States::A(a) => States::B(a), 246 | /// States::B(a) => States::A(a), 247 | /// }); 248 | /// } 249 | /// } 250 | /// ``` 251 | #[inline] 252 | pub fn replace_with_or_default T>(dest: &mut T, f: F) { 253 | replace_with(dest, T::default, f); 254 | } 255 | 256 | /// Temporarily takes ownership of a value at a mutable location, and replace it with a new value 257 | /// based on the old one. Aborts on panic. 258 | /// 259 | /// We move out of the reference temporarily, to apply a closure `f`, returning a new value, which 260 | /// is then placed at the original value's location. 261 | /// 262 | /// # An important note 263 | /// 264 | /// On panic (or to be more precise, unwinding) of the closure `f`, the process will **abort** to 265 | /// avoid returning control while `dest` is in a potentially invalid state. 266 | /// 267 | /// If this behaviour is undesirable, use [`replace_with`] or [`replace_with_or_default`]. 268 | /// 269 | /// Equivalent to `replace_with(dest, || process::abort(), f)`. 270 | /// 271 | /// # Example 272 | /// 273 | /// ``` 274 | /// # use replace_with::*; 275 | /// enum States { 276 | /// A(String), 277 | /// B(String), 278 | /// } 279 | /// 280 | /// # #[cfg(any(feature = "std", feature = "nightly"))] 281 | /// impl States { 282 | /// fn poll(&mut self) { 283 | /// replace_with_or_abort(self, |self_| match self_ { 284 | /// States::A(a) => States::B(a), 285 | /// States::B(a) => States::A(a), 286 | /// }); 287 | /// } 288 | /// } 289 | /// ``` 290 | #[inline] 291 | pub fn replace_with_or_abort T>(dest: &mut T, f: F) { 292 | replace_with(dest, || abort(), f); 293 | } 294 | 295 | /// Temporarily takes ownership of a value at a mutable location, and replace it with a new value 296 | /// based on the old one. Aborts on panic. 297 | /// 298 | /// We move out of the reference temporarily, to apply a closure `f`, returning a new value, which 299 | /// is then placed at the original value's location. 300 | /// 301 | /// # An important note 302 | /// 303 | /// On panic (or to be more precise, unwinding) of the closure `f`, the process will **abort** to 304 | /// avoid returning control while `dest` is in a potentially invalid state. 305 | /// 306 | /// Unlike for `replace_with_or_abort()` users of `replace_with_or_abort_unchecked()` are expected 307 | /// to have `features = ["panic_abort", …]` defined in `Cargo.toml` 308 | /// and `panic = "abort"` defined in their profile for it to behave semantically correct: 309 | /// 310 | /// ```toml 311 | /// # Cargo.toml 312 | /// 313 | /// [profile.debug] 314 | /// panic = "abort" 315 | /// 316 | /// [profile.release] 317 | /// panic = "abort" 318 | /// ``` 319 | /// 320 | /// # Safety 321 | /// 322 | /// It is crucial to only ever use this function having defined `panic = "abort"`, or else bad 323 | /// things may happen. It's *up to you* to uphold this invariant! 324 | /// 325 | /// If this behaviour is undesirable, use [`replace_with`] or [`replace_with_or_default`]. 326 | /// 327 | /// Equivalent to `replace_with(dest, || process::abort(), f)`. 328 | /// 329 | /// # Example 330 | /// 331 | /// ``` 332 | /// # use replace_with::*; 333 | /// enum States { 334 | /// A(String), 335 | /// B(String), 336 | /// } 337 | /// 338 | /// impl States { 339 | /// fn poll(&mut self) { 340 | /// unsafe { 341 | /// replace_with_or_abort_unchecked(self, |self_| match self_ { 342 | /// States::A(a) => States::B(a), 343 | /// States::B(a) => States::A(a), 344 | /// }); 345 | /// } 346 | /// } 347 | /// } 348 | /// ``` 349 | /// 350 | #[inline] 351 | #[cfg(feature = "panic_abort")] 352 | #[deprecated = "Use replace_with_or_abort() instead, which used cfg!(panic = \"abort\") to guarentee soundness"] 353 | pub unsafe fn replace_with_or_abort_unchecked T>(dest: &mut T, f: F) { 354 | ptr::write(dest, f(ptr::read(dest))); 355 | } 356 | 357 | /// Temporarily takes ownership of a value at a mutable location, and replace it with a new value 358 | /// based on the old one. Lets the closure return a custom value as well. 359 | /// 360 | /// We move out of the reference temporarily, to apply a closure `f`, returning a new value, which 361 | /// is then placed at the original value's location. 362 | /// 363 | /// This is effectively the same function as [`replace_with`], but it lets the closure return a 364 | /// custom value as well. 365 | /// 366 | /// # An important note 367 | /// 368 | /// On panic (or to be more precise, unwinding) of the closure `f`, `default` will be called to 369 | /// provide a replacement value. `default` should not panic – doing so will abort the process. 370 | /// 371 | /// # Example 372 | /// 373 | /// ``` 374 | /// # use replace_with::*; 375 | /// 376 | /// fn take(option: &mut Option) -> Option { 377 | /// replace_with_and_return(option, || None, |option| (option, None)) 378 | /// } 379 | /// 380 | /// let mut opt = Some(3); 381 | /// assert_eq!(take(&mut opt), Some(3)); 382 | /// assert_eq!(take(&mut opt), None); 383 | /// ``` 384 | #[inline] 385 | pub fn replace_with_and_return T, F: FnOnce(T) -> (U, T)>( 386 | dest: &mut T, default: D, f: F, 387 | ) -> U { 388 | unsafe { 389 | let old = ptr::read(dest); 390 | let ((res, new), _default) = 391 | on_unwind_inner(move || f(old), || ptr::write(dest, abort_unwind(default))); 392 | ptr::write(dest, new); 393 | res 394 | } 395 | } 396 | 397 | /// Temporarily takes ownership of a value at a mutable location, and replace it with a new value 398 | /// based on the old one. Replaces with [`Default::default()`] on panic. 399 | /// Lets the closure return a custom value as well. 400 | /// 401 | /// We move out of the reference temporarily, to apply a closure `f`, returning a new value, which 402 | /// is then placed at the original value's location. 403 | /// 404 | /// This is effectively the same function as [`replace_with_or_default`], but it lets the closure 405 | /// return a custom value as well. 406 | /// 407 | /// # An important note 408 | /// 409 | /// On panic (or to be more precise, unwinding) of the closure `f`, `T::default()` will be called to 410 | /// provide a replacement value. `T::default()` should not panic – doing so will abort the process. 411 | /// 412 | /// Equivalent to `replace_with_and_return(dest, T::default, f)`. 413 | /// 414 | /// # Example 415 | /// 416 | /// ``` 417 | /// # use replace_with::*; 418 | /// 419 | /// fn take(option: &mut Option) -> Option { 420 | /// replace_with_or_default_and_return(option, |option| (option, None)) 421 | /// } 422 | /// ``` 423 | #[inline] 424 | pub fn replace_with_or_default_and_return (U, T)>( 425 | dest: &mut T, f: F, 426 | ) -> U { 427 | replace_with_and_return(dest, T::default, f) 428 | } 429 | 430 | /// Temporarily takes ownership of a value at a mutable location, and replace it with a new value 431 | /// based on the old one. Aborts on panic. Lets the closure return a custom value as well. 432 | /// 433 | /// We move out of the reference temporarily, to apply a closure `f`, returning a new value, which 434 | /// is then placed at the original value's location. 435 | /// 436 | /// This is effectively the same function as [`replace_with_or_abort`], but it lets the closure 437 | /// return a custom value as well. 438 | /// 439 | /// # An important note 440 | /// 441 | /// On panic (or to be more precise, unwinding) of the closure `f`, the process will **abort** to 442 | /// avoid returning control while `dest` is in a potentially invalid state. 443 | /// 444 | /// If this behaviour is undesirable, use [`replace_with_and_return`] or 445 | /// [`replace_with_or_default_and_return`] instead. 446 | /// 447 | /// Equivalent to `replace_with_and_return(dest, || process::abort(), f)`. 448 | /// 449 | /// # Example 450 | /// 451 | /// ``` 452 | /// # use replace_with::*; 453 | /// 454 | /// fn take(option: &mut Option) -> Option { 455 | /// replace_with_or_abort_and_return(option, |option| (option, None)) 456 | /// } 457 | /// ``` 458 | #[inline] 459 | pub fn replace_with_or_abort_and_return (U, T)>(dest: &mut T, f: F) -> U { 460 | replace_with_and_return(dest, || abort(), f) 461 | } 462 | 463 | /// Temporarily takes ownership of a value at a mutable location, and replace it with a new value 464 | /// based on the old one. Aborts on panic. Lets the closure return a custom value as well. 465 | /// 466 | /// We move out of the reference temporarily, to apply a closure `f`, returning a new value, which 467 | /// is then placed at the original value's location. 468 | /// 469 | /// This is effectively the same function as [`replace_with_or_abort_unchecked`], but it lets the 470 | /// closure return a custom value as well. 471 | /// 472 | /// # An important note 473 | /// 474 | /// On panic (or to be more precise, unwinding) of the closure `f`, the process will **abort** to 475 | /// avoid returning control while `dest` is in a potentially invalid state. 476 | /// 477 | /// Unlike for `replace_with_or_abort()` users of `replace_with_or_abort_unchecked()` are expected 478 | /// to have `features = ["panic_abort", …]` defined in `Cargo.toml` 479 | /// and `panic = "abort"` defined in their profile for it to behave semantically correct: 480 | /// 481 | /// ```toml 482 | /// # Cargo.toml 483 | /// 484 | /// [profile.debug] 485 | /// panic = "abort" 486 | /// 487 | /// [profile.release] 488 | /// panic = "abort" 489 | /// ``` 490 | /// 491 | /// # Safety 492 | /// 493 | /// It is crucial to only ever use this function having defined `panic = "abort"`, or else bad 494 | /// things may happen. It's *up to you* to uphold this invariant! 495 | /// 496 | /// If this behaviour is undesirable, use [`replace_with_and_return`] or 497 | /// [`replace_with_or_default_and_return`]. 498 | /// 499 | /// Equivalent to `replace_with_and_return(dest, || process::abort(), f)`. 500 | /// 501 | /// # Example 502 | /// 503 | /// ``` 504 | /// # use replace_with::*; 505 | /// 506 | /// unsafe fn take(option: &mut Option) -> Option { 507 | /// replace_with_or_abort_and_return_unchecked(option, |option| (option, None)) 508 | /// } 509 | /// ``` 510 | #[inline] 511 | #[cfg(feature = "panic_abort")] 512 | #[deprecated = "Use replace_with_or_abort_and_return() instead, which used cfg!(panic = \"abort\") to guarentee soundness"] 513 | pub unsafe fn replace_with_or_abort_and_return_unchecked (U, T)>( 514 | dest: &mut T, f: F, 515 | ) -> U { 516 | let (res, new) = f(ptr::read(dest)); 517 | ptr::write(dest, new); 518 | res 519 | } 520 | 521 | #[cfg(test)] 522 | mod test { 523 | /// https://github.com/alecmocatta/replace_with/issues/18 replace_with[_and_return] has 524 | /// undefined behavior if default panics. 525 | #[test] 526 | #[ignore = "should abort, cc https://github.com/rust-lang/rust/issues/67650"] 527 | #[cfg(feature = "std")] 528 | fn default_panic() { 529 | let mut s = String::from("abc"); 530 | replace_with( 531 | &mut s, 532 | move || { 533 | panic!(); 534 | }, 535 | |s| { 536 | drop(s); 537 | panic!(); 538 | }, 539 | ); 540 | } 541 | 542 | /// https://github.com/alecmocatta/replace_with/issues/21 replace_with doesn't write the return 543 | /// value before dropping the default closure, causing a use after free if the drop glue of the 544 | /// latter panics 545 | #[test] 546 | #[should_panic] 547 | #[cfg(feature = "std")] 548 | fn default_drop_panic() { 549 | struct OnDropPanic(); 550 | impl Drop for OnDropPanic { 551 | fn drop(&mut self) { 552 | panic!(); 553 | } 554 | } 555 | 556 | let mut s = String::from("abc"); 557 | let panicking_drop = OnDropPanic(); 558 | replace_with( 559 | &mut s, 560 | // The code inside this closure never runs, but because `panicking_drop` is owned by the 561 | // closure, dropping this closure causes a panic. 562 | move || { 563 | drop(panicking_drop); 564 | unreachable!() 565 | }, 566 | |s| { 567 | drop(s); 568 | String::new() 569 | }, 570 | ); 571 | } 572 | 573 | // These functions copied from https://github.com/Sgeo/take_mut/blob/1bd70d842c6febcd16ec1fe3a954a84032b89f52/src/lib.rs#L102-L147 574 | 575 | // Copyright (c) 2016 Sgeo 576 | 577 | // Permission is hereby granted, free of charge, to any person obtaining a copy 578 | // of this software and associated documentation files (the "Software"), to deal 579 | // in the Software without restriction, including without limitation the rights 580 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 581 | // copies of the Software, and to permit persons to whom the Software is 582 | // furnished to do so, subject to the following conditions: 583 | 584 | // The above copyright notice and this permission notice shall be included in all 585 | // copies or substantial portions of the Software. 586 | 587 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 588 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 589 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 590 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 591 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 592 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 593 | // SOFTWARE. 594 | 595 | use super::*; 596 | 597 | #[test] 598 | fn it_works_recover() { 599 | #[derive(PartialEq, Eq, Debug)] 600 | enum Foo { 601 | A, 602 | B, 603 | } 604 | impl Drop for Foo { 605 | #[cfg(feature = "std")] 606 | fn drop(&mut self) { 607 | match *self { 608 | Foo::A => println!("Foo::A dropped"), 609 | Foo::B => println!("Foo::B dropped"), 610 | } 611 | } 612 | 613 | #[cfg(not(feature = "std"))] 614 | fn drop(&mut self) { 615 | match *self { 616 | Foo::A | Foo::B => (), 617 | } 618 | } 619 | } 620 | let mut quax = Foo::A; 621 | replace_with( 622 | &mut quax, 623 | || Foo::A, 624 | |f| { 625 | drop(f); 626 | Foo::B 627 | }, 628 | ); 629 | assert_eq!(&quax, &Foo::B); 630 | 631 | let n = replace_with_and_return( 632 | &mut quax, 633 | || Foo::B, 634 | |f| { 635 | drop(f); 636 | (3, Foo::A) 637 | }, 638 | ); 639 | assert_eq!(n, 3); 640 | assert_eq!(&quax, &Foo::A); 641 | } 642 | 643 | #[test] 644 | #[cfg(feature = "std")] 645 | fn it_works_recover_panic() { 646 | use std::panic; 647 | 648 | #[derive(PartialEq, Eq, Debug)] 649 | enum Foo { 650 | A, 651 | B, 652 | C, 653 | } 654 | impl Drop for Foo { 655 | fn drop(&mut self) { 656 | match *self { 657 | Foo::A => println!("Foo::A dropped"), 658 | Foo::B => println!("Foo::B dropped"), 659 | Foo::C => println!("Foo::C dropped"), 660 | } 661 | } 662 | } 663 | let mut quax = Foo::A; 664 | 665 | let res = panic::catch_unwind(panic::AssertUnwindSafe(|| { 666 | replace_with( 667 | &mut quax, 668 | || Foo::C, 669 | |f| { 670 | drop(f); 671 | panic!("panic"); 672 | #[allow(unreachable_code)] 673 | Foo::B 674 | }, 675 | ); 676 | })); 677 | 678 | assert!(res.is_err()); 679 | assert_eq!(&quax, &Foo::C); 680 | } 681 | } 682 | --------------------------------------------------------------------------------