file_operation/read/async/
fn.rs

1use std::path::Path;
2use tokio::fs::*;
3use tokio::io::AsyncReadExt;
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 async fn async_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).await?;
20    let mut content: Vec<u8> = Vec::new();
21    file.read_to_end(&mut content).await?;
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 async fn async_get_file_size(file_path: &str) -> Option<u64> {
35    metadata(file_path)
36        .await
37        .and_then(|metadata| Ok(Some(metadata.len())))
38        .unwrap_or(None)
39}