diff --git a/CHANGELOG.md b/CHANGELOG.md index aa5fe157..5b932719 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,36 @@ # Releases +## 1.1.0 + +### Changes + +- Consolidate `FileExt` and `AsyncFileExt` into single crate-root traits + (`fs4::FileExt`, `fs4::AsyncFileExt`) instead of generating a distinct + trait per backend module. The per-backend modules (`fs4::tokio`, + `fs4::async_std`, `fs4::smol`, `fs4::fs_err2`, `fs4::fs_err3`, + `fs4::fs_err2_tokio`, `fs4::fs_err3_tokio`) now re-export the unified + crate-root trait. Method-call sites that import the trait via `use` + continue to compile unchanged; code that named two backend traits as + distinct types will see them unify. +- Add blanket impls `impl FileExt for &F` and + `impl AsyncFileExt for &F`, so the + extension methods are now callable through shared references. +- Seal `FileExt` and `AsyncFileExt` via a private `sealed::Sealed` + supertrait, so the set of implementing types is closed to the + concrete file types fs4 already supports (and references to them). + This locks in the freedom to add methods to either trait in future + minor releases without breaking downstream impls. +- Add `DynAsyncFileExt`, an object-safe mirror of `AsyncFileExt` whose + async methods return `BoxFuture<'_, T>` (alias for + `Pin + Send + '_>>`). Use it whenever + type erasure is needed (`Box`, + `&dyn DynAsyncFileExt`); prefer the static `AsyncFileExt` for + generic code since it has no allocation or dynamic-dispatch + overhead. Every type implementing `AsyncFileExt` also implements + `DynAsyncFileExt`, and the trait is sealed. +- Mark the delegating methods `#[inline(always)]` (skipped under + `tarpaulin` coverage builds). + ## 1.0.1 ### Fixes diff --git a/Cargo.toml b/Cargo.toml index e17c1e20..deee6b1d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "fs4" # NB: When modifying, also modify html_root_url in lib.rs -version = "1.0.2" +version = "1.1.0" rust-version = "1.75.0" authors = ["Dan Burkert ", "Al Liu "] license = "MIT OR Apache-2.0" @@ -47,7 +47,7 @@ fs-err3 = { package = "fs-err", version = "3", features = ["tokio"] } smol-potat = "1.1" tempfile = "3" tokio = { version = "1", features = ["full"] } -libc = "0.2" + [package.metadata.docs.rs] all-features = true diff --git a/rustfmt.toml b/rustfmt.toml index f54d5e6e..29ccec77 100644 --- a/rustfmt.toml +++ b/rustfmt.toml @@ -3,6 +3,7 @@ hard_tabs = false tab_spaces = 2 newline_style = "Auto" use_small_heuristics = "Default" +imports_granularity = "Crate" reorder_imports = true reorder_modules = true remove_nested_parens = true diff --git a/src/file_ext/async_impl.rs b/src/file_ext/async_impl.rs index 28a2455e..04f14e94 100644 --- a/src/file_ext/async_impl.rs +++ b/src/file_ext/async_impl.rs @@ -2,88 +2,9 @@ macro_rules! async_file_ext { ($file: ty, $file_name: literal) => { use std::io::Result; - #[doc = concat!("Extension trait for `", $file_name, "` which provides allocation and locking methods.")] - /// - /// ## Notes on File Locks - /// - /// This library provides whole-file locks in both shared (read) and exclusive - /// (read-write) varieties. - /// - /// File locks are a cross-platform hazard since the file lock APIs exposed by - /// operating system kernels vary in subtle and not-so-subtle ways. - /// - /// The API exposed by this library can be safely used across platforms as long - /// as the following rules are followed: - /// - /// * Multiple locks should not be created on an individual `File` instance - /// concurrently. - /// * Duplicated files should not be locked without great care. - /// * Files to be locked should be opened with at least read or write - /// permissions. - /// * File locks may only be relied upon to be advisory. - /// - /// File locks are released automatically when the file handle is closed (for - /// example when the owning `File` is dropped), so calling [`AsyncFileExt::unlock`] - /// explicitly is optional. - /// - /// File locks are implemented with - /// [`flock(2)`](http://man7.org/linux/man-pages/man2/flock.2.html) on Unix and - /// [`LockFileEx`](https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-lockfileex) - /// on Windows. The `lock_*` and `try_lock_*` methods are synchronous because - /// the underlying system calls are blocking. The separate - /// [`AsyncFileExt::unlock_async`] method is provided for convenience inside - /// async code, but the underlying `unlock` syscall is still blocking. - pub trait AsyncFileExt { - /// Returns the amount of physical space allocated for a file. - fn allocated_size(&self) -> impl core::future::Future>; - - /// Ensures that at least `len` bytes of disk space are allocated for the - /// file. After a successful call to `allocate`, subsequent writes to the - /// file within the specified length are guaranteed not to fail because of - /// lack of disk space. - /// - /// On most platforms the file's logical size is also extended to `len` - /// bytes. On Windows, if the file's existing cluster-aligned allocation - /// already covers `len`, the logical size is left unchanged to work around - /// buffered-I/O quirks observed when the end-of-file pointer is moved - /// inside an already-allocated cluster. - fn allocate(&self, len: u64) -> impl core::future::Future>; - - /// Acquires a shared lock on the file, blocking until the lock can be - /// acquired. - fn lock_shared(&self) -> Result<()>; - - /// Acquires an exclusive lock on the file, blocking until the lock can be - /// acquired. Mirrors [`std::fs::File::lock`]. - fn lock(&self) -> Result<()>; - - /// Attempts to acquire a shared lock on the file, without blocking. - /// - /// Returns `Ok(())` if the lock was acquired, or - /// `Err(`[`TryLockError::WouldBlock`](crate::TryLockError::WouldBlock)`)` - /// if the file is currently locked. - fn try_lock_shared(&self) -> std::result::Result<(), crate::TryLockError>; - - /// Attempts to acquire an exclusive lock on the file, without blocking. - /// - /// Returns `Ok(())` if the lock was acquired, or - /// `Err(`[`TryLockError::WouldBlock`](crate::TryLockError::WouldBlock)`)` - /// if the file is currently locked. - fn try_lock(&self) -> std::result::Result<(), crate::TryLockError>; - - /// Releases any lock held on the file. The lock is also released - /// automatically when the file handle is closed. - fn unlock(&self) -> Result<()>; - - /// Releases any lock held on the file. - /// - /// **Note:** This method is not truly async; the underlying system call is - /// still blocking. It exists for convenience when used from an async - /// context. - fn unlock_async(&self) -> impl core::future::Future>; - } + impl $crate::sealed::Sealed for $file {} - impl AsyncFileExt for $file { + impl $crate::AsyncFileExt for $file { async fn allocated_size(&self) -> Result { sys::allocated_size(self).await } @@ -98,11 +19,11 @@ macro_rules! async_file_ext { sys::lock(self) } - fn try_lock_shared(&self) -> std::result::Result<(), crate::TryLockError> { + fn try_lock_shared(&self) -> std::result::Result<(), $crate::TryLockError> { sys::try_lock_shared(self) } - fn try_lock(&self) -> std::result::Result<(), crate::TryLockError> { + fn try_lock(&self) -> std::result::Result<(), $crate::TryLockError> { sys::try_lock(self) } @@ -114,6 +35,48 @@ macro_rules! async_file_ext { sys::unlock(self) } } + + impl $crate::DynAsyncFileExt for $file { + #[cfg_attr(not(tarpaulin), inline(always))] + fn allocated_size(&self) -> $crate::BoxFuture<'_, Result> { + Box::pin(::allocated_size(self)) + } + + #[cfg_attr(not(tarpaulin), inline(always))] + fn allocate(&self, len: u64) -> $crate::BoxFuture<'_, Result<()>> { + Box::pin(::allocate(self, len)) + } + + #[cfg_attr(not(tarpaulin), inline(always))] + fn lock_shared(&self) -> Result<()> { + ::lock_shared(self) + } + + #[cfg_attr(not(tarpaulin), inline(always))] + fn lock(&self) -> Result<()> { + ::lock(self) + } + + #[cfg_attr(not(tarpaulin), inline(always))] + fn try_lock_shared(&self) -> std::result::Result<(), $crate::TryLockError> { + ::try_lock_shared(self) + } + + #[cfg_attr(not(tarpaulin), inline(always))] + fn try_lock(&self) -> std::result::Result<(), $crate::TryLockError> { + ::try_lock(self) + } + + #[cfg_attr(not(tarpaulin), inline(always))] + fn unlock(&self) -> Result<()> { + ::unlock(self) + } + + #[cfg_attr(not(tarpaulin), inline(always))] + fn unlock_async(&self) -> $crate::BoxFuture<'_, Result<()>> { + Box::pin(::unlock_async(self)) + } + } } } @@ -122,12 +85,84 @@ macro_rules! test_mod { #[cfg(test)] mod test { extern crate tempfile; - use crate::{allocation_granularity, TryLockError}; + + use crate::{allocation_granularity, TryLockError, AsyncFileExt}; $( $use_stmt )* + /// Exercises `impl AsyncFileExt for &F`. + /// The other tests call methods directly on the concrete file type + /// and resolve to `::*`, so without this the + /// blanket-impl bodies are unreached. + #[$annotation] + async fn async_file_ext_blanket_for_ref() { + async fn drive(f: &F, len: u64) { + f.lock_shared().unwrap(); + f.unlock().unwrap(); + f.lock().unwrap(); + f.unlock().unwrap(); + f.try_lock_shared().unwrap(); + f.unlock().unwrap(); + f.try_lock().unwrap(); + f.unlock_async().await.unwrap(); + f.allocate(len).await.unwrap(); + let _ = f.allocated_size().await.unwrap(); + } + + let tempdir = tempfile::TempDir::with_prefix("fs4").unwrap(); + let path = tempdir.path().join("fs4"); + let file = fs::OpenOptions::new() + .read(true) + .write(true) + .create(true) + .open(&path) + .await + .unwrap(); + let blksize = allocation_granularity(&path).unwrap(); + + // `&&file` binds `F = &File`, so calls go through the blanket. + drive(&&file, blksize).await; + } + + /// Drives every `DynAsyncFileExt` method twice: once on the + /// concrete file type to cover the per-backend macro impl, and + /// once through `&File` to cover the `for &F` blanket. + #[$annotation] + async fn dyn_async_file_ext_smoke() { + use crate::DynAsyncFileExt; + + async fn drive(f: &F, len: u64) { + f.lock_shared().unwrap(); + f.unlock().unwrap(); + f.lock().unwrap(); + f.unlock().unwrap(); + f.try_lock_shared().unwrap(); + f.unlock().unwrap(); + f.try_lock().unwrap(); + f.unlock_async().await.unwrap(); + f.allocate(len).await.unwrap(); + let _ = f.allocated_size().await.unwrap(); + } + + let tempdir = tempfile::TempDir::with_prefix("fs4").unwrap(); + let path = tempdir.path().join("fs4"); + let file = fs::OpenOptions::new() + .read(true) + .write(true) + .create(true) + .open(&path) + .await + .unwrap(); + let blksize = allocation_granularity(&path).unwrap(); + + // `&file` binds `F = File`, exercising the per-backend impl. + drive(&file, blksize).await; + // `&&file` binds `F = &File`, exercising the blanket impl. + drive(&&file, blksize).await; + } + /// Tests shared file lock operations. #[$annotation] async fn lock_shared() { diff --git a/src/file_ext/async_impl/async_std_impl.rs b/src/file_ext/async_impl/async_std_impl.rs index d3c049b6..a25833ce 100644 --- a/src/file_ext/async_impl/async_std_impl.rs +++ b/src/file_ext/async_impl/async_std_impl.rs @@ -8,6 +8,5 @@ async_file_ext!(File, "async_std::fs::File"); test_mod! { async_std::test, - use crate::async_std::AsyncFileExt; use async_std::fs; } diff --git a/src/file_ext/async_impl/fs_err2_tokio_impl.rs b/src/file_ext/async_impl/fs_err2_tokio_impl.rs index 02893c72..8d70b4ef 100644 --- a/src/file_ext/async_impl/fs_err2_tokio_impl.rs +++ b/src/file_ext/async_impl/fs_err2_tokio_impl.rs @@ -8,6 +8,5 @@ async_file_ext!(File, "fs_err::tokio::File"); test_mod! { tokio::test, - use crate::fs_err2_tokio::AsyncFileExt; use fs_err2::tokio as fs; } diff --git a/src/file_ext/async_impl/fs_err3_tokio_impl.rs b/src/file_ext/async_impl/fs_err3_tokio_impl.rs index 57c23452..da9b4944 100644 --- a/src/file_ext/async_impl/fs_err3_tokio_impl.rs +++ b/src/file_ext/async_impl/fs_err3_tokio_impl.rs @@ -8,6 +8,5 @@ async_file_ext!(File, "fs_err::tokio::File"); test_mod! { tokio::test, - use crate::fs_err3_tokio::AsyncFileExt; use fs_err3::tokio as fs; } diff --git a/src/file_ext/async_impl/smol_impl.rs b/src/file_ext/async_impl/smol_impl.rs index 63b7c74c..58a32f18 100644 --- a/src/file_ext/async_impl/smol_impl.rs +++ b/src/file_ext/async_impl/smol_impl.rs @@ -8,6 +8,5 @@ async_file_ext!(File, "smol::fs::File"); test_mod! { smol_potat::test, - use crate::smol::AsyncFileExt; use smol::fs; } diff --git a/src/file_ext/async_impl/tokio_impl.rs b/src/file_ext/async_impl/tokio_impl.rs index 648de57c..e3f5f1f7 100644 --- a/src/file_ext/async_impl/tokio_impl.rs +++ b/src/file_ext/async_impl/tokio_impl.rs @@ -8,6 +8,5 @@ async_file_ext!(File, "tokio::fs::File"); test_mod! { tokio::test, - use crate::tokio::AsyncFileExt; use tokio::fs; } diff --git a/src/file_ext/sync_impl.rs b/src/file_ext/sync_impl.rs index 50793924..5012cc17 100644 --- a/src/file_ext/sync_impl.rs +++ b/src/file_ext/sync_impl.rs @@ -1,106 +1,40 @@ macro_rules! file_ext { - ($file:ty, $file_name:literal) => { - use std::io::Result; - - #[doc = concat!("Extension trait for `", $file_name, "` which provides allocation and locking methods.")] - /// - /// ## Notes on File Locks - /// - /// This library provides whole-file locks in both shared (read) and exclusive - /// (read-write) varieties. - /// - /// File locks are a cross-platform hazard since the file lock APIs exposed by - /// operating system kernels vary in subtle and not-so-subtle ways. - /// - /// The API exposed by this library can be safely used across platforms as long - /// as the following rules are followed: - /// - /// * Multiple locks should not be created on an individual `File` instance - /// concurrently. - /// * Duplicated files should not be locked without great care. - /// * Files to be locked should be opened with at least read or write - /// permissions. - /// * File locks may only be relied upon to be advisory. - /// - /// File locks are released automatically when the file handle is closed (for - /// example when the owning `File` is dropped), so calling [`FileExt::unlock`] - /// explicitly is optional. - /// - /// File locks are implemented with - /// [`flock(2)`](http://man7.org/linux/man-pages/man2/flock.2.html) on Unix and - /// [`LockFileEx`](https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-lockfileex) - /// on Windows. - pub trait FileExt { - /// Returns the amount of physical space allocated for a file. - fn allocated_size(&self) -> Result; - - /// Ensures that at least `len` bytes of disk space are allocated for the - /// file. After a successful call to `allocate`, subsequent writes to the - /// file within the specified length are guaranteed not to fail because of - /// lack of disk space. - /// - /// On most platforms the file's logical size is also extended to `len` - /// bytes. On Windows, if the file's existing cluster-aligned allocation - /// already covers `len`, the logical size is left unchanged to work around - /// buffered-I/O quirks observed when the end-of-file pointer is moved - /// inside an already-allocated cluster. - fn allocate(&self, len: u64) -> Result<()>; - - /// Acquires a shared lock on the file, blocking until the lock can be - /// acquired. - fn lock_shared(&self) -> Result<()>; - - /// Acquires an exclusive lock on the file, blocking until the lock can be - /// acquired. - /// - /// This is the blocking counterpart of [`FileExt::try_lock`]. It mirrors - /// [`std::fs::File::lock`]. - fn lock(&self) -> Result<()>; - - /// Attempts to acquire a shared lock on the file, without blocking. - /// - /// Returns `Ok(())` if the lock was acquired, or - /// `Err(`[`TryLockError::WouldBlock`](crate::TryLockError::WouldBlock)`)` - /// if the file is currently locked. Mirrors - /// [`std::fs::File::try_lock_shared`]. - fn try_lock_shared(&self) -> std::result::Result<(), crate::TryLockError>; - - /// Attempts to acquire an exclusive lock on the file, without blocking. - /// - /// Returns `Ok(())` if the lock was acquired, or - /// `Err(`[`TryLockError::WouldBlock`](crate::TryLockError::WouldBlock)`)` - /// if the file is currently locked. Mirrors [`std::fs::File::try_lock`]. - fn try_lock(&self) -> std::result::Result<(), crate::TryLockError>; - - /// Releases any lock held on the file. The lock is also released - /// automatically when the file handle is closed. - fn unlock(&self) -> Result<()>; - } - - impl FileExt for $file { - fn allocated_size(&self) -> Result { - sys::allocated_size(self) - } - fn allocate(&self, len: u64) -> Result<()> { - sys::allocate(self, len) - } - fn lock_shared(&self) -> Result<()> { - sys::lock_shared(self) - } - fn lock(&self) -> Result<()> { - sys::lock(self) - } - fn try_lock_shared(&self) -> std::result::Result<(), crate::TryLockError> { - sys::try_lock_shared(self) - } - fn try_lock(&self) -> std::result::Result<(), crate::TryLockError> { - sys::try_lock(self) - } - fn unlock(&self) -> Result<()> { - sys::unlock(self) - } - } + ($file:ty, $file_name:literal) => { + use std::io::Result; + + impl $crate::sealed::Sealed for $file {} + + impl $crate::FileExt for $file { + #[cfg_attr(not(tarpaulin), inline(always))] + fn allocated_size(&self) -> Result { + sys::allocated_size(self) + } + #[cfg_attr(not(tarpaulin), inline(always))] + fn allocate(&self, len: u64) -> Result<()> { + sys::allocate(self, len) + } + #[cfg_attr(not(tarpaulin), inline(always))] + fn lock_shared(&self) -> Result<()> { + sys::lock_shared(self) + } + #[cfg_attr(not(tarpaulin), inline(always))] + fn lock(&self) -> Result<()> { + sys::lock(self) + } + #[cfg_attr(not(tarpaulin), inline(always))] + fn try_lock_shared(&self) -> std::result::Result<(), $crate::TryLockError> { + sys::try_lock_shared(self) + } + #[cfg_attr(not(tarpaulin), inline(always))] + fn try_lock(&self) -> std::result::Result<(), $crate::TryLockError> { + sys::try_lock(self) + } + #[cfg_attr(not(tarpaulin), inline(always))] + fn unlock(&self) -> Result<()> { + sys::unlock(self) + } } + }; } macro_rules! test_mod { @@ -109,13 +43,47 @@ macro_rules! test_mod { mod test { extern crate tempfile; - use super::*; - use crate::{allocation_granularity, statvfs, FsStats, TryLockError}; + use crate::{allocation_granularity, statvfs, FsStats, TryLockError, FileExt}; $( $use_stmt )* + /// Exercises `impl FileExt for &F`. Without this + /// every method body in the blanket impl is uncovered, since the + /// other tests call methods directly on the concrete file type and + /// resolve to `::*`. + #[test] + fn file_ext_blanket_for_ref() { + fn drive(f: &F, len: u64) { + f.lock_shared().unwrap(); + f.unlock().unwrap(); + f.lock().unwrap(); + f.unlock().unwrap(); + f.try_lock_shared().unwrap(); + f.unlock().unwrap(); + f.try_lock().unwrap(); + f.unlock().unwrap(); + f.allocate(len).unwrap(); + let _ = f.allocated_size().unwrap(); + } + + let tempdir = tempfile::TempDir::with_prefix("fs4").unwrap(); + let path = tempdir.path().join("fs4"); + let file = fs::OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(true) + .open(&path) + .unwrap(); + let blksize = allocation_granularity(&path).unwrap(); + + // `&&file` makes the inner `F` bind to `&File`, so all method + // calls resolve to the `<&File as FileExt>` blanket impl. + drive(&&file, blksize); + } + /// Tests shared file lock operations. #[test] fn lock_shared() { diff --git a/src/lib.rs b/src/lib.rs index 296c7173..74058f7a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -135,50 +135,46 @@ use windows as sys; #[cfg(any(unix, windows))] mod file_ext; -#[cfg(all(feature = "sync", any(unix, windows)))] -#[cfg_attr(docsrs, doc(cfg(feature = "sync")))] -pub use crate::file_ext::sync_impl::std_impl::FileExt; - #[cfg(all(feature = "fs-err2", any(unix, windows)))] #[cfg_attr(docsrs, doc(cfg(feature = "fs-err2")))] pub mod fs_err2 { - pub use crate::file_ext::sync_impl::fs_err2_impl::FileExt; + pub use crate::FileExt; } #[cfg(all(feature = "fs-err3", any(unix, windows)))] #[cfg_attr(docsrs, doc(cfg(feature = "fs-err3")))] pub mod fs_err3 { - pub use crate::file_ext::sync_impl::fs_err3_impl::FileExt; + pub use crate::FileExt; } #[cfg(all(feature = "async-std", any(unix, windows)))] #[cfg_attr(docsrs, doc(cfg(feature = "async-std")))] pub mod async_std { - pub use crate::file_ext::async_impl::async_std_impl::AsyncFileExt; + pub use crate::{AsyncFileExt, DynAsyncFileExt}; } #[cfg(all(feature = "fs-err2-tokio", any(unix, windows)))] #[cfg_attr(docsrs, doc(cfg(feature = "fs-err2-tokio")))] pub mod fs_err2_tokio { - pub use crate::file_ext::async_impl::fs_err2_tokio_impl::AsyncFileExt; + pub use crate::{AsyncFileExt, DynAsyncFileExt}; } #[cfg(all(feature = "fs-err3-tokio", any(unix, windows)))] #[cfg_attr(docsrs, doc(cfg(feature = "fs-err3-tokio")))] pub mod fs_err3_tokio { - pub use crate::file_ext::async_impl::fs_err3_tokio_impl::AsyncFileExt; + pub use crate::{AsyncFileExt, DynAsyncFileExt}; } #[cfg(all(feature = "smol", any(unix, windows)))] #[cfg_attr(docsrs, doc(cfg(feature = "smol")))] pub mod smol { - pub use crate::file_ext::async_impl::smol_impl::AsyncFileExt; + pub use crate::{AsyncFileExt, DynAsyncFileExt}; } #[cfg(all(feature = "tokio", any(unix, windows)))] #[cfg_attr(docsrs, doc(cfg(feature = "tokio")))] pub mod tokio { - pub use crate::file_ext::async_impl::tokio_impl::AsyncFileExt; + pub use crate::{AsyncFileExt, DynAsyncFileExt}; } mod fs_stats; @@ -187,7 +183,6 @@ pub use fs_stats::FsStats; mod try_lock_error; pub use try_lock_error::TryLockError; -#[cfg(any(unix, windows))] use std::io::Result; #[cfg(any(unix, windows))] use std::path::Path; @@ -244,6 +239,361 @@ where statvfs(path).map(|stat| stat.allocation_granularity) } +mod sealed { + pub trait Sealed {} + + impl Sealed for &F {} +} + +/// Extension trait for file which provides allocation and locking methods. +/// +/// This trait is sealed and cannot be implemented for types outside of `fs4`. +/// +/// ## Notes on File Locks +/// +/// This library provides whole-file locks in both shared (read) and exclusive +/// (read-write) varieties. +/// +/// File locks are a cross-platform hazard since the file lock APIs exposed by +/// operating system kernels vary in subtle and not-so-subtle ways. +/// +/// The API exposed by this library can be safely used across platforms as long +/// as the following rules are followed: +/// +/// * Multiple locks should not be created on an individual `File` instance +/// concurrently. +/// * Duplicated files should not be locked without great care. +/// * Files to be locked should be opened with at least read or write +/// permissions. +/// * File locks may only be relied upon to be advisory. +/// +/// File locks are released automatically when the file handle is closed (for +/// example when the owning `File` is dropped), so calling [`FileExt::unlock`] +/// explicitly is optional. +/// +/// File locks are implemented with +/// [`flock(2)`](http://man7.org/linux/man-pages/man2/flock.2.html) on Unix and +/// [`LockFileEx`](https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-lockfileex) +/// on Windows. +pub trait FileExt: sealed::Sealed { + /// Returns the amount of physical space allocated for a file. + fn allocated_size(&self) -> Result; + + /// Ensures that at least `len` bytes of disk space are allocated for the + /// file. After a successful call to `allocate`, subsequent writes to the + /// file within the specified length are guaranteed not to fail because of + /// lack of disk space. + /// + /// On most platforms the file's logical size is also extended to `len` + /// bytes. On Windows, if the file's existing cluster-aligned allocation + /// already covers `len`, the logical size is left unchanged to work around + /// buffered-I/O quirks observed when the end-of-file pointer is moved + /// inside an already-allocated cluster. + fn allocate(&self, len: u64) -> Result<()>; + + /// Acquires a shared lock on the file, blocking until the lock can be + /// acquired. + fn lock_shared(&self) -> Result<()>; + + /// Acquires an exclusive lock on the file, blocking until the lock can be + /// acquired. + /// + /// This is the blocking counterpart of [`FileExt::try_lock`]. It mirrors + /// [`std::fs::File::lock`]. + fn lock(&self) -> Result<()>; + + /// Attempts to acquire a shared lock on the file, without blocking. + /// + /// Returns `Ok(())` if the lock was acquired, or + /// `Err(`[`TryLockError::WouldBlock`](crate::TryLockError::WouldBlock)`)` + /// if the file is currently locked. Mirrors + /// [`std::fs::File::try_lock_shared`]. + fn try_lock_shared(&self) -> std::result::Result<(), TryLockError>; + + /// Attempts to acquire an exclusive lock on the file, without blocking. + /// + /// Returns `Ok(())` if the lock was acquired, or + /// `Err(`[`TryLockError::WouldBlock`](crate::TryLockError::WouldBlock)`)` + /// if the file is currently locked. Mirrors [`std::fs::File::try_lock`]. + fn try_lock(&self) -> std::result::Result<(), TryLockError>; + + /// Releases any lock held on the file. The lock is also released + /// automatically when the file handle is closed. + fn unlock(&self) -> Result<()>; +} + +impl FileExt for &F { + #[cfg_attr(not(tarpaulin), inline(always))] + fn allocated_size(&self) -> Result { + ::allocated_size(*self) + } + + #[cfg_attr(not(tarpaulin), inline(always))] + fn allocate(&self, len: u64) -> Result<()> { + ::allocate(*self, len) + } + + #[cfg_attr(not(tarpaulin), inline(always))] + fn lock_shared(&self) -> Result<()> { + ::lock_shared(*self) + } + + #[cfg_attr(not(tarpaulin), inline(always))] + fn lock(&self) -> Result<()> { + ::lock(*self) + } + + #[cfg_attr(not(tarpaulin), inline(always))] + fn try_lock_shared(&self) -> std::result::Result<(), TryLockError> { + ::try_lock_shared(*self) + } + + #[cfg_attr(not(tarpaulin), inline(always))] + fn try_lock(&self) -> std::result::Result<(), TryLockError> { + ::try_lock(*self) + } + + #[cfg_attr(not(tarpaulin), inline(always))] + fn unlock(&self) -> Result<()> { + ::unlock(*self) + } +} + +/// Extension trait for file which provides allocation and locking methods. +/// +/// ## Notes on File Locks +/// +/// This library provides whole-file locks in both shared (read) and exclusive +/// (read-write) varieties. +/// +/// File locks are a cross-platform hazard since the file lock APIs exposed by +/// operating system kernels vary in subtle and not-so-subtle ways. +/// +/// The API exposed by this library can be safely used across platforms as long +/// as the following rules are followed: +/// +/// * Multiple locks should not be created on an individual `File` instance +/// concurrently. +/// * Duplicated files should not be locked without great care. +/// * Files to be locked should be opened with at least read or write +/// permissions. +/// * File locks may only be relied upon to be advisory. +/// +/// File locks are released automatically when the file handle is closed (for +/// example when the owning `File` is dropped), so calling [`AsyncFileExt::unlock`] +/// explicitly is optional. +/// +/// File locks are implemented with +/// [`flock(2)`](http://man7.org/linux/man-pages/man2/flock.2.html) on Unix and +/// [`LockFileEx`](https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-lockfileex) +/// on Windows. The `lock_*` and `try_lock_*` methods are synchronous because +/// the underlying system calls are blocking. The separate +/// [`AsyncFileExt::unlock_async`] method is provided for convenience inside +/// async code, but the underlying `unlock` syscall is still blocking. +/// +/// This trait is sealed and cannot be implemented for types outside of `fs4`. +pub trait AsyncFileExt: sealed::Sealed { + /// Returns the amount of physical space allocated for a file. + fn allocated_size(&self) -> impl core::future::Future>; + + /// Ensures that at least `len` bytes of disk space are allocated for the + /// file. After a successful call to `allocate`, subsequent writes to the + /// file within the specified length are guaranteed not to fail because of + /// lack of disk space. + /// + /// On most platforms the file's logical size is also extended to `len` + /// bytes. On Windows, if the file's existing cluster-aligned allocation + /// already covers `len`, the logical size is left unchanged to work around + /// buffered-I/O quirks observed when the end-of-file pointer is moved + /// inside an already-allocated cluster. + fn allocate(&self, len: u64) -> impl core::future::Future>; + + /// Acquires a shared lock on the file, blocking until the lock can be + /// acquired. + fn lock_shared(&self) -> Result<()>; + + /// Acquires an exclusive lock on the file, blocking until the lock can be + /// acquired. Mirrors [`std::fs::File::lock`]. + fn lock(&self) -> Result<()>; + + /// Attempts to acquire a shared lock on the file, without blocking. + /// + /// Returns `Ok(())` if the lock was acquired, or + /// `Err(`[`TryLockError::WouldBlock`](crate::TryLockError::WouldBlock)`)` + /// if the file is currently locked. + fn try_lock_shared(&self) -> std::result::Result<(), crate::TryLockError>; + + /// Attempts to acquire an exclusive lock on the file, without blocking. + /// + /// Returns `Ok(())` if the lock was acquired, or + /// `Err(`[`TryLockError::WouldBlock`](crate::TryLockError::WouldBlock)`)` + /// if the file is currently locked. + fn try_lock(&self) -> std::result::Result<(), crate::TryLockError>; + + /// Releases any lock held on the file. The lock is also released + /// automatically when the file handle is closed. + fn unlock(&self) -> Result<()>; + + /// Releases any lock held on the file. + /// + /// **Note:** This method is not truly async; the underlying system call is + /// still blocking. It exists for convenience when used from an async + /// context. + fn unlock_async(&self) -> impl core::future::Future>; +} + +impl AsyncFileExt for &F { + #[cfg_attr(not(tarpaulin), inline(always))] + async fn allocated_size(&self) -> Result { + ::allocated_size(*self).await + } + + #[cfg_attr(not(tarpaulin), inline(always))] + async fn allocate(&self, len: u64) -> Result<()> { + ::allocate(*self, len).await + } + + #[cfg_attr(not(tarpaulin), inline(always))] + fn lock_shared(&self) -> Result<()> { + ::lock_shared(*self) + } + + #[cfg_attr(not(tarpaulin), inline(always))] + fn lock(&self) -> Result<()> { + ::lock(*self) + } + + #[cfg_attr(not(tarpaulin), inline(always))] + fn try_lock_shared(&self) -> std::result::Result<(), crate::TryLockError> { + ::try_lock_shared(*self) + } + + #[cfg_attr(not(tarpaulin), inline(always))] + fn try_lock(&self) -> std::result::Result<(), crate::TryLockError> { + ::try_lock(*self) + } + + #[cfg_attr(not(tarpaulin), inline(always))] + fn unlock(&self) -> Result<()> { + ::unlock(*self) + } + + #[cfg_attr(not(tarpaulin), inline(always))] + async fn unlock_async(&self) -> Result<()> { + ::unlock_async(*self).await + } +} + +/// A heap-allocated, dynamically-typed `Send` future used by +/// [`DynAsyncFileExt`] to keep its methods object-safe. +pub type BoxFuture<'a, T> = core::pin::Pin + Send + 'a>>; + +/// Object-safe variant of [`AsyncFileExt`] returning boxed `Send` futures, so +/// it can be used behind a trait object (e.g. `Box` or +/// `&dyn DynAsyncFileExt`). +/// +/// [`AsyncFileExt`] uses return-position `impl Future`, which is not +/// object-safe; this trait wraps the same operations behind +/// [`BoxFuture`]s so the trait *can* be used as a trait object. Every type +/// that implements [`AsyncFileExt`] also implements `DynAsyncFileExt`. +/// +/// Prefer [`AsyncFileExt`] for generic code (no allocation, no dynamic +/// dispatch); reach for `DynAsyncFileExt` only when type erasure is +/// required. +/// +/// This trait is sealed and cannot be implemented for types outside of `fs4`. +pub trait DynAsyncFileExt: sealed::Sealed { + /// Returns the amount of physical space allocated for a file. + fn allocated_size(&self) -> BoxFuture<'_, Result>; + + /// Ensures that at least `len` bytes of disk space are allocated for the + /// file. After a successful call to `allocate`, subsequent writes to the + /// file within the specified length are guaranteed not to fail because of + /// lack of disk space. + /// + /// On most platforms the file's logical size is also extended to `len` + /// bytes. On Windows, if the file's existing cluster-aligned allocation + /// already covers `len`, the logical size is left unchanged to work around + /// buffered-I/O quirks observed when the end-of-file pointer is moved + /// inside an already-allocated cluster. + fn allocate(&self, len: u64) -> BoxFuture<'_, Result<()>>; + + /// Acquires a shared lock on the file, blocking until the lock can be + /// acquired. + fn lock_shared(&self) -> Result<()>; + + /// Acquires an exclusive lock on the file, blocking until the lock can be + /// acquired. Mirrors [`std::fs::File::lock`]. + fn lock(&self) -> Result<()>; + + /// Attempts to acquire a shared lock on the file, without blocking. + /// + /// Returns `Ok(())` if the lock was acquired, or + /// `Err(`[`TryLockError::WouldBlock`](crate::TryLockError::WouldBlock)`)` + /// if the file is currently locked. + fn try_lock_shared(&self) -> std::result::Result<(), crate::TryLockError>; + + /// Attempts to acquire an exclusive lock on the file, without blocking. + /// + /// Returns `Ok(())` if the lock was acquired, or + /// `Err(`[`TryLockError::WouldBlock`](crate::TryLockError::WouldBlock)`)` + /// if the file is currently locked. + fn try_lock(&self) -> std::result::Result<(), crate::TryLockError>; + + /// Releases any lock held on the file. The lock is also released + /// automatically when the file handle is closed. + fn unlock(&self) -> Result<()>; + + /// Releases any lock held on the file. + /// + /// **Note:** This method is not truly async; the underlying system call is + /// still blocking. It exists for convenience when used from an async + /// context. + fn unlock_async(&self) -> BoxFuture<'_, Result<()>>; +} + +impl DynAsyncFileExt for &F { + #[cfg_attr(not(tarpaulin), inline(always))] + fn allocated_size(&self) -> BoxFuture<'_, Result> { + ::allocated_size(*self) + } + + #[cfg_attr(not(tarpaulin), inline(always))] + fn allocate(&self, len: u64) -> BoxFuture<'_, Result<()>> { + ::allocate(*self, len) + } + + #[cfg_attr(not(tarpaulin), inline(always))] + fn lock_shared(&self) -> Result<()> { + ::lock_shared(*self) + } + + #[cfg_attr(not(tarpaulin), inline(always))] + fn lock(&self) -> Result<()> { + ::lock(*self) + } + + #[cfg_attr(not(tarpaulin), inline(always))] + fn try_lock_shared(&self) -> std::result::Result<(), crate::TryLockError> { + ::try_lock_shared(*self) + } + + #[cfg_attr(not(tarpaulin), inline(always))] + fn try_lock(&self) -> std::result::Result<(), crate::TryLockError> { + ::try_lock(*self) + } + + #[cfg_attr(not(tarpaulin), inline(always))] + fn unlock(&self) -> Result<()> { + ::unlock(*self) + } + + #[cfg_attr(not(tarpaulin), inline(always))] + fn unlock_async(&self) -> BoxFuture<'_, Result<()>> { + ::unlock_async(*self) + } +} + #[cfg(all(test, any(unix, windows)))] mod tests { //! The `free_space` / `available_space` / `total_space` helpers diff --git a/src/unix/async_impl.rs b/src/unix/async_impl.rs index 4f49f4df..5f7e9271 100644 --- a/src/unix/async_impl.rs +++ b/src/unix/async_impl.rs @@ -72,7 +72,7 @@ macro_rules! test_mod { mod test { extern crate tempfile; - use crate::TryLockError; + use crate::{TryLockError, AsyncFileExt}; $( $use_stmt diff --git a/src/unix/async_impl/async_std_impl.rs b/src/unix/async_impl/async_std_impl.rs index 81d4fa14..82c8c310 100644 --- a/src/unix/async_impl/async_std_impl.rs +++ b/src/unix/async_impl/async_std_impl.rs @@ -8,6 +8,5 @@ allocate_size!(File); test_mod! { async_std::test, - use crate::async_std::AsyncFileExt; use async_std::fs; } diff --git a/src/unix/async_impl/fs_err2_tokio_impl.rs b/src/unix/async_impl/fs_err2_tokio_impl.rs index a7b06d62..ad6ff76b 100644 --- a/src/unix/async_impl/fs_err2_tokio_impl.rs +++ b/src/unix/async_impl/fs_err2_tokio_impl.rs @@ -8,6 +8,5 @@ allocate_size!(File); test_mod! { tokio::test, - use crate::fs_err2_tokio::AsyncFileExt; use fs_err2::tokio as fs; } diff --git a/src/unix/async_impl/fs_err3_tokio_impl.rs b/src/unix/async_impl/fs_err3_tokio_impl.rs index 4bb79260..21fdf083 100644 --- a/src/unix/async_impl/fs_err3_tokio_impl.rs +++ b/src/unix/async_impl/fs_err3_tokio_impl.rs @@ -8,6 +8,5 @@ allocate_size!(File); test_mod! { tokio::test, - use crate::fs_err3_tokio::AsyncFileExt; use fs_err3::tokio as fs; } diff --git a/src/unix/async_impl/smol_impl.rs b/src/unix/async_impl/smol_impl.rs index d09dfb09..437a4c47 100644 --- a/src/unix/async_impl/smol_impl.rs +++ b/src/unix/async_impl/smol_impl.rs @@ -8,6 +8,5 @@ allocate_size!(File); test_mod! { smol_potat::test, - use crate::smol::AsyncFileExt; use smol::fs; } diff --git a/src/unix/async_impl/tokio_impl.rs b/src/unix/async_impl/tokio_impl.rs index e3803d29..24ea5a28 100644 --- a/src/unix/async_impl/tokio_impl.rs +++ b/src/unix/async_impl/tokio_impl.rs @@ -8,6 +8,5 @@ allocate_size!(File); test_mod! { tokio::test, - use crate::tokio::AsyncFileExt; use tokio::fs; }