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 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.
27pub async fn async_read_from_file<T>(file_path: &str) -> Result<T, Box<dyn std::error::Error>>
28where
29 T: From<Vec<u8>>,
30{
31 let path: &Path = Path::new(file_path);
32 let mut file: File = File::open(path).await?;
33 let mut content: Vec<u8> = Vec::new();
34 file.read_to_end(&mut content).await?;
35 Ok(T::from(content))
36}
37
38/// Retrieves the size of a file at the specified `file_path` in bytes.
39///
40/// # Parameters
41/// - `file_path`: The path to the file whose size is to be fetched.
42///
43/// # Returns
44/// - `Option<u64>`:
45/// - `Some(size)`: The size of the file in bytes if the file exists and its metadata can be accessed.
46/// - `None`: If the file doesn't exist, or there is an error retrieving the file's metadata.
47///
48/// # Errors
49/// - If the file at `file_path` doesn't exist, or there is an issue accessing its metadata,
50/// the function will return `None` to indicate the failure.
51///
52/// # Notes
53/// - The function uses `metadata` to retrieve the file's metadata and specifically its size (`metadata.len()`).
54/// If the file metadata is not accessible or the file does not exist, the function will return `None`.
55/// This is useful when you want to safely handle cases where the file might not be present or readable.
56pub async fn async_get_file_size(file_path: &str) -> Option<u64> {
57 metadata(file_path)
58 .await
59 .and_then(|metadata| Ok(Some(metadata.len())))
60 .unwrap_or(None)
61}