pub struct Utils;
impl Utils {
pub fn md5(data: &[u8]) -> Vec<u8> {
use md5::{Digest, Md5};
let mut hasher = Md5::new();
hasher.update(data);
hasher.finalize().to_vec()
}
pub fn sha1(data: &[u8]) -> Vec<u8> {
use sha1::{Digest, Sha1};
let mut hasher = Sha1::new();
hasher.update(data);
hasher.finalize().to_vec()
}
}
pub(crate) fn temporary_sibling(
destination: &std::path::Path,
) -> Result<std::path::PathBuf, crate::error::OpenteleError> {
use std::ffi::OsString;
let parent = destination
.parent()
.unwrap_or_else(|| std::path::Path::new("."));
std::fs::create_dir_all(parent)?;
let file_name = destination.file_name().ok_or_else(|| {
crate::error::OpenteleError::InvalidArgument("output path has no file name".into())
})?;
loop {
let mut temporary_name = OsString::from(".");
temporary_name.push(file_name);
temporary_name.push(format!(".{:016x}.tmp", rand::random::<u64>()));
let candidate = parent.join(temporary_name);
if !candidate.exists() {
return Ok(candidate);
}
}
}
pub(crate) fn replace_file(
temporary: &std::path::Path,
destination: &std::path::Path,
) -> Result<(), crate::error::OpenteleError> {
if !destination.exists() {
std::fs::rename(temporary, destination)?;
return Ok(());
}
let backup = temporary_sibling(destination)?.with_extension("backup");
std::fs::rename(destination, &backup)?;
match std::fs::rename(temporary, destination) {
Ok(()) => {
std::fs::remove_file(backup)?;
Ok(())
}
Err(error) => {
let _ = std::fs::rename(backup, destination);
Err(error.into())
}
}
}