in-place

Crates.ioin-place
lib.rsin-place
version0.2.1
sourcesrc
created_at2023-05-18 00:46:47.179074
updated_at2024-07-25 16:22:00.57428
descriptionIn-place file processing
homepage
repositoryhttps://github.com/jwodder/in-place-rs
max_upload_size
id867321
size102,724
John T. Wodder II (jwodder)

documentation

README

Project Status: Active – The project has reached a stable, usable state and is being actively developed. CI Status codecov.io Minimum Supported Rust Version MIT License

GitHub | crates.io | Documentation | Issues | Changelog

The in_place library provides an InPlace type for reading & writing a file "in-place": data that you write ends up at the same filepath that you read from, and in_place takes care of all the necessary mucking about with temporary files for you.

For example, given the file somefile.txt:

'Twas brillig, and the slithy toves
    Did gyre and gimble in the wabe;
All mimsy were the borogoves,
    And the mome raths outgrabe.

and the following program:

use in_place::InPlace;
use std::io::{BufRead, BufReader, Write};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let inp = InPlace::new("somefile.txt").open()?;
    let reader = BufReader::new(inp.reader());
    let mut writer = inp.writer();
    for line in reader.lines() {
        let mut line = line?;
        line.retain(|ch| !"AEIOUaeiou".contains(ch));
        writeln!(writer, "{line}")?;
    }
    inp.save()?;
    Ok(())
}

after running the program, somefile.txt will have been edited in place, reducing it to just:

'Tws brllg, nd th slthy tvs
    Dd gyr nd gmbl n th wb;
ll mmsy wr th brgvs,
    nd th mm rths tgrb.

and no sign of those pesky vowels remains! If you want a sign of those pesky vowels to remain, you can instead save the file's original contents in, say, somefile.txt~ by opening the file with:

let inp = InPlace::new("somefile.txt")
    .backup(in_place::Backup::Append("~".into()))
    .open()?;

or save to someotherfile.txt with:

let inp = InPlace::new("somefile.txt")
    .backup(in_place::Backup::Path("someotherfile.txt".into()))
    .open()?;

If you decide halfway through that you don't want to edit the file (say, because an unrecoverable error occurs), calling inp.discard() instead of inp.save() will close the file handles and reset things to the way they were before. Any changes are also discarded if inp is dropped without saving, except that in that case any errors are silently ignored.

Commit count: 62

cargo fmt