#io-error #io #error #file-io #stdio #std #fs-file

io-extra

An extension trait for std::io::Error, with shorthand constructors for various std::io::ErrorKinds

3 releases (breaking)

0.3.0 Apr 12, 2024
0.2.0 Apr 11, 2024
0.1.0 Dec 7, 2023

#2126 in Rust patterns

Download history 21/week @ 2024-09-22 6/week @ 2024-09-29

108 downloads per month
Used in tracing-configuration

MIT/Apache

9KB
140 lines

An extension trait for io::Error, with shorthand constructors for various io::ErrorKinds, and a [context()] method.

use std::{fs::File, io::{self, Write as _}, str};
use io_extra::{IoErrorExt as _, context, with};

fn write_log(contents: &[u8], mut file: File) -> io::Result<()> {
    if let Err(e) = str::from_utf8(contents) {
        return Err(io::Error::invalid_input("`contents` was not UTF-8"))
                           // ^ shorthand constructor
    }
    file.write_all(contents).map_err(with("couldn't write file"))
                                  // ^ easily add context
}

lib.rs:

An extension trait for io::Error, with shorthand constructors for various io::ErrorKinds, and a [context()] method.

use std::{fs::File, io::{self, Write as _}, str};
use io_extra::{IoErrorExt as _, context, with};

fn write_log(contents: &[u8], mut file: File) -> io::Result<()> {
    if let Err(e) = str::from_utf8(contents) {
        return Err(io::Error::invalid_input("`contents` was not UTF-8"))
                           // ^ shorthand constructor
    }
    file.write_all(contents).map_err(with("couldn't write file"))
                                  // ^ easily add context
}

No runtime deps