From f78cd44602fd8360657b9a205061ca7bf0592140 Mon Sep 17 00:00:00 2001 From: bjorn3 Date: Thu, 16 Sep 2021 14:48:33 +0200 Subject: [PATCH] Optimize ThreadInfo::with The RefCell is now borrowed exactly once. In addition a code sequence that contains an unwrap that is guaranteed to never panic at runtime is replaced with get_or_insert_with, which makes the intended behavior clearer and will not emit code to panic even without optimizations. --- library/std/src/sys_common/thread_info.rs | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/library/std/src/sys_common/thread_info.rs b/library/std/src/sys_common/thread_info.rs index f09d16c33e6d6..a0dbdcd979add 100644 --- a/library/std/src/sys_common/thread_info.rs +++ b/library/std/src/sys_common/thread_info.rs @@ -17,12 +17,13 @@ impl ThreadInfo { F: FnOnce(&mut ThreadInfo) -> R, { THREAD_INFO - .try_with(move |c| { - if c.borrow().is_none() { - *c.borrow_mut() = - Some(ThreadInfo { stack_guard: None, thread: Thread::new(None) }) - } - f(c.borrow_mut().as_mut().unwrap()) + .try_with(move |thread_info| { + let mut thread_info = thread_info.borrow_mut(); + let thread_info = thread_info.get_or_insert_with(|| ThreadInfo { + stack_guard: None, + thread: Thread::new(None), + }); + f(thread_info) }) .ok() }