Skip to content

Commit

Permalink
Merge pull request #151 from andjo403/to_small_file
Browse files Browse the repository at this point in the history
return error if the file is too small instead of panicking
  • Loading branch information
wesleywiser authored Feb 9, 2021
2 parents 9591c4d + 7d3323e commit 3807a1f
Showing 1 changed file with 21 additions and 3 deletions.
24 changes: 21 additions & 3 deletions measureme/src/file_header.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,12 +43,23 @@ pub fn verify_file_header(
// The implementation here relies on FILE_HEADER_SIZE to have the value 8.
// Let's make sure this assumption cannot be violated without being noticed.
assert_eq!(FILE_HEADER_SIZE, 8);
assert!(bytes.len() >= FILE_HEADER_SIZE);

let actual_magic = &bytes[0..4];

let diagnostic_file_path = diagnostic_file_path.unwrap_or(Path::new("<in-memory>"));

if bytes.len() < FILE_HEADER_SIZE {
let msg = format!(
"Error reading {} stream in file `{}`: Expected file to contain at least `{:?}` bytes but found `{:?}` bytes",
stream_tag,
diagnostic_file_path.display(),
FILE_HEADER_SIZE,
bytes.len()
);

return Err(From::from(msg));
}

let actual_magic = &bytes[0..4];

if actual_magic != expected_magic {
let msg = format!(
"Error reading {} stream in file `{}`: Expected file magic `{:?}` but found `{:?}`",
Expand Down Expand Up @@ -124,4 +135,11 @@ mod tests {
data[7] = 0xFF;
assert!(verify_file_header(&data, FILE_MAGIC_STRINGTABLE_INDEX, None, "test").is_err());
}

#[test]
fn empty_file() {
let data: [u8; 0] = [];

assert!(verify_file_header(&data, FILE_MAGIC_STRINGTABLE_DATA, None, "test").is_err());
}
}

0 comments on commit 3807a1f

Please sign in to comment.