use std::cell::RefCell;
use std::fmt::Arguments;
use std::io::Write;
thread_local! {
static HELD: RefCell<Option<Vec<u8>>> = const { RefCell::new(None) };
}
pub fn line(args: Arguments<'_>) {
let held = HELD.with(|held| {
let mut held = held.borrow_mut();
let buffer = held.as_mut()?;
let _ = writeln!(buffer, "{args}");
Some(())
});
if held.is_none() {
println!("{args}");
}
}
pub fn held<T>(f: impl FnOnce() -> T) -> (T, Vec<u8>) {
HELD.with(|held| *held.borrow_mut() = Some(Vec::new()));
let value = f();
let written = HELD
.with(|held| held.borrow_mut().take())
.unwrap_or_default();
(value, written)
}
pub fn release(written: &[u8]) {
let mut stdout = std::io::stdout().lock();
if let Err(e) = stdout.write_all(written) {
panic!("failed printing to stdout: {e}");
}
}
#[macro_export]
macro_rules! say {
() => {
$crate::out::line(format_args!(""))
};
($($arg:tt)*) => {
$crate::out::line(format_args!($($arg)*))
};
}