use std::{
fs::File,
path::{Path, PathBuf},
};
use crate::error::{Error, Result};
fn on_path(path: &Path, err: &std::io::Error) -> Error {
Error::Io(std::io::Error::new(
err.kind(),
format!("{}: {err}", path.display()),
))
}
pub struct MappedFile {
map: memmap2::Mmap,
}
pub struct OpenedFile {
file: File,
len: u64,
}
impl MappedFile {
pub fn open(path: &Path) -> Result<Self> {
Self::map(path, &Self::open_file(path)?)
}
pub fn open_file(path: &Path) -> Result<OpenedFile> {
let file = File::open(path).map_err(|err| on_path(path, &err))?;
let len = file.metadata().map_err(|err| on_path(path, &err))?.len();
Ok(OpenedFile { file, len })
}
pub fn map(path: &Path, file: &OpenedFile) -> Result<Self> {
let len = usize::try_from(file.len).map_err(|_| {
Error::Format("input larger than the address space")
})?;
let map =
unsafe { memmap2::MmapOptions::new().len(len).map(&file.file) }
.map_err(|err| on_path(path, &err))?;
Ok(Self { map })
}
pub fn bytes(&self) -> &[u8] {
&self.map
}
}
pub struct OutputFile {
map: Option<memmap2::MmapMut>,
file: Option<File>,
temp: PathBuf,
dest: PathBuf,
}
impl Drop for OutputFile {
fn drop(&mut self) {
if !self.temp.as_os_str().is_empty() {
let _ = std::fs::remove_file(&self.temp);
}
}
}
#[cfg(target_os = "linux")]
fn reserve_blocks(file: &File, size: u64) -> Result<()> {
use std::os::fd::AsRawFd;
let Ok(len) = i64::try_from(size) else {
return Ok(());
};
if len == 0 || on_tmpfs(file) {
return Ok(());
}
let rc = unsafe { libc::posix_fallocate(file.as_raw_fd(), 0, len) };
match rc {
0 | libc::EOPNOTSUPP | libc::EINVAL | libc::ENOSYS => Ok(()),
code => Err(std::io::Error::from_raw_os_error(code).into()),
}
}
#[cfg(target_os = "linux")]
fn on_tmpfs(file: &File) -> bool {
use std::{mem::MaybeUninit, os::fd::AsRawFd};
let mut buf = MaybeUninit::<libc::statfs>::uninit();
let rc = unsafe { libc::fstatfs(file.as_raw_fd(), buf.as_mut_ptr()) };
if rc != 0 {
return false;
}
let statfs = unsafe { buf.assume_init() };
statfs.f_type == libc::TMPFS_MAGIC
}
#[allow(clippy::unnecessary_wraps)]
#[cfg(not(target_os = "linux"))]
fn reserve_blocks(_file: &File, _size: u64) -> Result<()> {
Ok(())
}
impl OutputFile {
pub fn create(dest: &Path, size: u64) -> Result<Self> {
let temp = temp_path(dest);
let file = File::options()
.read(true)
.write(true)
.create(true)
.truncate(true)
.open(&temp)?;
file.set_len(size)?;
reserve_blocks(&file, size)?;
let map = if size == 0 {
None
} else {
let map = unsafe { memmap2::MmapMut::map_mut(&file)? };
#[cfg(target_os = "linux")]
let _ = map.advise(memmap2::Advice::DontFork);
Some(map)
};
let file = (map.is_none()).then_some(file);
Ok(Self {
map,
file,
temp,
dest: dest.to_path_buf(),
})
}
pub fn bytes(&mut self) -> &mut [u8] {
self.map.as_mut().map_or(&mut [], |m| m)
}
pub fn finish(mut self) -> Result<()> {
use std::os::unix::fs::PermissionsExt;
drop(self.map.take());
drop(self.file.take());
std::fs::set_permissions(
&self.temp,
std::fs::Permissions::from_mode(crate::util::output_mode()),
)?;
std::fs::rename(&self.temp, &self.dest)?;
self.temp.clear();
crate::detach::published();
Ok(())
}
}
pub(crate) fn temp_path(dest: &Path) -> PathBuf {
let name = dest.file_name().unwrap_or_default();
let mut temp = name.to_os_string();
temp.push(format!(".xold-{}", std::process::id()));
dest.parent().unwrap_or_else(|| Path::new(".")).join(temp)
}