write_to_file/function.rs
1use std::{
2 fs,
3 io::Write,
4 path::Path
5};
6
7/// Write `buf` to `path`, with create required directories if not exists.
8/// ```rust
9/// // write binary
10/// let buf = vec![1u8, 2, 3, 4]; // Both of Vec<u8> and &[u8] are supported.
11/// let path = "target/test/path/to/file.bin";
12/// write_to_file::write_to_file(path, buf);
13/// // write text
14/// let buf = "Nyanko is one of the greatest life."; // Both of String and str are supported.
15/// let path = "target/test/path/to/file.txt";
16/// write_to_file::write_to_file(path, buf);
17/// ```
18pub fn write_to_file<P, T>(path: P, buf: T) -> std::io::Result<()>
19where
20 P: AsRef<Path>,
21 T: AsRef<[u8]>
22{
23 let path = path.as_ref();
24
25 if let Some(dir) = path.parent()
26 {
27 fs::create_dir_all(dir)?;
28 }
29
30 fs::OpenOptions::new()
31 .write(true)
32 .create(true)
33 .truncate(true)
34 .open(path)?
35 .write_all(buf.as_ref())
36}