use std::io::{
Read,
Write,
};
use crate::{
FileSystem,
FsError,
FsErrorKind,
FsOperation,
FsPath,
FsResult,
ReadOptions,
WriteOptions,
WriteOutcome,
};
pub trait FileSystemExt {
fn read_all(&self, path: &FsPath) -> FsResult<Vec<u8>>;
fn write_all(&self, path: &FsPath, bytes: &[u8]) -> FsResult<WriteOutcome>;
}
impl<T> FileSystemExt for T
where
T: FileSystem + ?Sized,
{
fn read_all(&self, path: &FsPath) -> FsResult<Vec<u8>> {
let mut reader = self.open_reader(path, &ReadOptions::default())?;
let mut bytes = Vec::new();
reader.read_to_end(&mut bytes).map_err(|error| {
FsError::with_source(
FsErrorKind::Io,
FsOperation::OpenReader,
"failed to read resource",
error,
)
.with_path(path.clone())
})?;
Ok(bytes)
}
fn write_all(&self, path: &FsPath, bytes: &[u8]) -> FsResult<WriteOutcome> {
let mut writer = self.open_writer(path, &WriteOptions::default())?;
if let Err(error) = writer.write_all(bytes) {
let _ = writer.abort();
return Err(FsError::with_source(
FsErrorKind::Io,
FsOperation::OpenWriter,
"failed to write resource",
error,
)
.with_path(path.clone()));
}
writer.commit()
}
}