Skip to content

Instantly share code, notes, and snippets.

@jsancio
Created December 2, 2014 19:48
Show Gist options
  • Save jsancio/46d4d2c222229ce09571 to your computer and use it in GitHub Desktop.
Save jsancio/46d4d2c222229ce09571 to your computer and use it in GitHub Desktop.
Rust Scope Exit
#![feature(unsafe_destructor)]
use std::io;
fn main() {
match test_scope() {
Ok(_) => println!("Main: test scope succeeded"),
Err(err) => panic!("Main: file error: {}", err),
};
}
fn test_scope() -> io::IoResult<()> {
let mut scope_error = ScopeExit::new(|| println!("error while calling test_scope"));
let mut res1 = ExternalResource::new();
let mut scoped1 = ScopeExit::new(|| {
if res1.access() {
res1.mutate()
}
});
scoped1.commit();
if !res1.access() {
res1.mutate()
}
scope_error.dismiss();
Ok(())
}
struct ExternalResource {
variable: bool
}
impl ExternalResource {
fn new() -> ExternalResource {
ExternalResource { variable: false }
}
fn mutate(&mut self) {
self.variable = true;
}
fn access(& self) -> bool {
self.variable
}
fn consume(self) -> ExternalResource {
self
}
}
struct ScopeExit<'a> {
fun: ||: 'a -> (),
commit: bool
}
impl<'a> ScopeExit<'a> {
fn new(fun: ||: 'a -> ()) -> ScopeExit<'a> {
ScopeExit { fun: fun, commit: true }
}
fn commit(&mut self) {
self.commit = true
}
fn dismiss(&mut self) {
self.commit = false;
}
}
#[unsafe_destructor]
impl<'a> Drop for ScopeExit<'a> {
fn drop(&mut self) {
println!("ScopeExit: drop called for scope exit");
if self.commit {
println!("ScopeExit: commiting!");
(self.fun)();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment