From 5db0d9d5bbf6eaca4d65310c1c4c3f6bfcf9dbaa Mon Sep 17 00:00:00 2001 From: Pavel Ivanov Date: Fri, 3 May 2024 14:54:20 +0200 Subject: [PATCH] fix: added filename to the error message in case of read errors --- Cargo.lock | 4 ++-- Cargo.toml | 2 +- src/input.rs | 50 +++++++++++++++++++++++++++++++++++++++++++++++++- 3 files changed, 52 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 41cfc6e9..335c06fb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -600,7 +600,7 @@ checksum = "edd0f118536f44f5ccd48bcb8b111bdc3de888b58c74639dfb034a357d0f206d" [[package]] name = "encstr" -version = "0.29.0-alpha.6" +version = "0.29.0-alpha.7" [[package]] name = "enum-map" @@ -757,7 +757,7 @@ checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" [[package]] name = "hl" -version = "0.29.0-alpha.6" +version = "0.29.0-alpha.7" dependencies = [ "atoi", "bincode", diff --git a/Cargo.toml b/Cargo.toml index 3311f626..f21b05df 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ members = [".", "crate/encstr"] [workspace.package] repository = "https://github.com/pamburus/hl" authors = ["Pavel Ivanov "] -version = "0.29.0-alpha.6" +version = "0.29.0-alpha.7" edition = "2021" license = "MIT" diff --git a/src/input.rs b/src/input.rs index ddf92621..6fb6713c 100644 --- a/src/input.rs +++ b/src/input.rs @@ -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 { @@ -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 { + 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, @@ -491,3 +512,30 @@ impl 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 { + Err(std::io::Error::new(std::io::ErrorKind::Other, "read error")) + } + } +}