#file-io #io-error #writers #traits #resources #drop #dropping

io-close

An extension trait for safely dropping I/O writers such as File and BufWriter

22 releases

0.3.7 Apr 3, 2021
0.3.6 Apr 2, 2021
0.3.3 Jan 1, 2021
0.3.1 Dec 2, 2020
0.1.9 Nov 22, 2020

#1085 in Rust patterns

Download history 32992/week @ 2024-06-12 30045/week @ 2024-06-19 27512/week @ 2024-06-26 27868/week @ 2024-07-03 28202/week @ 2024-07-10 28461/week @ 2024-07-17 33947/week @ 2024-07-24 31868/week @ 2024-07-31 31791/week @ 2024-08-07 31269/week @ 2024-08-14 30492/week @ 2024-08-21 28407/week @ 2024-08-28 31421/week @ 2024-09-04 28928/week @ 2024-09-11 27782/week @ 2024-09-18 23780/week @ 2024-09-25

117,213 downloads per month
Used in 58 crates (4 directly)

MIT/Apache

12KB
154 lines

Please see https://docs.rs/io-close.


lib.rs:

An extension trait for safely dropping I/O writers such as File and BufWriter. Specifically, it is for I/O writers which may contain a resource handle (such as a raw file descriptor), and where the automatic process of closing this handle during drop may generate an unseen I/O error. Using this trait (called Close) these errors can be seen and dealt with.

In the case of Linux the man page for close(2) has the following to say:

Not checking the return value of close() is a common but nevertheless serious programming error. It is quite possible that errors on a previous write(2) operation are first reported at the final close(). Not checking the return value when closing the file may lead to silent loss of data. This can especially be observed with NFS and with disk quota.

Implementations of Close are provided for most standard library I/O writers and (optionally) for a selection of I/O writers defined in external crates.

BufWriter example

use std::io::{BufWriter, Result, Write};
use io_close::Close;

fn main() -> Result<()> {
    let data = b"hello world";
    let mut buffer = BufWriter::new(tempfile::tempfile()?);
    buffer.write_all(data)?;
    buffer.close()?; // safely drop buffer and its contained File
    Ok(())
}

Optional implementations

Optional implementations of Close are provided for the following I/O writers defined in external crates, enabled through cargo features:

Dependencies

~225KB