├── .circleci └── config.yml ├── .github └── dependabot.yml ├── .gitignore ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md └── src └── lib.rs /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | restore_registry: &RESTORE_REGISTRY 2 | restore_cache: 3 | key: registry 4 | save_registry: &SAVE_REGISTRY 5 | save_cache: 6 | key: registry-{{ .BuildNum }} 7 | paths: 8 | - /usr/local/cargo/registry/index 9 | deps_key: &DEPS_KEY 10 | key: deps-{{ checksum "~/rust-version" }}-{{ checksum "Cargo.lock" }} 11 | restore_deps: &RESTORE_DEPS 12 | restore_cache: 13 | <<: *DEPS_KEY 14 | save_deps: &SAVE_DEPS 15 | save_cache: 16 | <<: *DEPS_KEY 17 | paths: 18 | - target 19 | - /usr/local/cargo/registry/cache 20 | 21 | version: 2 22 | jobs: 23 | build: 24 | working_directory: ~/build 25 | docker: 26 | - image: rustlang/rust:nightly 27 | environment: 28 | RUSTFLAGS: -D warnings 29 | steps: 30 | - checkout 31 | - *RESTORE_REGISTRY 32 | - run: cargo generate-lockfile 33 | - *SAVE_REGISTRY 34 | - run: rustc --version > ~/rust-version 35 | - *RESTORE_DEPS 36 | - run: cargo test 37 | - *SAVE_DEPS 38 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: cargo 4 | directory: "/" 5 | schedule: 6 | interval: daily 7 | time: "13:00" 8 | open-pull-requests-limit: 10 9 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | **/*.rs.bk 3 | Cargo.lock 4 | 5 | .vscode/ 6 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "tokio-io-timeout" 3 | version = "1.2.0" 4 | authors = ["Steven Fackler "] 5 | license = "MIT/Apache-2.0" 6 | description = "Tokio wrappers which apply timeouts to IO operations" 7 | repository = "https://github.com/sfackler/tokio-io-timeout" 8 | readme = "README.md" 9 | edition = "2018" 10 | 11 | [dependencies] 12 | pin-project-lite = "0.2" 13 | tokio = { version = "1.0", features = ["time"] } 14 | 15 | [dev-dependencies] 16 | tokio = { version = "1.0", features = ["full"] } 17 | -------------------------------------------------------------------------------- /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 | 203 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2017 The tokio-io-timeout Developers 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy 4 | of this software and associated documentation files (the "Software"), to deal 5 | in the Software without restriction, including without limitation the rights 6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | copies of the Software, and to permit persons to whom the Software is 8 | furnished to do so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in all 11 | copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 19 | SOFTWARE. 20 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # tokio-io-timeout 2 | [![CircleCI](https://circleci.com/gh/sfackler/tokio-io-timeout.svg?style=shield)](https://circleci.com/gh/sfackler/tokio-io-timeout) 3 | 4 | [Documentation](https://docs.rs/tokio-io-timeout) 5 | 6 | Tokio wrappers which apply timeouts to IO operations. 7 | 8 | ## License 9 | 10 | Licensed under either of 11 | 12 | * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) 13 | * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 14 | 15 | at your option. 16 | 17 | ### Contribution 18 | 19 | Unless you explicitly state otherwise, any contribution intentionally 20 | submitted for inclusion in the work by you, as defined in the Apache-2.0 21 | license, shall be dual licensed as above, without any additional terms or 22 | conditions. 23 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! Tokio wrappers which apply timeouts to IO operations. 2 | //! 3 | //! These timeouts are analogous to the read and write timeouts on traditional blocking sockets. A timeout countdown is 4 | //! initiated when a read/write operation returns [`Poll::Pending`]. If a read/write does not return successfully before 5 | //! the countdown expires, an [`io::Error`] with a kind of [`TimedOut`](io::ErrorKind::TimedOut) is returned. 6 | #![doc(html_root_url = "https://docs.rs/tokio-io-timeout/1")] 7 | #![warn(missing_docs)] 8 | 9 | use pin_project_lite::pin_project; 10 | use std::future::Future; 11 | use std::io; 12 | use std::io::SeekFrom; 13 | use std::pin::Pin; 14 | use std::task::{Context, Poll}; 15 | use std::time::Duration; 16 | use tokio::io::{AsyncRead, AsyncSeek, AsyncWrite, ReadBuf}; 17 | use tokio::time::{sleep_until, Instant, Sleep}; 18 | 19 | pin_project! { 20 | #[derive(Debug)] 21 | struct TimeoutState { 22 | timeout: Option, 23 | #[pin] 24 | cur: Sleep, 25 | active: bool, 26 | } 27 | } 28 | 29 | impl TimeoutState { 30 | #[inline] 31 | fn new() -> TimeoutState { 32 | TimeoutState { 33 | timeout: None, 34 | cur: sleep_until(Instant::now()), 35 | active: false, 36 | } 37 | } 38 | 39 | #[inline] 40 | fn timeout(&self) -> Option { 41 | self.timeout 42 | } 43 | 44 | #[inline] 45 | fn set_timeout(&mut self, timeout: Option) { 46 | // since this takes &mut self, we can't yet be active 47 | self.timeout = timeout; 48 | } 49 | 50 | #[inline] 51 | fn set_timeout_pinned(mut self: Pin<&mut Self>, timeout: Option) { 52 | *self.as_mut().project().timeout = timeout; 53 | self.reset(); 54 | } 55 | 56 | #[inline] 57 | fn reset(self: Pin<&mut Self>) { 58 | let this = self.project(); 59 | 60 | if *this.active { 61 | *this.active = false; 62 | this.cur.reset(Instant::now()); 63 | } 64 | } 65 | 66 | #[inline] 67 | fn poll_check(self: Pin<&mut Self>, cx: &mut Context<'_>) -> io::Result<()> { 68 | let mut this = self.project(); 69 | 70 | let timeout = match this.timeout { 71 | Some(timeout) => *timeout, 72 | None => return Ok(()), 73 | }; 74 | 75 | if !*this.active { 76 | this.cur.as_mut().reset(Instant::now() + timeout); 77 | *this.active = true; 78 | } 79 | 80 | match this.cur.poll(cx) { 81 | Poll::Ready(()) => Err(io::Error::from(io::ErrorKind::TimedOut)), 82 | Poll::Pending => Ok(()), 83 | } 84 | } 85 | } 86 | 87 | pin_project! { 88 | /// An `AsyncRead`er which applies a timeout to read operations. 89 | #[derive(Debug)] 90 | pub struct TimeoutReader { 91 | #[pin] 92 | reader: R, 93 | #[pin] 94 | state: TimeoutState, 95 | } 96 | } 97 | 98 | impl TimeoutReader 99 | where 100 | R: AsyncRead, 101 | { 102 | /// Returns a new `TimeoutReader` wrapping the specified reader. 103 | /// 104 | /// There is initially no timeout. 105 | pub fn new(reader: R) -> TimeoutReader { 106 | TimeoutReader { 107 | reader, 108 | state: TimeoutState::new(), 109 | } 110 | } 111 | 112 | /// Returns the current read timeout. 113 | pub fn timeout(&self) -> Option { 114 | self.state.timeout() 115 | } 116 | 117 | /// Sets the read timeout. 118 | /// 119 | /// This can only be used before the reader is pinned; use [`set_timeout_pinned`](Self::set_timeout_pinned) 120 | /// otherwise. 121 | pub fn set_timeout(&mut self, timeout: Option) { 122 | self.state.set_timeout(timeout); 123 | } 124 | 125 | /// Sets the read timeout. 126 | /// 127 | /// This will reset any pending timeout. Use [`set_timeout`](Self::set_timeout) instead if the reader is not yet 128 | /// pinned. 129 | pub fn set_timeout_pinned(self: Pin<&mut Self>, timeout: Option) { 130 | self.project().state.set_timeout_pinned(timeout); 131 | } 132 | 133 | /// Returns a shared reference to the inner reader. 134 | pub fn get_ref(&self) -> &R { 135 | &self.reader 136 | } 137 | 138 | /// Returns a mutable reference to the inner reader. 139 | pub fn get_mut(&mut self) -> &mut R { 140 | &mut self.reader 141 | } 142 | 143 | /// Returns a pinned mutable reference to the inner reader. 144 | pub fn get_pin_mut(self: Pin<&mut Self>) -> Pin<&mut R> { 145 | self.project().reader 146 | } 147 | 148 | /// Consumes the `TimeoutReader`, returning the inner reader. 149 | pub fn into_inner(self) -> R { 150 | self.reader 151 | } 152 | } 153 | 154 | impl AsyncRead for TimeoutReader 155 | where 156 | R: AsyncRead, 157 | { 158 | fn poll_read( 159 | self: Pin<&mut Self>, 160 | cx: &mut Context<'_>, 161 | buf: &mut ReadBuf<'_>, 162 | ) -> Poll> { 163 | let this = self.project(); 164 | let r = this.reader.poll_read(cx, buf); 165 | match r { 166 | Poll::Pending => this.state.poll_check(cx)?, 167 | _ => this.state.reset(), 168 | } 169 | r 170 | } 171 | } 172 | 173 | impl AsyncWrite for TimeoutReader 174 | where 175 | R: AsyncWrite, 176 | { 177 | fn poll_write( 178 | self: Pin<&mut Self>, 179 | cx: &mut Context, 180 | buf: &[u8], 181 | ) -> Poll> { 182 | self.project().reader.poll_write(cx, buf) 183 | } 184 | 185 | fn poll_flush(self: Pin<&mut Self>, cx: &mut Context) -> Poll> { 186 | self.project().reader.poll_flush(cx) 187 | } 188 | 189 | fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context) -> Poll> { 190 | self.project().reader.poll_shutdown(cx) 191 | } 192 | 193 | fn poll_write_vectored( 194 | self: Pin<&mut Self>, 195 | cx: &mut Context<'_>, 196 | bufs: &[io::IoSlice<'_>], 197 | ) -> Poll> { 198 | self.project().reader.poll_write_vectored(cx, bufs) 199 | } 200 | 201 | fn is_write_vectored(&self) -> bool { 202 | self.reader.is_write_vectored() 203 | } 204 | } 205 | 206 | impl AsyncSeek for TimeoutReader 207 | where 208 | R: AsyncSeek, 209 | { 210 | fn start_seek(self: Pin<&mut Self>, position: SeekFrom) -> io::Result<()> { 211 | self.project().reader.start_seek(position) 212 | } 213 | fn poll_complete(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { 214 | self.project().reader.poll_complete(cx) 215 | } 216 | } 217 | 218 | pin_project! { 219 | /// An `AsyncWrite`er which applies a timeout to write operations. 220 | #[derive(Debug)] 221 | pub struct TimeoutWriter { 222 | #[pin] 223 | writer: W, 224 | #[pin] 225 | state: TimeoutState, 226 | } 227 | } 228 | 229 | impl TimeoutWriter 230 | where 231 | W: AsyncWrite, 232 | { 233 | /// Returns a new `TimeoutReader` wrapping the specified reader. 234 | /// 235 | /// There is initially no timeout. 236 | pub fn new(writer: W) -> TimeoutWriter { 237 | TimeoutWriter { 238 | writer, 239 | state: TimeoutState::new(), 240 | } 241 | } 242 | 243 | /// Returns the current write timeout. 244 | pub fn timeout(&self) -> Option { 245 | self.state.timeout() 246 | } 247 | 248 | /// Sets the write timeout. 249 | /// 250 | /// This can only be used before the writer is pinned; use [`set_timeout_pinned`](Self::set_timeout_pinned) 251 | /// otherwise. 252 | pub fn set_timeout(&mut self, timeout: Option) { 253 | self.state.set_timeout(timeout); 254 | } 255 | 256 | /// Sets the write timeout. 257 | /// 258 | /// This will reset any pending timeout. Use [`set_timeout`](Self::set_timeout) instead if the reader is not yet 259 | /// pinned. 260 | pub fn set_timeout_pinned(self: Pin<&mut Self>, timeout: Option) { 261 | self.project().state.set_timeout_pinned(timeout); 262 | } 263 | 264 | /// Returns a shared reference to the inner writer. 265 | pub fn get_ref(&self) -> &W { 266 | &self.writer 267 | } 268 | 269 | /// Returns a mutable reference to the inner writer. 270 | pub fn get_mut(&mut self) -> &mut W { 271 | &mut self.writer 272 | } 273 | 274 | /// Returns a pinned mutable reference to the inner writer. 275 | pub fn get_pin_mut(self: Pin<&mut Self>) -> Pin<&mut W> { 276 | self.project().writer 277 | } 278 | 279 | /// Consumes the `TimeoutWriter`, returning the inner writer. 280 | pub fn into_inner(self) -> W { 281 | self.writer 282 | } 283 | } 284 | 285 | impl AsyncWrite for TimeoutWriter 286 | where 287 | W: AsyncWrite, 288 | { 289 | fn poll_write( 290 | self: Pin<&mut Self>, 291 | cx: &mut Context, 292 | buf: &[u8], 293 | ) -> Poll> { 294 | let this = self.project(); 295 | let r = this.writer.poll_write(cx, buf); 296 | match r { 297 | Poll::Pending => this.state.poll_check(cx)?, 298 | _ => this.state.reset(), 299 | } 300 | r 301 | } 302 | 303 | fn poll_flush(self: Pin<&mut Self>, cx: &mut Context) -> Poll> { 304 | let this = self.project(); 305 | let r = this.writer.poll_flush(cx); 306 | match r { 307 | Poll::Pending => this.state.poll_check(cx)?, 308 | _ => this.state.reset(), 309 | } 310 | r 311 | } 312 | 313 | fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context) -> Poll> { 314 | let this = self.project(); 315 | let r = this.writer.poll_shutdown(cx); 316 | match r { 317 | Poll::Pending => this.state.poll_check(cx)?, 318 | _ => this.state.reset(), 319 | } 320 | r 321 | } 322 | 323 | fn poll_write_vectored( 324 | self: Pin<&mut Self>, 325 | cx: &mut Context<'_>, 326 | bufs: &[io::IoSlice<'_>], 327 | ) -> Poll> { 328 | let this = self.project(); 329 | let r = this.writer.poll_write_vectored(cx, bufs); 330 | match r { 331 | Poll::Pending => this.state.poll_check(cx)?, 332 | _ => this.state.reset(), 333 | } 334 | r 335 | } 336 | 337 | fn is_write_vectored(&self) -> bool { 338 | self.writer.is_write_vectored() 339 | } 340 | } 341 | 342 | impl AsyncRead for TimeoutWriter 343 | where 344 | W: AsyncRead, 345 | { 346 | fn poll_read( 347 | self: Pin<&mut Self>, 348 | cx: &mut Context<'_>, 349 | buf: &mut ReadBuf<'_>, 350 | ) -> Poll> { 351 | self.project().writer.poll_read(cx, buf) 352 | } 353 | } 354 | 355 | impl AsyncSeek for TimeoutWriter 356 | where 357 | W: AsyncSeek, 358 | { 359 | fn start_seek(self: Pin<&mut Self>, position: SeekFrom) -> io::Result<()> { 360 | self.project().writer.start_seek(position) 361 | } 362 | fn poll_complete(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { 363 | self.project().writer.poll_complete(cx) 364 | } 365 | } 366 | 367 | pin_project! { 368 | /// A stream which applies read and write timeouts to an inner stream. 369 | #[derive(Debug)] 370 | pub struct TimeoutStream { 371 | #[pin] 372 | stream: TimeoutReader> 373 | } 374 | } 375 | 376 | impl TimeoutStream 377 | where 378 | S: AsyncRead + AsyncWrite, 379 | { 380 | /// Returns a new `TimeoutStream` wrapping the specified stream. 381 | /// 382 | /// There is initially no read or write timeout. 383 | pub fn new(stream: S) -> TimeoutStream { 384 | let writer = TimeoutWriter::new(stream); 385 | let stream = TimeoutReader::new(writer); 386 | TimeoutStream { stream } 387 | } 388 | 389 | /// Returns the current read timeout. 390 | pub fn read_timeout(&self) -> Option { 391 | self.stream.timeout() 392 | } 393 | 394 | /// Sets the read timeout. 395 | /// 396 | /// This can only be used before the stream is pinned; use 397 | /// [`set_read_timeout_pinned`](Self::set_read_timeout_pinned) otherwise. 398 | pub fn set_read_timeout(&mut self, timeout: Option) { 399 | self.stream.set_timeout(timeout) 400 | } 401 | 402 | /// Sets the read timeout. 403 | /// 404 | /// This will reset any pending read timeout. Use [`set_read_timeout`](Self::set_read_timeout) instead if the stream 405 | /// has not yet been pinned. 406 | pub fn set_read_timeout_pinned(self: Pin<&mut Self>, timeout: Option) { 407 | self.project().stream.set_timeout_pinned(timeout) 408 | } 409 | 410 | /// Returns the current write timeout. 411 | pub fn write_timeout(&self) -> Option { 412 | self.stream.get_ref().timeout() 413 | } 414 | 415 | /// Sets the write timeout. 416 | /// 417 | /// This can only be used before the stream is pinned; use 418 | /// [`set_write_timeout_pinned`](Self::set_write_timeout_pinned) otherwise. 419 | pub fn set_write_timeout(&mut self, timeout: Option) { 420 | self.stream.get_mut().set_timeout(timeout) 421 | } 422 | 423 | /// Sets the write timeout. 424 | /// 425 | /// This will reset any pending write timeout. Use [`set_write_timeout`](Self::set_write_timeout) instead if the 426 | /// stream has not yet been pinned. 427 | pub fn set_write_timeout_pinned(self: Pin<&mut Self>, timeout: Option) { 428 | self.project() 429 | .stream 430 | .get_pin_mut() 431 | .set_timeout_pinned(timeout) 432 | } 433 | 434 | /// Returns a shared reference to the inner stream. 435 | pub fn get_ref(&self) -> &S { 436 | self.stream.get_ref().get_ref() 437 | } 438 | 439 | /// Returns a mutable reference to the inner stream. 440 | pub fn get_mut(&mut self) -> &mut S { 441 | self.stream.get_mut().get_mut() 442 | } 443 | 444 | /// Returns a pinned mutable reference to the inner stream. 445 | pub fn get_pin_mut(self: Pin<&mut Self>) -> Pin<&mut S> { 446 | self.project().stream.get_pin_mut().get_pin_mut() 447 | } 448 | 449 | /// Consumes the stream, returning the inner stream. 450 | pub fn into_inner(self) -> S { 451 | self.stream.into_inner().into_inner() 452 | } 453 | } 454 | 455 | impl AsyncRead for TimeoutStream 456 | where 457 | S: AsyncRead + AsyncWrite, 458 | { 459 | fn poll_read( 460 | self: Pin<&mut Self>, 461 | cx: &mut Context<'_>, 462 | buf: &mut ReadBuf<'_>, 463 | ) -> Poll> { 464 | self.project().stream.poll_read(cx, buf) 465 | } 466 | } 467 | 468 | impl AsyncWrite for TimeoutStream 469 | where 470 | S: AsyncRead + AsyncWrite, 471 | { 472 | fn poll_write( 473 | self: Pin<&mut Self>, 474 | cx: &mut Context, 475 | buf: &[u8], 476 | ) -> Poll> { 477 | self.project().stream.poll_write(cx, buf) 478 | } 479 | 480 | fn poll_flush(self: Pin<&mut Self>, cx: &mut Context) -> Poll> { 481 | self.project().stream.poll_flush(cx) 482 | } 483 | 484 | fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context) -> Poll> { 485 | self.project().stream.poll_shutdown(cx) 486 | } 487 | 488 | fn poll_write_vectored( 489 | self: Pin<&mut Self>, 490 | cx: &mut Context<'_>, 491 | bufs: &[io::IoSlice<'_>], 492 | ) -> Poll> { 493 | self.project().stream.poll_write_vectored(cx, bufs) 494 | } 495 | 496 | fn is_write_vectored(&self) -> bool { 497 | self.stream.is_write_vectored() 498 | } 499 | } 500 | 501 | #[cfg(test)] 502 | mod test { 503 | use super::*; 504 | use std::io::Write; 505 | use std::net::TcpListener; 506 | use std::thread; 507 | use tokio::io::{AsyncReadExt, AsyncWriteExt}; 508 | use tokio::net::TcpStream; 509 | use tokio::pin; 510 | 511 | pin_project! { 512 | struct DelayStream { 513 | #[pin] 514 | sleep: Sleep, 515 | } 516 | } 517 | 518 | impl DelayStream { 519 | fn new(until: Instant) -> Self { 520 | DelayStream { 521 | sleep: sleep_until(until), 522 | } 523 | } 524 | } 525 | 526 | impl AsyncRead for DelayStream { 527 | fn poll_read( 528 | self: Pin<&mut Self>, 529 | cx: &mut Context, 530 | _buf: &mut ReadBuf, 531 | ) -> Poll> { 532 | match self.project().sleep.poll(cx) { 533 | Poll::Ready(()) => Poll::Ready(Ok(())), 534 | Poll::Pending => Poll::Pending, 535 | } 536 | } 537 | } 538 | 539 | impl AsyncWrite for DelayStream { 540 | fn poll_write( 541 | self: Pin<&mut Self>, 542 | cx: &mut Context, 543 | buf: &[u8], 544 | ) -> Poll> { 545 | match self.project().sleep.poll(cx) { 546 | Poll::Ready(()) => Poll::Ready(Ok(buf.len())), 547 | Poll::Pending => Poll::Pending, 548 | } 549 | } 550 | 551 | fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context) -> Poll> { 552 | Poll::Ready(Ok(())) 553 | } 554 | 555 | fn poll_shutdown(self: Pin<&mut Self>, _cx: &mut Context) -> Poll> { 556 | Poll::Ready(Ok(())) 557 | } 558 | } 559 | 560 | #[tokio::test] 561 | async fn read_timeout() { 562 | let reader = DelayStream::new(Instant::now() + Duration::from_millis(500)); 563 | let mut reader = TimeoutReader::new(reader); 564 | reader.set_timeout(Some(Duration::from_millis(100))); 565 | pin!(reader); 566 | 567 | let r = reader.read(&mut [0]).await; 568 | assert_eq!(r.err().unwrap().kind(), io::ErrorKind::TimedOut); 569 | } 570 | 571 | #[tokio::test] 572 | async fn read_ok() { 573 | let reader = DelayStream::new(Instant::now() + Duration::from_millis(100)); 574 | let mut reader = TimeoutReader::new(reader); 575 | reader.set_timeout(Some(Duration::from_millis(500))); 576 | pin!(reader); 577 | 578 | reader.read(&mut [0]).await.unwrap(); 579 | } 580 | 581 | #[tokio::test] 582 | async fn write_timeout() { 583 | let writer = DelayStream::new(Instant::now() + Duration::from_millis(500)); 584 | let mut writer = TimeoutWriter::new(writer); 585 | writer.set_timeout(Some(Duration::from_millis(100))); 586 | pin!(writer); 587 | 588 | let r = writer.write(&[0]).await; 589 | assert_eq!(r.err().unwrap().kind(), io::ErrorKind::TimedOut); 590 | } 591 | 592 | #[tokio::test] 593 | async fn write_ok() { 594 | let writer = DelayStream::new(Instant::now() + Duration::from_millis(100)); 595 | let mut writer = TimeoutWriter::new(writer); 596 | writer.set_timeout(Some(Duration::from_millis(500))); 597 | pin!(writer); 598 | 599 | writer.write(&[0]).await.unwrap(); 600 | } 601 | 602 | #[tokio::test] 603 | async fn tcp_read() { 604 | let listener = TcpListener::bind("127.0.0.1:0").unwrap(); 605 | let addr = listener.local_addr().unwrap(); 606 | 607 | thread::spawn(move || { 608 | let mut socket = listener.accept().unwrap().0; 609 | thread::sleep(Duration::from_millis(10)); 610 | socket.write_all(b"f").unwrap(); 611 | thread::sleep(Duration::from_millis(500)); 612 | let _ = socket.write_all(b"f"); // this may hit an eof 613 | }); 614 | 615 | let s = TcpStream::connect(&addr).await.unwrap(); 616 | let mut s = TimeoutStream::new(s); 617 | s.set_read_timeout(Some(Duration::from_millis(100))); 618 | pin!(s); 619 | s.read(&mut [0]).await.unwrap(); 620 | let r = s.read(&mut [0]).await; 621 | 622 | match r { 623 | Ok(_) => panic!("unexpected success"), 624 | Err(ref e) if e.kind() == io::ErrorKind::TimedOut => (), 625 | Err(e) => panic!("{:?}", e), 626 | } 627 | } 628 | } 629 | --------------------------------------------------------------------------------