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::unstable::finally::Finally;
28 // this code is always run
35 #[cfg(test)] use task::failing;
37 pub trait Finally<T> {
38 fn finally(&self, dtor: ||) -> T;
41 impl<'a,T> Finally<T> for ||: 'a -> T {
42 fn finally(&self, dtor: ||) -> T {
43 try_finally(&mut (), (),
49 impl<T> Finally<T> for fn() -> T {
50 fn finally(&self, dtor: ||) -> T {
51 try_finally(&mut (), (),
58 * The most general form of the `finally` functions. The function
59 * `try_fn` will be invoked first; whether or not it fails, the
60 * function `finally_fn` will be invoked next. The two parameters
61 * `mutate` and `drop` are used to thread state through the two
62 * closures. `mutate` is used for any shared, mutable state that both
63 * closures require access to; `drop` is used for any state that the
64 * `try_fn` requires ownership of.
66 * **WARNING:** While shared, mutable state between the try and finally
67 * function is often necessary, one must be very careful; the `try`
68 * function could have failed at any point, so the values of the shared
69 * state may be inconsistent.
74 * use std::unstable::finally::try_finally;
76 * struct State<'a> { buffer: &'a mut [u8], len: uint }
78 * let mut state = State { buffer: buf, len: 0 };
82 * // use state.buffer, state.len
85 * // use state.buffer, state.len to cleanup
89 pub fn try_finally<T,U,R>(mutate: &mut T,
91 try_fn: |&mut T, U| -> R,
94 let f = Finallyalizer {
98 try_fn(&mut *f.mutate, drop)
101 struct Finallyalizer<'a,A> {
107 impl<'a,A> Drop for Finallyalizer<'a,A> {
110 (self.dtor)(self.mutate);
148 let closure: || -> int = || 10;
149 let i = closure.finally(|| { });
155 fn do_some_fallible_work() {}
156 fn but_always_run_this_function() { }
157 do_some_fallible_work.finally(
158 but_always_run_this_function);