#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)

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

#994 in Rust patterns

Download history 11/week @ 2024-02-24 2/week @ 2024-03-02 17/week @ 2024-03-30 66/week @ 2024-04-06

83 downloads per month

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