diff --git a/.codecov.yml b/.codecov.yml new file mode 100644 index 00000000..3941323f --- /dev/null +++ b/.codecov.yml @@ -0,0 +1,23 @@ +codecov: + require_ci_to_pass: false + +ignore: + +coverage: + status: + project: # Overall project status + default: + target: auto + if_not_found: success + only_pulls: false + patch: # Status for the patch in pull requests + default: + target: auto + if_not_found: success + only_pulls: true + changes: false # Whether to comment on the coverage changes in pull requests + +comment: + layout: "header, diff, files, footer" + behavior: default + require_changes: false diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 49028506..0bf8246d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -21,7 +21,8 @@ on: - '**.md' - '**.txt' workflow_dispatch: - schedule: [cron: "0 1 */7 * *"] + schedule: + - cron: "0 1 1 * *" env: CARGO_TERM_COLOR: always @@ -30,17 +31,6 @@ env: nightly: nightly jobs: - # Check formatting - rustfmt: - name: rustfmt - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - name: Install Rust - run: rustup update stable && rustup default stable - - name: Check formatting - run: rustfmt --check --edition 2021 $(git ls-files '*.rs') - # This represents the minimum Rust version supported by # Bytes. Updating this should be done in a dedicated PR. # @@ -50,115 +40,141 @@ jobs: name: minrust runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v6 - name: Install Rust run: rustup update 1.75.0 && rustup default 1.75.0 - name: Check run: cargo check - # Apply clippy lints - clippy: - name: clippy + # Check formatting (platform-independent, one OS is enough) + rustfmt: + name: rustfmt runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 - - name: Apply clippy lints - run: cargo clippy --all-features + - uses: actions/checkout@v6 + - name: Install Rust + run: rustup update stable && rustup default stable && rustup component add rustfmt + - name: Check formatting + run: cargo fmt --all -- --check - unit-tests: - name: unit tests - runs-on: ${{ matrix.os }} + # Apply clippy lints + clippy: + name: clippy strategy: matrix: - rust: - - nightly os: + - ubuntu-latest - macos-latest - windows-latest - - ubuntu-latest + runs-on: ${{ matrix.os }} steps: - - uses: actions/checkout@v4 - - name: Install latest nightly - uses: actions-rs/toolchain@v1 - with: - toolchain: ${{ matrix.rust }} - override: true - components: rustfmt, clippy - - - uses: Swatinem/rust-cache@v1 - - uses: actions/cache@v4 - with: - path: | - ~/.cargo/registry - ~/.cargo/git - target - key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }} + - uses: actions/checkout@v6 + - name: Install Rust + # --no-self-update is necessary because the windows environment cannot self-update rustup.exe. + run: rustup update stable --no-self-update && rustup default stable && rustup component add clippy + - name: Install cargo-hack + run: cargo install cargo-hack + - name: Apply clippy lints + run: cargo hack clippy --each-feature - - name: test all features - # Run sequentially to avoid race condition around file system size - run: cargo test --all-features -- --test-threads 1 - docs: - name: docs + # Run tests on some extra platforms + cross: + name: cross + strategy: + matrix: + target: + - aarch64-unknown-linux-gnu + - aarch64-linux-android + - aarch64-unknown-linux-musl + - i686-linux-android + - x86_64-linux-android + - i686-pc-windows-gnu + - x86_64-pc-windows-gnu + - i686-unknown-linux-gnu + - powerpc64-unknown-linux-gnu + - riscv64gc-unknown-linux-gnu runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v6 - name: Cache cargo build and registry - uses: actions/cache@v4 + uses: actions/cache@v5 with: path: | ~/.cargo/registry ~/.cargo/git target - key: ubuntu-latest-docs-${{ hashFiles('**/Cargo.lock') }} + key: ${{ runner.os }}-cross-${{ hashFiles('**/Cargo.lock') }} restore-keys: | - ubuntu-latest-docs- - - uses: actions-rs/toolchain@v1 - with: - toolchain: ${{ env.nightly }} - override: true - - name: "doc --lib --all-features" - run: cargo doc --lib --no-deps --all-features - env: - RUSTFLAGS: --cfg docsrs - RUSTDOCFLAGS: --cfg docsrs -Dwarnings + ${{ runner.os }}-cross- + - name: Install Rust + run: rustup update stable && rustup default stable + - name: Install MinGW toolchain for Windows GNU cross targets + # windows-sys >= 0.61 generates import libraries via `dlltool` + # when building for *-pc-windows-gnu. ubuntu-latest ships the + # x86_64 MinGW toolchain pre-installed, but not the i686 one. + if: contains(matrix.target, 'pc-windows-gnu') + run: | + sudo apt-get update + sudo apt-get install -y gcc-mingw-w64 binutils-mingw-w64 + - name: cargo build --target ${{ matrix.target }} + run: | + rustup target add ${{ matrix.target }} + cargo build --target ${{ matrix.target }} + + build: + name: build + strategy: + matrix: + os: + - ubuntu-latest + - macos-latest + - windows-latest + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v6 + - name: Cache cargo build and registry + uses: actions/cache@v5 + with: + path: | + ~/.cargo/registry + ~/.cargo/git + target + key: ${{ runner.os }}-build-${{ hashFiles('**/Cargo.lock') }} + restore-keys: | + ${{ runner.os }}-build- + - name: Install Rust + # --no-self-update is necessary because the windows environment cannot self-update rustup.exe. + run: rustup update stable --no-self-update && rustup default stable + - name: Install cargo-hack + run: cargo install cargo-hack + - name: Run build + run: cargo hack build --each-feature - coverage: - name: cargo tarpaulin - runs-on: ubuntu-latest - needs: - - unit-tests - - clippy - - rustfmt - - minrust + test: + name: test + strategy: + matrix: + os: + - ubuntu-latest + - macos-latest + - windows-latest + runs-on: ${{ matrix.os }} steps: - - uses: actions/checkout@v4 - - name: Install latest nightly - uses: actions-rs/toolchain@v1 - with: - toolchain: nightly - override: true - - uses: actions-rs/install@v0.1 - with: - crate: cargo-tarpaulin - version: latest - - name: Cache ~/.cargo - uses: actions/cache@v4 - with: - path: ~/.cargo - key: ${{ runner.os }}-coverage-dotcargo - - name: Cache cargo build - uses: actions/cache@v4 - with: - path: target - key: ${{ runner.os }}-coverage-cargo-build-target - - name: Run tarpaulin - uses: actions-rs/cargo@v1 - with: - command: tarpaulin - args: --all-features --run-types tests --run-types doctests --workspace --out xml - - name: Upload to codecov.io - uses: codecov/codecov-action@v4 - with: - token: ${{ secrets.CODECOV_TOKEN }} - fail_ci_if_error: true - slug: al8n/fs4-rs + - uses: actions/checkout@v6 + - name: Cache cargo build and registry + uses: actions/cache@v5 + with: + path: | + ~/.cargo/registry + ~/.cargo/git + target + key: ${{ runner.os }}-test-${{ hashFiles('**/Cargo.lock') }} + restore-keys: | + ${{ runner.os }}-test- + - name: Install Rust + # --no-self-update is necessary because the windows environment cannot self-update rustup.exe. + run: rustup update stable --no-self-update && rustup default stable + - name: Install cargo-hack + run: cargo install cargo-hack + - name: Run test + run: cargo hack test --each-feature -- --test-threads 1 diff --git a/.github/workflows/coverage.yml b/.github/workflows/coverage.yml new file mode 100644 index 00000000..385d9ac4 --- /dev/null +++ b/.github/workflows/coverage.yml @@ -0,0 +1,147 @@ +name: coverage + +on: + push: + branches: + - main + paths-ignore: + - 'COPYRIGHT' + - 'LICENSE-*' + - '**.md' + - '**.txt' + pull_request: + paths-ignore: + - 'COPYRIGHT' + - 'LICENSE-*' + - '**.md' + - '**.txt' + workflow_dispatch: + +env: + CARGO_TERM_COLOR: always + +# Matrix dimensions covered for Codecov to reflect the per-OS split of +# fs4's platform code: +# +# - linux-x86_64: src/unix.rs + src/unix/**, exercising rustix's +# Linux `fallocate` path and `statvfs`. +# - macos-aarch64: src/unix.rs + src/unix/**, exercising rustix's +# macOS `F_PREALLOCATE` path (different enough from +# Linux that issue #15 was macOS-specific). +# - windows-x86_64: src/windows.rs + src/windows/**, exercising the +# Win32 lock + `FILE_ALLOCATION_INFO` APIs. +# +# On each runner we exclude the other OS's sources so they don't +# register as 0/N uncovered lines. Codecov merges the three reports, +# so every OS file ends up covered by its native host. +# +# `--all-features` on each host covers every feature-gated impl leaf +# (crate-root `FileExt` for `std::fs::File`, plus `fs_err2`, `fs_err3`, +# `tokio`, `smol`, `async_std`, `fs_err2_tokio`, `fs_err3_tokio`), +# since they all expand from the same macros. + +jobs: + coverage: + name: coverage (${{ matrix.label }}) + strategy: + matrix: + include: + # ---- Unix (Linux) ---- + - os: ubuntu-latest + label: linux-x86_64 + exclude_os: >- + --exclude-files 'src/windows.rs' + --exclude-files 'src/windows/**' + + # ---- Unix (macOS / aarch64) ---- + - os: macos-latest + label: macos-aarch64 + exclude_os: >- + --exclude-files 'src/windows.rs' + --exclude-files 'src/windows/**' + + # ---- Windows ---- + - os: windows-latest + label: windows-x86_64 + exclude_os: >- + --exclude-files 'src/unix.rs' + --exclude-files 'src/unix/**' + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v6 + + - name: Install Rust stable + # `llvm-tools-preview` is required by `cargo tarpaulin --engine + # llvm`, which is the only tarpaulin engine that works + # uniformly on Linux + macOS + Windows. + shell: bash + run: | + rustup toolchain install stable --component llvm-tools-preview --profile minimal + rustup default stable + + - name: Install cargo-tarpaulin + uses: taiki-e/install-action@v2 + with: + tool: cargo-tarpaulin + + - name: Generate coverage + shell: bash + # --engine llvm: works on all three OSes (ptrace is Linux-only). + # --all-features: exercise every feature-gated impl leaf. + # --run-types tests: run `cargo test` targets only (skip doctests + # since the crate has no doctests, and benches, + # since `cargo test` does not execute them). + # --ignore-tests: omit test/bench function bodies from the + # coverage percentage; measure the library, + # not the test harness. + # Lock-test parallelism: the filesystem_space tests share /tmp + # with each other and can flap when run in parallel. Force + # single-threaded execution, matching ci.yml. + run: | + mkdir -p coverage + cargo tarpaulin \ + --engine llvm \ + --all-features \ + --run-types tests \ + --ignore-tests \ + ${{ matrix.exclude_os }} \ + --out xml \ + --output-dir coverage \ + -- --test-threads 1 + continue-on-error: false + + - name: Upload coverage artifact + uses: actions/upload-artifact@v7 + with: + name: coverage-${{ matrix.label }} + path: coverage/cobertura.xml + + upload-codecov: + name: Upload merged coverage to Codecov + needs: coverage + runs-on: ubuntu-latest + if: always() + strategy: + fail-fast: false + matrix: + label: + - linux-x86_64 + - macos-aarch64 + - windows-x86_64 + steps: + - uses: actions/checkout@v6 + + - name: Download ${{ matrix.label }} report + uses: actions/download-artifact@v6 + with: + name: coverage-${{ matrix.label }} + path: coverage/ + + - name: Upload ${{ matrix.label }} to Codecov + uses: codecov/codecov-action@v6 + with: + files: coverage/cobertura.xml + flags: ${{ matrix.label }} + fail_ci_if_error: true + env: + CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} diff --git a/.github/workflows/loc.yml b/.github/workflows/loc.yml new file mode 100644 index 00000000..c8d2872c --- /dev/null +++ b/.github/workflows/loc.yml @@ -0,0 +1,58 @@ +name: loc + +on: + push: + branches: + - main + paths-ignore: + - 'README.md' + - 'COPYRIGHT' + - 'LICENSE*' + - '**.md' + - '**.txt' + - 'art' + pull_request: + paths-ignore: + - 'README.md' + - 'COPYRIGHT' + - 'LICENSE*' + - '**.md' + - '**.txt' + - 'art' + workflow_dispatch: + +jobs: + loc: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + + - name: Install Rust + run: | + rustup update stable && rustup default stable + rustup component add clippy + rustup component add rustfmt + + - name: Install tokeit + run: | + cargo install tokeit --force + + - name: Count total lines of code + run: | + tokeit + - name: Upload total loc to GitHub Gist + uses: actions/github-script@v9 + with: + github-token: ${{ secrets.GIST_PAT }} + script: | + const fs = require('fs'); + const output = fs.readFileSync('tokeit.json', 'utf8'); + const gistId = '327b2a8aef9003246e45c6e47fe63937'; + await github.rest.gists.update({ + gist_id: gistId, + files: { + "fs4": { + content: output + } + } + }); diff --git a/.gitignore b/.gitignore index 64f40ab2..fa98a160 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,5 @@ target Cargo.lock .idea + +**.claude/ diff --git a/CHANGELOG.md b/CHANGELOG.md index 810c35d9..cc0cc050 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,7 +1,138 @@ # Releases +## 1.0.0 + +### Breakage + +- Renamed `FileExt::lock_exclusive` / `AsyncFileExt::lock_exclusive` to + `lock`, matching the stabilized [`std::fs::File::lock`] API. +- Renamed `FileExt::try_lock_exclusive` / `AsyncFileExt::try_lock_exclusive` + to `try_lock`, matching [`std::fs::File::try_lock`]. +- Changed the return type of `try_lock` and `try_lock_shared` from + `std::io::Result` to `Result<(), TryLockError>`. `Ok(())` still + indicates the lock was acquired; `Err(TryLockError::WouldBlock)` now + indicates the lock is held by another handle. This matches the stable + [`std::fs::File::try_lock`] signature (`Ok(false)` was the nightly + shape prior to 1.89). +- Removed the top-level `lock_contended_error()` helper. Use + `TryLockError::WouldBlock` instead. +- Flattened the `fs_std` module: the `FileExt` trait for + `std::fs::File` now lives at the crate root. Update imports from + `use fs4::fs_std::FileExt;` to `use fs4::FileExt;`. All other + backends (`fs_err2`, `fs_err3`, `tokio`, `smol`, `async_std`, + `fs_err2_tokio`, `fs_err3_tokio`) remain nested, since each + defines its own `FileExt`/`AsyncFileExt` over a different concrete + `File` type. + +### Additions + +- New `fs4::TryLockError` enum, mirroring [`std::fs::TryLockError`] + with `Error(io::Error)` and `WouldBlock` variants. Implements + `Debug`, `Display`, `std::error::Error` (with `source()` exposing + the inner `io::Error`), `From` (kind `WouldBlock` + collapses into the `WouldBlock` variant; everything else wraps into + `Error`), and `From for io::Error` (`WouldBlock` + becomes `io::Error::from(io::ErrorKind::WouldBlock)`; `Error(inner)` + passes through verbatim). + +### Fixes + +- Fixed feature typos that made the crate fail to compile with only + `fs-err2`, `fs-err3`, `fs-err2-tokio`, or `fs-err3-tokio` enabled + (without `sync` / `tokio`). `#[cfg(feature = "fs-err")]` and + `feature = "fs-err-tokio"` both referenced feature names that do not + exist in `Cargo.toml`. +- On Windows, skip the internal `set_len` call when the file's existing + cluster-aligned allocation already covers `len`. Avoids the Windows + buffered-I/O quirks observed when the end-of-file pointer is moved + inside an already-allocated cluster (#13). The trait doc now carves + this behavior out from the general "file size is at least `len` + bytes" contract. +- Short-circuited `allocate` on Unix when the file is already at least + `len` bytes long. Fixes macOS `fallocate` spuriously returning + `ENOSPC` when re-calling `allocate(len)` on an existing file (#15). +- Added `cygwin` to the `allocate` `target_os` set so builds stop + failing with a missing `sys::allocate` symbol on that target (#44). +- Added `redox` and `cygwin` to the async `allocate` fallback branch + so it matches the sync variant (#43 follow-up). +- Moved AIX from the async `fallocate` branch to the `set_len` + fallback branch, matching the sync implementation. +- Trait docs now explicitly state that locks are released + automatically when the owning file handle is closed (#23). +- Removed the stale trait-doc reference to non-existent cross-platform + tests in `lib.rs` (#16). +- Mitigated #31 (compiler warning about name collisions with upcoming + std methods): because 1.0 renames the trait methods to match std + exactly, `std::fs::File::lock` / `try_lock` / `unlock` (stable in + Rust 1.89+) now win via inherent dispatch and `unstable_name_collisions` + no longer fires for std users on recent rustc. +- Gated the `lock_impl!` macro with `#[allow(unused_macros)]` so + `cargo clippy --no-default-features` (filesystem-stats-only build) + does not fail under `-D warnings`. +- Removed dead duplicate macros `cfg_fs2_err` / `cfg_fs3_err` from + `lib.rs` (unified with `cfg_fs_err2` / `cfg_fs_err3`). +- Updated `html_root_url` to the 1.0.0 docs.rs path. + +### Dependency updates + +- Bumped `windows-sys` from 0.59 to 0.61. + +### Testing + +- Removed all `#[bench]` functions from the test harness. They + measured OS syscalls (`flock`, `LockFileEx`, `fallocate`, `statvfs`) + rather than fs4 code, and produced numbers dominated by the + underlying filesystem. Dropping them lets the crate build and test + on **stable** Rust (the bench harness was the only thing pinning + nightly via `#![cfg_attr(test, feature(test))]`). + `rust-toolchain.toml` is now `stable`. +- Added regression tests: + - `allocate_preserves_eof_within_cluster` — exercises the #13 + precondition (cluster-aligned `AllocationSize` with EOF inside + the cluster) and asserts EOF is not moved when `allocate(len)` is + re-called with `len <= allocated_size` on Windows. + - `allocate_idempotent` — exercises the #15 precondition (back-to-back + `allocate(len)` calls on macOS) to prevent a regression in the + short-circuit. + - Seven `TryLockError` unit tests covering variants, `Display`, + `std::error::Error::source`, `From`, `From + for io::Error`, and round-trip preservation of `ErrorKind`. + - `FsStats` getter + derive unit tests (previously every test + destructured the struct, so the four getter method bodies were + never executed and showed as uncovered). +- Fixed a long-standing macOS test failure: the cross-platform + `filesystem_space` test asserted `available_space <= free_space`, + which does not hold on macOS APFS. APFS counts purgeable space + (snapshots, cached data reclaimable on demand) in `f_bavail` but + not in `f_bfree`, so the POSIX invariant is violated on every run. + The assertion is removed and the async variant now makes a single + `statvfs` call plus destructure instead of three separate calls + racing with concurrent filesystem activity from other tests. + +### CI / tooling + +- New `.github/workflows/coverage.yml` workflow: per-OS matrix + (ubuntu-latest, macos-latest, windows-latest) running + `cargo tarpaulin --engine llvm --all-features --run-types tests + --ignore-tests` on each runner and uploading per-OS reports to + Codecov with per-OS flags. Each runner `--exclude-files` the other + OS's sources so they do not register as 0/N uncovered lines. +- The `cross` job now installs the MinGW-w64 toolchain when targeting + `*-pc-windows-gnu`. `windows-sys` 0.61 invokes `dlltool` during + build, and `ubuntu-latest` ships only the x86_64 MinGW toolchain + by default. +- README install snippets updated from `fs4 = { version = "0.13", ... }` + to `fs4 = { version = "1", ... }`. +- Housekeeping: added `.codecov.yml`, `rustfmt.toml` (2-space indent, + explains the session-wide reformat), and + `.github/workflows/loc.yml`; removed the obsolete `tea.yaml`. + ## 0.13.0 ### Breakage - Make `try_lock_*` return `std::io::Result`, which is compatible with the upcoming `std::fs::File::try_lock*` in `std`. + +[`std::fs::File::lock`]: https://doc.rust-lang.org/std/fs/struct.File.html#method.lock +[`std::fs::File::try_lock`]: https://doc.rust-lang.org/std/fs/struct.File.html#method.try_lock +[`std::fs::TryLockError`]: https://doc.rust-lang.org/std/fs/enum.TryLockError.html diff --git a/Cargo.toml b/Cargo.toml index c14d9546..3dd726bc 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 = "0.13.1" +version = "1.0.0" rust-version = "1.75.0" authors = ["Dan Burkert ", "Al Liu "] license = "MIT OR Apache-2.0" @@ -28,7 +28,7 @@ fs-err3-tokio = ["fs-err3", "fs-err3/tokio"] rustix = { version = "1", features = ["fs"] } [target.'cfg(windows)'.dependencies.windows-sys] -version = "0.59" +version = "0.61" features = ["Win32_Foundation", "Win32_Storage_FileSystem", "Win32_System_IO"] [dependencies] diff --git a/README.md b/README.md index 1d24eb0a..89d85ab6 100644 --- a/README.md +++ b/README.md @@ -8,14 +8,14 @@ Extended utilities for working with files and filesystems in Rust. This is a fork of the [fs2-rs](https://github.com/danburkert/fs2-rs) crate, the aim for this fork is to support `async` and replace `libc` by [rustix](https://github.com/bytecodealliance/rustix). -[github][Github-url] +[github][Github-url] +LoC [Build][CI-url] -[codecov][codecov-url] +[codecov][codecov-url] -[docs.rs][doc-url] +[docs.rs][doc-url] [crates.io][crates-url] [crates.io][crates-url] - license @@ -26,56 +26,56 @@ and replace `libc` by [rustix](https://github.com/bytecodealliance/rustix). ```toml [dependencies] - fs4 = { version = "0.13", features = ["sync"] } + fs4 = { version = "1", features = ["sync"] } ``` - [async-std runtime](https://crates.io/crates/async-std) ```toml [dependencies] - fs4 = { version = "0.13", features = ["async-std"] } + fs4 = { version = "1", features = ["async-std"] } ``` - [fs-err v2](https://crates.io/crates/fs-err) ```toml [dependencies] - fs4 = { version = "0.13", features = ["fs-err2"] } + fs4 = { version = "1", features = ["fs-err2"] } ``` - [fs-err-tokio v2](https://crates.io/crates/fs-err) ```toml [dependencies] - fs4 = { version = "0.13", features = ["fs-err2-tokio"] } + fs4 = { version = "1", features = ["fs-err2-tokio"] } ``` - [fs-err v3](https://crates.io/crates/fs-err) ```toml [dependencies] - fs4 = { version = "0.13", features = ["fs-err3"] } + fs4 = { version = "1", features = ["fs-err3"] } ``` - [fs-err-tokio v3](https://crates.io/crates/fs-err) ```toml [dependencies] - fs4 = { version = "0.13", features = ["fs-err3-tokio"] } + fs4 = { version = "1", features = ["fs-err3-tokio"] } ``` - [smol runtime](https://crates.io/crates/smol) ```toml [dependencies] - fs4 = { version = "0.13", features = ["smol"] } + fs4 = { version = "1", features = ["smol"] } ``` - [tokio runtime](https://crates.io/crates/tokio) ```toml [dependencies] - fs4 = { version = "0.13", features = ["tokio"] } + fs4 = { version = "1", features = ["tokio"] } ``` ## Features @@ -96,7 +96,7 @@ Apache License (Version 2.0). See [LICENSE-APACHE](LICENSE-APACHE), [LICENSE-MIT](LICENSE-MIT) for details. -Copyright (c) 2025 Al Liu. +Copyright (c) 2026 Al Liu. Copyright (c) 2015 Dan Burkert. diff --git a/rust-toolchain.toml b/rust-toolchain.toml index f5f24d9a..195f5daf 100644 --- a/rust-toolchain.toml +++ b/rust-toolchain.toml @@ -1,3 +1,2 @@ [toolchain] -# channel = 'stable' -channel = 'nightly' +channel = 'stable' diff --git a/rustfmt.toml b/rustfmt.toml new file mode 100644 index 00000000..f54d5e6e --- /dev/null +++ b/rustfmt.toml @@ -0,0 +1,13 @@ +max_width = 100 +hard_tabs = false +tab_spaces = 2 +newline_style = "Auto" +use_small_heuristics = "Default" +reorder_imports = true +reorder_modules = true +remove_nested_parens = true +merge_derives = true +use_try_shorthand = true +use_field_init_shorthand = true +force_explicit_abi = true + diff --git a/src/file_ext.rs b/src/file_ext.rs index 22038716..8298ecb6 100644 --- a/src/file_ext.rs +++ b/src/file_ext.rs @@ -1,7 +1,6 @@ -cfg_sync!( - pub(crate) mod sync_impl; -); +#[cfg(any(feature = "sync", feature = "fs-err2", feature = "fs-err3"))] +pub(crate) mod sync_impl; cfg_async!( - pub(crate) mod async_impl; + pub(crate) mod async_impl; ); diff --git a/src/file_ext/async_impl.rs b/src/file_ext/async_impl.rs index 2ae858a8..d209aea6 100644 --- a/src/file_ext/async_impl.rs +++ b/src/file_ext/async_impl.rs @@ -2,7 +2,7 @@ macro_rules! async_file_ext { ($file: ty, $file_name: literal) => { use std::io::Result; - #[doc = concat!("Extension trait for `", $file_name, "` which provides allocation, duplication and locking methods.")] + #[doc = concat!("Extension trait for `", $file_name, "` which provides allocation and locking methods.")] /// /// ## Notes on File Locks /// @@ -22,49 +22,64 @@ macro_rules! async_file_ext { /// permissions. /// * File locks may only be relied upon to be advisory. /// - /// See the tests in `lib.rs` for cross-platform lock behavior that may be - /// relied upon; see the tests in `unix.rs` and `windows.rs` for examples of - /// platform-specific behavior. File locks are implemented with + /// 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 - /// [`LockFile`](https://msdn.microsoft.com/en-us/library/windows/desktop/aa365202(v=vs.85).aspx) - /// on Windows. + /// [`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, and the file size is at least `len` bytes. 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. + /// 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>; - /// Locks the file for shared usage, blocking if the file is currently - /// locked exclusively. + /// Acquires a shared lock on the file, blocking until the lock can be + /// acquired. fn lock_shared(&self) -> Result<()>; - /// Locks the file for exclusive usage, blocking if the file is currently - /// locked. - fn lock_exclusive(&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<()>; - /// Locks the file for shared usage. - /// - /// Returns `Ok(true)` if the lock was acquired, `Ok(false)` if the file is currently - /// locked. - fn try_lock_shared(&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>; - /// Locks the file for exclusive usage. - /// - /// Returns `Ok(true)` if the lock was acquired, `Ok(false)` if the file is currently - /// locked. - fn try_lock_exclusive(&self) -> Result; + /// 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>; - /// Unlocks the file. + /// Releases any lock held on the file. The lock is also released + /// automatically when the file handle is closed. fn unlock(&self) -> Result<()>; - /// Unlocks the file. + /// Releases any lock held on the file. /// - /// **Note:** This method is not really "async", the underlying system call is still blocking. - /// Having this method as async is just for convenience when using it in async runtime. + /// **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>; } @@ -79,16 +94,16 @@ macro_rules! async_file_ext { sys::lock_shared(self) } - fn lock_exclusive(&self) -> Result<()> { - sys::lock_exclusive(self) + fn lock(&self) -> Result<()> { + sys::lock(self) } - fn try_lock_shared(&self) -> Result { + fn try_lock_shared(&self) -> std::result::Result<(), crate::TryLockError> { sys::try_lock_shared(self) } - fn try_lock_exclusive(&self) -> Result { - sys::try_lock_exclusive(self) + fn try_lock(&self) -> std::result::Result<(), crate::TryLockError> { + sys::try_lock(self) } fn unlock(&self) -> Result<()> { @@ -107,11 +122,7 @@ macro_rules! test_mod { #[cfg(test)] mod test { extern crate tempfile; - extern crate test; - use crate::{ - allocation_granularity, available_space, free_space, - total_space, - }; + use crate::{allocation_granularity, TryLockError}; $( $use_stmt @@ -147,19 +158,13 @@ macro_rules! test_mod { // Concurrent shared access is OK, but not shared and exclusive. file1.lock_shared().unwrap(); file2.lock_shared().unwrap(); - assert_eq!( - file3.try_lock_exclusive().unwrap(), - false, - ); + assert!(matches!(file3.try_lock(), Err(TryLockError::WouldBlock))); file1.unlock().unwrap(); - assert_eq!( - file3.try_lock_exclusive().unwrap(), - false, - ); + assert!(matches!(file3.try_lock(), Err(TryLockError::WouldBlock))); // Once all shared file locks are dropped, an exclusive lock may be created; file2.unlock().unwrap(); - file3.lock_exclusive().unwrap(); + file3.lock().unwrap(); } /// Tests exclusive file lock operations. @@ -183,19 +188,16 @@ macro_rules! test_mod { .unwrap(); // No other access is possible once an exclusive lock is created. - file1.lock_exclusive().unwrap(); - assert_eq!( - file2.try_lock_exclusive().unwrap(), - false, - ); - assert_eq!( - file2.try_lock_shared().unwrap(), - false, - ); + file1.lock().unwrap(); + assert!(matches!(file2.try_lock(), Err(TryLockError::WouldBlock))); + assert!(matches!( + file2.try_lock_shared(), + Err(TryLockError::WouldBlock), + )); // Once the exclusive lock is dropped, the second file is able to create a lock. file1.unlock().unwrap(); - file2.lock_exclusive().unwrap(); + file2.lock().unwrap(); } /// Tests that a lock is released after the file that owns it is dropped. @@ -218,11 +220,11 @@ macro_rules! test_mod { .await .unwrap(); - file1.lock_exclusive().unwrap(); - assert_eq!( - file2.try_lock_shared().unwrap(), - false, - ); + file1.lock().unwrap(); + assert!(matches!( + file2.try_lock_shared(), + Err(TryLockError::WouldBlock), + )); // Drop file1; the lock should be released. drop(file1); @@ -261,17 +263,85 @@ macro_rules! test_mod { assert_eq!(blksize + 1, file.metadata().await.unwrap().len()); } + /// Regression for issue #13: on Windows, re-`allocate`-ing + /// inside an already-allocated cluster must not move the EOF + /// pointer (the old path called `set_len`, which triggered + /// Windows buffered-I/O quirks). The trait doc carves this + /// out from the general "file size is at least `len`" + /// contract, so this test asserts the strict invariant on + /// Windows and a loose one on Unix. + #[$annotation] + async fn allocate_preserves_eof_within_cluster() { + let tempdir = tempfile::TempDir::with_prefix("fs4").unwrap(); + let path = tempdir.path().join("fs4"); + let file = fs::OpenOptions::new() + .write(true) + .create(true) + .open(&path) + .await + .unwrap(); + let blksize = allocation_granularity(&path).unwrap(); + + file.allocate(2 * blksize - 1).await.unwrap(); + assert_eq!(2 * blksize - 1, file.metadata().await.unwrap().len()); + + file.allocate(2 * blksize).await.unwrap(); + + #[cfg(windows)] + assert_eq!( + 2 * blksize - 1, + file.metadata().await.unwrap().len(), + "Windows allocate must not extend EOF inside an already-allocated cluster (#13)", + ); + #[cfg(unix)] + assert!(file.metadata().await.unwrap().len() >= 2 * blksize - 1); + } + + /// Regression test for issue #15: re-allocating the same length must + /// not fail on macOS. + #[$annotation] + async fn allocate_idempotent() { + let tempdir = tempfile::TempDir::with_prefix("fs4").unwrap(); + let path = tempdir.path().join("fs4"); + let file = fs::OpenOptions::new() + .write(true) + .create(true) + .open(&path) + .await + .unwrap(); + let blksize = allocation_granularity(&path).unwrap(); + + file.allocate(2 * blksize).await.unwrap(); + file.allocate(2 * blksize).await.unwrap(); + file.allocate(blksize).await.unwrap(); + assert!(file.metadata().await.unwrap().len() >= 2 * blksize); + } + /// Checks filesystem space methods. + /// + /// Uses a single `statvfs` call + destructure so the three + /// numbers are read atomically; calling `free_space` / + /// `available_space` / `total_space` separately makes the + /// assertions race with concurrent filesystem activity + /// from other tests. + /// + /// Does not assert `available_space <= free_space`: on + /// macOS APFS the kernel reports `f_bavail > f_bfree` + /// because purgeable space (snapshots, cached data) is + /// counted as available but not as free, so the usual + /// POSIX invariant does not hold. #[$annotation] async fn filesystem_space() { let tempdir = tempfile::TempDir::with_prefix("fs4").unwrap(); - let total_space = total_space(tempdir.path()).unwrap(); - let free_space = free_space(tempdir.path()).unwrap(); - let available_space = available_space(tempdir.path()).unwrap(); - - assert!(total_space > free_space); - assert!(total_space > available_space); - assert!(available_space <= free_space); + let crate::FsStats { + free_space, + available_space, + total_space, + .. + } = crate::statvfs(tempdir.path()).unwrap(); + + assert!(total_space >= free_space); + assert!(total_space >= available_space); } } }; diff --git a/src/file_ext/sync_impl.rs b/src/file_ext/sync_impl.rs index 6fcdc1fa..b66a15e8 100644 --- a/src/file_ext/sync_impl.rs +++ b/src/file_ext/sync_impl.rs @@ -2,7 +2,7 @@ macro_rules! file_ext { ($file:ty, $file_name:literal) => { use std::io::Result; - #[doc = concat!("Extension trait for `", $file_name, "` which provides allocation, duplication and locking methods.")] + #[doc = concat!("Extension trait for `", $file_name, "` which provides allocation and locking methods.")] /// /// ## Notes on File Locks /// @@ -22,43 +22,58 @@ macro_rules! file_ext { /// permissions. /// * File locks may only be relied upon to be advisory. /// - /// See the tests in `lib.rs` for cross-platform lock behavior that may be - /// relied upon; see the tests in `unix.rs` and `windows.rs` for examples of - /// platform-specific behavior. File locks are implemented with + /// 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 - /// [`LockFile`](https://msdn.microsoft.com/en-us/library/windows/desktop/aa365202(v=vs.85).aspx) + /// [`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, and the file size is at least `len` bytes. 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. + /// 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<()>; - /// Locks the file for shared usage, blocking if the file is currently - /// locked exclusively. + /// Acquires a shared lock on the file, blocking until the lock can be + /// acquired. fn lock_shared(&self) -> Result<()>; - /// Locks the file for exclusive usage, blocking if the file is currently - /// locked. - fn lock_exclusive(&self) -> Result<()>; - - /// Locks the file for shared usage. - /// - /// Returns `Ok(true)` if the lock was acquired, `Ok(false)` if the file is currently - /// locked. - fn try_lock_shared(&self) -> Result; - - /// Locks the file for exclusive usage. - /// - /// Returns `Ok(true)` if the lock was acquired, `Ok(false)` if the file is currently - /// locked. - fn try_lock_exclusive(&self) -> Result; - - /// Unlocks the file. + /// 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<()>; } @@ -72,14 +87,14 @@ macro_rules! file_ext { fn lock_shared(&self) -> Result<()> { sys::lock_shared(self) } - fn lock_exclusive(&self) -> Result<()> { - sys::lock_exclusive(self) + fn lock(&self) -> Result<()> { + sys::lock(self) } - fn try_lock_shared(&self) -> Result { + fn try_lock_shared(&self) -> std::result::Result<(), crate::TryLockError> { sys::try_lock_shared(self) } - fn try_lock_exclusive(&self) -> Result { - sys::try_lock_exclusive(self) + fn try_lock(&self) -> std::result::Result<(), crate::TryLockError> { + sys::try_lock(self) } fn unlock(&self) -> Result<()> { sys::unlock(self) @@ -93,13 +108,9 @@ macro_rules! test_mod { #[cfg(test)] mod test { extern crate tempfile; - extern crate test; use super::*; - use crate::{ - allocation_granularity, available_space, free_space, statvfs, - total_space, FsStats, - }; + use crate::{allocation_granularity, statvfs, FsStats, TryLockError}; $( $use_stmt @@ -133,21 +144,21 @@ macro_rules! test_mod { .unwrap(); // Concurrent shared access is OK, but not shared and exclusive. - file1.lock_shared().unwrap(); - file2.lock_shared().unwrap(); - assert_eq!( - file3.try_lock_exclusive().unwrap(), - false, - ); - file1.unlock().unwrap(); - assert_eq!( - file3.try_lock_exclusive().unwrap(), - false, - ); + FileExt::lock_shared(&file1).unwrap(); + FileExt::lock_shared(&file2).unwrap(); + assert!(matches!( + FileExt::try_lock(&file3), + Err(TryLockError::WouldBlock), + )); + FileExt::unlock(&file1).unwrap(); + assert!(matches!( + FileExt::try_lock(&file3), + Err(TryLockError::WouldBlock), + )); // Once all shared file locks are dropped, an exclusive lock may be created; - file2.unlock().unwrap(); - file3.lock_exclusive().unwrap(); + FileExt::unlock(&file2).unwrap(); + FileExt::lock(&file3).unwrap(); } /// Tests exclusive file lock operations. @@ -171,19 +182,19 @@ macro_rules! test_mod { .unwrap(); // No other access is possible once an exclusive lock is created. - file1.lock_exclusive().unwrap(); - assert_eq!( - file2.try_lock_exclusive().unwrap(), - false, - ); - assert_eq!( - FileExt::try_lock_shared(&file2).unwrap(), - false, - ); + FileExt::lock(&file1).unwrap(); + assert!(matches!( + FileExt::try_lock(&file2), + Err(TryLockError::WouldBlock), + )); + assert!(matches!( + FileExt::try_lock_shared(&file2), + Err(TryLockError::WouldBlock), + )); // Once the exclusive lock is dropped, the second file is able to create a lock. - file1.unlock().unwrap(); - file2.lock_exclusive().unwrap(); + FileExt::unlock(&file1).unwrap(); + FileExt::lock(&file2).unwrap(); } /// Tests that a lock is released after the file that owns it is dropped. @@ -206,15 +217,15 @@ macro_rules! test_mod { .open(&path) .unwrap(); - file1.lock_exclusive().unwrap(); - assert_eq!( - FileExt::try_lock_shared(&file2).unwrap(), - false, - ); + FileExt::lock(&file1).unwrap(); + assert!(matches!( + FileExt::try_lock_shared(&file2), + Err(TryLockError::WouldBlock), + )); // Drop file1; the lock should be released. drop(file1); - file2.lock_shared().unwrap(); + FileExt::lock_shared(&file2).unwrap(); } /// Tests file allocation. @@ -231,176 +242,115 @@ macro_rules! test_mod { let blksize = allocation_granularity(&path).unwrap(); // New files are created with no allocated size. - assert_eq!(0, file.allocated_size().unwrap()); + assert_eq!(0, FileExt::allocated_size(&file).unwrap()); assert_eq!(0, file.metadata().unwrap().len()); // Allocate space for the file, checking that the allocated size steps // up by block size, and the file length matches the allocated size. - file.allocate(2 * blksize - 1).unwrap(); - assert_eq!(2 * blksize, file.allocated_size().unwrap()); + FileExt::allocate(&file, 2 * blksize - 1).unwrap(); + assert_eq!(2 * blksize, FileExt::allocated_size(&file).unwrap()); assert_eq!(2 * blksize - 1, file.metadata().unwrap().len()); // Truncate the file, checking that the allocated size steps down by // block size. file.set_len(blksize + 1).unwrap(); - assert_eq!(2 * blksize, file.allocated_size().unwrap()); + assert_eq!(2 * blksize, FileExt::allocated_size(&file).unwrap()); assert_eq!(blksize + 1, file.metadata().unwrap().len()); } - /// Checks filesystem space methods. + /// Regression for issue #13: on Windows, re-`allocate`-ing inside + /// an already-allocated cluster must not move the EOF pointer + /// (the old behaviour called `set_len`, which triggered Windows + /// buffered-I/O quirks). The trait doc explicitly carves this + /// behaviour out from the general "file size is at least `len`" + /// contract, so this test asserts the strict invariant on + /// Windows and a loose one on Unix. #[test] - fn filesystem_space() { + fn allocate_preserves_eof_within_cluster() { let tempdir = tempfile::TempDir::with_prefix("fs4").unwrap(); - let FsStats { - free_space, - available_space, - total_space, - .. - } = statvfs(tempdir.path()).unwrap(); - - assert!(total_space > free_space); - assert!(total_space > available_space); - assert!(available_space <= free_space); - } - - /// Benchmarks creating and removing a file. This is a baseline benchmark - /// for comparing against the truncate and allocate benchmarks. - #[bench] - fn bench_file_create(b: &mut test::Bencher) { - let tempdir = tempfile::TempDir::with_prefix("fs4").unwrap(); - let path = tempdir.path().join("file"); - - b.iter(|| { - fs::OpenOptions::new() - .read(true) - .write(true) - .create(true) - .truncate(true) - .open(&path) - .unwrap(); - fs::remove_file(&path).unwrap(); - }); - } - - /// Benchmarks creating a file, truncating it to 32MiB, and deleting it. - #[bench] - fn bench_file_truncate(b: &mut test::Bencher) { - let size = 32 * 1024 * 1024; - let tempdir = tempfile::TempDir::with_prefix("fs4").unwrap(); - let path = tempdir.path().join("file"); - - b.iter(|| { - let file = fs::OpenOptions::new() - .read(true) - .write(true) - .create(true) - .truncate(true) - .open(&path) - .unwrap(); - file.set_len(size).unwrap(); - fs::remove_file(&path).unwrap(); - }); - } - - /// Benchmarks creating a file, allocating 32MiB for it, and deleting it. - #[bench] - fn bench_file_allocate(b: &mut test::Bencher) { - let size = 32 * 1024 * 1024; - let tempdir = tempfile::TempDir::with_prefix("fs4").unwrap(); - let path = tempdir.path().join("file"); - - b.iter(|| { - let file = fs::OpenOptions::new() - .read(true) - .write(true) - .create(true) - .truncate(true) - .open(&path) - .unwrap(); - file.allocate(size).unwrap(); - fs::remove_file(&path).unwrap(); - }); - } - - /// Benchmarks creating a file, allocating 32MiB for it, and deleting it. - #[bench] - fn bench_allocated_size(b: &mut test::Bencher) { - let size = 32 * 1024 * 1024; - let tempdir = tempfile::TempDir::with_prefix("fs4").unwrap(); - let path = tempdir.path().join("file"); + let path = tempdir.path().join("fs4"); let file = fs::OpenOptions::new() - .read(true) .write(true) .create(true) .truncate(true) - .open(path) + .open(&path) .unwrap(); - file.allocate(size).unwrap(); + let blksize = allocation_granularity(&path).unwrap(); - b.iter(|| { - file.allocated_size().unwrap(); - }); + // Reserve cluster-aligned space but leave EOF below the + // cluster boundary — the precondition reported in #13. + FileExt::allocate(&file, 2 * blksize - 1).unwrap(); + assert_eq!(2 * blksize - 1, file.metadata().unwrap().len()); + + // Request `allocate` up to the cluster boundary. Before + // the fix, Windows would `set_len(2*blksize)`; after, it + // short-circuits since `allocated_size >= len`. + FileExt::allocate(&file, 2 * blksize).unwrap(); + + #[cfg(windows)] + assert_eq!( + 2 * blksize - 1, + file.metadata().unwrap().len(), + "Windows allocate must not extend EOF inside an already-allocated cluster (#13)", + ); + #[cfg(unix)] + assert!(file.metadata().unwrap().len() >= 2 * blksize - 1); } - /// Benchmarks locking and unlocking a file lock. - #[bench] - fn bench_lock_unlock(b: &mut test::Bencher) { + /// Re-allocating the same length must not fail. Regression for issue #15. + #[test] + fn allocate_idempotent() { 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) + .open(&path) .unwrap(); + let blksize = allocation_granularity(&path).unwrap(); - b.iter(|| { - file.lock_exclusive().unwrap(); - file.unlock().unwrap(); - }); + FileExt::allocate(&file, 2 * blksize).unwrap(); + FileExt::allocate(&file, 2 * blksize).unwrap(); + FileExt::allocate(&file, blksize).unwrap(); + assert!(file.metadata().unwrap().len() >= 2 * blksize); } - /// Benchmarks the free space method. - #[bench] - fn bench_free_space(b: &mut test::Bencher) { + /// Checks filesystem space methods. + /// + /// Does not assert `available_space <= free_space`: on + /// macOS APFS the kernel reports `f_bavail > f_bfree` + /// because purgeable space (snapshots, cached data) is + /// counted as available but not as free, so the usual + /// POSIX invariant does not hold. + #[test] + fn filesystem_space() { let tempdir = tempfile::TempDir::with_prefix("fs4").unwrap(); - b.iter(|| { - test::black_box(free_space(tempdir.path()).unwrap()); - }); - } + let FsStats { + free_space, + available_space, + total_space, + .. + } = statvfs(tempdir.path()).unwrap(); - /// Benchmarks the available space method. - #[bench] - fn bench_available_space(b: &mut test::Bencher) { - let tempdir = tempfile::TempDir::with_prefix("fs4").unwrap(); - b.iter(|| { - test::black_box(available_space(tempdir.path()).unwrap()); - }); + assert!(total_space >= free_space); + assert!(total_space >= available_space); } - /// Benchmarks the total space method. - #[bench] - fn bench_total_space(b: &mut test::Bencher) { - let tempdir = tempfile::TempDir::with_prefix("fs4").unwrap(); - b.iter(|| { - test::black_box(total_space(tempdir.path()).unwrap()); - }); - } } }; } cfg_sync! { - pub(crate) mod std_impl; + pub(crate) mod std_impl; } -cfg_fs2_err! { +cfg_fs_err2! { pub(crate) mod fs_err2_impl; } -cfg_fs3_err! { +cfg_fs_err3! { pub(crate) mod fs_err3_impl; } diff --git a/src/fs_stats.rs b/src/fs_stats.rs index 9e9e53d5..43f8a6da 100644 --- a/src/fs_stats.rs +++ b/src/fs_stats.rs @@ -1,37 +1,82 @@ /// `FsStats` contains some common stats about a file system. #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct FsStats { - pub(crate) free_space: u64, - pub(crate) available_space: u64, - pub(crate) total_space: u64, - pub(crate) allocation_granularity: u64, + pub(crate) free_space: u64, + pub(crate) available_space: u64, + pub(crate) total_space: u64, + pub(crate) allocation_granularity: u64, } impl FsStats { - /// Returns the number of free bytes in the file system containing the provided - /// path. - pub fn free_space(&self) -> u64 { - self.free_space - } - - /// Returns the available space in bytes to non-priveleged users in the file - /// system containing the provided path. - pub fn available_space(&self) -> u64 { - self.available_space - } - - /// Returns the total space in bytes in the file system containing the provided - /// path. - pub fn total_space(&self) -> u64 { - self.total_space - } - - /// Returns the filesystem's disk space allocation granularity in bytes. - /// The provided path may be for any file in the filesystem. - /// - /// On Posix, this is equivalent to the filesystem's block size. - /// On Windows, this is equivalent to the filesystem's cluster size. - pub fn allocation_granularity(&self) -> u64 { - self.allocation_granularity - } + /// Returns the number of free bytes in the file system containing the provided + /// path. + pub fn free_space(&self) -> u64 { + self.free_space + } + + /// Returns the available space in bytes to non-privileged users in the file + /// system containing the provided path. + pub fn available_space(&self) -> u64 { + self.available_space + } + + /// Returns the total space in bytes in the file system containing the provided + /// path. + pub fn total_space(&self) -> u64 { + self.total_space + } + + /// Returns the filesystem's disk space allocation granularity in bytes. + /// The provided path may be for any file in the filesystem. + /// + /// On Posix, this is equivalent to the filesystem's block size. + /// On Windows, this is equivalent to the filesystem's cluster size. + pub fn allocation_granularity(&self) -> u64 { + self.allocation_granularity + } +} + +#[cfg(test)] +mod tests { + //! The cross-platform `filesystem_space` tests destructure `FsStats` + //! directly, and the top-level `free_space` / `available_space` / + //! `total_space` / `allocation_granularity` functions on the crate + //! root use field access too, so the four getter methods above + //! never get called from the integration tests. These unit tests + //! exist so coverage reflects that the getters do what they claim. + + use super::*; + + #[test] + fn getters_return_fields_verbatim() { + let stats = FsStats { + free_space: 1, + available_space: 2, + total_space: 3, + allocation_granularity: 4, + }; + assert_eq!(stats.free_space(), 1); + assert_eq!(stats.available_space(), 2); + assert_eq!(stats.total_space(), 3); + assert_eq!(stats.allocation_granularity(), 4); + } + + #[test] + fn derives_work() { + let a = FsStats { + free_space: 1, + available_space: 2, + total_space: 3, + allocation_granularity: 4, + }; + let b = a.clone(); + assert_eq!(a, b); + assert!(!format!("{a:?}").is_empty()); + + let c = FsStats { + free_space: 9, + ..a.clone() + }; + assert_ne!(a, c); + } } diff --git a/src/lib.rs b/src/lib.rs index a91d1d5b..7e006a80 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,6 +1,5 @@ //! Extended utilities for working with files and filesystems in Rust. -#![doc(html_root_url = "https://docs.rs/fs4/0.13.0")] -#![cfg_attr(test, feature(test))] +#![doc(html_root_url = "https://docs.rs/fs4/1.0.0")] #![cfg_attr(docsrs, feature(doc_cfg))] #![cfg_attr(docsrs, allow(unused_attributes))] #![allow(unexpected_cfgs, unstable_name_collisions)] @@ -18,8 +17,6 @@ macro_rules! cfg_async_std { } } -// This lint is a bug, it is being used in multiple places. -#[allow(unused_macros)] macro_rules! cfg_fs_err2 { ($($item:item)*) => { $( @@ -40,8 +37,6 @@ macro_rules! cfg_fs_err2_tokio { } } -// This lint is a bug, it is being used in multiple places. -#[allow(unused_macros)] macro_rules! cfg_fs_err3 { ($($item:item)*) => { $( @@ -92,31 +87,23 @@ macro_rules! cfg_sync { } } -macro_rules! cfg_fs2_err { - ($($item:item)*) => { - $( - #[cfg(feature = "fs-err2")] - #[cfg_attr(docsrs, doc(cfg(feature = "fs-err2")))] - $item - )* - } -} - -macro_rules! cfg_fs3_err { - ($($item:item)*) => { - $( - #[cfg(feature = "fs-err3")] - #[cfg_attr(docsrs, doc(cfg(feature = "fs-err3")))] - $item - )* - } -} - macro_rules! cfg_async { ($($item:item)*) => { $( - #[cfg(any(feature = "smol", feature = "async-std", feature = "tokio", feature = "fs-err-tokio"))] - #[cfg_attr(docsrs, doc(cfg(any(feature = "smol", feature = "async-std", feature = "tokio", feature = "fs-err-tokio"))))] + #[cfg(any( + feature = "smol", + feature = "async-std", + feature = "tokio", + feature = "fs-err2-tokio", + feature = "fs-err3-tokio", + ))] + #[cfg_attr(docsrs, doc(cfg(any( + feature = "smol", + feature = "async-std", + feature = "tokio", + feature = "fs-err2-tokio", + feature = "fs-err3-tokio", + ))))] $item )* } @@ -136,98 +123,93 @@ use windows as sys; mod file_ext; cfg_sync!( - pub mod fs_std { - pub use crate::file_ext::sync_impl::std_impl::FileExt; - } + pub use crate::file_ext::sync_impl::std_impl::FileExt; ); cfg_fs_err2!( - pub mod fs_err2 { - pub use crate::file_ext::sync_impl::fs_err2_impl::FileExt; - } + pub mod fs_err2 { + pub use crate::file_ext::sync_impl::fs_err2_impl::FileExt; + } ); cfg_fs_err3!( - pub mod fs_err3 { - pub use crate::file_ext::sync_impl::fs_err3_impl::FileExt; - } + pub mod fs_err3 { + pub use crate::file_ext::sync_impl::fs_err3_impl::FileExt; + } ); cfg_async_std!( - pub mod async_std { - pub use crate::file_ext::async_impl::async_std_impl::AsyncFileExt; - } + pub mod async_std { + pub use crate::file_ext::async_impl::async_std_impl::AsyncFileExt; + } ); cfg_fs_err2_tokio!( - pub mod fs_err2_tokio { - pub use crate::file_ext::async_impl::fs_err2_tokio_impl::AsyncFileExt; - } + pub mod fs_err2_tokio { + pub use crate::file_ext::async_impl::fs_err2_tokio_impl::AsyncFileExt; + } ); cfg_fs_err3_tokio!( - pub mod fs_err3_tokio { - pub use crate::file_ext::async_impl::fs_err3_tokio_impl::AsyncFileExt; - } + pub mod fs_err3_tokio { + pub use crate::file_ext::async_impl::fs_err3_tokio_impl::AsyncFileExt; + } ); cfg_smol!( - pub mod smol { - pub use crate::file_ext::async_impl::smol_impl::AsyncFileExt; - } + pub mod smol { + pub use crate::file_ext::async_impl::smol_impl::AsyncFileExt; + } ); cfg_tokio!( - pub mod tokio { - pub use crate::file_ext::async_impl::tokio_impl::AsyncFileExt; - } + pub mod tokio { + pub use crate::file_ext::async_impl::tokio_impl::AsyncFileExt; + } ); mod fs_stats; pub use fs_stats::FsStats; -use std::io::{Error, Result}; -use std::path::Path; +mod try_lock_error; +pub use try_lock_error::TryLockError; -/// Returns the error that a call to a try lock method on a contended file will -/// return. -pub fn lock_contended_error() -> Error { - sys::lock_error() -} +use std::io::Result; +use std::path::Path; /// Get the stats of the file system containing the provided path. pub fn statvfs

