pax_global_header00006660000000000000000000000064145043430050014510gustar00rootroot0000000000000052 comment=c3b5e01b3ca47ee7861f0491f8681736422d109a blocking-1.4.0/000077500000000000000000000000001450434300500133025ustar00rootroot00000000000000blocking-1.4.0/.github/000077500000000000000000000000001450434300500146425ustar00rootroot00000000000000blocking-1.4.0/.github/dependabot.yml000066400000000000000000000002331450434300500174700ustar00rootroot00000000000000version: 2 updates: - package-ecosystem: cargo directory: / schedule: interval: weekly commit-message: prefix: '' labels: [] blocking-1.4.0/.github/workflows/000077500000000000000000000000001450434300500166775ustar00rootroot00000000000000blocking-1.4.0/.github/workflows/ci.yml000066400000000000000000000050531450434300500200200ustar00rootroot00000000000000name: CI permissions: contents: read on: pull_request: push: branches: - master schedule: - cron: '0 2 * * 0' env: CARGO_INCREMENTAL: 0 CARGO_NET_GIT_FETCH_WITH_CLI: true CARGO_NET_RETRY: 10 CARGO_TERM_COLOR: always RUST_BACKTRACE: 1 RUSTFLAGS: -D warnings RUSTDOCFLAGS: -D warnings RUSTUP_MAX_RETRIES: 10 defaults: run: shell: bash jobs: test: runs-on: ${{ matrix.os }} strategy: fail-fast: false matrix: os: [ubuntu-latest] rust: [nightly, beta, stable] steps: - uses: actions/checkout@v4 - name: Install Rust run: rustup update ${{ matrix.rust }} && rustup default ${{ matrix.rust }} - run: cargo build --all --all-features --all-targets - name: Run cargo check (without dev-dependencies to catch missing feature flags) if: startsWith(matrix.rust, 'nightly') run: cargo check -Z features=dev_dep - run: cargo test msrv: runs-on: ubuntu-latest strategy: matrix: # When updating this, the reminder to update the minimum supported # Rust version in Cargo.toml. rust: ['1.59'] steps: - uses: actions/checkout@v4 - name: Install Rust run: rustup update ${{ matrix.rust }} && rustup default ${{ matrix.rust }} - run: cargo build clippy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Install Rust run: rustup update stable - run: cargo clippy --all-features --all-targets fmt: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Install Rust run: rustup update stable - run: cargo fmt --all --check miri: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Install Rust run: rustup toolchain install nightly --component miri && rustup default nightly - run: cargo miri test env: # -Zmiri-ignore-leaks is needed because we use detached threads in tests/docs: https://github.com/rust-lang/miri/issues/1371 MIRIFLAGS: -Zmiri-strict-provenance -Zmiri-symbolic-alignment-check -Zmiri-disable-isolation -Zmiri-ignore-leaks RUSTFLAGS: ${{ env.RUSTFLAGS }} -Z randomize-layout security_audit: permissions: checks: write contents: read issues: write runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 # https://github.com/rustsec/audit-check/issues/2 - uses: rustsec/audit-check@master with: token: ${{ secrets.GITHUB_TOKEN }} blocking-1.4.0/.github/workflows/release.yml000066400000000000000000000006411450434300500210430ustar00rootroot00000000000000name: Release permissions: contents: write on: push: tags: - v[0-9]+.* jobs: create-release: if: github.repository_owner == 'smol-rs' runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: taiki-e/create-gh-release-action@v1 with: changelog: CHANGELOG.md branch: master env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} blocking-1.4.0/.gitignore000066400000000000000000000000231450434300500152650ustar00rootroot00000000000000/target Cargo.lock blocking-1.4.0/CHANGELOG.md000066400000000000000000000037671450434300500151300ustar00rootroot00000000000000# Version 1.4.0 - Bump MSRV to 1.59. (#44) - Remove the unused `memchr` dependency. (#38) - Extract read/write pipes into the `piper` crate, which this crate now uses. (#37) - Mark as `forbid(unsafe_code)` (#37). - Set up logging using `tracing`. (#40) # Version 1.3.1 - Gracefully handle the inability to spawn threads. (#31) # Version 1.3.0 - Remove the dependency on the `once_cell` crate to restore the MSRV. (#30) # Version 1.2.0 - Return `Task` from `unblock` instead of returning opaque type. (#25) # Version 1.1.0 - Add an environment variable to customize the maximum number of threads. (#21) # Version 1.0.2 - Update `futures-lite`. # Version 1.0.1 - Use `async-task`. # Version 1.0.0 - Stabilize. # Version 0.6.1 - Add probabilistic yielding to improve fairness. # Version 0.6.0 - Remove the `unblock!` macro. # Version 0.5.2 - Implement `Sync` for `Unblock`. # Version 0.5.1 - Add `Unblock::with_capacity()`. - Add `unblock()` function. - An optimization in task spawning. # Version 0.5.0 - Simplify the API to just `unblock!` and `Unblock`. # Version 0.4.7 - Simplify dependencies for faster compilation. # Version 0.4.6 - Update doc comment on `Unblock`. # Version 0.4.5 - Implement `AsyncSeek`/`Seek` for `Unblock`/`BlockOn`. # Version 0.4.4 - Remove the initial poll in block_on that caused lost wakeups. # Version 0.4.3 - Fix a bug where a closed `Receiver` causes panics. # Version 0.4.2 - Start thread numbering from 1. # Version 0.4.1 - Attach names to spawned threads. # Version 0.4.0 - Remove `Future` impl for `Blocking`. - Add `unblock()`. - Rename `blocking!` to `unblock!`. - Rename `Blocking` to `Unblock`. - Add `block_on()`, `block_on!`, and `BlockOn`. # Version 0.3.2 - Make `Blocking` implement `Send` in more cases. # Version 0.3.1 - Add `Blocking::with_mut()`. # Version 0.3.0 - Remove `Blocking::spawn()`. - Implement `Future` for `Blocking` only when the inner type is a `FnOnce`. # Version 0.2.0 - Initial version # Version 0.1.0 - Reserved crate name blocking-1.4.0/Cargo.toml000066400000000000000000000015401450434300500152320ustar00rootroot00000000000000[package] name = "blocking" # When publishing a new version: # - Update CHANGELOG.md # - Create "v1.x.y" git tag version = "1.4.0" authors = ["Stjepan Glavina "] edition = "2018" rust-version = "1.59" description = "A thread pool for isolating blocking I/O in async programs" license = "Apache-2.0 OR MIT" repository = "https://github.com/smol-rs/blocking" keywords = ["async", "file", "stdio", "stdin", "process"] categories = ["asynchronous", "concurrency"] exclude = ["/.*"] [dependencies] async-channel = "1.4.0" async-lock = "2.6.0" async-task = "4.0.2" fastrand = "2.0.0" futures-io = { version = "0.3.28", default-features = false, features = ["std"] } futures-lite = { version = "1.11.0", default-features = false } piper = "0.2.0" tracing = { version = "0.1.37", default-features = false } [dev-dependencies] futures-lite = "1.11.0" blocking-1.4.0/LICENSE-APACHE000066400000000000000000000251371450434300500152360ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. blocking-1.4.0/LICENSE-MIT000066400000000000000000000017771450434300500147520ustar00rootroot00000000000000Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. blocking-1.4.0/README.md000066400000000000000000000055421450434300500145670ustar00rootroot00000000000000# blocking [![Build](https://github.com/smol-rs/blocking/workflows/Build%20and%20test/badge.svg)]( https://github.com/smol-rs/blocking/actions) [![License](https://img.shields.io/badge/license-Apache--2.0_OR_MIT-blue.svg)]( https://github.com/smol-rs/blocking) [![Cargo](https://img.shields.io/crates/v/blocking.svg)]( https://crates.io/crates/blocking) [![Documentation](https://docs.rs/blocking/badge.svg)]( https://docs.rs/blocking) A thread pool for isolating blocking I/O in async programs. Sometimes there's no way to avoid blocking I/O. Consider files or stdin, which have weak async support on modern operating systems. While [IOCP], [AIO], and [io_uring] are possible solutions, they're not always available or ideal. Since blocking is not allowed inside futures, we must move blocking I/O onto a special thread pool provided by this crate. The pool dynamically spawns and stops threads depending on the current number of running I/O jobs. Note that there is a limit on the number of active threads. Once that limit is hit, a running job has to finish before others get a chance to run. When a thread is idle, it waits for the next job or shuts down after a certain timeout. The default number of threads (set to 500) can be altered by setting BLOCKING_MAX_THREADS environment variable with value between 1 and 10000. [IOCP]: https://en.wikipedia.org/wiki/Input/output_completion_port [AIO]: http://man7.org/linux/man-pages/man2/io_submit.2.html [io_uring]: https://lwn.net/Articles/776703 ## Examples Read the contents of a file: ```rust use blocking::unblock; use std::fs; let contents = unblock(|| fs::read_to_string("file.txt")).await?; println!("{}", contents); ``` Read a file and pipe its contents to stdout: ```rust use blocking::{unblock, Unblock}; use futures_lite::io; use std::fs::File; let input = unblock(|| File::open("file.txt")).await?; let input = Unblock::new(input); let mut output = Unblock::new(std::io::stdout()); io::copy(input, &mut output).await?; ``` Iterate over the contents of a directory: ```rust use blocking::Unblock; use futures_lite::prelude::*; use std::fs; let mut dir = Unblock::new(fs::read_dir(".")?); while let Some(item) = dir.next().await { println!("{}", item?.file_name().to_string_lossy()); } ``` Spawn a process: ```rust use blocking::unblock; use std::process::Command; let out = unblock(|| Command::new("dir").output()).await?; ``` ## License Licensed under either of * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) at your option. #### Contribution Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. blocking-1.4.0/examples/000077500000000000000000000000001450434300500151205ustar00rootroot00000000000000blocking-1.4.0/examples/ls.rs000066400000000000000000000010151450434300500161010ustar00rootroot00000000000000//! Lists contents of a directory. //! //! Run with: //! //! ``` //! cargo run --example ls . //! ``` use std::{env, fs, io}; use blocking::Unblock; use futures_lite::{future, prelude::*}; fn main() -> io::Result<()> { let path = env::args().nth(1).unwrap_or_else(|| ".".into()); future::block_on(async { let mut dir = Unblock::new(fs::read_dir(path)?); while let Some(item) = dir.next().await { println!("{}", item?.file_name().to_string_lossy()); } Ok(()) }) } blocking-1.4.0/src/000077500000000000000000000000001450434300500140715ustar00rootroot00000000000000blocking-1.4.0/src/lib.rs000066400000000000000000001055121450434300500152110ustar00rootroot00000000000000//! A thread pool for isolating blocking I/O in async programs. //! //! Sometimes there's no way to avoid blocking I/O. Consider files or stdin, which have weak async //! support on modern operating systems. While [IOCP], [AIO], and [io_uring] are possible //! solutions, they're not always available or ideal. //! //! Since blocking is not allowed inside futures, we must move blocking I/O onto a special thread //! pool provided by this crate. The pool dynamically spawns and stops threads depending on the //! current number of running I/O jobs. //! //! Note that there is a limit on the number of active threads. Once that limit is hit, a running //! job has to finish before others get a chance to run. When a thread is idle, it waits for the //! next job or shuts down after a certain timeout. //! //! The default number of threads (set to 500) can be altered by setting BLOCKING_MAX_THREADS environment //! variable with value between 1 and 10000. //! //! [IOCP]: https://en.wikipedia.org/wiki/Input/output_completion_port //! [AIO]: http://man7.org/linux/man-pages/man2/io_submit.2.html //! [io_uring]: https://lwn.net/Articles/776703 //! //! # Examples //! //! Read the contents of a file: //! //! ```no_run //! use blocking::unblock; //! use std::fs; //! //! # futures_lite::future::block_on(async { //! let contents = unblock(|| fs::read_to_string("file.txt")).await?; //! println!("{}", contents); //! # std::io::Result::Ok(()) }); //! ``` //! //! Read a file and pipe its contents to stdout: //! //! ```no_run //! use blocking::{unblock, Unblock}; //! use futures_lite::io; //! use std::fs::File; //! //! # futures_lite::future::block_on(async { //! let input = unblock(|| File::open("file.txt")).await?; //! let input = Unblock::new(input); //! let mut output = Unblock::new(std::io::stdout()); //! //! io::copy(input, &mut output).await?; //! # std::io::Result::Ok(()) }); //! ``` //! //! Iterate over the contents of a directory: //! //! ```no_run //! use blocking::Unblock; //! use futures_lite::prelude::*; //! use std::fs; //! //! # futures_lite::future::block_on(async { //! let mut dir = Unblock::new(fs::read_dir(".")?); //! while let Some(item) = dir.next().await { //! println!("{}", item?.file_name().to_string_lossy()); //! } //! # std::io::Result::Ok(()) }); //! ``` //! //! Spawn a process: //! //! ```no_run //! use blocking::unblock; //! use std::process::Command; //! //! # futures_lite::future::block_on(async { //! let out = unblock(|| Command::new("dir").output()).await?; //! # std::io::Result::Ok(()) }); //! ``` #![warn(missing_docs, missing_debug_implementations, rust_2018_idioms)] #![forbid(unsafe_code)] #![doc( html_favicon_url = "https://raw.githubusercontent.com/smol-rs/smol/master/assets/images/logo_fullsize_transparent.png" )] #![doc( html_logo_url = "https://raw.githubusercontent.com/smol-rs/smol/master/assets/images/logo_fullsize_transparent.png" )] use std::any::Any; use std::collections::VecDeque; use std::env; use std::fmt; use std::io::{self, Read, Seek, SeekFrom, Write}; use std::num::NonZeroUsize; use std::panic; use std::pin::Pin; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{Condvar, Mutex, MutexGuard}; use std::task::{Context, Poll}; use std::thread; use std::time::Duration; use async_channel::{bounded, Receiver}; use async_lock::OnceCell; use async_task::Runnable; use futures_io::{AsyncRead, AsyncSeek, AsyncWrite}; use futures_lite::{future, prelude::*, ready}; use piper::{pipe, Reader, Writer}; #[doc(no_inline)] pub use async_task::Task; /// Default value for max threads that Executor can grow to const DEFAULT_MAX_THREADS: usize = 500; /// Minimum value for max threads config const MIN_MAX_THREADS: usize = 1; /// Maximum value for max threads config const MAX_MAX_THREADS: usize = 10000; /// Env variable that allows to override default value for max threads. const MAX_THREADS_ENV: &str = "BLOCKING_MAX_THREADS"; /// The blocking executor. struct Executor { /// Inner state of the executor. inner: Mutex, /// Used to put idle threads to sleep and wake them up when new work comes in. cvar: Condvar, } /// Inner state of the blocking executor. struct Inner { /// Number of idle threads in the pool. /// /// Idle threads are sleeping, waiting to get a task to run. idle_count: usize, /// Total number of threads in the pool. /// /// This is the number of idle threads + the number of active threads. thread_count: usize, /// The queue of blocking tasks. queue: VecDeque, /// Maximum number of threads in the pool thread_limit: NonZeroUsize, } impl Executor { fn max_threads() -> usize { match env::var(MAX_THREADS_ENV) { Ok(v) => v .parse::() .map(|v| v.max(MIN_MAX_THREADS).min(MAX_MAX_THREADS)) .unwrap_or(DEFAULT_MAX_THREADS), Err(_) => DEFAULT_MAX_THREADS, } } /// Spawns a future onto this executor. /// /// Returns a [`Task`] handle for the spawned task. fn spawn(future: impl Future + Send + 'static) -> Task { static EXECUTOR: OnceCell = OnceCell::new(); let (runnable, task) = async_task::spawn(future, |r| { // Initialize the executor if we haven't already. let executor = EXECUTOR.get_or_init_blocking(|| { let thread_limit = Self::max_threads(); Executor { inner: Mutex::new(Inner { idle_count: 0, thread_count: 0, queue: VecDeque::new(), thread_limit: NonZeroUsize::new(thread_limit).unwrap(), }), cvar: Condvar::new(), } }); // Schedule the task on our executor. executor.schedule(r) }); runnable.schedule(); task } /// Runs the main loop on the current thread. /// /// This function runs blocking tasks until it becomes idle and times out. fn main_loop(&'static self) { let span = tracing::trace_span!("blocking::main_loop"); let _enter = span.enter(); let mut inner = self.inner.lock().unwrap(); loop { // This thread is not idle anymore because it's going to run tasks. inner.idle_count -= 1; // Run tasks in the queue. while let Some(runnable) = inner.queue.pop_front() { // We have found a task - grow the pool if needed. self.grow_pool(inner); // Run the task. panic::catch_unwind(|| runnable.run()).ok(); // Re-lock the inner state and continue. inner = self.inner.lock().unwrap(); } // This thread is now becoming idle. inner.idle_count += 1; // Put the thread to sleep until another task is scheduled. let timeout = Duration::from_millis(500); tracing::trace!(?timeout, "going to sleep"); let (lock, res) = self.cvar.wait_timeout(inner, timeout).unwrap(); inner = lock; // If there are no tasks after a while, stop this thread. if res.timed_out() && inner.queue.is_empty() { inner.idle_count -= 1; inner.thread_count -= 1; break; } tracing::trace!("notified"); } tracing::trace!("shutting down due to lack of tasks"); } /// Schedules a runnable task for execution. fn schedule(&'static self, runnable: Runnable) { let mut inner = self.inner.lock().unwrap(); inner.queue.push_back(runnable); // Notify a sleeping thread and spawn more threads if needed. self.cvar.notify_one(); self.grow_pool(inner); } /// Spawns more blocking threads if the pool is overloaded with work. fn grow_pool(&'static self, mut inner: MutexGuard<'static, Inner>) { let span = tracing::error_span!( "grow_pool", queue_len = inner.queue.len(), idle_count = inner.idle_count, thread_count = inner.thread_count, ); let _enter = span.enter(); // If runnable tasks greatly outnumber idle threads and there aren't too many threads // already, then be aggressive: wake all idle threads and spawn one more thread. while inner.queue.len() > inner.idle_count * 5 && inner.thread_count < inner.thread_limit.get() { tracing::trace!("spawning a new thread to handle blocking tasks"); // The new thread starts in idle state. inner.idle_count += 1; inner.thread_count += 1; // Notify all existing idle threads because we need to hurry up. self.cvar.notify_all(); // Generate a new thread ID. static ID: AtomicUsize = AtomicUsize::new(1); let id = ID.fetch_add(1, Ordering::Relaxed); // Spawn the new thread. if let Err(e) = thread::Builder::new() .name(format!("blocking-{}", id)) .spawn(move || self.main_loop()) { // We were unable to spawn the thread, so we need to undo the state changes. tracing::error!("failed to spawn a blocking thread: {}", e); inner.idle_count -= 1; inner.thread_count -= 1; // The current number of threads is likely to be the system's upper limit, so update // thread_limit accordingly. inner.thread_limit = { let new_limit = inner.thread_count; // If the limit is about to be set to zero, set it to one instead so that if, // in the future, we are able to spawn more threads, we will be able to do so. NonZeroUsize::new(new_limit).unwrap_or_else(|| { tracing::warn!( "attempted to lower thread_limit to zero; setting to one instead" ); NonZeroUsize::new(1).unwrap() }) }; } } } } /// Runs blocking code on a thread pool. /// /// # Examples /// /// Read the contents of a file: /// /// ```no_run /// use blocking::unblock; /// use std::fs; /// /// # futures_lite::future::block_on(async { /// let contents = unblock(|| fs::read_to_string("file.txt")).await?; /// # std::io::Result::Ok(()) }); /// ``` /// /// Spawn a process: /// /// ```no_run /// use blocking::unblock; /// use std::process::Command; /// /// # futures_lite::future::block_on(async { /// let out = unblock(|| Command::new("dir").output()).await?; /// # std::io::Result::Ok(()) }); /// ``` pub fn unblock(f: F) -> Task where F: FnOnce() -> T + Send + 'static, T: Send + 'static, { Executor::spawn(async move { f() }) } /// Runs blocking I/O on a thread pool. /// /// Blocking I/O must be isolated from async code. This type moves blocking I/O operations onto a /// special thread pool while exposing a familiar async interface. /// /// This type implements traits [`Stream`], [`AsyncRead`], [`AsyncWrite`], or [`AsyncSeek`] if the /// inner type implements [`Iterator`], [`Read`], [`Write`], or [`Seek`], respectively. /// /// # Caveats /// /// [`Unblock`] is a low-level primitive, and as such it comes with some caveats. /// /// For higher-level primitives built on top of [`Unblock`], look into [`async-fs`] or /// [`async-process`] (on Windows). /// /// [`async-fs`]: https://github.com/smol-rs/async-fs /// [`async-process`]: https://github.com/smol-rs/async-process /// /// [`Unblock`] communicates with I/O operations on the thread pool through a pipe. That means an /// async read/write operation simply receives/sends some bytes from/into the pipe. When in reading /// mode, the thread pool reads bytes from the I/O handle and forwards them into the pipe until it /// becomes full. When in writing mode, the thread pool reads bytes from the pipe and forwards them /// into the I/O handle. /// /// Use [`Unblock::with_capacity()`] to configure the capacity of the pipe. /// /// ### Reading /// /// If you create an [`Unblock`]`<`[`Stdin`][`std::io::Stdin`]`>`, read some bytes from it, /// and then drop it, a blocked read operation may keep hanging on the thread pool. The next /// attempt to read from stdin will lose bytes read by the hanging operation. This is a difficult /// problem to solve, so make sure you only use a single stdin handle for the duration of the /// entire program. /// /// ### Writing /// /// If writing data through the [`AsyncWrite`] trait, make sure to flush before dropping the /// [`Unblock`] handle or some buffered data might get lost. /// /// ### Seeking /// /// Because of buffering in the pipe, if [`Unblock`] wraps a [`File`][`std::fs::File`], a single /// read operation may move the file cursor farther than is the span of the operation. In fact, /// reading just keeps going in the background until the pipe gets full. Keep this mind when /// using [`AsyncSeek`] with [relative][`SeekFrom::Current`] offsets. /// /// # Examples /// /// ``` /// use blocking::Unblock; /// use futures_lite::prelude::*; /// /// # futures_lite::future::block_on(async { /// let mut stdout = Unblock::new(std::io::stdout()); /// stdout.write_all(b"Hello world!").await?; /// stdout.flush().await?; /// # std::io::Result::Ok(()) }); /// ``` pub struct Unblock { state: State, cap: Option, } impl Unblock { /// Wraps a blocking I/O handle into the async [`Unblock`] interface. /// /// # Examples /// /// ```no_run /// use blocking::Unblock; /// /// let stdin = Unblock::new(std::io::stdin()); /// ``` pub fn new(io: T) -> Unblock { Unblock { state: State::Idle(Some(Box::new(io))), cap: None, } } /// Wraps a blocking I/O handle into the async [`Unblock`] interface with a custom buffer /// capacity. /// /// When communicating with the inner [`Stream`]/[`Read`]/[`Write`] type from async code, data /// transferred between blocking and async code goes through a buffer of limited capacity. This /// constructor configures that capacity. /// /// The default capacity is: /// /// * For [`Iterator`] types: 8192 items. /// * For [`Read`]/[`Write`] types: 8 MB. /// /// # Examples /// /// ```no_run /// use blocking::Unblock; /// /// let stdout = Unblock::with_capacity(64 * 1024, std::io::stdout()); /// ``` pub fn with_capacity(cap: usize, io: T) -> Unblock { Unblock { state: State::Idle(Some(Box::new(io))), cap: Some(cap), } } /// Gets a mutable reference to the blocking I/O handle. /// /// This is an async method because the I/O handle might be on the thread pool and needs to /// be moved onto the current thread before we can get a reference to it. /// /// # Examples /// /// ```no_run /// use blocking::{unblock, Unblock}; /// use std::fs::File; /// /// # futures_lite::future::block_on(async { /// let file = unblock(|| File::create("file.txt")).await?; /// let mut file = Unblock::new(file); /// /// let metadata = file.get_mut().await.metadata()?; /// # std::io::Result::Ok(()) }); /// ``` pub async fn get_mut(&mut self) -> &mut T { // Wait for the running task to stop and ignore I/O errors if there are any. future::poll_fn(|cx| self.poll_stop(cx)).await.ok(); // Assume idle state and get a reference to the inner value. match &mut self.state { State::Idle(t) => t.as_mut().expect("inner value was taken out"), State::WithMut(..) | State::Streaming(..) | State::Reading(..) | State::Writing(..) | State::Seeking(..) => { unreachable!("when stopped, the state machine must be in idle state"); } } } /// Performs a blocking operation on the I/O handle. /// /// # Examples /// /// ```no_run /// use blocking::{unblock, Unblock}; /// use std::fs::File; /// /// # futures_lite::future::block_on(async { /// let file = unblock(|| File::create("file.txt")).await?; /// let mut file = Unblock::new(file); /// /// let metadata = file.with_mut(|f| f.metadata()).await?; /// # std::io::Result::Ok(()) }); /// ``` pub async fn with_mut(&mut self, op: F) -> R where F: FnOnce(&mut T) -> R + Send + 'static, R: Send + 'static, T: Send + 'static, { // Wait for the running task to stop and ignore I/O errors if there are any. future::poll_fn(|cx| self.poll_stop(cx)).await.ok(); // Assume idle state and take out the inner value. let mut t = match &mut self.state { State::Idle(t) => t.take().expect("inner value was taken out"), State::WithMut(..) | State::Streaming(..) | State::Reading(..) | State::Writing(..) | State::Seeking(..) => { unreachable!("when stopped, the state machine must be in idle state"); } }; let (sender, receiver) = bounded(1); let task = Executor::spawn(async move { sender.try_send(op(&mut t)).ok(); t }); self.state = State::WithMut(task); receiver .recv() .await .expect("`Unblock::with_mut()` operation has panicked") } /// Extracts the inner blocking I/O handle. /// /// This is an async method because the I/O handle might be on the thread pool and needs to /// be moved onto the current thread before we can extract it. /// /// # Examples /// /// ```no_run /// use blocking::{unblock, Unblock}; /// use futures_lite::prelude::*; /// use std::fs::File; /// /// # futures_lite::future::block_on(async { /// let file = unblock(|| File::create("file.txt")).await?; /// let file = Unblock::new(file); /// /// let file = file.into_inner().await; /// # std::io::Result::Ok(()) }); /// ``` pub async fn into_inner(self) -> T { // There's a bug in rustdoc causing it to render `mut self` as `__arg0: Self`, so we just // bind `self` to a local mutable variable. let mut this = self; // Wait for the running task to stop and ignore I/O errors if there are any. future::poll_fn(|cx| this.poll_stop(cx)).await.ok(); // Assume idle state and extract the inner value. match &mut this.state { State::Idle(t) => *t.take().expect("inner value was taken out"), State::WithMut(..) | State::Streaming(..) | State::Reading(..) | State::Writing(..) | State::Seeking(..) => { unreachable!("when stopped, the state machine must be in idle state"); } } } /// Waits for the running task to stop. /// /// On success, the state machine is moved into the idle state. fn poll_stop(&mut self, cx: &mut Context<'_>) -> Poll> { loop { match &mut self.state { State::Idle(_) => return Poll::Ready(Ok(())), State::WithMut(task) => { // Poll the task to wait for it to finish. let io = ready!(Pin::new(task).poll(cx)); self.state = State::Idle(Some(io)); } State::Streaming(any, task) => { // Drop the receiver to close the channel. This stops the `send()` operation in // the task, after which the task returns the iterator back. any.take(); // Poll the task to retrieve the iterator. let iter = ready!(Pin::new(task).poll(cx)); self.state = State::Idle(Some(iter)); } State::Reading(reader, task) => { // Drop the reader to close the pipe. This stops copying inside the task, after // which the task returns the I/O handle back. reader.take(); // Poll the task to retrieve the I/O handle. let (res, io) = ready!(Pin::new(task).poll(cx)); // Make sure to move into the idle state before reporting errors. self.state = State::Idle(Some(io)); res?; } State::Writing(writer, task) => { // Drop the writer to close the pipe. This stops copying inside the task, after // which the task flushes the I/O handle and writer.take(); // Poll the task to retrieve the I/O handle. let (res, io) = ready!(Pin::new(task).poll(cx)); // Make sure to move into the idle state before reporting errors. self.state = State::Idle(Some(io)); res?; } State::Seeking(task) => { // Poll the task to wait for it to finish. let (_, res, io) = ready!(Pin::new(task).poll(cx)); // Make sure to move into the idle state before reporting errors. self.state = State::Idle(Some(io)); res?; } } } } } impl fmt::Debug for Unblock { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { struct Closed; impl fmt::Debug for Closed { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("") } } struct Blocked; impl fmt::Debug for Blocked { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("") } } match &self.state { State::Idle(None) => f.debug_struct("Unblock").field("io", &Closed).finish(), State::Idle(Some(io)) => { let io: &T = io; f.debug_struct("Unblock").field("io", io).finish() } State::WithMut(..) | State::Streaming(..) | State::Reading(..) | State::Writing(..) | State::Seeking(..) => f.debug_struct("Unblock").field("io", &Blocked).finish(), } } } /// Current state of a blocking task. enum State { /// There is no blocking task. /// /// The inner value is readily available, unless it has already been extracted. The value is /// extracted out by [`Unblock::into_inner()`], [`AsyncWrite::poll_close()`], or by awaiting /// [`Unblock`]. Idle(Option>), /// A [`Unblock::with_mut()`] closure was spawned and is still running. WithMut(Task>), /// The inner value is an [`Iterator`] currently iterating in a task. /// /// The `dyn Any` value here is a `mpsc::Receiver<::Item>`. Streaming(Option>, Task>), /// The inner value is a [`Read`] currently reading in a task. Reading(Option, Task<(io::Result<()>, Box)>), /// The inner value is a [`Write`] currently writing in a task. Writing(Option, Task<(io::Result<()>, Box)>), /// The inner value is a [`Seek`] currently seeking in a task. Seeking(Task<(SeekFrom, io::Result, Box)>), } impl Stream for Unblock where T::Item: Send + 'static, { type Item = T::Item; fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { loop { match &mut self.state { // If not in idle or active streaming state, stop the running task. State::WithMut(..) | State::Streaming(None, _) | State::Reading(..) | State::Writing(..) | State::Seeking(..) => { // Wait for the running task to stop. ready!(self.poll_stop(cx)).ok(); } // If idle, start a streaming task. State::Idle(iter) => { // Take the iterator out to run it on a blocking task. let mut iter = iter.take().expect("inner iterator was taken out"); // This channel capacity seems to work well in practice. If it's too low, there // will be too much synchronization between tasks. If too high, memory // consumption increases. let (sender, receiver) = bounded(self.cap.unwrap_or(8 * 1024)); // 8192 items // Spawn a blocking task that runs the iterator and returns it when done. let task = Executor::spawn(async move { for item in &mut iter { if sender.send(item).await.is_err() { break; } } iter }); // Move into the busy state and poll again. self.state = State::Streaming(Some(Box::new(receiver)), task); } // If streaming, receive an item. State::Streaming(Some(any), task) => { let receiver = any.downcast_mut::>().unwrap(); // Poll the channel. let opt = ready!(Pin::new(receiver).poll_next(cx)); // If the channel is closed, retrieve the iterator back from the blocking task. // This is not really a required step, but it's cleaner to drop the iterator on // the same thread that created it. if opt.is_none() { // Poll the task to retrieve the iterator. let iter = ready!(Pin::new(task).poll(cx)); self.state = State::Idle(Some(iter)); } return Poll::Ready(opt); } } } } } impl AsyncRead for Unblock { fn poll_read( mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut [u8], ) -> Poll> { loop { match &mut self.state { // If not in idle or active reading state, stop the running task. State::WithMut(..) | State::Reading(None, _) | State::Streaming(..) | State::Writing(..) | State::Seeking(..) => { // Wait for the running task to stop. ready!(self.poll_stop(cx))?; } // If idle, start a reading task. State::Idle(io) => { // Take the I/O handle out to read it on a blocking task. let mut io = io.take().expect("inner value was taken out"); // This pipe capacity seems to work well in practice. If it's too low, there // will be too much synchronization between tasks. If too high, memory // consumption increases. let (reader, mut writer) = pipe(self.cap.unwrap_or(8 * 1024 * 1024)); // 8 MB // Spawn a blocking task that reads and returns the I/O handle when done. let task = Executor::spawn(async move { // Copy bytes from the I/O handle into the pipe until the pipe is closed or // an error occurs. loop { match future::poll_fn(|cx| writer.poll_fill(cx, &mut io)).await { Ok(0) => return (Ok(()), io), Ok(_) => {} Err(err) => return (Err(err), io), } } }); // Move into the busy state and poll again. self.state = State::Reading(Some(reader), task); } // If reading, read bytes from the pipe. State::Reading(Some(reader), task) => { // Poll the pipe. let n = ready!(reader.poll_drain(cx, buf))?; // If the pipe is closed, retrieve the I/O handle back from the blocking task. // This is not really a required step, but it's cleaner to drop the handle on // the same thread that created it. if n == 0 { // Poll the task to retrieve the I/O handle. let (res, io) = ready!(Pin::new(task).poll(cx)); // Make sure to move into the idle state before reporting errors. self.state = State::Idle(Some(io)); res?; } return Poll::Ready(Ok(n)); } } } } } impl AsyncWrite for Unblock { fn poll_write( mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8], ) -> Poll> { loop { match &mut self.state { // If not in idle or active writing state, stop the running task. State::WithMut(..) | State::Writing(None, _) | State::Streaming(..) | State::Reading(..) | State::Seeking(..) => { // Wait for the running task to stop. ready!(self.poll_stop(cx))?; } // If idle, start the writing task. State::Idle(io) => { // Take the I/O handle out to write on a blocking task. let mut io = io.take().expect("inner value was taken out"); // This pipe capacity seems to work well in practice. If it's too low, there will // be too much synchronization between tasks. If too high, memory consumption // increases. let (mut reader, writer) = pipe(self.cap.unwrap_or(8 * 1024 * 1024)); // 8 MB // Spawn a blocking task that writes and returns the I/O handle when done. let task = Executor::spawn(async move { // Copy bytes from the pipe into the I/O handle until the pipe is closed or an // error occurs. Flush the I/O handle at the end. loop { match future::poll_fn(|cx| reader.poll_drain(cx, &mut io)).await { Ok(0) => return (io.flush(), io), Ok(_) => {} Err(err) => { io.flush().ok(); return (Err(err), io); } } } }); // Move into the busy state and poll again. self.state = State::Writing(Some(writer), task); } // If writing, write more bytes into the pipe. State::Writing(Some(writer), _) => return writer.poll_fill(cx, buf), } } } fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { loop { match &mut self.state { // If not in idle state, stop the running task. State::WithMut(..) | State::Streaming(..) | State::Writing(..) | State::Reading(..) | State::Seeking(..) => { // Wait for the running task to stop. ready!(self.poll_stop(cx))?; } // Idle implies flushed. State::Idle(_) => return Poll::Ready(Ok(())), } } } fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { // First, make sure the I/O handle is flushed. ready!(Pin::new(&mut self).poll_flush(cx))?; // Then move into the idle state with no I/O handle, thus dropping it. self.state = State::Idle(None); Poll::Ready(Ok(())) } } impl AsyncSeek for Unblock { fn poll_seek( mut self: Pin<&mut Self>, cx: &mut Context<'_>, pos: SeekFrom, ) -> Poll> { loop { match &mut self.state { // If not in idle state, stop the running task. State::WithMut(..) | State::Streaming(..) | State::Reading(..) | State::Writing(..) => { // Wait for the running task to stop. ready!(self.poll_stop(cx))?; } State::Idle(io) => { // Take the I/O handle out to seek on a blocking task. let mut io = io.take().expect("inner value was taken out"); let task = Executor::spawn(async move { let res = io.seek(pos); (pos, res, io) }); self.state = State::Seeking(task); } State::Seeking(task) => { // Poll the task to wait for it to finish. let (original_pos, res, io) = ready!(Pin::new(task).poll(cx)); // Make sure to move into the idle state before reporting errors. self.state = State::Idle(Some(io)); let current = res?; // If the `pos` argument matches the original one, return the result. if original_pos == pos { return Poll::Ready(Ok(current)); } } } } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_max_threads() { // properly set env var env::set_var(MAX_THREADS_ENV, "100"); assert_eq!(100, Executor::max_threads()); // passed value below minimum, so we set it to minimum env::set_var(MAX_THREADS_ENV, "0"); assert_eq!(1, Executor::max_threads()); // passed value above maximum, so we set to allowed maximum env::set_var(MAX_THREADS_ENV, "50000"); assert_eq!(10000, Executor::max_threads()); // no env var, use default env::set_var(MAX_THREADS_ENV, ""); assert_eq!(500, Executor::max_threads()); // not a number, use default env::set_var(MAX_THREADS_ENV, "NOTINT"); assert_eq!(500, Executor::max_threads()); } } blocking-1.4.0/tests/000077500000000000000000000000001450434300500144445ustar00rootroot00000000000000blocking-1.4.0/tests/unblock.rs000066400000000000000000000045641450434300500164600ustar00rootroot00000000000000#![allow(clippy::needless_range_loop)] use std::io::{Cursor, SeekFrom}; use std::sync::mpsc; use std::thread; use std::time::{Duration, Instant}; use blocking::{unblock, Unblock}; use futures_lite::{future, pin, prelude::*}; #[test] fn sleep() { let dur = Duration::from_secs(1); let start = Instant::now(); future::block_on(async { let f = unblock(move || thread::sleep(dur)); pin!(f); assert!(future::poll_once(&mut f).await.is_none()); f.await; }); assert!(start.elapsed() >= dur); } #[test] fn chan() { const N: i32 = if cfg!(miri) { 50 } else { 100_000 }; future::block_on(async { let (s, r) = mpsc::sync_channel::(100); let handle = thread::spawn(move || { for i in 0..N { s.send(i).unwrap(); } }); let mut r = Unblock::new(r.into_iter()); for i in 0..N { assert_eq!(r.next().await, Some(i)); } handle.join().unwrap(); assert!(r.next().await.is_none()); }) } #[test] fn read() { const N: usize = if cfg!(miri) { 20_000 } else { 20_000_000 }; future::block_on(async { let mut v1 = vec![0u8; N]; for i in 0..v1.len() { v1[i] = i as u8; } let mut v1 = Unblock::new(Cursor::new(v1)); let mut v2 = vec![]; v1.read_to_end(&mut v2).await.unwrap(); let v1 = v1.into_inner().await.into_inner(); assert!(v1 == v2); }) } #[test] fn write() { const N: usize = if cfg!(miri) { 20_000 } else { 20_000_000 }; future::block_on(async { let mut v1 = vec![0u8; N]; for i in 0..v1.len() { v1[i] = i as u8; } let v2 = vec![]; let mut v2 = Unblock::new(Cursor::new(v2)); v2.write_all(&v1).await.unwrap(); let v2 = v2.into_inner().await.into_inner(); assert!(v1 == v2); }) } #[test] fn seek() { future::block_on(async { let len = 1_000; let mut v = vec![0u8; len]; for i in 0..len { v[i] = i as u8; } let mut v = Unblock::new(Cursor::new(v)); assert_eq!(v.seek(SeekFrom::Current(7i64)).await.unwrap(), 7); assert_eq!(v.seek(SeekFrom::Current(8i64)).await.unwrap(), 15); let mut byte = [0u8]; v.read(&mut byte).await.unwrap(); assert_eq!(byte[0], 15); }) }