├── .appveyor.yml ├── .gitignore ├── .travis.yml ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md └── src ├── lib.rs ├── unix.rs └── windows.rs /.appveyor.yml: -------------------------------------------------------------------------------- 1 | environment: 2 | matrix: 3 | - TARGET: x86_64-pc-windows-msvc 4 | - TARGET: i686-pc-windows-msvc 5 | - TARGET: x86_64-pc-windows-gnu 6 | - TARGET: i686-pc-windows-gnu 7 | 8 | install: 9 | - ps: Start-FileDownload "https://static.rust-lang.org/dist/rust-nightly-${env:TARGET}.exe" -FileName "rust-nightly.exe" 10 | - ps: .\rust-nightly.exe /VERYSILENT /NORESTART /DIR="C:\rust" | Out-Null 11 | - ps: $env:PATH="$env:PATH;C:\rust\bin" 12 | 13 | build_script: 14 | - cargo build -v 15 | 16 | test_script: 17 | - SET RUST_BACKTRACE=1 18 | - cargo test -v 19 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: rust 2 | 3 | rust: 4 | - 1.8.0 5 | - stable 6 | - nightly 7 | 8 | os: 9 | - linux 10 | - osx 11 | 12 | env: 13 | matrix: 14 | - ARCH=x86_64 15 | - ARCH=i686 16 | 17 | script: 18 | - cargo build --verbose 19 | - if [[ $TRAVIS_RUST_VERSION = nightly* ]]; then 20 | env RUST_BACKTRACE=1 cargo test -v; 21 | fi 22 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "fs2" 3 | # NB: When modifying, also modify html_root_url in lib.rs 4 | version = "0.4.3" 5 | authors = ["Dan Burkert "] 6 | license = "MIT/Apache-2.0" 7 | repository = "https://github.com/danburkert/fs2-rs" 8 | documentation = "https://docs.rs/fs2" 9 | description = "Cross-platform file locks and file duplication." 10 | keywords = ["file", "file-system", "lock", "duplicate", "flock"] 11 | 12 | [badges] 13 | travis-ci = { repository = "danburkert/fs2-rs" } 14 | appveyor = { repository = "danburkert/fs2-rs" } 15 | 16 | [target.'cfg(unix)'.dependencies] 17 | libc = "0.2.30" 18 | 19 | [target.'cfg(windows)'.dependencies] 20 | winapi = { version = "0.3", features = ["handleapi", "processthreadsapi", "winerror", "fileapi", "winbase", "std"] } 21 | 22 | [dev-dependencies] 23 | tempdir = "0.3" 24 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2015 The Rust Project Developers 2 | 3 | Permission is hereby granted, free of charge, to any 4 | person obtaining a copy of this software and associated 5 | documentation files (the "Software"), to deal in the 6 | Software without restriction, including without 7 | limitation the rights to use, copy, modify, merge, 8 | publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software 10 | is furnished to do so, subject to the following 11 | conditions: 12 | 13 | The above copyright notice and this permission notice 14 | shall be included in all copies or substantial portions 15 | of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 18 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 19 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 21 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 22 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 23 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 24 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 25 | DEALINGS IN THE SOFTWARE. 26 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # fs2 2 | 3 | Extended utilities for working with files and filesystems in Rust. `fs2` 4 | requires Rust stable 1.8 or greater. 5 | 6 | [![Build Status](https://travis-ci.org/danburkert/fs2-rs.svg?branch=master)](https://travis-ci.org/danburkert/fs2-rs) 7 | [![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) 8 | [![Documentation](https://docs.rs/fs2/badge.svg)](https://docs.rs/fs2) 9 | [![Crate](https://img.shields.io/crates/v/fs2.svg)](https://crates.io/crates/fs2) 10 | 11 | ## Features 12 | 13 | - [x] file descriptor duplication. 14 | - [x] file locks. 15 | - [x] file (pre)allocation. 16 | - [x] file allocation information. 17 | - [x] filesystem space usage information. 18 | 19 | ## Platforms 20 | 21 | `fs2` should work on any platform supported by 22 | [`libc`](https://github.com/rust-lang-nursery/libc#platforms-and-documentation). 23 | 24 | `fs2` is continuously tested on: 25 | * `x86_64-unknown-linux-gnu` (Linux) 26 | * `i686-unknown-linux-gnu` 27 | * `x86_64-apple-darwin` (OSX) 28 | * `i686-apple-darwin` 29 | * `x86_64-pc-windows-msvc` (Windows) 30 | * `i686-pc-windows-msvc` 31 | * `x86_64-pc-windows-gnu` 32 | * `i686-pc-windows-gnu` 33 | 34 | ## Benchmarks 35 | 36 | Simple benchmarks are provided for the methods provided. Many of these 37 | benchmarks use files in a temporary directory. On many modern Linux distros the 38 | default temporary directory, `/tmp`, is mounted on a tempfs filesystem, which 39 | will have different performance characteristics than a disk-backed filesystem. 40 | The temporary directory is configurable at runtime through the environment (see 41 | [`env::temp_dir`](https://doc.rust-lang.org/stable/std/env/fn.temp_dir.html)). 42 | 43 | ## License 44 | 45 | `fs2` is primarily distributed under the terms of both the MIT license and the 46 | Apache License (Version 2.0). 47 | 48 | See [LICENSE-APACHE](LICENSE-APACHE), [LICENSE-MIT](LICENSE-MIT) for details. 49 | 50 | Copyright (c) 2015 Dan Burkert. 51 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! Extended utilities for working with files and filesystems in Rust. 2 | 3 | #![doc(html_root_url = "https://docs.rs/fs2/0.4.3")] 4 | 5 | #![cfg_attr(test, feature(test))] 6 | 7 | #[cfg(windows)] 8 | extern crate winapi; 9 | 10 | #[cfg(unix)] 11 | mod unix; 12 | #[cfg(unix)] 13 | use unix as sys; 14 | 15 | #[cfg(windows)] 16 | mod windows; 17 | #[cfg(windows)] 18 | use windows as sys; 19 | 20 | use std::fs::File; 21 | use std::io::{Error, Result}; 22 | use std::path::Path; 23 | 24 | /// Extension trait for `std::fs::File` which provides allocation, duplication and locking methods. 25 | /// 26 | /// ## Notes on File Locks 27 | /// 28 | /// This library provides whole-file locks in both shared (read) and exclusive 29 | /// (read-write) varieties. 30 | /// 31 | /// File locks are a cross-platform hazard since the file lock APIs exposed by 32 | /// operating system kernels vary in subtle and not-so-subtle ways. 33 | /// 34 | /// The API exposed by this library can be safely used across platforms as long 35 | /// as the following rules are followed: 36 | /// 37 | /// * Multiple locks should not be created on an individual `File` instance 38 | /// concurrently. 39 | /// * Duplicated files should not be locked without great care. 40 | /// * Files to be locked should be opened with at least read or write 41 | /// permissions. 42 | /// * File locks may only be relied upon to be advisory. 43 | /// 44 | /// See the tests in `lib.rs` for cross-platform lock behavior that may be 45 | /// relied upon; see the tests in `unix.rs` and `windows.rs` for examples of 46 | /// platform-specific behavior. File locks are implemented with 47 | /// [`flock(2)`](http://man7.org/linux/man-pages/man2/flock.2.html) on Unix and 48 | /// [`LockFile`](https://msdn.microsoft.com/en-us/library/windows/desktop/aa365202(v=vs.85).aspx) 49 | /// on Windows. 50 | pub trait FileExt { 51 | 52 | /// Returns a duplicate instance of the file. 53 | /// 54 | /// The returned file will share the same file position as the original 55 | /// file. 56 | /// 57 | /// If using rustc version 1.9 or later, prefer using `File::try_clone` to this. 58 | /// 59 | /// # Notes 60 | /// 61 | /// This is implemented with 62 | /// [`dup(2)`](http://man7.org/linux/man-pages/man2/dup.2.html) on Unix and 63 | /// [`DuplicateHandle`](https://msdn.microsoft.com/en-us/library/windows/desktop/ms724251(v=vs.85).aspx) 64 | /// on Windows. 65 | fn duplicate(&self) -> Result; 66 | 67 | /// Returns the amount of physical space allocated for a file. 68 | fn allocated_size(&self) -> Result; 69 | 70 | /// Ensures that at least `len` bytes of disk space are allocated for the 71 | /// file, and the file size is at least `len` bytes. After a successful call 72 | /// to `allocate`, subsequent writes to the file within the specified length 73 | /// are guaranteed not to fail because of lack of disk space. 74 | fn allocate(&self, len: u64) -> Result<()>; 75 | 76 | /// Locks the file for shared usage, blocking if the file is currently 77 | /// locked exclusively. 78 | fn lock_shared(&self) -> Result<()>; 79 | 80 | /// Locks the file for exclusive usage, blocking if the file is currently 81 | /// locked. 82 | fn lock_exclusive(&self) -> Result<()>; 83 | 84 | /// Locks the file for shared usage, or returns a an error if the file is 85 | /// currently locked (see `lock_contended_error`). 86 | fn try_lock_shared(&self) -> Result<()>; 87 | 88 | /// Locks the file for shared usage, or returns a an error if the file is 89 | /// currently locked (see `lock_contended_error`). 90 | fn try_lock_exclusive(&self) -> Result<()>; 91 | 92 | /// Unlocks the file. 93 | fn unlock(&self) -> Result<()>; 94 | } 95 | 96 | impl FileExt for File { 97 | fn duplicate(&self) -> Result { 98 | sys::duplicate(self) 99 | } 100 | fn allocated_size(&self) -> Result { 101 | sys::allocated_size(self) 102 | } 103 | fn allocate(&self, len: u64) -> Result<()> { 104 | sys::allocate(self, len) 105 | } 106 | fn lock_shared(&self) -> Result<()> { 107 | sys::lock_shared(self) 108 | } 109 | fn lock_exclusive(&self) -> Result<()> { 110 | sys::lock_exclusive(self) 111 | } 112 | fn try_lock_shared(&self) -> Result<()> { 113 | sys::try_lock_shared(self) 114 | } 115 | fn try_lock_exclusive(&self) -> Result<()> { 116 | sys::try_lock_exclusive(self) 117 | } 118 | fn unlock(&self) -> Result<()> { 119 | sys::unlock(self) 120 | } 121 | } 122 | 123 | /// Returns the error that a call to a try lock method on a contended file will 124 | /// return. 125 | pub fn lock_contended_error() -> Error { 126 | sys::lock_error() 127 | } 128 | 129 | /// `FsStats` contains some common stats about a file system. 130 | #[derive(Clone, Debug, PartialEq, Eq, Hash)] 131 | pub struct FsStats { 132 | free_space: u64, 133 | available_space: u64, 134 | total_space: u64, 135 | allocation_granularity: u64, 136 | } 137 | 138 | impl FsStats { 139 | /// Returns the number of free bytes in the file system containing the provided 140 | /// path. 141 | pub fn free_space(&self) -> u64 { 142 | self.free_space 143 | } 144 | 145 | /// Returns the available space in bytes to non-priveleged users in the file 146 | /// system containing the provided path. 147 | pub fn available_space(&self) -> u64 { 148 | self.available_space 149 | } 150 | 151 | /// Returns the total space in bytes in the file system containing the provided 152 | /// path. 153 | pub fn total_space(&self) -> u64 { 154 | self.total_space 155 | } 156 | 157 | /// Returns the filesystem's disk space allocation granularity in bytes. 158 | /// The provided path may be for any file in the filesystem. 159 | /// 160 | /// On Posix, this is equivalent to the filesystem's block size. 161 | /// On Windows, this is equivalent to the filesystem's cluster size. 162 | pub fn allocation_granularity(&self) -> u64 { 163 | self.allocation_granularity 164 | } 165 | } 166 | 167 | /// Get the stats of the file system containing the provided path. 168 | pub fn statvfs

