diff --git a/src/cmp.rs b/src/cmp.rs index 0175466..50c0163 100644 --- a/src/cmp.rs +++ b/src/cmp.rs @@ -3,6 +3,7 @@ // For the full copyright and license information, please view the LICENSE-* // files that was distributed with this source code. +use crate::safe_println; use crate::utils::format_failure_to_read_input_file; use std::env::{self, ArgsOs}; use std::ffi::OsString; @@ -721,7 +722,7 @@ fn report_difference( format_visible_byte(to_byte) ); } - println!(); + safe_println!(); } #[cfg(test)] diff --git a/src/diff.rs b/src/diff.rs index f4c0614..c0e5b8f 100644 --- a/src/diff.rs +++ b/src/diff.rs @@ -91,7 +91,7 @@ pub fn main(opts: Peekable) -> ExitCode { params.to.to_string_lossy() ); } else { - io::stdout().write_all(&result).unwrap(); + let _ = io::stdout().write_all(&result); } if result.is_empty() { maybe_report_identical_files(); diff --git a/src/macros.rs b/src/macros.rs index 90a4eaa..18bef11 100644 --- a/src/macros.rs +++ b/src/macros.rs @@ -23,3 +23,15 @@ macro_rules! assert_diff_eq { assert_eq!(actual, $expected); }}; } + +/// A safe version of println!() that does not panic if stdout is redirected to /dev/full +#[macro_export] +macro_rules! safe_println { + () => { + let _ = ::std::io::Write::write_all(&mut ::std::io::stdout(), b"\n"); + }; + ($($arg:tt)*) => { + let _ = ::std::io::Write::write_fmt(&mut ::std::io::stdout(), format_args!($($arg)*)) + .and_then(|_| ::std::io::Write::write_all(&mut ::std::io::stdout(), b"\n")); + }; +} diff --git a/src/main.rs b/src/main.rs index d0adb69..13efd17 100644 --- a/src/main.rs +++ b/src/main.rs @@ -40,10 +40,10 @@ fn name(binary_path: &Path) -> &OsStr { const VERSION: &str = env!("CARGO_PKG_VERSION"); fn usage(name: &str) { - println!("{name} {VERSION} (multi-call binary)\n"); - println!("Usage: {name} [function [arguments...]]\n"); - println!("Currently defined functions:\n"); - println!(" cmp, diff\n"); + safe_println!("{name} {VERSION} (multi-call binary)\n"); + safe_println!("Usage: {name} [function [arguments...]]\n"); + safe_println!("Currently defined functions:\n"); + safe_println!(" cmp, diff\n"); } fn second_arg_error(name: &OsStr) -> ! {