1 // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
12 The Finally trait provides a method, `finally` on
13 stack closures that emulates Java-style try/finally blocks.
15 Using the `finally` method is sometimes convenient, but the type rules
16 prohibit any shared, mutable state between the "try" case and the
17 "finally" case. For advanced cases, the `try_finally` function can
18 also be used. See that function for more details.
23 use std::finally::Finally;
28 // this code is always run
37 /// A trait for executing a destructor unconditionally after a block of code,
38 /// regardless of whether the blocked fails.
39 pub trait Finally<T> {
40 /// Executes this object, unconditionally running `dtor` after this block of
42 fn finally(&mut self, dtor: ||) -> T;
45 impl<'a,T> Finally<T> for ||: 'a -> T {
46 fn finally(&mut self, dtor: ||) -> T {
47 try_finally(&mut (), self,
53 impl<T> Finally<T> for fn() -> T {
54 fn finally(&mut self, dtor: ||) -> T {
55 try_finally(&mut (), (),
62 * The most general form of the `finally` functions. The function
63 * `try_fn` will be invoked first; whether or not it fails, the
64 * function `finally_fn` will be invoked next. The two parameters
65 * `mutate` and `drop` are used to thread state through the two
66 * closures. `mutate` is used for any shared, mutable state that both
67 * closures require access to; `drop` is used for any state that the
68 * `try_fn` requires ownership of.
70 * **WARNING:** While shared, mutable state between the try and finally
71 * function is often necessary, one must be very careful; the `try`
72 * function could have failed at any point, so the values of the shared
73 * state may be inconsistent.
78 * use std::finally::try_finally;
80 * struct State<'a> { buffer: &'a mut [u8], len: uint }
82 * let mut state = State { buffer: buf, len: 0 };
86 * // use state.buffer, state.len
89 * // use state.buffer, state.len to cleanup
93 pub fn try_finally<T,U,R>(mutate: &mut T,
95 try_fn: |&mut T, U| -> R,
98 let f = Finallyalizer {
102 try_fn(&mut *f.mutate, drop)
105 struct Finallyalizer<'a,A> {
111 impl<'a,A> Drop for Finallyalizer<'a,A> {
114 (self.dtor)(self.mutate);
120 use super::{try_finally, Finally};
121 use realstd::task::failing;
157 let mut closure: || -> int = || 10;
158 let i = closure.finally(|| { });
164 fn do_some_fallible_work() {}
165 fn but_always_run_this_function() { }
166 let mut f = do_some_fallible_work;
167 f.finally(but_always_run_this_function);