File tree Expand file tree Collapse file tree 2 files changed +46
-0
lines changed Expand file tree Collapse file tree 2 files changed +46
-0
lines changed Original file line number Diff line number Diff line change @@ -50,6 +50,7 @@ export spawn_connected;
50
50
export connected_fn;
51
51
export connected_task;
52
52
export currently_unwinding;
53
+ export try;
53
54
54
55
#[ abi = "rust-intrinsic" ]
55
56
native mod rusti {
@@ -349,6 +350,30 @@ fn currently_unwinding() -> bool {
349
350
rustrt:: rust_task_is_unwinding ( rustrt:: rust_get_task ( ) )
350
351
}
351
352
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
+
352
377
// Local Variables:
353
378
// mode: rust;
354
379
// fill-column: 78;
Original file line number Diff line number Diff line change @@ -57,3 +57,24 @@ fn spawn_polymorphic() {
57
57
task:: spawn { || foo ( true ) ; } ;
58
58
task:: spawn { || foo ( 42 ) ; } ;
59
59
}
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
+ }
You can’t perform that action at this time.
0 commit comments