From 442c6c7d74f91fcae56d78d1f1ef2982fcf7153e Mon Sep 17 00:00:00 2001 From: maxmielchen <max@mielchen.email> Date: Fri, 5 Jul 2024 15:17:43 +0200 Subject: [PATCH] chore: Refactor file/helpers.rs for improved readability and maintainability --- src/file/helpers.rs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/src/file/helpers.rs b/src/file/helpers.rs index ff2dc52..31e1cb8 100644 --- a/src/file/helpers.rs +++ b/src/file/helpers.rs @@ -5,10 +5,13 @@ pub const EMPTY: [u8; 1] = [0; 1]; pub const OP_LEN: u8 = 4; pub fn write_empty_byte(file: &mut File) { + let res = file.write(&EMPTY); + if let Err(e) = res { panic!("Failed to write empty byte: {}", e); } + if res.unwrap() != EMPTY.len() { panic!("Failed to write empty byte: {}", "Write length mismatch."); } @@ -34,6 +37,7 @@ pub fn cut(file: &mut File) { } pub fn truncate(file: &mut File) { + let res = file.set_len(0); if let Err(e) = res { @@ -45,6 +49,7 @@ pub fn truncate(file: &mut File) { } pub fn jump_stream_start(file: &mut File) { + let res = file.seek(SeekFrom::Start(0)); if let Err(e) = res { @@ -53,6 +58,7 @@ pub fn jump_stream_start(file: &mut File) { } pub fn jump_stream_end(file: &mut File) { + let res = file.seek(SeekFrom::End(-1)); if let Err(e) = res { @@ -61,6 +67,7 @@ pub fn jump_stream_end(file: &mut File) { } pub fn catch_stream_read(file: &mut File, read: usize, predict: usize, fix_fn: fn(file: &mut File)) -> Result<(), Error> { + if read != predict { fix_fn(file); return Err( @@ -70,6 +77,7 @@ pub fn catch_stream_read(file: &mut File, read: usize, predict: usize, fix_fn: f ) ); } + Ok(()) } @@ -170,6 +178,7 @@ pub fn read(file: &mut File) -> Result<Vec<u8>, Error> { } pub fn seek_forward(file: &mut File) -> Result<(), Error> { + let mut len_buf: [u8; OP_LEN as usize] = [0; OP_LEN as usize]; let res = file.read(&mut len_buf); @@ -203,6 +212,7 @@ pub fn seek_forward(file: &mut File) -> Result<(), Error> { } pub fn seek_backward(file: &mut File) -> Result<(), Error> { + let mut len_buf: [u8; OP_LEN as usize] = [0; OP_LEN as usize]; let res = file.seek(SeekFrom::Current(-(OP_LEN as i64))); @@ -251,6 +261,7 @@ pub fn seek_backward(file: &mut File) -> Result<(), Error> { } pub fn seek_forward_n(file: &mut File, n: u64) -> Result<(), Error> { + for _ in 0..n { seek_forward(file)?; } @@ -258,6 +269,7 @@ pub fn seek_forward_n(file: &mut File, n: u64) -> Result<(), Error> { } pub fn seek_backward_n(file: &mut File, n: u64) -> Result<(), Error> { + for _ in 0..n { seek_backward(file)?; } @@ -265,6 +277,7 @@ pub fn seek_backward_n(file: &mut File, n: u64) -> Result<(), Error> { } pub fn inner_len(file: &mut File) -> Result<u32, Error> { + let mut len_buf: [u8; OP_LEN as usize] = [0; OP_LEN as usize]; let res = file.read(&mut len_buf); @@ -291,6 +304,7 @@ pub fn inner_len(file: &mut File) -> Result<u32, Error> { } pub fn len_calc(inner_lens: Vec<u32>, op_sets: u8) -> i64 { + let mut len = 0; for inner_len in inner_lens { len += inner_len as u64 + 2*OP_LEN as u64;