file_operation/read/sync/
fn.rs

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