@@ -48,6 +48,30 @@ impl Process {
4848 } )
4949 }
5050
51+ /// Run a function in the context of a process definition.
52+ ///
53+ /// If the function panics, the process definition *in that thread* is cleared
54+ /// by an implicitly installed global panic hook.
55+ pub fn run < R > ( self , f : impl FnOnce ( ) -> R ) -> R {
56+ HOOK_INSTALLED . call_once ( || {
57+ let orig_hook = panic:: take_hook ( ) ;
58+ panic:: set_hook ( Box :: new ( move |info| {
59+ clear_process ( ) ;
60+ orig_hook ( info) ;
61+ } ) ) ;
62+ } ) ;
63+
64+ PROCESS . with ( |p| {
65+ if let Some ( old_p) = & * p. borrow ( ) {
66+ panic ! ( "current process already set {old_p:?}" ) ;
67+ }
68+ * p. borrow_mut ( ) = Some ( self ) ;
69+ let result = f ( ) ;
70+ * p. borrow_mut ( ) = None ;
71+ result
72+ } )
73+ }
74+
5175 pub fn name ( & self ) -> Option < String > {
5276 let arg0 = match self . var ( "RUSTUP_FORCE_ARG0" ) {
5377 Ok ( v) => Some ( v) ,
@@ -173,33 +197,6 @@ impl From<TestProcess> for Process {
173197
174198static HOOK_INSTALLED : Once = Once :: new ( ) ;
175199
176- /// Run a function in the context of a process definition.
177- ///
178- /// If the function panics, the process definition *in that thread* is cleared
179- /// by an implicitly installed global panic hook.
180- pub fn with < F , R > ( process : Process , f : F ) -> R
181- where
182- F : FnOnce ( ) -> R ,
183- {
184- HOOK_INSTALLED . call_once ( || {
185- let orig_hook = panic:: take_hook ( ) ;
186- panic:: set_hook ( Box :: new ( move |info| {
187- clear_process ( ) ;
188- orig_hook ( info) ;
189- } ) ) ;
190- } ) ;
191-
192- PROCESS . with ( |p| {
193- if let Some ( old_p) = & * p. borrow ( ) {
194- panic ! ( "current process already set {old_p:?}" ) ;
195- }
196- * p. borrow_mut ( ) = Some ( process) ;
197- let result = f ( ) ;
198- * p. borrow_mut ( ) = None ;
199- result
200- } )
201- }
202-
203200/// Internal - for the panic hook only
204201fn clear_process ( ) {
205202 PROCESS . with ( |p| p. replace ( None ) ) ;
@@ -248,6 +245,11 @@ impl TestProcess {
248245 stderr : Arc :: new ( Mutex :: new ( Vec :: new ( ) ) ) ,
249246 }
250247 }
248+
249+ pub ( crate ) fn run < R > ( self , f : impl FnOnce ( ) -> R ) -> R {
250+ Process :: from ( self ) . run ( f)
251+ }
252+
251253 fn new_id ( ) -> u64 {
252254 let low_bits: u64 = std:: process:: id ( ) as u64 ;
253255 let mut rng = thread_rng ( ) ;
@@ -279,7 +281,7 @@ mod tests {
279281
280282 use rustup_macros:: unit_test as test;
281283
282- use super :: { with , Process , TestProcess } ;
284+ use super :: { Process , TestProcess } ;
283285
284286 #[ test]
285287 fn test_instance ( ) {
@@ -289,7 +291,8 @@ mod tests {
289291 HashMap :: default ( ) ,
290292 "" ,
291293 ) ;
292- with ( proc. clone ( ) . into ( ) , || {
294+
295+ proc. clone ( ) . run ( || {
293296 let cur = Process :: get ( ) ;
294297 assert_eq ! ( proc. id, cur. id( ) , "{:?} != {:?}" , proc, cur)
295298 } ) ;
0 commit comments