use std::{
fs::{self, File},
io::Write,
path::Path,
};
use crate::DbError;
pub(crate) fn atomic_write(
directory: &Path,
temp_path: &Path,
final_path: &Path,
bytes: &[u8],
) -> Result<(), DbError> {
fs::create_dir_all(directory)
.map_err(|error| DbError::io("create database directory", error))?;
let mut file =
File::create(temp_path).map_err(|error| DbError::io("create temp file", error))?;
file.write_all(bytes)
.map_err(|error| DbError::io("write temp file", error))?;
file.flush()
.map_err(|error| DbError::io("flush temp file", error))?;
file.sync_all()
.map_err(|error| DbError::io("sync temp file", error))?;
fs::rename(temp_path, final_path).map_err(|error| DbError::io("publish file", error))?;
sync_directory(directory)
}
#[cfg(unix)]
pub(crate) fn sync_directory(path: &Path) -> Result<(), DbError> {
let directory =
File::open(path).map_err(|error| DbError::io("open database directory", error))?;
directory
.sync_all()
.map_err(|error| DbError::io("sync database directory", error))
}
#[cfg(not(unix))]
pub(crate) fn sync_directory(_path: &Path) -> Result<(), DbError> {
Ok(())
}