fs4-0.7.0/.github/workflows/ci.yml000064400000000000000000000065241046102023000150460ustar 00000000000000name: CI on: push: # Ignore bors branches, since they are covered by `clippy_bors.yml` branches: - master # Don't run Clippy tests, when only textfiles were modified paths-ignore: - 'README' - 'COPYRIGHT' - 'LICENSE-*' - '**.md' - '**.txt' pull_request: # Don't run Clippy tests, when only textfiles were modified paths-ignore: - 'README' - 'COPYRIGHT' - 'LICENSE-*' - '**.md' - '**.txt' env: CARGO_TERM_COLOR: always RUSTFLAGS: -Dwarnings RUST_BACKTRACE: 1 nightly: nightly jobs: # Check formatting rustfmt: name: rustfmt runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Install Rust run: rustup update stable && rustup default stable - name: Check formatting run: cargo fmt --all -- --check # Apply clippy lints clippy: name: clippy runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Apply clippy lints run: cargo clippy --all-features unit-tests: name: unit tests runs-on: ${{ matrix.os }} strategy: matrix: rust: - nightly os: - macos-latest - windows-latest - ubuntu-latest steps: - uses: actions/checkout@v2 - 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@v2 with: path: | ~/.cargo/registry ~/.cargo/git target key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }} - name: test all features run: cargo test --all-features coverage: name: cargo tarpaulin runs-on: ubuntu-latest needs: - docs - unit-tests - clippy - rustfmt steps: - uses: actions/checkout@v3 - 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@v3 with: path: ~/.cargo key: ${{ runner.os }}-coverage-dotcargo - name: Cache cargo build uses: actions/cache@v3 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@v3.1.1 with: token: ${{ secrets.CODECOV_TOKEN }} fail_ci_if_error: true docs: name: docs runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - uses: actions-rs/toolchain@v1 with: toolchain: ${{ env.nightly }} override: true - uses: Swatinem/rust-cache@v1 - name: "doc --lib --all-features" run: cargo doc --lib --no-deps --all-features --document-private-items env: RUSTFLAGS: --cfg docsrs RUSTDOCFLAGS: --cfg docsrs -Dwarnings fs4-0.7.0/.gitignore000064400000000000000000000000301046102023000123050ustar 00000000000000target Cargo.lock .idea fs4-0.7.0/Cargo.toml0000644000000040700000000000100075330ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" name = "fs4" version = "0.7.0" authors = [ "Dan Burkert ", "Al Liu ", ] description = "No libc, pure Rust cross-platform file locks. Original fs2, now supports async and replace libc by rustix." documentation = "https://docs.rs/fs4" readme = "README.md" keywords = [ "file", "fs2", "lock", "duplicate", "flock", ] categories = [ "filesystem", "external-ffi-bindings", "asynchronous", ] license = "MIT/Apache-2.0" repository = "https://github.com/al8n/fs4-rs" [package.metadata.docs.rs] all-features = true rustdoc-args = [ "--cfg", "docsrs", ] [dependencies.async-std] version = "1.12" optional = true [dependencies.async-trait] version = "0.1" optional = true [dependencies.smol] version = "1.3" optional = true [dependencies.tokio] version = "1.32" features = ["fs"] optional = true default-features = false [dev-dependencies.async-std] version = "1.12" features = ["attributes"] [dev-dependencies.libc] version = "0.2" [dev-dependencies.smol-potat] version = "1.1" [dev-dependencies.tempdir] version = "0.3" [dev-dependencies.tokio] version = "1.19" features = ["full"] [features] async-std = [ "dep:async-std", "async-trait", ] default = ["sync"] smol = [ "dep:smol", "async-trait", ] sync = [] tokio = [ "dep:tokio", "async-trait", ] [target."cfg(not(windows))".dependencies.rustix] version = "0.38" features = ["fs"] [target."cfg(windows)".dependencies.windows-sys] version = "0.48.0" features = [ "Win32_Foundation", "Win32_Storage_FileSystem", "Win32_System_IO", ] fs4-0.7.0/Cargo.toml.orig000064400000000000000000000027061046102023000132200ustar 00000000000000[package] name = "fs4" # NB: When modifying, also modify html_root_url in lib.rs version = "0.7.0" authors = ["Dan Burkert ", "Al Liu "] license = "MIT/Apache-2.0" repository = "https://github.com/al8n/fs4-rs" documentation = "https://docs.rs/fs4" description = "No libc, pure Rust cross-platform file locks. Original fs2, now supports async and replace libc by rustix." keywords = ["file", "fs2", "lock", "duplicate", "flock"] categories = ["filesystem", "external-ffi-bindings", "asynchronous"] edition = "2021" [features] default = ["sync"] sync = [] async-std = ["dep:async-std", "async-trait"] tokio = ["dep:tokio", "async-trait"] smol = ["dep:smol", "async-trait"] [target.'cfg(not(windows))'.dependencies] rustix = { version = "0.38", features = ["fs"] } [target.'cfg(windows)'.dependencies.windows-sys] version = "0.48.0" features = [ "Win32_Foundation", "Win32_Storage_FileSystem", "Win32_System_IO" ] [dependencies] async-trait = { version = "0.1", optional = true } async-std = { version = "1.12", optional = true } smol = { version = "1.3", optional = true } tokio = { version = "1.32", optional = true, default-features = false, features = ["fs"] } [dev-dependencies] async-std = { version = "1.12", features = ["attributes"] } smol-potat = "1.1" tempdir = "0.3" tokio = { version = "1.19", features = ["full"]} libc = "0.2" [package.metadata.docs.rs] all-features = true rustdoc-args = ["--cfg", "docsrs"] fs4-0.7.0/LICENSE-APACHE000064400000000000000000000251371046102023000122600ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. fs4-0.7.0/LICENSE-MIT000064400000000000000000000020571046102023000117640ustar 00000000000000Copyright (c) 2015 The Rust Project Developers Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. fs4-0.7.0/README.md000064400000000000000000000176401046102023000116130ustar 00000000000000

