Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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<F: FileExt + ?Sized> FileExt for &F` and
`impl<F: AsyncFileExt + ?Sized> 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<Box<dyn Future<Output = T> + Send + '_>>`). Use it whenever
type erasure is needed (`Box<dyn DynAsyncFileExt>`,
`&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
Expand Down
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -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 <dan@danburkert.com>", "Al Liu <scygliu1@gmail.com>"]
license = "MIT OR Apache-2.0"
Expand Down
1 change: 1 addition & 0 deletions rustfmt.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
203 changes: 119 additions & 84 deletions src/file_ext/async_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Output = Result<u64>>;

/// 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<Output = 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) -> impl core::future::Future<Output = Result<()>>;
}
impl $crate::sealed::Sealed for $file {}

impl AsyncFileExt for $file {
impl $crate::AsyncFileExt for $file {
async fn allocated_size(&self) -> Result<u64> {
sys::allocated_size(self).await
}
Expand All @@ -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)
}

Expand All @@ -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<u64>> {
Box::pin(<Self as $crate::AsyncFileExt>::allocated_size(self))
}

#[cfg_attr(not(tarpaulin), inline(always))]
fn allocate(&self, len: u64) -> $crate::BoxFuture<'_, Result<()>> {
Box::pin(<Self as $crate::AsyncFileExt>::allocate(self, len))
}

#[cfg_attr(not(tarpaulin), inline(always))]
fn lock_shared(&self) -> Result<()> {
<Self as $crate::AsyncFileExt>::lock_shared(self)
}

#[cfg_attr(not(tarpaulin), inline(always))]
fn lock(&self) -> Result<()> {
<Self as $crate::AsyncFileExt>::lock(self)
}

#[cfg_attr(not(tarpaulin), inline(always))]
fn try_lock_shared(&self) -> std::result::Result<(), $crate::TryLockError> {
<Self as $crate::AsyncFileExt>::try_lock_shared(self)
}

#[cfg_attr(not(tarpaulin), inline(always))]
fn try_lock(&self) -> std::result::Result<(), $crate::TryLockError> {
<Self as $crate::AsyncFileExt>::try_lock(self)
}

#[cfg_attr(not(tarpaulin), inline(always))]
fn unlock(&self) -> Result<()> {
<Self as $crate::AsyncFileExt>::unlock(self)
}

#[cfg_attr(not(tarpaulin), inline(always))]
fn unlock_async(&self) -> $crate::BoxFuture<'_, Result<()>> {
Box::pin(<Self as $crate::AsyncFileExt>::unlock_async(self))
}
}
}
}

Expand All @@ -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<F: AsyncFileExt + ?Sized> AsyncFileExt for &F`.
/// The other tests call methods directly on the concrete file type
/// and resolve to `<File as AsyncFileExt>::*`, so without this the
/// blanket-impl bodies are unreached.
#[$annotation]
async fn async_file_ext_blanket_for_ref() {
async fn drive<F: AsyncFileExt + ?Sized>(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: DynAsyncFileExt + ?Sized>(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() {
Expand Down
1 change: 0 additions & 1 deletion src/file_ext/async_impl/async_std_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
1 change: 0 additions & 1 deletion src/file_ext/async_impl/fs_err2_tokio_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
1 change: 0 additions & 1 deletion src/file_ext/async_impl/fs_err3_tokio_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
1 change: 0 additions & 1 deletion src/file_ext/async_impl/smol_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,5 @@ async_file_ext!(File, "smol::fs::File");

test_mod! {
smol_potat::test,
use crate::smol::AsyncFileExt;
use smol::fs;
}
1 change: 0 additions & 1 deletion src/file_ext/async_impl/tokio_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,5 @@ async_file_ext!(File, "tokio::fs::File");

test_mod! {
tokio::test,
use crate::tokio::AsyncFileExt;
use tokio::fs;
}
Loading
Loading