Skip to content

Commit

Permalink
jackson's sync write
Browse files Browse the repository at this point in the history
  • Loading branch information
thesuzerain committed Dec 21, 2023
1 parent d875828 commit 6a4a918
Showing 1 changed file with 33 additions and 6 deletions.
39 changes: 33 additions & 6 deletions theseus/src/util/io.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
// IO error
// A wrapper around the tokio IO functions that adds the path to the error message, instead of the uninformative std::io::Error.

use std::path::Path;
use std::{path::Path, io::Write};

use tempfile::NamedTempFile;
use tauri::async_runtime::spawn_blocking;

#[derive(Debug, thiserror::Error)]
pub enum IOError {
Expand Down Expand Up @@ -113,15 +116,39 @@ pub async fn write(
path: impl AsRef<std::path::Path>,
data: impl AsRef<[u8]>,
) -> Result<(), IOError> {
let path = path.as_ref();
tokio::fs::write(path, data)
.await
.map_err(|e| IOError::IOPathError {
let path = path.as_ref().to_owned();
let data = data.as_ref().to_owned();
spawn_blocking(move || {
let cloned_path = path.clone();
sync_write(data, path).map_err(|e| IOError::IOPathError {
source: e,
path: path.to_string_lossy().to_string(),
path: cloned_path.to_string_lossy().to_string(),
})
})
.await
.map_err(|_| {
std::io::Error::new(std::io::ErrorKind::Other, "background task failed")
})??;

Ok(())
}

fn sync_write(
data: impl AsRef<[u8]>,
path: impl AsRef<Path>,
) -> Result<(), std::io::Error> {
let mut tempfile = NamedTempFile::new_in(path.as_ref().parent().ok_or_else(|| {
std::io::Error::new(
std::io::ErrorKind::Other,
"could not get parent directory for temporary file",
)
})?)?;
tempfile.write_all(data.as_ref())?;
let tmp_path = tempfile.into_temp_path();
let path = path.as_ref();
tmp_path.persist(path)?;
std::io::Result::Ok(())
}
// rename
pub async fn rename(
from: impl AsRef<std::path::Path>,
Expand Down

0 comments on commit 6a4a918

Please sign in to comment.