fs4

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`. [github][Github-url] [Build][CI-url] [codecov][codecov-url] [docs.rs][doc-url] [crates.io][crates-url] [crates.io][crates-url] license
## Installation - std ```toml [dependencies] fs4 = { version = "0.7", features = ["sync"] } ``` - [tokio runtime](https://crates.io/crates/tokio) ```toml [dependencies] fs4 = { version = "0.7", features = ["tokio"] } ``` - [async-std runtime](https://crates.io/crates/async-std) ```toml [dependencies] fs4 = { version = "0.7", features = ["async-std"] } ``` - [smol runtime](https://crates.io/crates/smol) ```toml [dependencies] fs4 = { version = "0.7", features = ["smol"] } ``` ## Features - [x] file locks. - [x] file (pre)allocation. - [x] file allocation information. - [x] filesystem space usage information. - [x] [tokio support](https://crates.io/crates/tokio) - [x] [smol support](https://crates.io/crates/smol) - [x] [async-std support](https://crates.io/crates/async-std) ## License `fs4` is primarily distributed under the terms of both the MIT license and the Apache License (Version 2.0). See [LICENSE-APACHE](LICENSE-APACHE), [LICENSE-MIT](LICENSE-MIT) for details. Copyright (c) 2021 Al Liu. Copyright (c) 2015 Dan Burkert. [Github-url]: https://github.com/al8n/fs4-rs/ [CI-url]: https://github.com/al8n/fs4-rs/actions/workflows/ci.yml [doc-url]: https://docs.rs/fs4 [crates-url]: https://crates.io/crates/fs4 [codecov-url]: https://app.codecov.io/gh/al8n/fs4-rs/ fs4-0.7.0/src/file_ext/async_impl/async_std_impl.rs000064400000000000000000000114561046102023000204350ustar 00000000000000use async_std::fs::File; #[cfg(unix)] use crate::unix::async_impl::async_std_impl as sys; #[cfg(windows)] use crate::windows::async_impl::async_std_impl as sys; async_file_ext!(File, "async_std::fs::File"); #[cfg(test)] mod test { extern crate tempdir; extern crate test; use async_std::fs; use crate::{allocation_granularity, available_space, async_std::AsyncFileExt, free_space, lock_contended_error, total_space}; /// Tests shared file lock operations. #[async_std::test] async fn lock_shared() { let tempdir = tempdir::TempDir::new("fs4").unwrap(); let path = tempdir.path().join("fs4"); let file1 = fs::OpenOptions::new().read(true).write(true).create(true).open(&path).await.unwrap(); let file2 = fs::OpenOptions::new().read(true).write(true).create(true).open(&path).await.unwrap(); let file3 = fs::OpenOptions::new().read(true).write(true).create(true).open(&path).await.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_err().kind(), lock_contended_error().kind()); file1.unlock().unwrap(); assert_eq!(file3.try_lock_exclusive().unwrap_err().kind(), lock_contended_error().kind()); // Once all shared file locks are dropped, an exclusive lock may be created; file2.unlock().unwrap(); file3.lock_exclusive().unwrap(); } /// Tests exclusive file lock operations. #[async_std::test] async fn lock_exclusive() { let tempdir = tempdir::TempDir::new("fs4").unwrap(); let path = tempdir.path().join("fs4"); let file1 = fs::OpenOptions::new().read(true).write(true).create(true).open(&path).await.unwrap(); let file2 = fs::OpenOptions::new().read(true).write(true).create(true).open(&path).await.unwrap(); // No other access is possible once an exclusive lock is created. file1.lock_exclusive().unwrap(); assert_eq!(file2.try_lock_exclusive().unwrap_err().kind(), lock_contended_error().kind()); assert_eq!(file2.try_lock_shared().unwrap_err().kind(), lock_contended_error().kind()); // Once the exclusive lock is dropped, the second file is able to create a lock. file1.unlock().unwrap(); file2.lock_exclusive().unwrap(); } /// Tests that a lock is released after the file that owns it is dropped. #[async_std::test] async fn lock_cleanup() { let tempdir = tempdir::TempDir::new("fs4").unwrap(); let path = tempdir.path().join("fs4"); let file1 = fs::OpenOptions::new().read(true).write(true).create(true).open(&path).await.unwrap(); let file2 = fs::OpenOptions::new().read(true).write(true).create(true).open(&path).await.unwrap(); file1.lock_exclusive().unwrap(); assert_eq!(file2.try_lock_shared().unwrap_err().kind(), lock_contended_error().kind()); // Drop file1; the lock should be released. drop(file1); file2.lock_shared().unwrap(); } /// Tests file allocation. #[async_std::test] async fn allocate() { let tempdir = tempdir::TempDir::new("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(); // New files are created with no allocated size. assert_eq!(0, file.allocated_size().await.unwrap()); assert_eq!(0, file.metadata().await.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).await.unwrap(); assert_eq!(2 * blksize, file.allocated_size().await.unwrap()); assert_eq!(2 * blksize - 1, file.metadata().await.unwrap().len()); // Truncate the file, checking that the allocated size steps down by // block size. file.set_len(blksize + 1).await.unwrap(); assert_eq!(2 * blksize, file.allocated_size().await.unwrap()); assert_eq!(blksize + 1, file.metadata().await.unwrap().len()); } /// Checks filesystem space methods. #[async_std::test] async fn filesystem_space() { let tempdir = tempdir::TempDir::new("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); } }fs4-0.7.0/src/file_ext/async_impl/smol_impl.rs000064400000000000000000000114241046102023000174130ustar 00000000000000use smol::fs::File; #[cfg(unix)] use crate::unix::async_impl::smol_impl as sys; #[cfg(windows)] use crate::windows::async_impl::smol_impl as sys; async_file_ext!(File, "smol::fs::File"); #[cfg(test)] mod test { extern crate tempdir; extern crate test; use smol::fs; use crate::{allocation_granularity, available_space, smol::AsyncFileExt, free_space, lock_contended_error, total_space}; /// Tests shared file lock operations. #[smol_potat::test] async fn lock_shared() { let tempdir = tempdir::TempDir::new("fs4").unwrap(); let path = tempdir.path().join("fs4"); let file1 = fs::OpenOptions::new().read(true).write(true).create(true).open(&path).await.unwrap(); let file2 = fs::OpenOptions::new().read(true).write(true).create(true).open(&path).await.unwrap(); let file3 = fs::OpenOptions::new().read(true).write(true).create(true).open(&path).await.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_err().kind(), lock_contended_error().kind()); file1.unlock().unwrap(); assert_eq!(file3.try_lock_exclusive().unwrap_err().kind(), lock_contended_error().kind()); // Once all shared file locks are dropped, an exclusive lock may be created; file2.unlock().unwrap(); file3.lock_exclusive().unwrap(); } /// Tests exclusive file lock operations. #[smol_potat::test] async fn lock_exclusive() { let tempdir = tempdir::TempDir::new("fs4").unwrap(); let path = tempdir.path().join("fs4"); let file1 = fs::OpenOptions::new().read(true).write(true).create(true).open(&path).await.unwrap(); let file2 = fs::OpenOptions::new().read(true).write(true).create(true).open(&path).await.unwrap(); // No other access is possible once an exclusive lock is created. file1.lock_exclusive().unwrap(); assert_eq!(file2.try_lock_exclusive().unwrap_err().kind(), lock_contended_error().kind()); assert_eq!(file2.try_lock_shared().unwrap_err().kind(), lock_contended_error().kind()); // Once the exclusive lock is dropped, the second file is able to create a lock. file1.unlock().unwrap(); file2.lock_exclusive().unwrap(); } /// Tests that a lock is released after the file that owns it is dropped. #[smol_potat::test] async fn lock_cleanup() { let tempdir = tempdir::TempDir::new("fs4").unwrap(); let path = tempdir.path().join("fs4"); let file1 = fs::OpenOptions::new().read(true).write(true).create(true).open(&path).await.unwrap(); let file2 = fs::OpenOptions::new().read(true).write(true).create(true).open(&path).await.unwrap(); file1.lock_exclusive().unwrap(); assert_eq!(file2.try_lock_shared().unwrap_err().kind(), lock_contended_error().kind()); // Drop file1; the lock should be released. drop(file1); file2.lock_shared().unwrap(); } /// Tests file allocation. #[smol_potat::test] async fn allocate() { let tempdir = tempdir::TempDir::new("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(); // New files are created with no allocated size. assert_eq!(0, file.allocated_size().await.unwrap()); assert_eq!(0, file.metadata().await.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).await.unwrap(); assert_eq!(2 * blksize, file.allocated_size().await.unwrap()); assert_eq!(2 * blksize - 1, file.metadata().await.unwrap().len()); // Truncate the file, checking that the allocated size steps down by // block size. file.set_len(blksize + 1).await.unwrap(); assert_eq!(2 * blksize, file.allocated_size().await.unwrap()); assert_eq!(blksize + 1, file.metadata().await.unwrap().len()); } /// Checks filesystem space methods. #[smol_potat::test] async fn filesystem_space() { let tempdir = tempdir::TempDir::new("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); } }fs4-0.7.0/src/file_ext/async_impl/tokio_impl.rs000064400000000000000000000114021046102023000175620ustar 00000000000000use tokio::fs::File; #[cfg(unix)] use crate::unix::async_impl::tokio_impl as sys; #[cfg(windows)] use crate::windows::async_impl::tokio_impl as sys; async_file_ext!(File, "tokio::fs::File"); #[cfg(test)] mod test { extern crate tempdir; extern crate test; use tokio::fs; use crate::{allocation_granularity, available_space, tokio::AsyncFileExt, free_space, lock_contended_error, total_space}; /// Tests shared file lock operations. #[tokio::test] async fn lock_shared() { let tempdir = tempdir::TempDir::new("fs4").unwrap(); let path = tempdir.path().join("fs4"); let file1 = fs::OpenOptions::new().read(true).write(true).create(true).open(&path).await.unwrap(); let file2 = fs::OpenOptions::new().read(true).write(true).create(true).open(&path).await.unwrap(); let file3 = fs::OpenOptions::new().read(true).write(true).create(true).open(&path).await.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_err().kind(), lock_contended_error().kind()); file1.unlock().unwrap(); assert_eq!(file3.try_lock_exclusive().unwrap_err().kind(), lock_contended_error().kind()); // Once all shared file locks are dropped, an exclusive lock may be created; file2.unlock().unwrap(); file3.lock_exclusive().unwrap(); } /// Tests exclusive file lock operations. #[tokio::test] async fn lock_exclusive() { let tempdir = tempdir::TempDir::new("fs4").unwrap(); let path = tempdir.path().join("fs4"); let file1 = fs::OpenOptions::new().read(true).write(true).create(true).open(&path).await.unwrap(); let file2 = fs::OpenOptions::new().read(true).write(true).create(true).open(&path).await.unwrap(); // No other access is possible once an exclusive lock is created. file1.lock_exclusive().unwrap(); assert_eq!(file2.try_lock_exclusive().unwrap_err().kind(), lock_contended_error().kind()); assert_eq!(file2.try_lock_shared().unwrap_err().kind(), lock_contended_error().kind()); // Once the exclusive lock is dropped, the second file is able to create a lock. file1.unlock().unwrap(); file2.lock_exclusive().unwrap(); } /// Tests that a lock is released after the file that owns it is dropped. #[tokio::test] async fn lock_cleanup() { let tempdir = tempdir::TempDir::new("fs4").unwrap(); let path = tempdir.path().join("fs4"); let file1 = fs::OpenOptions::new().read(true).write(true).create(true).open(&path).await.unwrap(); let file2 = fs::OpenOptions::new().read(true).write(true).create(true).open(&path).await.unwrap(); file1.lock_exclusive().unwrap(); assert_eq!(file2.try_lock_shared().unwrap_err().kind(), lock_contended_error().kind()); // Drop file1; the lock should be released. drop(file1); file2.lock_shared().unwrap(); } /// Tests file allocation. #[tokio::test] async fn allocate() { let tempdir = tempdir::TempDir::new("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(); // New files are created with no allocated size. assert_eq!(0, file.allocated_size().await.unwrap()); assert_eq!(0, file.metadata().await.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).await.unwrap(); assert_eq!(2 * blksize, file.allocated_size().await.unwrap()); assert_eq!(2 * blksize - 1, file.metadata().await.unwrap().len()); // Truncate the file, checking that the allocated size steps down by // block size. file.set_len(blksize + 1).await.unwrap(); assert_eq!(2 * blksize, file.allocated_size().await.unwrap()); assert_eq!(blksize + 1, file.metadata().await.unwrap().len()); } /// Checks filesystem space methods. #[tokio::test] async fn filesystem_space() { let tempdir = tempdir::TempDir::new("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); } }fs4-0.7.0/src/file_ext/async_impl.rs000064400000000000000000000077061046102023000154300ustar 00000000000000macro_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.")] /// /// ## 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. /// /// 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 /// [`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. #[async_trait::async_trait] pub trait AsyncFileExt { /// Returns the amount of physical space allocated for a file. async 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. async fn allocate(&self, len: u64) -> Result<()>; /// Locks the file for shared usage, blocking if the file is currently /// locked exclusively. 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, or returns a an error if the file is /// currently locked (see `lock_contended_error`). fn try_lock_shared(&self) -> Result<()>; /// Locks the file for shared usage, or returns a an error if the file is /// currently locked (see `lock_contended_error`). fn try_lock_exclusive(&self) -> Result<()>; /// Unlocks the file. fn unlock(&self) -> Result<()>; } #[async_trait::async_trait] impl AsyncFileExt for $file { async fn allocated_size(&self) -> Result { sys::allocated_size(self).await } async fn allocate(&self, len: u64) -> Result<()> { sys::allocate(self, len).await } fn lock_shared(&self) -> Result<()> { sys::lock_shared(self) } fn lock_exclusive(&self) -> Result<()> { sys::lock_exclusive(self) } fn try_lock_shared(&self) -> Result<()> { sys::try_lock_shared(self) } fn try_lock_exclusive(&self) -> Result<()> { sys::try_lock_exclusive(self) } fn unlock(&self) -> Result<()> { sys::unlock(self) } } } } cfg_async_std! { pub(crate) mod async_std_impl; } cfg_smol! { pub(crate) mod smol_impl; } cfg_tokio! { pub(crate) mod tokio_impl; } fs4-0.7.0/src/file_ext/sync_impl.rs000064400000000000000000000261341046102023000152630ustar 00000000000000use std::fs::File; use std::io::Result; #[cfg(unix)] use crate::unix::sync_impl as sys; #[cfg(windows)] use crate::windows::sync_impl as sys; /// Extension trait for `std::fs::File` which provides allocation, duplication 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. /// /// 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 /// [`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. 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. fn allocate(&self, len: u64) -> Result<()>; /// Locks the file for shared usage, blocking if the file is currently /// locked exclusively. 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, or returns a an error if the file is /// currently locked (see `lock_contended_error`). fn try_lock_shared(&self) -> Result<()>; /// Locks the file for shared usage, or returns a an error if the file is /// currently locked (see `lock_contended_error`). fn try_lock_exclusive(&self) -> Result<()>; /// Unlocks the file. fn unlock(&self) -> Result<()>; } impl FileExt for File { fn allocated_size(&self) -> Result { sys::allocated_size(self) } fn allocate(&self, len: u64) -> Result<()> { sys::allocate(self, len) } fn lock_shared(&self) -> Result<()> { sys::lock_shared(self) } fn lock_exclusive(&self) -> Result<()> { sys::lock_exclusive(self) } fn try_lock_shared(&self) -> Result<()> { sys::try_lock_shared(self) } fn try_lock_exclusive(&self) -> Result<()> { sys::try_lock_exclusive(self) } fn unlock(&self) -> Result<()> { sys::unlock(self) } } #[cfg(test)] mod test { extern crate tempdir; extern crate test; use std::fs; use super::*; use crate::{allocation_granularity, available_space, free_space, lock_contended_error, total_space}; /// Tests shared file lock operations. #[test] fn lock_shared() { let tempdir = tempdir::TempDir::new("fs4").unwrap(); let path = tempdir.path().join("fs4"); let file1 = fs::OpenOptions::new().read(true).write(true).create(true).open(&path).unwrap(); let file2 = fs::OpenOptions::new().read(true).write(true).create(true).open(&path).unwrap(); let file3 = fs::OpenOptions::new().read(true).write(true).create(true).open(&path).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_err().kind(), lock_contended_error().kind()); file1.unlock().unwrap(); assert_eq!(file3.try_lock_exclusive().unwrap_err().kind(), lock_contended_error().kind()); // Once all shared file locks are dropped, an exclusive lock may be created; file2.unlock().unwrap(); file3.lock_exclusive().unwrap(); } /// Tests exclusive file lock operations. #[test] fn lock_exclusive() { let tempdir = tempdir::TempDir::new("fs4").unwrap(); let path = tempdir.path().join("fs4"); let file1 = fs::OpenOptions::new().read(true).write(true).create(true).open(&path).unwrap(); let file2 = fs::OpenOptions::new().read(true).write(true).create(true).open(&path).unwrap(); // No other access is possible once an exclusive lock is created. file1.lock_exclusive().unwrap(); assert_eq!(file2.try_lock_exclusive().unwrap_err().kind(), lock_contended_error().kind()); assert_eq!(file2.try_lock_shared().unwrap_err().kind(), lock_contended_error().kind()); // Once the exclusive lock is dropped, the second file is able to create a lock. file1.unlock().unwrap(); file2.lock_exclusive().unwrap(); } /// Tests that a lock is released after the file that owns it is dropped. #[test] fn lock_cleanup() { let tempdir = tempdir::TempDir::new("fs4").unwrap(); let path = tempdir.path().join("fs4"); let file1 = fs::OpenOptions::new().read(true).write(true).create(true).open(&path).unwrap(); let file2 = fs::OpenOptions::new().read(true).write(true).create(true).open(&path).unwrap(); file1.lock_exclusive().unwrap(); assert_eq!(file2.try_lock_shared().unwrap_err().kind(), lock_contended_error().kind()); // Drop file1; the lock should be released. drop(file1); file2.lock_shared().unwrap(); } /// Tests file allocation. #[test] fn allocate() { let tempdir = tempdir::TempDir::new("fs4").unwrap(); let path = tempdir.path().join("fs4"); let file = fs::OpenOptions::new().write(true).create(true).open(&path).unwrap(); let blksize = allocation_granularity(&path).unwrap(); // New files are created with no allocated size. assert_eq!(0, file.allocated_size().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()); 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!(blksize + 1, file.metadata().unwrap().len()); } /// Checks filesystem space methods. #[test] fn filesystem_space() { let tempdir = tempdir::TempDir::new("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); } /// 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 = tempdir::TempDir::new("fs4").unwrap(); let path = tempdir.path().join("file"); b.iter(|| { fs::OpenOptions::new() .read(true) .write(true) .create(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 = tempdir::TempDir::new("fs4").unwrap(); let path = tempdir.path().join("file"); b.iter(|| { let file = fs::OpenOptions::new() .read(true) .write(true) .create(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 = tempdir::TempDir::new("fs4").unwrap(); let path = tempdir.path().join("file"); b.iter(|| { let file = fs::OpenOptions::new() .read(true) .write(true) .create(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 = tempdir::TempDir::new("fs4").unwrap(); let path = tempdir.path().join("file"); let file = fs::OpenOptions::new() .read(true) .write(true) .create(true) .open(path) .unwrap(); file.allocate(size).unwrap(); b.iter(|| { file.allocated_size().unwrap(); }); } /// Benchmarks locking and unlocking a file lock. #[bench] fn bench_lock_unlock(b: &mut test::Bencher) { let tempdir = tempdir::TempDir::new("fs4").unwrap(); let path = tempdir.path().join("fs4"); let file = fs::OpenOptions::new().read(true).write(true).create(true).open(path).unwrap(); b.iter(|| { file.lock_exclusive().unwrap(); file.unlock().unwrap(); }); } /// Benchmarks the free space method. #[bench] fn bench_free_space(b: &mut test::Bencher) { let tempdir = tempdir::TempDir::new("fs4").unwrap(); b.iter(|| { test::black_box(free_space(tempdir.path()).unwrap()); }); } /// Benchmarks the available space method. #[bench] fn bench_available_space(b: &mut test::Bencher) { let tempdir = tempdir::TempDir::new("fs4").unwrap(); b.iter(|| { test::black_box(available_space(tempdir.path()).unwrap()); }); } /// Benchmarks the total space method. #[bench] fn bench_total_space(b: &mut test::Bencher) { let tempdir = tempdir::TempDir::new("fs4").unwrap(); b.iter(|| { test::black_box(total_space(tempdir.path()).unwrap()); }); } } fs4-0.7.0/src/file_ext.rs000064400000000000000000000001601046102023000132550ustar 00000000000000cfg_sync!( mod sync_impl; pub use sync_impl::FileExt; ); cfg_async!( pub(crate) mod async_impl; ); fs4-0.7.0/src/fs_stats.rs000064400000000000000000000023031046102023000133050ustar 00000000000000/// `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, } 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 } } fs4-0.7.0/src/lib.rs000064400000000000000000000065561046102023000122430ustar 00000000000000//! Extended utilities for working with files and filesystems in Rust. #![doc(html_root_url = "https://docs.rs/fs4/0.7.0")] #![cfg_attr(test, feature(test))] #![cfg_attr(docsrs, feature(doc_cfg))] #![cfg_attr(docsrs, allow(unused_attributes))] #[cfg(windows)] extern crate windows_sys; macro_rules! cfg_async_std { ($($item:item)*) => { $( #[cfg(feature = "async-std")] #[cfg_attr(docsrs, doc(cfg(feature = "async-std")))] $item )* } } macro_rules! cfg_smol { ($($item:item)*) => { $( #[cfg(feature = "smol")] #[cfg_attr(docsrs, doc(cfg(feature = "smol")))] $item )* } } macro_rules! cfg_tokio { ($($item:item)*) => { $( #[cfg(feature = "tokio")] #[cfg_attr(docsrs, doc(cfg(feature = "tokio")))] $item )* } } macro_rules! cfg_sync { ($($item:item)*) => { $( #[cfg(feature = "sync")] #[cfg_attr(docsrs, doc(cfg(feature = "sync")))] $item )* } } macro_rules! cfg_async { ($($item:item)*) => { $( #[cfg(any(feature = "smol", feature = "async-std", feature = "tokio"))] #[cfg_attr(docsrs, doc(cfg(any(feature = "smol", feature = "async-std", feature = "tokio"))))] $item )* } } #[cfg(unix)] mod unix; #[cfg(unix)] use unix as sys; #[cfg(windows)] mod windows; #[cfg(windows)] use windows as sys; mod file_ext; #[cfg(feature = "sync")] pub use file_ext::FileExt; cfg_async_std!( pub mod async_std { pub use crate::file_ext::async_impl::async_std_impl::AsyncFileExt; } ); cfg_smol!( 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; } ); mod fs_stats; pub use fs_stats::FsStats; use std::io::{Error, Result}; use std::path::Path; /// 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() } /// Get the stats of the file system containing the provided path. pub fn statvfs

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

