use std::cell::RefCell;
type OutputHook = Option<Box<dyn Fn(&str) + Send>>;
thread_local! {
static STDOUT_HOOK: RefCell<OutputHook> = RefCell::new(None);
static STDERR_HOOK: RefCell<OutputHook> = RefCell::new(None);
}
pub fn set_stdout_hook(hook: OutputHook) {
STDOUT_HOOK.with(|cell| *cell.borrow_mut() = hook);
}
pub fn set_stderr_hook(hook: OutputHook) {
STDERR_HOOK.with(|cell| *cell.borrow_mut() = hook);
}
pub fn write_stdout(s: &str) {
STDOUT_HOOK.with(|cell| {
if let Some(hook) = cell.borrow().as_ref() {
hook(s);
} else {
print!("{}", s);
}
});
}
pub fn write_stderr(s: &str) {
STDERR_HOOK.with(|cell| {
if let Some(hook) = cell.borrow().as_ref() {
hook(s);
} else {
eprint!("{}", s);
}
});
}