fs2-0.4.3/.appveyor.yml010064400007660000024000000007731300274353500131070ustar0000000000000000environment: matrix: - TARGET: x86_64-pc-windows-msvc - TARGET: i686-pc-windows-msvc - TARGET: x86_64-pc-windows-gnu - TARGET: i686-pc-windows-gnu install: - ps: Start-FileDownload "https://static.rust-lang.org/dist/rust-nightly-${env:TARGET}.exe" -FileName "rust-nightly.exe" - ps: .\rust-nightly.exe /VERYSILENT /NORESTART /DIR="C:\rust" | Out-Null - ps: $env:PATH="$env:PATH;C:\rust\bin" build_script: - cargo build -v test_script: - SET RUST_BACKTRACE=1 - cargo test -v fs2-0.4.3/.gitignore010064400007660000024000000000221300274353500124140ustar0000000000000000target Cargo.lock fs2-0.4.3/.travis.yml010064400007660000024000000004011305440402300125270ustar0000000000000000language: rust rust: - 1.8.0 - stable - nightly os: - linux - osx env: matrix: - ARCH=x86_64 - ARCH=i686 script: - cargo build --verbose - if [[ $TRAVIS_RUST_VERSION = nightly* ]]; then env RUST_BACKTRACE=1 cargo test -v; fi fs2-0.4.3/Cargo.toml.orig010064400007660000024000000013451322422737000133240ustar0000000000000000[package] name = "fs2" # NB: When modifying, also modify html_root_url in lib.rs version = "0.4.3" authors = ["Dan Burkert "] license = "MIT/Apache-2.0" repository = "https://github.com/danburkert/fs2-rs" documentation = "https://docs.rs/fs2" description = "Cross-platform file locks and file duplication." keywords = ["file", "file-system", "lock", "duplicate", "flock"] [badges] travis-ci = { repository = "danburkert/fs2-rs" } appveyor = { repository = "danburkert/fs2-rs" } [target.'cfg(unix)'.dependencies] libc = "0.2.30" [target.'cfg(windows)'.dependencies] winapi = { version = "0.3", features = ["handleapi", "processthreadsapi", "winerror", "fileapi", "winbase", "std"] } [dev-dependencies] tempdir = "0.3" fs2-0.4.3/Cargo.toml0000644000000022720000000000000075720ustar00# 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 believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] name = "fs2" version = "0.4.3" authors = ["Dan Burkert "] description = "Cross-platform file locks and file duplication." documentation = "https://docs.rs/fs2" keywords = ["file", "file-system", "lock", "duplicate", "flock"] license = "MIT/Apache-2.0" repository = "https://github.com/danburkert/fs2-rs" [dev-dependencies.tempdir] version = "0.3" [target."cfg(unix)".dependencies.libc] version = "0.2.30" [target."cfg(windows)".dependencies.winapi] version = "0.3" features = ["handleapi", "processthreadsapi", "winerror", "fileapi", "winbase", "std"] [badges.appveyor] repository = "danburkert/fs2-rs" [badges.travis-ci] repository = "danburkert/fs2-rs" fs2-0.4.3/LICENSE-APACHE010064400007660000024000000251371300274353500123660ustar0000000000000000 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. fs2-0.4.3/LICENSE-MIT010064400007660000024000000020571300274353500120720ustar0000000000000000Copyright (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. fs2-0.4.3/README.md010064400007660000024000000035311322422534000117060ustar0000000000000000# fs2 Extended utilities for working with files and filesystems in Rust. `fs2` requires Rust stable 1.8 or greater. [![Build Status](https://travis-ci.org/danburkert/fs2-rs.svg?branch=master)](https://travis-ci.org/danburkert/fs2-rs) [![Windows Build status](https://ci.appveyor.com/api/projects/status/iuvjv1aaaml0rntt/branch/master?svg=true)](https://ci.appveyor.com/project/danburkert/fs2-rs/branch/master) [![Documentation](https://docs.rs/fs2/badge.svg)](https://docs.rs/memmap) [![Crate](https://img.shields.io/crates/v/fs2.svg)](https://crates.io/crates/memmap) ## Features - [x] file descriptor duplication. - [x] file locks. - [x] file (pre)allocation. - [x] file allocation information. - [x] filesystem space usage information. ## Platforms `fs2` should work on any platform supported by [`libc`](https://github.com/rust-lang-nursery/libc#platforms-and-documentation). `fs2` is continuously tested on: * `x86_64-unknown-linux-gnu` (Linux) * `i686-unknown-linux-gnu` * `x86_64-apple-darwin` (OSX) * `i686-apple-darwin` * `x86_64-pc-windows-msvc` (Windows) * `i686-pc-windows-msvc` * `x86_64-pc-windows-gnu` * `i686-pc-windows-gnu` ## Benchmarks Simple benchmarks are provided for the methods provided. Many of these benchmarks use files in a temporary directory. On many modern Linux distros the default temporary directory, `/tmp`, is mounted on a tempfs filesystem, which will have different performance characteristics than a disk-backed filesystem. The temporary directory is configurable at runtime through the environment (see [`env::temp_dir`](https://doc.rust-lang.org/stable/std/env/fn.temp_dir.html)). ## License `fs2` 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) 2015 Dan Burkert. fs2-0.4.3/src/lib.rs010064400007660000024000000400231322422736600123410ustar0000000000000000//! Extended utilities for working with files and filesystems in Rust. #![doc(html_root_url = "https://docs.rs/fs2/0.4.3")] #![cfg_attr(test, feature(test))] #[cfg(windows)] extern crate winapi; #[cfg(unix)] mod unix; #[cfg(unix)] use unix as sys; #[cfg(windows)] mod windows; #[cfg(windows)] use windows as sys; use std::fs::File; use std::io::{Error, Result}; use std::path::Path; /// 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 a duplicate instance of the file. /// /// The returned file will share the same file position as the original /// file. /// /// If using rustc version 1.9 or later, prefer using `File::try_clone` to this. /// /// # Notes /// /// This is implemented with /// [`dup(2)`](http://man7.org/linux/man-pages/man2/dup.2.html) on Unix and /// [`DuplicateHandle`](https://msdn.microsoft.com/en-us/library/windows/desktop/ms724251(v=vs.85).aspx) /// on Windows. fn duplicate(&self) -> Result; /// 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 duplicate(&self) -> Result { sys::duplicate(self) } 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) } } /// 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() } /// `FsStats` contains some common stats about a file system. #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct FsStats { free_space: u64, available_space: u64, total_space: u64, 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 } } /// 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) } #[cfg(test)] mod test { extern crate tempdir; extern crate test; use std::fs; use super::*; use std::io::{Read, Seek, SeekFrom, Write}; /// Tests file duplication. #[test] fn duplicate() { let tempdir = tempdir::TempDir::new("fs2").unwrap(); let path = tempdir.path().join("fs2"); let mut file1 = fs::OpenOptions::new().read(true).write(true).create(true).open(&path).unwrap(); let mut file2 = file1.duplicate().unwrap(); // Write into the first file and then drop it. file1.write_all(b"foo").unwrap(); drop(file1); let mut buf = vec![]; // Read from the second file; since the position is shared it will already be at EOF. file2.read_to_end(&mut buf).unwrap(); assert_eq!(0, buf.len()); // Rewind and read. file2.seek(SeekFrom::Start(0)).unwrap(); file2.read_to_end(&mut buf).unwrap(); assert_eq!(&buf, &b"foo"); } /// Tests shared file lock operations. #[test] fn lock_shared() { let tempdir = tempdir::TempDir::new("fs2").unwrap(); let path = tempdir.path().join("fs2"); 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("fs2").unwrap(); let path = tempdir.path().join("fs2"); 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("fs2").unwrap(); let path = tempdir.path().join("fs2"); 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("fs2").unwrap(); let path = tempdir.path().join("fs2"); 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("fs2").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("fs2").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("fs2").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("fs2").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("fs2").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 duplicating a file descriptor or handle. #[bench] fn bench_duplicate(b: &mut test::Bencher) { let tempdir = tempdir::TempDir::new("fs2").unwrap(); let path = tempdir.path().join("fs2"); let file = fs::OpenOptions::new().read(true).write(true).create(true).open(&path).unwrap(); b.iter(|| test::black_box(file.duplicate().unwrap())); } /// Benchmarks locking and unlocking a file lock. #[bench] fn bench_lock_unlock(b: &mut test::Bencher) { let tempdir = tempdir::TempDir::new("fs2").unwrap(); let path = tempdir.path().join("fs2"); 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("fs2").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("fs2").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("fs2").unwrap(); b.iter(|| { test::black_box(total_space(&tempdir.path()).unwrap()); }); } } fs2-0.4.3/src/unix.rs010064400007660000024000000177201322421236600125600ustar0000000000000000extern crate libc; use std::ffi::CString; use std::fs::File; use std::io::{Error, ErrorKind, Result}; use std::mem; use std::os::unix::ffi::OsStrExt; use std::os::unix::fs::MetadataExt; use std::os::unix::io::{AsRawFd, FromRawFd}; use std::path::Path; use FsStats; pub fn duplicate(file: &File) -> Result { unsafe { let fd = libc::dup(file.as_raw_fd()); if fd < 0 { Err(Error::last_os_error()) } else { Ok(File::from_raw_fd(fd)) } } } pub fn lock_shared(file: &File) -> Result<()> { flock(file, libc::LOCK_SH) } pub fn lock_exclusive(file: &File) -> Result<()> { flock(file, libc::LOCK_EX) } pub fn try_lock_shared(file: &File) -> Result<()> { flock(file, libc::LOCK_SH | libc::LOCK_NB) } pub fn try_lock_exclusive(file: &File) -> Result<()> { flock(file, libc::LOCK_EX | libc::LOCK_NB) } pub fn unlock(file: &File) -> Result<()> { flock(file, libc::LOCK_UN) } pub fn lock_error() -> Error { Error::from_raw_os_error(libc::EWOULDBLOCK) } #[cfg(not(target_os = "solaris"))] fn flock(file: &File, flag: libc::c_int) -> Result<()> { let ret = unsafe { libc::flock(file.as_raw_fd(), flag) }; if ret < 0 { Err(Error::last_os_error()) } else { Ok(()) } } /// Simulate flock() using fcntl(); primarily for Oracle Solaris. #[cfg(target_os = "solaris")] fn flock(file: &File, flag: libc::c_int) -> Result<()> { let mut fl = libc::flock { l_whence: 0, l_start: 0, l_len: 0, l_type: 0, l_pad: [0; 4], l_pid: 0, l_sysid: 0, }; // In non-blocking mode, use F_SETLK for cmd, F_SETLKW otherwise, and don't forget to clear // LOCK_NB. let (cmd, operation) = match flag & libc::LOCK_NB { 0 => (libc::F_SETLKW, flag), _ => (libc::F_SETLK, flag & !libc::LOCK_NB), }; match operation { libc::LOCK_SH => fl.l_type |= libc::F_RDLCK, libc::LOCK_EX => fl.l_type |= libc::F_WRLCK, libc::LOCK_UN => fl.l_type |= libc::F_UNLCK, _ => return Err(Error::from_raw_os_error(libc::EINVAL)), } let ret = unsafe { libc::fcntl(file.as_raw_fd(), cmd, &fl) }; match ret { // Translate EACCES to EWOULDBLOCK -1 => match Error::last_os_error().raw_os_error() { Some(libc::EACCES) => return Err(lock_error()), _ => return Err(Error::last_os_error()) }, _ => Ok(()) } } pub fn allocated_size(file: &File) -> Result { file.metadata().map(|m| m.blocks() as u64 * 512) } #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "android", target_os = "nacl"))] pub fn allocate(file: &File, len: u64) -> Result<()> { let ret = unsafe { libc::posix_fallocate(file.as_raw_fd(), 0, len as libc::off_t) }; if ret == 0 { Ok(()) } else { Err(Error::last_os_error()) } } #[cfg(any(target_os = "macos", target_os = "ios"))] pub fn allocate(file: &File, len: u64) -> Result<()> { let stat = try!(file.metadata()); if len > stat.blocks() as u64 * 512 { let mut fstore = libc::fstore_t { fst_flags: libc::F_ALLOCATECONTIG, fst_posmode: libc::F_PEOFPOSMODE, fst_offset: 0, fst_length: len as libc::off_t, fst_bytesalloc: 0, }; let ret = unsafe { libc::fcntl(file.as_raw_fd(), libc::F_PREALLOCATE, &fstore) }; if ret == -1 { // Unable to allocate contiguous disk space; attempt to allocate non-contiguously. fstore.fst_flags = libc::F_ALLOCATEALL; let ret = unsafe { libc::fcntl(file.as_raw_fd(), libc::F_PREALLOCATE, &fstore) }; if ret == -1 { return Err(Error::last_os_error()); } } } if len > stat.size() as u64 { file.set_len(len) } else { Ok(()) } } #[cfg(any(target_os = "openbsd", target_os = "netbsd", target_os = "dragonfly", target_os = "solaris", target_os = "haiku"))] pub fn allocate(file: &File, len: u64) -> Result<()> { // No file allocation API available, just set the length if necessary. if len > try!(file.metadata()).len() as u64 { file.set_len(len) } else { Ok(()) } } pub fn statvfs(path: &Path) -> Result { let cstr = match CString::new(path.as_os_str().as_bytes()) { Ok(cstr) => cstr, Err(..) => return Err(Error::new(ErrorKind::InvalidInput, "path contained a null")), }; unsafe { let mut stat: libc::statvfs = mem::zeroed(); // danburkert/fs2-rs#1: cast is necessary for platforms where c_char != u8. if libc::statvfs(cstr.as_ptr() as *const _, &mut stat) != 0 { Err(Error::last_os_error()) } else { Ok(FsStats { free_space: stat.f_frsize as u64 * stat.f_bfree as u64, available_space: stat.f_frsize as u64 * stat.f_bavail as u64, total_space: stat.f_frsize as u64 * stat.f_blocks as u64, allocation_granularity: stat.f_frsize as u64, }) } } } #[cfg(test)] mod test { extern crate tempdir; extern crate libc; use std::fs::{self, File}; use std::os::unix::io::AsRawFd; use {FileExt, lock_contended_error}; /// The duplicate method returns a file with a new file descriptor. #[test] fn duplicate_new_fd() { let tempdir = tempdir::TempDir::new("fs2").unwrap(); let path = tempdir.path().join("fs2"); let file1 = fs::OpenOptions::new().write(true).create(true).open(&path).unwrap(); let file2 = file1.duplicate().unwrap(); assert!(file1.as_raw_fd() != file2.as_raw_fd()); } /// The duplicate method should preservesthe close on exec flag. #[test] fn duplicate_cloexec() { fn flags(file: &File) -> libc::c_int { unsafe { libc::fcntl(file.as_raw_fd(), libc::F_GETFL, 0) } } let tempdir = tempdir::TempDir::new("fs2").unwrap(); let path = tempdir.path().join("fs2"); let file1 = fs::OpenOptions::new().write(true).create(true).open(&path).unwrap(); let file2 = file1.duplicate().unwrap(); assert_eq!(flags(&file1), flags(&file2)); } /// 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("fs2").unwrap(); let path = tempdir.path().join("fs2"); 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(); } /// Tests that locks are shared among duplicated file descriptors. #[test] fn lock_duplicate() { let tempdir = tempdir::TempDir::new("fs2").unwrap(); let path = tempdir.path().join("fs2"); let file1 = fs::OpenOptions::new().write(true).create(true).open(&path).unwrap(); let file2 = file1.duplicate().unwrap(); let file3 = fs::OpenOptions::new().write(true).create(true).open(&path).unwrap(); // Create a lock through fd1, then replace it through fd2. file1.lock_shared().unwrap(); file2.lock_exclusive().unwrap(); assert_eq!(file3.try_lock_shared().unwrap_err().raw_os_error(), lock_contended_error().raw_os_error()); // Either of the file descriptors should be able to unlock. file1.unlock().unwrap(); file3.lock_shared().unwrap(); } } fs2-0.4.3/src/windows.rs010064400007660000024000000243641322422416000132640ustar0000000000000000use std::fs::File; use std::io::{Error, Result}; use std::mem; use std::os::windows::ffi::OsStrExt; use std::os::windows::io::{AsRawHandle, FromRawHandle}; use std::path::Path; use std::ptr; use winapi::shared::minwindef::{BOOL, DWORD}; use winapi::shared::winerror::ERROR_LOCK_VIOLATION; use winapi::um::fileapi::{FILE_ALLOCATION_INFO, FILE_STANDARD_INFO, GetDiskFreeSpaceW}; use winapi::um::fileapi::{GetVolumePathNameW, LockFileEx, UnlockFile, SetFileInformationByHandle}; use winapi::um::handleapi::DuplicateHandle; use winapi::um::minwinbase::{FileAllocationInfo, FileStandardInfo}; use winapi::um::minwinbase::{LOCKFILE_FAIL_IMMEDIATELY, LOCKFILE_EXCLUSIVE_LOCK}; use winapi::um::processthreadsapi::GetCurrentProcess; use winapi::um::winbase::GetFileInformationByHandleEx; use winapi::um::winnt::DUPLICATE_SAME_ACCESS; use FsStats; pub fn duplicate(file: &File) -> Result { unsafe { let mut handle = ptr::null_mut(); let current_process = GetCurrentProcess(); let ret = DuplicateHandle(current_process, file.as_raw_handle(), current_process, &mut handle, 0, true as BOOL, DUPLICATE_SAME_ACCESS); if ret == 0 { Err(Error::last_os_error()) } else { Ok(File::from_raw_handle(handle)) } } } pub fn allocated_size(file: &File) -> Result { unsafe { let mut info: FILE_STANDARD_INFO = mem::zeroed(); let ret = GetFileInformationByHandleEx( file.as_raw_handle(), FileStandardInfo, &mut info as *mut _ as *mut _, mem::size_of::() as DWORD); if ret == 0 { Err(Error::last_os_error()) } else { Ok(*info.AllocationSize.QuadPart() as u64) } } } pub fn allocate(file: &File, len: u64) -> Result<()> { if try!(allocated_size(file)) < len { unsafe { let mut info: FILE_ALLOCATION_INFO = mem::zeroed(); *info.AllocationSize.QuadPart_mut() = len as i64; let ret = SetFileInformationByHandle( file.as_raw_handle(), FileAllocationInfo, &mut info as *mut _ as *mut _, mem::size_of::() as DWORD); if ret == 0 { return Err(Error::last_os_error()); } } } if try!(file.metadata()).len() < len { file.set_len(len) } else { Ok(()) } } 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(), 0, 0, !0, !0); if ret == 0 { Err(Error::last_os_error()) } else { Ok(()) } } } pub fn lock_error() -> Error { Error::from_raw_os_error(ERROR_LOCK_VIOLATION as i32) } fn lock_file(file: &File, flags: DWORD) -> Result<()> { unsafe { let mut overlapped = mem::zeroed(); let ret = LockFileEx(file.as_raw_handle(), flags, 0, !0, !0, &mut overlapped); if ret == 0 { Err(Error::last_os_error()) } else { Ok(()) } } } 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 DWORD); if ret == 0 { Err(Error::last_os_error()) } else { Ok(()) } } } pub fn statvfs(path: &Path) -> Result { let root_path: &mut [u16] = &mut [0; 261]; try!(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: free_space, available_space: free_space, total_space: total_space, allocation_granularity: bytes_per_cluster, }) } } } #[cfg(test)] mod test { extern crate tempdir; use std::fs; use std::os::windows::io::AsRawHandle; use {FileExt, lock_contended_error}; /// The duplicate method returns a file with a new file handle. #[test] fn duplicate_new_handle() { let tempdir = tempdir::TempDir::new("fs2").unwrap(); let path = tempdir.path().join("fs2"); let file1 = fs::OpenOptions::new().write(true).create(true).open(&path).unwrap(); let file2 = file1.duplicate().unwrap(); assert!(file1.as_raw_handle() != file2.as_raw_handle()); } /// A duplicated file handle does not have access to the original handle's locks. #[test] fn lock_duplicate_handle_independence() { let tempdir = tempdir::TempDir::new("fs2").unwrap(); let path = tempdir.path().join("fs2"); let file1 = fs::OpenOptions::new().read(true).write(true).create(true).open(&path).unwrap(); let file2 = file1.duplicate().unwrap(); // Locking the original file handle will block the duplicate file handle from opening a lock. file1.lock_shared().unwrap(); assert_eq!(file2.try_lock_exclusive().unwrap_err().raw_os_error(), lock_contended_error().raw_os_error()); // Once the original file handle is unlocked, the duplicate handle can proceed with a lock. file1.unlock().unwrap(); file2.lock_exclusive().unwrap(); } /// 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("fs2").unwrap(); let path = tempdir.path().join("fs2"); 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("fs2").unwrap(); let path = tempdir.path().join("fs2"); 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("fs2").unwrap(); let path = tempdir.path().join("fs2"); 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(); } /// A file handle's locks will not be released until the original handle and all of its /// duplicates have been closed. This on really smells like a bug in Windows. #[test] fn lock_duplicate_cleanup() { let tempdir = tempdir::TempDir::new("fs2").unwrap(); let path = tempdir.path().join("fs2"); let file1 = fs::OpenOptions::new().read(true).write(true).create(true).open(&path).unwrap(); let file2 = file1.duplicate().unwrap(); // Open a lock on the original handle, then close it. file1.lock_shared().unwrap(); drop(file1); // Attempting to create a lock on the file with the duplicate handle will fail. assert_eq!(file2.try_lock_exclusive().unwrap_err().raw_os_error(), lock_contended_error().raw_os_error()); } }