@@ -18,7 +18,7 @@ pub trait Local {
18
18
fn put ( value : ~Self ) ;
19
19
fn take ( ) -> ~Self ;
20
20
fn exists ( ) -> bool ;
21
- fn borrow ( f : & fn ( & mut Self ) ) ;
21
+ fn borrow < T > ( f : & fn ( & mut Self ) -> T ) -> T ;
22
22
unsafe fn unsafe_borrow ( ) -> * mut Self ;
23
23
unsafe fn try_unsafe_borrow ( ) -> Option < * mut Self > ;
24
24
}
@@ -27,7 +27,20 @@ impl Local for Scheduler {
27
27
fn put ( value : ~Scheduler ) { unsafe { local_ptr:: put ( value) } }
28
28
fn take ( ) -> ~Scheduler { unsafe { local_ptr:: take ( ) } }
29
29
fn exists ( ) -> bool { local_ptr:: exists ( ) }
30
- fn borrow ( f : & fn ( & mut Scheduler ) ) { unsafe { local_ptr:: borrow ( f) } }
30
+ fn borrow < T > ( f : & fn ( & mut Scheduler ) -> T ) -> T {
31
+ let mut res: Option < T > = None ;
32
+ let res_ptr: * mut Option < T > = & mut res;
33
+ unsafe {
34
+ do local_ptr:: borrow |sched| {
35
+ let result = f ( sched) ;
36
+ * res_ptr = Some ( result) ;
37
+ }
38
+ }
39
+ match res {
40
+ Some ( r) => { r }
41
+ None => abort ! ( "function failed!" )
42
+ }
43
+ }
31
44
unsafe fn unsafe_borrow ( ) -> * mut Scheduler { local_ptr:: unsafe_borrow ( ) }
32
45
unsafe fn try_unsafe_borrow ( ) -> Option < * mut Scheduler > { abort ! ( "unimpl" ) }
33
46
}
@@ -36,8 +49,8 @@ impl Local for Task {
36
49
fn put ( _value : ~Task ) { abort ! ( "unimpl" ) }
37
50
fn take ( ) -> ~Task { abort ! ( "unimpl" ) }
38
51
fn exists ( ) -> bool { abort ! ( "unimpl" ) }
39
- fn borrow ( f : & fn ( & mut Task ) ) {
40
- do Local :: borrow :: < Scheduler > |sched| {
52
+ fn borrow < T > ( f : & fn ( & mut Task ) -> T ) -> T {
53
+ do Local :: borrow :: < Scheduler , T > |sched| {
41
54
match sched. current_task {
42
55
Some ( ~ref mut task) => {
43
56
f ( & mut * task. task )
@@ -74,7 +87,7 @@ impl Local for IoFactoryObject {
74
87
fn put ( _value : ~IoFactoryObject ) { abort ! ( "unimpl" ) }
75
88
fn take ( ) -> ~IoFactoryObject { abort ! ( "unimpl" ) }
76
89
fn exists ( ) -> bool { abort ! ( "unimpl" ) }
77
- fn borrow ( _f : & fn ( & mut IoFactoryObject ) ) { abort ! ( "unimpl" ) }
90
+ fn borrow < T > ( _f : & fn ( & mut IoFactoryObject ) -> T ) -> T { abort ! ( "unimpl" ) }
78
91
unsafe fn unsafe_borrow ( ) -> * mut IoFactoryObject {
79
92
let sched = Local :: unsafe_borrow :: < Scheduler > ( ) ;
80
93
let io: * mut IoFactoryObject = ( * sched) . event_loop . io ( ) . unwrap ( ) ;
@@ -115,4 +128,16 @@ mod test {
115
128
}
116
129
let _scheduler: ~Scheduler = Local :: take ( ) ;
117
130
}
131
+
132
+ #[ test]
133
+ fn borrow_with_return ( ) {
134
+ let scheduler = ~new_test_uv_sched ( ) ;
135
+ Local :: put ( scheduler) ;
136
+ let res = do Local :: borrow :: < Scheduler , bool > |_sched| {
137
+ true
138
+ } ;
139
+ assert ! ( res)
140
+ let _scheduler: ~Scheduler = Local :: take ( ) ;
141
+ }
142
+
118
143
}
0 commit comments