diff --git a/src/libcore/task.rs b/src/libcore/task.rs index afb64da8b6f3..b24e27596b5f 100644 --- a/src/libcore/task.rs +++ b/src/libcore/task.rs @@ -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(+f: fn~() -> T) -> result::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; diff --git a/src/test/stdtest/task.rs b/src/test/stdtest/task.rs index d1408d183d52..021a56a5dff4 100644 --- a/src/test/stdtest/task.rs +++ b/src/test/stdtest/task.rs @@ -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; } + } +} \ No newline at end of file