use std::fs::{File, OpenOptions};
use std::io::{self, Read, Write};
use std::path::Path;
use crate::fault;
pub(crate) fn create_new_private(path: &Path) -> io::Result<File> {
let mut options = OpenOptions::new();
options.read(true).write(true).create_new(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600);
}
options.open(path)
}
pub(crate) fn open_read(path: &Path) -> io::Result<File> {
let mut options = OpenOptions::new();
options.read(true);
#[cfg(windows)]
{
use std::os::windows::fs::OpenOptionsExt;
const FILE_SHARE_READ: u32 = 0x1;
const FILE_SHARE_WRITE: u32 = 0x2;
const FILE_SHARE_DELETE: u32 = 0x4;
options.share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE);
}
options.open(path)
}
pub(crate) fn write_new_durable(path: &Path, bytes: &[u8]) -> io::Result<()> {
fault::point("create")?;
let mut file = create_new_private(path)?;
fault::point("write")?;
file.write_all(bytes)?;
fault::point("sync")?;
crate::sync::sync_all(&file, path)?;
drop(file);
sync_parent(path)
}
pub(crate) fn read_at_most(path: &Path, limit: u64) -> io::Result<Option<Vec<u8>>> {
let mut bytes = Vec::new();
open_read(path)?
.take(limit.saturating_add(1))
.read_to_end(&mut bytes)?;
Ok((bytes.len() as u64 <= limit).then_some(bytes))
}
pub(crate) fn remove_file(path: &Path) -> io::Result<()> {
fault::point("remove")?;
match std::fs::remove_file(path) {
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
result => result,
}
}
pub(crate) fn rename_new_durable(from: &Path, to: &Path) -> io::Result<()> {
if to.exists() {
return Err(io::Error::new(
io::ErrorKind::AlreadyExists,
"a stored file name is never reused",
));
}
fault::point("rename")?;
std::fs::rename(from, to)?;
sync_parent(to)
}
pub(crate) fn sync_parent(path: &Path) -> io::Result<()> {
match path.parent() {
Some(parent) => sync_dir(parent),
None => Ok(()),
}
}
pub(crate) fn sync_dir(path: &Path) -> io::Result<()> {
fault::point("sync_dir")?;
#[cfg(unix)]
{
crate::sync::sync_all(&File::open(path)?, path)
}
#[cfg(not(unix))]
{
let _ = path;
Ok(())
}
}
pub(crate) fn read_exact_at(file: &File, buf: &mut [u8], offset: u64) -> io::Result<()> {
#[cfg(unix)]
{
use std::os::unix::fs::FileExt;
file.read_exact_at(buf, offset)
}
#[cfg(windows)]
{
use std::os::windows::fs::FileExt;
let mut done = 0;
while done < buf.len() {
let read = file.seek_read(&mut buf[done..], offset + done as u64)?;
if read == 0 {
return Err(io::Error::new(
io::ErrorKind::UnexpectedEof,
"file ended before the requested range",
));
}
done += read;
}
Ok(())
}
}