Skip to content

Commit

Permalink
Buffer file I/O
Browse files Browse the repository at this point in the history
  • Loading branch information
jwodder committed Dec 22, 2023
1 parent 176640f commit 4eebe80
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 5 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
v0.2.0 (in development)
-----------------------
- Files opened by the `load()` & `dump()` methods & functions are now wrapped
in `std::io::BufReader`/`std::io::BufWriter`
- Added `Flush` variant to `DumpError`

v0.1.0 (2023-10-30)
-------------------
Expand Down
15 changes: 10 additions & 5 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ use serde::{de::DeserializeOwned, Serialize};
#[allow(unused_imports)]
use serde_path_to_error::{deserialize as depath, serialize as serpath, Error as PathError};
use std::fs::File;
use std::io;
use std::io::{self, Write};
use std::path::Path;
use strum::{Display, EnumIter, EnumString};
use thiserror::Error;
Expand Down Expand Up @@ -457,7 +457,7 @@ impl Format {
/// Returns an error if an I/O error occurs or if the underlying serializer
/// returns an error.
#[allow(unused_mut, unused_variables)]
pub fn dump_to_writer<W: io::Write, T: Serialize>(
pub fn dump_to_writer<W: Write, T: Serialize>(
&self,
mut writer: W,
value: &T,
Expand Down Expand Up @@ -665,7 +665,7 @@ impl Cfgfifo {
/// the underlying deserializer returns an error.
pub fn load<T: DeserializeOwned, P: AsRef<Path>>(&self, path: P) -> Result<T, LoadError> {
let fmt = self.identify(&path)?;
let fp = File::open(path).map_err(LoadError::Open)?;
let fp = io::BufReader::new(File::open(path).map_err(LoadError::Open)?);
fmt.load_from_reader(fp).map_err(Into::into)
}

Expand All @@ -679,8 +679,9 @@ impl Cfgfifo {
/// the underlying serializer returns an error.
pub fn dump<P: AsRef<Path>, T: Serialize>(&self, path: P, value: &T) -> Result<(), DumpError> {
let fmt = self.identify(&path)?;
let fp = File::create(path).map_err(DumpError::Open)?;
fmt.dump_to_writer(fp, value).map_err(Into::into)
let mut fp = io::BufWriter::new(File::create(path).map_err(DumpError::Open)?);
fmt.dump_to_writer(&mut fp, value)?;
fp.flush().map_err(DumpError::Flush)
}
}

Expand Down Expand Up @@ -858,6 +859,10 @@ pub enum DumpError {
/// Returned if serialization failed
#[error("failed to serialize structure")]
Serialize(#[from] SerializeError),

/// Returned if flushing the file failed after writing
#[error("failed to flush output file")]
Flush(#[source] io::Error),
}

#[cfg(feature = "ron")]
Expand Down

0 comments on commit 4eebe80

Please sign in to comment.