From 587db0464c064f2f29c974216f1ca464c7d54068 Mon Sep 17 00:00:00 2001 From: Matthias Schiffer Date: Sun, 7 May 2023 16:32:13 +0200 Subject: [PATCH] io/storage: use fs::create_with_tmpfile() helper --- src/bin/minedmap/region_processor.rs | 13 +------------ src/io/storage.rs | 9 ++++----- 2 files changed, 5 insertions(+), 17 deletions(-) diff --git a/src/bin/minedmap/region_processor.rs b/src/bin/minedmap/region_processor.rs index e1ea187..d81994f 100644 --- a/src/bin/minedmap/region_processor.rs +++ b/src/bin/minedmap/region_processor.rs @@ -63,19 +63,8 @@ impl<'a> RegionProcessor<'a> { } fn save_region(&self, coords: RegionCoords, processed_region: &ProcessedRegion) -> Result<()> { - let tmp_path = self.config.processed_path(coords, true); - storage::write(&tmp_path, processed_region)?; - let output_path = self.config.processed_path(coords, false); - fs::rename(&tmp_path, &output_path).with_context(|| { - format!( - "Failed to rename {} to {}", - tmp_path.display(), - output_path.display(), - ) - })?; - - Ok(()) + storage::write(&output_path, processed_region) } fn save_lightmap(&self, coords: RegionCoords, lightmap: &image::GrayAlphaImage) -> Result<()> { diff --git a/src/io/storage.rs b/src/io/storage.rs index f4b2eed..c1a9e5e 100644 --- a/src/io/storage.rs +++ b/src/io/storage.rs @@ -7,21 +7,20 @@ use std::{ use anyhow::{Context, Result}; use serde::{de::DeserializeOwned, Serialize}; +use super::fs; + pub fn write(path: &Path, value: &T) -> Result<()> { - (|| -> Result<()> { + fs::create_with_tmpfile(path, |file| { let data = bincode::serialize(value)?; let len = u32::try_from(data.len())?; let compressed = zstd::bulk::compress(&data, 1)?; drop(data); - let mut file = File::create(path)?; file.write_all(&len.to_be_bytes())?; file.write_all(&compressed)?; - file.flush()?; Ok(()) - })() - .with_context(|| format!("Failed to write file {}", path.display())) + }) } pub fn read(path: &Path) -> Result {