file_operation/read/sync/
fn.rs

1use crate::*;
2
3/// Reads the content of a file and converts it to the specified type.
4///
5/// # Arguments
6///
7/// - `&str` - The path to the file to read.
8///
9/// # Returns
10///
11/// - `Result<T, Box<dyn std::error::Error + Send + Sync>>` - The converted file content or an error.
12pub fn read_from_file<T>(file_path: &str) -> Result<T, Box<dyn std::error::Error>>
13where
14    T: From<Vec<u8>>,
15{
16    let path: &Path = Path::new(file_path);
17    let mut file: std::fs::File = std::fs::File::open(path)?;
18    let mut content: Vec<u8> = Vec::new();
19    std::io::Read::read_to_end(&mut file, &mut content)?;
20    Ok(T::from(content))
21}
22
23/// Gets the size of a file in bytes.
24///
25/// # Arguments
26///
27/// - `&str` - The path to the file.
28///
29/// # Returns
30///
31/// - `Option<u64>` - The file size in bytes if successful, None otherwise.
32pub fn get_file_size(file_path: &str) -> Option<u64> {
33    std::fs::metadata(file_path)
34        .map(|metadata| Some(metadata.len()))
35        .unwrap_or(None)
36}