Skip to content

Commit e66c036

Browse files
committed
libcore: Add task::try
1 parent 31bb6a6 commit e66c036

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

src/libcore/task.rs

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ export spawn_connected;
5050
export connected_fn;
5151
export connected_task;
5252
export currently_unwinding;
53+
export try;
5354

5455
#[abi = "rust-intrinsic"]
5556
native mod rusti {
@@ -349,6 +350,30 @@ fn currently_unwinding() -> bool {
349350
rustrt::rust_task_is_unwinding(rustrt::rust_get_task())
350351
}
351352

353+
/*
354+
Function: try
355+
356+
Execute a function in another task and return either the return value
357+
of the function or result::err.
358+
359+
Returns:
360+
361+
If the function executed successfully then try returns result::ok
362+
containing the value returned by the function. If the function fails
363+
then try returns result::err containing nil.
364+
*/
365+
fn try<T:send>(+f: fn~() -> T) -> result::t<T,()> {
366+
let p = comm::port();
367+
let ch = comm::chan(p);
368+
alt join(spawn_joinable {||
369+
unsupervise();
370+
comm::send(ch, f());
371+
}) {
372+
tr_success. { result::ok(comm::recv(p)) }
373+
tr_failure. { result::err(()) }
374+
}
375+
}
376+
352377
// Local Variables:
353378
// mode: rust;
354379
// fill-column: 78;

src/test/stdtest/task.rs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,3 +57,24 @@ fn spawn_polymorphic() {
5757
task::spawn {|| foo(true);};
5858
task::spawn {|| foo(42);};
5959
}
60+
61+
#[test]
62+
fn try_success() {
63+
alt task::try {||
64+
"Success!"
65+
} {
66+
result::ok("Success!") { }
67+
_ { fail; }
68+
}
69+
}
70+
71+
#[test]
72+
#[ignore(cfg(target_os = "win32"))]
73+
fn try_fail() {
74+
alt task::try {||
75+
fail
76+
} {
77+
result::err(()) { }
78+
_ { fail; }
79+
}
80+
}

0 commit comments

Comments
 (0)