├── .github └── workflows │ └── ci.yaml ├── .gitignore ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── examples └── readme.rs └── src └── lib.rs /.github/workflows/ci.yaml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | - push 5 | - pull_request 6 | 7 | env: 8 | CARGO_TERM_COLOR: always 9 | 10 | jobs: 11 | build: 12 | runs-on: ubuntu-latest 13 | strategy: 14 | matrix: 15 | rust: 16 | - stable 17 | - beta 18 | - nightly 19 | - 1.20.0 # MSRV 20 | steps: 21 | - uses: actions/checkout@v2 22 | - name: Install Rust 23 | uses: actions-rs/toolchain@v1 24 | with: 25 | profile: minimal 26 | toolchain: ${{ matrix.rust }} 27 | override: true 28 | - name: Build 29 | run: cargo build 30 | - name: Run tests 31 | run: cargo test 32 | - name: Run tests (without default features) 33 | run: cargo test --no-default-features 34 | 35 | no_std: 36 | runs-on: ubuntu-latest 37 | steps: 38 | - uses: actions/checkout@v2 39 | - name: Test no_std support 40 | run: | 41 | rustup target add thumbv6m-none-eabi 42 | cargo build --no-default-features --target thumbv6m-none-eabi 43 | 44 | format: 45 | runs-on: ubuntu-latest 46 | steps: 47 | - uses: actions/checkout@v2 48 | - name: Check formatting 49 | run: cargo fmt -- --check 50 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | Cargo.lock 2 | target 3 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "scopeguard" 3 | version = "1.2.0" 4 | 5 | license = "MIT OR Apache-2.0" 6 | repository = "https://github.com/bluss/scopeguard" 7 | documentation = "https://docs.rs/scopeguard/" 8 | authors = ["bluss"] 9 | 10 | description = """ 11 | A RAII scope guard that will run a given closure when it goes out of scope, 12 | even if the code between panics (assuming unwinding panic). 13 | 14 | Defines the macros `defer!`, `defer_on_unwind!`, `defer_on_success!` as 15 | shorthands for guards with one of the implemented strategies. 16 | """ 17 | 18 | keywords = ["scope-guard", "defer", "panic", "unwind"] 19 | categories = ["rust-patterns", "no-std"] 20 | 21 | [features] 22 | default = ["use_std"] 23 | use_std = [] 24 | 25 | [package.metadata.release] 26 | no-dev-version = true 27 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2016-2019 Ulrik Sverdrup "bluss" and scopeguard developers 2 | 3 | Permission is hereby granted, free of charge, to any 4 | person obtaining a copy of this software and associated 5 | documentation files (the "Software"), to deal in the 6 | Software without restriction, including without 7 | limitation the rights to use, copy, modify, merge, 8 | publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software 10 | is furnished to do so, subject to the following 11 | conditions: 12 | 13 | The above copyright notice and this permission notice 14 | shall be included in all copies or substantial portions 15 | of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 18 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 19 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 21 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 22 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 23 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 24 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 25 | DEALINGS IN THE SOFTWARE. 26 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # scopeguard 2 | 3 | Rust crate for a convenient RAII scope guard that will run a given closure when 4 | it goes out of scope, even if the code between panics (assuming unwinding panic). 5 | 6 | The `defer!` macro and `guard` are `no_std` compatible (require only `core`), 7 | but the on unwinding / not on unwinding strategies require linking to `std`. 8 | By default, the `use_std` crate feature is enabled. Disable the default features 9 | for `no_std` support. 10 | 11 | Please read the [API documentation here](https://docs.rs/scopeguard/). 12 | 13 | Minimum supported Rust version: 1.20 14 | 15 | [![build_status](https://github.com/bluss/scopeguard/actions/workflows/ci.yaml/badge.svg)](https://github.com/bluss/scopeguard/actions/workflows/ci.yaml) 16 | [![crates](https://img.shields.io/crates/v/scopeguard.svg)](https://crates.io/crates/scopeguard) 17 | 18 | ## How to use 19 | 20 | ```rs 21 | #[macro_use(defer)] 22 | extern crate scopeguard; 23 | 24 | use scopeguard::guard; 25 | 26 | fn f() { 27 | defer! { 28 | println!("Called at return or panic"); 29 | } 30 | panic!(); 31 | } 32 | 33 | use std::fs::File; 34 | use std::io::Write; 35 | 36 | fn g() { 37 | let f = File::create("newfile.txt").unwrap(); 38 | let mut file = guard(f, |f| { 39 | // write file at return or panic 40 | let _ = f.sync_all(); 41 | }); 42 | // access the file through the scope guard itself 43 | file.write_all(b"test me\n").unwrap(); 44 | } 45 | ``` 46 | 47 | ## Recent Changes 48 | 49 | - 1.2.0 50 | 51 | - Use ManuallyDrop instead of mem::forget in into_inner. (by @willtunnels) 52 | - Warn if the guard is not assigned to a variable and is dropped immediately 53 | instead of at the scope's end. (by @sergey-v-galtsev) 54 | 55 | - 1.1.0 56 | 57 | - Change macros (`defer!`, `defer_on_success!` and `defer_on_unwind!`) 58 | to accept statements. (by @konsumlamm) 59 | 60 | - 1.0.0 61 | 62 | - Change the closure type from `FnMut(&mut T)` to `FnOnce(T)`: 63 | Passing the inner value by value instead of a mutable reference is a 64 | breaking change, but allows the guard closure to consume it. (by @tormol) 65 | 66 | - Add `defer_on_success!`, `guard_on_success()` and `OnSuccess` 67 | strategy, which triggers when scope is exited *without* panic. It's the 68 | opposite to `defer_on_unwind!` / `guard_on_unwind()` / `OnUnwind`. 69 | 70 | - Add `ScopeGuard::into_inner()`, which "defuses" the guard and returns the 71 | guarded value. (by @tormol) 72 | 73 | - Implement `Sync` for guards with non-`Sync` closures. 74 | 75 | - Require Rust 1.20 76 | 77 | - 0.3.3 78 | 79 | - Use `#[inline]` on a few more functions by @stjepang (#14) 80 | - Add examples to crate documentation 81 | 82 | - 0.3.2 83 | 84 | - Add crate categories 85 | 86 | - 0.3.1 87 | 88 | - Add `defer_on_unwind!`, `Strategy` trait 89 | - Rename `Guard` → `ScopeGuard` 90 | - Add `ScopeGuard::with_strategy`. 91 | - `ScopeGuard` now implements `Debug`. 92 | - Require Rust 1.11 93 | 94 | - 0.2.0 95 | 96 | - Require Rust 1.6 97 | - Use `no_std` unconditionally 98 | - No other changes 99 | 100 | - 0.1.2 101 | 102 | - Add macro `defer!` 103 | -------------------------------------------------------------------------------- /examples/readme.rs: -------------------------------------------------------------------------------- 1 | #[macro_use(defer)] 2 | extern crate scopeguard; 3 | 4 | use scopeguard::guard; 5 | 6 | fn f() { 7 | defer! { 8 | println!("Called at return or panic"); 9 | } 10 | panic!(); 11 | } 12 | 13 | use std::fs::File; 14 | use std::io::Write; 15 | 16 | fn g() { 17 | let f = File::create("newfile.txt").unwrap(); 18 | let mut file = guard(f, |f| { 19 | // write file at return or panic 20 | let _ = f.sync_all(); 21 | }); 22 | // access the file through the scope guard itself 23 | file.write_all(b"test me\n").unwrap(); 24 | } 25 | 26 | fn main() { 27 | f(); 28 | g(); 29 | } 30 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #![cfg_attr(not(any(test, feature = "use_std")), no_std)] 2 | #![doc(html_root_url = "https://docs.rs/scopeguard/1/")] 3 | 4 | //! A scope guard will run a given closure when it goes out of scope, 5 | //! even if the code between panics. 6 | //! (as long as panic doesn't abort) 7 | //! 8 | //! # Examples 9 | //! 10 | //! ## Hello World 11 | //! 12 | //! This example creates a scope guard with an example function: 13 | //! 14 | //! ``` 15 | //! extern crate scopeguard; 16 | //! 17 | //! fn f() { 18 | //! let _guard = scopeguard::guard((), |_| { 19 | //! println!("Hello Scope Exit!"); 20 | //! }); 21 | //! 22 | //! // rest of the code here. 23 | //! 24 | //! // Here, at the end of `_guard`'s scope, the guard's closure is called. 25 | //! // It is also called if we exit this scope through unwinding instead. 26 | //! } 27 | //! # fn main() { 28 | //! # f(); 29 | //! # } 30 | //! ``` 31 | //! 32 | //! ## `defer!` 33 | //! 34 | //! Use the `defer` macro to run an operation at scope exit, 35 | //! either regular scope exit or during unwinding from a panic. 36 | //! 37 | //! ``` 38 | //! #[macro_use(defer)] extern crate scopeguard; 39 | //! 40 | //! use std::cell::Cell; 41 | //! 42 | //! fn main() { 43 | //! // use a cell to observe drops during and after the scope guard is active 44 | //! let drop_counter = Cell::new(0); 45 | //! { 46 | //! // Create a scope guard using `defer!` for the current scope 47 | //! defer! { 48 | //! drop_counter.set(1 + drop_counter.get()); 49 | //! } 50 | //! 51 | //! // Do regular operations here in the meantime. 52 | //! 53 | //! // Just before scope exit: it hasn't run yet. 54 | //! assert_eq!(drop_counter.get(), 0); 55 | //! 56 | //! // The following scope end is where the defer closure is called 57 | //! } 58 | //! assert_eq!(drop_counter.get(), 1); 59 | //! } 60 | //! ``` 61 | //! 62 | //! ## Scope Guard with Value 63 | //! 64 | //! If the scope guard closure needs to access an outer value that is also 65 | //! mutated outside of the scope guard, then you may want to use the scope guard 66 | //! with a value. The guard works like a smart pointer, so the inner value can 67 | //! be accessed by reference or by mutable reference. 68 | //! 69 | //! ### 1. The guard owns a file 70 | //! 71 | //! In this example, the scope guard owns a file and ensures pending writes are 72 | //! synced at scope exit. 73 | //! 74 | //! ``` 75 | //! extern crate scopeguard; 76 | //! 77 | //! use std::fs::*; 78 | //! use std::io::{self, Write}; 79 | //! # // Mock file so that we don't actually write a file 80 | //! # struct MockFile; 81 | //! # impl MockFile { 82 | //! # fn create(_s: &str) -> io::Result { Ok(MockFile) } 83 | //! # fn write_all(&self, _b: &[u8]) -> io::Result<()> { Ok(()) } 84 | //! # fn sync_all(&self) -> io::Result<()> { Ok(()) } 85 | //! # } 86 | //! # use self::MockFile as File; 87 | //! 88 | //! fn try_main() -> io::Result<()> { 89 | //! let f = File::create("newfile.txt")?; 90 | //! let mut file = scopeguard::guard(f, |f| { 91 | //! // ensure we flush file at return or panic 92 | //! let _ = f.sync_all(); 93 | //! }); 94 | //! // Access the file through the scope guard itself 95 | //! file.write_all(b"test me\n").map(|_| ()) 96 | //! } 97 | //! 98 | //! fn main() { 99 | //! try_main().unwrap(); 100 | //! } 101 | //! 102 | //! ``` 103 | //! 104 | //! ### 2. The guard restores an invariant on scope exit 105 | //! 106 | //! ``` 107 | //! extern crate scopeguard; 108 | //! 109 | //! use std::mem::ManuallyDrop; 110 | //! use std::ptr; 111 | //! 112 | //! // This function, just for this example, takes the first element 113 | //! // and inserts it into the assumed sorted tail of the vector. 114 | //! // 115 | //! // For optimization purposes we temporarily violate an invariant of the 116 | //! // Vec, that it owns all of its elements. 117 | //! // 118 | //! // The safe approach is to use swap, which means two writes to memory, 119 | //! // the optimization is to use a “hole” which uses only one write of memory 120 | //! // for each position it moves. 121 | //! // 122 | //! // We *must* use a scope guard to run this code safely. We 123 | //! // are running arbitrary user code (comparison operators) that may panic. 124 | //! // The scope guard ensures we restore the invariant after successful 125 | //! // exit or during unwinding from panic. 126 | //! fn insertion_sort_first(v: &mut Vec) 127 | //! where T: PartialOrd 128 | //! { 129 | //! struct Hole<'a, T: 'a> { 130 | //! v: &'a mut Vec, 131 | //! index: usize, 132 | //! value: ManuallyDrop, 133 | //! } 134 | //! 135 | //! unsafe { 136 | //! // Create a moved-from location in the vector, a “hole”. 137 | //! let value = ptr::read(&v[0]); 138 | //! let mut hole = Hole { v: v, index: 0, value: ManuallyDrop::new(value) }; 139 | //! 140 | //! // Use a scope guard with a value. 141 | //! // At scope exit, plug the hole so that the vector is fully 142 | //! // initialized again. 143 | //! // The scope guard owns the hole, but we can access it through the guard. 144 | //! let mut hole_guard = scopeguard::guard(hole, |hole| { 145 | //! // plug the hole in the vector with the value that was // taken out 146 | //! let index = hole.index; 147 | //! ptr::copy_nonoverlapping(&*hole.value, &mut hole.v[index], 1); 148 | //! }); 149 | //! 150 | //! // run algorithm that moves the hole in the vector here 151 | //! // move the hole until it's in a sorted position 152 | //! for i in 1..hole_guard.v.len() { 153 | //! if *hole_guard.value >= hole_guard.v[i] { 154 | //! // move the element back and the hole forward 155 | //! let index = hole_guard.index; 156 | //! hole_guard.v.swap(index, index + 1); 157 | //! hole_guard.index += 1; 158 | //! } else { 159 | //! break; 160 | //! } 161 | //! } 162 | //! 163 | //! // When the scope exits here, the Vec becomes whole again! 164 | //! } 165 | //! } 166 | //! 167 | //! fn main() { 168 | //! let string = String::from; 169 | //! let mut data = vec![string("c"), string("a"), string("b"), string("d")]; 170 | //! insertion_sort_first(&mut data); 171 | //! assert_eq!(data, vec!["a", "b", "c", "d"]); 172 | //! } 173 | //! 174 | //! ``` 175 | //! 176 | //! 177 | //! # Crate Features 178 | //! 179 | //! - `use_std` 180 | //! + Enabled by default. Enables the `OnUnwind` and `OnSuccess` strategies. 181 | //! + Disable to use `no_std`. 182 | //! 183 | //! # Rust Version 184 | //! 185 | //! This version of the crate requires Rust 1.20 or later. 186 | //! 187 | //! The scopeguard 1.x release series will use a carefully considered version 188 | //! upgrade policy, where in a later 1.x version, we will raise the minimum 189 | //! required Rust version. 190 | 191 | #[cfg(not(any(test, feature = "use_std")))] 192 | extern crate core as std; 193 | 194 | use std::fmt; 195 | use std::marker::PhantomData; 196 | use std::mem::ManuallyDrop; 197 | use std::ops::{Deref, DerefMut}; 198 | use std::ptr; 199 | 200 | /// Controls in which cases the associated code should be run 201 | pub trait Strategy { 202 | /// Return `true` if the guard’s associated code should run 203 | /// (in the context where this method is called). 204 | fn should_run() -> bool; 205 | } 206 | 207 | /// Always run on scope exit. 208 | /// 209 | /// “Always” run: on regular exit from a scope or on unwinding from a panic. 210 | /// Can not run on abort, process exit, and other catastrophic events where 211 | /// destructors don’t run. 212 | #[derive(Debug)] 213 | pub enum Always {} 214 | 215 | /// Run on scope exit through unwinding. 216 | /// 217 | /// Requires crate feature `use_std`. 218 | #[cfg(feature = "use_std")] 219 | #[derive(Debug)] 220 | pub enum OnUnwind {} 221 | 222 | /// Run on regular scope exit, when not unwinding. 223 | /// 224 | /// Requires crate feature `use_std`. 225 | #[cfg(feature = "use_std")] 226 | #[derive(Debug)] 227 | pub enum OnSuccess {} 228 | 229 | impl Strategy for Always { 230 | #[inline(always)] 231 | fn should_run() -> bool { 232 | true 233 | } 234 | } 235 | 236 | #[cfg(feature = "use_std")] 237 | impl Strategy for OnUnwind { 238 | #[inline] 239 | fn should_run() -> bool { 240 | std::thread::panicking() 241 | } 242 | } 243 | 244 | #[cfg(feature = "use_std")] 245 | impl Strategy for OnSuccess { 246 | #[inline] 247 | fn should_run() -> bool { 248 | !std::thread::panicking() 249 | } 250 | } 251 | 252 | /// Macro to create a `ScopeGuard` (always run). 253 | /// 254 | /// The macro takes statements, which are the body of a closure 255 | /// that will run when the scope is exited. 256 | #[macro_export] 257 | macro_rules! defer { 258 | ($($t:tt)*) => { 259 | let _guard = $crate::guard((), |()| { $($t)* }); 260 | }; 261 | } 262 | 263 | /// Macro to create a `ScopeGuard` (run on successful scope exit). 264 | /// 265 | /// The macro takes statements, which are the body of a closure 266 | /// that will run when the scope is exited. 267 | /// 268 | /// Requires crate feature `use_std`. 269 | #[cfg(feature = "use_std")] 270 | #[macro_export] 271 | macro_rules! defer_on_success { 272 | ($($t:tt)*) => { 273 | let _guard = $crate::guard_on_success((), |()| { $($t)* }); 274 | }; 275 | } 276 | 277 | /// Macro to create a `ScopeGuard` (run on unwinding from panic). 278 | /// 279 | /// The macro takes statements, which are the body of a closure 280 | /// that will run when the scope is exited. 281 | /// 282 | /// Requires crate feature `use_std`. 283 | #[cfg(feature = "use_std")] 284 | #[macro_export] 285 | macro_rules! defer_on_unwind { 286 | ($($t:tt)*) => { 287 | let _guard = $crate::guard_on_unwind((), |()| { $($t)* }); 288 | }; 289 | } 290 | 291 | /// `ScopeGuard` is a scope guard that may own a protected value. 292 | /// 293 | /// If you place a guard in a local variable, the closure can 294 | /// run regardless how you leave the scope — through regular return or panic 295 | /// (except if panic or other code aborts; so as long as destructors run). 296 | /// It is run only once. 297 | /// 298 | /// The `S` parameter for [`Strategy`](trait.Strategy.html) determines if 299 | /// the closure actually runs. 300 | /// 301 | /// The guard's closure will be called with the held value in the destructor. 302 | /// 303 | /// The `ScopeGuard` implements `Deref` so that you can access the inner value. 304 | pub struct ScopeGuard 305 | where 306 | F: FnOnce(T), 307 | S: Strategy, 308 | { 309 | value: ManuallyDrop, 310 | dropfn: ManuallyDrop, 311 | // fn(S) -> S is used, so that the S is not taken into account for auto traits. 312 | strategy: PhantomData S>, 313 | } 314 | 315 | impl ScopeGuard 316 | where 317 | F: FnOnce(T), 318 | S: Strategy, 319 | { 320 | /// Create a `ScopeGuard` that owns `v` (accessible through deref) and calls 321 | /// `dropfn` when its destructor runs. 322 | /// 323 | /// The `Strategy` decides whether the scope guard's closure should run. 324 | #[inline] 325 | #[must_use] 326 | pub fn with_strategy(v: T, dropfn: F) -> ScopeGuard { 327 | ScopeGuard { 328 | value: ManuallyDrop::new(v), 329 | dropfn: ManuallyDrop::new(dropfn), 330 | strategy: PhantomData, 331 | } 332 | } 333 | 334 | /// “Defuse” the guard and extract the value without calling the closure. 335 | /// 336 | /// ``` 337 | /// extern crate scopeguard; 338 | /// 339 | /// use scopeguard::{guard, ScopeGuard}; 340 | /// 341 | /// fn conditional() -> bool { true } 342 | /// 343 | /// fn main() { 344 | /// let mut guard = guard(Vec::new(), |mut v| v.clear()); 345 | /// guard.push(1); 346 | /// 347 | /// if conditional() { 348 | /// // a condition maybe makes us decide to 349 | /// // “defuse” the guard and get back its inner parts 350 | /// let value = ScopeGuard::into_inner(guard); 351 | /// } else { 352 | /// // guard still exists in this branch 353 | /// } 354 | /// } 355 | /// ``` 356 | #[inline] 357 | pub fn into_inner(guard: Self) -> T { 358 | // Cannot move out of `Drop`-implementing types, 359 | // so `ptr::read` the value and forget the guard. 360 | let mut guard = ManuallyDrop::new(guard); 361 | unsafe { 362 | let value = ptr::read(&*guard.value); 363 | // Drop the closure after `value` has been read, so that if the 364 | // closure's `drop` function panics, unwinding still tries to drop 365 | // `value`. 366 | ManuallyDrop::drop(&mut guard.dropfn); 367 | value 368 | } 369 | } 370 | } 371 | 372 | /// Create a new `ScopeGuard` owning `v` and with deferred closure `dropfn`. 373 | #[inline] 374 | #[must_use] 375 | pub fn guard(v: T, dropfn: F) -> ScopeGuard 376 | where 377 | F: FnOnce(T), 378 | { 379 | ScopeGuard::with_strategy(v, dropfn) 380 | } 381 | 382 | /// Create a new `ScopeGuard` owning `v` and with deferred closure `dropfn`. 383 | /// 384 | /// Requires crate feature `use_std`. 385 | #[cfg(feature = "use_std")] 386 | #[inline] 387 | #[must_use] 388 | pub fn guard_on_success(v: T, dropfn: F) -> ScopeGuard 389 | where 390 | F: FnOnce(T), 391 | { 392 | ScopeGuard::with_strategy(v, dropfn) 393 | } 394 | 395 | /// Create a new `ScopeGuard` owning `v` and with deferred closure `dropfn`. 396 | /// 397 | /// Requires crate feature `use_std`. 398 | /// 399 | /// ## Examples 400 | /// 401 | /// For performance reasons, or to emulate “only run guard on unwind” in 402 | /// no-std environments, we can also use the default guard and simply manually 403 | /// defuse it at the end of scope like the following example. (The performance 404 | /// reason would be if the [`OnUnwind`]'s call to [std::thread::panicking()] is 405 | /// an issue.) 406 | /// 407 | /// ``` 408 | /// extern crate scopeguard; 409 | /// 410 | /// use scopeguard::ScopeGuard; 411 | /// # fn main() { 412 | /// { 413 | /// let guard = scopeguard::guard((), |_| {}); 414 | /// 415 | /// // rest of the code here 416 | /// 417 | /// // we reached the end of scope without unwinding - defuse it 418 | /// ScopeGuard::into_inner(guard); 419 | /// } 420 | /// # } 421 | /// ``` 422 | #[cfg(feature = "use_std")] 423 | #[inline] 424 | #[must_use] 425 | pub fn guard_on_unwind(v: T, dropfn: F) -> ScopeGuard 426 | where 427 | F: FnOnce(T), 428 | { 429 | ScopeGuard::with_strategy(v, dropfn) 430 | } 431 | 432 | // ScopeGuard can be Sync even if F isn't because the closure is 433 | // not accessible from references. 434 | // The guard does not store any instance of S, so it is also irrelevant. 435 | unsafe impl Sync for ScopeGuard 436 | where 437 | T: Sync, 438 | F: FnOnce(T), 439 | S: Strategy, 440 | { 441 | } 442 | 443 | impl Deref for ScopeGuard 444 | where 445 | F: FnOnce(T), 446 | S: Strategy, 447 | { 448 | type Target = T; 449 | 450 | fn deref(&self) -> &T { 451 | &*self.value 452 | } 453 | } 454 | 455 | impl DerefMut for ScopeGuard 456 | where 457 | F: FnOnce(T), 458 | S: Strategy, 459 | { 460 | fn deref_mut(&mut self) -> &mut T { 461 | &mut *self.value 462 | } 463 | } 464 | 465 | impl Drop for ScopeGuard 466 | where 467 | F: FnOnce(T), 468 | S: Strategy, 469 | { 470 | fn drop(&mut self) { 471 | // This is OK because the fields are `ManuallyDrop`s 472 | // which will not be dropped by the compiler. 473 | let (value, dropfn) = unsafe { (ptr::read(&*self.value), ptr::read(&*self.dropfn)) }; 474 | if S::should_run() { 475 | dropfn(value); 476 | } 477 | } 478 | } 479 | 480 | impl fmt::Debug for ScopeGuard 481 | where 482 | T: fmt::Debug, 483 | F: FnOnce(T), 484 | S: Strategy, 485 | { 486 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 487 | f.debug_struct(stringify!(ScopeGuard)) 488 | .field("value", &*self.value) 489 | .finish() 490 | } 491 | } 492 | 493 | #[cfg(test)] 494 | mod tests { 495 | use super::*; 496 | use std::cell::Cell; 497 | use std::panic::catch_unwind; 498 | use std::panic::AssertUnwindSafe; 499 | 500 | #[test] 501 | fn test_defer() { 502 | let drops = Cell::new(0); 503 | defer!(drops.set(1000)); 504 | assert_eq!(drops.get(), 0); 505 | } 506 | 507 | #[cfg(feature = "use_std")] 508 | #[test] 509 | fn test_defer_success_1() { 510 | let drops = Cell::new(0); 511 | { 512 | defer_on_success!(drops.set(1)); 513 | assert_eq!(drops.get(), 0); 514 | } 515 | assert_eq!(drops.get(), 1); 516 | } 517 | 518 | #[cfg(feature = "use_std")] 519 | #[test] 520 | fn test_defer_success_2() { 521 | let drops = Cell::new(0); 522 | let _ = catch_unwind(AssertUnwindSafe(|| { 523 | defer_on_success!(drops.set(1)); 524 | panic!("failure") 525 | })); 526 | assert_eq!(drops.get(), 0); 527 | } 528 | 529 | #[cfg(feature = "use_std")] 530 | #[test] 531 | fn test_defer_unwind_1() { 532 | let drops = Cell::new(0); 533 | let _ = catch_unwind(AssertUnwindSafe(|| { 534 | defer_on_unwind!(drops.set(1)); 535 | assert_eq!(drops.get(), 0); 536 | panic!("failure") 537 | })); 538 | assert_eq!(drops.get(), 1); 539 | } 540 | 541 | #[cfg(feature = "use_std")] 542 | #[test] 543 | fn test_defer_unwind_2() { 544 | let drops = Cell::new(0); 545 | { 546 | defer_on_unwind!(drops.set(1)); 547 | } 548 | assert_eq!(drops.get(), 0); 549 | } 550 | 551 | #[test] 552 | fn test_only_dropped_by_closure_when_run() { 553 | let value_drops = Cell::new(0); 554 | let value = guard((), |()| value_drops.set(1 + value_drops.get())); 555 | let closure_drops = Cell::new(0); 556 | let guard = guard(value, |_| closure_drops.set(1 + closure_drops.get())); 557 | assert_eq!(value_drops.get(), 0); 558 | assert_eq!(closure_drops.get(), 0); 559 | drop(guard); 560 | assert_eq!(value_drops.get(), 1); 561 | assert_eq!(closure_drops.get(), 1); 562 | } 563 | 564 | #[cfg(feature = "use_std")] 565 | #[test] 566 | fn test_dropped_once_when_not_run() { 567 | let value_drops = Cell::new(0); 568 | let value = guard((), |()| value_drops.set(1 + value_drops.get())); 569 | let captured_drops = Cell::new(0); 570 | let captured = guard((), |()| captured_drops.set(1 + captured_drops.get())); 571 | let closure_drops = Cell::new(0); 572 | let guard = guard_on_unwind(value, |value| { 573 | drop(value); 574 | drop(captured); 575 | closure_drops.set(1 + closure_drops.get()) 576 | }); 577 | assert_eq!(value_drops.get(), 0); 578 | assert_eq!(captured_drops.get(), 0); 579 | assert_eq!(closure_drops.get(), 0); 580 | drop(guard); 581 | assert_eq!(value_drops.get(), 1); 582 | assert_eq!(captured_drops.get(), 1); 583 | assert_eq!(closure_drops.get(), 0); 584 | } 585 | 586 | #[test] 587 | fn test_into_inner() { 588 | let dropped = Cell::new(false); 589 | let value = guard(42, |_| dropped.set(true)); 590 | let guard = guard(value, |_| dropped.set(true)); 591 | let inner = ScopeGuard::into_inner(guard); 592 | assert_eq!(dropped.get(), false); 593 | assert_eq!(*inner, 42); 594 | } 595 | } 596 | --------------------------------------------------------------------------------