| <!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta name="generator" content="rustdoc"><meta name="description" content="A scope guard will run a given closure when it goes out of scope, even if the code between panics. (as long as panic doesn’t abort)"><meta name="keywords" content="rust, rustlang, rust-lang, scopeguard"><title>scopeguard - Rust</title><link rel="preload" as="font" type="font/woff2" crossorigin href="../SourceSerif4-Regular.ttf.woff2"><link rel="preload" as="font" type="font/woff2" crossorigin href="../FiraSans-Regular.woff2"><link rel="preload" as="font" type="font/woff2" crossorigin href="../FiraSans-Medium.woff2"><link rel="preload" as="font" type="font/woff2" crossorigin href="../SourceCodePro-Regular.ttf.woff2"><link rel="preload" as="font" type="font/woff2" crossorigin href="../SourceSerif4-Bold.ttf.woff2"><link rel="preload" as="font" type="font/woff2" crossorigin href="../SourceCodePro-Semibold.ttf.woff2"><link rel="stylesheet" href="../normalize.css"><link rel="stylesheet" href="../rustdoc.css" id="mainThemeStyle"><link rel="stylesheet" href="../ayu.css" disabled><link rel="stylesheet" href="../dark.css" disabled><link rel="stylesheet" href="../light.css" id="themeStyle"><script id="default-settings" ></script><script src="../storage.js"></script><script defer src="../crates.js"></script><script defer src="../main.js"></script><noscript><link rel="stylesheet" href="../noscript.css"></noscript><link rel="alternate icon" type="image/png" href="../favicon-16x16.png"><link rel="alternate icon" type="image/png" href="../favicon-32x32.png"><link rel="icon" type="image/svg+xml" href="../favicon.svg"></head><body class="rustdoc mod crate"><!--[if lte IE 11]><div class="warning">This old browser is unsupported and will most likely display funky things.</div><![endif]--><nav class="mobile-topbar"><button class="sidebar-menu-toggle">☰</button><a class="sidebar-logo" href="../scopeguard/index.html"><div class="logo-container"><img class="rust-logo" src="../rust-logo.svg" alt="logo"></div></a><h2></h2></nav><nav class="sidebar"><a class="sidebar-logo" href="../scopeguard/index.html"><div class="logo-container"><img class="rust-logo" src="../rust-logo.svg" alt="logo"></div></a><h2 class="location"><a href="#">Crate scopeguard</a></h2><div class="sidebar-elems"><ul class="block"><li class="version">Version 1.1.0</li><li><a id="all-types" href="all.html">All Items</a></li></ul><section><ul class="block"><li><a href="#macros">Macros</a></li><li><a href="#structs">Structs</a></li><li><a href="#enums">Enums</a></li><li><a href="#traits">Traits</a></li><li><a href="#functions">Functions</a></li></ul></section></div></nav><main><div class="width-limiter"><nav class="sub"><form class="search-form"><div class="search-container"><span></span><input class="search-input" name="search" autocomplete="off" spellcheck="false" placeholder="Click or press ‘S’ to search, ‘?’ for more options…" type="search"><div id="help-button" title="help" tabindex="-1"><a href="../help.html">?</a></div><div id="settings-menu" tabindex="-1"><a href="../settings.html" title="settings"><img width="22" height="22" alt="Change settings" src="../wheel.svg"></a></div></div></form></nav><section id="main-content" class="content"><div class="main-heading"><h1 class="fqn">Crate <a class="mod" href="#">scopeguard</a><button id="copy-path" onclick="copy_path(this)" title="Copy item path to clipboard"><img src="../clipboard.svg" width="19" height="18" alt="Copy item path"></button></h1><span class="out-of-band"><a class="srclink" href="../src/scopeguard/lib.rs.html#1-578">source</a> · <a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs">[<span class="inner">−</span>]</a></span></div><details class="rustdoc-toggle top-doc" open><summary class="hideme"><span>Expand description</span></summary><div class="docblock"><p>A scope guard will run a given closure when it goes out of scope, |
| even if the code between panics. |
| (as long as panic doesn’t abort)</p> |
| <h2 id="examples"><a href="#examples">Examples</a></h2><h3 id="hello-world"><a href="#hello-world">Hello World</a></h3> |
| <p>This example creates a scope guard with an example function:</p> |
| |
| <div class="example-wrap"><pre class="rust rust-example-rendered"><code><span class="kw">extern crate </span>scopeguard; |
| |
| <span class="kw">fn </span>f() { |
| <span class="kw">let </span>_guard = scopeguard::guard((), |<span class="kw">_</span>| { |
| <span class="macro">println!</span>(<span class="string">"Hello Scope Exit!"</span>); |
| }); |
| |
| <span class="comment">// rest of the code here. |
| |
| // Here, at the end of `_guard`'s scope, the guard's closure is called. |
| // It is also called if we exit this scope through unwinding instead. |
| </span>}</code></pre></div> |
| <h3 id="defer"><a href="#defer"><code>defer!</code></a></h3> |
| <p>Use the <code>defer</code> macro to run an operation at scope exit, |
| either regular scope exit or during unwinding from a panic.</p> |
| |
| <div class="example-wrap"><pre class="rust rust-example-rendered"><code><span class="attribute">#[macro_use(defer)] </span><span class="kw">extern crate </span>scopeguard; |
| |
| <span class="kw">use </span>std::cell::Cell; |
| |
| <span class="kw">fn </span>main() { |
| <span class="comment">// use a cell to observe drops during and after the scope guard is active |
| </span><span class="kw">let </span>drop_counter = Cell::new(<span class="number">0</span>); |
| { |
| <span class="comment">// Create a scope guard using `defer!` for the current scope |
| </span><span class="macro">defer! </span>{ |
| drop_counter.set(<span class="number">1 </span>+ drop_counter.get()); |
| } |
| |
| <span class="comment">// Do regular operations here in the meantime. |
| |
| // Just before scope exit: it hasn't run yet. |
| </span><span class="macro">assert_eq!</span>(drop_counter.get(), <span class="number">0</span>); |
| |
| <span class="comment">// The following scope end is where the defer closure is called |
| </span>} |
| <span class="macro">assert_eq!</span>(drop_counter.get(), <span class="number">1</span>); |
| }</code></pre></div> |
| <h3 id="scope-guard-with-value"><a href="#scope-guard-with-value">Scope Guard with Value</a></h3> |
| <p>If the scope guard closure needs to access an outer value that is also |
| mutated outside of the scope guard, then you may want to use the scope guard |
| with a value. The guard works like a smart pointer, so the inner value can |
| be accessed by reference or by mutable reference.</p> |
| <h4 id="1-the-guard-owns-a-file"><a href="#1-the-guard-owns-a-file">1. The guard owns a file</a></h4> |
| <p>In this example, the scope guard owns a file and ensures pending writes are |
| synced at scope exit.</p> |
| |
| <div class="example-wrap"><pre class="rust rust-example-rendered"><code><span class="kw">extern crate </span>scopeguard; |
| |
| <span class="kw">use </span>std::fs::<span class="kw-2">*</span>; |
| <span class="kw">use </span>std::io::{<span class="self">self</span>, Write}; |
| |
| <span class="kw">fn </span>try_main() -> io::Result<()> { |
| <span class="kw">let </span>f = File::create(<span class="string">"newfile.txt"</span>)<span class="question-mark">?</span>; |
| <span class="kw">let </span><span class="kw-2">mut </span>file = scopeguard::guard(f, |f| { |
| <span class="comment">// ensure we flush file at return or panic |
| </span><span class="kw">let _ </span>= f.sync_all(); |
| }); |
| <span class="comment">// Access the file through the scope guard itself |
| </span>file.write_all(<span class="string">b"test me\n"</span>).map(|<span class="kw">_</span>| ()) |
| } |
| |
| <span class="kw">fn </span>main() { |
| try_main().unwrap(); |
| } |
| </code></pre></div> |
| <h4 id="2-the-guard-restores-an-invariant-on-scope-exit"><a href="#2-the-guard-restores-an-invariant-on-scope-exit">2. The guard restores an invariant on scope exit</a></h4> |
| <div class="example-wrap"><pre class="rust rust-example-rendered"><code><span class="kw">extern crate </span>scopeguard; |
| |
| <span class="kw">use </span>std::mem::ManuallyDrop; |
| <span class="kw">use </span>std::ptr; |
| |
| <span class="comment">// This function, just for this example, takes the first element |
| // and inserts it into the assumed sorted tail of the vector. |
| // |
| // For optimization purposes we temporarily violate an invariant of the |
| // Vec, that it owns all of its elements. |
| // |
| // The safe approach is to use swap, which means two writes to memory, |
| // the optimization is to use a “hole” which uses only one write of memory |
| // for each position it moves. |
| // |
| // We *must* use a scope guard to run this code safely. We |
| // are running arbitrary user code (comparison operators) that may panic. |
| // The scope guard ensures we restore the invariant after successful |
| // exit or during unwinding from panic. |
| </span><span class="kw">fn </span>insertion_sort_first<T>(v: <span class="kw-2">&mut </span>Vec<T>) |
| <span class="kw">where </span>T: PartialOrd |
| { |
| <span class="kw">struct </span>Hole<<span class="lifetime">'a</span>, T: <span class="lifetime">'a</span>> { |
| v: <span class="kw-2">&</span><span class="lifetime">'a </span><span class="kw-2">mut </span>Vec<T>, |
| index: usize, |
| value: ManuallyDrop<T>, |
| } |
| |
| <span class="kw">unsafe </span>{ |
| <span class="comment">// Create a moved-from location in the vector, a “hole”. |
| </span><span class="kw">let </span>value = ptr::read(<span class="kw-2">&</span>v[<span class="number">0</span>]); |
| <span class="kw">let </span><span class="kw-2">mut </span>hole = Hole { v: v, index: <span class="number">0</span>, value: ManuallyDrop::new(value) }; |
| |
| <span class="comment">// Use a scope guard with a value. |
| // At scope exit, plug the hole so that the vector is fully |
| // initialized again. |
| // The scope guard owns the hole, but we can access it through the guard. |
| </span><span class="kw">let </span><span class="kw-2">mut </span>hole_guard = scopeguard::guard(hole, |hole| { |
| <span class="comment">// plug the hole in the vector with the value that was // taken out |
| </span><span class="kw">let </span>index = hole.index; |
| ptr::copy_nonoverlapping(<span class="kw-2">&*</span>hole.value, <span class="kw-2">&mut </span>hole.v[index], <span class="number">1</span>); |
| }); |
| |
| <span class="comment">// run algorithm that moves the hole in the vector here |
| // move the hole until it's in a sorted position |
| </span><span class="kw">for </span>i <span class="kw">in </span><span class="number">1</span>..hole_guard.v.len() { |
| <span class="kw">if </span><span class="kw-2">*</span>hole_guard.value >= hole_guard.v[i] { |
| <span class="comment">// move the element back and the hole forward |
| </span><span class="kw">let </span>index = hole_guard.index; |
| ptr::copy_nonoverlapping(<span class="kw-2">&</span>hole_guard.v[index + <span class="number">1</span>], <span class="kw-2">&mut </span>hole_guard.v[index], <span class="number">1</span>); |
| hole_guard.index += <span class="number">1</span>; |
| } <span class="kw">else </span>{ |
| <span class="kw">break</span>; |
| } |
| } |
| |
| <span class="comment">// When the scope exits here, the Vec becomes whole again! |
| </span>} |
| } |
| |
| <span class="kw">fn </span>main() { |
| <span class="kw">let </span>string = String::from; |
| <span class="kw">let </span><span class="kw-2">mut </span>data = <span class="macro">vec!</span>[string(<span class="string">"c"</span>), string(<span class="string">"a"</span>), string(<span class="string">"b"</span>), string(<span class="string">"d"</span>)]; |
| insertion_sort_first(<span class="kw-2">&mut </span>data); |
| <span class="macro">assert_eq!</span>(data, <span class="macro">vec!</span>[<span class="string">"a"</span>, <span class="string">"b"</span>, <span class="string">"c"</span>, <span class="string">"d"</span>]); |
| } |
| </code></pre></div> |
| <h2 id="crate-features"><a href="#crate-features">Crate Features</a></h2> |
| <ul> |
| <li><code>use_std</code> |
| <ul> |
| <li>Enabled by default. Enables the <code>OnUnwind</code> and <code>OnSuccess</code> strategies.</li> |
| <li>Disable to use <code>no_std</code>.</li> |
| </ul> |
| </li> |
| </ul> |
| <h2 id="rust-version"><a href="#rust-version">Rust Version</a></h2> |
| <p>This version of the crate requires Rust 1.20 or later.</p> |
| <p>The scopeguard 1.x release series will use a carefully considered version |
| upgrade policy, where in a later 1.x version, we will raise the minimum |
| required Rust version.</p> |
| </div></details><h2 id="macros" class="small-section-header"><a href="#macros">Macros</a></h2><div class="item-table"><div class="item-row"><div class="item-left module-item"><a class="macro" href="macro.defer.html" title="scopeguard::defer macro">defer</a></div><div class="item-right docblock-short">Macro to create a <code>ScopeGuard</code> (always run).</div></div></div><h2 id="structs" class="small-section-header"><a href="#structs">Structs</a></h2><div class="item-table"><div class="item-row"><div class="item-left module-item"><a class="struct" href="struct.ScopeGuard.html" title="scopeguard::ScopeGuard struct">ScopeGuard</a></div><div class="item-right docblock-short"><code>ScopeGuard</code> is a scope guard that may own a protected value.</div></div></div><h2 id="enums" class="small-section-header"><a href="#enums">Enums</a></h2><div class="item-table"><div class="item-row"><div class="item-left module-item"><a class="enum" href="enum.Always.html" title="scopeguard::Always enum">Always</a></div><div class="item-right docblock-short">Always run on scope exit.</div></div></div><h2 id="traits" class="small-section-header"><a href="#traits">Traits</a></h2><div class="item-table"><div class="item-row"><div class="item-left module-item"><a class="trait" href="trait.Strategy.html" title="scopeguard::Strategy trait">Strategy</a></div><div class="item-right docblock-short">Controls in which cases the associated code should be run</div></div></div><h2 id="functions" class="small-section-header"><a href="#functions">Functions</a></h2><div class="item-table"><div class="item-row"><div class="item-left module-item"><a class="fn" href="fn.guard.html" title="scopeguard::guard fn">guard</a></div><div class="item-right docblock-short">Create a new <code>ScopeGuard</code> owning <code>v</code> and with deferred closure <code>dropfn</code>.</div></div></div></section></div></main><div id="rustdoc-vars" data-root-path="../" data-current-crate="scopeguard" data-themes="ayu,dark,light" data-resource-suffix="" data-rustdoc-version="1.66.0-nightly (5c8bff74b 2022-10-21)" ></div></body></html> |