use std::path::{Path, PathBuf};
use serde::{Serialize, de::DeserializeOwned};
use tokio::{
fs::{File, OpenOptions},
io::{AsyncReadExt, AsyncWriteExt},
};
pub async fn read_file<P, T>(path: P) -> std::io::Result<T>
where
P: AsRef<Path>,
T: DeserializeOwned,
{
let mut buf = Vec::new();
File::open(path.as_ref())
.await?
.read_to_end(&mut buf)
.await?;
serde_json::from_slice(&buf).map_err(std::io::Error::other)
}
pub async fn write_file(path: impl AsRef<Path>, content: &impl Serialize) -> std::io::Result<()> {
let buf = serde_json::to_vec(content).map_err(std::io::Error::other)?;
OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.open(path.as_ref())
.await?
.write_all(&buf)
.await?;
Ok(())
}
pub fn get_tmp_path<S: AsRef<str>>(name: S) -> PathBuf {
let path = std::env::temp_dir();
let current_thread = std::thread::current().id();
path.join(format!("{:?}_{}", current_thread, name.as_ref()))
}