use crate::error::{Aria2Error, Result};
use crate::filesystem::disk_writer::SeekableDiskWriter;
use crate::filesystem::positioned_disk_writer::PositionedDiskWriter;
use std::path::Path;
#[cfg(unix)]
fn path_to_cstring(path: &Path) -> Option<std::ffi::CString> {
use std::os::unix::ffi::OsStrExt;
std::ffi::CString::new(path.as_os_str().as_bytes()).ok()
}
pub(crate) async fn truncate(writer: &mut PositionedDiskWriter, length: u64) -> Result<()> {
writer.truncate(length).await
}
pub(crate) async fn zero_fill_allocation(
writer: &mut PositionedDiskWriter,
length: u64,
) -> Result<()> {
let existing_length = writer.len().await?.min(length);
writer.truncate(length).await?;
async_zero_fill_from(writer, existing_length, length).await
}
#[cfg(test)]
pub(crate) async fn async_zero_fill(writer: &mut PositionedDiskWriter, length: u64) -> Result<()> {
async_zero_fill_from(writer, 0, length).await
}
pub(crate) async fn async_zero_fill_from(
writer: &mut PositionedDiskWriter,
offset: u64,
length: u64,
) -> Result<()> {
const CHUNK_SIZE: usize = 1024 * 1024; let zero_chunk = vec![0u8; CHUNK_SIZE];
let mut position = offset.min(length);
let mut remaining = length.saturating_sub(position);
while remaining > 0 {
let write_len = remaining.min(CHUNK_SIZE as u64) as usize;
writer.write_at(position, &zero_chunk[..write_len]).await?;
position += write_len as u64;
remaining -= write_len as u64;
tokio::task::yield_now().await;
}
Ok(())
}
pub async fn get_available_space(path: &Path) -> Result<u64> {
let path = path.to_path_buf();
crate::filesystem::disk_io_pool::shared()
.run(move || get_available_space_sync(&path), "disk space query")
.await
}
fn get_available_space_sync(path: &Path) -> Result<u64> {
let parent = path.parent().unwrap_or_else(|| Path::new("."));
#[cfg(target_os = "linux")]
{
let _metadata = std::fs::metadata(parent).map_err(|e| Aria2Error::Io(e.to_string()))?;
let statvfs_result = unsafe {
let mut stat: libc::statvfs64 = std::mem::zeroed();
let Some(c_path) = path_to_cstring(parent) else {
return Err(Aria2Error::Io("path contains an embedded NUL byte".into()));
};
let ret = libc::statvfs64(c_path.as_ptr(), &mut stat);
(ret, stat)
};
if statvfs_result.0 == 0 {
let stat = statvfs_result.1;
Ok(stat.f_bavail as u64 * stat.f_frsize as u64)
} else {
Err(Aria2Error::Io("Failed to get disk space".to_string()))
}
}
#[cfg(all(unix, not(target_os = "linux")))]
{
let _metadata = std::fs::metadata(parent).map_err(|e| Aria2Error::Io(e.to_string()))?;
let statvfs_result = unsafe {
let mut stat: libc::statvfs = std::mem::zeroed();
let Some(c_path) = path_to_cstring(parent) else {
return Err(Aria2Error::Io("path contains an embedded NUL byte".into()));
};
let ret = libc::statvfs(c_path.as_ptr(), &mut stat);
(ret, stat)
};
if statvfs_result.0 == 0 {
let stat = statvfs_result.1;
Ok(stat.f_bavail as u64 * stat.f_frsize as u64)
} else {
Err(Aria2Error::Io("Failed to get disk space".to_string()))
}
}
#[cfg(windows)]
{
use std::os::windows::ffi::OsStrExt;
let abs_path = match std::fs::canonicalize(parent) {
Ok(p) => p,
Err(_) => std::env::current_dir().unwrap_or_else(|_| Path::new(".").to_path_buf()),
};
let mut wide_path: Vec<u16> = abs_path.as_os_str().encode_wide().collect();
wide_path.push(0);
let mut free_bytes_available: u64 = 0;
let result = unsafe {
windows_sys::Win32::Storage::FileSystem::GetDiskFreeSpaceExW(
wide_path.as_ptr(),
&mut free_bytes_available as *mut u64 as *mut _,
std::ptr::null_mut(),
std::ptr::null_mut(),
)
};
if result == 0 {
Err(Aria2Error::Io("Failed to get disk space".to_string()))
} else {
Ok(free_bytes_available)
}
}
#[cfg(all(not(unix), not(windows)))]
{
Ok(u64::MAX)
}
}