Skip to content

Commit

Permalink
fix: added filename to the error message in case of read errors (#235)
Browse files Browse the repository at this point in the history
  • Loading branch information
pamburus authored May 3, 2024
1 parent 361a2a5 commit e62600c
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 4 deletions.
4 changes: 2 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ members = [".", "crate/encstr"]
[workspace.package]
repository = "https://github.com/pamburus/hl"
authors = ["Pavel Ivanov <mr.pavel.ivanov@gmail.com>"]
version = "0.29.0-alpha.6"
version = "0.29.0-alpha.7"
edition = "2021"
license = "MIT"

Expand Down
50 changes: 49 additions & 1 deletion src/input.rs
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,10 @@ pub struct Input {

impl Input {
pub fn new(reference: InputReference, stream: InputStream) -> Self {
Self { reference, stream }
Self {
reference: reference.clone(),
stream: Box::new(WrappedInputStream { reference, stream }),
}
}

pub fn open(path: &PathBuf) -> io::Result<Self> {
Expand All @@ -173,6 +176,24 @@ impl Input {

// ---

pub struct WrappedInputStream {
reference: InputReference,
stream: InputStream,
}

impl Read for WrappedInputStream {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
self.stream.read(buf).map_err(|e| {
io::Error::new(
e.kind(),
format!("failed to read {}: {}", self.reference.description(), e),
)
})
}
}

// ---

pub struct IndexedInput {
pub reference: InputReference,
pub stream: InputSeekStream,
Expand Down Expand Up @@ -491,3 +512,30 @@ impl<T: Read + Send + Sync + 'static> AsInputStream for T {
Box::new(self)
}
}

#[cfg(test)]
mod tests {
use super::*;
use std::io::ErrorKind;
use std::io::Read;

#[test]
fn test_input_read_error() {
let reference = InputReference::File(PathBuf::from("test.log"));
let mut input = Input::new(reference, Box::new(FailingReader));
let mut buf = [0; 128];
let result = input.stream.read(&mut buf);
assert!(result.is_err());
let err = result.unwrap_err();
assert_eq!(err.kind(), ErrorKind::Other);
assert_eq!(err.to_string().contains("test.log"), true);
}

struct FailingReader;

impl Read for FailingReader {
fn read(&mut self, _buf: &mut [u8]) -> std::io::Result<usize> {
Err(std::io::Error::new(std::io::ErrorKind::Other, "read error"))
}
}
}

0 comments on commit e62600c

Please sign in to comment.