file_operation/file/read/async.rs
1use std::path::Path;
2use tokio::fs::*;
3use tokio::io::AsyncReadExt;
4
5/// Reads the content of a file at the specified `file_path` and converts it to the type `T`.
6/// The conversion is done by using the `From<Vec<u8>>` trait, which allows the file content
7/// (read as raw bytes) to be converted into a type `T`.
8///
9/// # Parameters
10/// - `file_path`: The path to the file that will be read.
11///
12/// # Returns
13/// - `Result<T, Box<dyn std::error::Error>>`:
14/// - `Ok(T)`: The file was read successfully and converted to the specified type `T`.
15/// - `Err(Box<dyn std::error::Error>)`: An error occurred while opening or reading the file.
16/// This will contain any errors encountered during the file operations, including I/O or conversion errors.
17///
18/// # Errors
19/// - This function may return an error if:
20/// - The file at `file_path` does not exist.
21/// - There is an I/O error while reading the file.
22/// - The content of the file cannot be converted to type `T`.
23///
24/// # Notes
25/// - The function assumes that the content of the file can be represented as a byte vector (`Vec<u8>`),
26/// which is then passed to `T::from` for conversion.
27#[inline]
28pub async fn async_read_from_file<T>(file_path: &str) -> Result<T, Box<dyn std::error::Error>>
29where
30 T: From<Vec<u8>>,
31{
32 let path: &Path = Path::new(file_path);
33 let mut file: File = File::open(path).await?;
34 let mut content: Vec<u8> = Vec::new();
35 file.read_to_end(&mut content).await?;
36 Ok(T::from(content))
37}
38
39/// Retrieves the size of a file at the specified `file_path` in bytes.
40///
41/// # Parameters
42/// - `file_path`: The path to the file whose size is to be fetched.
43///
44/// # Returns
45/// - `Option<u64>`:
46/// - `Some(size)`: The size of the file in bytes if the file exists and its metadata can be accessed.
47/// - `None`: If the file doesn't exist, or there is an error retrieving the file's metadata.
48///
49/// # Errors
50/// - If the file at `file_path` doesn't exist, or there is an issue accessing its metadata,
51/// the function will return `None` to indicate the failure.
52///
53/// # Notes
54/// - The function uses `metadata` to retrieve the file's metadata and specifically its size (`metadata.len()`).
55/// If the file metadata is not accessible or the file does not exist, the function will return `None`.
56/// This is useful when you want to safely handle cases where the file might not be present or readable.
57#[inline]
58pub async fn async_get_file_size(file_path: &str) -> Option<u64> {
59 metadata(file_path)
60 .await
61 .and_then(|metadata| Ok(Some(metadata.len())))
62 .unwrap_or(None)
63}