From a45c8b09e86ea4eed283a6163b44c493d15ee5c3 Mon Sep 17 00:00:00 2001 From: Lee Bousfield Date: Mon, 10 Jul 2017 20:18:36 -0400 Subject: [PATCH] Use LocalKey::try_with in std --- src/libstd/io/stdio.rs | 22 ++++++++-------------- src/libstd/sys_common/thread_info.rs | 11 +++-------- 2 files changed, 11 insertions(+), 22 deletions(-) diff --git a/src/libstd/io/stdio.rs b/src/libstd/io/stdio.rs index fb489bf487b..d71fa133454 100644 --- a/src/libstd/io/stdio.rs +++ b/src/libstd/io/stdio.rs @@ -17,7 +17,7 @@ use io::{self, Initializer, BufReader, LineWriter}; use sync::{Arc, Mutex, MutexGuard}; use sys::stdio; use sys_common::remutex::{ReentrantMutex, ReentrantMutexGuard}; -use thread::{LocalKey, LocalKeyState}; +use thread::LocalKey; /// Stdout used by print! and println! macros thread_local! { @@ -674,20 +674,14 @@ fn print_to(args: fmt::Arguments, local_s: &'static LocalKey>>>, global_s: fn() -> T, label: &str) where T: Write { - let result = match local_s.state() { - LocalKeyState::Uninitialized | - LocalKeyState::Destroyed => global_s().write_fmt(args), - LocalKeyState::Valid => { - local_s.with(|s| { - if let Ok(mut borrowed) = s.try_borrow_mut() { - if let Some(w) = borrowed.as_mut() { - return w.write_fmt(args); - } - } - global_s().write_fmt(args) - }) + let result = local_s.try_with(|s| { + if let Ok(mut borrowed) = s.try_borrow_mut() { + if let Some(w) = borrowed.as_mut() { + return w.write_fmt(args); + } } - }; + global_s().write_fmt(args) + }).unwrap_or_else(|_| global_s().write_fmt(args)); if let Err(e) = result { panic!("failed printing to {}: {}", label, e); } diff --git a/src/libstd/sys_common/thread_info.rs b/src/libstd/sys_common/thread_info.rs index 5ed48ee4558..2abb8afa828 100644 --- a/src/libstd/sys_common/thread_info.rs +++ b/src/libstd/sys_common/thread_info.rs @@ -12,7 +12,6 @@ use cell::RefCell; use thread::Thread; -use thread::LocalKeyState; struct ThreadInfo { stack_guard: Option, @@ -23,19 +22,15 @@ thread_local! { static THREAD_INFO: RefCell> = RefCell::new(N impl ThreadInfo { fn with(f: F) -> Option where F: FnOnce(&mut ThreadInfo) -> R { - if THREAD_INFO.state() == LocalKeyState::Destroyed { - return None - } - - THREAD_INFO.with(move |c| { + THREAD_INFO.try_with(move |c| { if c.borrow().is_none() { *c.borrow_mut() = Some(ThreadInfo { stack_guard: None, thread: Thread::new(None), }) } - Some(f(c.borrow_mut().as_mut().unwrap())) - }) + f(c.borrow_mut().as_mut().unwrap()) + }).ok() } }