(path: P) -> Result where P: AsRef { 169 | sys::statvfs(path.as_ref()) 170 | } 171 | 172 | /// Returns the number of free bytes in the file system containing the provided 173 | /// path. 174 | pub fn free_space

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

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

(path: P) -> Result where P: AsRef { 187 | statvfs(path).map(|stat| stat.total_space) 188 | } 189 | 190 | /// Returns the filesystem's disk space allocation granularity in bytes. 191 | /// The provided path may be for any file in the filesystem. 192 | /// 193 | /// On Posix, this is equivalent to the filesystem's block size. 194 | /// On Windows, this is equivalent to the filesystem's cluster size. 195 | pub fn allocation_granularity

(path: P) -> Result where P: AsRef { 196 | statvfs(path).map(|stat| stat.allocation_granularity) 197 | } 198 | 199 | #[cfg(test)] 200 | mod test { 201 | 202 | extern crate tempdir; 203 | extern crate test; 204 | 205 | use std::fs; 206 | use super::*; 207 | use std::io::{Read, Seek, SeekFrom, Write}; 208 | 209 | /// Tests file duplication. 210 | #[test] 211 | fn duplicate() { 212 | let tempdir = tempdir::TempDir::new("fs2").unwrap(); 213 | let path = tempdir.path().join("fs2"); 214 | let mut file1 = 215 | fs::OpenOptions::new().read(true).write(true).create(true).open(&path).unwrap(); 216 | let mut file2 = file1.duplicate().unwrap(); 217 | 218 | // Write into the first file and then drop it. 219 | file1.write_all(b"foo").unwrap(); 220 | drop(file1); 221 | 222 | let mut buf = vec![]; 223 | 224 | // Read from the second file; since the position is shared it will already be at EOF. 225 | file2.read_to_end(&mut buf).unwrap(); 226 | assert_eq!(0, buf.len()); 227 | 228 | // Rewind and read. 229 | file2.seek(SeekFrom::Start(0)).unwrap(); 230 | file2.read_to_end(&mut buf).unwrap(); 231 | assert_eq!(&buf, &b"foo"); 232 | } 233 | 234 | /// Tests shared file lock operations. 235 | #[test] 236 | fn lock_shared() { 237 | let tempdir = tempdir::TempDir::new("fs2").unwrap(); 238 | let path = tempdir.path().join("fs2"); 239 | let file1 = fs::OpenOptions::new().read(true).write(true).create(true).open(&path).unwrap(); 240 | let file2 = fs::OpenOptions::new().read(true).write(true).create(true).open(&path).unwrap(); 241 | let file3 = fs::OpenOptions::new().read(true).write(true).create(true).open(&path).unwrap(); 242 | 243 | // Concurrent shared access is OK, but not shared and exclusive. 244 | file1.lock_shared().unwrap(); 245 | file2.lock_shared().unwrap(); 246 | assert_eq!(file3.try_lock_exclusive().unwrap_err().kind(), 247 | lock_contended_error().kind()); 248 | file1.unlock().unwrap(); 249 | assert_eq!(file3.try_lock_exclusive().unwrap_err().kind(), 250 | lock_contended_error().kind()); 251 | 252 | // Once all shared file locks are dropped, an exclusive lock may be created; 253 | file2.unlock().unwrap(); 254 | file3.lock_exclusive().unwrap(); 255 | } 256 | 257 | /// Tests exclusive file lock operations. 258 | #[test] 259 | fn lock_exclusive() { 260 | let tempdir = tempdir::TempDir::new("fs2").unwrap(); 261 | let path = tempdir.path().join("fs2"); 262 | let file1 = fs::OpenOptions::new().read(true).write(true).create(true).open(&path).unwrap(); 263 | let file2 = fs::OpenOptions::new().read(true).write(true).create(true).open(&path).unwrap(); 264 | 265 | // No other access is possible once an exclusive lock is created. 266 | file1.lock_exclusive().unwrap(); 267 | assert_eq!(file2.try_lock_exclusive().unwrap_err().kind(), 268 | lock_contended_error().kind()); 269 | assert_eq!(file2.try_lock_shared().unwrap_err().kind(), 270 | lock_contended_error().kind()); 271 | 272 | // Once the exclusive lock is dropped, the second file is able to create a lock. 273 | file1.unlock().unwrap(); 274 | file2.lock_exclusive().unwrap(); 275 | } 276 | 277 | /// Tests that a lock is released after the file that owns it is dropped. 278 | #[test] 279 | fn lock_cleanup() { 280 | let tempdir = tempdir::TempDir::new("fs2").unwrap(); 281 | let path = tempdir.path().join("fs2"); 282 | let file1 = fs::OpenOptions::new().read(true).write(true).create(true).open(&path).unwrap(); 283 | let file2 = fs::OpenOptions::new().read(true).write(true).create(true).open(&path).unwrap(); 284 | 285 | file1.lock_exclusive().unwrap(); 286 | assert_eq!(file2.try_lock_shared().unwrap_err().kind(), 287 | lock_contended_error().kind()); 288 | 289 | // Drop file1; the lock should be released. 290 | drop(file1); 291 | file2.lock_shared().unwrap(); 292 | } 293 | 294 | /// Tests file allocation. 295 | #[test] 296 | fn allocate() { 297 | let tempdir = tempdir::TempDir::new("fs2").unwrap(); 298 | let path = tempdir.path().join("fs2"); 299 | let file = fs::OpenOptions::new().write(true).create(true).open(&path).unwrap(); 300 | let blksize = allocation_granularity(&path).unwrap(); 301 | 302 | // New files are created with no allocated size. 303 | assert_eq!(0, file.allocated_size().unwrap()); 304 | assert_eq!(0, file.metadata().unwrap().len()); 305 | 306 | // Allocate space for the file, checking that the allocated size steps 307 | // up by block size, and the file length matches the allocated size. 308 | 309 | file.allocate(2 * blksize - 1).unwrap(); 310 | assert_eq!(2 * blksize, file.allocated_size().unwrap()); 311 | assert_eq!(2 * blksize - 1, file.metadata().unwrap().len()); 312 | 313 | // Truncate the file, checking that the allocated size steps down by 314 | // block size. 315 | 316 | file.set_len(blksize + 1).unwrap(); 317 | assert_eq!(2 * blksize, file.allocated_size().unwrap()); 318 | assert_eq!(blksize + 1, file.metadata().unwrap().len()); 319 | } 320 | 321 | /// Checks filesystem space methods. 322 | #[test] 323 | fn filesystem_space() { 324 | let tempdir = tempdir::TempDir::new("fs2").unwrap(); 325 | let total_space = total_space(&tempdir.path()).unwrap(); 326 | let free_space = free_space(&tempdir.path()).unwrap(); 327 | let available_space = available_space(&tempdir.path()).unwrap(); 328 | 329 | assert!(total_space > free_space); 330 | assert!(total_space > available_space); 331 | assert!(available_space <= free_space); 332 | } 333 | 334 | /// Benchmarks creating and removing a file. This is a baseline benchmark 335 | /// for comparing against the truncate and allocate benchmarks. 336 | #[bench] 337 | fn bench_file_create(b: &mut test::Bencher) { 338 | let tempdir = tempdir::TempDir::new("fs2").unwrap(); 339 | let path = tempdir.path().join("file"); 340 | 341 | b.iter(|| { 342 | fs::OpenOptions::new() 343 | .read(true) 344 | .write(true) 345 | .create(true) 346 | .open(&path) 347 | .unwrap(); 348 | fs::remove_file(&path).unwrap(); 349 | }); 350 | } 351 | 352 | /// Benchmarks creating a file, truncating it to 32MiB, and deleting it. 353 | #[bench] 354 | fn bench_file_truncate(b: &mut test::Bencher) { 355 | let size = 32 * 1024 * 1024; 356 | let tempdir = tempdir::TempDir::new("fs2").unwrap(); 357 | let path = tempdir.path().join("file"); 358 | 359 | b.iter(|| { 360 | let file = fs::OpenOptions::new() 361 | .read(true) 362 | .write(true) 363 | .create(true) 364 | .open(&path) 365 | .unwrap(); 366 | file.set_len(size).unwrap(); 367 | fs::remove_file(&path).unwrap(); 368 | }); 369 | } 370 | 371 | /// Benchmarks creating a file, allocating 32MiB for it, and deleting it. 372 | #[bench] 373 | fn bench_file_allocate(b: &mut test::Bencher) { 374 | let size = 32 * 1024 * 1024; 375 | let tempdir = tempdir::TempDir::new("fs2").unwrap(); 376 | let path = tempdir.path().join("file"); 377 | 378 | b.iter(|| { 379 | let file = fs::OpenOptions::new() 380 | .read(true) 381 | .write(true) 382 | .create(true) 383 | .open(&path) 384 | .unwrap(); 385 | file.allocate(size).unwrap(); 386 | fs::remove_file(&path).unwrap(); 387 | }); 388 | } 389 | 390 | /// Benchmarks creating a file, allocating 32MiB for it, and deleting it. 391 | #[bench] 392 | fn bench_allocated_size(b: &mut test::Bencher) { 393 | let size = 32 * 1024 * 1024; 394 | let tempdir = tempdir::TempDir::new("fs2").unwrap(); 395 | let path = tempdir.path().join("file"); 396 | let file = fs::OpenOptions::new() 397 | .read(true) 398 | .write(true) 399 | .create(true) 400 | .open(&path) 401 | .unwrap(); 402 | file.allocate(size).unwrap(); 403 | 404 | b.iter(|| { 405 | file.allocated_size().unwrap(); 406 | }); 407 | } 408 | 409 | /// Benchmarks duplicating a file descriptor or handle. 410 | #[bench] 411 | fn bench_duplicate(b: &mut test::Bencher) { 412 | let tempdir = tempdir::TempDir::new("fs2").unwrap(); 413 | let path = tempdir.path().join("fs2"); 414 | let file = fs::OpenOptions::new().read(true).write(true).create(true).open(&path).unwrap(); 415 | 416 | b.iter(|| test::black_box(file.duplicate().unwrap())); 417 | } 418 | 419 | /// Benchmarks locking and unlocking a file lock. 420 | #[bench] 421 | fn bench_lock_unlock(b: &mut test::Bencher) { 422 | let tempdir = tempdir::TempDir::new("fs2").unwrap(); 423 | let path = tempdir.path().join("fs2"); 424 | let file = fs::OpenOptions::new().read(true).write(true).create(true).open(&path).unwrap(); 425 | 426 | b.iter(|| { 427 | file.lock_exclusive().unwrap(); 428 | file.unlock().unwrap(); 429 | }); 430 | } 431 | 432 | /// Benchmarks the free space method. 433 | #[bench] 434 | fn bench_free_space(b: &mut test::Bencher) { 435 | let tempdir = tempdir::TempDir::new("fs2").unwrap(); 436 | b.iter(|| { 437 | test::black_box(free_space(&tempdir.path()).unwrap()); 438 | }); 439 | } 440 | 441 | /// Benchmarks the available space method. 442 | #[bench] 443 | fn bench_available_space(b: &mut test::Bencher) { 444 | let tempdir = tempdir::TempDir::new("fs2").unwrap(); 445 | b.iter(|| { 446 | test::black_box(available_space(&tempdir.path()).unwrap()); 447 | }); 448 | } 449 | 450 | /// Benchmarks the total space method. 451 | #[bench] 452 | fn bench_total_space(b: &mut test::Bencher) { 453 | let tempdir = tempdir::TempDir::new("fs2").unwrap(); 454 | b.iter(|| { 455 | test::black_box(total_space(&tempdir.path()).unwrap()); 456 | }); 457 | } 458 | } 459 | -------------------------------------------------------------------------------- /src/unix.rs: -------------------------------------------------------------------------------- 1 | extern crate libc; 2 | 3 | use std::ffi::CString; 4 | use std::fs::File; 5 | use std::io::{Error, ErrorKind, Result}; 6 | use std::mem; 7 | use std::os::unix::ffi::OsStrExt; 8 | use std::os::unix::fs::MetadataExt; 9 | use std::os::unix::io::{AsRawFd, FromRawFd}; 10 | use std::path::Path; 11 | 12 | use FsStats; 13 | 14 | pub fn duplicate(file: &File) -> Result { 15 | unsafe { 16 | let fd = libc::dup(file.as_raw_fd()); 17 | 18 | if fd < 0 { 19 | Err(Error::last_os_error()) 20 | } else { 21 | Ok(File::from_raw_fd(fd)) 22 | } 23 | } 24 | } 25 | 26 | pub fn lock_shared(file: &File) -> Result<()> { 27 | flock(file, libc::LOCK_SH) 28 | } 29 | 30 | pub fn lock_exclusive(file: &File) -> Result<()> { 31 | flock(file, libc::LOCK_EX) 32 | } 33 | 34 | pub fn try_lock_shared(file: &File) -> Result<()> { 35 | flock(file, libc::LOCK_SH | libc::LOCK_NB) 36 | } 37 | 38 | pub fn try_lock_exclusive(file: &File) -> Result<()> { 39 | flock(file, libc::LOCK_EX | libc::LOCK_NB) 40 | } 41 | 42 | pub fn unlock(file: &File) -> Result<()> { 43 | flock(file, libc::LOCK_UN) 44 | } 45 | 46 | pub fn lock_error() -> Error { 47 | Error::from_raw_os_error(libc::EWOULDBLOCK) 48 | } 49 | 50 | #[cfg(not(target_os = "solaris"))] 51 | fn flock(file: &File, flag: libc::c_int) -> Result<()> { 52 | let ret = unsafe { libc::flock(file.as_raw_fd(), flag) }; 53 | if ret < 0 { Err(Error::last_os_error()) } else { Ok(()) } 54 | } 55 | 56 | /// Simulate flock() using fcntl(); primarily for Oracle Solaris. 57 | #[cfg(target_os = "solaris")] 58 | fn flock(file: &File, flag: libc::c_int) -> Result<()> { 59 | let mut fl = libc::flock { 60 | l_whence: 0, 61 | l_start: 0, 62 | l_len: 0, 63 | l_type: 0, 64 | l_pad: [0; 4], 65 | l_pid: 0, 66 | l_sysid: 0, 67 | }; 68 | 69 | // In non-blocking mode, use F_SETLK for cmd, F_SETLKW otherwise, and don't forget to clear 70 | // LOCK_NB. 71 | let (cmd, operation) = match flag & libc::LOCK_NB { 72 | 0 => (libc::F_SETLKW, flag), 73 | _ => (libc::F_SETLK, flag & !libc::LOCK_NB), 74 | }; 75 | 76 | match operation { 77 | libc::LOCK_SH => fl.l_type |= libc::F_RDLCK, 78 | libc::LOCK_EX => fl.l_type |= libc::F_WRLCK, 79 | libc::LOCK_UN => fl.l_type |= libc::F_UNLCK, 80 | _ => return Err(Error::from_raw_os_error(libc::EINVAL)), 81 | } 82 | 83 | let ret = unsafe { libc::fcntl(file.as_raw_fd(), cmd, &fl) }; 84 | match ret { 85 | // Translate EACCES to EWOULDBLOCK 86 | -1 => match Error::last_os_error().raw_os_error() { 87 | Some(libc::EACCES) => return Err(lock_error()), 88 | _ => return Err(Error::last_os_error()) 89 | }, 90 | _ => Ok(()) 91 | } 92 | } 93 | 94 | pub fn allocated_size(file: &File) -> Result { 95 | file.metadata().map(|m| m.blocks() as u64 * 512) 96 | } 97 | 98 | #[cfg(any(target_os = "linux", 99 | target_os = "freebsd", 100 | target_os = "android", 101 | target_os = "emscripten", 102 | target_os = "nacl"))] 103 | pub fn allocate(file: &File, len: u64) -> Result<()> { 104 | let ret = unsafe { libc::posix_fallocate(file.as_raw_fd(), 0, len as libc::off_t) }; 105 | if ret == 0 { Ok(()) } else { Err(Error::last_os_error()) } 106 | } 107 | 108 | #[cfg(any(target_os = "macos", target_os = "ios"))] 109 | pub fn allocate(file: &File, len: u64) -> Result<()> { 110 | let stat = try!(file.metadata()); 111 | 112 | if len > stat.blocks() as u64 * 512 { 113 | let mut fstore = libc::fstore_t { 114 | fst_flags: libc::F_ALLOCATECONTIG, 115 | fst_posmode: libc::F_PEOFPOSMODE, 116 | fst_offset: 0, 117 | fst_length: len as libc::off_t, 118 | fst_bytesalloc: 0, 119 | }; 120 | 121 | let ret = unsafe { libc::fcntl(file.as_raw_fd(), libc::F_PREALLOCATE, &fstore) }; 122 | if ret == -1 { 123 | // Unable to allocate contiguous disk space; attempt to allocate non-contiguously. 124 | fstore.fst_flags = libc::F_ALLOCATEALL; 125 | let ret = unsafe { libc::fcntl(file.as_raw_fd(), libc::F_PREALLOCATE, &fstore) }; 126 | if ret == -1 { 127 | return Err(Error::last_os_error()); 128 | } 129 | } 130 | } 131 | 132 | if len > stat.size() as u64 { 133 | file.set_len(len) 134 | } else { 135 | Ok(()) 136 | } 137 | } 138 | 139 | #[cfg(any(target_os = "openbsd", 140 | target_os = "netbsd", 141 | target_os = "dragonfly", 142 | target_os = "solaris", 143 | target_os = "haiku"))] 144 | pub fn allocate(file: &File, len: u64) -> Result<()> { 145 | // No file allocation API available, just set the length if necessary. 146 | if len > try!(file.metadata()).len() as u64 { 147 | file.set_len(len) 148 | } else { 149 | Ok(()) 150 | } 151 | } 152 | 153 | pub fn statvfs(path: &Path) -> Result { 154 | let cstr = match CString::new(path.as_os_str().as_bytes()) { 155 | Ok(cstr) => cstr, 156 | Err(..) => return Err(Error::new(ErrorKind::InvalidInput, "path contained a null")), 157 | }; 158 | 159 | unsafe { 160 | let mut stat: libc::statvfs = mem::zeroed(); 161 | // danburkert/fs2-rs#1: cast is necessary for platforms where c_char != u8. 162 | if libc::statvfs(cstr.as_ptr() as *const _, &mut stat) != 0 { 163 | Err(Error::last_os_error()) 164 | } else { 165 | Ok(FsStats { 166 | free_space: stat.f_frsize as u64 * stat.f_bfree as u64, 167 | available_space: stat.f_frsize as u64 * stat.f_bavail as u64, 168 | total_space: stat.f_frsize as u64 * stat.f_blocks as u64, 169 | allocation_granularity: stat.f_frsize as u64, 170 | }) 171 | } 172 | } 173 | } 174 | 175 | #[cfg(test)] 176 | mod test { 177 | extern crate tempdir; 178 | extern crate libc; 179 | 180 | use std::fs::{self, File}; 181 | use std::os::unix::io::AsRawFd; 182 | 183 | use {FileExt, lock_contended_error}; 184 | 185 | /// The duplicate method returns a file with a new file descriptor. 186 | #[test] 187 | fn duplicate_new_fd() { 188 | let tempdir = tempdir::TempDir::new("fs2").unwrap(); 189 | let path = tempdir.path().join("fs2"); 190 | let file1 = fs::OpenOptions::new().write(true).create(true).open(&path).unwrap(); 191 | let file2 = file1.duplicate().unwrap(); 192 | assert!(file1.as_raw_fd() != file2.as_raw_fd()); 193 | } 194 | 195 | /// The duplicate method should preservesthe close on exec flag. 196 | #[test] 197 | fn duplicate_cloexec() { 198 | 199 | fn flags(file: &File) -> libc::c_int { 200 | unsafe { libc::fcntl(file.as_raw_fd(), libc::F_GETFL, 0) } 201 | } 202 | 203 | let tempdir = tempdir::TempDir::new("fs2").unwrap(); 204 | let path = tempdir.path().join("fs2"); 205 | let file1 = fs::OpenOptions::new().write(true).create(true).open(&path).unwrap(); 206 | let file2 = file1.duplicate().unwrap(); 207 | 208 | assert_eq!(flags(&file1), flags(&file2)); 209 | } 210 | 211 | /// Tests that locking a file descriptor will replace any existing locks 212 | /// held on the file descriptor. 213 | #[test] 214 | fn lock_replace() { 215 | let tempdir = tempdir::TempDir::new("fs2").unwrap(); 216 | let path = tempdir.path().join("fs2"); 217 | let file1 = fs::OpenOptions::new().write(true).create(true).open(&path).unwrap(); 218 | let file2 = fs::OpenOptions::new().write(true).create(true).open(&path).unwrap(); 219 | 220 | // Creating a shared lock will drop an exclusive lock. 221 | file1.lock_exclusive().unwrap(); 222 | file1.lock_shared().unwrap(); 223 | file2.lock_shared().unwrap(); 224 | 225 | // Attempting to replace a shared lock with an exclusive lock will fail 226 | // with multiple lock holders, and remove the original shared lock. 227 | assert_eq!(file2.try_lock_exclusive().unwrap_err().raw_os_error(), 228 | lock_contended_error().raw_os_error()); 229 | file1.lock_shared().unwrap(); 230 | } 231 | 232 | /// Tests that locks are shared among duplicated file descriptors. 233 | #[test] 234 | fn lock_duplicate() { 235 | let tempdir = tempdir::TempDir::new("fs2").unwrap(); 236 | let path = tempdir.path().join("fs2"); 237 | let file1 = fs::OpenOptions::new().write(true).create(true).open(&path).unwrap(); 238 | let file2 = file1.duplicate().unwrap(); 239 | let file3 = fs::OpenOptions::new().write(true).create(true).open(&path).unwrap(); 240 | 241 | // Create a lock through fd1, then replace it through fd2. 242 | file1.lock_shared().unwrap(); 243 | file2.lock_exclusive().unwrap(); 244 | assert_eq!(file3.try_lock_shared().unwrap_err().raw_os_error(), 245 | lock_contended_error().raw_os_error()); 246 | 247 | // Either of the file descriptors should be able to unlock. 248 | file1.unlock().unwrap(); 249 | file3.lock_shared().unwrap(); 250 | } 251 | } 252 | -------------------------------------------------------------------------------- /src/windows.rs: -------------------------------------------------------------------------------- 1 | use std::fs::File; 2 | use std::io::{Error, Result}; 3 | use std::mem; 4 | use std::os::windows::ffi::OsStrExt; 5 | use std::os::windows::io::{AsRawHandle, FromRawHandle}; 6 | use std::path::Path; 7 | use std::ptr; 8 | 9 | use winapi::shared::minwindef::{BOOL, DWORD}; 10 | use winapi::shared::winerror::ERROR_LOCK_VIOLATION; 11 | use winapi::um::fileapi::{FILE_ALLOCATION_INFO, FILE_STANDARD_INFO, GetDiskFreeSpaceW}; 12 | use winapi::um::fileapi::{GetVolumePathNameW, LockFileEx, UnlockFile, SetFileInformationByHandle}; 13 | use winapi::um::handleapi::DuplicateHandle; 14 | use winapi::um::minwinbase::{FileAllocationInfo, FileStandardInfo}; 15 | use winapi::um::minwinbase::{LOCKFILE_FAIL_IMMEDIATELY, LOCKFILE_EXCLUSIVE_LOCK}; 16 | use winapi::um::processthreadsapi::GetCurrentProcess; 17 | use winapi::um::winbase::GetFileInformationByHandleEx; 18 | use winapi::um::winnt::DUPLICATE_SAME_ACCESS; 19 | 20 | use FsStats; 21 | 22 | pub fn duplicate(file: &File) -> Result { 23 | unsafe { 24 | let mut handle = ptr::null_mut(); 25 | let current_process = GetCurrentProcess(); 26 | let ret = DuplicateHandle(current_process, 27 | file.as_raw_handle(), 28 | current_process, 29 | &mut handle, 30 | 0, 31 | true as BOOL, 32 | DUPLICATE_SAME_ACCESS); 33 | if ret == 0 { 34 | Err(Error::last_os_error()) 35 | } else { 36 | Ok(File::from_raw_handle(handle)) 37 | } 38 | } 39 | } 40 | 41 | pub fn allocated_size(file: &File) -> Result { 42 | unsafe { 43 | let mut info: FILE_STANDARD_INFO = mem::zeroed(); 44 | 45 | let ret = GetFileInformationByHandleEx( 46 | file.as_raw_handle(), 47 | FileStandardInfo, 48 | &mut info as *mut _ as *mut _, 49 | mem::size_of::() as DWORD); 50 | 51 | if ret == 0 { 52 | Err(Error::last_os_error()) 53 | } else { 54 | Ok(*info.AllocationSize.QuadPart() as u64) 55 | } 56 | } 57 | } 58 | 59 | pub fn allocate(file: &File, len: u64) -> Result<()> { 60 | if try!(allocated_size(file)) < len { 61 | unsafe { 62 | let mut info: FILE_ALLOCATION_INFO = mem::zeroed(); 63 | *info.AllocationSize.QuadPart_mut() = len as i64; 64 | let ret = SetFileInformationByHandle( 65 | file.as_raw_handle(), 66 | FileAllocationInfo, 67 | &mut info as *mut _ as *mut _, 68 | mem::size_of::() as DWORD); 69 | if ret == 0 { 70 | return Err(Error::last_os_error()); 71 | } 72 | } 73 | } 74 | if try!(file.metadata()).len() < len { 75 | file.set_len(len) 76 | } else { 77 | Ok(()) 78 | } 79 | } 80 | 81 | pub fn lock_shared(file: &File) -> Result<()> { 82 | lock_file(file, 0) 83 | } 84 | 85 | pub fn lock_exclusive(file: &File) -> Result<()> { 86 | lock_file(file, LOCKFILE_EXCLUSIVE_LOCK) 87 | } 88 | 89 | pub fn try_lock_shared(file: &File) -> Result<()> { 90 | lock_file(file, LOCKFILE_FAIL_IMMEDIATELY) 91 | } 92 | 93 | pub fn try_lock_exclusive(file: &File) -> Result<()> { 94 | lock_file(file, LOCKFILE_EXCLUSIVE_LOCK | LOCKFILE_FAIL_IMMEDIATELY) 95 | } 96 | 97 | pub fn unlock(file: &File) -> Result<()> { 98 | unsafe { 99 | let ret = UnlockFile(file.as_raw_handle(), 0, 0, !0, !0); 100 | if ret == 0 { Err(Error::last_os_error()) } else { Ok(()) } 101 | } 102 | } 103 | 104 | pub fn lock_error() -> Error { 105 | Error::from_raw_os_error(ERROR_LOCK_VIOLATION as i32) 106 | } 107 | 108 | fn lock_file(file: &File, flags: DWORD) -> Result<()> { 109 | unsafe { 110 | let mut overlapped = mem::zeroed(); 111 | let ret = LockFileEx(file.as_raw_handle(), flags, 0, !0, !0, &mut overlapped); 112 | if ret == 0 { Err(Error::last_os_error()) } else { Ok(()) } 113 | } 114 | } 115 | 116 | fn volume_path(path: &Path, volume_path: &mut [u16]) -> Result<()> { 117 | let path_utf8: Vec = path.as_os_str().encode_wide().chain(Some(0)).collect(); 118 | unsafe { 119 | let ret = GetVolumePathNameW(path_utf8.as_ptr(), 120 | volume_path.as_mut_ptr(), 121 | volume_path.len() as DWORD); 122 | if ret == 0 { Err(Error::last_os_error()) } else { Ok(()) 123 | } 124 | } 125 | } 126 | 127 | pub fn statvfs(path: &Path) -> Result { 128 | let root_path: &mut [u16] = &mut [0; 261]; 129 | try!(volume_path(path, root_path)); 130 | unsafe { 131 | 132 | let mut sectors_per_cluster = 0; 133 | let mut bytes_per_sector = 0; 134 | let mut number_of_free_clusters = 0; 135 | let mut total_number_of_clusters = 0; 136 | let ret = GetDiskFreeSpaceW(root_path.as_ptr(), 137 | &mut sectors_per_cluster, 138 | &mut bytes_per_sector, 139 | &mut number_of_free_clusters, 140 | &mut total_number_of_clusters); 141 | if ret == 0 { 142 | Err(Error::last_os_error()) 143 | } else { 144 | let bytes_per_cluster = sectors_per_cluster as u64 * bytes_per_sector as u64; 145 | let free_space = bytes_per_cluster * number_of_free_clusters as u64; 146 | let total_space = bytes_per_cluster * total_number_of_clusters as u64; 147 | Ok(FsStats { 148 | free_space: free_space, 149 | available_space: free_space, 150 | total_space: total_space, 151 | allocation_granularity: bytes_per_cluster, 152 | }) 153 | } 154 | } 155 | } 156 | 157 | #[cfg(test)] 158 | mod test { 159 | 160 | extern crate tempdir; 161 | 162 | use std::fs; 163 | use std::os::windows::io::AsRawHandle; 164 | 165 | use {FileExt, lock_contended_error}; 166 | 167 | /// The duplicate method returns a file with a new file handle. 168 | #[test] 169 | fn duplicate_new_handle() { 170 | let tempdir = tempdir::TempDir::new("fs2").unwrap(); 171 | let path = tempdir.path().join("fs2"); 172 | let file1 = fs::OpenOptions::new().write(true).create(true).open(&path).unwrap(); 173 | let file2 = file1.duplicate().unwrap(); 174 | assert!(file1.as_raw_handle() != file2.as_raw_handle()); 175 | } 176 | 177 | /// A duplicated file handle does not have access to the original handle's locks. 178 | #[test] 179 | fn lock_duplicate_handle_independence() { 180 | let tempdir = tempdir::TempDir::new("fs2").unwrap(); 181 | let path = tempdir.path().join("fs2"); 182 | let file1 = fs::OpenOptions::new().read(true).write(true).create(true).open(&path).unwrap(); 183 | let file2 = file1.duplicate().unwrap(); 184 | 185 | // Locking the original file handle will block the duplicate file handle from opening a lock. 186 | file1.lock_shared().unwrap(); 187 | assert_eq!(file2.try_lock_exclusive().unwrap_err().raw_os_error(), 188 | lock_contended_error().raw_os_error()); 189 | 190 | // Once the original file handle is unlocked, the duplicate handle can proceed with a lock. 191 | file1.unlock().unwrap(); 192 | file2.lock_exclusive().unwrap(); 193 | } 194 | 195 | /// A file handle may not be exclusively locked multiple times, or exclusively locked and then 196 | /// shared locked. 197 | #[test] 198 | fn lock_non_reentrant() { 199 | let tempdir = tempdir::TempDir::new("fs2").unwrap(); 200 | let path = tempdir.path().join("fs2"); 201 | let file = fs::OpenOptions::new().read(true).write(true).create(true).open(&path).unwrap(); 202 | 203 | // Multiple exclusive locks fails. 204 | file.lock_exclusive().unwrap(); 205 | assert_eq!(file.try_lock_exclusive().unwrap_err().raw_os_error(), 206 | lock_contended_error().raw_os_error()); 207 | file.unlock().unwrap(); 208 | 209 | // Shared then Exclusive locks fails. 210 | file.lock_shared().unwrap(); 211 | assert_eq!(file.try_lock_exclusive().unwrap_err().raw_os_error(), 212 | lock_contended_error().raw_os_error()); 213 | } 214 | 215 | /// A file handle can hold an exclusive lock and any number of shared locks, all of which must 216 | /// be unlocked independently. 217 | #[test] 218 | fn lock_layering() { 219 | let tempdir = tempdir::TempDir::new("fs2").unwrap(); 220 | let path = tempdir.path().join("fs2"); 221 | let file = fs::OpenOptions::new().read(true).write(true).create(true).open(&path).unwrap(); 222 | 223 | // Open two shared locks on the file, and then try and fail to open an exclusive lock. 224 | file.lock_exclusive().unwrap(); 225 | file.lock_shared().unwrap(); 226 | file.lock_shared().unwrap(); 227 | assert_eq!(file.try_lock_exclusive().unwrap_err().raw_os_error(), 228 | lock_contended_error().raw_os_error()); 229 | 230 | // Pop one of the shared locks and try again. 231 | file.unlock().unwrap(); 232 | assert_eq!(file.try_lock_exclusive().unwrap_err().raw_os_error(), 233 | lock_contended_error().raw_os_error()); 234 | 235 | // Pop the second shared lock and try again. 236 | file.unlock().unwrap(); 237 | assert_eq!(file.try_lock_exclusive().unwrap_err().raw_os_error(), 238 | lock_contended_error().raw_os_error()); 239 | 240 | // Pop the exclusive lock and finally succeed. 241 | file.unlock().unwrap(); 242 | file.lock_exclusive().unwrap(); 243 | } 244 | 245 | /// A file handle with multiple open locks will have all locks closed on drop. 246 | #[test] 247 | fn lock_layering_cleanup() { 248 | let tempdir = tempdir::TempDir::new("fs2").unwrap(); 249 | let path = tempdir.path().join("fs2"); 250 | let file1 = fs::OpenOptions::new().read(true).write(true).create(true).open(&path).unwrap(); 251 | let file2 = fs::OpenOptions::new().read(true).write(true).create(true).open(&path).unwrap(); 252 | 253 | // Open two shared locks on the file, and then try and fail to open an exclusive lock. 254 | file1.lock_shared().unwrap(); 255 | assert_eq!(file2.try_lock_exclusive().unwrap_err().raw_os_error(), 256 | lock_contended_error().raw_os_error()); 257 | 258 | drop(file1); 259 | file2.lock_exclusive().unwrap(); 260 | } 261 | 262 | /// A file handle's locks will not be released until the original handle and all of its 263 | /// duplicates have been closed. This on really smells like a bug in Windows. 264 | #[test] 265 | fn lock_duplicate_cleanup() { 266 | let tempdir = tempdir::TempDir::new("fs2").unwrap(); 267 | let path = tempdir.path().join("fs2"); 268 | let file1 = fs::OpenOptions::new().read(true).write(true).create(true).open(&path).unwrap(); 269 | let file2 = file1.duplicate().unwrap(); 270 | 271 | // Open a lock on the original handle, then close it. 272 | file1.lock_shared().unwrap(); 273 | drop(file1); 274 | 275 | // Attempting to create a lock on the file with the duplicate handle will fail. 276 | assert_eq!(file2.try_lock_exclusive().unwrap_err().raw_os_error(), 277 | lock_contended_error().raw_os_error()); 278 | } 279 | } 280 | --------------------------------------------------------------------------------