shim-fs

Crates.ioshim-fs
lib.rsshim-fs
version0.1.0
sourcesrc
created_at2022-01-06 18:01:07.849804
updated_at2022-01-06 18:01:07.849804
descriptionA drop-in replacement for std::fs::File that redirects all disk writes to memory.
homepage
repositoryhttps://git.sr.ht/~mvforell/shim-fs
max_upload_size
id509101
size12,111
Max von Forell (mvforell)

documentation

README

shim-fs

A (near) drop-in replacement for std::fs::File that redirects all disk writes to a memory buffer, with no dependencies. To be precise, the std::io::{Seek, Write} traits are implemented for shim_fs::File.

Possible use cases

This can be useful when third-party code writes something to disk, only for you to read it back into memory immediately afterwards: you still have to modify the third-party code, but if you're lucky (see below for details), you may have to only change a few lines.

Another possible use case is targeting WebAssembly, where normal disk writes are not possible.

A concrete use case scenario: imagine you are using a third-party code-generation crate. The generated code is always written to a file, but you want to further process it and therefore need it in memory. If the crate uses std::fs::File::create() to create the file and no functionality besides the Seek and Write traits is used, it is extremely easy to skip all the intermediate file system stuff and just obtain the written bytes in a buffer: replace the crate's std::fs::File::create() call with shim_fs::File::create() and call shim_fs::get_files() in your code after the third-party crate has done its work. Yes, it's that easy.

Example usage

The following example creates a regular file if the use-shim-fs feature is not enabled. If it is enabled, no file will be created and the writes to the File object will be redirected to memory instead. The contents of the shimmed file can be easily accessed.

#[cfg(feature = "use-shim-fs")]
use shim_fs::File;
#[cfg(not(feature = "use-shim-fs"))]
use std::fs::File;

use std::io::Write;
use std::path::Path;

fn main() {
    let path = Path::new("hello.txt");
    let mut file = File::create(path).unwrap();
    write!(file, "Hello, world!").unwrap();

    #[cfg(feature = "use-shim-fs")]
    {
        assert_eq!(shim_fs::get_files()[path], "Hello, world!".as_bytes())
    }
}
Commit count: 0

cargo fmt