From f9050799bb77f2f922ddae97ffd9e9887142800b Mon Sep 17 00:00:00 2001 From: Jakob Naucke Date: Fri, 31 Jan 2025 16:32:28 +0100 Subject: [PATCH] rust/pv_core: Add misc::read_file_string MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Like read_file, this is a function that reads from a file with error handling conveniences, but that reads to a trimmed string instead of a byte vector. Signed-off-by: Jakob Naucke Reviewed-by: Steffen Eiden Signed-off-by: Jan Höppner --- rust/pv_core/src/lib.rs | 3 ++- rust/pv_core/src/utils.rs | 11 +++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/rust/pv_core/src/lib.rs b/rust/pv_core/src/lib.rs index bfb25612..53978145 100644 --- a/rust/pv_core/src/lib.rs +++ b/rust/pv_core/src/lib.rs @@ -20,9 +20,10 @@ pub mod attest { /// Miscellaneous functions and definitions pub mod misc { pub use crate::utils::pv_guest_bit_set; - pub use crate::utils::{create_file, open_file, read_exact_file, read_file, write_file}; + pub use crate::utils::{create_file, open_file}; pub use crate::utils::{decode_hex, encode_hex, parse_hex}; pub use crate::utils::{read, write}; + pub use crate::utils::{read_exact_file, read_file, read_file_string, write_file}; pub use crate::utils::{to_u16, to_u32, try_parse_u128, try_parse_u64}; pub use crate::utils::{Flags, Lsb0Flags64, Msb0Flags64}; } diff --git a/rust/pv_core/src/utils.rs b/rust/pv_core/src/utils.rs index 27055a97..08758e14 100644 --- a/rust/pv_core/src/utils.rs +++ b/rust/pv_core/src/utils.rs @@ -262,6 +262,17 @@ pub fn read_exact_file, const COUNT: usize>( Ok(buf) } +/// Read content from a file as string and add context in case of an error +/// +/// * `path` - Path to file +/// * `ctx` - Error context string in case of an error +/// +/// # Errors +/// Passes through any kind of error `std::fs::read` produces +pub fn read_file_string>(path: P, ctx: &str) -> Result { + std::fs::read_to_string(&path).map_err(|e| file_error!(Read, ctx, path, e)) +} + /// Read content from a file and add context in case of an error /// /// * `path` - Path to file