(path: P) -> Result where - P: AsRef, + P: AsRef, { - sys::statvfs(path.as_ref()) + sys::statvfs(path.as_ref()) } /// Returns the number of free bytes in the file system containing the provided /// path. pub fn free_space

(path: P) -> Result where - P: AsRef, + P: AsRef, { - statvfs(path).map(|stat| stat.free_space) + statvfs(path).map(|stat| stat.free_space) } -/// Returns the available space in bytes to non-priveleged users in the file +/// Returns the available space in bytes to non-privileged users in the file /// system containing the provided path. pub fn available_space

(path: P) -> Result where - P: AsRef, + P: AsRef, { - statvfs(path).map(|stat| stat.available_space) + statvfs(path).map(|stat| stat.available_space) } /// Returns the total space in bytes in the file system containing the provided /// path. pub fn total_space

(path: P) -> Result where - P: AsRef, + P: AsRef, { - statvfs(path).map(|stat| stat.total_space) + statvfs(path).map(|stat| stat.total_space) } /// Returns the filesystem's disk space allocation granularity in bytes. @@ -237,7 +219,7 @@ where /// On Windows, this is equivalent to the filesystem's cluster size. pub fn allocation_granularity

(path: P) -> Result where - P: AsRef, + P: AsRef, { - statvfs(path).map(|stat| stat.allocation_granularity) + statvfs(path).map(|stat| stat.allocation_granularity) } diff --git a/src/try_lock_error.rs b/src/try_lock_error.rs new file mode 100644 index 00000000..6356935d --- /dev/null +++ b/src/try_lock_error.rs @@ -0,0 +1,150 @@ +use std::fmt; +use std::io; + +/// The error returned from [`FileExt::try_lock`](crate::FileExt::try_lock) +/// and [`FileExt::try_lock_shared`](crate::FileExt::try_lock_shared). +/// +/// This mirrors [`std::fs::TryLockError`] that was stabilized alongside +/// [`File::try_lock`](std::fs::File::try_lock) in Rust 1.89. +#[derive(Debug)] +pub enum TryLockError { + /// The lock could not be acquired due to an I/O error on the file. + Error(io::Error), + /// The lock could not be acquired at this time because the operation would + /// otherwise block. + WouldBlock, +} + +impl fmt::Display for TryLockError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Error(err) => err.fmt(f), + Self::WouldBlock => "try_lock failed because the operation would block".fmt(f), + } + } +} + +impl std::error::Error for TryLockError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Self::Error(err) => Some(err), + Self::WouldBlock => None, + } + } +} + +impl From for io::Error { + fn from(err: TryLockError) -> Self { + match err { + TryLockError::Error(err) => err, + TryLockError::WouldBlock => io::Error::from(io::ErrorKind::WouldBlock), + } + } +} + +impl From for TryLockError { + fn from(err: io::Error) -> Self { + if err.kind() == io::ErrorKind::WouldBlock { + TryLockError::WouldBlock + } else { + TryLockError::Error(err) + } + } +} + +#[cfg(test)] +mod tests { + //! Regression tests for the 1.0 `TryLockError` API. These exist so + //! that the `Result<(), TryLockError>` shape (which now mirrors + //! `std::fs::TryLockError`) stays compatible with std's semantics. + + use super::*; + use std::error::Error as _; + use std::io; + + /// A raw `io::Error` with kind `WouldBlock` must collapse into the + /// `WouldBlock` variant — callers rely on this to distinguish "lock + /// contended" from "real I/O failure". + #[test] + fn from_io_error_would_block_collapses_to_would_block() { + let err: TryLockError = io::Error::from(io::ErrorKind::WouldBlock).into(); + assert!(matches!(err, TryLockError::WouldBlock)); + } + + /// Any other `io::Error` kind must surface as `Error(inner)`, + /// preserving the underlying `io::Error` so callers can inspect it. + #[test] + fn from_io_error_other_preserves_inner() { + let err: TryLockError = io::Error::from(io::ErrorKind::PermissionDenied).into(); + match err { + TryLockError::Error(inner) => { + assert_eq!(inner.kind(), io::ErrorKind::PermissionDenied); + } + other => panic!("expected TryLockError::Error, got {other:?}"), + } + } + + /// `io::Error::from(TryLockError::WouldBlock)` must produce an + /// error whose `kind()` is `WouldBlock`, matching std's + /// `impl From for io::Error`. + #[test] + fn into_io_error_would_block() { + let err: io::Error = TryLockError::WouldBlock.into(); + assert_eq!(err.kind(), io::ErrorKind::WouldBlock); + } + + /// `io::Error::from(TryLockError::Error(inner))` must return the + /// original `inner` verbatim (same kind, same OS error if any). + #[test] + fn into_io_error_passes_inner_through() { + let inner = io::Error::from(io::ErrorKind::NotFound); + let err: io::Error = TryLockError::Error(inner).into(); + assert_eq!(err.kind(), io::ErrorKind::NotFound); + } + + /// Round-trip: `io::Error` → `TryLockError` → `io::Error` must + /// preserve the `ErrorKind` for both variants. + #[test] + fn round_trip_preserves_error_kind() { + for kind in [ + io::ErrorKind::WouldBlock, + io::ErrorKind::PermissionDenied, + io::ErrorKind::NotFound, + io::ErrorKind::Interrupted, + ] { + let original = io::Error::from(kind); + let converted: io::Error = TryLockError::from(original).into(); + assert_eq!( + converted.kind(), + kind, + "round-trip changed kind for {kind:?}" + ); + } + } + + /// `Display` must produce a non-empty message for both variants so + /// logs and `?` chains remain human-readable. + #[test] + fn display_is_non_empty() { + assert!(!TryLockError::WouldBlock.to_string().is_empty()); + let inner = io::Error::from(io::ErrorKind::NotFound); + assert!(!TryLockError::Error(inner).to_string().is_empty()); + } + + /// `std::error::Error::source` must expose the inner `io::Error` + /// for the `Error` variant and return `None` for `WouldBlock`, so + /// downstream error-chain walkers (anyhow, eyre, etc.) can recover + /// the OS error. + #[test] + fn source_exposes_inner_only_for_error_variant() { + assert!(TryLockError::WouldBlock.source().is_none()); + + let inner = io::Error::from(io::ErrorKind::NotFound); + let err = TryLockError::Error(inner); + let src = err.source().expect("Error variant must expose source"); + assert!( + src.downcast_ref::().is_some(), + "source must be an io::Error" + ); + } +} diff --git a/src/unix.rs b/src/unix.rs index bd046421..898c59b8 100644 --- a/src/unix.rs +++ b/src/unix.rs @@ -1,85 +1,80 @@ +// Expanded inside the `sync_impl` and `async_impl` submodules, both of +// which are feature-gated. With `--no-default-features` (nothing but +// the filesystem-stats API enabled), this macro has no caller, so +// silence the resulting unused-macro lint. +#[allow(unused_macros)] macro_rules! lock_impl { - ($file: ty) => { - #[cfg(not(target_os = "wasi"))] - pub fn lock_shared(file: &$file) -> std::io::Result<()> { - flock(file, rustix::fs::FlockOperation::LockShared) - } + ($file: ty) => { + #[cfg(not(target_os = "wasi"))] + pub fn lock_shared(file: &$file) -> std::io::Result<()> { + flock(file, rustix::fs::FlockOperation::LockShared) + } - #[cfg(not(target_os = "wasi"))] - pub fn lock_exclusive(file: &$file) -> std::io::Result<()> { - flock(file, rustix::fs::FlockOperation::LockExclusive) - } + #[cfg(not(target_os = "wasi"))] + pub fn lock(file: &$file) -> std::io::Result<()> { + flock(file, rustix::fs::FlockOperation::LockExclusive) + } - #[cfg(not(target_os = "wasi"))] - pub fn try_lock_shared(file: &$file) -> std::io::Result { - try_flock(file, rustix::fs::FlockOperation::NonBlockingLockShared) - } + #[cfg(not(target_os = "wasi"))] + pub fn try_lock_shared(file: &$file) -> std::result::Result<(), $crate::TryLockError> { + try_flock(file, rustix::fs::FlockOperation::NonBlockingLockShared) + } - #[cfg(not(target_os = "wasi"))] - pub fn try_lock_exclusive(file: &$file) -> std::io::Result { - try_flock(file, rustix::fs::FlockOperation::NonBlockingLockExclusive) - } + #[cfg(not(target_os = "wasi"))] + pub fn try_lock(file: &$file) -> std::result::Result<(), $crate::TryLockError> { + try_flock(file, rustix::fs::FlockOperation::NonBlockingLockExclusive) + } - #[cfg(not(target_os = "wasi"))] - pub fn unlock(file: &$file) -> std::io::Result<()> { - flock(file, rustix::fs::FlockOperation::Unlock) - } + #[cfg(not(target_os = "wasi"))] + pub fn unlock(file: &$file) -> std::io::Result<()> { + flock(file, rustix::fs::FlockOperation::Unlock) + } - #[cfg(not(target_os = "wasi"))] - fn flock(file: &$file, flag: rustix::fs::FlockOperation) -> std::io::Result<()> { - let borrowed_fd = unsafe { rustix::fd::BorrowedFd::borrow_raw(file.as_raw_fd()) }; + #[cfg(not(target_os = "wasi"))] + fn flock(file: &$file, flag: rustix::fs::FlockOperation) -> std::io::Result<()> { + let borrowed_fd = unsafe { rustix::fd::BorrowedFd::borrow_raw(file.as_raw_fd()) }; - match rustix::fs::flock(borrowed_fd, flag) { - Ok(_) => Ok(()), - Err(e) => Err(std::io::Error::from_raw_os_error(e.raw_os_error())), - } - } + rustix::fs::flock(borrowed_fd, flag) + .map_err(|e| std::io::Error::from_raw_os_error(e.raw_os_error())) + } - #[cfg(not(target_os = "wasi"))] - fn try_flock(file: &$file, flag: rustix::fs::FlockOperation) -> std::io::Result { - let borrowed_fd = unsafe { rustix::fd::BorrowedFd::borrow_raw(file.as_raw_fd()) }; + #[cfg(not(target_os = "wasi"))] + fn try_flock( + file: &$file, + flag: rustix::fs::FlockOperation, + ) -> std::result::Result<(), $crate::TryLockError> { + let borrowed_fd = unsafe { rustix::fd::BorrowedFd::borrow_raw(file.as_raw_fd()) }; - match rustix::fs::flock(borrowed_fd, flag) { - Ok(_) => Ok(true), - Err(e) => { - let err = std::io::Error::from_raw_os_error(e.raw_os_error()); - if let std::io::ErrorKind::WouldBlock = err.kind() { - return Ok(false); - } - Err(err) - } - } - } - }; + rustix::fs::flock(borrowed_fd, flag) + .map_err(|e| std::io::Error::from_raw_os_error(e.raw_os_error()).into()) + } + }; } #[cfg(any( - feature = "smol", - feature = "async-std", - feature = "tokio", - feature = "fs-err-tokio" + feature = "smol", + feature = "async-std", + feature = "tokio", + feature = "fs-err2-tokio", + feature = "fs-err3-tokio", ))] pub(crate) mod async_impl; -#[cfg(any(feature = "sync", feature = "fs-err"))] +#[cfg(any(feature = "sync", feature = "fs-err2", feature = "fs-err3"))] pub(crate) mod sync_impl; use crate::FsStats; -use std::io::{Error, Result}; +use std::io::Result; use std::path::Path; -pub fn lock_error() -> Error { - Error::from_raw_os_error(rustix::io::Errno::WOULDBLOCK.raw_os_error()) -} - pub fn statvfs(path: impl AsRef) -> Result { - match rustix::fs::statvfs(path.as_ref()) { - Ok(stat) => Ok(FsStats { - free_space: stat.f_frsize * stat.f_bfree, - available_space: stat.f_frsize * stat.f_bavail, - total_space: stat.f_frsize * stat.f_blocks, - allocation_granularity: stat.f_frsize, - }), - Err(e) => Err(std::io::Error::from_raw_os_error(e.raw_os_error())), - } + match rustix::fs::statvfs(path.as_ref()) { + Ok(stat) => Ok(FsStats { + free_space: stat.f_frsize.saturating_mul(stat.f_bfree), + available_space: stat.f_frsize.saturating_mul(stat.f_bavail), + total_space: stat.f_frsize.saturating_mul(stat.f_blocks), + allocation_granularity: stat.f_frsize, + }), + Err(e) => Err(std::io::Error::from_raw_os_error(e.raw_os_error())), + } } diff --git a/src/unix/async_impl.rs b/src/unix/async_impl.rs index 9ad68ac4..df44a091 100644 --- a/src/unix/async_impl.rs +++ b/src/unix/async_impl.rs @@ -1,57 +1,65 @@ macro_rules! allocate { - ($file: ty) => { - #[cfg(any( - target_os = "aix", - target_os = "linux", - target_os = "freebsd", - target_os = "android", - target_os = "emscripten", - target_os = "nacl", - target_os = "macos", - target_os = "ios", - target_os = "watchos", - target_os = "tvos" - ))] - pub async fn allocate(file: &$file, len: u64) -> std::io::Result<()> { - use rustix::{ - fd::BorrowedFd, - fs::{fallocate, FallocateFlags}, - }; - unsafe { - let borrowed_fd = BorrowedFd::borrow_raw(file.as_raw_fd()); - match fallocate(borrowed_fd, FallocateFlags::empty(), 0, len) { - Ok(_) => Ok(()), - Err(e) => Err(std::io::Error::from_raw_os_error(e.raw_os_error())), - } - } + ($file: ty) => { + #[cfg(any( + target_os = "linux", + target_os = "freebsd", + target_os = "android", + target_os = "emscripten", + target_os = "nacl", + target_os = "macos", + target_os = "ios", + target_os = "watchos", + target_os = "tvos" + ))] + pub async fn allocate(file: &$file, len: u64) -> std::io::Result<()> { + use rustix::{ + fd::BorrowedFd, + fs::{fallocate, FallocateFlags}, + }; + // See the comment in the sync implementation. Short-circuit when + // the file is already large enough to avoid the macOS + // `F_PREALLOCATE` re-allocate-ENOSPC issue (#15). + if file.metadata().await?.len() >= len { + return Ok(()); + } + unsafe { + let borrowed_fd = BorrowedFd::borrow_raw(file.as_raw_fd()); + match fallocate(borrowed_fd, FallocateFlags::empty(), 0, len) { + Ok(_) => Ok(()), + Err(e) => Err(std::io::Error::from_raw_os_error(e.raw_os_error())), } + } + } - #[cfg(any( - target_os = "openbsd", - target_os = "netbsd", - target_os = "dragonfly", - target_os = "solaris", - target_os = "illumos", - target_os = "haiku", - target_os = "hurd", - ))] - pub async fn allocate(file: &$file, len: u64) -> std::io::Result<()> { - // No file allocation API available, just set the length if necessary. - if len > file.metadata().await?.len() as u64 { - file.set_len(len).await - } else { - Ok(()) - } - } - }; + #[cfg(any( + target_os = "aix", + target_os = "openbsd", + target_os = "netbsd", + target_os = "dragonfly", + target_os = "redox", + target_os = "solaris", + target_os = "illumos", + target_os = "haiku", + target_os = "hurd", + target_os = "cygwin", + ))] + pub async fn allocate(file: &$file, len: u64) -> std::io::Result<()> { + // No file allocation API available, just set the length if necessary. + if len > file.metadata().await?.len() as u64 { + file.set_len(len).await + } else { + Ok(()) + } + } + }; } macro_rules! allocate_size { - ($file: ty) => { - pub async fn allocated_size(file: &$file) -> std::io::Result { - file.metadata().await.map(|m| m.blocks() as u64 * 512) - } - }; + ($file: ty) => { + pub async fn allocated_size(file: &$file) -> std::io::Result { + file.metadata().await.map(|m| m.blocks() * 512) + } + }; } macro_rules! test_mod { @@ -60,6 +68,8 @@ macro_rules! test_mod { mod test { extern crate tempfile; + use crate::TryLockError; + $( $use_stmt )* @@ -86,16 +96,13 @@ macro_rules! test_mod { .unwrap(); // Creating a shared lock will drop an exclusive lock. - file1.lock_exclusive().unwrap(); + file1.lock().unwrap(); file1.lock_shared().unwrap(); file2.lock_shared().unwrap(); // Attempting to replace a shared lock with an exclusive lock will fail // with multiple lock holders, and remove the original shared lock. - assert_eq!( - file2.try_lock_exclusive().unwrap(), - false, - ); + assert!(matches!(file2.try_lock(), Err(TryLockError::WouldBlock))); file1.lock_shared().unwrap(); } } diff --git a/src/unix/sync_impl.rs b/src/unix/sync_impl.rs index c5f5f285..e9c72c2a 100644 --- a/src/unix/sync_impl.rs +++ b/src/unix/sync_impl.rs @@ -1,58 +1,65 @@ macro_rules! allocate_size { - ($file:ty) => { - pub fn allocated_size(file: &$file) -> std::io::Result { - file.metadata().map(|m| m.blocks() * 512) - } - }; + ($file:ty) => { + pub fn allocated_size(file: &$file) -> std::io::Result { + file.metadata().map(|m| m.blocks() * 512) + } + }; } macro_rules! allocate { - ($file:ty) => { - #[cfg(any( - target_os = "linux", - target_os = "freebsd", - target_os = "android", - target_os = "emscripten", - target_os = "nacl", - target_os = "macos", - target_os = "ios", - target_os = "watchos", - target_os = "tvos" - ))] - pub fn allocate(file: &$file, len: u64) -> std::io::Result<()> { - use rustix::{ - fd::BorrowedFd, - fs::{fallocate, FallocateFlags}, - }; - unsafe { - let borrowed_fd = BorrowedFd::borrow_raw(file.as_raw_fd()); - match fallocate(borrowed_fd, FallocateFlags::empty(), 0, len) { - Ok(_) => Ok(()), - Err(e) => Err(std::io::Error::from_raw_os_error(e.raw_os_error())), - } - } + ($file:ty) => { + #[cfg(any( + target_os = "linux", + target_os = "freebsd", + target_os = "android", + target_os = "emscripten", + target_os = "nacl", + target_os = "macos", + target_os = "ios", + target_os = "watchos", + target_os = "tvos" + ))] + pub fn allocate(file: &$file, len: u64) -> std::io::Result<()> { + use rustix::{ + fd::BorrowedFd, + fs::{fallocate, FallocateFlags}, + }; + // See the comment in file_ext/sync_impl.rs. Short-circuit when the + // file is already large enough to avoid the macOS + // `F_PREALLOCATE` re-allocate-ENOSPC issue (#15). + if file.metadata()?.len() >= len { + return Ok(()); + } + unsafe { + let borrowed_fd = BorrowedFd::borrow_raw(file.as_raw_fd()); + match fallocate(borrowed_fd, FallocateFlags::empty(), 0, len) { + Ok(_) => Ok(()), + Err(e) => Err(std::io::Error::from_raw_os_error(e.raw_os_error())), } + } + } - #[cfg(any( - target_os = "aix", - target_os = "openbsd", - target_os = "netbsd", - target_os = "dragonfly", - target_os = "redox", - target_os = "solaris", - target_os = "illumos", - target_os = "haiku", - target_os = "hurd", - ))] - pub fn allocate(file: &$file, len: u64) -> std::io::Result<()> { - // No file allocation API available, just set the length if necessary. - if len > file.metadata()?.len() as u64 { - file.set_len(len) - } else { - Ok(()) - } - } - }; + #[cfg(any( + target_os = "aix", + target_os = "openbsd", + target_os = "netbsd", + target_os = "dragonfly", + target_os = "redox", + target_os = "solaris", + target_os = "illumos", + target_os = "haiku", + target_os = "hurd", + target_os = "cygwin", + ))] + pub fn allocate(file: &$file, len: u64) -> std::io::Result<()> { + // No file allocation API available, just set the length if necessary. + if len > file.metadata()?.len() as u64 { + file.set_len(len) + } else { + Ok(()) + } + } + }; } macro_rules! test_mod { @@ -61,6 +68,8 @@ macro_rules! test_mod { mod test { extern crate tempfile; + use crate::TryLockError; + $( $use_stmt )* @@ -85,16 +94,16 @@ macro_rules! test_mod { .unwrap(); // Creating a shared lock will drop an exclusive lock. - FileExt::lock_exclusive(&file1).unwrap(); + FileExt::lock(&file1).unwrap(); FileExt::lock_shared(&file1).unwrap(); FileExt::lock_shared(&file2).unwrap(); // Attempting to replace a shared lock with an exclusive lock will fail // with multiple lock holders, and remove the original shared lock. - assert_eq!( - FileExt::try_lock_exclusive(&file2).unwrap(), - false, - ); + assert!(matches!( + FileExt::try_lock(&file2), + Err(TryLockError::WouldBlock), + )); FileExt::lock_shared(&file1).unwrap(); } } diff --git a/src/unix/sync_impl/std_impl.rs b/src/unix/sync_impl/std_impl.rs index 9381af0a..0959ab96 100644 --- a/src/unix/sync_impl/std_impl.rs +++ b/src/unix/sync_impl/std_impl.rs @@ -7,6 +7,6 @@ allocate!(File); allocate_size!(File); test_mod! { - use crate::fs_std::FileExt; + use crate::FileExt; use std::fs; } diff --git a/src/windows.rs b/src/windows.rs index 94232c70..45814dde 100644 --- a/src/windows.rs +++ b/src/windows.rs @@ -1,157 +1,156 @@ +// Expanded inside the `sync_impl` and `async_impl` submodules, both of +// which are feature-gated. With `--no-default-features` (nothing but +// the filesystem-stats API enabled), this macro has no caller, so +// silence the resulting unused-macro lint. +#[allow(unused_macros)] macro_rules! lock_impl { - ($file: ty) => { - pub fn lock_shared(file: &$file) -> Result<()> { - lock_file(file, 0) - } + ($file: ty) => { + pub fn lock_shared(file: &$file) -> std::io::Result<()> { + lock_file(file, 0) + } - pub fn lock_exclusive(file: &$file) -> Result<()> { - lock_file(file, LOCKFILE_EXCLUSIVE_LOCK) - } + pub fn lock(file: &$file) -> std::io::Result<()> { + lock_file(file, LOCKFILE_EXCLUSIVE_LOCK) + } - pub fn try_lock_shared(file: &$file) -> Result { - try_lock_file(file, LOCKFILE_FAIL_IMMEDIATELY) - } + pub fn try_lock_shared(file: &$file) -> std::result::Result<(), $crate::TryLockError> { + try_lock_file(file, LOCKFILE_FAIL_IMMEDIATELY) + } - pub fn try_lock_exclusive(file: &$file) -> Result { - try_lock_file(file, LOCKFILE_EXCLUSIVE_LOCK | LOCKFILE_FAIL_IMMEDIATELY) - } + pub fn try_lock(file: &$file) -> std::result::Result<(), $crate::TryLockError> { + try_lock_file(file, LOCKFILE_EXCLUSIVE_LOCK | LOCKFILE_FAIL_IMMEDIATELY) + } - pub fn unlock(file: &$file) -> Result<()> { - unsafe { - let ret = UnlockFile(file.as_raw_handle() as HANDLE, 0, 0, !0, !0); - if ret == 0 { - Err(Error::last_os_error()) - } else { - Ok(()) - } - } + pub fn unlock(file: &$file) -> std::io::Result<()> { + unsafe { + let ret = UnlockFile(file.as_raw_handle() as HANDLE, 0, 0, !0, !0); + if ret == 0 { + Err(Error::last_os_error()) + } else { + Ok(()) } + } + } - fn lock_file(file: &$file, flags: u32) -> Result<()> { - unsafe { - let mut overlapped = mem::zeroed(); - let ret = LockFileEx( - file.as_raw_handle() as HANDLE, - flags, - 0, - !0, - !0, - &mut overlapped, - ); - if ret == 0 { - Err(Error::last_os_error()) - } else { - Ok(()) - } - } + fn lock_file(file: &$file, flags: u32) -> std::io::Result<()> { + unsafe { + let mut overlapped = mem::zeroed(); + let ret = LockFileEx( + file.as_raw_handle() as HANDLE, + flags, + 0, + !0, + !0, + &mut overlapped, + ); + if ret == 0 { + Err(Error::last_os_error()) + } else { + Ok(()) } + } + } - fn try_lock_file(file: &$file, flags: u32) -> Result { - unsafe { - let mut overlapped = mem::zeroed(); - let ret = LockFileEx( - file.as_raw_handle() as HANDLE, - flags, - 0, - !0, - !0, - &mut overlapped, - ); - if ret == 0 { - let err = Error::last_os_error(); - if err.raw_os_error() - == Some(::windows_sys::Win32::Foundation::ERROR_IO_PENDING as i32) - || err.raw_os_error() - == Some(::windows_sys::Win32::Foundation::ERROR_LOCK_VIOLATION as i32) - { - return Ok(false); - } + fn try_lock_file(file: &$file, flags: u32) -> std::result::Result<(), $crate::TryLockError> { + unsafe { + let mut overlapped = mem::zeroed(); + let ret = LockFileEx( + file.as_raw_handle() as HANDLE, + flags, + 0, + !0, + !0, + &mut overlapped, + ); + if ret == 0 { + let err = Error::last_os_error(); + if err.raw_os_error() + == Some(::windows_sys::Win32::Foundation::ERROR_LOCK_VIOLATION as i32) + { + return Err($crate::TryLockError::WouldBlock); + } - Err(err) - } else { - Ok(true) - } - } + Err($crate::TryLockError::Error(err)) + } else { + Ok(()) } - }; + } + } + }; } #[cfg(any( - feature = "smol", - feature = "async-std", - feature = "tokio", - feature = "fs-err-tokio" + feature = "smol", + feature = "async-std", + feature = "tokio", + feature = "fs-err2-tokio", + feature = "fs-err3-tokio", ))] pub(crate) mod async_impl; -#[cfg(any(feature = "sync", feature = "fs-err"))] +#[cfg(any(feature = "sync", feature = "fs-err2", feature = "fs-err3"))] pub(crate) mod sync_impl; use crate::FsStats; use std::io::{Error, Result}; use std::os::windows::ffi::OsStrExt; use std::path::Path; -use windows_sys::Win32::Foundation::ERROR_LOCK_VIOLATION; use windows_sys::Win32::Storage::FileSystem::{ - GetDiskFreeSpaceExW, GetDiskFreeSpaceW, GetVolumePathNameW, + GetDiskFreeSpaceExW, GetDiskFreeSpaceW, GetVolumePathNameW, }; -pub fn lock_error() -> Error { - Error::from_raw_os_error(ERROR_LOCK_VIOLATION as i32) -} - fn volume_path(path: &Path, volume_path: &mut [u16]) -> Result<()> { - let path_utf8: Vec = path.as_os_str().encode_wide().chain(Some(0)).collect(); - unsafe { - let ret = GetVolumePathNameW( - path_utf8.as_ptr(), - volume_path.as_mut_ptr(), - volume_path.len() as u32, - ); - if ret == 0 { - Err(Error::last_os_error()) - } else { - Ok(()) - } + let path_utf8: Vec = path.as_os_str().encode_wide().chain(Some(0)).collect(); + unsafe { + let ret = GetVolumePathNameW( + path_utf8.as_ptr(), + volume_path.as_mut_ptr(), + volume_path.len() as u32, + ); + if ret == 0 { + Err(Error::last_os_error()) + } else { + Ok(()) } + } } pub fn statvfs(path: &Path) -> Result { - let root_path: &mut [u16] = &mut [0; 261]; - volume_path(path, root_path)?; - unsafe { - let mut free_space = 0; - let mut total_space = 0; - let ret = GetDiskFreeSpaceExW( - root_path.as_ptr(), - &mut free_space, - &mut total_space, - std::ptr::null_mut(), - ); - if ret == 0 { - return Err(Error::last_os_error()); - } + let root_path: &mut [u16] = &mut [0; 261]; + volume_path(path, root_path)?; + unsafe { + let mut free_space = 0; + let mut total_space = 0; + let ret = GetDiskFreeSpaceExW( + root_path.as_ptr(), + &mut free_space, + &mut total_space, + std::ptr::null_mut(), + ); + if ret == 0 { + return Err(Error::last_os_error()); + } - let mut sectors_per_cluster = 0; - let mut bytes_per_sector = 0; - let mut _number_of_free_clusters = 0; - let mut _total_number_of_clusters = 0; - let ret = GetDiskFreeSpaceW( - root_path.as_ptr(), - &mut sectors_per_cluster, - &mut bytes_per_sector, - &mut _number_of_free_clusters, - &mut _total_number_of_clusters, - ); - if ret == 0 { - Err(Error::last_os_error()) - } else { - let bytes_per_cluster = sectors_per_cluster as u64 * bytes_per_sector as u64; - Ok(FsStats { - free_space, - available_space: free_space, - total_space, - allocation_granularity: bytes_per_cluster, - }) - } + let mut sectors_per_cluster = 0; + let mut bytes_per_sector = 0; + let mut _number_of_free_clusters = 0; + let mut _total_number_of_clusters = 0; + let ret = GetDiskFreeSpaceW( + root_path.as_ptr(), + &mut sectors_per_cluster, + &mut bytes_per_sector, + &mut _number_of_free_clusters, + &mut _total_number_of_clusters, + ); + if ret == 0 { + Err(Error::last_os_error()) + } else { + let bytes_per_cluster = sectors_per_cluster as u64 * bytes_per_sector as u64; + Ok(FsStats { + free_space, + available_space: free_space, + total_space, + allocation_granularity: bytes_per_cluster, + }) } + } } diff --git a/src/windows/async_impl.rs b/src/windows/async_impl.rs index c66bd760..e3741ebc 100644 --- a/src/windows/async_impl.rs +++ b/src/windows/async_impl.rs @@ -1,51 +1,58 @@ macro_rules! allocate_size { - ($file: ty) => { - pub async fn allocated_size(file: &$file) -> Result { - unsafe { - let mut info: FILE_STANDARD_INFO = mem::zeroed(); - - let ret = GetFileInformationByHandleEx( - file.as_raw_handle() as HANDLE, - FileStandardInfo, - &mut info as *mut _ as *mut _, - mem::size_of::() as u32, - ); - - if ret == 0 { - Err(Error::last_os_error()) - } else { - Ok(info.AllocationSize as u64) - } - } + ($file: ty) => { + pub async fn allocated_size(file: &$file) -> Result { + unsafe { + let mut info: FILE_STANDARD_INFO = mem::zeroed(); + + let ret = GetFileInformationByHandleEx( + file.as_raw_handle() as HANDLE, + FileStandardInfo, + &mut info as *mut _ as *mut _, + mem::size_of::() as u32, + ); + + if ret == 0 { + Err(Error::last_os_error()) + } else { + Ok(info.AllocationSize as u64) } - }; + } + } + }; } macro_rules! allocate { - ($file: ty) => { - pub async fn allocate(file: &$file, len: u64) -> Result<()> { - if allocated_size(file).await? < len { - unsafe { - let mut info: FILE_ALLOCATION_INFO = mem::zeroed(); - info.AllocationSize = len as i64; - let ret = SetFileInformationByHandle( - file.as_raw_handle() as HANDLE, - FileAllocationInfo, - &mut info as *mut _ as *mut _, - mem::size_of::() as u32, - ); - if ret == 0 { - return Err(Error::last_os_error()); - } - } - } - if file.metadata().await?.len() < len { - file.set_len(len).await - } else { - Ok(()) - } + ($file: ty) => { + pub async fn allocate(file: &$file, len: u64) -> Result<()> { + // See the comment in windows/sync_impl.rs — if the + // existing cluster-aligned allocation already covers + // `len`, don't touch EOF. This avoids the Windows + // buffered-I/O quirks seen when `set_len` is called on a + // file whose logical EOF is less than `AllocationSize` + // (issue #13). + if allocated_size(file).await? >= len { + return Ok(()); + } + unsafe { + let mut info: FILE_ALLOCATION_INFO = mem::zeroed(); + info.AllocationSize = len as i64; + let ret = SetFileInformationByHandle( + file.as_raw_handle() as HANDLE, + FileAllocationInfo, + &mut info as *mut _ as *mut _, + mem::size_of::() as u32, + ); + if ret == 0 { + return Err(Error::last_os_error()); } - }; + } + if file.metadata().await?.len() < len { + file.set_len(len).await + } else { + Ok(()) + } + } + }; } macro_rules! test_mod { @@ -54,6 +61,8 @@ macro_rules! test_mod { mod test { extern crate tempfile; + use crate::TryLockError; + $( $use_stmt )* @@ -73,19 +82,13 @@ macro_rules! test_mod { .unwrap(); // Multiple exclusive locks fails. - file.lock_exclusive().unwrap(); - assert_eq!( - file.try_lock_exclusive().unwrap(), - false - ); + file.lock().unwrap(); + assert!(matches!(file.try_lock(), Err(TryLockError::WouldBlock))); file.unlock().unwrap(); // Shared then Exclusive locks fails. file.lock_shared().unwrap(); - assert_eq!( - file.try_lock_exclusive().unwrap(), - false - ); + assert!(matches!(file.try_lock(), Err(TryLockError::WouldBlock))); } /// A file handle can hold an exclusive lock and any number of shared locks, all of which must @@ -103,34 +106,31 @@ macro_rules! test_mod { .unwrap(); // Open two shared locks on the file, and then try and fail to open an exclusive lock. - file.lock_exclusive().unwrap(); + file.lock().unwrap(); file.lock_shared().unwrap(); file.lock_shared().unwrap(); - assert_eq!( - file.try_lock_exclusive().unwrap(), - false, + assert!( + matches!(file.try_lock(), Err(TryLockError::WouldBlock)), "the first try lock exclusive", ); // Pop one of the shared locks and try again. file.unlock().unwrap(); - assert_eq!( - file.try_lock_exclusive().unwrap(), - false, - "pop the first shared lock", + assert!( + matches!(file.try_lock(), Err(TryLockError::WouldBlock)), + "pop the first shared lock", ); // Pop the second shared lock and try again. file.unlock().unwrap(); - assert_eq!( - file.try_lock_exclusive().unwrap(), - false, - "pop the second shared lock", + assert!( + matches!(file.try_lock(), Err(TryLockError::WouldBlock)), + "pop the second shared lock", ); // Pop the exclusive lock and finally succeed. file.unlock().unwrap(); - file.lock_exclusive().unwrap(); + file.lock().unwrap(); } /// A file handle with multiple open locks will have all locks closed on drop. @@ -155,13 +155,10 @@ macro_rules! test_mod { // Open two shared locks on the file, and then try and fail to open an exclusive lock. file1.lock_shared().unwrap(); - assert_eq!( - file2.try_lock_exclusive().unwrap(), - false - ); + assert!(matches!(file2.try_lock(), Err(TryLockError::WouldBlock))); drop(file1); - file2.lock_exclusive().unwrap(); + file2.lock().unwrap(); } } }; diff --git a/src/windows/sync_impl.rs b/src/windows/sync_impl.rs index a66c864d..6f794a0d 100644 --- a/src/windows/sync_impl.rs +++ b/src/windows/sync_impl.rs @@ -1,51 +1,60 @@ macro_rules! allocate_size { - ($file:ty) => { - pub fn allocated_size(file: &$file) -> Result { - unsafe { - let mut info: FILE_STANDARD_INFO = mem::zeroed(); - - let ret = GetFileInformationByHandleEx( - file.as_raw_handle() as HANDLE, - FileStandardInfo, - &mut info as *mut _ as *mut _, - mem::size_of::() as u32, - ); - - if ret == 0 { - Err(Error::last_os_error()) - } else { - Ok(info.AllocationSize as u64) - } - } + ($file:ty) => { + pub fn allocated_size(file: &$file) -> Result { + unsafe { + let mut info: FILE_STANDARD_INFO = mem::zeroed(); + + let ret = GetFileInformationByHandleEx( + file.as_raw_handle() as HANDLE, + FileStandardInfo, + &mut info as *mut _ as *mut _, + mem::size_of::() as u32, + ); + + if ret == 0 { + Err(Error::last_os_error()) + } else { + Ok(info.AllocationSize as u64) } - }; + } + } + }; } macro_rules! allocate { - ($file:ty) => { - pub fn allocate(file: &$file, len: u64) -> Result<()> { - if allocated_size(file)? < len { - unsafe { - let mut info: FILE_ALLOCATION_INFO = mem::zeroed(); - info.AllocationSize = len as i64; - let ret = SetFileInformationByHandle( - file.as_raw_handle() as HANDLE, - FileAllocationInfo, - &mut info as *mut _ as *mut _, - mem::size_of::() as u32, - ); - if ret == 0 { - return Err(Error::last_os_error()); - } - } - } - if file.metadata()?.len() < len { - file.set_len(len) - } else { - Ok(()) - } + ($file:ty) => { + pub fn allocate(file: &$file, len: u64) -> Result<()> { + // If the file already has `len` bytes of cluster-aligned + // allocation, do nothing. Calling `set_len` in this branch + // (to extend the EOF pointer to `len` when it lags behind + // the `AllocationSize`) has been observed to trigger + // Windows quirks on the subsequent buffered I/O path — see + // issue #13. Skipping it is safe: the physical disk space + // the caller asked for is already reserved, and + // subsequent writes will extend EOF naturally. + if allocated_size(file)? >= len { + return Ok(()); + } + unsafe { + let mut info: FILE_ALLOCATION_INFO = mem::zeroed(); + info.AllocationSize = len as i64; + let ret = SetFileInformationByHandle( + file.as_raw_handle() as HANDLE, + FileAllocationInfo, + &mut info as *mut _ as *mut _, + mem::size_of::() as u32, + ); + if ret == 0 { + return Err(Error::last_os_error()); } - }; + } + if file.metadata()?.len() < len { + file.set_len(len) + } else { + Ok(()) + } + } + }; } macro_rules! test_mod { @@ -54,6 +63,8 @@ macro_rules! test_mod { mod test { extern crate tempfile; + use crate::TryLockError; + $( $use_stmt )* @@ -72,19 +83,19 @@ macro_rules! test_mod { .unwrap(); // Multiple exclusive locks fails. - FileExt::lock_exclusive(&file).unwrap(); - assert_eq!( - FileExt::try_lock_exclusive(&file).unwrap(), - false - ); + FileExt::lock(&file).unwrap(); + assert!(matches!( + FileExt::try_lock(&file), + Err(TryLockError::WouldBlock), + )); FileExt::unlock(&file).unwrap(); // Shared then Exclusive locks fails. FileExt::lock_shared(&file).unwrap(); - assert_eq!( - FileExt::try_lock_exclusive(&file).unwrap(), - false - ); + assert!(matches!( + FileExt::try_lock(&file), + Err(TryLockError::WouldBlock), + )); } /// A file handle can hold an exclusive lock and any number of shared locks, all of which must @@ -101,34 +112,31 @@ macro_rules! test_mod { .unwrap(); // Open two shared locks on the file, and then try and fail to open an exclusive lock. - FileExt::lock_exclusive(&file).unwrap(); + FileExt::lock(&file).unwrap(); FileExt::lock_shared(&file).unwrap(); FileExt::lock_shared(&file).unwrap(); - assert_eq!( - FileExt::try_lock_exclusive(&file).unwrap(), - false, + assert!( + matches!(FileExt::try_lock(&file), Err(TryLockError::WouldBlock)), "the first try lock exclusive", ); // Pop one of the shared locks and try again. FileExt::unlock(&file).unwrap(); - assert_eq!( - FileExt::try_lock_exclusive(&file).unwrap(), - false, + assert!( + matches!(FileExt::try_lock(&file), Err(TryLockError::WouldBlock)), "pop the first shared lock", ); // Pop the second shared lock and try again. FileExt::unlock(&file).unwrap(); - assert_eq!( - FileExt::try_lock_exclusive(&file).unwrap(), - false, + assert!( + matches!(FileExt::try_lock(&file), Err(TryLockError::WouldBlock)), "pop the second shared lock", ); // Pop the exclusive lock and finally succeed. FileExt::unlock(&file).unwrap(); - FileExt::lock_exclusive(&file).unwrap(); + FileExt::lock(&file).unwrap(); } /// A file handle with multiple open locks will have all locks closed on drop. @@ -151,13 +159,13 @@ macro_rules! test_mod { // Open two shared locks on the file, and then try and fail to open an exclusive lock. FileExt::lock_shared(&file1).unwrap(); - assert_eq!( - FileExt::try_lock_exclusive(&file2).unwrap(), - false, - ); + assert!(matches!( + FileExt::try_lock(&file2), + Err(TryLockError::WouldBlock), + )); drop(file1); - FileExt::lock_exclusive(&file2).unwrap(); + FileExt::lock(&file2).unwrap(); } } }; diff --git a/src/windows/sync_impl/std_impl.rs b/src/windows/sync_impl/std_impl.rs index e65814c3..6b151c0b 100644 --- a/src/windows/sync_impl/std_impl.rs +++ b/src/windows/sync_impl/std_impl.rs @@ -16,6 +16,6 @@ allocate!(File); allocate_size!(File); test_mod! { - use crate::fs_std::FileExt; + use crate::FileExt; use std::fs; } diff --git a/tea.yaml b/tea.yaml deleted file mode 100644 index 927f1067..00000000 --- a/tea.yaml +++ /dev/null @@ -1,6 +0,0 @@ -# https://tea.xyz/what-is-this-file ---- -version: 1.0.0 -codeOwners: - - '0x7cc40A714f3b4572D8Ce05c5325aF8e5B6baB3ae' -quorum: 1