From 52074cf1622436b6b701fe07b2aac47643eaca59 Mon Sep 17 00:00:00 2001 From: DaniPopes <57450786+DaniPopes@users.noreply.github.com> Date: Thu, 28 Dec 2023 21:41:32 +0100 Subject: [PATCH] Don't initialize stdout during io cleanup Slightly simplify the `std::io::cleanup` code by using `OnceCell::get` instead of checking initialization manually with `get_or_init`. This also has the consequence of not initializing stdout with an empty buffer if it hasn't been already, but I believe this is inconsequential given that this code only runs at process exit. --- library/std/src/io/stdio.rs | 8 +------- library/std/src/rt.rs | 4 ++-- 2 files changed, 3 insertions(+), 9 deletions(-) diff --git a/library/std/src/io/stdio.rs b/library/std/src/io/stdio.rs index 05b21eeb40f71..1fac8f997da05 100644 --- a/library/std/src/io/stdio.rs +++ b/library/std/src/io/stdio.rs @@ -623,13 +623,7 @@ pub fn stdout() -> Stdout { // by replacing the line writer by one with zero // buffering capacity. pub fn cleanup() { - let mut initialized = false; - let stdout = STDOUT.get_or_init(|| { - initialized = true; - ReentrantMutex::new(RefCell::new(LineWriter::with_capacity(0, stdout_raw()))) - }); - - if !initialized { + if let Some(stdout) = STDOUT.get() { // The buffer was previously initialized, overwrite it here. // We use try_lock() instead of lock(), because someone // might have leaked a StdoutLock, which would diff --git a/library/std/src/rt.rs b/library/std/src/rt.rs index 335944845ae0b..8e0a5f3dc8e05 100644 --- a/library/std/src/rt.rs +++ b/library/std/src/rt.rs @@ -111,11 +111,11 @@ unsafe fn init(argc: isize, argv: *const *const u8, sigpipe: u8) { // NOTE: this is not guaranteed to run, for example when the program aborts. pub(crate) fn cleanup() { static CLEANUP: Once = Once::new(); - CLEANUP.call_once(|| unsafe { + CLEANUP.call_once(|| { // Flush stdout and disable buffering. crate::io::cleanup(); // SAFETY: Only called once during runtime cleanup. - sys::cleanup(); + unsafe { sys::cleanup() }; }); }