mod falloc;
mod strategies;
#[cfg(windows)]
mod windows;
#[cfg(test)]
mod tests;
pub use crate::filesystem::disk_space::{check_disk_space, check_disk_space_async};
pub use strategies::get_available_space;
use super::disk_adaptor::{DirectDiskAdaptor, DiskAdaptor};
use crate::error::{Aria2Error, FatalError, Result};
use std::path::Path;
#[cfg_attr(target_os = "linux", allow(dead_code))]
static SECURE_FALLOC_WARN_ONCE: std::sync::Once = std::sync::Once::new();
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub enum AllocationStrategy {
#[default]
None,
Prealloc,
Falloc,
Trunc,
Mmap,
}
impl AllocationStrategy {
#[allow(clippy::should_implement_trait)]
pub fn from_str(s: &str) -> Self {
match s {
"prealloc" => AllocationStrategy::Prealloc,
"falloc" => AllocationStrategy::Falloc,
"trunc" => AllocationStrategy::Trunc,
"mmap" => AllocationStrategy::Mmap,
_ => AllocationStrategy::None,
}
}
}
pub async fn allocate_file<D: DiskAdaptor>(
adaptor: &mut D,
_path: &Path,
length: u64,
strategy: AllocationStrategy,
secure: bool,
) -> Result<()> {
match strategy {
AllocationStrategy::None => Ok(()),
AllocationStrategy::Prealloc | AllocationStrategy::Falloc => {
falloc::fallocate(adaptor, length, secure).await
}
AllocationStrategy::Trunc => strategies::truncate(adaptor, length).await,
AllocationStrategy::Mmap => falloc::fallocate(adaptor, length, secure).await,
}
}
pub async fn preallocate_file(
path: &Path,
length: u64,
strategy: &str,
secure: bool,
) -> Result<()> {
preallocate_file_with_progress(path, length, strategy, None::<&fn(u64, u64)>, secure).await
}
pub async fn preallocate_file_with_progress<F>(
path: &Path,
length: u64,
strategy: &str,
on_progress: Option<&F>,
secure: bool,
) -> Result<()>
where
F: Fn(u64, u64) + Send + Sync,
{
let alloc_strategy = AllocationStrategy::from_str(strategy);
if length == 0 || alloc_strategy == AllocationStrategy::None {
return Ok(());
}
if let Err(_e) = check_disk_space_async(path, length).await {
return Err(Aria2Error::Fatal(FatalError::DiskSpaceExhausted));
}
if let Some(parent) = path.parent() {
let parent: &Path = parent;
if !parent.exists() {
tokio::fs::create_dir_all(parent)
.await
.map_err(|e: std::io::Error| Aria2Error::Io(e.to_string()))?;
}
}
const PROGRESS_THRESHOLD: u64 = 100 * 1024 * 1024;
if let Some(cb) = on_progress
&& length >= PROGRESS_THRESHOLD
{
cb(0, length);
}
let mut adaptor = DirectDiskAdaptor::new();
adaptor.open(path).await?;
allocate_file(&mut adaptor, path, length, alloc_strategy, secure).await?;
if let Some(cb) = on_progress
&& length >= PROGRESS_THRESHOLD
{
cb(length, length);
}
adaptor.close().await
}