use std::io::{ErrorKind, Write};
use std::path::{Path, PathBuf};
use super::error::StoreError;
pub fn publish_compressed_node(
final_path: &Path,
compressed: &[u8],
) -> Result<Option<PathBuf>, StoreError> {
let Some(parent_dir) = final_path.parent() else {
return Err(StoreError::MissingParentDirectory {
path: final_path.to_path_buf(),
});
};
let mut temp_file = tempfile::Builder::new()
.prefix(".node-")
.suffix(".tmp")
.tempfile_in(parent_dir)
.map_err(StoreError::Io)?;
temp_file.write_all(compressed).map_err(StoreError::Io)?;
temp_file.as_file_mut().sync_all().map_err(StoreError::Io)?;
match temp_file.persist_noclobber(final_path) {
Ok(_file) => Ok(Some(parent_dir.to_path_buf())),
Err(error) if error.error.kind() == ErrorKind::AlreadyExists => Ok(None),
Err(error) => Err(StoreError::Io(error.error)),
}
}
pub fn path_exists(path: &Path) -> Result<bool, StoreError> {
path.try_exists().map_err(StoreError::Io)
}
pub fn compress_node(serialised: &[u8]) -> Result<Vec<u8>, StoreError> {
zstd::stream::encode_all(serialised, 0)
.map_err(|error| StoreError::Compression(error.to_string()))
}
pub fn decompress_node(compressed: &[u8]) -> Result<Vec<u8>, StoreError> {
zstd::stream::decode_all(compressed).map_err(|error| StoreError::Compression(error.to_string()))
}