Crates.io | shim-fs |
lib.rs | shim-fs |
version | 0.1.0 |
source | src |
created_at | 2022-01-06 18:01:07.849804 |
updated_at | 2022-01-06 18:01:07.849804 |
description | A drop-in replacement for std::fs::File that redirects all disk writes to memory. |
homepage | |
repository | https://git.sr.ht/~mvforell/shim-fs |
max_upload_size | |
id | 509101 |
size | 12,111 |
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
.
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.
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())
}
}