From 7b8c4c9c5f373d6f25ea63ae3f10a0eaa20a65da Mon Sep 17 00:00:00 2001 From: Joshua Goins Date: Thu, 18 Jul 2024 14:17:24 -0400 Subject: [PATCH] Add tests for the string file operations, fix nul terminator handling Since this recently had a hand in patch regression, let's start adding some basic tests for this function. I realized the writing functions did not take into account the nul terminator, which is not correct and has been fixed. --- src/common_file_operations.rs | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/src/common_file_operations.rs b/src/common_file_operations.rs index 88b5ace..f81aa39 100644 --- a/src/common_file_operations.rs +++ b/src/common_file_operations.rs @@ -25,12 +25,12 @@ pub(crate) fn read_string(byte_stream: Vec) -> String { pub(crate) fn write_string(str: &String) -> Vec { let c_string = CString::new(&**str).unwrap(); - c_string.as_bytes().to_vec() + c_string.as_bytes_with_nul().to_vec() } pub(crate) fn get_string_len(str: &String) -> usize { let c_string = CString::new(&**str).unwrap(); - c_string.count_bytes() + c_string.count_bytes() + 1 // for the nul terminator } #[binrw::parser(reader)] @@ -122,4 +122,25 @@ mod tests { assert_eq!(write_bool_as::(&false), DATA[0]); assert_eq!(write_bool_as::(&true), DATA[1]); } + + // "FOO\0" + const STRING_DATA: [u8; 4] = [0x46u8, 0x4Fu8, 0x4Fu8, 0x0u8]; + + #[test] + fn read_string() { + // The nul terminator is supposed to be removed + assert_eq!(crate::common_file_operations::read_string(STRING_DATA.to_vec()), "FOO".to_string()); + } + + #[test] + fn write_string() { + // Supposed to include the nul terminator + assert_eq!(crate::common_file_operations::write_string(&"FOO".to_string()), STRING_DATA.to_vec()); + } + + #[test] + fn get_string_len() { + // Supposed to include the nul terminator + assert_eq!(crate::common_file_operations::get_string_len(&"FOO".to_string()), 4); + } }