libcore: Add task::try

This commit is contained in:
Brian Anderson 2012-01-13 14:20:56 -08:00
parent 31bb6a60bb
commit e66c036c9f
2 changed files with 46 additions and 0 deletions

View file

@ -50,6 +50,7 @@ export spawn_connected;
export connected_fn;
export connected_task;
export currently_unwinding;
export try;
#[abi = "rust-intrinsic"]
native mod rusti {
@ -349,6 +350,30 @@ fn currently_unwinding() -> bool {
rustrt::rust_task_is_unwinding(rustrt::rust_get_task())
}
/*
Function: try
Execute a function in another task and return either the return value
of the function or result::err.
Returns:
If the function executed successfully then try returns result::ok
containing the value returned by the function. If the function fails
then try returns result::err containing nil.
*/
fn try<T:send>(+f: fn~() -> T) -> result::t<T,()> {
let p = comm::port();
let ch = comm::chan(p);
alt join(spawn_joinable {||
unsupervise();
comm::send(ch, f());
}) {
tr_success. { result::ok(comm::recv(p)) }
tr_failure. { result::err(()) }
}
}
// Local Variables:
// mode: rust;
// fill-column: 78;

View file

@ -57,3 +57,24 @@ fn spawn_polymorphic() {
task::spawn {|| foo(true);};
task::spawn {|| foo(42);};
}
#[test]
fn try_success() {
alt task::try {||
"Success!"
} {
result::ok("Success!") { }
_ { fail; }
}
}
#[test]
#[ignore(cfg(target_os = "win32"))]
fn try_fail() {
alt task::try {||
fail
} {
result::err(()) { }
_ { fail; }
}
}