use std::fs;
use std::path::{Path, PathBuf};
use std::io;
pub fn get_file_size_bytes<P: AsRef<Path>>(path: P) -> io::Result<u64> {
let metadata = fs::metadata(path)?;
if metadata.is_file() {
Ok(metadata.len())
} else {
Err(io::Error::new(io::ErrorKind::InvalidInput, "Not a file"))
}
}
pub fn get_directory_size_bytes<P: AsRef<Path>>(path: P) -> io::Result<u64> {
let mut total_size = 0;
for entry in fs::read_dir(path)? {
let entry = entry?;
let path = entry.path();
if path.is_file() {
total_size += get_file_size_bytes(&path)?;
}
else if path.is_dir() {
total_size += get_directory_size_bytes(&path)?;
}
}
Ok(total_size)
}
pub fn bytes_to_mb(bytes: u64) -> f64 {
bytes as f64 / 1_048_576.0
}
pub fn get_path_size<P: AsRef<Path>>(path: P) -> io::Result<(u64, f64)> {
let path_ref = path.as_ref();
let size_bytes = if path_ref.is_file() {
get_file_size_bytes(path_ref)?
} else if path_ref.is_dir() {
get_directory_size_bytes(path_ref)?
} else {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"Path does not exist or is not a file or directory"
));
};
let size_mb = bytes_to_mb(size_bytes);
Ok((size_bytes, size_mb))
}
pub fn get_paths_size(paths: &[PathBuf]) -> io::Result<(u64, f64)> {
let mut total_bytes = 0;
for path in paths {
let (bytes, _) = get_path_size(path)?;
total_bytes += bytes;
}
let total_mb = bytes_to_mb(total_bytes);
Ok((total_bytes, total_mb))
}
fn main(){
}