Skip to content

Instantly share code, notes, and snippets.

@python273
Created May 5, 2021 18:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save python273/3c31f15a82b71a5c74cc474765f202bc to your computer and use it in GitHub Desktop.
Save python273/3c31f15a82b71a5c74cc474765f202bc to your computer and use it in GitHub Desktop.
Rust piping fix (e.g. when piping into less or head)
thread 'main' panicked at 'failed printing to stdout: Broken pipe (os error 32)', library/std/src/io/stdio.rs:940:9
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
use std::error;
use std::io::Write;


fn main() -> std::result::Result<(), Box<dyn error::Error>> {
    let stdout = std::io::stdout();
    let mut handle = stdout.lock();

    /// Fixes piping error
    /// https://github.com/rust-lang/rust/issues/46016
    macro_rules! println {
        () => (
            if let Err(_) = writeln!(handle) { return Ok(()); }
        );
        ($($arg:tt)*) => (
            if let Err(_) = writeln!(handle, $($arg)*) { return Ok(()); }
        );
    }

    for i in 0..8128 {
        println!("hello world!");
    };

    Ok(())
}

or

use std::error;
use std::io::Write;


/// Fixes piping error
/// https://github.com/rust-lang/rust/issues/46016
macro_rules! myprintln {
    ($dst:expr $(,)?) => (
        if let Err(_) = writeln!($dst) { return Ok(()); }
    );
    ($dst:expr, $($arg:tt)*) => (
        if let Err(_) = writeln!($dst, $($arg)*) { return Ok(()); }
    );
}


fn main() -> std::result::Result<(), Box<dyn error::Error>> {
    let stdout = std::io::stdout();
    let mut handle = stdout.lock();

    for i in 0..8128 {
        myprintln!(handle, "hello world!");
    };

    Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment