From eedcf9a1b1204cf0d9b1713f05bbfcc402c75e19 Mon Sep 17 00:00:00 2001 From: Dmitry Date: Tue, 13 Sep 2022 11:38:04 +0300 Subject: [PATCH] process_files refactor --- src/main.rs | 60 ++++++++++++++++++++++------------------------------- 1 file changed, 25 insertions(+), 35 deletions(-) diff --git a/src/main.rs b/src/main.rs index 8207136..9b96171 100644 --- a/src/main.rs +++ b/src/main.rs @@ -22,22 +22,6 @@ struct OutFileDescr<'a> { trap: EncoderTrap, } -impl<'a> OutFileDescr<'a> { - fn new( - name: String, - options: &'a FileOptions, - enc: &'a dyn Encoding, - trap: EncoderTrap, - ) -> OutFileDescr<'a> { - OutFileDescr { - name, - options, - encoding: enc, - trap, - } - } -} - fn read_file(file: impl Read, enc: &dyn Encoding) -> Result> { let buf = io::BufReader::new(file); let mut reader = TextReader::new(buf, enc, DecoderTrap::Ignore); @@ -58,9 +42,9 @@ fn write_file( Ok(()) } -fn process_files(files: &[PathBuf]) { +fn process_files(files: &[PathBuf]) -> Result<(), Box> { if files.is_empty() { - return; + return Ok(()); } let enc_input = KOI8_R; @@ -68,32 +52,38 @@ fn process_files(files: &[PathBuf]) { let options = zip::write::FileOptions::default() .compression_method(zip::CompressionMethod::Deflated) .compression_level(Some(9)); + let file_def = OutFileDescr { + name: String::new(), + options: &options, + encoding: enc_output, + trap: EncoderTrap::Ignore, + }; - let zip_file = fs::File::open(INPUT_FILENAME).unwrap(); + let zip_file = fs::File::open(INPUT_FILENAME)?; let zip_reader = io::BufReader::new(zip_file); - let mut archive = zip::ZipArchive::new(zip_reader).unwrap(); + let mut archive = zip::ZipArchive::new(zip_reader)?; - let mut outfile = fs::File::create(OUTPUT_FILENAME).unwrap(); + let mut outfile = fs::File::create(OUTPUT_FILENAME)?; let mut zip_writer = ZipWriter::new(&mut outfile); - files.iter().for_each(|name| { - let name_str = name.to_str().unwrap(); + for name in files { + let name_str = name.to_str().ok_or("name to str err")?; // read string from file in input zip - let file = archive.by_name(name_str).unwrap(); - let data = read_file(file, enc_input).unwrap(); + let file = archive.by_name(name_str)?; + let data = read_file(file, enc_input)?; // write string to file in output zip - let out_file = OutFileDescr::new( - name_str.to_string(), - &options, - enc_output, - EncoderTrap::Ignore, - ); - write_file(&mut zip_writer, out_file, data).unwrap(); - }); + let out_file = OutFileDescr { + name: name_str.to_string(), + ..file_def + }; + write_file(&mut zip_writer, out_file, data)?; + } - zip_writer.finish().unwrap(); + zip_writer.finish()?; + + Ok(()) } fn main() -> Result<(), Box> { @@ -122,7 +112,7 @@ fn main() -> Result<(), Box> { source_files.sort(); let source_files = source_files; - process_files(&source_files); + process_files(&source_files)?; println!("done"); Ok(())