From 73dab7ba938fc46edb922c94a15a0f759c756a61 Mon Sep 17 00:00:00 2001 From: Costin-Robert Sin Date: Tue, 26 Mar 2024 11:18:05 +0200 Subject: [PATCH] Replace `expect` with a safer alternative that returns `None` instead Given the fact that this function returns a `Result`, in case of a failure, the function should either return an `Err` or silent fail. When using `expect`, the program just panics, so none of the above situations happen. I have replaced `expect` with `and_then`. Now the code silent fails in case time before UNIX epoch is not supported, returning `None` instead. Signed-off-by: Costin-Robert Sin --- utils/src/lib.rs | 23 +++++++++++------------ 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/utils/src/lib.rs b/utils/src/lib.rs index 4c7a5c3..861ed18 100644 --- a/utils/src/lib.rs +++ b/utils/src/lib.rs @@ -146,18 +146,17 @@ pub fn read_file_from_fs(file_path: &Path) -> io::Result { }; let metadata = fs::metadata(file_path)?; - let last_modified = metadata.modified().ok().map(|last_modified| { - last_modified - .duration_since(SystemTime::UNIX_EPOCH) - .expect("Time before the UNIX epoch is unsupported") - .as_secs() - }); - let created = metadata.created().ok().map(|created| { - created - .duration_since(SystemTime::UNIX_EPOCH) - .expect("Time before the UNIX epoch is unsupported") - .as_secs() - }); + let last_modified = metadata + .modified() + .ok() + .and_then(|modified| modified.duration_since(SystemTime::UNIX_EPOCH).ok()) + .map(|secs| secs.as_secs()); + + let created = metadata + .created() + .ok() + .and_then(|created| created.duration_since(SystemTime::UNIX_EPOCH).ok()) + .map(|secs| secs.as_secs()); #[cfg(feature = "mime-guess")] let mimetype = mime_guess::from_path(file_path).first_or_octet_stream().to_string();