(path: P) -> Result where P: AsRef, { 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, { statvfs(path).map(|stat| stat.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

(path: P) -> Result where P: AsRef, { statvfs(path).map(|stat| stat.allocation_granularity) } fs4-0.7.0/src/unix/async_impl/async_std_impl.rs000064400000000000000000000023741046102023000176200ustar 00000000000000use std::os::unix::fs::MetadataExt; use std::os::unix::io::AsRawFd; use async_std::fs::File; lock_impl!(File); allocate!(File); allocate_size!(File); #[cfg(test)] mod test { extern crate tempdir; use async_std::fs; use crate::{lock_contended_error, async_std::AsyncFileExt}; /// Tests that locking a file descriptor will replace any existing locks /// held on the file descriptor. #[async_std::test] async fn lock_replace() { let tempdir = tempdir::TempDir::new("fs4").unwrap(); let path = tempdir.path().join("fs4"); let file1 = fs::OpenOptions::new().write(true).create(true).open(&path).await.unwrap(); let file2 = fs::OpenOptions::new().write(true).create(true).open(&path).await.unwrap(); // Creating a shared lock will drop an exclusive lock. file1.lock_exclusive().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_err().raw_os_error(), lock_contended_error().raw_os_error()); file1.lock_shared().unwrap(); } }fs4-0.7.0/src/unix/async_impl/smol_impl.rs000064400000000000000000000023561046102023000166030ustar 00000000000000use std::os::unix::fs::MetadataExt; use std::os::unix::io::AsRawFd; use smol::fs::File; lock_impl!(File); allocate!(File); allocate_size!(File); #[cfg(test)] mod test { extern crate tempdir; use smol::fs; use crate::{lock_contended_error, smol::AsyncFileExt}; /// Tests that locking a file descriptor will replace any existing locks /// held on the file descriptor. #[smol_potat::test] async fn lock_replace() { let tempdir = tempdir::TempDir::new("fs4").unwrap(); let path = tempdir.path().join("fs4"); let file1 = fs::OpenOptions::new().write(true).create(true).open(&path).await.unwrap(); let file2 = fs::OpenOptions::new().write(true).create(true).open(&path).await.unwrap(); // Creating a shared lock will drop an exclusive lock. file1.lock_exclusive().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_err().raw_os_error(), lock_contended_error().raw_os_error()); file1.lock_shared().unwrap(); } }fs4-0.7.0/src/unix/async_impl/tokio_impl.rs000064400000000000000000000023551046102023000167550ustar 00000000000000use std::os::unix::fs::MetadataExt; use std::os::unix::io::AsRawFd; use tokio::fs::File; lock_impl!(File); allocate!(File); allocate_size!(File); #[cfg(test)] mod test { extern crate tempdir; use tokio::fs; use crate::{lock_contended_error, tokio::AsyncFileExt}; /// Tests that locking a file descriptor will replace any existing locks /// held on the file descriptor. #[tokio::test] async fn lock_replace() { let tempdir = tempdir::TempDir::new("fs4").unwrap(); let path = tempdir.path().join("fs4"); let file1 = fs::OpenOptions::new().write(true).create(true).open(&path).await.unwrap(); let file2 = fs::OpenOptions::new().write(true).create(true).open(&path).await.unwrap(); // Creating a shared lock will drop an exclusive lock. file1.lock_exclusive().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_err().raw_os_error(), lock_contended_error().raw_os_error()); file1.lock_shared().unwrap(); } }fs4-0.7.0/src/unix/async_impl.rs000064400000000000000000000035061046102023000146060ustar 00000000000000macro_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 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())), } } } #[cfg(any( target_os = "openbsd", target_os = "netbsd", target_os = "dragonfly", target_os = "solaris", target_os = "illumos", target_os = "haiku" ))] 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) } }; } cfg_async_std! { pub(crate) mod async_std_impl; } cfg_smol! { pub(crate) mod smol_impl; } cfg_tokio! { pub(crate) mod tokio_impl; } fs4-0.7.0/src/unix/sync_impl.rs000064400000000000000000000047221046102023000144460ustar 00000000000000use std::fs::File; use std::os::unix::fs::MetadataExt; use std::os::unix::io::AsRawFd; lock_impl!(File); pub fn allocated_size(file: &File) -> std::io::Result { file.metadata().map(|m| m.blocks() * 512) } #[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())), } } } #[cfg(any( target_os = "openbsd", target_os = "netbsd", target_os = "dragonfly", target_os = "solaris", target_os = "illumos", target_os = "haiku", ))] 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(test)] mod test { extern crate tempdir; use std::fs; use crate::{lock_contended_error, FileExt}; /// Tests that locking a file descriptor will replace any existing locks /// held on the file descriptor. #[test] fn lock_replace() { let tempdir = tempdir::TempDir::new("fs4").unwrap(); let path = tempdir.path().join("fs4"); let file1 = fs::OpenOptions::new() .write(true) .create(true) .open(&path) .unwrap(); let file2 = fs::OpenOptions::new() .write(true) .create(true) .open(&path) .unwrap(); // Creating a shared lock will drop an exclusive lock. file1.lock_exclusive().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_err().raw_os_error(), lock_contended_error().raw_os_error() ); file1.lock_shared().unwrap(); } } fs4-0.7.0/src/unix.rs000064400000000000000000000042401046102023000124440ustar 00000000000000macro_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) } #[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 try_lock_shared(file: &$file) -> std::io::Result<()> { flock(file, rustix::fs::FlockOperation::NonBlockingLockShared) } #[cfg(not(target_os = "wasi"))] pub fn try_lock_exclusive(file: &$file) -> std::io::Result<()> { 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"))] 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())), } } }; } #[cfg(any(feature = "smol", feature = "async-std", feature = "tokio"))] pub(crate) mod async_impl; #[cfg(feature = "sync")] pub(crate) mod sync_impl; use crate::FsStats; use std::io::{Error, 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())), } } fs4-0.7.0/src/windows/async_impl/async_std_impl.rs000064400000000000000000000070471046102023000203310ustar 00000000000000use std::io::{Error, Result}; use std::mem; use std::os::windows::io::AsRawHandle; use windows_sys::Win32::Foundation::HANDLE; use windows_sys::Win32::Storage::FileSystem::{ FileAllocationInfo, FileStandardInfo, GetFileInformationByHandleEx, SetFileInformationByHandle, UnlockFile, FILE_ALLOCATION_INFO, FILE_STANDARD_INFO, LOCKFILE_EXCLUSIVE_LOCK, LOCKFILE_FAIL_IMMEDIATELY, LockFileEx, }; use async_std::fs::File; lock_impl!(File); allocate!(File); allocate_size!(File); #[cfg(test)] mod test { extern crate tempdir; use async_std::fs; use crate::{lock_contended_error, async_std::AsyncFileExt}; /// A file handle may not be exclusively locked multiple times, or exclusively locked and then /// shared locked. #[async_std::test] async fn lock_non_reentrant() { let tempdir = tempdir::TempDir::new("fs4").unwrap(); let path = tempdir.path().join("fs4"); let file = fs::OpenOptions::new().read(true).write(true).create(true).open(&path).await.unwrap(); // Multiple exclusive locks fails. file.lock_exclusive().unwrap(); assert_eq!(file.try_lock_exclusive().unwrap_err().raw_os_error(), lock_contended_error().raw_os_error()); file.unlock().unwrap(); // Shared then Exclusive locks fails. file.lock_shared().unwrap(); assert_eq!(file.try_lock_exclusive().unwrap_err().raw_os_error(), lock_contended_error().raw_os_error()); } /// A file handle can hold an exclusive lock and any number of shared locks, all of which must /// be unlocked independently. #[async_std::test] async fn lock_layering() { let tempdir = tempdir::TempDir::new("fs4").unwrap(); let path = tempdir.path().join("fs4"); let file = fs::OpenOptions::new().read(true).write(true).create(true).open(&path).await.unwrap(); // Open two shared locks on the file, and then try and fail to open an exclusive lock. file.lock_exclusive().unwrap(); file.lock_shared().unwrap(); file.lock_shared().unwrap(); assert_eq!(file.try_lock_exclusive().unwrap_err().raw_os_error(), lock_contended_error().raw_os_error()); // Pop one of the shared locks and try again. file.unlock().unwrap(); assert_eq!(file.try_lock_exclusive().unwrap_err().raw_os_error(), lock_contended_error().raw_os_error()); // Pop the second shared lock and try again. file.unlock().unwrap(); assert_eq!(file.try_lock_exclusive().unwrap_err().raw_os_error(), lock_contended_error().raw_os_error()); // Pop the exclusive lock and finally succeed. file.unlock().unwrap(); file.lock_exclusive().unwrap(); } /// A file handle with multiple open locks will have all locks closed on drop. #[async_std::test] async fn lock_layering_cleanup() { let tempdir = tempdir::TempDir::new("fs4").unwrap(); let path = tempdir.path().join("fs4"); let file1 = fs::OpenOptions::new().read(true).write(true).create(true).open(&path).await.unwrap(); let file2 = fs::OpenOptions::new().read(true).write(true).create(true).open(&path).await.unwrap(); // 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_err().raw_os_error(), lock_contended_error().raw_os_error()); drop(file1); file2.lock_exclusive().unwrap(); } }fs4-0.7.0/src/windows/async_impl/smol_impl.rs000064400000000000000000000070311046102023000173050ustar 00000000000000use std::io::{Error, Result}; use std::mem; use std::os::windows::io::AsRawHandle; use windows_sys::Win32::Foundation::HANDLE; use windows_sys::Win32::Storage::FileSystem::{ FileAllocationInfo, FileStandardInfo, GetFileInformationByHandleEx, SetFileInformationByHandle, UnlockFile, FILE_ALLOCATION_INFO, FILE_STANDARD_INFO, LOCKFILE_EXCLUSIVE_LOCK, LOCKFILE_FAIL_IMMEDIATELY, LockFileEx }; use smol::fs::File; lock_impl!(File); allocate!(File); allocate_size!(File); #[cfg(test)] mod test { extern crate tempdir; use smol::fs; use crate::{lock_contended_error, smol::AsyncFileExt}; /// A file handle may not be exclusively locked multiple times, or exclusively locked and then /// shared locked. #[smol_potat::test] async fn lock_non_reentrant() { let tempdir = tempdir::TempDir::new("fs4").unwrap(); let path = tempdir.path().join("fs4"); let file = fs::OpenOptions::new().read(true).write(true).create(true).open(&path).await.unwrap(); // Multiple exclusive locks fails. file.lock_exclusive().unwrap(); assert_eq!(file.try_lock_exclusive().unwrap_err().raw_os_error(), lock_contended_error().raw_os_error()); file.unlock().unwrap(); // Shared then Exclusive locks fails. file.lock_shared().unwrap(); assert_eq!(file.try_lock_exclusive().unwrap_err().raw_os_error(), lock_contended_error().raw_os_error()); } /// A file handle can hold an exclusive lock and any number of shared locks, all of which must /// be unlocked independently. #[smol_potat::test] async fn lock_layering() { let tempdir = tempdir::TempDir::new("fs4").unwrap(); let path = tempdir.path().join("fs4"); let file = fs::OpenOptions::new().read(true).write(true).create(true).open(&path).await.unwrap(); // Open two shared locks on the file, and then try and fail to open an exclusive lock. file.lock_exclusive().unwrap(); file.lock_shared().unwrap(); file.lock_shared().unwrap(); assert_eq!(file.try_lock_exclusive().unwrap_err().raw_os_error(), lock_contended_error().raw_os_error()); // Pop one of the shared locks and try again. file.unlock().unwrap(); assert_eq!(file.try_lock_exclusive().unwrap_err().raw_os_error(), lock_contended_error().raw_os_error()); // Pop the second shared lock and try again. file.unlock().unwrap(); assert_eq!(file.try_lock_exclusive().unwrap_err().raw_os_error(), lock_contended_error().raw_os_error()); // Pop the exclusive lock and finally succeed. file.unlock().unwrap(); file.lock_exclusive().unwrap(); } /// A file handle with multiple open locks will have all locks closed on drop. #[smol_potat::test] async fn lock_layering_cleanup() { let tempdir = tempdir::TempDir::new("fs4").unwrap(); let path = tempdir.path().join("fs4"); let file1 = fs::OpenOptions::new().read(true).write(true).create(true).open(&path).await.unwrap(); let file2 = fs::OpenOptions::new().read(true).write(true).create(true).open(&path).await.unwrap(); // 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_err().raw_os_error(), lock_contended_error().raw_os_error()); drop(file1); file2.lock_exclusive().unwrap(); } }fs4-0.7.0/src/windows/async_impl/tokio_impl.rs000064400000000000000000000070151046102023000174620ustar 00000000000000use std::io::{Error, Result}; use std::mem; use std::os::windows::io::AsRawHandle; use windows_sys::Win32::Foundation::HANDLE; use windows_sys::Win32::Storage::FileSystem::{ FileAllocationInfo, FileStandardInfo, GetFileInformationByHandleEx, SetFileInformationByHandle, UnlockFile, FILE_ALLOCATION_INFO, FILE_STANDARD_INFO, LOCKFILE_EXCLUSIVE_LOCK, LOCKFILE_FAIL_IMMEDIATELY, LockFileEx }; use tokio::fs::File; lock_impl!(File); allocate!(File); allocate_size!(File); #[cfg(test)] mod test { extern crate tempdir; use tokio::fs; use crate::{lock_contended_error, tokio::AsyncFileExt}; /// A file handle may not be exclusively locked multiple times, or exclusively locked and then /// shared locked. #[tokio::test] async fn lock_non_reentrant() { let tempdir = tempdir::TempDir::new("fs4").unwrap(); let path = tempdir.path().join("fs4"); let file = fs::OpenOptions::new().read(true).write(true).create(true).open(&path).await.unwrap(); // Multiple exclusive locks fails. file.lock_exclusive().unwrap(); assert_eq!(file.try_lock_exclusive().unwrap_err().raw_os_error(), lock_contended_error().raw_os_error()); file.unlock().unwrap(); // Shared then Exclusive locks fails. file.lock_shared().unwrap(); assert_eq!(file.try_lock_exclusive().unwrap_err().raw_os_error(), lock_contended_error().raw_os_error()); } /// A file handle can hold an exclusive lock and any number of shared locks, all of which must /// be unlocked independently. #[tokio::test] async fn lock_layering() { let tempdir = tempdir::TempDir::new("fs4").unwrap(); let path = tempdir.path().join("fs4"); let file = fs::OpenOptions::new().read(true).write(true).create(true).open(&path).await.unwrap(); // Open two shared locks on the file, and then try and fail to open an exclusive lock. file.lock_exclusive().unwrap(); file.lock_shared().unwrap(); file.lock_shared().unwrap(); assert_eq!(file.try_lock_exclusive().unwrap_err().raw_os_error(), lock_contended_error().raw_os_error()); // Pop one of the shared locks and try again. file.unlock().unwrap(); assert_eq!(file.try_lock_exclusive().unwrap_err().raw_os_error(), lock_contended_error().raw_os_error()); // Pop the second shared lock and try again. file.unlock().unwrap(); assert_eq!(file.try_lock_exclusive().unwrap_err().raw_os_error(), lock_contended_error().raw_os_error()); // Pop the exclusive lock and finally succeed. file.unlock().unwrap(); file.lock_exclusive().unwrap(); } /// A file handle with multiple open locks will have all locks closed on drop. #[tokio::test] async fn lock_layering_cleanup() { let tempdir = tempdir::TempDir::new("fs4").unwrap(); let path = tempdir.path().join("fs4"); let file1 = fs::OpenOptions::new().read(true).write(true).create(true).open(&path).await.unwrap(); let file2 = fs::OpenOptions::new().read(true).write(true).create(true).open(&path).await.unwrap(); // 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_err().raw_os_error(), lock_contended_error().raw_os_error()); drop(file1); file2.lock_exclusive().unwrap(); } }fs4-0.7.0/src/windows/async_impl.rs000064400000000000000000000033651046102023000153200ustar 00000000000000macro_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) } } } }; } 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(()) } } }; } cfg_async_std! { pub(crate) mod async_std_impl; } cfg_smol! { pub(crate) mod smol_impl; } cfg_tokio! { pub(crate) mod tokio_impl; } fs4-0.7.0/src/windows/sync_impl.rs000064400000000000000000000116301046102023000151510ustar 00000000000000use std::fs::File; use std::io::{Error, Result}; use std::mem; use std::os::windows::io::AsRawHandle; use windows_sys::Win32::Foundation::HANDLE; use windows_sys::Win32::Storage::FileSystem::{ FileAllocationInfo, FileStandardInfo, GetFileInformationByHandleEx, LockFileEx, SetFileInformationByHandle, UnlockFile, FILE_ALLOCATION_INFO, FILE_STANDARD_INFO, LOCKFILE_EXCLUSIVE_LOCK, LOCKFILE_FAIL_IMMEDIATELY, }; lock_impl!(File); 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) } } } 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(()) } } #[cfg(test)] mod test { extern crate tempdir; use std::fs; use crate::{lock_contended_error, FileExt}; /// A file handle may not be exclusively locked multiple times, or exclusively locked and then /// shared locked. #[test] fn lock_non_reentrant() { let tempdir = tempdir::TempDir::new("fs4").unwrap(); let path = tempdir.path().join("fs4"); let file = fs::OpenOptions::new() .read(true) .write(true) .create(true) .open(&path) .unwrap(); // Multiple exclusive locks fails. file.lock_exclusive().unwrap(); assert_eq!( file.try_lock_exclusive().unwrap_err().raw_os_error(), lock_contended_error().raw_os_error() ); file.unlock().unwrap(); // Shared then Exclusive locks fails. file.lock_shared().unwrap(); assert_eq!( file.try_lock_exclusive().unwrap_err().raw_os_error(), lock_contended_error().raw_os_error() ); } /// A file handle can hold an exclusive lock and any number of shared locks, all of which must /// be unlocked independently. #[test] fn lock_layering() { let tempdir = tempdir::TempDir::new("fs4").unwrap(); let path = tempdir.path().join("fs4"); let file = fs::OpenOptions::new() .read(true) .write(true) .create(true) .open(&path) .unwrap(); // Open two shared locks on the file, and then try and fail to open an exclusive lock. file.lock_exclusive().unwrap(); file.lock_shared().unwrap(); file.lock_shared().unwrap(); assert_eq!( file.try_lock_exclusive().unwrap_err().raw_os_error(), lock_contended_error().raw_os_error() ); // Pop one of the shared locks and try again. file.unlock().unwrap(); assert_eq!( file.try_lock_exclusive().unwrap_err().raw_os_error(), lock_contended_error().raw_os_error() ); // Pop the second shared lock and try again. file.unlock().unwrap(); assert_eq!( file.try_lock_exclusive().unwrap_err().raw_os_error(), lock_contended_error().raw_os_error() ); // Pop the exclusive lock and finally succeed. file.unlock().unwrap(); file.lock_exclusive().unwrap(); } /// A file handle with multiple open locks will have all locks closed on drop. #[test] fn lock_layering_cleanup() { let tempdir = tempdir::TempDir::new("fs4").unwrap(); let path = tempdir.path().join("fs4"); let file1 = fs::OpenOptions::new() .read(true) .write(true) .create(true) .open(&path) .unwrap(); let file2 = fs::OpenOptions::new() .read(true) .write(true) .create(true) .open(&path) .unwrap(); // 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_err().raw_os_error(), lock_contended_error().raw_os_error() ); drop(file1); file2.lock_exclusive().unwrap(); } } fs4-0.7.0/src/windows.rs000064400000000000000000000066371046102023000131670ustar 00000000000000macro_rules! lock_impl { ($file: ty) => { pub fn lock_shared(file: &$file) -> Result<()> { lock_file(file, 0) } pub fn lock_exclusive(file: &$file) -> Result<()> { lock_file(file, LOCKFILE_EXCLUSIVE_LOCK) } pub fn try_lock_shared(file: &$file) -> Result<()> { lock_file(file, LOCKFILE_FAIL_IMMEDIATELY) } pub fn try_lock_exclusive(file: &$file) -> Result<()> { 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(()) } } } 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(()) } } } }; } #[cfg(any(feature = "smol", feature = "async-std", feature = "tokio"))] pub(crate) mod async_impl; #[cfg(feature = "sync")] 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::{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(()) } } } pub fn statvfs(path: &Path) -> Result { let root_path: &mut [u16] = &mut [0; 261]; volume_path(path, root_path)?; unsafe { 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; let free_space = bytes_per_cluster * number_of_free_clusters as u64; let total_space = bytes_per_cluster * total_number_of_clusters as u64; Ok(FsStats { free_space, available_space: free_space, total_space, allocation_granularity: bytes_per_cluster, }) } } }