use std::fs::File;
use std::io;
use std::path::Path;
#[cfg(unix)]
pub(crate) fn same_file(a: &File, b: &File) -> io::Result<bool> {
use std::os::unix::fs::MetadataExt;
let a = a.metadata()?;
let b = b.metadata()?;
Ok(a.dev() == b.dev() && a.ino() == b.ino())
}
#[cfg(windows)]
pub(crate) fn same_file(a: &File, b: &File) -> io::Result<bool> {
use std::os::windows::io::AsRawHandle;
use windows_sys::Win32::Storage::FileSystem::{
GetFileInformationByHandle, BY_HANDLE_FILE_INFORMATION,
};
fn identity(f: &File) -> io::Result<(u32, u32, u32)> {
let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { std::mem::zeroed() };
let ok = unsafe { GetFileInformationByHandle(f.as_raw_handle() as _, &mut info) };
if ok == 0 {
return Err(io::Error::last_os_error());
}
Ok((info.dwVolumeSerialNumber, info.nFileIndexHigh, info.nFileIndexLow))
}
Ok(identity(a)? == identity(b)?)
}
#[cfg(target_os = "wasi")]
pub(crate) fn same_file(a: &File, b: &File) -> io::Result<bool> {
use std::os::fd::AsRawFd;
let a = unsafe { wasi::fd_filestat_get(a.as_raw_fd() as u32) }.map_err(wasi_err)?;
let b = unsafe { wasi::fd_filestat_get(b.as_raw_fd() as u32) }.map_err(wasi_err)?;
Ok(a.dev == b.dev && a.ino == b.ino)
}
#[cfg(not(any(unix, windows, target_os = "wasi")))]
pub(crate) fn same_file(_a: &File, _b: &File) -> io::Result<bool> {
Ok(true)
}
#[cfg(windows)]
fn wide_path(path: &Path) -> io::Result<Vec<u16>> {
use std::os::windows::ffi::{OsStrExt, OsStringExt};
use std::path::{Component, Prefix};
const MAX_PATH: usize = 260;
let plain: Vec<u16> = path.as_os_str().encode_wide().collect();
if plain.contains(&0) {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "path contains NUL"));
}
if plain.len() < MAX_PATH {
return Ok(plain.into_iter().chain(std::iter::once(0)).collect());
}
let already_verbatim = matches!(
path.components().next(),
Some(Component::Prefix(p)) if p.kind().is_verbatim()
);
if already_verbatim {
return Ok(plain.into_iter().chain(std::iter::once(0)).collect());
}
let absolute = std::path::absolute(path)?;
let mut out: Vec<u16> = Vec::with_capacity(absolute.as_os_str().len() + 8);
let unc = matches!(
absolute.components().next(),
Some(Component::Prefix(p)) if matches!(p.kind(), Prefix::UNC(..))
);
if unc {
out.extend("\\\\?\\UNC".encode_utf16());
let rest: Vec<u16> = absolute.as_os_str().encode_wide().skip(1).collect();
out.extend(rest);
} else {
out.extend("\\\\?\\".encode_utf16());
out.extend(absolute.as_os_str().encode_wide());
}
for c in &mut out {
if *c == b'/' as u16 {
*c = b'\\' as u16;
}
}
debug_assert!(!std::ffi::OsString::from_wide(&out).is_empty());
out.push(0);
Ok(out)
}
#[cfg(unix)]
fn checked_filesystem_bytes<A: Into<u64>, B: Into<u64>>(blocks: A, block_size: B) -> Option<u64> {
blocks.into().checked_mul(block_size.into())
}
#[cfg(unix)]
pub(crate) fn filesystem_available_bytes(path: &Path) -> io::Result<Option<u64>> {
use std::os::unix::ffi::OsStrExt;
let path = std::ffi::CString::new(path.as_os_str().as_bytes())
.map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "path contains NUL"))?;
let mut stats = std::mem::MaybeUninit::<libc::statvfs>::uninit();
if unsafe { libc::statvfs(path.as_ptr(), stats.as_mut_ptr()) } != 0 {
return Err(io::Error::last_os_error());
}
let stats = unsafe { stats.assume_init() };
Ok(checked_filesystem_bytes(stats.f_bavail, stats.f_frsize))
}
#[cfg(windows)]
pub(crate) fn filesystem_available_bytes(path: &Path) -> io::Result<Option<u64>> {
use windows_sys::Win32::Storage::FileSystem::GetDiskFreeSpaceExW;
let dir = if path.is_file() { path.parent().unwrap_or_else(|| Path::new(".")) } else { path };
let dir = if dir.as_os_str().is_empty() { Path::new(".") } else { dir };
let wide = wide_path(dir)?;
let mut available: u64 = 0;
let rc = unsafe {
GetDiskFreeSpaceExW(
wide.as_ptr(),
&mut available,
std::ptr::null_mut(),
std::ptr::null_mut(),
)
};
if rc == 0 {
return Err(io::Error::last_os_error());
}
Ok(Some(available))
}
#[cfg(not(any(unix, windows)))]
pub(crate) fn filesystem_available_bytes(_path: &Path) -> io::Result<Option<u64>> {
Ok(None)
}
#[cfg(unix)]
#[inline]
pub(crate) fn read_exact_at(f: &File, buf: &mut [u8], off: u64) -> io::Result<()> {
std::os::unix::fs::FileExt::read_exact_at(f, buf, off)
}
#[cfg(unix)]
#[inline]
pub(crate) fn write_all_at(f: &File, buf: &[u8], off: u64) -> io::Result<()> {
std::os::unix::fs::FileExt::write_all_at(f, buf, off)
}
#[cfg(target_os = "wasi")]
fn wasi_err(e: wasi::Errno) -> io::Error {
io::Error::from_raw_os_error(e.raw().into())
}
#[cfg(target_os = "wasi")]
pub(crate) fn read_exact_at(f: &File, mut buf: &mut [u8], mut off: u64) -> io::Result<()> {
use std::os::fd::AsRawFd;
let fd = f.as_raw_fd() as u32;
while !buf.is_empty() {
let iov = [wasi::Iovec { buf: buf.as_mut_ptr(), buf_len: buf.len() }];
let n = unsafe { wasi::fd_pread(fd, &iov, off) }.map_err(wasi_err)?;
if n == 0 {
return Err(io::Error::new(
io::ErrorKind::UnexpectedEof,
"positioned read hit end of file before filling the buffer",
));
}
buf = &mut buf[n..];
off += n as u64;
}
Ok(())
}
#[cfg(target_os = "wasi")]
pub(crate) fn write_all_at(f: &File, mut buf: &[u8], mut off: u64) -> io::Result<()> {
use std::os::fd::AsRawFd;
let fd = f.as_raw_fd() as u32;
while !buf.is_empty() {
let iov = [wasi::Ciovec { buf: buf.as_ptr(), buf_len: buf.len() }];
let n = unsafe { wasi::fd_pwrite(fd, &iov, off) }.map_err(wasi_err)?;
if n == 0 {
return Err(io::Error::new(
io::ErrorKind::WriteZero,
"positioned write made no progress",
));
}
buf = &buf[n..];
off += n as u64;
}
Ok(())
}
#[cfg(windows)]
pub(crate) fn read_exact_at(f: &File, mut buf: &mut [u8], mut off: u64) -> io::Result<()> {
use std::os::windows::fs::FileExt;
while !buf.is_empty() {
match f.seek_read(buf, off) {
Ok(0) => {
return Err(io::Error::new(
io::ErrorKind::UnexpectedEof,
"positioned read hit end of file before filling the buffer",
))
}
Ok(n) => {
buf = &mut buf[n..];
off += n as u64;
}
Err(e) if e.kind() == io::ErrorKind::Interrupted => {}
Err(e) => return Err(e),
}
}
Ok(())
}
#[cfg(windows)]
pub(crate) fn write_all_at(f: &File, mut buf: &[u8], mut off: u64) -> io::Result<()> {
use std::os::windows::fs::FileExt;
while !buf.is_empty() {
match f.seek_write(buf, off) {
Ok(0) => {
return Err(io::Error::new(
io::ErrorKind::WriteZero,
"positioned write made no progress",
))
}
Ok(n) => {
buf = &buf[n..];
off += n as u64;
}
Err(e) if e.kind() == io::ErrorKind::Interrupted => {}
Err(e) => return Err(e),
}
}
Ok(())
}
#[cfg(not(any(unix, windows, target_os = "wasi")))]
pub(crate) fn read_exact_at(_f: &File, _buf: &mut [u8], _off: u64) -> io::Result<()> {
Err(io::Error::new(
io::ErrorKind::Unsupported,
"this target has no filesystem positioned-read primitive; use a custom ReadAt source",
))
}
#[cfg(not(any(unix, windows, target_os = "wasi")))]
pub(crate) fn write_all_at(_f: &File, _buf: &[u8], _off: u64) -> io::Result<()> {
Err(io::Error::new(
io::ErrorKind::Unsupported,
"this target has no filesystem positioned-write primitive",
))
}
#[inline]
pub(crate) fn lock_exclusive(f: &File) -> io::Result<bool> {
#[cfg(unix)]
{
use std::os::unix::io::AsRawFd;
let rc = unsafe { libc::flock(f.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) };
if rc == 0 {
return Ok(true);
}
let e = io::Error::last_os_error();
match e.raw_os_error() {
Some(c) if c == libc::EWOULDBLOCK || c == libc::EAGAIN => Ok(false),
_ => Err(e),
}
}
#[cfg(windows)]
{
use std::os::windows::io::AsRawHandle;
use windows_sys::Win32::Foundation::{ERROR_IO_PENDING, ERROR_LOCK_VIOLATION};
use windows_sys::Win32::Storage::FileSystem::{
LockFileEx, LOCKFILE_EXCLUSIVE_LOCK, LOCKFILE_FAIL_IMMEDIATELY,
};
use windows_sys::Win32::System::IO::OVERLAPPED;
let mut overlapped: OVERLAPPED = unsafe { std::mem::zeroed() };
overlapped.Anonymous.Anonymous.Offset = LOCK_BYTE_OFFSET as u32;
overlapped.Anonymous.Anonymous.OffsetHigh = (LOCK_BYTE_OFFSET >> 32) as u32;
let rc = unsafe {
LockFileEx(
f.as_raw_handle() as _,
LOCKFILE_EXCLUSIVE_LOCK | LOCKFILE_FAIL_IMMEDIATELY,
0,
1,
0,
&mut overlapped,
)
};
if rc != 0 {
return Ok(true);
}
let e = io::Error::last_os_error();
match e.raw_os_error() {
Some(c) if c == ERROR_LOCK_VIOLATION as i32 || c == ERROR_IO_PENDING as i32 => {
Ok(false)
}
_ => Err(e),
}
}
#[cfg(not(any(unix, windows)))]
{
let _ = f;
Ok(true)
}
}
#[cfg(windows)]
const LOCK_BYTE_OFFSET: u64 = u64::MAX - 1;
#[inline]
pub(crate) fn punch_hole(f: &File, off: u64, len: u64) -> io::Result<()> {
#[cfg(target_os = "linux")]
{
use std::os::unix::io::AsRawFd;
let rc = unsafe {
libc::fallocate(
f.as_raw_fd(),
libc::FALLOC_FL_PUNCH_HOLE | libc::FALLOC_FL_KEEP_SIZE,
off as libc::off_t,
len as libc::off_t,
)
};
if rc != 0 {
return Err(io::Error::last_os_error());
}
Ok(())
}
#[cfg(windows)]
{
use std::os::windows::io::AsRawHandle;
use windows_sys::Win32::System::Ioctl::{
FILE_ZERO_DATA_INFORMATION, FSCTL_SET_SPARSE, FSCTL_SET_ZERO_DATA,
};
use windows_sys::Win32::System::IO::DeviceIoControl;
let end = off.checked_add(len).ok_or_else(|| {
io::Error::new(io::ErrorKind::InvalidInput, "punch range overflows u64")
})?;
if end > i64::MAX as u64 {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"punch range exceeds the Windows file offset space",
));
}
let h = f.as_raw_handle() as _;
let mut returned: u32 = 0;
let rc = unsafe {
DeviceIoControl(
h,
FSCTL_SET_SPARSE,
std::ptr::null(),
0,
std::ptr::null_mut(),
0,
&mut returned,
std::ptr::null_mut(),
)
};
if rc == 0 {
return Err(io::Error::last_os_error());
}
let info =
FILE_ZERO_DATA_INFORMATION { FileOffset: off as i64, BeyondFinalZero: end as i64 };
let rc = unsafe {
DeviceIoControl(
h,
FSCTL_SET_ZERO_DATA,
(&info as *const FILE_ZERO_DATA_INFORMATION).cast(),
std::mem::size_of::<FILE_ZERO_DATA_INFORMATION>() as u32,
std::ptr::null_mut(),
0,
&mut returned,
std::ptr::null_mut(),
)
};
if rc == 0 {
return Err(io::Error::last_os_error());
}
Ok(())
}
#[cfg(not(any(target_os = "linux", windows)))]
{
let _ = (f, off, len);
Err(io::Error::new(
io::ErrorKind::Unsupported,
"hole punching needs fallocate(FALLOC_FL_PUNCH_HOLE), which this platform lacks",
))
}
}
#[cfg(target_os = "linux")]
pub(crate) fn rename_noreplace(from: &Path, to: &Path) -> io::Result<()> {
use std::os::unix::ffi::OsStrExt;
let from = std::ffi::CString::new(from.as_os_str().as_bytes())
.map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "source path contains NUL"))?;
let to = std::ffi::CString::new(to.as_os_str().as_bytes()).map_err(|_| {
io::Error::new(io::ErrorKind::InvalidInput, "destination path contains NUL")
})?;
let rc = unsafe {
libc::syscall(
libc::SYS_renameat2,
libc::AT_FDCWD,
from.as_ptr(),
libc::AT_FDCWD,
to.as_ptr(),
libc::RENAME_NOREPLACE,
)
};
if rc == 0 {
Ok(())
} else {
Err(io::Error::last_os_error())
}
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
pub(crate) fn rename_noreplace(from: &Path, to: &Path) -> io::Result<()> {
use std::os::unix::ffi::OsStrExt;
let from = std::ffi::CString::new(from.as_os_str().as_bytes())
.map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "source path contains NUL"))?;
let to = std::ffi::CString::new(to.as_os_str().as_bytes()).map_err(|_| {
io::Error::new(io::ErrorKind::InvalidInput, "destination path contains NUL")
})?;
let rc = unsafe { libc::renamex_np(from.as_ptr(), to.as_ptr(), libc::RENAME_EXCL) };
if rc == 0 {
Ok(())
} else {
Err(io::Error::last_os_error())
}
}
#[cfg(windows)]
pub(crate) fn rename_noreplace(from: &Path, to: &Path) -> io::Result<()> {
use windows_sys::Win32::Storage::FileSystem::{MoveFileExW, MOVEFILE_WRITE_THROUGH};
let (from, to) = (wide_path(from)?, wide_path(to)?);
let rc = unsafe { MoveFileExW(from.as_ptr(), to.as_ptr(), MOVEFILE_WRITE_THROUGH) };
if rc == 0 {
return Err(io::Error::last_os_error());
}
Ok(())
}
#[cfg(target_os = "wasi")]
pub(crate) fn rename_noreplace(from: &Path, to: &Path) -> io::Result<()> {
std::fs::hard_link(from, to)?;
std::fs::remove_file(from)
}
#[cfg(not(any(
target_os = "linux",
target_os = "macos",
target_os = "ios",
target_os = "wasi",
windows
)))]
pub(crate) fn rename_noreplace(_from: &Path, _to: &Path) -> io::Result<()> {
Err(io::Error::new(
io::ErrorKind::Unsupported,
"atomic no-replace rename is unavailable on this platform",
))
}
#[cfg(not(windows))]
#[inline]
pub(crate) fn rename(from: &Path, to: &Path) -> io::Result<()> {
std::fs::rename(from, to)
}
#[cfg(windows)]
pub(crate) fn rename(from: &Path, to: &Path) -> io::Result<()> {
use windows_sys::Win32::Foundation::ERROR_ACCESS_DENIED;
use windows_sys::Win32::Storage::FileSystem::{
MoveFileExW, MOVEFILE_REPLACE_EXISTING, MOVEFILE_WRITE_THROUGH,
};
let (wfrom, wto) = (wide_path(from)?, wide_path(to)?);
let rc = unsafe {
MoveFileExW(
wfrom.as_ptr(),
wto.as_ptr(),
MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH,
)
};
if rc != 0 {
return Ok(());
}
let e = io::Error::last_os_error();
if e.raw_os_error() == Some(ERROR_ACCESS_DENIED as i32) {
return std::fs::rename(from, to);
}
Err(e)
}
#[cfg(not(windows))]
#[inline]
pub(crate) fn sync_dir(dir: &Path) -> io::Result<()> {
File::open(dir)?.sync_all()
}
#[cfg(windows)]
#[inline]
pub(crate) fn sync_dir(_dir: &Path) -> io::Result<()> {
Ok(())
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum ReplaceOpenDurability {
Atomic,
Lagged,
}
#[inline]
pub(crate) const fn replace_open_durability() -> ReplaceOpenDurability {
if cfg!(windows) {
ReplaceOpenDurability::Lagged
} else {
ReplaceOpenDurability::Atomic
}
}
#[cfg(test)]
mod guarantee_tests {
use super::*;
#[test]
fn the_replace_guarantee_is_lagged_on_windows_and_atomic_everywhere_else() {
let expected = if cfg!(target_os = "windows") {
ReplaceOpenDurability::Lagged
} else {
ReplaceOpenDurability::Atomic
};
assert_eq!(replace_open_durability(), expected);
}
}
#[cfg(all(test, windows))]
mod windows_tests {
use super::*;
use std::io::Write;
fn scratch(tag: &str) -> std::path::PathBuf {
let p = std::env::temp_dir().join(format!("turndb-sys-{tag}-{}", std::process::id()));
let _ = std::fs::remove_file(&p);
p
}
fn open_rw(p: &Path) -> File {
std::fs::OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(p)
.unwrap()
}
#[test]
fn second_writer_is_refused_and_the_lock_dies_with_its_handle() {
let p = scratch("lock");
let a = open_rw(&p);
assert!(lock_exclusive(&a).unwrap(), "first writer takes the lock");
let b = open_rw(&p);
assert!(!lock_exclusive(&b).unwrap(), "second handle sees contention, not an error");
drop(a);
assert!(lock_exclusive(&b).unwrap(), "closing the holder's handle releases the lock");
drop(b);
let _ = std::fs::remove_file(&p);
}
#[test]
fn an_ordinary_reader_reads_the_whole_file_under_a_writer_lock() {
let p = scratch("lock-read");
let mut w = open_rw(&p);
w.write_all(&[7u8; 100_000]).unwrap();
assert!(lock_exclusive(&w).unwrap());
let r = File::open(&p).unwrap();
let mut buf = vec![0u8; 100_000];
read_exact_at(&r, &mut buf, 0).expect("a lock-free reader must not be denied");
assert!(buf.iter().all(|&b| b == 7));
let all = std::fs::read(&p).unwrap();
assert_eq!(all.len(), 100_000);
drop(r);
drop(w);
let _ = std::fs::remove_file(&p);
}
#[test]
fn a_mapped_view_reads_the_whole_file_under_a_writer_lock() {
use std::os::windows::io::AsRawHandle;
use windows_sys::Win32::Foundation::CloseHandle;
use windows_sys::Win32::System::Memory::{
CreateFileMappingW, MapViewOfFile, UnmapViewOfFile, FILE_MAP_READ, PAGE_READONLY,
};
let p = scratch("lock-map");
let mut w = open_rw(&p);
w.write_all(&[9u8; 65_536]).unwrap();
w.sync_all().unwrap();
assert!(lock_exclusive(&w).unwrap());
let r = File::open(&p).unwrap();
unsafe {
let mapping = CreateFileMappingW(
r.as_raw_handle() as _,
std::ptr::null(),
PAGE_READONLY,
0,
0,
std::ptr::null(),
);
assert!(!mapping.is_null(), "CreateFileMappingW: {}", io::Error::last_os_error());
let view = MapViewOfFile(mapping, FILE_MAP_READ, 0, 0, 0);
assert!(!view.Value.is_null(), "MapViewOfFile: {}", io::Error::last_os_error());
let bytes = std::slice::from_raw_parts(view.Value as *const u8, 65_536);
assert!(bytes.iter().all(|&b| b == 9), "mapped view must read every byte");
assert_ne!(UnmapViewOfFile(view), 0);
assert_ne!(CloseHandle(mapping), 0);
}
drop(r);
drop(w);
let _ = std::fs::remove_file(&p);
}
#[test]
fn punch_zeroes_the_range_and_keeps_the_length() {
let p = scratch("punch");
let mut f = open_rw(&p);
let body: Vec<u8> = (0..256 * 1024).map(|i| (i % 251) as u8 + 1).collect();
f.write_all(&body).unwrap();
f.sync_all().unwrap();
punch_hole(&f, 65_536, 65_536).expect("FSCTL_SET_ZERO_DATA on a sparse file");
f.sync_all().unwrap();
assert_eq!(f.metadata().unwrap().len(), body.len() as u64, "length unchanged");
let mut back = vec![0u8; body.len()];
read_exact_at(&f, &mut back, 0).unwrap();
assert_eq!(&back[..65_536], &body[..65_536]);
assert!(back[65_536..131_072].iter().all(|&b| b == 0), "punched range reads as zeros");
assert_eq!(&back[131_072..], &body[131_072..]);
drop(f);
let _ = std::fs::remove_file(&p);
}
#[test]
fn rename_noreplace_refuses_an_existing_destination_and_replace_rename_does_not() {
let a = scratch("ren-a");
let b = scratch("ren-b");
std::fs::write(&a, b"a").unwrap();
std::fs::write(&b, b"b").unwrap();
let err = rename_noreplace(&a, &b).expect_err("destination exists");
assert!(err.raw_os_error().is_some());
assert_eq!(std::fs::read(&b).unwrap(), b"b", "destination untouched");
rename(&a, &b).expect("replace rename");
assert_eq!(std::fs::read(&b).unwrap(), b"a");
assert!(!a.exists());
let _ = std::fs::remove_file(&b);
}
#[test]
fn a_path_with_an_interior_nul_is_invalid_input_not_a_truncated_name() {
use std::os::windows::ffi::OsStringExt;
let bad = std::ffi::OsString::from_wide(&[b'a' as u16, 0, b'b' as u16]);
let bad = Path::new(&bad);
let err = wide_path(bad).expect_err("interior NUL");
assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
assert_eq!(rename(bad, bad).expect_err("rename").kind(), io::ErrorKind::InvalidInput);
assert_eq!(
rename_noreplace(bad, bad).expect_err("rename_noreplace").kind(),
io::ErrorKind::InvalidInput
);
assert_eq!(
filesystem_available_bytes(bad).expect_err("free space").kind(),
io::ErrorKind::InvalidInput
);
}
#[test]
fn paths_past_max_path_work_for_rename_and_the_space_measurements() {
let base = Path::new("target").join(format!("turndb-long-{}", std::process::id()));
let mut rel = base.clone();
while rel.as_os_str().len() < 300 {
rel.push("a-deliberately-long-directory-component-0123456789");
}
std::fs::create_dir_all(&rel).unwrap();
assert!(rel.is_relative() && rel.as_os_str().len() > 260);
{
let a = rel.join("rel-a.turndb");
let b = rel.join("rel-b.turndb");
std::fs::write(&a, b"a").unwrap();
rename_noreplace(&a, &b).expect("relative no-replace rename past MAX_PATH");
std::fs::write(&a, b"a2").unwrap();
rename(&a, &b).expect("relative replace rename past MAX_PATH");
assert_eq!(std::fs::read(&b).unwrap(), b"a2");
assert!(filesystem_available_bytes(&rel).unwrap().is_some());
assert!(filesystem_available_bytes(&b).unwrap().is_some());
}
let dir = std::path::absolute(&rel).unwrap();
assert!(dir.is_absolute() && dir.as_os_str().len() > 260);
let a = dir.join("a.turndb");
let b = dir.join("b.turndb");
let c = dir.join("c.turndb");
std::fs::write(&a, b"a").unwrap();
std::fs::write(&b, b"b").unwrap();
rename_noreplace(&a, &c).expect("no-replace rename past MAX_PATH");
assert!(c.exists() && !a.exists());
rename_noreplace(&c, &b).expect_err("destination exists");
rename(&c, &b).expect("replace rename past MAX_PATH");
assert_eq!(std::fs::read(&b).unwrap(), b"a");
assert!(filesystem_available_bytes(&dir).unwrap().is_some());
assert!(filesystem_available_bytes(&b).unwrap().is_some());
drop(std::fs::remove_dir_all(&base));
}
#[test]
fn replace_rename_over_an_open_locked_destination_succeeds_and_the_old_handle_survives() {
let a = scratch("open-a");
let b = scratch("open-b");
std::fs::write(&a, b"fresh").unwrap();
let mut old = open_rw(&b);
old.write_all(b"old").unwrap();
old.sync_all().unwrap();
assert!(lock_exclusive(&old).unwrap());
rename(&a, &b).expect("replace over an open, locked destination");
assert_eq!(std::fs::read(&b).unwrap(), b"fresh", "the name now serves the fresh bytes");
let mut back = [0u8; 3];
read_exact_at(&old, &mut back, 0).unwrap();
assert_eq!(&back, b"old", "the old handle still reads the old file");
drop(old);
let _ = std::fs::remove_file(&b);
}
#[test]
fn the_candidate_lock_survives_the_replace_fallback_and_gates_the_new_name() {
let cand = scratch("handoff-cand");
let store = scratch("handoff-store");
std::fs::write(&cand, b"new").unwrap();
std::fs::write(&store, b"old").unwrap();
let old = open_rw(&store);
assert!(lock_exclusive(&old).unwrap(), "old store locked, as reclaim holds it");
let new = open_rw(&cand);
assert!(lock_exclusive(&new).unwrap(), "candidate locked before publication");
rename(&cand, &store).expect("replace over the open, locked destination (fallback)");
let third = open_rw(&store);
assert!(
!lock_exclusive(&third).unwrap(),
"a writer at the name meets the candidate's lock"
);
drop(old);
let fourth = open_rw(&store);
assert!(
!lock_exclusive(&fourth).unwrap(),
"the old handle's lock was never what gated the new name"
);
drop(new);
assert!(lock_exclusive(&fourth).unwrap(), "released with the candidate handle");
drop(third);
drop(fourth);
let _ = std::fs::remove_file(&store);
}
#[test]
fn free_space_is_measured_for_a_directory_and_for_a_file_path() {
let p = scratch("space");
std::fs::write(&p, b"x").unwrap();
let by_dir = filesystem_available_bytes(&std::env::temp_dir()).unwrap();
let by_file = filesystem_available_bytes(&p).unwrap();
assert!(by_dir.is_some() && by_file.is_some());
let _ = std::fs::remove_file(&p);
}
}