README.rst
1
2scopeguard
3==========
4
5Rust crate for a convenient RAII scope guard that will run a given closure when
6it goes out of scope, even if the code between panics (assuming unwinding panic).
7
8The `defer!` macro and `guard` are `no_std` compatible (require only core),
9but the on unwinding / not on uwinding strategies requires linking to `std`.
10
11Requires Rust 1.20.
12
13
14Please read the `API documentation here`__
15
16__ https://docs.rs/scopeguard/
17
18|build_status|_ |crates|_
19
20.. |build_status| image:: https://travis-ci.org/bluss/scopeguard.svg
21.. _build_status: https://travis-ci.org/bluss/scopeguard
22
23.. |crates| image:: http://meritbadge.herokuapp.com/scopeguard
24.. _crates: https://crates.io/crates/scopeguard
25
26How to use
27----------
28
29.. code:: rust
30
31 #[macro_use(defer)] extern crate scopeguard;
32
33 use scopeguard::guard;
34
35 fn f() {
36 defer!(println!("Called at return or panic"));
37 panic!();
38 }
39
40 use std::fs::File;
41 use std::io::Write;
42
43 fn g() {
44 let f = File::create("newfile.txt").unwrap();
45 let mut file = guard(f, |f| {
46 // write file at return or panic
47 let _ = f.sync_all();
48 });
49 // Access the file through the scope guard itself
50 file.write_all(b"test me\n").unwrap();
51 }
52
53Recent Changes
54--------------
55
56- 1.0.0
57
58 - Change the closure type from ``FnMut(&mut T)`` to ``FnOnce(T)``:
59 Passing the inner value by value instead of a mutable reference is a
60 breaking change, but allows the guard closure to consume it. (by @tormol)
61
62 - Add ``defer_on_success!{}``, ``guard_on_success()`` and ``OnSuccess``
63 strategy, which triggers when scope is exited *without* panic. It's the
64 opposite to ``OnUnwind`` / ``guard_on_unwind()`` / ``defer_on_unwind!{}``.
65
66 - Add ``ScopeGuard::into_inner()``, which "defuses" the guard and returns the
67 guarded value. (by @tormol)
68
69 - Implement ``Sync`` for guards with non-``Sync`` closures.
70
71 - Require Rust 1.20
72
73- 0.3.3
74
75 - Use ``#[inline]`` on a few more functions by @stjepang (#14)
76 - Add examples to crate documentation
77
78- 0.3.2
79
80 - Add crate categories
81
82- 0.3.1
83
84 - Add ``defer_on_unwind!``, ``Strategy`` trait
85 - Rename ``Guard`` → ``ScopeGuard``
86 - Add ``ScopeGuard::with_strategy``.
87 - ``ScopeGuard`` now implements ``Debug``.
88 - Require Rust 1.11
89
90- 0.2.0
91
92 - Require Rust 1.6
93 - Use `no_std` unconditionally
94 - No other changes
95
96- 0.1.2
97
98 - Add macro ``defer!()``
99