use crate::error::{Error, Result};
use serde::Serialize;
use serde::de::DeserializeOwned;
use std::fs;
use std::io::{ErrorKind, Write};
use std::path::Path;
pub fn read_toml<T: DeserializeOwned>(path: &Path, label: &str) -> Result<T> {
let content = fs::read_to_string(path)
.map_err(|e| Error::State(format!("Failed to read {label}: {e}")))?;
toml::from_str(&content).map_err(|e| Error::State(format!("Failed to parse {label}: {e}")))
}
pub fn write_toml_atomic<T: Serialize>(path: &Path, value: &T, label: &str) -> Result<()> {
let content = toml::to_string(value)
.map_err(|e| Error::State(format!("Failed to serialize {label}: {e}")))?;
write_atomic(path, &content, label)
}
pub fn write_atomic(path: &Path, content: &str, label: &str) -> Result<()> {
let nonce = {
use std::time::{SystemTime, UNIX_EPOCH};
let nanos = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.subsec_nanos();
std::process::id() ^ nanos
};
let mut tmp_path = path.with_extension(format!("{nonce}.tmp"));
let mut file = None;
for attempt in 0..64u32 {
if attempt > 0 {
tmp_path = path.with_extension(format!("{nonce}-{attempt}.tmp"));
}
match fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&tmp_path)
{
Ok(f) => {
file = Some(f);
break;
}
Err(e) if e.kind() == ErrorKind::AlreadyExists => {}
Err(e) => {
return Err(Error::State(format!(
"Failed to create {label} temp file: {e}"
)));
}
}
}
{
let mut f = file.ok_or_else(|| {
Error::State(format!("Failed to create {label} temp file: no free name"))
})?;
f.write_all(content.as_bytes())
.map_err(|e| Error::State(format!("Failed to write {label}: {e}")))?;
}
fs::rename(&tmp_path, path).map_err(|e| {
let _ = fs::remove_file(&tmp_path); Error::State(format!("Failed to finalize {label}: {e}"))
})
}