├── .github └── workflows │ └── build.yml ├── .gitignore ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── changelog.md ├── examples ├── seek.rs ├── stdin.rs └── stdin_actix_web.rs ├── src └── lib.rs └── tests ├── run ├── test_actix_web_input.txt ├── test_actix_web_output.txt ├── test_input.txt └── test_output.txt /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: build 2 | on: 3 | pull_request: 4 | push: 5 | schedule: 6 | - cron: 12 20 3 * * 7 | workflow_dispatch: 8 | jobs: 9 | build: 10 | runs-on: ubuntu-latest 11 | steps: 12 | - uses: actions/checkout@v2 13 | - uses: actions-rs/cargo@v1 14 | with: 15 | command: test 16 | args: -v --all-features 17 | - run: tests/run 18 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # generic 2 | .#* 3 | \#*# 4 | .nfs???? 5 | [tT]humbs.db 6 | *~ 7 | *.dep 8 | *.log 9 | *.orig 10 | *.pid 11 | *.tmp 12 | 13 | # native 14 | a.out 15 | *.a 16 | *.aps 17 | *.dll 18 | *.dylib 19 | *.exe 20 | *.gcda 21 | *.gch 22 | *.gcno 23 | *.ipch 24 | *.lcov 25 | *.lib 26 | *.ncb 27 | *.o 28 | *.obj 29 | *.opensdf 30 | *.pch 31 | *.so 32 | *.sdf 33 | *.stackdump 34 | *.suo 35 | *.user 36 | 37 | # Fortran 38 | *.mod 39 | 40 | # Haskell 41 | .cabal-sandbox/ 42 | .stack-work/ 43 | dist/ 44 | cabal.config 45 | cabal.sandbox.config 46 | stack.yaml 47 | *.chi 48 | *.hcr 49 | *.hi 50 | 51 | # JavaScript 52 | node_modules/ 53 | 54 | # Python 55 | MANIFEST 56 | __pycache__ 57 | *.pyc 58 | 59 | # Rust 60 | target/ 61 | Cargo.lock 62 | 63 | # TeX 64 | *.aux 65 | *.bbl 66 | *.blg 67 | *.fdb_latexmk 68 | *.fls 69 | *.thm 70 | *.toc 71 | *Notes.bib 72 | 73 | # web 74 | .sass-cache 75 | *.css.map 76 | *.js.map 77 | 78 | # Examples / Tests output 79 | tests/seek.txt 80 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "tokio-file-unix" 3 | version = "0.6.0" 4 | authors = ["Phil Ruffwind "] 5 | description = "Asynchronous support for epollable files via Tokio on Unix-like platforms" 6 | documentation = "https://docs.rs/tokio-file-unix" 7 | repository = "https://github.com/Rufflewind/tokio-file-unix" 8 | readme = "README.md" 9 | keywords = ["asynchronous", "file", "pipe", "stdio", "tokio"] 10 | categories = ["asynchronous"] 11 | license = "MIT/Apache-2.0" 12 | exclude = [".gitignore", ".travis.yml", "tests/seek.txt"] 13 | edition = "2018" 14 | 15 | [dependencies] 16 | libc = "0.2.21" 17 | mio = "0.6.6" 18 | tokio = { version = "0.2.6", features = ["io-driver"] } 19 | 20 | [dev-dependencies] 21 | futures = "0.3.8" 22 | tokio = { version = "0.2.6", features = ["io-util", "macros"] } 23 | tokio-util = { version = "0.3.0", features = ["codec"] } 24 | actix-rt = "1.1.1" 25 | actix-web = "3.3.0" 26 | -------------------------------------------------------------------------------- /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 | The MIT License (MIT) 2 | 3 | Copyright (c) 2017 Phil Ruffwind 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # `tokio-file-unix` 2 | 3 | [![Documentation](https://docs.rs/tokio-file-unix/badge.svg)](https://docs.rs/tokio-file-unix) 4 | [![Crates.io](https://img.shields.io/crates/v/tokio-file-unix.svg)](https://crates.io/crates/tokio-file-unix) 5 | [![Build Status](https://github.com/Rufflewind/tokio-file-unix/actions/workflows/build.yml/badge.svg)](https://github.com/Rufflewind/tokio-file-unix/actions/workflows/build.yml) 6 | 7 | Asynchronous support for file-like objects via [Tokio](https://tokio.rs). **Only supports Unix-like platforms.** 8 | 9 | This crate is primarily intended for pipes and other files that support nonblocking I/O. Regular files do not support nonblocking I/O, so this crate has no effect on them. 10 | 11 | ## Usage 12 | 13 | Add this to your `Cargo.toml`: 14 | 15 | ~~~toml 16 | [dependencies] 17 | tokio-file-unix = "0.5.1" 18 | ~~~ 19 | 20 | Next, add this to the root module of your crate: 21 | 22 | ~~~rust 23 | extern crate tokio_file_unix; 24 | ~~~ 25 | 26 | ## Examples 27 | 28 | See the `examples` directory as well as the documentation. 29 | 30 | ## License 31 | 32 | Dual-licensed under Apache and MIT. 33 | -------------------------------------------------------------------------------- /changelog.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | ## 0.6.0 4 | 5 | - `File::to_io` has been removed in favor of having `File::new_nb` and 6 | `File::raw_new` return a `PollEvented` directly. 7 | - `File::get_nonblocking` and `File::set_nonblocking` have been migrated to 8 | module-level. 9 | - `StdFile` has been removed in favor of `raw_stdin`, `raw_stdout`, and 10 | `raw_stderr`. 11 | - `DelimCodec` has been removed in favor of `tokio_util::codec::FramedRead`. 12 | - tokio dependency has been migrated to 0.2.6 and Rust edition to 2018. 13 | 14 | ## 0.5.1 15 | 16 | - Add `impl Seek for File`. 17 | 18 | ## 0.5.0 19 | 20 | - Migrate from `tokio-core` to `tokio-reactor`. 21 | - Add `raw_std{in,out,err}` and deprecate `StdFile` in favor of those. 22 | 23 | ## 0.4.2 24 | 25 | - Add `File::get_nonblocking`. 26 | 27 | ## 0.4.1 28 | 29 | - Improved documentation and added another example `stdin_lines.rs`. 30 | 31 | ## 0.4.0 32 | 33 | - Added “support” for regular files (which never block anyway). 34 | https://github.com/Rufflewind/tokio-file-unix/issues/2 35 | - Constructor of `File` is now private. 36 | Use `File::new_nb` or `File::raw_new` instead. 37 | - `File` is no longer `Sync`. 38 | - `File::set_nonblocking` no longer requires `&mut self`, just `&self`. 39 | 40 | ## 0.3.0 41 | 42 | - Removed fake implementations of `Read` and `Write` for `StdFile`. 43 | - Upgraded to tokio-io. 44 | 45 | ## 0.2.0 46 | 47 | - Added `DelimCodec` and `StdFile`. 48 | - Generalized `File`. 49 | 50 | ## 0.1.0 51 | 52 | - Initial release. 53 | -------------------------------------------------------------------------------- /examples/seek.rs: -------------------------------------------------------------------------------- 1 | use std::fs::File; 2 | use std::io::{self, Seek, SeekFrom}; 3 | use tokio::io::AsyncWriteExt; 4 | 5 | #[tokio::main] 6 | async fn main() -> io::Result<()> { 7 | let file = File::create("tests/seek.txt")?; 8 | file.set_len(0x11)?; 9 | let mut file = tokio_file_unix::File::new_nb(file)?; 10 | 11 | file.write_all(b"aaaaAAAAaaaaAAAA\n").await?; 12 | file.get_mut().seek(SeekFrom::Start(8))?; 13 | file.write_all(&[b'b'; 8]).await?; 14 | file.get_mut().seek(SeekFrom::Start(2))?; 15 | file.write_all(&[b'c'; 4]).await?; 16 | 17 | Ok(()) 18 | } 19 | -------------------------------------------------------------------------------- /examples/stdin.rs: -------------------------------------------------------------------------------- 1 | use std::io; 2 | use tokio::stream::StreamExt; 3 | use tokio_util::codec::{FramedRead, LinesCodec}; 4 | 5 | #[tokio::main] 6 | async fn main() -> io::Result<()> { 7 | // convert stdin into a nonblocking file; 8 | // this is the only part that makes use of tokio_file_unix 9 | let file = tokio_file_unix::raw_stdin()?; 10 | let file = tokio_file_unix::File::new_nb(file)?; 11 | 12 | let mut framed = FramedRead::new(file, LinesCodec::new()); 13 | 14 | println!("Type something and hit enter!"); 15 | while let Some(got) = framed.next().await { 16 | println!("Got: {:?}", got); 17 | } 18 | 19 | Ok(()) 20 | } 21 | -------------------------------------------------------------------------------- /examples/stdin_actix_web.rs: -------------------------------------------------------------------------------- 1 | use actix_web::client::Client; 2 | use actix_web::{get, web, App, HttpServer, Responder}; 3 | use futures::future::FutureExt; 4 | use futures::{pin_mut, select}; 5 | use std::{error, io}; 6 | use tokio::stream::StreamExt; 7 | use tokio_util::codec::{FramedRead, LinesCodec}; 8 | 9 | fn stringify_error(e: E) -> io::Error { 10 | io::Error::new(io::ErrorKind::Other, e.to_string()) 11 | } 12 | 13 | #[get("/{something}")] 14 | async fn index(info: web::Path) -> impl Responder { 15 | format!("Hello Got this: {}", info) 16 | } 17 | 18 | #[actix_rt::main] 19 | async fn main() -> io::Result<()> { 20 | println!("Type something and hit enter!"); 21 | let stdin_fut = async { 22 | let file = tokio_file_unix::raw_stdin()?; 23 | let file = tokio_file_unix::File::new_nb(file)?; 24 | 25 | let client = Client::default(); 26 | 27 | let mut framed = FramedRead::new(file, LinesCodec::new()); 28 | 29 | while let Some(got) = framed.next().await { 30 | println!("Sending this: {:?}", got); 31 | 32 | let mut response = client 33 | .get(format!( 34 | "http://127.0.0.1:8080/{}", 35 | got.map_err(stringify_error)? 36 | )) 37 | .send() 38 | .await 39 | .map_err(stringify_error)?; 40 | 41 | let body = response.body().await.map_err(stringify_error)?; 42 | 43 | println!( 44 | "Got bytes: {:?}", 45 | String::from_utf8(body.to_vec()).map_err(stringify_error)?, 46 | ); 47 | } 48 | Ok(()) 49 | } 50 | .fuse(); 51 | 52 | let server_fut = HttpServer::new(|| App::new().service(index)) 53 | .bind("127.0.0.1:8080")? 54 | .run() 55 | .fuse(); 56 | 57 | pin_mut!(stdin_fut, server_fut); 58 | select! { 59 | result = stdin_fut => result, 60 | result = server_fut => result, 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! A utility library that adds asynchronous support to file-like objects on 2 | //! Unix-like platforms. 3 | //! 4 | //! This crate is primarily intended for pipes and other files that support 5 | //! nonblocking I/O. Regular files do not support nonblocking I/O, so this 6 | //! crate has no effect on them. 7 | //! 8 | //! See [`File`](struct.File.html) for an example of how a file can be made 9 | //! suitable for asynchronous I/O. 10 | 11 | use std::cell::RefCell; 12 | use std::os::unix::io::{AsRawFd, FromRawFd, RawFd}; 13 | use std::{fs, io}; 14 | use tokio::io::PollEvented; 15 | 16 | unsafe fn dupe_file_from_fd(old_fd: RawFd) -> io::Result { 17 | let fd = libc::fcntl(old_fd, libc::F_DUPFD_CLOEXEC, 0); 18 | if fd < 0 { 19 | return Err(io::Error::last_os_error()); 20 | } 21 | Ok(fs::File::from_raw_fd(fd)) 22 | } 23 | 24 | /// Duplicate the standard input file. 25 | /// 26 | /// Unlike `std::io::Stdin`, this file is not buffered. 27 | pub fn raw_stdin() -> io::Result { 28 | unsafe { dupe_file_from_fd(libc::STDIN_FILENO) } 29 | } 30 | 31 | /// Duplicate the standard output file. 32 | /// 33 | /// Unlike `std::io::Stdout`, this file is not buffered. 34 | pub fn raw_stdout() -> io::Result { 35 | unsafe { dupe_file_from_fd(libc::STDOUT_FILENO) } 36 | } 37 | 38 | /// Duplicate the standard error file. 39 | /// 40 | /// Unlike `std::io::Stderr`, this file is not buffered. 41 | pub fn raw_stderr() -> io::Result { 42 | unsafe { dupe_file_from_fd(libc::STDERR_FILENO) } 43 | } 44 | 45 | /// Gets the nonblocking mode of the underlying file descriptor. 46 | /// 47 | /// Implementation detail: uses `fcntl` to retrieve `O_NONBLOCK`. 48 | pub fn get_nonblocking(file: &F) -> io::Result { 49 | unsafe { 50 | let flags = libc::fcntl(file.as_raw_fd(), libc::F_GETFL); 51 | if flags < 0 { 52 | return Err(io::Error::last_os_error()); 53 | } 54 | Ok(flags & libc::O_NONBLOCK != 0) 55 | } 56 | } 57 | 58 | /// Sets the nonblocking mode of the underlying file descriptor to either on 59 | /// (`true`) or off (`false`). If `File::new_nb` was previously used to 60 | /// construct the `File`, then nonblocking mode has already been turned on. 61 | /// 62 | /// This function is not atomic. It should only called if you have exclusive 63 | /// control of the underlying file descriptor. 64 | /// 65 | /// Implementation detail: uses `fcntl` to query the flags and set 66 | /// `O_NONBLOCK`. 67 | pub fn set_nonblocking(file: &mut F, nonblocking: bool) -> io::Result<()> { 68 | unsafe { 69 | let fd = file.as_raw_fd(); 70 | // shamelessly copied from libstd/sys/unix/fd.rs 71 | let previous = libc::fcntl(fd, libc::F_GETFL); 72 | if previous < 0 { 73 | return Err(io::Error::last_os_error()); 74 | } 75 | let new = if nonblocking { 76 | previous | libc::O_NONBLOCK 77 | } else { 78 | previous & !libc::O_NONBLOCK 79 | }; 80 | if libc::fcntl(fd, libc::F_SETFL, new) < 0 { 81 | return Err(io::Error::last_os_error()); 82 | } 83 | Ok(()) 84 | } 85 | } 86 | 87 | /// Wraps file-like objects for asynchronous I/O. 88 | /// 89 | /// Normally, you should use `File::new_nb` rather than `File::raw_new` unless 90 | /// the underlying file descriptor has already been set to nonblocking mode. 91 | /// Using a file descriptor that is not in nonblocking mode for asynchronous 92 | /// I/O will lead to subtle and confusing bugs. 93 | /// 94 | /// Wrapping regular files has no effect because they do not support 95 | /// nonblocking mode. 96 | /// 97 | /// The most common instantiation of this type is `File`, which 98 | /// indirectly provides the following trait implementation: 99 | /// 100 | /// ```ignore 101 | /// impl AsyncRead + AsyncWrite for PollEvented>; 102 | /// ``` 103 | /// 104 | /// ## Example: read standard input line by line 105 | /// 106 | /// ``` 107 | /// use tokio::stream::StreamExt; 108 | /// use tokio_util::codec::FramedRead; 109 | /// use tokio_util::codec::LinesCodec; 110 | /// 111 | /// #[tokio::main] 112 | /// async fn main() -> std::io::Result<()> { 113 | /// // convert stdin into a nonblocking file; 114 | /// // this is the only part that makes use of tokio_file_unix 115 | /// let file = tokio_file_unix::raw_stdin()?; 116 | /// let file = tokio_file_unix::File::new_nb(file)?; 117 | /// 118 | /// let mut framed = FramedRead::new(file, LinesCodec::new()); 119 | /// 120 | /// while let Some(got) = framed.next().await { 121 | /// println!("Got this: {:?}", got); 122 | /// } 123 | /// 124 | /// println!("Received None, lol"); 125 | /// Ok(()) 126 | /// } 127 | /// ``` 128 | /// 129 | /// ## Example: unsafe creation from raw file descriptor 130 | /// 131 | /// To unsafely create `File` from a raw file descriptor `fd`, you can do 132 | /// something like: 133 | /// 134 | /// ``` 135 | /// # use std::os::unix::io::{AsRawFd, RawFd}; 136 | /// use std::os::unix::io::FromRawFd; 137 | /// 138 | /// # unsafe fn test(fd: RawFd) -> std::io::Result<()> { 139 | /// let file = tokio_file_unix::File::new_nb(F::from_raw_fd(fd))?; 140 | /// # Ok(()) 141 | /// # } 142 | /// ``` 143 | /// 144 | /// which will enable nonblocking mode upon creation. The choice of `F` is 145 | /// critical: it determines the ownership semantics of the file descriptor. 146 | /// For example, if you choose `F = std::fs::File`, the file descriptor will 147 | /// be closed when the `File` is dropped. 148 | #[derive(Debug)] 149 | pub struct File { 150 | file: F, 151 | evented: RefCell>, 152 | } 153 | 154 | impl File { 155 | /// Wraps a file-like object into a pollable object that supports 156 | /// `tokio::io::AsyncRead` and `tokio::io::AsyncWrite`, and also *enables 157 | /// nonblocking mode* on the underlying file descriptor. 158 | pub fn new_nb(mut file: F) -> io::Result> { 159 | set_nonblocking(&mut file, true)?; 160 | File::raw_new(file) 161 | } 162 | 163 | /// Raw constructor that **does not enable nonblocking mode** on the 164 | /// underlying file descriptor. This constructor should only be used if 165 | /// you are certain that the underlying file descriptor is already in 166 | /// nonblocking mode. 167 | pub fn raw_new(file: F) -> io::Result> { 168 | PollEvented::new(File { 169 | file: file, 170 | evented: Default::default(), 171 | }) 172 | } 173 | } 174 | 175 | impl AsRawFd for File { 176 | fn as_raw_fd(&self) -> RawFd { 177 | self.file.as_raw_fd() 178 | } 179 | } 180 | 181 | impl mio::Evented for File { 182 | fn register( 183 | &self, 184 | poll: &mio::Poll, 185 | token: mio::Token, 186 | interest: mio::Ready, 187 | opts: mio::PollOpt, 188 | ) -> io::Result<()> { 189 | match mio::unix::EventedFd(&self.as_raw_fd()).register(poll, token, interest, opts) { 190 | // this is a workaround for regular files, which are not supported 191 | // by epoll; they would instead cause EPERM upon registration 192 | Err(ref e) if e.raw_os_error() == Some(libc::EPERM) => { 193 | set_nonblocking(&mut self.as_raw_fd(), false)?; 194 | // workaround: PollEvented/IoToken always starts off in the 195 | // "not ready" state so we have to use a real Evented object 196 | // to set its readiness state 197 | let (r, s) = mio::Registration::new2(); 198 | r.register(poll, token, interest, opts)?; 199 | s.set_readiness(mio::Ready::readable() | mio::Ready::writable())?; 200 | *self.evented.borrow_mut() = Some(r); 201 | Ok(()) 202 | } 203 | e => e, 204 | } 205 | } 206 | 207 | fn reregister( 208 | &self, 209 | poll: &mio::Poll, 210 | token: mio::Token, 211 | interest: mio::Ready, 212 | opts: mio::PollOpt, 213 | ) -> io::Result<()> { 214 | match *self.evented.borrow() { 215 | None => mio::unix::EventedFd(&self.as_raw_fd()).reregister(poll, token, interest, opts), 216 | Some(ref r) => r.reregister(poll, token, interest, opts), 217 | } 218 | } 219 | 220 | fn deregister(&self, poll: &mio::Poll) -> io::Result<()> { 221 | match *self.evented.borrow() { 222 | None => mio::unix::EventedFd(&self.as_raw_fd()).deregister(poll), 223 | Some(ref r) => mio::Evented::deregister(r, poll), 224 | } 225 | } 226 | } 227 | 228 | impl io::Read for File { 229 | fn read(&mut self, buf: &mut [u8]) -> io::Result { 230 | self.file.read(buf) 231 | } 232 | } 233 | 234 | impl io::Write for File { 235 | fn write(&mut self, buf: &[u8]) -> io::Result { 236 | self.file.write(buf) 237 | } 238 | 239 | fn flush(&mut self) -> io::Result<()> { 240 | self.file.flush() 241 | } 242 | } 243 | 244 | impl io::Seek for File { 245 | fn seek(&mut self, pos: io::SeekFrom) -> io::Result { 246 | self.file.seek(pos) 247 | } 248 | } 249 | 250 | #[cfg(test)] 251 | mod tests { 252 | use super::*; 253 | use std::os::unix::net::UnixStream; 254 | 255 | #[test] 256 | fn test_nonblocking() -> io::Result<()> { 257 | let (sock, _) = UnixStream::pair()?; 258 | let mut fd = sock.as_raw_fd(); 259 | set_nonblocking(&mut fd, false)?; 260 | assert!(!get_nonblocking(&fd)?); 261 | set_nonblocking(&mut fd, true)?; 262 | assert!(get_nonblocking(&fd)?); 263 | set_nonblocking(&mut fd, false)?; 264 | assert!(!get_nonblocking(&fd)?); 265 | Ok(()) 266 | } 267 | } 268 | -------------------------------------------------------------------------------- /tests/run: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -eux 3 | { 4 | sleep 0.01 5 | cat tests/test_input.txt 6 | } | cargo run --example stdin | diff -u tests/test_output.txt - 7 | cargo run --example stdin