use std::fmt;
use std::io::{self, Write};
const SIGPIPE_EXIT: i32 = 141;
pub(crate) fn write_stdout(args: fmt::Arguments<'_>, newline: bool) {
let mut out = io::stdout().lock();
let result = out
.write_fmt(args)
.and_then(|()| if newline { out.write_all(b"\n") } else { Ok(()) })
.and_then(|()| out.flush());
if let Err(error) = result {
if error.kind() == io::ErrorKind::BrokenPipe {
std::process::exit(SIGPIPE_EXIT);
}
let _ = writeln!(io::stderr(), "error: failed to write stdout: {error}");
std::process::exit(1);
}
}
pub(crate) fn write_stderr(args: fmt::Arguments<'_>, newline: bool) {
let mut out = io::stderr().lock();
let result = out
.write_fmt(args)
.and_then(|()| if newline { out.write_all(b"\n") } else { Ok(()) })
.and_then(|()| out.flush());
if let Err(error) = result
&& error.kind() == io::ErrorKind::BrokenPipe
{
std::process::exit(SIGPIPE_EXIT);
}
}
macro_rules! println {
() => {
$crate::output::write_stdout(format_args!(""), true)
};
($($arg:tt)*) => {
$crate::output::write_stdout(format_args!($($arg)*), true)
};
}
macro_rules! print {
($($arg:tt)*) => {
$crate::output::write_stdout(format_args!($($arg)*), false)
};
}
macro_rules! eprintln {
() => {
$crate::output::write_stderr(format_args!(""), true)
};
($($arg:tt)*) => {
$crate::output::write_stderr(format_args!($($arg)*), true)
};
}
#[cfg(test)]
mod tests {
use super::SIGPIPE_EXIT;
#[test]
fn sigpipe_exit_matches_shell_convention() {
assert_eq!(SIGPIPE_EXIT, 141);
}
}