forked from mirror/async-std
Compare commits
1 commit
master
...
split-by-p
Author | SHA1 | Date | |
---|---|---|---|
|
91104336fc |
101 changed files with 2266 additions and 2312 deletions
88
.github/workflows/ci.yml
vendored
88
.github/workflows/ci.yml
vendored
|
@ -29,24 +29,6 @@ jobs:
|
||||||
toolchain: ${{ matrix.rust }}
|
toolchain: ${{ matrix.rust }}
|
||||||
override: true
|
override: true
|
||||||
|
|
||||||
- name: Cache cargo registry
|
|
||||||
uses: actions/cache@v2
|
|
||||||
with:
|
|
||||||
path: ~/.cargo/registry
|
|
||||||
key: ${{ matrix.os }}-${{ matrix.rust }}-cargo-registry-${{ hashFiles('**/Cargo.toml') }}
|
|
||||||
|
|
||||||
- name: Cache cargo index
|
|
||||||
uses: actions/cache@v2
|
|
||||||
with:
|
|
||||||
path: ~/.cargo/git
|
|
||||||
key: ${{ matrix.os }}-${{ matrix.rust }}-cargo-index-${{ hashFiles('**/Cargo.toml') }}
|
|
||||||
|
|
||||||
- name: Cache cargo build
|
|
||||||
uses: actions/cache@v2
|
|
||||||
with:
|
|
||||||
path: target
|
|
||||||
key: ${{ matrix.os }}-${{ matrix.rust }}-cargo-build-target-${{ hashFiles('**/Cargo.toml') }}
|
|
||||||
|
|
||||||
- name: check
|
- name: check
|
||||||
uses: actions-rs/cargo@v1
|
uses: actions-rs/cargo@v1
|
||||||
with:
|
with:
|
||||||
|
@ -59,14 +41,6 @@ jobs:
|
||||||
command: check
|
command: check
|
||||||
args: --features unstable --all --bins --examples --tests
|
args: --features unstable --all --bins --examples --tests
|
||||||
|
|
||||||
- name: check wasm
|
|
||||||
uses: actions-rs/cargo@v1
|
|
||||||
with:
|
|
||||||
command: check
|
|
||||||
target: wasm32-unknown-unknown
|
|
||||||
override: true
|
|
||||||
args: --features unstable --all --bins --tests
|
|
||||||
|
|
||||||
- name: check bench
|
- name: check bench
|
||||||
uses: actions-rs/cargo@v1
|
uses: actions-rs/cargo@v1
|
||||||
if: matrix.rust == 'nightly'
|
if: matrix.rust == 'nightly'
|
||||||
|
@ -92,6 +66,12 @@ jobs:
|
||||||
command: test
|
command: test
|
||||||
args: --all --features "unstable attributes"
|
args: --all --features "unstable attributes"
|
||||||
|
|
||||||
|
- name: documentation test
|
||||||
|
uses: actions-rs/cargo@v1
|
||||||
|
with:
|
||||||
|
command: test
|
||||||
|
args: --doc --features "unstable attributes"
|
||||||
|
|
||||||
build__with_no_std:
|
build__with_no_std:
|
||||||
name: Build with no-std
|
name: Build with no-std
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
@ -110,50 +90,6 @@ jobs:
|
||||||
command: check
|
command: check
|
||||||
args: --no-default-features --features alloc --target thumbv7m-none-eabi -Z avoid-dev-deps
|
args: --no-default-features --features alloc --target thumbv7m-none-eabi -Z avoid-dev-deps
|
||||||
|
|
||||||
check_tokio_02_feature:
|
|
||||||
name: Check tokio02 feature
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@master
|
|
||||||
- name: check tokio02
|
|
||||||
uses: actions-rs/cargo@v1
|
|
||||||
with:
|
|
||||||
command: check
|
|
||||||
args: --all --features tokio02
|
|
||||||
|
|
||||||
cross:
|
|
||||||
name: Cross compile
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
strategy:
|
|
||||||
matrix:
|
|
||||||
target:
|
|
||||||
- i686-unknown-linux-gnu
|
|
||||||
- powerpc-unknown-linux-gnu
|
|
||||||
- powerpc64-unknown-linux-gnu
|
|
||||||
- mips-unknown-linux-gnu
|
|
||||||
- arm-linux-androideabi
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@master
|
|
||||||
|
|
||||||
- name: Install nightly
|
|
||||||
uses: actions-rs/toolchain@v1
|
|
||||||
with:
|
|
||||||
toolchain: nightly
|
|
||||||
override: true
|
|
||||||
|
|
||||||
- name: Install cross
|
|
||||||
run: cargo install cross
|
|
||||||
|
|
||||||
- name: check
|
|
||||||
run: cross check --all --target ${{ matrix.target }}
|
|
||||||
|
|
||||||
- name: check unstable
|
|
||||||
run: cross check --all --features unstable --target ${{ matrix.target }}
|
|
||||||
|
|
||||||
- name: test
|
|
||||||
run: cross test --all --features unstable --target ${{ matrix.target }}
|
|
||||||
|
|
||||||
check_fmt_and_docs:
|
check_fmt_and_docs:
|
||||||
name: Checking fmt and docs
|
name: Checking fmt and docs
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
@ -181,3 +117,15 @@ jobs:
|
||||||
|
|
||||||
- name: Docs
|
- name: Docs
|
||||||
run: cargo doc --features docs
|
run: cargo doc --features docs
|
||||||
|
|
||||||
|
# clippy_check:
|
||||||
|
# name: Clippy check
|
||||||
|
# runs-on: ubuntu-latest
|
||||||
|
# steps:
|
||||||
|
# - uses: actions/checkout@v1
|
||||||
|
# - name: Install rust
|
||||||
|
# run: rustup update beta && rustup default beta
|
||||||
|
# - name: Install clippy
|
||||||
|
# run: rustup component add clippy
|
||||||
|
# - name: clippy
|
||||||
|
# run: cargo clippy --all --features unstable
|
||||||
|
|
76
CHANGELOG.md
76
CHANGELOG.md
|
@ -7,75 +7,6 @@ and this project adheres to [Semantic Versioning](https://book.async.rs/overview
|
||||||
|
|
||||||
## [Unreleased]
|
## [Unreleased]
|
||||||
|
|
||||||
# [1.6.2] - 2020-06-19
|
|
||||||
|
|
||||||
## Added
|
|
||||||
|
|
||||||
- Add `UdpSocket::peer_addr` ([#816](https://github.com/async-rs/async-std/pull/816))
|
|
||||||
|
|
||||||
## Changed
|
|
||||||
|
|
||||||
## Fixed
|
|
||||||
|
|
||||||
- Ensure the reactor is running for sockets and timers ([#819](https://github.com/async-rs/async-std/pull/819)).
|
|
||||||
- Avoid excessive polling in `flatten` and `flat_map` ([#701](https://github.com/async-rs/async-std/pull/701))
|
|
||||||
|
|
||||||
|
|
||||||
# [1.6.1] - 2020-06-11
|
|
||||||
|
|
||||||
## Added
|
|
||||||
|
|
||||||
- Added `tokio02` feature flag, to allow compatability usage with tokio@0.2 ([#804](https://github.com/async-rs/async-std/pull/804)).
|
|
||||||
|
|
||||||
## Changed
|
|
||||||
|
|
||||||
- Removed unstable `stdio` lock methods, due to their unsoundness ([#807](https://github.com/async-rs/async-std/pull/807)).
|
|
||||||
|
|
||||||
## Fixed
|
|
||||||
|
|
||||||
- Fixed wrong slice index for file reading ([#802](https://github.com/async-rs/async-std/pull/802)).
|
|
||||||
- Fixed recursive calls to `block_on` ([#799](https://github.com/async-rs/async-std/pull/799)) and ([#809](https://github.com/async-rs/async-std/pull/809)).
|
|
||||||
- Remove `default` feature requirement for the `unstable` feature ([#806](https://github.com/async-rs/async-std/pull/806)).
|
|
||||||
|
|
||||||
# [1.6.0] - 2020-05-22
|
|
||||||
|
|
||||||
See `1.6.0-beta.1` and `1.6.0-beta.2`.
|
|
||||||
|
|
||||||
# [1.6.0-beta.2] - 2020-05-19
|
|
||||||
|
|
||||||
## Added
|
|
||||||
|
|
||||||
- Added an environment variable to configure the thread pool size of the runtime. ([#774](https://github.com/async-rs/async-std/pull/774))
|
|
||||||
- Implement `Clone` for `UnixStream` ([#772](https://github.com/async-rs/async-std/pull/772))
|
|
||||||
|
|
||||||
## Changed
|
|
||||||
|
|
||||||
- For `wasm`, switched underlying `Timer` implementation to [`futures-timer`](https://github.com/async-rs/futures-timer). ([#776](https://github.com/async-rs/async-std/pull/776))
|
|
||||||
|
|
||||||
## Fixed
|
|
||||||
|
|
||||||
- Use `smol::block_on` to handle drop of `File`, avoiding nested executor panic. ([#768](https://github.com/async-rs/async-std/pull/768))
|
|
||||||
|
|
||||||
# [1.6.0-beta.1] - 2020-05-07
|
|
||||||
|
|
||||||
## Added
|
|
||||||
|
|
||||||
- Added `task::spawn_local`. ([#757](https://github.com/async-rs/async-std/pull/757))
|
|
||||||
- Added out of the box support for `wasm`. ([#757](https://github.com/async-rs/async-std/pull/757))
|
|
||||||
- Added `JoinHandle::cancel` ([#757](https://github.com/async-rs/async-std/pull/757))
|
|
||||||
- Added `sync::Condvar` ([#369](https://github.com/async-rs/async-std/pull/369))
|
|
||||||
- Added `sync::Sender::try_send` and `sync::Receiver::try_recv` ([#585](https://github.com/async-rs/async-std/pull/585))
|
|
||||||
- Added `no_std` support for `task`, `future` and `stream` ([#680](https://github.com/async-rs/async-std/pull/680))
|
|
||||||
|
|
||||||
## Changed
|
|
||||||
|
|
||||||
- Switched underlying runtime to [`smol`](https://github.com/stjepang/smol/). ([#757](https://github.com/async-rs/async-std/pull/757))
|
|
||||||
- Switched implementation of `sync::Barrier` to use `sync::Condvar` like `std` does. ([#581](https://github.com/async-rs/async-std/pull/581))
|
|
||||||
|
|
||||||
## Fixed
|
|
||||||
|
|
||||||
- Allow compilation on 32 bit targets, by using `AtomicUsize` for `TaskId`. ([#756](https://github.com/async-rs/async-std/pull/756))
|
|
||||||
|
|
||||||
# [1.5.0] - 2020-02-03
|
# [1.5.0] - 2020-02-03
|
||||||
|
|
||||||
[API Documentation](https://docs.rs/async-std/1.5.0/async-std)
|
[API Documentation](https://docs.rs/async-std/1.5.0/async-std)
|
||||||
|
@ -746,12 +677,7 @@ task::blocking(async {
|
||||||
|
|
||||||
- Initial beta release
|
- Initial beta release
|
||||||
|
|
||||||
[Unreleased]: https://github.com/async-rs/async-std/compare/v1.6.2...HEAD
|
[Unreleased]: https://github.com/async-rs/async-std/compare/v1.5.0...HEAD
|
||||||
[1.6.2]: https://github.com/async-rs/async-std/compare/v1.6.1...v1.6.2
|
|
||||||
[1.6.1]: https://github.com/async-rs/async-std/compare/v1.6.0...v1.6.1
|
|
||||||
[1.6.0]: https://github.com/async-rs/async-std/compare/v1.5.0...v1.6.0
|
|
||||||
[1.6.0-beta.2]: https://github.com/async-rs/async-std/compare/v1.6.0-beta.1...v1.6.0-beta.2
|
|
||||||
[1.6.0-beta.1]: https://github.com/async-rs/async-std/compare/v1.5.0...v1.6.0-beta.1
|
|
||||||
[1.5.0]: https://github.com/async-rs/async-std/compare/v1.4.0...v1.5.0
|
[1.5.0]: https://github.com/async-rs/async-std/compare/v1.4.0...v1.5.0
|
||||||
[1.4.0]: https://github.com/async-rs/async-std/compare/v1.3.0...v1.4.0
|
[1.4.0]: https://github.com/async-rs/async-std/compare/v1.3.0...v1.4.0
|
||||||
[1.3.0]: https://github.com/async-rs/async-std/compare/v1.2.0...v1.3.0
|
[1.3.0]: https://github.com/async-rs/async-std/compare/v1.2.0...v1.3.0
|
||||||
|
|
66
Cargo.toml
66
Cargo.toml
|
@ -1,10 +1,9 @@
|
||||||
[package]
|
[package]
|
||||||
name = "async-std"
|
name = "async-std"
|
||||||
version = "1.6.2"
|
version = "1.5.0"
|
||||||
authors = [
|
authors = [
|
||||||
"Stjepan Glavina <stjepang@gmail.com>",
|
"Stjepan Glavina <stjepang@gmail.com>",
|
||||||
"Yoshua Wuyts <yoshuawuyts@gmail.com>",
|
"Yoshua Wuyts <yoshuawuyts@gmail.com>",
|
||||||
"Friedel Ziegelmayer <me@dignifiedquire.com>",
|
|
||||||
"Contributors to async-std",
|
"Contributors to async-std",
|
||||||
]
|
]
|
||||||
edition = "2018"
|
edition = "2018"
|
||||||
|
@ -25,17 +24,18 @@ rustdoc-args = ["--cfg", "feature=\"docs\""]
|
||||||
default = [
|
default = [
|
||||||
"std",
|
"std",
|
||||||
"async-task",
|
"async-task",
|
||||||
|
"crossbeam-channel",
|
||||||
|
"crossbeam-deque",
|
||||||
|
"futures-timer",
|
||||||
"kv-log-macro",
|
"kv-log-macro",
|
||||||
"log",
|
"log",
|
||||||
|
"mio",
|
||||||
|
"mio-uds",
|
||||||
"num_cpus",
|
"num_cpus",
|
||||||
"pin-project-lite",
|
"pin-project-lite",
|
||||||
"smol",
|
|
||||||
]
|
]
|
||||||
docs = ["attributes", "unstable", "default"]
|
docs = ["attributes", "unstable", "default"]
|
||||||
unstable = [
|
unstable = ["std", "broadcaster", "futures-timer"]
|
||||||
"std",
|
|
||||||
"futures-timer",
|
|
||||||
]
|
|
||||||
attributes = ["async-attributes"]
|
attributes = ["async-attributes"]
|
||||||
std = [
|
std = [
|
||||||
"alloc",
|
"alloc",
|
||||||
|
@ -46,53 +46,39 @@ std = [
|
||||||
"once_cell",
|
"once_cell",
|
||||||
"pin-utils",
|
"pin-utils",
|
||||||
"slab",
|
"slab",
|
||||||
"wasm-bindgen-futures",
|
|
||||||
"futures-channel",
|
|
||||||
"async-mutex",
|
|
||||||
]
|
]
|
||||||
alloc = [
|
alloc = [
|
||||||
"futures-core/alloc",
|
"futures-core/alloc",
|
||||||
"pin-project-lite",
|
"pin-project-lite",
|
||||||
]
|
]
|
||||||
tokio02 = ["smol/tokio02"]
|
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
async-attributes = { version = "1.1.1", optional = true }
|
async-attributes = { version = "1.1.1", optional = true }
|
||||||
async-task = { version = "3.0.0", optional = true }
|
async-task = { version = "1.2.1", optional = true }
|
||||||
async-mutex = { version = "1.1.3", optional = true }
|
broadcaster = { version = "1.0.0", optional = true }
|
||||||
crossbeam-utils = { version = "0.7.2", optional = true }
|
crossbeam-channel = { version = "0.4.0", optional = true }
|
||||||
futures-core = { version = "0.3.4", optional = true, default-features = false }
|
crossbeam-deque = { version = "0.7.2", optional = true }
|
||||||
futures-io = { version = "0.3.4", optional = true }
|
crossbeam-utils = { version = "0.7.0", optional = true }
|
||||||
kv-log-macro = { version = "1.0.6", optional = true }
|
futures-core = { version = "0.3.1", optional = true, default-features = false }
|
||||||
|
futures-io = { version = "0.3.1", optional = true }
|
||||||
|
futures-timer = { version = "2.0.2", optional = true }
|
||||||
|
kv-log-macro = { version = "1.0.4", optional = true }
|
||||||
log = { version = "0.4.8", features = ["kv_unstable"], optional = true }
|
log = { version = "0.4.8", features = ["kv_unstable"], optional = true }
|
||||||
memchr = { version = "2.3.3", optional = true }
|
memchr = { version = "2.3.0", optional = true }
|
||||||
num_cpus = { version = "1.12.0", optional = true }
|
mio = { version = "0.6.19", optional = true }
|
||||||
once_cell = { version = "1.3.1", optional = true }
|
mio-uds = { version = "0.6.7", optional = true }
|
||||||
pin-project-lite = { version = "0.1.4", optional = true }
|
num_cpus = { version = "1.11.1", optional = true }
|
||||||
|
once_cell = { version = "1.2.0", optional = true }
|
||||||
|
pin-project-lite = { version = "0.1.2", optional = true }
|
||||||
pin-utils = { version = "0.1.0-alpha.4", optional = true }
|
pin-utils = { version = "0.1.0-alpha.4", optional = true }
|
||||||
slab = { version = "0.4.2", optional = true }
|
slab = { version = "0.4.2", optional = true }
|
||||||
futures-timer = { version = "3.0.2", optional = true }
|
|
||||||
|
|
||||||
# Devdepencency, but they are not allowed to be optional :/
|
|
||||||
surf = { version = "1.0.3", optional = true }
|
|
||||||
|
|
||||||
[target.'cfg(not(target_os = "unknown"))'.dependencies]
|
|
||||||
smol = { version = "0.1.17", optional = true }
|
|
||||||
|
|
||||||
[target.'cfg(target_arch = "wasm32")'.dependencies]
|
|
||||||
futures-timer = { version = "3.0.2", optional = true, features = ["wasm-bindgen"] }
|
|
||||||
wasm-bindgen-futures = { version = "0.4.10", optional = true }
|
|
||||||
futures-channel = { version = "0.3.4", optional = true }
|
|
||||||
|
|
||||||
[target.'cfg(target_arch = "wasm32")'.dev-dependencies]
|
|
||||||
wasm-bindgen-test = "0.3.10"
|
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
femme = "1.3.0"
|
femme = "1.3.0"
|
||||||
rand = "0.7.3"
|
rand = "0.7.3"
|
||||||
|
surf = "1.0.3"
|
||||||
tempdir = "0.3.7"
|
tempdir = "0.3.7"
|
||||||
futures = "0.3.4"
|
futures = "0.3.1"
|
||||||
rand_xorshift = "0.2.0"
|
|
||||||
|
|
||||||
[[test]]
|
[[test]]
|
||||||
name = "stream"
|
name = "stream"
|
||||||
|
@ -101,7 +87,3 @@ required-features = ["unstable"]
|
||||||
[[example]]
|
[[example]]
|
||||||
name = "tcp-ipv4-and-6-echo"
|
name = "tcp-ipv4-and-6-echo"
|
||||||
required-features = ["unstable"]
|
required-features = ["unstable"]
|
||||||
|
|
||||||
[[example]]
|
|
||||||
name = "surf-web"
|
|
||||||
required-features = ["surf"]
|
|
||||||
|
|
|
@ -8,11 +8,6 @@
|
||||||
<br />
|
<br />
|
||||||
|
|
||||||
<div align="center">
|
<div align="center">
|
||||||
<!-- CI status -->
|
|
||||||
<a href="https://github.com/async-rs/async-std/actions">
|
|
||||||
<img src="https://github.com/async-rs/async-std/workflows/CI/badge.svg"
|
|
||||||
alt="CI Status" />
|
|
||||||
</a>
|
|
||||||
<!-- Crates version -->
|
<!-- Crates version -->
|
||||||
<a href="https://crates.io/crates/async-std">
|
<a href="https://crates.io/crates/async-std">
|
||||||
<img src="https://img.shields.io/crates/v/async-std.svg?style=flat-square"
|
<img src="https://img.shields.io/crates/v/async-std.svg?style=flat-square"
|
||||||
|
@ -141,8 +136,6 @@ documentation] on how to enable them.
|
||||||
|
|
||||||
* [Xactor](https://crates.io/crates/xactor) — Xactor is a rust actors framework based on async-std.
|
* [Xactor](https://crates.io/crates/xactor) — Xactor is a rust actors framework based on async-std.
|
||||||
|
|
||||||
* [async-graphql](https://crates.io/crates/async-graphql) — A GraphQL server library implemented in rust, with full support for async/await.
|
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
<sup>
|
<sup>
|
||||||
|
|
|
@ -4,14 +4,11 @@ use std::pin::Pin;
|
||||||
use crate::prelude::*;
|
use crate::prelude::*;
|
||||||
use crate::stream::{self, IntoStream};
|
use crate::stream::{self, IntoStream};
|
||||||
|
|
||||||
impl<T: Ord + Send> stream::Extend<T> for BinaryHeap<T> {
|
impl<T: Ord> stream::Extend<T> for BinaryHeap<T> {
|
||||||
fn extend<'a, S: IntoStream<Item = T> + 'a>(
|
fn extend<'a, S: IntoStream<Item = T> + 'a>(
|
||||||
&'a mut self,
|
&'a mut self,
|
||||||
stream: S,
|
stream: S,
|
||||||
) -> Pin<Box<dyn Future<Output = ()> + 'a + Send>>
|
) -> Pin<Box<dyn Future<Output = ()> + 'a>> {
|
||||||
where
|
|
||||||
<S as IntoStream>::IntoStream: Send,
|
|
||||||
{
|
|
||||||
let stream = stream.into_stream();
|
let stream = stream.into_stream();
|
||||||
|
|
||||||
self.reserve(stream.size_hint().0);
|
self.reserve(stream.size_hint().0);
|
||||||
|
|
|
@ -4,14 +4,11 @@ use std::pin::Pin;
|
||||||
use crate::prelude::*;
|
use crate::prelude::*;
|
||||||
use crate::stream::{self, FromStream, IntoStream};
|
use crate::stream::{self, FromStream, IntoStream};
|
||||||
|
|
||||||
impl<T: Ord + Send> FromStream<T> for BinaryHeap<T> {
|
impl<T: Ord> FromStream<T> for BinaryHeap<T> {
|
||||||
#[inline]
|
#[inline]
|
||||||
fn from_stream<'a, S: IntoStream<Item = T> + 'a>(
|
fn from_stream<'a, S: IntoStream<Item = T> + 'a>(
|
||||||
stream: S,
|
stream: S,
|
||||||
) -> Pin<Box<dyn Future<Output = Self> + 'a + Send>>
|
) -> Pin<Box<dyn Future<Output = Self> + 'a>> {
|
||||||
where
|
|
||||||
<S as IntoStream>::IntoStream: Send,
|
|
||||||
{
|
|
||||||
let stream = stream.into_stream();
|
let stream = stream.into_stream();
|
||||||
|
|
||||||
Box::pin(async move {
|
Box::pin(async move {
|
||||||
|
|
|
@ -4,14 +4,11 @@ use std::pin::Pin;
|
||||||
use crate::prelude::*;
|
use crate::prelude::*;
|
||||||
use crate::stream::{self, IntoStream};
|
use crate::stream::{self, IntoStream};
|
||||||
|
|
||||||
impl<K: Ord + Send, V: Send> stream::Extend<(K, V)> for BTreeMap<K, V> {
|
impl<K: Ord, V> stream::Extend<(K, V)> for BTreeMap<K, V> {
|
||||||
fn extend<'a, S: IntoStream<Item = (K, V)> + 'a>(
|
fn extend<'a, S: IntoStream<Item = (K, V)> + 'a>(
|
||||||
&'a mut self,
|
&'a mut self,
|
||||||
stream: S,
|
stream: S,
|
||||||
) -> Pin<Box<dyn Future<Output = ()> + 'a + Send>>
|
) -> Pin<Box<dyn Future<Output = ()> + 'a>> {
|
||||||
where
|
|
||||||
<S as IntoStream>::IntoStream: Send,
|
|
||||||
{
|
|
||||||
Box::pin(stream.into_stream().for_each(move |(k, v)| {
|
Box::pin(stream.into_stream().for_each(move |(k, v)| {
|
||||||
self.insert(k, v);
|
self.insert(k, v);
|
||||||
}))
|
}))
|
||||||
|
|
|
@ -4,14 +4,11 @@ use std::pin::Pin;
|
||||||
use crate::prelude::*;
|
use crate::prelude::*;
|
||||||
use crate::stream::{self, FromStream, IntoStream};
|
use crate::stream::{self, FromStream, IntoStream};
|
||||||
|
|
||||||
impl<K: Ord + Send, V: Send> FromStream<(K, V)> for BTreeMap<K, V> {
|
impl<K: Ord, V> FromStream<(K, V)> for BTreeMap<K, V> {
|
||||||
#[inline]
|
#[inline]
|
||||||
fn from_stream<'a, S: IntoStream<Item = (K, V)> + 'a>(
|
fn from_stream<'a, S: IntoStream<Item = (K, V)> + 'a>(
|
||||||
stream: S,
|
stream: S,
|
||||||
) -> Pin<Box<dyn Future<Output = Self> + 'a + Send>>
|
) -> Pin<Box<dyn Future<Output = Self> + 'a>> {
|
||||||
where
|
|
||||||
<S as IntoStream>::IntoStream: Send,
|
|
||||||
{
|
|
||||||
let stream = stream.into_stream();
|
let stream = stream.into_stream();
|
||||||
|
|
||||||
Box::pin(async move {
|
Box::pin(async move {
|
||||||
|
|
|
@ -4,14 +4,11 @@ use std::pin::Pin;
|
||||||
use crate::prelude::*;
|
use crate::prelude::*;
|
||||||
use crate::stream::{self, IntoStream};
|
use crate::stream::{self, IntoStream};
|
||||||
|
|
||||||
impl<T: Ord + Send> stream::Extend<T> for BTreeSet<T> {
|
impl<T: Ord> stream::Extend<T> for BTreeSet<T> {
|
||||||
fn extend<'a, S: IntoStream<Item = T> + 'a>(
|
fn extend<'a, S: IntoStream<Item = T> + 'a>(
|
||||||
&'a mut self,
|
&'a mut self,
|
||||||
stream: S,
|
stream: S,
|
||||||
) -> Pin<Box<dyn Future<Output = ()> + 'a + Send>>
|
) -> Pin<Box<dyn Future<Output = ()> + 'a>> {
|
||||||
where
|
|
||||||
<S as IntoStream>::IntoStream: Send,
|
|
||||||
{
|
|
||||||
Box::pin(stream.into_stream().for_each(move |item| {
|
Box::pin(stream.into_stream().for_each(move |item| {
|
||||||
self.insert(item);
|
self.insert(item);
|
||||||
}))
|
}))
|
||||||
|
|
|
@ -4,14 +4,11 @@ use std::pin::Pin;
|
||||||
use crate::prelude::*;
|
use crate::prelude::*;
|
||||||
use crate::stream::{self, FromStream, IntoStream};
|
use crate::stream::{self, FromStream, IntoStream};
|
||||||
|
|
||||||
impl<T: Ord + Send> FromStream<T> for BTreeSet<T> {
|
impl<T: Ord> FromStream<T> for BTreeSet<T> {
|
||||||
#[inline]
|
#[inline]
|
||||||
fn from_stream<'a, S: IntoStream<Item = T> + 'a>(
|
fn from_stream<'a, S: IntoStream<Item = T> + 'a>(
|
||||||
stream: S,
|
stream: S,
|
||||||
) -> Pin<Box<dyn Future<Output = Self> + 'a + Send>>
|
) -> Pin<Box<dyn Future<Output = Self> + 'a>> {
|
||||||
where
|
|
||||||
<S as IntoStream>::IntoStream: Send,
|
|
||||||
{
|
|
||||||
let stream = stream.into_stream();
|
let stream = stream.into_stream();
|
||||||
|
|
||||||
Box::pin(async move {
|
Box::pin(async move {
|
||||||
|
|
|
@ -7,17 +7,13 @@ use crate::stream::{self, IntoStream};
|
||||||
|
|
||||||
impl<K, V, H> stream::Extend<(K, V)> for HashMap<K, V, H>
|
impl<K, V, H> stream::Extend<(K, V)> for HashMap<K, V, H>
|
||||||
where
|
where
|
||||||
K: Eq + Hash + Send,
|
K: Eq + Hash,
|
||||||
V: Send,
|
H: BuildHasher + Default,
|
||||||
H: BuildHasher + Default + Send,
|
|
||||||
{
|
{
|
||||||
fn extend<'a, S: IntoStream<Item = (K, V)> + 'a>(
|
fn extend<'a, S: IntoStream<Item = (K, V)> + 'a>(
|
||||||
&'a mut self,
|
&'a mut self,
|
||||||
stream: S,
|
stream: S,
|
||||||
) -> Pin<Box<dyn Future<Output = ()> + 'a + Send>>
|
) -> Pin<Box<dyn Future<Output = ()> + 'a>> {
|
||||||
where
|
|
||||||
<S as IntoStream>::IntoStream: Send,
|
|
||||||
{
|
|
||||||
let stream = stream.into_stream();
|
let stream = stream.into_stream();
|
||||||
|
|
||||||
// The following is adapted from the hashbrown source code:
|
// The following is adapted from the hashbrown source code:
|
||||||
|
|
|
@ -7,17 +7,13 @@ use crate::stream::{self, FromStream, IntoStream};
|
||||||
|
|
||||||
impl<K, V, H> FromStream<(K, V)> for HashMap<K, V, H>
|
impl<K, V, H> FromStream<(K, V)> for HashMap<K, V, H>
|
||||||
where
|
where
|
||||||
K: Eq + Hash + Send,
|
K: Eq + Hash,
|
||||||
H: BuildHasher + Default + Send,
|
H: BuildHasher + Default,
|
||||||
V: Send,
|
|
||||||
{
|
{
|
||||||
#[inline]
|
#[inline]
|
||||||
fn from_stream<'a, S: IntoStream<Item = (K, V)> + 'a>(
|
fn from_stream<'a, S: IntoStream<Item = (K, V)> + 'a>(
|
||||||
stream: S,
|
stream: S,
|
||||||
) -> Pin<Box<dyn Future<Output = Self> + 'a + Send>>
|
) -> Pin<Box<dyn Future<Output = Self> + 'a>> {
|
||||||
where
|
|
||||||
<S as IntoStream>::IntoStream: Send,
|
|
||||||
{
|
|
||||||
let stream = stream.into_stream();
|
let stream = stream.into_stream();
|
||||||
|
|
||||||
Box::pin(async move {
|
Box::pin(async move {
|
||||||
|
|
|
@ -7,16 +7,13 @@ use crate::stream::{self, IntoStream};
|
||||||
|
|
||||||
impl<T, H> stream::Extend<T> for HashSet<T, H>
|
impl<T, H> stream::Extend<T> for HashSet<T, H>
|
||||||
where
|
where
|
||||||
T: Eq + Hash + Send,
|
T: Eq + Hash,
|
||||||
H: BuildHasher + Default + Send,
|
H: BuildHasher + Default,
|
||||||
{
|
{
|
||||||
fn extend<'a, S: IntoStream<Item = T> + 'a>(
|
fn extend<'a, S: IntoStream<Item = T> + 'a>(
|
||||||
&'a mut self,
|
&'a mut self,
|
||||||
stream: S,
|
stream: S,
|
||||||
) -> Pin<Box<dyn Future<Output = ()> + 'a + Send>>
|
) -> Pin<Box<dyn Future<Output = ()> + 'a>> {
|
||||||
where
|
|
||||||
<S as IntoStream>::IntoStream: Send,
|
|
||||||
{
|
|
||||||
// The Extend impl for HashSet in the standard library delegates to the internal HashMap.
|
// The Extend impl for HashSet in the standard library delegates to the internal HashMap.
|
||||||
// Thus, this impl is just a copy of the async Extend impl for HashMap in this crate.
|
// Thus, this impl is just a copy of the async Extend impl for HashMap in this crate.
|
||||||
|
|
||||||
|
|
|
@ -7,16 +7,13 @@ use crate::stream::{self, FromStream, IntoStream};
|
||||||
|
|
||||||
impl<T, H> FromStream<T> for HashSet<T, H>
|
impl<T, H> FromStream<T> for HashSet<T, H>
|
||||||
where
|
where
|
||||||
T: Eq + Hash + Send,
|
T: Eq + Hash,
|
||||||
H: BuildHasher + Default + Send,
|
H: BuildHasher + Default,
|
||||||
{
|
{
|
||||||
#[inline]
|
#[inline]
|
||||||
fn from_stream<'a, S: IntoStream<Item = T> + 'a>(
|
fn from_stream<'a, S: IntoStream<Item = T> + 'a>(
|
||||||
stream: S,
|
stream: S,
|
||||||
) -> Pin<Box<dyn Future<Output = Self> + 'a + Send>>
|
) -> Pin<Box<dyn Future<Output = Self> + 'a>> {
|
||||||
where
|
|
||||||
<S as IntoStream>::IntoStream: Send,
|
|
||||||
{
|
|
||||||
let stream = stream.into_stream();
|
let stream = stream.into_stream();
|
||||||
|
|
||||||
Box::pin(async move {
|
Box::pin(async move {
|
||||||
|
|
|
@ -4,14 +4,11 @@ use std::pin::Pin;
|
||||||
use crate::prelude::*;
|
use crate::prelude::*;
|
||||||
use crate::stream::{self, IntoStream};
|
use crate::stream::{self, IntoStream};
|
||||||
|
|
||||||
impl<T: Send> stream::Extend<T> for LinkedList<T> {
|
impl<T> stream::Extend<T> for LinkedList<T> {
|
||||||
fn extend<'a, S: IntoStream<Item = T> + 'a>(
|
fn extend<'a, S: IntoStream<Item = T> + 'a>(
|
||||||
&'a mut self,
|
&'a mut self,
|
||||||
stream: S,
|
stream: S,
|
||||||
) -> Pin<Box<dyn Future<Output = ()> + 'a + Send>>
|
) -> Pin<Box<dyn Future<Output = ()> + 'a>> {
|
||||||
where
|
|
||||||
<S as IntoStream>::IntoStream: Send,
|
|
||||||
{
|
|
||||||
let stream = stream.into_stream();
|
let stream = stream.into_stream();
|
||||||
Box::pin(stream.for_each(move |item| self.push_back(item)))
|
Box::pin(stream.for_each(move |item| self.push_back(item)))
|
||||||
}
|
}
|
||||||
|
|
|
@ -4,14 +4,11 @@ use std::pin::Pin;
|
||||||
use crate::prelude::*;
|
use crate::prelude::*;
|
||||||
use crate::stream::{self, FromStream, IntoStream};
|
use crate::stream::{self, FromStream, IntoStream};
|
||||||
|
|
||||||
impl<T: Send> FromStream<T> for LinkedList<T> {
|
impl<T> FromStream<T> for LinkedList<T> {
|
||||||
#[inline]
|
#[inline]
|
||||||
fn from_stream<'a, S: IntoStream<Item = T> + 'a>(
|
fn from_stream<'a, S: IntoStream<Item = T> + 'a>(
|
||||||
stream: S,
|
stream: S,
|
||||||
) -> Pin<Box<dyn Future<Output = Self> + 'a + Send>>
|
) -> Pin<Box<dyn Future<Output = Self> + 'a>> {
|
||||||
where
|
|
||||||
<S as IntoStream>::IntoStream: Send,
|
|
||||||
{
|
|
||||||
let stream = stream.into_stream();
|
let stream = stream.into_stream();
|
||||||
|
|
||||||
Box::pin(async move {
|
Box::pin(async move {
|
||||||
|
|
|
@ -4,14 +4,11 @@ use std::pin::Pin;
|
||||||
use crate::prelude::*;
|
use crate::prelude::*;
|
||||||
use crate::stream::{self, IntoStream};
|
use crate::stream::{self, IntoStream};
|
||||||
|
|
||||||
impl<T: Send> stream::Extend<T> for VecDeque<T> {
|
impl<T> stream::Extend<T> for VecDeque<T> {
|
||||||
fn extend<'a, S: IntoStream<Item = T> + 'a>(
|
fn extend<'a, S: IntoStream<Item = T> + 'a>(
|
||||||
&'a mut self,
|
&'a mut self,
|
||||||
stream: S,
|
stream: S,
|
||||||
) -> Pin<Box<dyn Future<Output = ()> + 'a + Send>>
|
) -> Pin<Box<dyn Future<Output = ()> + 'a>> {
|
||||||
where
|
|
||||||
<S as IntoStream>::IntoStream: Send,
|
|
||||||
{
|
|
||||||
let stream = stream.into_stream();
|
let stream = stream.into_stream();
|
||||||
|
|
||||||
self.reserve(stream.size_hint().0);
|
self.reserve(stream.size_hint().0);
|
||||||
|
|
|
@ -4,14 +4,11 @@ use std::pin::Pin;
|
||||||
use crate::prelude::*;
|
use crate::prelude::*;
|
||||||
use crate::stream::{self, FromStream, IntoStream};
|
use crate::stream::{self, FromStream, IntoStream};
|
||||||
|
|
||||||
impl<T: Send> FromStream<T> for VecDeque<T> {
|
impl<T> FromStream<T> for VecDeque<T> {
|
||||||
#[inline]
|
#[inline]
|
||||||
fn from_stream<'a, S: IntoStream<Item = T> + 'a>(
|
fn from_stream<'a, S: IntoStream<Item = T> + 'a>(
|
||||||
stream: S,
|
stream: S,
|
||||||
) -> Pin<Box<dyn Future<Output = Self> + 'a + Send>>
|
) -> Pin<Box<dyn Future<Output = Self> + 'a>> {
|
||||||
where
|
|
||||||
<S as IntoStream>::IntoStream: Send,
|
|
||||||
{
|
|
||||||
let stream = stream.into_stream();
|
let stream = stream.into_stream();
|
||||||
|
|
||||||
Box::pin(async move {
|
Box::pin(async move {
|
||||||
|
|
|
@ -12,7 +12,7 @@ use crate::future;
|
||||||
use crate::io::{self, Read, Seek, SeekFrom, Write};
|
use crate::io::{self, Read, Seek, SeekFrom, Write};
|
||||||
use crate::path::Path;
|
use crate::path::Path;
|
||||||
use crate::prelude::*;
|
use crate::prelude::*;
|
||||||
use crate::task::{spawn_blocking, Context, Poll, Waker};
|
use crate::task::{self, spawn_blocking, Context, Poll, Waker};
|
||||||
use crate::utils::Context as _;
|
use crate::utils::Context as _;
|
||||||
|
|
||||||
/// An open file on the filesystem.
|
/// An open file on the filesystem.
|
||||||
|
@ -315,7 +315,7 @@ impl Drop for File {
|
||||||
// non-blocking fashion, but our only other option here is losing data remaining in the
|
// non-blocking fashion, but our only other option here is losing data remaining in the
|
||||||
// write cache. Good task schedulers should be resilient to occasional blocking hiccups in
|
// write cache. Good task schedulers should be resilient to occasional blocking hiccups in
|
||||||
// file destructors so we don't expect this to be a common problem in practice.
|
// file destructors so we don't expect this to be a common problem in practice.
|
||||||
let _ = smol::block_on(self.flush());
|
let _ = task::block_on(self.flush());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -673,7 +673,7 @@ impl LockGuard<State> {
|
||||||
if available > 0 || self.cache.is_empty() {
|
if available > 0 || self.cache.is_empty() {
|
||||||
// Copy data from the cache into the buffer.
|
// Copy data from the cache into the buffer.
|
||||||
let n = cmp::min(available, buf.len());
|
let n = cmp::min(available, buf.len());
|
||||||
buf[..n].copy_from_slice(&self.cache[start..(start + n)]);
|
buf[..n].copy_from_slice(&self.cache[start..n]);
|
||||||
|
|
||||||
// Move the read cursor forward.
|
// Move the read cursor forward.
|
||||||
self.mode = Mode::Reading(start + n);
|
self.mode = Mode::Reading(start + n);
|
||||||
|
@ -867,15 +867,3 @@ impl LockGuard<State> {
|
||||||
Poll::Ready(Ok(()))
|
Poll::Ready(Ok(()))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn async_file_drop() {
|
|
||||||
crate::task::block_on(async move {
|
|
||||||
File::open(file!()).await.unwrap();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
|
@ -2,10 +2,10 @@ use std::future::Future;
|
||||||
use std::pin::Pin;
|
use std::pin::Pin;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use futures_timer::Delay;
|
||||||
use pin_project_lite::pin_project;
|
use pin_project_lite::pin_project;
|
||||||
|
|
||||||
use crate::task::{Context, Poll};
|
use crate::task::{Context, Poll};
|
||||||
use crate::utils::{timer_after, Timer};
|
|
||||||
|
|
||||||
pin_project! {
|
pin_project! {
|
||||||
#[doc(hidden)]
|
#[doc(hidden)]
|
||||||
|
@ -14,13 +14,13 @@ pin_project! {
|
||||||
#[pin]
|
#[pin]
|
||||||
future: F,
|
future: F,
|
||||||
#[pin]
|
#[pin]
|
||||||
delay: Timer,
|
delay: Delay,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<F> DelayFuture<F> {
|
impl<F> DelayFuture<F> {
|
||||||
pub fn new(future: F, dur: Duration) -> DelayFuture<F> {
|
pub fn new(future: F, dur: Duration) -> DelayFuture<F> {
|
||||||
let delay = timer_after(dur);
|
let delay = Delay::new(dur);
|
||||||
|
|
||||||
DelayFuture { future, delay }
|
DelayFuture { future, delay }
|
||||||
}
|
}
|
||||||
|
|
|
@ -61,10 +61,10 @@ cfg_std! {
|
||||||
mod ready;
|
mod ready;
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(any(feature = "unstable", feature = "default"))]
|
cfg_default! {
|
||||||
pub use timeout::{timeout, TimeoutError};
|
pub use timeout::{timeout, TimeoutError};
|
||||||
#[cfg(any(feature = "unstable", feature = "default"))]
|
mod timeout;
|
||||||
mod timeout;
|
}
|
||||||
|
|
||||||
cfg_unstable! {
|
cfg_unstable! {
|
||||||
pub use into_future::IntoFuture;
|
pub use into_future::IntoFuture;
|
||||||
|
|
|
@ -1,13 +1,13 @@
|
||||||
use std::error::Error;
|
use std::error::Error;
|
||||||
use std::fmt;
|
use std::fmt;
|
||||||
use std::future::Future;
|
|
||||||
use std::pin::Pin;
|
use std::pin::Pin;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
use std::future::Future;
|
||||||
|
|
||||||
|
use futures_timer::Delay;
|
||||||
use pin_project_lite::pin_project;
|
use pin_project_lite::pin_project;
|
||||||
|
|
||||||
use crate::task::{Context, Poll};
|
use crate::task::{Context, Poll};
|
||||||
use crate::utils::{timer_after, Timer};
|
|
||||||
|
|
||||||
/// Awaits a future or times out after a duration of time.
|
/// Awaits a future or times out after a duration of time.
|
||||||
///
|
///
|
||||||
|
@ -33,7 +33,11 @@ pub async fn timeout<F, T>(dur: Duration, f: F) -> Result<T, TimeoutError>
|
||||||
where
|
where
|
||||||
F: Future<Output = T>,
|
F: Future<Output = T>,
|
||||||
{
|
{
|
||||||
TimeoutFuture::new(f, dur).await
|
let f = TimeoutFuture {
|
||||||
|
future: f,
|
||||||
|
delay: Delay::new(dur),
|
||||||
|
};
|
||||||
|
f.await
|
||||||
}
|
}
|
||||||
|
|
||||||
pin_project! {
|
pin_project! {
|
||||||
|
@ -42,17 +46,14 @@ pin_project! {
|
||||||
#[pin]
|
#[pin]
|
||||||
future: F,
|
future: F,
|
||||||
#[pin]
|
#[pin]
|
||||||
delay: Timer,
|
delay: Delay,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<F> TimeoutFuture<F> {
|
impl<F> TimeoutFuture<F> {
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
pub(super) fn new(future: F, dur: Duration) -> TimeoutFuture<F> {
|
pub(super) fn new(future: F, dur: Duration) -> TimeoutFuture<F> {
|
||||||
TimeoutFuture {
|
TimeoutFuture { future: future, delay: Delay::new(dur) }
|
||||||
future,
|
|
||||||
delay: timer_after(dur),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -29,7 +29,7 @@ extension_trait! {
|
||||||
|
|
||||||
```
|
```
|
||||||
# #[allow(unused_imports)]
|
# #[allow(unused_imports)]
|
||||||
use async_std::io::prelude::*;
|
use async_std::prelude::*;
|
||||||
```
|
```
|
||||||
|
|
||||||
[`std::io::BufRead`]: https://doc.rust-lang.org/std/io/trait.BufRead.html
|
[`std::io::BufRead`]: https://doc.rust-lang.org/std/io/trait.BufRead.html
|
||||||
|
|
|
@ -307,24 +307,22 @@ cfg_std! {
|
||||||
cfg_default! {
|
cfg_default! {
|
||||||
// For use in the print macros.
|
// For use in the print macros.
|
||||||
#[doc(hidden)]
|
#[doc(hidden)]
|
||||||
#[cfg(not(target_os = "unknown"))]
|
|
||||||
pub use stdio::{_eprint, _print};
|
pub use stdio::{_eprint, _print};
|
||||||
|
|
||||||
#[cfg(not(target_os = "unknown"))]
|
|
||||||
pub use stderr::{stderr, Stderr};
|
pub use stderr::{stderr, Stderr};
|
||||||
#[cfg(not(target_os = "unknown"))]
|
|
||||||
pub use stdin::{stdin, Stdin};
|
pub use stdin::{stdin, Stdin};
|
||||||
#[cfg(not(target_os = "unknown"))]
|
|
||||||
pub use stdout::{stdout, Stdout};
|
pub use stdout::{stdout, Stdout};
|
||||||
pub use timeout::timeout;
|
pub use timeout::timeout;
|
||||||
|
|
||||||
mod timeout;
|
mod timeout;
|
||||||
#[cfg(not(target_os = "unknown"))]
|
|
||||||
mod stderr;
|
mod stderr;
|
||||||
#[cfg(not(target_os = "unknown"))]
|
|
||||||
mod stdin;
|
mod stdin;
|
||||||
#[cfg(not(target_os = "unknown"))]
|
|
||||||
mod stdio;
|
mod stdio;
|
||||||
#[cfg(not(target_os = "unknown"))]
|
|
||||||
mod stdout;
|
mod stdout;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
cfg_unstable_default! {
|
||||||
|
pub use stderr::StderrLock;
|
||||||
|
pub use stdin::StdinLock;
|
||||||
|
pub use stdout::StdoutLock;
|
||||||
|
}
|
||||||
|
|
|
@ -17,9 +17,9 @@ use std::mem;
|
||||||
|
|
||||||
use crate::io::IoSliceMut;
|
use crate::io::IoSliceMut;
|
||||||
|
|
||||||
|
pub use take::Take;
|
||||||
pub use bytes::Bytes;
|
pub use bytes::Bytes;
|
||||||
pub use chain::Chain;
|
pub use chain::Chain;
|
||||||
pub use take::Take;
|
|
||||||
|
|
||||||
extension_trait! {
|
extension_trait! {
|
||||||
use std::pin::Pin;
|
use std::pin::Pin;
|
||||||
|
@ -477,13 +477,13 @@ unsafe fn initialize<R: futures_io::AsyncRead>(_reader: &R, buf: &mut [u8]) {
|
||||||
std::ptr::write_bytes(buf.as_mut_ptr(), 0, buf.len())
|
std::ptr::write_bytes(buf.as_mut_ptr(), 0, buf.len())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(all(test, not(target_os = "unknown")))]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use crate::io;
|
use crate::io;
|
||||||
use crate::prelude::*;
|
use crate::prelude::*;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_read_by_ref() {
|
fn test_read_by_ref() -> io::Result<()> {
|
||||||
crate::task::block_on(async {
|
crate::task::block_on(async {
|
||||||
let mut f = io::Cursor::new(vec![0u8, 1, 2, 3, 4, 5, 6, 7, 8]);
|
let mut f = io::Cursor::new(vec![0u8, 1, 2, 3, 4, 5, 6, 7, 8]);
|
||||||
let mut buffer = Vec::new();
|
let mut buffer = Vec::new();
|
||||||
|
@ -493,13 +493,14 @@ mod tests {
|
||||||
let reference = f.by_ref();
|
let reference = f.by_ref();
|
||||||
|
|
||||||
// read at most 5 bytes
|
// read at most 5 bytes
|
||||||
assert_eq!(reference.take(5).read_to_end(&mut buffer).await.unwrap(), 5);
|
assert_eq!(reference.take(5).read_to_end(&mut buffer).await?, 5);
|
||||||
assert_eq!(&buffer, &[0, 1, 2, 3, 4])
|
assert_eq!(&buffer, &[0, 1, 2, 3, 4])
|
||||||
} // drop our &mut reference so we can use f again
|
} // drop our &mut reference so we can use f again
|
||||||
|
|
||||||
// original file still usable, read the rest
|
// original file still usable, read the rest
|
||||||
assert_eq!(f.read_to_end(&mut other_buffer).await.unwrap(), 4);
|
assert_eq!(f.read_to_end(&mut other_buffer).await?, 4);
|
||||||
assert_eq!(&other_buffer, &[5, 6, 7, 8]);
|
assert_eq!(&other_buffer, &[5, 6, 7, 8]);
|
||||||
});
|
Ok(())
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -218,7 +218,7 @@ impl<T: BufRead> BufRead for Take<T> {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(all(test, not(target_os = "unknown")))]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use crate::io;
|
use crate::io;
|
||||||
use crate::prelude::*;
|
use crate::prelude::*;
|
||||||
|
|
|
@ -5,6 +5,11 @@ use std::future::Future;
|
||||||
use crate::io::{self, Write};
|
use crate::io::{self, Write};
|
||||||
use crate::task::{spawn_blocking, Context, JoinHandle, Poll};
|
use crate::task::{spawn_blocking, Context, JoinHandle, Poll};
|
||||||
|
|
||||||
|
cfg_unstable! {
|
||||||
|
use once_cell::sync::Lazy;
|
||||||
|
use std::io::Write as _;
|
||||||
|
}
|
||||||
|
|
||||||
/// Constructs a new handle to the standard error of the current process.
|
/// Constructs a new handle to the standard error of the current process.
|
||||||
///
|
///
|
||||||
/// This function is an async version of [`std::io::stderr`].
|
/// This function is an async version of [`std::io::stderr`].
|
||||||
|
@ -53,6 +58,22 @@ pub fn stderr() -> Stderr {
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct Stderr(Mutex<State>);
|
pub struct Stderr(Mutex<State>);
|
||||||
|
|
||||||
|
/// A locked reference to the Stderr handle.
|
||||||
|
///
|
||||||
|
/// This handle implements the [`Write`] traits, and is constructed via the [`Stderr::lock`]
|
||||||
|
/// method.
|
||||||
|
///
|
||||||
|
/// [`Write`]: trait.Read.html
|
||||||
|
/// [`Stderr::lock`]: struct.Stderr.html#method.lock
|
||||||
|
#[cfg(feature = "unstable")]
|
||||||
|
#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct StderrLock<'a>(std::io::StderrLock<'a>);
|
||||||
|
|
||||||
|
#[cfg(feature = "unstable")]
|
||||||
|
#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
|
||||||
|
unsafe impl Send for StderrLock<'_> {}
|
||||||
|
|
||||||
/// The state of the asynchronous stderr.
|
/// The state of the asynchronous stderr.
|
||||||
///
|
///
|
||||||
/// The stderr can be either idle or busy performing an asynchronous operation.
|
/// The stderr can be either idle or busy performing an asynchronous operation.
|
||||||
|
@ -87,14 +108,42 @@ enum Operation {
|
||||||
Flush(io::Result<()>),
|
Flush(io::Result<()>),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl Stderr {
|
||||||
|
/// Locks this handle to the standard error stream, returning a writable guard.
|
||||||
|
///
|
||||||
|
/// The lock is released when the returned lock goes out of scope. The returned guard also implements the Write trait for writing data.
|
||||||
|
///
|
||||||
|
/// # Examples
|
||||||
|
///
|
||||||
|
/// ```no_run
|
||||||
|
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
|
||||||
|
/// #
|
||||||
|
/// use async_std::io;
|
||||||
|
/// use async_std::prelude::*;
|
||||||
|
///
|
||||||
|
/// let stderr = io::stderr();
|
||||||
|
/// let mut handle = stderr.lock().await;
|
||||||
|
///
|
||||||
|
/// handle.write_all(b"hello world").await?;
|
||||||
|
/// #
|
||||||
|
/// # Ok(()) }) }
|
||||||
|
/// ```
|
||||||
|
#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
|
||||||
|
#[cfg(any(feature = "unstable", feature = "docs"))]
|
||||||
|
pub async fn lock(&self) -> StderrLock<'static> {
|
||||||
|
static STDERR: Lazy<std::io::Stderr> = Lazy::new(std::io::stderr);
|
||||||
|
|
||||||
|
spawn_blocking(move || StderrLock(STDERR.lock())).await
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl Write for Stderr {
|
impl Write for Stderr {
|
||||||
fn poll_write(
|
fn poll_write(
|
||||||
self: Pin<&mut Self>,
|
mut self: Pin<&mut Self>,
|
||||||
cx: &mut Context<'_>,
|
cx: &mut Context<'_>,
|
||||||
buf: &[u8],
|
buf: &[u8],
|
||||||
) -> Poll<io::Result<usize>> {
|
) -> Poll<io::Result<usize>> {
|
||||||
let mut state_guard = self.0.lock().unwrap();
|
let state = &mut *self.0.lock().unwrap();
|
||||||
let state = &mut *state_guard;
|
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
match state {
|
match state {
|
||||||
|
@ -138,9 +187,8 @@ impl Write for Stderr {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||||
let mut state_guard = self.0.lock().unwrap();
|
let state = &mut *self.0.lock().unwrap();
|
||||||
let state = &mut *state_guard;
|
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
match state {
|
match state {
|
||||||
|
@ -191,3 +239,23 @@ cfg_windows! {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "unstable")]
|
||||||
|
#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
|
||||||
|
impl io::Write for StderrLock<'_> {
|
||||||
|
fn poll_write(
|
||||||
|
mut self: Pin<&mut Self>,
|
||||||
|
_cx: &mut Context<'_>,
|
||||||
|
buf: &[u8],
|
||||||
|
) -> Poll<io::Result<usize>> {
|
||||||
|
Poll::Ready(self.0.write(buf))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn poll_flush(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||||
|
Poll::Ready(self.0.flush())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||||
|
self.poll_flush(cx)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
@ -7,6 +7,11 @@ use crate::io::{self, Read};
|
||||||
use crate::task::{spawn_blocking, Context, JoinHandle, Poll};
|
use crate::task::{spawn_blocking, Context, JoinHandle, Poll};
|
||||||
use crate::utils::Context as _;
|
use crate::utils::Context as _;
|
||||||
|
|
||||||
|
cfg_unstable! {
|
||||||
|
use once_cell::sync::Lazy;
|
||||||
|
use std::io::Read as _;
|
||||||
|
}
|
||||||
|
|
||||||
/// Constructs a new handle to the standard input of the current process.
|
/// Constructs a new handle to the standard input of the current process.
|
||||||
///
|
///
|
||||||
/// This function is an async version of [`std::io::stdin`].
|
/// This function is an async version of [`std::io::stdin`].
|
||||||
|
@ -56,6 +61,21 @@ pub fn stdin() -> Stdin {
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct Stdin(Mutex<State>);
|
pub struct Stdin(Mutex<State>);
|
||||||
|
|
||||||
|
/// A locked reference to the Stdin handle.
|
||||||
|
///
|
||||||
|
/// This handle implements the [`Read`] traits, and is constructed via the [`Stdin::lock`] method.
|
||||||
|
///
|
||||||
|
/// [`Read`]: trait.Read.html
|
||||||
|
/// [`Stdin::lock`]: struct.Stdin.html#method.lock
|
||||||
|
#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
|
||||||
|
#[cfg(feature = "unstable")]
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct StdinLock<'a>(std::io::StdinLock<'a>);
|
||||||
|
|
||||||
|
#[cfg(feature = "unstable")]
|
||||||
|
#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
|
||||||
|
unsafe impl Send for StdinLock<'_> {}
|
||||||
|
|
||||||
/// The state of the asynchronous stdin.
|
/// The state of the asynchronous stdin.
|
||||||
///
|
///
|
||||||
/// The stdin can be either idle or busy performing an asynchronous operation.
|
/// The stdin can be either idle or busy performing an asynchronous operation.
|
||||||
|
@ -145,16 +165,44 @@ impl Stdin {
|
||||||
.await
|
.await
|
||||||
.context(|| String::from("could not read line on stdin"))
|
.context(|| String::from("could not read line on stdin"))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Locks this handle to the standard input stream, returning a readable guard.
|
||||||
|
///
|
||||||
|
/// The lock is released when the returned lock goes out of scope. The returned guard also implements the Read trait for accessing the underlying data.
|
||||||
|
///
|
||||||
|
/// # Examples
|
||||||
|
///
|
||||||
|
/// ```no_run
|
||||||
|
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
|
||||||
|
/// #
|
||||||
|
/// use async_std::io;
|
||||||
|
/// use async_std::prelude::*;
|
||||||
|
///
|
||||||
|
/// let mut buffer = String::new();
|
||||||
|
///
|
||||||
|
/// let stdin = io::stdin();
|
||||||
|
/// let mut handle = stdin.lock().await;
|
||||||
|
///
|
||||||
|
/// handle.read_to_string(&mut buffer).await?;
|
||||||
|
/// #
|
||||||
|
/// # Ok(()) }) }
|
||||||
|
/// ```
|
||||||
|
#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
|
||||||
|
#[cfg(any(feature = "unstable", feature = "docs"))]
|
||||||
|
pub async fn lock(&self) -> StdinLock<'static> {
|
||||||
|
static STDIN: Lazy<std::io::Stdin> = Lazy::new(std::io::stdin);
|
||||||
|
|
||||||
|
spawn_blocking(move || StdinLock(STDIN.lock())).await
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Read for Stdin {
|
impl Read for Stdin {
|
||||||
fn poll_read(
|
fn poll_read(
|
||||||
self: Pin<&mut Self>,
|
mut self: Pin<&mut Self>,
|
||||||
cx: &mut Context<'_>,
|
cx: &mut Context<'_>,
|
||||||
buf: &mut [u8],
|
buf: &mut [u8],
|
||||||
) -> Poll<io::Result<usize>> {
|
) -> Poll<io::Result<usize>> {
|
||||||
let mut state_guard = self.0.lock().unwrap();
|
let state = &mut *self.0.lock().unwrap();
|
||||||
let state = &mut *state_guard;
|
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
match state {
|
match state {
|
||||||
|
@ -217,3 +265,15 @@ cfg_windows! {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "unstable")]
|
||||||
|
#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
|
||||||
|
impl Read for StdinLock<'_> {
|
||||||
|
fn poll_read(
|
||||||
|
mut self: Pin<&mut Self>,
|
||||||
|
_cx: &mut Context<'_>,
|
||||||
|
buf: &mut [u8],
|
||||||
|
) -> Poll<io::Result<usize>> {
|
||||||
|
Poll::Ready(self.0.read(buf))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
@ -5,6 +5,11 @@ use std::future::Future;
|
||||||
use crate::io::{self, Write};
|
use crate::io::{self, Write};
|
||||||
use crate::task::{spawn_blocking, Context, JoinHandle, Poll};
|
use crate::task::{spawn_blocking, Context, JoinHandle, Poll};
|
||||||
|
|
||||||
|
cfg_unstable! {
|
||||||
|
use once_cell::sync::Lazy;
|
||||||
|
use std::io::Write as _;
|
||||||
|
}
|
||||||
|
|
||||||
/// Constructs a new handle to the standard output of the current process.
|
/// Constructs a new handle to the standard output of the current process.
|
||||||
///
|
///
|
||||||
/// This function is an async version of [`std::io::stdout`].
|
/// This function is an async version of [`std::io::stdout`].
|
||||||
|
@ -53,6 +58,22 @@ pub fn stdout() -> Stdout {
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct Stdout(Mutex<State>);
|
pub struct Stdout(Mutex<State>);
|
||||||
|
|
||||||
|
/// A locked reference to the Stderr handle.
|
||||||
|
///
|
||||||
|
/// This handle implements the [`Write`] traits, and is constructed via the [`Stdout::lock`]
|
||||||
|
/// method.
|
||||||
|
///
|
||||||
|
/// [`Write`]: trait.Read.html
|
||||||
|
/// [`Stdout::lock`]: struct.Stdout.html#method.lock
|
||||||
|
#[cfg(feature = "unstable")]
|
||||||
|
#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct StdoutLock<'a>(std::io::StdoutLock<'a>);
|
||||||
|
|
||||||
|
#[cfg(feature = "unstable")]
|
||||||
|
#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
|
||||||
|
unsafe impl Send for StdoutLock<'_> {}
|
||||||
|
|
||||||
/// The state of the asynchronous stdout.
|
/// The state of the asynchronous stdout.
|
||||||
///
|
///
|
||||||
/// The stdout can be either idle or busy performing an asynchronous operation.
|
/// The stdout can be either idle or busy performing an asynchronous operation.
|
||||||
|
@ -87,14 +108,42 @@ enum Operation {
|
||||||
Flush(io::Result<()>),
|
Flush(io::Result<()>),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl Stdout {
|
||||||
|
/// Locks this handle to the standard error stream, returning a writable guard.
|
||||||
|
///
|
||||||
|
/// The lock is released when the returned lock goes out of scope. The returned guard also implements the Write trait for writing data.
|
||||||
|
///
|
||||||
|
/// # Examples
|
||||||
|
///
|
||||||
|
/// ```no_run
|
||||||
|
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
|
||||||
|
/// #
|
||||||
|
/// use async_std::io;
|
||||||
|
/// use async_std::prelude::*;
|
||||||
|
///
|
||||||
|
/// let stdout = io::stdout();
|
||||||
|
/// let mut handle = stdout.lock().await;
|
||||||
|
///
|
||||||
|
/// handle.write_all(b"hello world").await?;
|
||||||
|
/// #
|
||||||
|
/// # Ok(()) }) }
|
||||||
|
/// ```
|
||||||
|
#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
|
||||||
|
#[cfg(any(feature = "unstable", feature = "docs"))]
|
||||||
|
pub async fn lock(&self) -> StdoutLock<'static> {
|
||||||
|
static STDOUT: Lazy<std::io::Stdout> = Lazy::new(std::io::stdout);
|
||||||
|
|
||||||
|
spawn_blocking(move || StdoutLock(STDOUT.lock())).await
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl Write for Stdout {
|
impl Write for Stdout {
|
||||||
fn poll_write(
|
fn poll_write(
|
||||||
self: Pin<&mut Self>,
|
mut self: Pin<&mut Self>,
|
||||||
cx: &mut Context<'_>,
|
cx: &mut Context<'_>,
|
||||||
buf: &[u8],
|
buf: &[u8],
|
||||||
) -> Poll<io::Result<usize>> {
|
) -> Poll<io::Result<usize>> {
|
||||||
let mut state_guard = self.0.lock().unwrap();
|
let state = &mut *self.0.lock().unwrap();
|
||||||
let state = &mut *state_guard;
|
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
match state {
|
match state {
|
||||||
|
@ -138,9 +187,8 @@ impl Write for Stdout {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||||
let mut state_guard = self.0.lock().unwrap();
|
let state = &mut *self.0.lock().unwrap();
|
||||||
let state = &mut *state_guard;
|
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
match state {
|
match state {
|
||||||
|
@ -191,3 +239,23 @@ cfg_windows! {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "unstable")]
|
||||||
|
#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
|
||||||
|
impl Write for StdoutLock<'_> {
|
||||||
|
fn poll_write(
|
||||||
|
mut self: Pin<&mut Self>,
|
||||||
|
_cx: &mut Context<'_>,
|
||||||
|
buf: &[u8],
|
||||||
|
) -> Poll<io::Result<usize>> {
|
||||||
|
Poll::Ready(self.0.write(buf))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn poll_flush(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||||
|
Poll::Ready(self.0.flush())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||||
|
self.poll_flush(cx)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
@ -1,12 +1,12 @@
|
||||||
use std::future::Future;
|
|
||||||
use std::pin::Pin;
|
use std::pin::Pin;
|
||||||
use std::task::{Context, Poll};
|
use std::task::{Context, Poll};
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
use std::future::Future;
|
||||||
|
|
||||||
|
use futures_timer::Delay;
|
||||||
use pin_project_lite::pin_project;
|
use pin_project_lite::pin_project;
|
||||||
|
|
||||||
use crate::io;
|
use crate::io;
|
||||||
use crate::utils::{timer_after, Timer};
|
|
||||||
|
|
||||||
/// Awaits an I/O future or times out after a duration of time.
|
/// Awaits an I/O future or times out after a duration of time.
|
||||||
///
|
///
|
||||||
|
@ -37,7 +37,7 @@ where
|
||||||
F: Future<Output = io::Result<T>>,
|
F: Future<Output = io::Result<T>>,
|
||||||
{
|
{
|
||||||
Timeout {
|
Timeout {
|
||||||
timeout: timer_after(dur),
|
timeout: Delay::new(dur),
|
||||||
future: f,
|
future: f,
|
||||||
}
|
}
|
||||||
.await
|
.await
|
||||||
|
@ -53,7 +53,7 @@ pin_project! {
|
||||||
#[pin]
|
#[pin]
|
||||||
future: F,
|
future: F,
|
||||||
#[pin]
|
#[pin]
|
||||||
timeout: Timer,
|
timeout: Delay,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
45
src/lib.rs
45
src/lib.rs
|
@ -138,8 +138,7 @@
|
||||||
//!
|
//!
|
||||||
//! Call an async function from the main function:
|
//! Call an async function from the main function:
|
||||||
//!
|
//!
|
||||||
#![cfg_attr(feature = "attributes", doc = "```")]
|
//! ```
|
||||||
#![cfg_attr(not(feature = "attributes"), doc = "```ignore")]
|
|
||||||
//! async fn say_hello() {
|
//! async fn say_hello() {
|
||||||
//! println!("Hello, world!");
|
//! println!("Hello, world!");
|
||||||
//! }
|
//! }
|
||||||
|
@ -152,8 +151,7 @@
|
||||||
//!
|
//!
|
||||||
//! Await two futures concurrently, and return a tuple of their output:
|
//! Await two futures concurrently, and return a tuple of their output:
|
||||||
//!
|
//!
|
||||||
#![cfg_attr(feature = "attributes", doc = "```")]
|
//! ```
|
||||||
#![cfg_attr(not(feature = "attributes"), doc = "```ignore")]
|
|
||||||
//! use async_std::prelude::*;
|
//! use async_std::prelude::*;
|
||||||
//!
|
//!
|
||||||
//! #[async_std::main]
|
//! #[async_std::main]
|
||||||
|
@ -166,8 +164,7 @@
|
||||||
//!
|
//!
|
||||||
//! Create a UDP server that echoes back each received message to the sender:
|
//! Create a UDP server that echoes back each received message to the sender:
|
||||||
//!
|
//!
|
||||||
#![cfg_attr(feature = "attributes", doc = "```no_run")]
|
//! ```no_run
|
||||||
#![cfg_attr(not(feature = "attributes"), doc = "```ignore")]
|
|
||||||
//! use async_std::net::UdpSocket;
|
//! use async_std::net::UdpSocket;
|
||||||
//!
|
//!
|
||||||
//! #[async_std::main]
|
//! #[async_std::main]
|
||||||
|
@ -197,7 +194,7 @@
|
||||||
//!
|
//!
|
||||||
//! ```toml
|
//! ```toml
|
||||||
//! [dependencies.async-std]
|
//! [dependencies.async-std]
|
||||||
//! version = "1.6.2"
|
//! version = "1.0.0"
|
||||||
//! features = ["unstable"]
|
//! features = ["unstable"]
|
||||||
//! ```
|
//! ```
|
||||||
//!
|
//!
|
||||||
|
@ -210,25 +207,16 @@
|
||||||
//!
|
//!
|
||||||
//! ```toml
|
//! ```toml
|
||||||
//! [dependencies.async-std]
|
//! [dependencies.async-std]
|
||||||
//! version = "1.6.2"
|
//! version = "1.0.0"
|
||||||
//! features = ["attributes"]
|
//! features = ["attributes"]
|
||||||
//! ```
|
//! ```
|
||||||
//!
|
//!
|
||||||
//! Compatibility with the `tokio` runtime is possible using the `tokio02`
|
|
||||||
//! Cargo feature:
|
|
||||||
//!
|
|
||||||
//! ```toml
|
|
||||||
//! [dependencies.async-std]
|
|
||||||
//! version = "1.6.2"
|
|
||||||
//! features = ["tokio02"]
|
|
||||||
//! ```
|
|
||||||
//!
|
|
||||||
//! Additionally it's possible to only use the core traits and combinators by
|
//! Additionally it's possible to only use the core traits and combinators by
|
||||||
//! only enabling the `std` Cargo feature:
|
//! only enabling the `std` Cargo feature:
|
||||||
//!
|
//!
|
||||||
//! ```toml
|
//! ```toml
|
||||||
//! [dependencies.async-std]
|
//! [dependencies.async-std]
|
||||||
//! version = "1.6.2"
|
//! version = "1.0.0"
|
||||||
//! default-features = false
|
//! default-features = false
|
||||||
//! features = ["std"]
|
//! features = ["std"]
|
||||||
//! ```
|
//! ```
|
||||||
|
@ -238,25 +226,10 @@
|
||||||
//!
|
//!
|
||||||
//! ```toml
|
//! ```toml
|
||||||
//! [dependencies.async-std]
|
//! [dependencies.async-std]
|
||||||
//! version = "1.6.2"
|
//! version = "1.5.0"
|
||||||
//! default-features = false
|
//! default-features = false
|
||||||
//! features = ["alloc"]
|
//! features = ["alloc"]
|
||||||
//! ```
|
//! ```
|
||||||
//!
|
|
||||||
//! # Runtime configuration
|
|
||||||
//!
|
|
||||||
//! Several environment variables are available to tune the async-std
|
|
||||||
//! runtime:
|
|
||||||
//!
|
|
||||||
//! * `ASYNC_STD_THREAD_COUNT`: The number of threads that the
|
|
||||||
//! async-std runtime will start. By default, this is one per logical
|
|
||||||
//! cpu as reported by the [num_cpus](num_cpus) crate, which may be
|
|
||||||
//! different than the number of physical cpus. Async-std _will panic_
|
|
||||||
//! if this is set to any value other than a positive integer.
|
|
||||||
//! * `ASYNC_STD_THREAD_NAME`: The name that async-std's runtime
|
|
||||||
//! threads report to the operating system. The default value is
|
|
||||||
//! `"async-std/runtime"`.
|
|
||||||
//!
|
|
||||||
|
|
||||||
#![cfg_attr(not(feature = "std"), no_std)]
|
#![cfg_attr(not(feature = "std"), no_std)]
|
||||||
#![cfg_attr(feature = "docs", feature(doc_cfg))]
|
#![cfg_attr(feature = "docs", feature(doc_cfg))]
|
||||||
|
@ -294,17 +267,13 @@ cfg_std! {
|
||||||
}
|
}
|
||||||
|
|
||||||
cfg_default! {
|
cfg_default! {
|
||||||
#[cfg(not(target_os = "unknown"))]
|
|
||||||
pub mod fs;
|
pub mod fs;
|
||||||
pub mod path;
|
pub mod path;
|
||||||
pub mod net;
|
pub mod net;
|
||||||
#[cfg(not(target_os = "unknown"))]
|
|
||||||
pub(crate) mod rt;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
cfg_unstable! {
|
cfg_unstable! {
|
||||||
pub mod pin;
|
pub mod pin;
|
||||||
#[cfg(not(target_os = "unknown"))]
|
|
||||||
pub mod process;
|
pub mod process;
|
||||||
|
|
||||||
mod unit;
|
mod unit;
|
||||||
|
|
380
src/net/driver/mod.rs
Normal file
380
src/net/driver/mod.rs
Normal file
|
@ -0,0 +1,380 @@
|
||||||
|
use std::fmt;
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
|
||||||
|
use mio::{self, Evented};
|
||||||
|
use once_cell::sync::Lazy;
|
||||||
|
use slab::Slab;
|
||||||
|
|
||||||
|
use crate::io;
|
||||||
|
use crate::task::{Context, Poll, Waker};
|
||||||
|
use crate::utils::abort_on_panic;
|
||||||
|
|
||||||
|
/// Data associated with a registered I/O handle.
|
||||||
|
#[derive(Debug)]
|
||||||
|
struct Entry {
|
||||||
|
/// A unique identifier.
|
||||||
|
token: mio::Token,
|
||||||
|
|
||||||
|
/// Tasks that are blocked on reading from this I/O handle.
|
||||||
|
readers: Mutex<Readers>,
|
||||||
|
|
||||||
|
/// Thasks that are blocked on writing to this I/O handle.
|
||||||
|
writers: Mutex<Writers>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The set of `Waker`s interested in read readiness.
|
||||||
|
#[derive(Debug)]
|
||||||
|
struct Readers {
|
||||||
|
/// Flag indicating read readiness.
|
||||||
|
/// (cf. `Watcher::poll_read_ready`)
|
||||||
|
ready: bool,
|
||||||
|
/// The `Waker`s blocked on reading.
|
||||||
|
wakers: Vec<Waker>
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The set of `Waker`s interested in write readiness.
|
||||||
|
#[derive(Debug)]
|
||||||
|
struct Writers {
|
||||||
|
/// Flag indicating write readiness.
|
||||||
|
/// (cf. `Watcher::poll_write_ready`)
|
||||||
|
ready: bool,
|
||||||
|
/// The `Waker`s blocked on writing.
|
||||||
|
wakers: Vec<Waker>
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The state of a networking driver.
|
||||||
|
struct Reactor {
|
||||||
|
/// A mio instance that polls for new events.
|
||||||
|
poller: mio::Poll,
|
||||||
|
|
||||||
|
/// A collection of registered I/O handles.
|
||||||
|
entries: Mutex<Slab<Arc<Entry>>>,
|
||||||
|
|
||||||
|
/// Dummy I/O handle that is only used to wake up the polling thread.
|
||||||
|
notify_reg: (mio::Registration, mio::SetReadiness),
|
||||||
|
|
||||||
|
/// An identifier for the notification handle.
|
||||||
|
notify_token: mio::Token,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Reactor {
|
||||||
|
/// Creates a new reactor for polling I/O events.
|
||||||
|
fn new() -> io::Result<Reactor> {
|
||||||
|
let poller = mio::Poll::new()?;
|
||||||
|
let notify_reg = mio::Registration::new2();
|
||||||
|
|
||||||
|
let mut reactor = Reactor {
|
||||||
|
poller,
|
||||||
|
entries: Mutex::new(Slab::new()),
|
||||||
|
notify_reg,
|
||||||
|
notify_token: mio::Token(0),
|
||||||
|
};
|
||||||
|
|
||||||
|
// Register a dummy I/O handle for waking up the polling thread.
|
||||||
|
let entry = reactor.register(&reactor.notify_reg.0)?;
|
||||||
|
reactor.notify_token = entry.token;
|
||||||
|
|
||||||
|
Ok(reactor)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Registers an I/O event source and returns its associated entry.
|
||||||
|
fn register(&self, source: &dyn Evented) -> io::Result<Arc<Entry>> {
|
||||||
|
let mut entries = self.entries.lock().unwrap();
|
||||||
|
|
||||||
|
// Reserve a vacant spot in the slab and use its key as the token value.
|
||||||
|
let vacant = entries.vacant_entry();
|
||||||
|
let token = mio::Token(vacant.key());
|
||||||
|
|
||||||
|
// Allocate an entry and insert it into the slab.
|
||||||
|
let entry = Arc::new(Entry {
|
||||||
|
token,
|
||||||
|
readers: Mutex::new(Readers { ready: false, wakers: Vec::new() }),
|
||||||
|
writers: Mutex::new(Writers { ready: false, wakers: Vec::new() }),
|
||||||
|
});
|
||||||
|
vacant.insert(entry.clone());
|
||||||
|
|
||||||
|
// Register the I/O event source in the poller.
|
||||||
|
let interest = mio::Ready::all();
|
||||||
|
let opts = mio::PollOpt::edge();
|
||||||
|
self.poller.register(source, token, interest, opts)?;
|
||||||
|
|
||||||
|
Ok(entry)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Deregisters an I/O event source associated with an entry.
|
||||||
|
fn deregister(&self, source: &dyn Evented, entry: &Entry) -> io::Result<()> {
|
||||||
|
// Deregister the I/O object from the mio instance.
|
||||||
|
self.poller.deregister(source)?;
|
||||||
|
|
||||||
|
// Remove the entry associated with the I/O object.
|
||||||
|
self.entries.lock().unwrap().remove(entry.token.0);
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
// fn notify(&self) {
|
||||||
|
// self.notify_reg
|
||||||
|
// .1
|
||||||
|
// .set_readiness(mio::Ready::readable())
|
||||||
|
// .unwrap();
|
||||||
|
// }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The state of the global networking driver.
|
||||||
|
static REACTOR: Lazy<Reactor> = Lazy::new(|| {
|
||||||
|
// Spawn a thread that waits on the poller for new events and wakes up tasks blocked on I/O
|
||||||
|
// handles.
|
||||||
|
std::thread::Builder::new()
|
||||||
|
.name("async-std/net".to_string())
|
||||||
|
.spawn(move || {
|
||||||
|
// If the driver thread panics, there's not much we can do. It is not a
|
||||||
|
// recoverable error and there is no place to propagate it into so we just abort.
|
||||||
|
abort_on_panic(|| {
|
||||||
|
main_loop().expect("async networking thread has panicked");
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.expect("cannot start a thread driving blocking tasks");
|
||||||
|
|
||||||
|
Reactor::new().expect("cannot initialize reactor")
|
||||||
|
});
|
||||||
|
|
||||||
|
/// Waits on the poller for new events and wakes up tasks blocked on I/O handles.
|
||||||
|
fn main_loop() -> io::Result<()> {
|
||||||
|
let reactor = &REACTOR;
|
||||||
|
let mut events = mio::Events::with_capacity(1000);
|
||||||
|
|
||||||
|
loop {
|
||||||
|
// Block on the poller until at least one new event comes in.
|
||||||
|
reactor.poller.poll(&mut events, None)?;
|
||||||
|
|
||||||
|
// Lock the entire entry table while we're processing new events.
|
||||||
|
let entries = reactor.entries.lock().unwrap();
|
||||||
|
|
||||||
|
for event in events.iter() {
|
||||||
|
let token = event.token();
|
||||||
|
|
||||||
|
if token == reactor.notify_token {
|
||||||
|
// If this is the notification token, we just need the notification state.
|
||||||
|
reactor.notify_reg.1.set_readiness(mio::Ready::empty())?;
|
||||||
|
} else {
|
||||||
|
// Otherwise, look for the entry associated with this token.
|
||||||
|
if let Some(entry) = entries.get(token.0) {
|
||||||
|
// Set the readiness flags from this I/O event.
|
||||||
|
let readiness = event.readiness();
|
||||||
|
|
||||||
|
// Wake up reader tasks blocked on this I/O handle.
|
||||||
|
if !(readiness & reader_interests()).is_empty() {
|
||||||
|
let mut readers = entry.readers.lock().unwrap();
|
||||||
|
readers.ready = true;
|
||||||
|
for w in readers.wakers.drain(..) {
|
||||||
|
w.wake();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wake up writer tasks blocked on this I/O handle.
|
||||||
|
if !(readiness & writer_interests()).is_empty() {
|
||||||
|
let mut writers = entry.writers.lock().unwrap();
|
||||||
|
writers.ready = true;
|
||||||
|
for w in writers.wakers.drain(..) {
|
||||||
|
w.wake();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An I/O handle powered by the networking driver.
|
||||||
|
///
|
||||||
|
/// This handle wraps an I/O event source and exposes a "futurized" interface on top of it,
|
||||||
|
/// implementing traits `AsyncRead` and `AsyncWrite`.
|
||||||
|
pub struct Watcher<T: Evented> {
|
||||||
|
/// Data associated with the I/O handle.
|
||||||
|
entry: Arc<Entry>,
|
||||||
|
|
||||||
|
/// The I/O event source.
|
||||||
|
source: Option<T>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: Evented> Watcher<T> {
|
||||||
|
/// Creates a new I/O handle.
|
||||||
|
///
|
||||||
|
/// The provided I/O event source will be kept registered inside the reactor's poller for the
|
||||||
|
/// lifetime of the returned I/O handle.
|
||||||
|
pub fn new(source: T) -> Watcher<T> {
|
||||||
|
Watcher {
|
||||||
|
entry: REACTOR
|
||||||
|
.register(&source)
|
||||||
|
.expect("cannot register an I/O event source"),
|
||||||
|
source: Some(source),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns a reference to the inner I/O event source.
|
||||||
|
pub fn get_ref(&self) -> &T {
|
||||||
|
self.source.as_ref().unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Polls the inner I/O source for a non-blocking read operation.
|
||||||
|
///
|
||||||
|
/// If the operation returns an error of the `io::ErrorKind::WouldBlock` kind, the current task
|
||||||
|
/// will be registered for wakeup when the I/O source becomes readable.
|
||||||
|
pub fn poll_read_with<'a, F, R>(&'a self, cx: &mut Context<'_>, mut f: F) -> Poll<io::Result<R>>
|
||||||
|
where
|
||||||
|
F: FnMut(&'a T) -> io::Result<R>,
|
||||||
|
{
|
||||||
|
// If the operation isn't blocked, return its result.
|
||||||
|
match f(self.source.as_ref().unwrap()) {
|
||||||
|
Err(err) if err.kind() == io::ErrorKind::WouldBlock => {}
|
||||||
|
res => return Poll::Ready(res),
|
||||||
|
}
|
||||||
|
|
||||||
|
// Lock the waker list.
|
||||||
|
let mut readers = self.entry.readers.lock().unwrap();
|
||||||
|
|
||||||
|
// Try running the operation again.
|
||||||
|
match f(self.source.as_ref().unwrap()) {
|
||||||
|
Err(err) if err.kind() == io::ErrorKind::WouldBlock => {}
|
||||||
|
res => return Poll::Ready(res),
|
||||||
|
}
|
||||||
|
|
||||||
|
// Register the task if it isn't registered already.
|
||||||
|
if readers.wakers.iter().all(|w| !w.will_wake(cx.waker())) {
|
||||||
|
readers.wakers.push(cx.waker().clone());
|
||||||
|
}
|
||||||
|
|
||||||
|
readers.ready = false;
|
||||||
|
|
||||||
|
Poll::Pending
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Polls the inner I/O source for a non-blocking write operation.
|
||||||
|
///
|
||||||
|
/// If the operation returns an error of the `io::ErrorKind::WouldBlock` kind, the current task
|
||||||
|
/// will be registered for wakeup when the I/O source becomes writable.
|
||||||
|
pub fn poll_write_with<'a, F, R>(
|
||||||
|
&'a self,
|
||||||
|
cx: &mut Context<'_>,
|
||||||
|
mut f: F,
|
||||||
|
) -> Poll<io::Result<R>>
|
||||||
|
where
|
||||||
|
F: FnMut(&'a T) -> io::Result<R>,
|
||||||
|
{
|
||||||
|
// If the operation isn't blocked, return its result.
|
||||||
|
match f(self.source.as_ref().unwrap()) {
|
||||||
|
Err(err) if err.kind() == io::ErrorKind::WouldBlock => {}
|
||||||
|
res => return Poll::Ready(res),
|
||||||
|
}
|
||||||
|
|
||||||
|
// Lock the waker list.
|
||||||
|
let mut writers = self.entry.writers.lock().unwrap();
|
||||||
|
|
||||||
|
// Try running the operation again.
|
||||||
|
match f(self.source.as_ref().unwrap()) {
|
||||||
|
Err(err) if err.kind() == io::ErrorKind::WouldBlock => {}
|
||||||
|
res => return Poll::Ready(res),
|
||||||
|
}
|
||||||
|
|
||||||
|
// Register the task if it isn't registered already.
|
||||||
|
if writers.wakers.iter().all(|w| !w.will_wake(cx.waker())) {
|
||||||
|
writers.wakers.push(cx.waker().clone());
|
||||||
|
}
|
||||||
|
|
||||||
|
writers.ready = false;
|
||||||
|
|
||||||
|
Poll::Pending
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Polls the inner I/O source until a non-blocking read can be performed.
|
||||||
|
///
|
||||||
|
/// If non-blocking reads are currently not possible, the `Waker`
|
||||||
|
/// will be saved and notified when it can read non-blocking
|
||||||
|
/// again.
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub fn poll_read_ready(&self, cx: &mut Context<'_>) -> Poll<()> {
|
||||||
|
// Lock the waker list.
|
||||||
|
let mut readers = self.entry.readers.lock().unwrap();
|
||||||
|
if readers.ready {
|
||||||
|
return Poll::Ready(())
|
||||||
|
}
|
||||||
|
// Register the task if it isn't registered already.
|
||||||
|
if readers.wakers.iter().all(|w| !w.will_wake(cx.waker())) {
|
||||||
|
readers.wakers.push(cx.waker().clone());
|
||||||
|
}
|
||||||
|
Poll::Pending
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Polls the inner I/O source until a non-blocking write can be performed.
|
||||||
|
///
|
||||||
|
/// If non-blocking writes are currently not possible, the `Waker`
|
||||||
|
/// will be saved and notified when it can write non-blocking
|
||||||
|
/// again.
|
||||||
|
pub fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll<()> {
|
||||||
|
// Lock the waker list.
|
||||||
|
let mut writers = self.entry.writers.lock().unwrap();
|
||||||
|
if writers.ready {
|
||||||
|
return Poll::Ready(())
|
||||||
|
}
|
||||||
|
// Register the task if it isn't registered already.
|
||||||
|
if writers.wakers.iter().all(|w| !w.will_wake(cx.waker())) {
|
||||||
|
writers.wakers.push(cx.waker().clone());
|
||||||
|
}
|
||||||
|
Poll::Pending
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Deregisters and returns the inner I/O source.
|
||||||
|
///
|
||||||
|
/// This method is typically used to convert `Watcher`s to raw file descriptors/handles.
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub fn into_inner(mut self) -> T {
|
||||||
|
let source = self.source.take().unwrap();
|
||||||
|
REACTOR
|
||||||
|
.deregister(&source, &self.entry)
|
||||||
|
.expect("cannot deregister I/O event source");
|
||||||
|
source
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: Evented> Drop for Watcher<T> {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
if let Some(ref source) = self.source {
|
||||||
|
REACTOR
|
||||||
|
.deregister(source, &self.entry)
|
||||||
|
.expect("cannot deregister I/O event source");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: Evented + fmt::Debug> fmt::Debug for Watcher<T> {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
f.debug_struct("Watcher")
|
||||||
|
.field("entry", &self.entry)
|
||||||
|
.field("source", &self.source)
|
||||||
|
.finish()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns a mask containing flags that interest tasks reading from I/O handles.
|
||||||
|
#[inline]
|
||||||
|
fn reader_interests() -> mio::Ready {
|
||||||
|
mio::Ready::all() - mio::Ready::writable()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns a mask containing flags that interest tasks writing into I/O handles.
|
||||||
|
#[inline]
|
||||||
|
fn writer_interests() -> mio::Ready {
|
||||||
|
mio::Ready::writable() | hup()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns a flag containing the hangup status.
|
||||||
|
#[inline]
|
||||||
|
fn hup() -> mio::Ready {
|
||||||
|
#[cfg(unix)]
|
||||||
|
let ready = mio::unix::UnixReady::hup().into();
|
||||||
|
|
||||||
|
#[cfg(not(unix))]
|
||||||
|
let ready = mio::Ready::empty();
|
||||||
|
|
||||||
|
ready
|
||||||
|
}
|
|
@ -61,16 +61,11 @@ pub use std::net::Shutdown;
|
||||||
pub use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
|
pub use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
|
||||||
pub use std::net::{SocketAddr, SocketAddrV4, SocketAddrV6};
|
pub use std::net::{SocketAddr, SocketAddrV4, SocketAddrV6};
|
||||||
|
|
||||||
#[cfg(not(target_os = "unknown"))]
|
|
||||||
pub use addr::ToSocketAddrs;
|
pub use addr::ToSocketAddrs;
|
||||||
#[cfg(not(target_os = "unknown"))]
|
|
||||||
pub use tcp::{Incoming, TcpListener, TcpStream};
|
pub use tcp::{Incoming, TcpListener, TcpStream};
|
||||||
#[cfg(not(target_os = "unknown"))]
|
|
||||||
pub use udp::UdpSocket;
|
pub use udp::UdpSocket;
|
||||||
|
|
||||||
#[cfg(not(target_os = "unknown"))]
|
|
||||||
mod addr;
|
mod addr;
|
||||||
#[cfg(not(target_os = "unknown"))]
|
pub(crate) mod driver;
|
||||||
mod tcp;
|
mod tcp;
|
||||||
#[cfg(not(target_os = "unknown"))]
|
|
||||||
mod udp;
|
mod udp;
|
||||||
|
|
|
@ -1,13 +1,13 @@
|
||||||
use std::future::Future;
|
use std::future::Future;
|
||||||
use std::net::SocketAddr;
|
use std::net::SocketAddr;
|
||||||
use std::pin::Pin;
|
use std::pin::Pin;
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
use smol::Async;
|
use crate::future;
|
||||||
|
|
||||||
use crate::io;
|
use crate::io;
|
||||||
|
use crate::net::driver::Watcher;
|
||||||
use crate::net::{TcpStream, ToSocketAddrs};
|
use crate::net::{TcpStream, ToSocketAddrs};
|
||||||
use crate::stream::Stream;
|
use crate::stream::Stream;
|
||||||
use crate::sync::Arc;
|
|
||||||
use crate::task::{Context, Poll};
|
use crate::task::{Context, Poll};
|
||||||
|
|
||||||
/// A TCP socket server, listening for connections.
|
/// A TCP socket server, listening for connections.
|
||||||
|
@ -49,7 +49,7 @@ use crate::task::{Context, Poll};
|
||||||
/// ```
|
/// ```
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct TcpListener {
|
pub struct TcpListener {
|
||||||
watcher: Async<std::net::TcpListener>,
|
watcher: Watcher<mio::net::TcpListener>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl TcpListener {
|
impl TcpListener {
|
||||||
|
@ -75,15 +75,15 @@ impl TcpListener {
|
||||||
///
|
///
|
||||||
/// [`local_addr`]: #method.local_addr
|
/// [`local_addr`]: #method.local_addr
|
||||||
pub async fn bind<A: ToSocketAddrs>(addrs: A) -> io::Result<TcpListener> {
|
pub async fn bind<A: ToSocketAddrs>(addrs: A) -> io::Result<TcpListener> {
|
||||||
once_cell::sync::Lazy::force(&crate::rt::RUNTIME);
|
|
||||||
|
|
||||||
let mut last_err = None;
|
let mut last_err = None;
|
||||||
let addrs = addrs.to_socket_addrs().await?;
|
let addrs = addrs.to_socket_addrs().await?;
|
||||||
|
|
||||||
for addr in addrs {
|
for addr in addrs {
|
||||||
match Async::<std::net::TcpListener>::bind(&addr) {
|
match mio::net::TcpListener::bind(&addr) {
|
||||||
Ok(listener) => {
|
Ok(mio_listener) => {
|
||||||
return Ok(TcpListener { watcher: listener });
|
return Ok(TcpListener {
|
||||||
|
watcher: Watcher::new(mio_listener),
|
||||||
|
});
|
||||||
}
|
}
|
||||||
Err(err) => last_err = Some(err),
|
Err(err) => last_err = Some(err),
|
||||||
}
|
}
|
||||||
|
@ -114,9 +114,13 @@ impl TcpListener {
|
||||||
/// # Ok(()) }) }
|
/// # Ok(()) }) }
|
||||||
/// ```
|
/// ```
|
||||||
pub async fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> {
|
pub async fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> {
|
||||||
let (stream, addr) = self.watcher.accept().await?;
|
let (io, addr) =
|
||||||
|
future::poll_fn(|cx| self.watcher.poll_read_with(cx, |inner| inner.accept_std()))
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
let mio_stream = mio::net::TcpStream::from_stream(io)?;
|
||||||
let stream = TcpStream {
|
let stream = TcpStream {
|
||||||
watcher: Arc::new(stream),
|
watcher: Arc::new(Watcher::new(mio_stream)),
|
||||||
};
|
};
|
||||||
Ok((stream, addr))
|
Ok((stream, addr))
|
||||||
}
|
}
|
||||||
|
@ -202,10 +206,9 @@ impl<'a> Stream for Incoming<'a> {
|
||||||
impl From<std::net::TcpListener> for TcpListener {
|
impl From<std::net::TcpListener> for TcpListener {
|
||||||
/// Converts a `std::net::TcpListener` into its asynchronous equivalent.
|
/// Converts a `std::net::TcpListener` into its asynchronous equivalent.
|
||||||
fn from(listener: std::net::TcpListener) -> TcpListener {
|
fn from(listener: std::net::TcpListener) -> TcpListener {
|
||||||
once_cell::sync::Lazy::force(&crate::rt::RUNTIME);
|
let mio_listener = mio::net::TcpListener::from_std(listener).unwrap();
|
||||||
|
|
||||||
TcpListener {
|
TcpListener {
|
||||||
watcher: Async::new(listener).expect("TcpListener is known to be good"),
|
watcher: Watcher::new(mio_listener),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -227,31 +230,29 @@ cfg_unix! {
|
||||||
|
|
||||||
impl IntoRawFd for TcpListener {
|
impl IntoRawFd for TcpListener {
|
||||||
fn into_raw_fd(self) -> RawFd {
|
fn into_raw_fd(self) -> RawFd {
|
||||||
self.watcher.into_raw_fd()
|
self.watcher.into_inner().into_raw_fd()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
cfg_windows! {
|
cfg_windows! {
|
||||||
use crate::os::windows::io::{
|
// use crate::os::windows::io::{AsRawHandle, FromRawHandle, IntoRawHandle, RawHandle};
|
||||||
AsRawSocket, FromRawSocket, IntoRawSocket, RawSocket,
|
//
|
||||||
};
|
// impl AsRawSocket for TcpListener {
|
||||||
|
// fn as_raw_socket(&self) -> RawSocket {
|
||||||
impl AsRawSocket for TcpListener {
|
// self.raw_socket
|
||||||
fn as_raw_socket(&self) -> RawSocket {
|
// }
|
||||||
self.watcher.as_raw_socket()
|
// }
|
||||||
}
|
//
|
||||||
}
|
// impl FromRawSocket for TcpListener {
|
||||||
|
// unsafe fn from_raw_socket(handle: RawSocket) -> TcpListener {
|
||||||
impl FromRawSocket for TcpListener {
|
// net::TcpListener::from_raw_socket(handle).try_into().unwrap()
|
||||||
unsafe fn from_raw_socket(handle: RawSocket) -> TcpListener {
|
// }
|
||||||
std::net::TcpListener::from_raw_socket(handle).into()
|
// }
|
||||||
}
|
//
|
||||||
}
|
// impl IntoRawSocket for TcpListener {
|
||||||
|
// fn into_raw_socket(self) -> RawSocket {
|
||||||
impl IntoRawSocket for TcpListener {
|
// self.raw_socket
|
||||||
fn into_raw_socket(self) -> RawSocket {
|
// }
|
||||||
self.watcher.into_raw_socket()
|
// }
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,12 +1,12 @@
|
||||||
use std::io::{IoSlice, IoSliceMut};
|
use std::io::{IoSlice, IoSliceMut, Read as _, Write as _};
|
||||||
use std::net::SocketAddr;
|
use std::net::SocketAddr;
|
||||||
use std::pin::Pin;
|
use std::pin::Pin;
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
use smol::Async;
|
use crate::future;
|
||||||
|
|
||||||
use crate::io::{self, Read, Write};
|
use crate::io::{self, Read, Write};
|
||||||
|
use crate::net::driver::Watcher;
|
||||||
use crate::net::ToSocketAddrs;
|
use crate::net::ToSocketAddrs;
|
||||||
use crate::sync::Arc;
|
|
||||||
use crate::task::{Context, Poll};
|
use crate::task::{Context, Poll};
|
||||||
|
|
||||||
/// A TCP stream between a local and a remote socket.
|
/// A TCP stream between a local and a remote socket.
|
||||||
|
@ -47,7 +47,7 @@ use crate::task::{Context, Poll};
|
||||||
/// ```
|
/// ```
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct TcpStream {
|
pub struct TcpStream {
|
||||||
pub(super) watcher: Arc<Async<std::net::TcpStream>>,
|
pub(super) watcher: Arc<Watcher<mio::net::TcpStream>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl TcpStream {
|
impl TcpStream {
|
||||||
|
@ -71,22 +71,32 @@ impl TcpStream {
|
||||||
/// # Ok(()) }) }
|
/// # Ok(()) }) }
|
||||||
/// ```
|
/// ```
|
||||||
pub async fn connect<A: ToSocketAddrs>(addrs: A) -> io::Result<TcpStream> {
|
pub async fn connect<A: ToSocketAddrs>(addrs: A) -> io::Result<TcpStream> {
|
||||||
once_cell::sync::Lazy::force(&crate::rt::RUNTIME);
|
|
||||||
|
|
||||||
let mut last_err = None;
|
let mut last_err = None;
|
||||||
let addrs = addrs.to_socket_addrs().await?;
|
let addrs = addrs.to_socket_addrs().await?;
|
||||||
|
|
||||||
for addr in addrs {
|
for addr in addrs {
|
||||||
match Async::<std::net::TcpStream>::connect(&addr).await {
|
// mio's TcpStream::connect is non-blocking and may just be in progress
|
||||||
Ok(stream) => {
|
// when it returns with `Ok`. We therefore wait for write readiness to
|
||||||
return Ok(TcpStream {
|
// be sure the connection has either been established or there was an
|
||||||
watcher: Arc::new(stream),
|
// error which we check for afterwards.
|
||||||
});
|
let watcher = match mio::net::TcpStream::connect(&addr) {
|
||||||
}
|
Ok(s) => Watcher::new(s),
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
last_err = Some(e);
|
last_err = Some(e);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
future::poll_fn(|cx| watcher.poll_write_ready(cx)).await;
|
||||||
|
|
||||||
|
match watcher.get_ref().take_error() {
|
||||||
|
Ok(None) => {
|
||||||
|
return Ok(TcpStream {
|
||||||
|
watcher: Arc::new(watcher),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Ok(Some(e)) => last_err = Some(e),
|
||||||
|
Err(e) => last_err = Some(e),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -204,7 +214,7 @@ impl TcpStream {
|
||||||
/// # Ok(()) }) }
|
/// # Ok(()) }) }
|
||||||
/// ```
|
/// ```
|
||||||
pub async fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
|
pub async fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
|
||||||
self.watcher.peek(buf).await
|
future::poll_fn(|cx| self.watcher.poll_read_with(cx, |inner| inner.peek(buf))).await
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Gets the value of the `TCP_NODELAY` option on this socket.
|
/// Gets the value of the `TCP_NODELAY` option on this socket.
|
||||||
|
@ -307,7 +317,7 @@ impl Read for &TcpStream {
|
||||||
cx: &mut Context<'_>,
|
cx: &mut Context<'_>,
|
||||||
buf: &mut [u8],
|
buf: &mut [u8],
|
||||||
) -> Poll<io::Result<usize>> {
|
) -> Poll<io::Result<usize>> {
|
||||||
Pin::new(&mut &*self.watcher).poll_read(cx, buf)
|
self.watcher.poll_read_with(cx, |mut inner| inner.read(buf))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -343,25 +353,26 @@ impl Write for &TcpStream {
|
||||||
cx: &mut Context<'_>,
|
cx: &mut Context<'_>,
|
||||||
buf: &[u8],
|
buf: &[u8],
|
||||||
) -> Poll<io::Result<usize>> {
|
) -> Poll<io::Result<usize>> {
|
||||||
Pin::new(&mut &*self.watcher).poll_write(cx, buf)
|
self.watcher
|
||||||
|
.poll_write_with(cx, |mut inner| inner.write(buf))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||||
Pin::new(&mut &*self.watcher).poll_flush(cx)
|
self.watcher.poll_write_with(cx, |mut inner| inner.flush())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
fn poll_close(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||||
Pin::new(&mut &*self.watcher).poll_close(cx)
|
self.shutdown(std::net::Shutdown::Write)?;
|
||||||
|
Poll::Ready(Ok(()))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<std::net::TcpStream> for TcpStream {
|
impl From<std::net::TcpStream> for TcpStream {
|
||||||
/// Converts a `std::net::TcpStream` into its asynchronous equivalent.
|
/// Converts a `std::net::TcpStream` into its asynchronous equivalent.
|
||||||
fn from(stream: std::net::TcpStream) -> TcpStream {
|
fn from(stream: std::net::TcpStream) -> TcpStream {
|
||||||
once_cell::sync::Lazy::force(&crate::rt::RUNTIME);
|
let mio_stream = mio::net::TcpStream::from_stream(stream).unwrap();
|
||||||
|
|
||||||
TcpStream {
|
TcpStream {
|
||||||
watcher: Arc::new(Async::new(stream).expect("TcpStream is known to be good")),
|
watcher: Arc::new(Watcher::new(mio_stream)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -392,28 +403,23 @@ cfg_unix! {
|
||||||
}
|
}
|
||||||
|
|
||||||
cfg_windows! {
|
cfg_windows! {
|
||||||
use crate::os::windows::io::{
|
// use crate::os::windows::io::{AsRawHandle, FromRawHandle, IntoRawHandle, RawHandle};
|
||||||
RawSocket, AsRawSocket, FromRawSocket, IntoRawSocket
|
//
|
||||||
};
|
// impl AsRawSocket for TcpStream {
|
||||||
|
// fn as_raw_socket(&self) -> RawSocket {
|
||||||
impl AsRawSocket for TcpStream {
|
// self.raw_socket
|
||||||
fn as_raw_socket(&self) -> RawSocket {
|
// }
|
||||||
self.watcher.get_ref().as_raw_socket()
|
// }
|
||||||
}
|
//
|
||||||
}
|
// impl FromRawSocket for TcpStream {
|
||||||
|
// unsafe fn from_raw_socket(handle: RawSocket) -> TcpStream {
|
||||||
impl FromRawSocket for TcpStream {
|
// net::TcpStream::from_raw_socket(handle).try_into().unwrap()
|
||||||
unsafe fn from_raw_socket(handle: RawSocket) -> TcpStream {
|
// }
|
||||||
std::net::TcpStream::from_raw_socket(handle).into()
|
// }
|
||||||
}
|
//
|
||||||
}
|
// impl IntoRawSocket for TcpListener {
|
||||||
|
// fn into_raw_socket(self) -> RawSocket {
|
||||||
impl IntoRawSocket for TcpStream {
|
// self.raw_socket
|
||||||
fn into_raw_socket(self) -> RawSocket {
|
// }
|
||||||
// TODO(stjepang): This does not mean `RawFd` is now the sole owner of the file
|
// }
|
||||||
// descriptor because it's possible that there are other clones of this `TcpStream`
|
|
||||||
// using it at the same time. We should probably document that behavior.
|
|
||||||
self.as_raw_socket()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -2,8 +2,8 @@ use std::io;
|
||||||
use std::net::SocketAddr;
|
use std::net::SocketAddr;
|
||||||
use std::net::{Ipv4Addr, Ipv6Addr};
|
use std::net::{Ipv4Addr, Ipv6Addr};
|
||||||
|
|
||||||
use smol::Async;
|
use crate::future;
|
||||||
|
use crate::net::driver::Watcher;
|
||||||
use crate::net::ToSocketAddrs;
|
use crate::net::ToSocketAddrs;
|
||||||
use crate::utils::Context as _;
|
use crate::utils::Context as _;
|
||||||
|
|
||||||
|
@ -45,7 +45,7 @@ use crate::utils::Context as _;
|
||||||
/// ```
|
/// ```
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct UdpSocket {
|
pub struct UdpSocket {
|
||||||
watcher: Async<std::net::UdpSocket>,
|
watcher: Watcher<mio::net::UdpSocket>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl UdpSocket {
|
impl UdpSocket {
|
||||||
|
@ -68,15 +68,17 @@ impl UdpSocket {
|
||||||
/// # Ok(()) }) }
|
/// # Ok(()) }) }
|
||||||
/// ```
|
/// ```
|
||||||
pub async fn bind<A: ToSocketAddrs>(addrs: A) -> io::Result<UdpSocket> {
|
pub async fn bind<A: ToSocketAddrs>(addrs: A) -> io::Result<UdpSocket> {
|
||||||
once_cell::sync::Lazy::force(&crate::rt::RUNTIME);
|
|
||||||
|
|
||||||
let mut last_err = None;
|
let mut last_err = None;
|
||||||
let addrs = addrs.to_socket_addrs().await?;
|
let addrs = addrs
|
||||||
|
.to_socket_addrs()
|
||||||
|
.await?;
|
||||||
|
|
||||||
for addr in addrs {
|
for addr in addrs {
|
||||||
match Async::<std::net::UdpSocket>::bind(&addr) {
|
match mio::net::UdpSocket::bind(&addr) {
|
||||||
Ok(socket) => {
|
Ok(mio_socket) => {
|
||||||
return Ok(UdpSocket { watcher: socket });
|
return Ok(UdpSocket {
|
||||||
|
watcher: Watcher::new(mio_socket),
|
||||||
|
});
|
||||||
}
|
}
|
||||||
Err(err) => last_err = Some(err),
|
Err(err) => last_err = Some(err),
|
||||||
}
|
}
|
||||||
|
@ -90,32 +92,6 @@ impl UdpSocket {
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the peer address that this listener is connected to.
|
|
||||||
///
|
|
||||||
/// This can be useful, for example, when connect to port 0 to figure out which port was
|
|
||||||
/// actually connected.
|
|
||||||
///
|
|
||||||
/// # Examples
|
|
||||||
///
|
|
||||||
/// ```no_run
|
|
||||||
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
|
|
||||||
/// #
|
|
||||||
/// use async_std::net::UdpSocket;
|
|
||||||
///
|
|
||||||
/// let socket1 = UdpSocket::bind("127.0.0.1:0").await?;
|
|
||||||
/// let socket2 = UdpSocket::bind("127.0.0.1:0").await?;
|
|
||||||
/// socket1.connect(socket2.local_addr()?).await?;
|
|
||||||
/// let addr = socket1.peer_addr()?;
|
|
||||||
/// #
|
|
||||||
/// # Ok(()) }) }
|
|
||||||
/// ```
|
|
||||||
pub fn peer_addr(&self) -> io::Result<SocketAddr> {
|
|
||||||
self.watcher
|
|
||||||
.get_ref()
|
|
||||||
.peer_addr()
|
|
||||||
.context(|| String::from("could not get peer address"))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns the local address that this listener is bound to.
|
/// Returns the local address that this listener is bound to.
|
||||||
///
|
///
|
||||||
/// This can be useful, for example, when binding to port 0 to figure out which port was
|
/// This can be useful, for example, when binding to port 0 to figure out which port was
|
||||||
|
@ -177,8 +153,10 @@ impl UdpSocket {
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
future::poll_fn(|cx| {
|
||||||
self.watcher
|
self.watcher
|
||||||
.send_to(buf, addr)
|
.poll_write_with(cx, |inner| inner.send_to(buf, &addr))
|
||||||
|
})
|
||||||
.await
|
.await
|
||||||
.context(|| format!("could not send packet to {}", addr))
|
.context(|| format!("could not send packet to {}", addr))
|
||||||
}
|
}
|
||||||
|
@ -203,7 +181,22 @@ impl UdpSocket {
|
||||||
/// # Ok(()) }) }
|
/// # Ok(()) }) }
|
||||||
/// ```
|
/// ```
|
||||||
pub async fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
|
pub async fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
|
||||||
self.watcher.recv_from(buf).await
|
future::poll_fn(|cx| {
|
||||||
|
self.watcher
|
||||||
|
.poll_read_with(cx, |inner| inner.recv_from(buf))
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.context(|| {
|
||||||
|
use std::fmt::Write;
|
||||||
|
|
||||||
|
let mut error = String::from("could not receive data on ");
|
||||||
|
if let Ok(addr) = self.local_addr() {
|
||||||
|
let _ = write!(&mut error, "{}", addr);
|
||||||
|
} else {
|
||||||
|
error.push_str("socket");
|
||||||
|
}
|
||||||
|
error
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Connects the UDP socket to a remote address.
|
/// Connects the UDP socket to a remote address.
|
||||||
|
@ -274,7 +267,19 @@ impl UdpSocket {
|
||||||
/// # Ok(()) }) }
|
/// # Ok(()) }) }
|
||||||
/// ```
|
/// ```
|
||||||
pub async fn send(&self, buf: &[u8]) -> io::Result<usize> {
|
pub async fn send(&self, buf: &[u8]) -> io::Result<usize> {
|
||||||
self.watcher.send(buf).await
|
future::poll_fn(|cx| self.watcher.poll_write_with(cx, |inner| inner.send(buf)))
|
||||||
|
.await
|
||||||
|
.context(|| {
|
||||||
|
use std::fmt::Write;
|
||||||
|
|
||||||
|
let mut error = String::from("could not send data on ");
|
||||||
|
if let Ok(addr) = self.local_addr() {
|
||||||
|
let _ = write!(&mut error, "{}", addr);
|
||||||
|
} else {
|
||||||
|
error.push_str("socket");
|
||||||
|
}
|
||||||
|
error
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Receives data from the socket.
|
/// Receives data from the socket.
|
||||||
|
@ -298,7 +303,19 @@ impl UdpSocket {
|
||||||
/// # Ok(()) }) }
|
/// # Ok(()) }) }
|
||||||
/// ```
|
/// ```
|
||||||
pub async fn recv(&self, buf: &mut [u8]) -> io::Result<usize> {
|
pub async fn recv(&self, buf: &mut [u8]) -> io::Result<usize> {
|
||||||
self.watcher.recv(buf).await
|
future::poll_fn(|cx| self.watcher.poll_read_with(cx, |inner| inner.recv(buf)))
|
||||||
|
.await
|
||||||
|
.context(|| {
|
||||||
|
use std::fmt::Write;
|
||||||
|
|
||||||
|
let mut error = String::from("could not receive data on ");
|
||||||
|
if let Ok(addr) = self.local_addr() {
|
||||||
|
let _ = write!(&mut error, "{}", addr);
|
||||||
|
} else {
|
||||||
|
error.push_str("socket");
|
||||||
|
}
|
||||||
|
error
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Gets the value of the `SO_BROADCAST` option for this socket.
|
/// Gets the value of the `SO_BROADCAST` option for this socket.
|
||||||
|
@ -481,10 +498,9 @@ impl UdpSocket {
|
||||||
impl From<std::net::UdpSocket> for UdpSocket {
|
impl From<std::net::UdpSocket> for UdpSocket {
|
||||||
/// Converts a `std::net::UdpSocket` into its asynchronous equivalent.
|
/// Converts a `std::net::UdpSocket` into its asynchronous equivalent.
|
||||||
fn from(socket: std::net::UdpSocket) -> UdpSocket {
|
fn from(socket: std::net::UdpSocket) -> UdpSocket {
|
||||||
once_cell::sync::Lazy::force(&crate::rt::RUNTIME);
|
let mio_socket = mio::net::UdpSocket::from_socket(socket).unwrap();
|
||||||
|
|
||||||
UdpSocket {
|
UdpSocket {
|
||||||
watcher: Async::new(socket).expect("UdpSocket is known to be good"),
|
watcher: Watcher::new(mio_socket),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -506,31 +522,29 @@ cfg_unix! {
|
||||||
|
|
||||||
impl IntoRawFd for UdpSocket {
|
impl IntoRawFd for UdpSocket {
|
||||||
fn into_raw_fd(self) -> RawFd {
|
fn into_raw_fd(self) -> RawFd {
|
||||||
self.watcher.into_raw_fd()
|
self.watcher.into_inner().into_raw_fd()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
cfg_windows! {
|
cfg_windows! {
|
||||||
use crate::os::windows::io::{
|
// use crate::os::windows::io::{AsRawHandle, FromRawHandle, IntoRawHandle, RawHandle};
|
||||||
RawSocket, AsRawSocket, IntoRawSocket, FromRawSocket
|
//
|
||||||
};
|
// impl AsRawSocket for UdpSocket {
|
||||||
|
// fn as_raw_socket(&self) -> RawSocket {
|
||||||
impl AsRawSocket for UdpSocket {
|
// self.raw_socket
|
||||||
fn as_raw_socket(&self) -> RawSocket {
|
// }
|
||||||
self.watcher.get_ref().as_raw_socket()
|
// }
|
||||||
}
|
//
|
||||||
}
|
// impl FromRawSocket for UdpSocket {
|
||||||
|
// unsafe fn from_raw_socket(handle: RawSocket) -> UdpSocket {
|
||||||
impl FromRawSocket for UdpSocket {
|
// net::UdpSocket::from_raw_socket(handle).into()
|
||||||
unsafe fn from_raw_socket(handle: RawSocket) -> UdpSocket {
|
// }
|
||||||
std::net::UdpSocket::from_raw_socket(handle).into()
|
// }
|
||||||
}
|
//
|
||||||
}
|
// impl IntoRawSocket for UdpSocket {
|
||||||
|
// fn into_raw_socket(self) -> RawSocket {
|
||||||
impl IntoRawSocket for UdpSocket {
|
// self.raw_socket
|
||||||
fn into_raw_socket(self) -> RawSocket {
|
// }
|
||||||
self.watcher.into_raw_socket()
|
// }
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -4,7 +4,7 @@ use crate::prelude::*;
|
||||||
use crate::stream::{FromStream, IntoStream};
|
use crate::stream::{FromStream, IntoStream};
|
||||||
use std::convert::identity;
|
use std::convert::identity;
|
||||||
|
|
||||||
impl<T: Send, V> FromStream<Option<T>> for Option<V>
|
impl<T, V> FromStream<Option<T>> for Option<V>
|
||||||
where
|
where
|
||||||
V: FromStream<T>,
|
V: FromStream<T>,
|
||||||
{
|
{
|
||||||
|
@ -14,10 +14,7 @@ where
|
||||||
#[inline]
|
#[inline]
|
||||||
fn from_stream<'a, S: IntoStream<Item = Option<T>> + 'a>(
|
fn from_stream<'a, S: IntoStream<Item = Option<T>> + 'a>(
|
||||||
stream: S,
|
stream: S,
|
||||||
) -> Pin<Box<dyn Future<Output = Self> + 'a + Send>>
|
) -> Pin<Box<dyn Future<Output = Self> + 'a>> {
|
||||||
where
|
|
||||||
<S as IntoStream>::IntoStream: Send,
|
|
||||||
{
|
|
||||||
let stream = stream.into_stream();
|
let stream = stream.into_stream();
|
||||||
|
|
||||||
Box::pin(async move {
|
Box::pin(async move {
|
||||||
|
|
|
@ -2,14 +2,16 @@
|
||||||
|
|
||||||
use std::fmt;
|
use std::fmt;
|
||||||
use std::net::Shutdown;
|
use std::net::Shutdown;
|
||||||
use std::os::unix::net::UnixDatagram as StdUnixDatagram;
|
|
||||||
|
|
||||||
use smol::Async;
|
use mio_uds;
|
||||||
|
|
||||||
use super::SocketAddr;
|
use super::SocketAddr;
|
||||||
|
use crate::future;
|
||||||
use crate::io;
|
use crate::io;
|
||||||
|
use crate::net::driver::Watcher;
|
||||||
use crate::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd};
|
use crate::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd};
|
||||||
use crate::path::Path;
|
use crate::path::Path;
|
||||||
|
use crate::task::spawn_blocking;
|
||||||
|
|
||||||
/// A Unix datagram socket.
|
/// A Unix datagram socket.
|
||||||
///
|
///
|
||||||
|
@ -40,15 +42,13 @@ use crate::path::Path;
|
||||||
/// # Ok(()) }) }
|
/// # Ok(()) }) }
|
||||||
/// ```
|
/// ```
|
||||||
pub struct UnixDatagram {
|
pub struct UnixDatagram {
|
||||||
watcher: Async<StdUnixDatagram>,
|
watcher: Watcher<mio_uds::UnixDatagram>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl UnixDatagram {
|
impl UnixDatagram {
|
||||||
fn new(socket: StdUnixDatagram) -> UnixDatagram {
|
fn new(socket: mio_uds::UnixDatagram) -> UnixDatagram {
|
||||||
once_cell::sync::Lazy::force(&crate::rt::RUNTIME);
|
|
||||||
|
|
||||||
UnixDatagram {
|
UnixDatagram {
|
||||||
watcher: Async::new(socket).expect("UnixDatagram is known to be good"),
|
watcher: Watcher::new(socket),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -66,11 +66,9 @@ impl UnixDatagram {
|
||||||
/// # Ok(()) }) }
|
/// # Ok(()) }) }
|
||||||
/// ```
|
/// ```
|
||||||
pub async fn bind<P: AsRef<Path>>(path: P) -> io::Result<UnixDatagram> {
|
pub async fn bind<P: AsRef<Path>>(path: P) -> io::Result<UnixDatagram> {
|
||||||
once_cell::sync::Lazy::force(&crate::rt::RUNTIME);
|
|
||||||
|
|
||||||
let path = path.as_ref().to_owned();
|
let path = path.as_ref().to_owned();
|
||||||
let socket = Async::<StdUnixDatagram>::bind(path)?;
|
let socket = spawn_blocking(move || mio_uds::UnixDatagram::bind(path)).await?;
|
||||||
Ok(UnixDatagram { watcher: socket })
|
Ok(UnixDatagram::new(socket))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Creates a Unix datagram which is not bound to any address.
|
/// Creates a Unix datagram which is not bound to any address.
|
||||||
|
@ -87,7 +85,7 @@ impl UnixDatagram {
|
||||||
/// # Ok(()) }) }
|
/// # Ok(()) }) }
|
||||||
/// ```
|
/// ```
|
||||||
pub fn unbound() -> io::Result<UnixDatagram> {
|
pub fn unbound() -> io::Result<UnixDatagram> {
|
||||||
let socket = StdUnixDatagram::unbound()?;
|
let socket = mio_uds::UnixDatagram::unbound()?;
|
||||||
Ok(UnixDatagram::new(socket))
|
Ok(UnixDatagram::new(socket))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -107,7 +105,7 @@ impl UnixDatagram {
|
||||||
/// # Ok(()) }) }
|
/// # Ok(()) }) }
|
||||||
/// ```
|
/// ```
|
||||||
pub fn pair() -> io::Result<(UnixDatagram, UnixDatagram)> {
|
pub fn pair() -> io::Result<(UnixDatagram, UnixDatagram)> {
|
||||||
let (a, b) = StdUnixDatagram::pair()?;
|
let (a, b) = mio_uds::UnixDatagram::pair()?;
|
||||||
let a = UnixDatagram::new(a);
|
let a = UnixDatagram::new(a);
|
||||||
let b = UnixDatagram::new(b);
|
let b = UnixDatagram::new(b);
|
||||||
Ok((a, b))
|
Ok((a, b))
|
||||||
|
@ -199,7 +197,11 @@ impl UnixDatagram {
|
||||||
/// # Ok(()) }) }
|
/// # Ok(()) }) }
|
||||||
/// ```
|
/// ```
|
||||||
pub async fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
|
pub async fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
|
||||||
self.watcher.recv_from(buf).await
|
future::poll_fn(|cx| {
|
||||||
|
self.watcher
|
||||||
|
.poll_read_with(cx, |inner| inner.recv_from(buf))
|
||||||
|
})
|
||||||
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Receives data from the socket.
|
/// Receives data from the socket.
|
||||||
|
@ -220,7 +222,7 @@ impl UnixDatagram {
|
||||||
/// # Ok(()) }) }
|
/// # Ok(()) }) }
|
||||||
/// ```
|
/// ```
|
||||||
pub async fn recv(&self, buf: &mut [u8]) -> io::Result<usize> {
|
pub async fn recv(&self, buf: &mut [u8]) -> io::Result<usize> {
|
||||||
self.watcher.recv(buf).await
|
future::poll_fn(|cx| self.watcher.poll_read_with(cx, |inner| inner.recv(buf))).await
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Sends data on the socket to the specified address.
|
/// Sends data on the socket to the specified address.
|
||||||
|
@ -240,7 +242,11 @@ impl UnixDatagram {
|
||||||
/// # Ok(()) }) }
|
/// # Ok(()) }) }
|
||||||
/// ```
|
/// ```
|
||||||
pub async fn send_to<P: AsRef<Path>>(&self, buf: &[u8], path: P) -> io::Result<usize> {
|
pub async fn send_to<P: AsRef<Path>>(&self, buf: &[u8], path: P) -> io::Result<usize> {
|
||||||
self.watcher.send_to(buf, path.as_ref()).await
|
future::poll_fn(|cx| {
|
||||||
|
self.watcher
|
||||||
|
.poll_write_with(cx, |inner| inner.send_to(buf, path.as_ref()))
|
||||||
|
})
|
||||||
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Sends data on the socket to the socket's peer.
|
/// Sends data on the socket to the socket's peer.
|
||||||
|
@ -261,7 +267,7 @@ impl UnixDatagram {
|
||||||
/// # Ok(()) }) }
|
/// # Ok(()) }) }
|
||||||
/// ```
|
/// ```
|
||||||
pub async fn send(&self, buf: &[u8]) -> io::Result<usize> {
|
pub async fn send(&self, buf: &[u8]) -> io::Result<usize> {
|
||||||
self.watcher.send(buf).await
|
future::poll_fn(|cx| self.watcher.poll_write_with(cx, |inner| inner.send(buf))).await
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Shut down the read, write, or both halves of this connection.
|
/// Shut down the read, write, or both halves of this connection.
|
||||||
|
@ -306,35 +312,31 @@ impl fmt::Debug for UnixDatagram {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<StdUnixDatagram> for UnixDatagram {
|
impl From<std::os::unix::net::UnixDatagram> for UnixDatagram {
|
||||||
/// Converts a `std::os::unix::net::UnixDatagram` into its asynchronous equivalent.
|
/// Converts a `std::os::unix::net::UnixDatagram` into its asynchronous equivalent.
|
||||||
fn from(datagram: StdUnixDatagram) -> UnixDatagram {
|
fn from(datagram: std::os::unix::net::UnixDatagram) -> UnixDatagram {
|
||||||
once_cell::sync::Lazy::force(&crate::rt::RUNTIME);
|
let mio_datagram = mio_uds::UnixDatagram::from_datagram(datagram).unwrap();
|
||||||
|
|
||||||
UnixDatagram {
|
UnixDatagram {
|
||||||
watcher: Async::new(datagram).expect("UnixDatagram is known to be good"),
|
watcher: Watcher::new(mio_datagram),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl AsRawFd for UnixDatagram {
|
impl AsRawFd for UnixDatagram {
|
||||||
fn as_raw_fd(&self) -> RawFd {
|
fn as_raw_fd(&self) -> RawFd {
|
||||||
self.watcher.as_raw_fd()
|
self.watcher.get_ref().as_raw_fd()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl FromRawFd for UnixDatagram {
|
impl FromRawFd for UnixDatagram {
|
||||||
unsafe fn from_raw_fd(fd: RawFd) -> UnixDatagram {
|
unsafe fn from_raw_fd(fd: RawFd) -> UnixDatagram {
|
||||||
once_cell::sync::Lazy::force(&crate::rt::RUNTIME);
|
let datagram = std::os::unix::net::UnixDatagram::from_raw_fd(fd);
|
||||||
|
datagram.into()
|
||||||
let raw = StdUnixDatagram::from_raw_fd(fd);
|
|
||||||
let datagram = Async::<StdUnixDatagram>::new(raw).expect("invalid file descriptor");
|
|
||||||
UnixDatagram { watcher: datagram }
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl IntoRawFd for UnixDatagram {
|
impl IntoRawFd for UnixDatagram {
|
||||||
fn into_raw_fd(self) -> RawFd {
|
fn into_raw_fd(self) -> RawFd {
|
||||||
self.watcher.into_raw_fd()
|
self.watcher.into_inner().into_raw_fd()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,20 +1,20 @@
|
||||||
//! Unix-specific networking extensions.
|
//! Unix-specific networking extensions.
|
||||||
|
|
||||||
use std::fmt;
|
use std::fmt;
|
||||||
use std::future::Future;
|
|
||||||
use std::os::unix::net::UnixListener as StdUnixListener;
|
|
||||||
use std::pin::Pin;
|
use std::pin::Pin;
|
||||||
|
use std::future::Future;
|
||||||
|
|
||||||
use smol::Async;
|
use mio_uds;
|
||||||
|
|
||||||
use super::SocketAddr;
|
use super::SocketAddr;
|
||||||
use super::UnixStream;
|
use super::UnixStream;
|
||||||
|
use crate::future;
|
||||||
use crate::io;
|
use crate::io;
|
||||||
|
use crate::net::driver::Watcher;
|
||||||
use crate::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd};
|
use crate::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd};
|
||||||
use crate::path::Path;
|
use crate::path::Path;
|
||||||
use crate::stream::Stream;
|
use crate::stream::Stream;
|
||||||
use crate::sync::Arc;
|
use crate::task::{spawn_blocking, Context, Poll};
|
||||||
use crate::task::{Context, Poll};
|
|
||||||
|
|
||||||
/// A Unix domain socket server, listening for connections.
|
/// A Unix domain socket server, listening for connections.
|
||||||
///
|
///
|
||||||
|
@ -50,7 +50,7 @@ use crate::task::{Context, Poll};
|
||||||
/// # Ok(()) }) }
|
/// # Ok(()) }) }
|
||||||
/// ```
|
/// ```
|
||||||
pub struct UnixListener {
|
pub struct UnixListener {
|
||||||
watcher: Async<StdUnixListener>,
|
watcher: Watcher<mio_uds::UnixListener>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl UnixListener {
|
impl UnixListener {
|
||||||
|
@ -68,12 +68,12 @@ impl UnixListener {
|
||||||
/// # Ok(()) }) }
|
/// # Ok(()) }) }
|
||||||
/// ```
|
/// ```
|
||||||
pub async fn bind<P: AsRef<Path>>(path: P) -> io::Result<UnixListener> {
|
pub async fn bind<P: AsRef<Path>>(path: P) -> io::Result<UnixListener> {
|
||||||
once_cell::sync::Lazy::force(&crate::rt::RUNTIME);
|
|
||||||
|
|
||||||
let path = path.as_ref().to_owned();
|
let path = path.as_ref().to_owned();
|
||||||
let listener = Async::<StdUnixListener>::bind(path)?;
|
let listener = spawn_blocking(move || mio_uds::UnixListener::bind(path)).await?;
|
||||||
|
|
||||||
Ok(UnixListener { watcher: listener })
|
Ok(UnixListener {
|
||||||
|
watcher: Watcher::new(listener),
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Accepts a new incoming connection to this listener.
|
/// Accepts a new incoming connection to this listener.
|
||||||
|
@ -93,14 +93,29 @@ impl UnixListener {
|
||||||
/// # Ok(()) }) }
|
/// # Ok(()) }) }
|
||||||
/// ```
|
/// ```
|
||||||
pub async fn accept(&self) -> io::Result<(UnixStream, SocketAddr)> {
|
pub async fn accept(&self) -> io::Result<(UnixStream, SocketAddr)> {
|
||||||
let (stream, addr) = self.watcher.accept().await?;
|
future::poll_fn(|cx| {
|
||||||
|
let res = futures_core::ready!(self.watcher.poll_read_with(cx, |inner| {
|
||||||
|
match inner.accept_std() {
|
||||||
|
// Converting to `WouldBlock` so that the watcher will
|
||||||
|
// add the waker of this task to a list of readers.
|
||||||
|
Ok(None) => Err(io::ErrorKind::WouldBlock.into()),
|
||||||
|
res => res,
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
|
||||||
Ok((
|
match res? {
|
||||||
UnixStream {
|
Some((io, addr)) => {
|
||||||
watcher: Arc::new(stream),
|
let mio_stream = mio_uds::UnixStream::from_stream(io)?;
|
||||||
},
|
let stream = UnixStream {
|
||||||
addr,
|
watcher: Watcher::new(mio_stream),
|
||||||
))
|
};
|
||||||
|
Poll::Ready(Ok((stream, addr)))
|
||||||
|
}
|
||||||
|
// This should never happen since `None` is converted to `WouldBlock`
|
||||||
|
None => unreachable!(),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns a stream of incoming connections.
|
/// Returns a stream of incoming connections.
|
||||||
|
@ -191,20 +206,19 @@ impl Stream for Incoming<'_> {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<StdUnixListener> for UnixListener {
|
impl From<std::os::unix::net::UnixListener> for UnixListener {
|
||||||
/// Converts a `std::os::unix::net::UnixListener` into its asynchronous equivalent.
|
/// Converts a `std::os::unix::net::UnixListener` into its asynchronous equivalent.
|
||||||
fn from(listener: StdUnixListener) -> UnixListener {
|
fn from(listener: std::os::unix::net::UnixListener) -> UnixListener {
|
||||||
once_cell::sync::Lazy::force(&crate::rt::RUNTIME);
|
let mio_listener = mio_uds::UnixListener::from_listener(listener).unwrap();
|
||||||
|
|
||||||
UnixListener {
|
UnixListener {
|
||||||
watcher: Async::new(listener).expect("UnixListener is known to be good"),
|
watcher: Watcher::new(mio_listener),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl AsRawFd for UnixListener {
|
impl AsRawFd for UnixListener {
|
||||||
fn as_raw_fd(&self) -> RawFd {
|
fn as_raw_fd(&self) -> RawFd {
|
||||||
self.watcher.as_raw_fd()
|
self.watcher.get_ref().as_raw_fd()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -217,6 +231,6 @@ impl FromRawFd for UnixListener {
|
||||||
|
|
||||||
impl IntoRawFd for UnixListener {
|
impl IntoRawFd for UnixListener {
|
||||||
fn into_raw_fd(self) -> RawFd {
|
fn into_raw_fd(self) -> RawFd {
|
||||||
self.watcher.into_raw_fd()
|
self.watcher.into_inner().into_raw_fd()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,18 +1,18 @@
|
||||||
//! Unix-specific networking extensions.
|
//! Unix-specific networking extensions.
|
||||||
|
|
||||||
use std::fmt;
|
use std::fmt;
|
||||||
|
use std::io::{Read as _, Write as _};
|
||||||
use std::net::Shutdown;
|
use std::net::Shutdown;
|
||||||
use std::os::unix::net::UnixStream as StdUnixStream;
|
|
||||||
use std::pin::Pin;
|
use std::pin::Pin;
|
||||||
|
|
||||||
use smol::Async;
|
use mio_uds;
|
||||||
|
|
||||||
use super::SocketAddr;
|
use super::SocketAddr;
|
||||||
use crate::io::{self, Read, Write};
|
use crate::io::{self, Read, Write};
|
||||||
|
use crate::net::driver::Watcher;
|
||||||
use crate::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd};
|
use crate::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd};
|
||||||
use crate::path::Path;
|
use crate::path::Path;
|
||||||
use crate::sync::Arc;
|
use crate::task::{spawn_blocking, Context, Poll};
|
||||||
use crate::task::{Context, Poll};
|
|
||||||
|
|
||||||
/// A Unix stream socket.
|
/// A Unix stream socket.
|
||||||
///
|
///
|
||||||
|
@ -37,9 +37,8 @@ use crate::task::{Context, Poll};
|
||||||
/// #
|
/// #
|
||||||
/// # Ok(()) }) }
|
/// # Ok(()) }) }
|
||||||
/// ```
|
/// ```
|
||||||
#[derive(Clone)]
|
|
||||||
pub struct UnixStream {
|
pub struct UnixStream {
|
||||||
pub(super) watcher: Arc<Async<StdUnixStream>>,
|
pub(super) watcher: Watcher<mio_uds::UnixStream>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl UnixStream {
|
impl UnixStream {
|
||||||
|
@ -57,12 +56,16 @@ impl UnixStream {
|
||||||
/// # Ok(()) }) }
|
/// # Ok(()) }) }
|
||||||
/// ```
|
/// ```
|
||||||
pub async fn connect<P: AsRef<Path>>(path: P) -> io::Result<UnixStream> {
|
pub async fn connect<P: AsRef<Path>>(path: P) -> io::Result<UnixStream> {
|
||||||
once_cell::sync::Lazy::force(&crate::rt::RUNTIME);
|
|
||||||
|
|
||||||
let path = path.as_ref().to_owned();
|
let path = path.as_ref().to_owned();
|
||||||
let stream = Arc::new(Async::<StdUnixStream>::connect(path).await?);
|
|
||||||
|
|
||||||
Ok(UnixStream { watcher: stream })
|
spawn_blocking(move || {
|
||||||
|
let std_stream = std::os::unix::net::UnixStream::connect(path)?;
|
||||||
|
let mio_stream = mio_uds::UnixStream::from_stream(std_stream)?;
|
||||||
|
Ok(UnixStream {
|
||||||
|
watcher: Watcher::new(mio_stream),
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Creates an unnamed pair of connected sockets.
|
/// Creates an unnamed pair of connected sockets.
|
||||||
|
@ -81,14 +84,12 @@ impl UnixStream {
|
||||||
/// # Ok(()) }) }
|
/// # Ok(()) }) }
|
||||||
/// ```
|
/// ```
|
||||||
pub fn pair() -> io::Result<(UnixStream, UnixStream)> {
|
pub fn pair() -> io::Result<(UnixStream, UnixStream)> {
|
||||||
once_cell::sync::Lazy::force(&crate::rt::RUNTIME);
|
let (a, b) = mio_uds::UnixStream::pair()?;
|
||||||
|
|
||||||
let (a, b) = Async::<StdUnixStream>::pair()?;
|
|
||||||
let a = UnixStream {
|
let a = UnixStream {
|
||||||
watcher: Arc::new(a),
|
watcher: Watcher::new(a),
|
||||||
};
|
};
|
||||||
let b = UnixStream {
|
let b = UnixStream {
|
||||||
watcher: Arc::new(b),
|
watcher: Watcher::new(b),
|
||||||
};
|
};
|
||||||
Ok((a, b))
|
Ok((a, b))
|
||||||
}
|
}
|
||||||
|
@ -168,7 +169,7 @@ impl Read for &UnixStream {
|
||||||
cx: &mut Context<'_>,
|
cx: &mut Context<'_>,
|
||||||
buf: &mut [u8],
|
buf: &mut [u8],
|
||||||
) -> Poll<io::Result<usize>> {
|
) -> Poll<io::Result<usize>> {
|
||||||
Pin::new(&mut &*self.watcher).poll_read(cx, buf)
|
self.watcher.poll_read_with(cx, |mut inner| inner.read(buf))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -196,15 +197,16 @@ impl Write for &UnixStream {
|
||||||
cx: &mut Context<'_>,
|
cx: &mut Context<'_>,
|
||||||
buf: &[u8],
|
buf: &[u8],
|
||||||
) -> Poll<io::Result<usize>> {
|
) -> Poll<io::Result<usize>> {
|
||||||
Pin::new(&mut &*self.watcher).poll_write(cx, buf)
|
self.watcher
|
||||||
|
.poll_write_with(cx, |mut inner| inner.write(buf))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||||
Pin::new(&mut &*self.watcher).poll_flush(cx)
|
self.watcher.poll_write_with(cx, |mut inner| inner.flush())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
fn poll_close(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||||
Pin::new(&mut &*self.watcher).poll_close(cx)
|
Poll::Ready(Ok(()))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -225,21 +227,19 @@ impl fmt::Debug for UnixStream {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<StdUnixStream> for UnixStream {
|
impl From<std::os::unix::net::UnixStream> for UnixStream {
|
||||||
/// Converts a `std::os::unix::net::UnixStream` into its asynchronous equivalent.
|
/// Converts a `std::os::unix::net::UnixStream` into its asynchronous equivalent.
|
||||||
fn from(stream: StdUnixStream) -> UnixStream {
|
fn from(stream: std::os::unix::net::UnixStream) -> UnixStream {
|
||||||
once_cell::sync::Lazy::force(&crate::rt::RUNTIME);
|
let mio_stream = mio_uds::UnixStream::from_stream(stream).unwrap();
|
||||||
|
|
||||||
let stream = Async::new(stream).expect("UnixStream is known to be good");
|
|
||||||
UnixStream {
|
UnixStream {
|
||||||
watcher: Arc::new(stream),
|
watcher: Watcher::new(mio_stream),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl AsRawFd for UnixStream {
|
impl AsRawFd for UnixStream {
|
||||||
fn as_raw_fd(&self) -> RawFd {
|
fn as_raw_fd(&self) -> RawFd {
|
||||||
self.watcher.as_raw_fd()
|
self.watcher.get_ref().as_raw_fd()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -252,6 +252,6 @@ impl FromRawFd for UnixStream {
|
||||||
|
|
||||||
impl IntoRawFd for UnixStream {
|
impl IntoRawFd for UnixStream {
|
||||||
fn into_raw_fd(self) -> RawFd {
|
fn into_raw_fd(self) -> RawFd {
|
||||||
self.as_raw_fd()
|
self.watcher.into_inner().into_raw_fd()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -2,8 +2,7 @@
|
||||||
|
|
||||||
cfg_not_docs! {
|
cfg_not_docs! {
|
||||||
pub use std::os::windows::io::{
|
pub use std::os::windows::io::{
|
||||||
AsRawHandle, FromRawHandle, IntoRawHandle, RawHandle,
|
AsRawHandle, FromRawHandle, IntoRawHandle, RawHandle, RawSocket,
|
||||||
AsRawSocket, FromRawSocket, IntoRawSocket, RawSocket,
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -46,33 +45,4 @@ cfg_docs! {
|
||||||
/// it once it's no longer needed.
|
/// it once it's no longer needed.
|
||||||
fn into_raw_handle(self) -> RawHandle;
|
fn into_raw_handle(self) -> RawHandle;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Creates I/O objects from raw sockets.
|
|
||||||
pub trait FromRawSocket {
|
|
||||||
/// Creates a new I/O object from the given raw socket.
|
|
||||||
///
|
|
||||||
/// This function will consume ownership of the socket provided and it will be closed when the returned object goes out of scope.
|
|
||||||
///
|
|
||||||
/// This function is also unsafe as the primitives currently returned have the contract that they are the sole owner of the
|
|
||||||
/// file descriptor they are wrapping. Usage of this function could accidentally allow violating this contract which can cause
|
|
||||||
/// memory unsafety in code that relies on it being true.
|
|
||||||
unsafe fn from_raw_socket(sock: RawSocket) -> Self;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Extracts raw sockets.
|
|
||||||
pub trait AsRawSocket {
|
|
||||||
/// Extracts the underlying raw socket from this object.
|
|
||||||
fn as_raw_socket(&self) -> RawSocket;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A trait to express the ability to consume an object and acquire ownership of
|
|
||||||
/// its raw `SOCKET`.
|
|
||||||
pub trait IntoRawSocket {
|
|
||||||
/// Consumes this object, returning the raw underlying socket.
|
|
||||||
///
|
|
||||||
/// This function **transfers ownership** of the underlying socket to the
|
|
||||||
/// caller. Callers are then the unique owners of the socket and must close
|
|
||||||
/// it once it's no longer needed.
|
|
||||||
fn into_raw_socket(self) -> RawSocket;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -4,9 +4,9 @@ use std::ffi::{OsStr, OsString};
|
||||||
use std::rc::Rc;
|
use std::rc::Rc;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use crate::fs;
|
||||||
|
use crate::io;
|
||||||
use crate::path::{Ancestors, Components, Display, Iter, PathBuf, StripPrefixError};
|
use crate::path::{Ancestors, Components, Display, Iter, PathBuf, StripPrefixError};
|
||||||
#[cfg(not(target_os = "unknown"))]
|
|
||||||
use crate::{fs, io};
|
|
||||||
|
|
||||||
/// A slice of a path.
|
/// A slice of a path.
|
||||||
///
|
///
|
||||||
|
@ -584,7 +584,6 @@ impl Path {
|
||||||
/// #
|
/// #
|
||||||
/// # Ok(()) }) }
|
/// # Ok(()) }) }
|
||||||
/// ```
|
/// ```
|
||||||
#[cfg(not(target_os = "unknown"))]
|
|
||||||
pub async fn metadata(&self) -> io::Result<fs::Metadata> {
|
pub async fn metadata(&self) -> io::Result<fs::Metadata> {
|
||||||
fs::metadata(self).await
|
fs::metadata(self).await
|
||||||
}
|
}
|
||||||
|
@ -608,7 +607,6 @@ impl Path {
|
||||||
/// #
|
/// #
|
||||||
/// # Ok(()) }) }
|
/// # Ok(()) }) }
|
||||||
/// ```
|
/// ```
|
||||||
#[cfg(not(target_os = "unknown"))]
|
|
||||||
pub async fn symlink_metadata(&self) -> io::Result<fs::Metadata> {
|
pub async fn symlink_metadata(&self) -> io::Result<fs::Metadata> {
|
||||||
fs::symlink_metadata(self).await
|
fs::symlink_metadata(self).await
|
||||||
}
|
}
|
||||||
|
@ -634,7 +632,6 @@ impl Path {
|
||||||
/// #
|
/// #
|
||||||
/// # Ok(()) }) }
|
/// # Ok(()) }) }
|
||||||
/// ```
|
/// ```
|
||||||
#[cfg(not(target_os = "unknown"))]
|
|
||||||
pub async fn canonicalize(&self) -> io::Result<PathBuf> {
|
pub async fn canonicalize(&self) -> io::Result<PathBuf> {
|
||||||
fs::canonicalize(self).await
|
fs::canonicalize(self).await
|
||||||
}
|
}
|
||||||
|
@ -657,7 +654,6 @@ impl Path {
|
||||||
/// #
|
/// #
|
||||||
/// # Ok(()) }) }
|
/// # Ok(()) }) }
|
||||||
/// ```
|
/// ```
|
||||||
#[cfg(not(target_os = "unknown"))]
|
|
||||||
pub async fn read_link(&self) -> io::Result<PathBuf> {
|
pub async fn read_link(&self) -> io::Result<PathBuf> {
|
||||||
fs::read_link(self).await
|
fs::read_link(self).await
|
||||||
}
|
}
|
||||||
|
@ -692,7 +688,6 @@ impl Path {
|
||||||
/// #
|
/// #
|
||||||
/// # Ok(()) }) }
|
/// # Ok(()) }) }
|
||||||
/// ```
|
/// ```
|
||||||
#[cfg(not(target_os = "unknown"))]
|
|
||||||
pub async fn read_dir(&self) -> io::Result<fs::ReadDir> {
|
pub async fn read_dir(&self) -> io::Result<fs::ReadDir> {
|
||||||
fs::read_dir(self).await
|
fs::read_dir(self).await
|
||||||
}
|
}
|
||||||
|
@ -722,7 +717,6 @@ impl Path {
|
||||||
/// check errors, call [fs::metadata].
|
/// check errors, call [fs::metadata].
|
||||||
///
|
///
|
||||||
/// [fs::metadata]: ../fs/fn.metadata.html
|
/// [fs::metadata]: ../fs/fn.metadata.html
|
||||||
#[cfg(not(target_os = "unknown"))]
|
|
||||||
pub async fn exists(&self) -> bool {
|
pub async fn exists(&self) -> bool {
|
||||||
fs::metadata(self).await.is_ok()
|
fs::metadata(self).await.is_ok()
|
||||||
}
|
}
|
||||||
|
@ -755,7 +749,6 @@ impl Path {
|
||||||
///
|
///
|
||||||
/// [fs::metadata]: ../fs/fn.metadata.html
|
/// [fs::metadata]: ../fs/fn.metadata.html
|
||||||
/// [fs::Metadata::is_file]: ../fs/struct.Metadata.html#method.is_file
|
/// [fs::Metadata::is_file]: ../fs/struct.Metadata.html#method.is_file
|
||||||
#[cfg(not(target_os = "unknown"))]
|
|
||||||
pub async fn is_file(&self) -> bool {
|
pub async fn is_file(&self) -> bool {
|
||||||
fs::metadata(self)
|
fs::metadata(self)
|
||||||
.await
|
.await
|
||||||
|
@ -792,7 +785,6 @@ impl Path {
|
||||||
///
|
///
|
||||||
/// [fs::metadata]: ../fs/fn.metadata.html
|
/// [fs::metadata]: ../fs/fn.metadata.html
|
||||||
/// [fs::Metadata::is_dir]: ../fs/struct.Metadata.html#method.is_dir
|
/// [fs::Metadata::is_dir]: ../fs/struct.Metadata.html#method.is_dir
|
||||||
#[cfg(not(target_os = "unknown"))]
|
|
||||||
pub async fn is_dir(&self) -> bool {
|
pub async fn is_dir(&self) -> bool {
|
||||||
fs::metadata(self)
|
fs::metadata(self)
|
||||||
.await
|
.await
|
||||||
|
|
|
@ -323,10 +323,7 @@ impl<P: AsRef<Path>> stream::Extend<P> for PathBuf {
|
||||||
fn extend<'a, S: IntoStream<Item = P> + 'a>(
|
fn extend<'a, S: IntoStream<Item = P> + 'a>(
|
||||||
&'a mut self,
|
&'a mut self,
|
||||||
stream: S,
|
stream: S,
|
||||||
) -> Pin<Box<dyn Future<Output = ()> + 'a + Send>>
|
) -> Pin<Box<dyn Future<Output = ()> + 'a>> {
|
||||||
where
|
|
||||||
<S as IntoStream>::IntoStream: Send,
|
|
||||||
{
|
|
||||||
let stream = stream.into_stream();
|
let stream = stream.into_stream();
|
||||||
|
|
||||||
Box::pin(async move {
|
Box::pin(async move {
|
||||||
|
@ -340,14 +337,11 @@ impl<P: AsRef<Path>> stream::Extend<P> for PathBuf {
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "unstable")]
|
#[cfg(feature = "unstable")]
|
||||||
impl<'b, P: AsRef<Path> + 'b + Send> FromStream<P> for PathBuf {
|
impl<'b, P: AsRef<Path> + 'b> FromStream<P> for PathBuf {
|
||||||
#[inline]
|
#[inline]
|
||||||
fn from_stream<'a, S: IntoStream<Item = P> + 'a>(
|
fn from_stream<'a, S: IntoStream<Item = P> + 'a>(
|
||||||
stream: S,
|
stream: S,
|
||||||
) -> Pin<Box<dyn Future<Output = Self> + 'a + Send>>
|
) -> Pin<Box<dyn Future<Output = Self> + 'a>> {
|
||||||
where
|
|
||||||
<S as IntoStream>::IntoStream: Send,
|
|
||||||
{
|
|
||||||
let stream = stream.into_stream();
|
let stream = stream.into_stream();
|
||||||
|
|
||||||
Box::pin(async move {
|
Box::pin(async move {
|
||||||
|
|
|
@ -5,8 +5,6 @@ use crate::stream::{FromStream, IntoStream};
|
||||||
|
|
||||||
impl<T, E, V> FromStream<Result<T, E>> for Result<V, E>
|
impl<T, E, V> FromStream<Result<T, E>> for Result<V, E>
|
||||||
where
|
where
|
||||||
T: Send,
|
|
||||||
E: Send,
|
|
||||||
V: FromStream<T>,
|
V: FromStream<T>,
|
||||||
{
|
{
|
||||||
/// Takes each element in the stream: if it is an `Err`, no further
|
/// Takes each element in the stream: if it is an `Err`, no further
|
||||||
|
@ -32,10 +30,7 @@ where
|
||||||
#[inline]
|
#[inline]
|
||||||
fn from_stream<'a, S: IntoStream<Item = Result<T, E>> + 'a>(
|
fn from_stream<'a, S: IntoStream<Item = Result<T, E>> + 'a>(
|
||||||
stream: S,
|
stream: S,
|
||||||
) -> Pin<Box<dyn Future<Output = Self> + 'a + Send>>
|
) -> Pin<Box<dyn Future<Output = Self> + 'a>> {
|
||||||
where
|
|
||||||
<S as IntoStream>::IntoStream: Send,
|
|
||||||
{
|
|
||||||
let stream = stream.into_stream();
|
let stream = stream.into_stream();
|
||||||
|
|
||||||
Box::pin(async move {
|
Box::pin(async move {
|
||||||
|
|
|
@ -1,34 +0,0 @@
|
||||||
//! The runtime.
|
|
||||||
|
|
||||||
use std::env;
|
|
||||||
use std::thread;
|
|
||||||
|
|
||||||
use once_cell::sync::Lazy;
|
|
||||||
|
|
||||||
use crate::future;
|
|
||||||
|
|
||||||
/// Dummy runtime struct.
|
|
||||||
pub struct Runtime {}
|
|
||||||
|
|
||||||
/// The global runtime.
|
|
||||||
pub static RUNTIME: Lazy<Runtime> = Lazy::new(|| {
|
|
||||||
// Create an executor thread pool.
|
|
||||||
|
|
||||||
let thread_count = env::var("ASYNC_STD_THREAD_COUNT")
|
|
||||||
.map(|env| {
|
|
||||||
env.parse()
|
|
||||||
.expect("ASYNC_STD_THREAD_COUNT must be a number")
|
|
||||||
})
|
|
||||||
.unwrap_or_else(|_| num_cpus::get())
|
|
||||||
.max(1);
|
|
||||||
|
|
||||||
let thread_name = env::var("ASYNC_STD_THREAD_NAME").unwrap_or("async-std/runtime".to_string());
|
|
||||||
|
|
||||||
for _ in 0..thread_count {
|
|
||||||
thread::Builder::new()
|
|
||||||
.name(thread_name.clone())
|
|
||||||
.spawn(|| crate::task::block_on(future::pending::<()>()))
|
|
||||||
.expect("cannot start a runtime thread");
|
|
||||||
}
|
|
||||||
Runtime {}
|
|
||||||
});
|
|
|
@ -34,9 +34,7 @@ pub trait Extend<A> {
|
||||||
fn extend<'a, T: IntoStream<Item = A> + 'a>(
|
fn extend<'a, T: IntoStream<Item = A> + 'a>(
|
||||||
&'a mut self,
|
&'a mut self,
|
||||||
stream: T,
|
stream: T,
|
||||||
) -> Pin<Box<dyn Future<Output = ()> + 'a + Send>>
|
) -> Pin<Box<dyn Future<Output = ()> + 'a>>;
|
||||||
where
|
|
||||||
<T as IntoStream>::IntoStream: Send;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Extends a collection with the contents of a stream.
|
/// Extends a collection with the contents of a stream.
|
||||||
|
@ -71,7 +69,6 @@ pub async fn extend<'a, C, T, S>(collection: &mut C, stream: S)
|
||||||
where
|
where
|
||||||
C: Extend<T>,
|
C: Extend<T>,
|
||||||
S: IntoStream<Item = T> + 'a,
|
S: IntoStream<Item = T> + 'a,
|
||||||
<S as IntoStream>::IntoStream: Send,
|
|
||||||
{
|
{
|
||||||
Extend::extend(collection, stream).await
|
Extend::extend(collection, stream).await
|
||||||
}
|
}
|
||||||
|
|
|
@ -72,10 +72,7 @@ use crate::stream::IntoStream;
|
||||||
/// impl FromStream<i32> for MyCollection {
|
/// impl FromStream<i32> for MyCollection {
|
||||||
/// fn from_stream<'a, S: IntoStream<Item = i32> + 'a>(
|
/// fn from_stream<'a, S: IntoStream<Item = i32> + 'a>(
|
||||||
/// stream: S,
|
/// stream: S,
|
||||||
/// ) -> Pin<Box<dyn Future<Output = Self> + 'a + Send>>
|
/// ) -> Pin<Box<dyn Future<Output = Self> + 'a>> {
|
||||||
/// where
|
|
||||||
/// <S as IntoStream>::IntoStream: Send,
|
|
||||||
/// {
|
|
||||||
/// let stream = stream.into_stream();
|
/// let stream = stream.into_stream();
|
||||||
///
|
///
|
||||||
/// Box::pin(async move {
|
/// Box::pin(async move {
|
||||||
|
@ -110,12 +107,12 @@ use crate::stream::IntoStream;
|
||||||
/// assert_eq!(c.0, vec![5, 5, 5, 5, 5]);
|
/// assert_eq!(c.0, vec![5, 5, 5, 5, 5]);
|
||||||
/// #
|
/// #
|
||||||
/// # Ok(()) }) }
|
/// # Ok(()) }) }
|
||||||
/// ```
|
///```
|
||||||
///
|
///
|
||||||
/// [`IntoStream`]: trait.IntoStream.html
|
/// [`IntoStream`]: trait.IntoStream.html
|
||||||
#[cfg(feature = "unstable")]
|
#[cfg(feature = "unstable")]
|
||||||
#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
|
#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
|
||||||
pub trait FromStream<T: Send> {
|
pub trait FromStream<T> {
|
||||||
/// Creates a value from a stream.
|
/// Creates a value from a stream.
|
||||||
///
|
///
|
||||||
/// # Examples
|
/// # Examples
|
||||||
|
@ -138,7 +135,5 @@ pub trait FromStream<T: Send> {
|
||||||
/// ```
|
/// ```
|
||||||
fn from_stream<'a, S: IntoStream<Item = T> + 'a>(
|
fn from_stream<'a, S: IntoStream<Item = T> + 'a>(
|
||||||
stream: S,
|
stream: S,
|
||||||
) -> Pin<Box<dyn Future<Output = Self> + 'a + Send>>
|
) -> Pin<Box<dyn Future<Output = Self> + 'a>>;
|
||||||
where
|
|
||||||
<S as IntoStream>::IntoStream: Send;
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,10 +1,10 @@
|
||||||
use std::future::Future;
|
|
||||||
use std::pin::Pin;
|
use std::pin::Pin;
|
||||||
use std::task::{Context, Poll};
|
use std::task::{Context, Poll};
|
||||||
use std::time::Duration;
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
use crate::future::Future;
|
||||||
use crate::stream::Stream;
|
use crate::stream::Stream;
|
||||||
use crate::utils::{timer_after, Timer};
|
use futures_timer::Delay;
|
||||||
|
|
||||||
/// Creates a new stream that yields at a set interval.
|
/// Creates a new stream that yields at a set interval.
|
||||||
///
|
///
|
||||||
|
@ -45,7 +45,7 @@ use crate::utils::{timer_after, Timer};
|
||||||
#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
|
#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
|
||||||
pub fn interval(dur: Duration) -> Interval {
|
pub fn interval(dur: Duration) -> Interval {
|
||||||
Interval {
|
Interval {
|
||||||
delay: timer_after(dur),
|
delay: Delay::new(dur),
|
||||||
interval: dur,
|
interval: dur,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -60,7 +60,7 @@ pub fn interval(dur: Duration) -> Interval {
|
||||||
#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
|
#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct Interval {
|
pub struct Interval {
|
||||||
delay: Timer,
|
delay: Delay,
|
||||||
interval: Duration,
|
interval: Duration,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -71,8 +71,125 @@ impl Stream for Interval {
|
||||||
if Pin::new(&mut self.delay).poll(cx).is_pending() {
|
if Pin::new(&mut self.delay).poll(cx).is_pending() {
|
||||||
return Poll::Pending;
|
return Poll::Pending;
|
||||||
}
|
}
|
||||||
let interval = self.interval;
|
let when = Instant::now();
|
||||||
let _ = std::mem::replace(&mut self.delay, timer_after(interval));
|
let next = next_interval(when, Instant::now(), self.interval);
|
||||||
|
self.delay.reset(next);
|
||||||
Poll::Ready(Some(()))
|
Poll::Ready(Some(()))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Converts Duration object to raw nanoseconds if possible
|
||||||
|
///
|
||||||
|
/// This is useful to divide intervals.
|
||||||
|
///
|
||||||
|
/// While technically for large duration it's impossible to represent any
|
||||||
|
/// duration as nanoseconds, the largest duration we can represent is about
|
||||||
|
/// 427_000 years. Large enough for any interval we would use or calculate in
|
||||||
|
/// async-std.
|
||||||
|
fn duration_to_nanos(dur: Duration) -> Option<u64> {
|
||||||
|
dur.as_secs()
|
||||||
|
.checked_mul(1_000_000_000)
|
||||||
|
.and_then(|v| v.checked_add(u64::from(dur.subsec_nanos())))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn next_interval(prev: Instant, now: Instant, interval: Duration) -> Instant {
|
||||||
|
let new = prev + interval;
|
||||||
|
if new > now {
|
||||||
|
return new;
|
||||||
|
}
|
||||||
|
|
||||||
|
let spent_ns = duration_to_nanos(now.duration_since(prev)).expect("interval should be expired");
|
||||||
|
let interval_ns =
|
||||||
|
duration_to_nanos(interval).expect("interval is less that 427 thousand years");
|
||||||
|
let mult = spent_ns / interval_ns + 1;
|
||||||
|
assert!(
|
||||||
|
mult < (1 << 32),
|
||||||
|
"can't skip more than 4 billion intervals of {:?} \
|
||||||
|
(trying to skip {})",
|
||||||
|
interval,
|
||||||
|
mult
|
||||||
|
);
|
||||||
|
prev + interval * (mult as u32)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod test {
|
||||||
|
use super::next_interval;
|
||||||
|
use std::cmp::Ordering;
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
struct Timeline(Instant);
|
||||||
|
|
||||||
|
impl Timeline {
|
||||||
|
fn new() -> Timeline {
|
||||||
|
Timeline(Instant::now())
|
||||||
|
}
|
||||||
|
fn at(&self, millis: u64) -> Instant {
|
||||||
|
self.0 + Duration::from_millis(millis)
|
||||||
|
}
|
||||||
|
fn at_ns(&self, sec: u64, nanos: u32) -> Instant {
|
||||||
|
self.0 + Duration::new(sec, nanos)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn dur(millis: u64) -> Duration {
|
||||||
|
Duration::from_millis(millis)
|
||||||
|
}
|
||||||
|
|
||||||
|
// The math around Instant/Duration isn't 100% precise due to rounding
|
||||||
|
// errors, see #249 for more info
|
||||||
|
fn almost_eq(a: Instant, b: Instant) -> bool {
|
||||||
|
match a.cmp(&b) {
|
||||||
|
Ordering::Equal => true,
|
||||||
|
Ordering::Greater => a - b < Duration::from_millis(1),
|
||||||
|
Ordering::Less => b - a < Duration::from_millis(1),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn norm_next() {
|
||||||
|
let tm = Timeline::new();
|
||||||
|
assert!(almost_eq(
|
||||||
|
next_interval(tm.at(1), tm.at(2), dur(10)),
|
||||||
|
tm.at(11)
|
||||||
|
));
|
||||||
|
assert!(almost_eq(
|
||||||
|
next_interval(tm.at(7777), tm.at(7788), dur(100)),
|
||||||
|
tm.at(7877)
|
||||||
|
));
|
||||||
|
assert!(almost_eq(
|
||||||
|
next_interval(tm.at(1), tm.at(1000), dur(2100)),
|
||||||
|
tm.at(2101)
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn fast_forward() {
|
||||||
|
let tm = Timeline::new();
|
||||||
|
assert!(almost_eq(
|
||||||
|
next_interval(tm.at(1), tm.at(1000), dur(10)),
|
||||||
|
tm.at(1001)
|
||||||
|
));
|
||||||
|
assert!(almost_eq(
|
||||||
|
next_interval(tm.at(7777), tm.at(8888), dur(100)),
|
||||||
|
tm.at(8977)
|
||||||
|
));
|
||||||
|
assert!(almost_eq(
|
||||||
|
next_interval(tm.at(1), tm.at(10000), dur(2100)),
|
||||||
|
tm.at(10501)
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// TODO: this test actually should be successful, but since we can't
|
||||||
|
/// multiply Duration on anything larger than u32 easily we decided
|
||||||
|
/// to allow it to fail for now
|
||||||
|
#[test]
|
||||||
|
#[should_panic(expected = "can't skip more than 4 billion intervals")]
|
||||||
|
fn large_skip() {
|
||||||
|
let tm = Timeline::new();
|
||||||
|
assert_eq!(
|
||||||
|
next_interval(tm.at_ns(0, 1), tm.at_ns(25, 0), Duration::new(0, 2)),
|
||||||
|
tm.at_ns(25, 1)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
@ -6,7 +6,6 @@ use pin_project_lite::pin_project;
|
||||||
|
|
||||||
use crate::stream::Stream;
|
use crate::stream::Stream;
|
||||||
use crate::task::{Context, Poll};
|
use crate::task::{Context, Poll};
|
||||||
use crate::utils::{timer_after, Timer};
|
|
||||||
|
|
||||||
pin_project! {
|
pin_project! {
|
||||||
#[doc(hidden)]
|
#[doc(hidden)]
|
||||||
|
@ -15,7 +14,7 @@ pin_project! {
|
||||||
#[pin]
|
#[pin]
|
||||||
stream: S,
|
stream: S,
|
||||||
#[pin]
|
#[pin]
|
||||||
delay: Timer,
|
delay: futures_timer::Delay,
|
||||||
delay_done: bool,
|
delay_done: bool,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -24,7 +23,7 @@ impl<S> Delay<S> {
|
||||||
pub(super) fn new(stream: S, dur: Duration) -> Self {
|
pub(super) fn new(stream: S, dur: Duration) -> Self {
|
||||||
Delay {
|
Delay {
|
||||||
stream,
|
stream,
|
||||||
delay: timer_after(dur),
|
delay: futures_timer::Delay::new(dur),
|
||||||
delay_done: false,
|
delay_done: false,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -50,15 +50,14 @@ where
|
||||||
let mut this = self.project();
|
let mut this = self.project();
|
||||||
loop {
|
loop {
|
||||||
if let Some(inner) = this.inner_stream.as_mut().as_pin_mut() {
|
if let Some(inner) = this.inner_stream.as_mut().as_pin_mut() {
|
||||||
match futures_core::ready!(inner.poll_next(cx)) {
|
if let item @ Some(_) = futures_core::ready!(inner.poll_next(cx)) {
|
||||||
item @ Some(_) => return Poll::Ready(item),
|
return Poll::Ready(item);
|
||||||
None => this.inner_stream.set(None),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
match futures_core::ready!(this.stream.as_mut().poll_next(cx)) {
|
match futures_core::ready!(this.stream.as_mut().poll_next(cx)) {
|
||||||
inner @ Some(_) => this.inner_stream.set(inner.map(IntoStream::into_stream)),
|
|
||||||
None => return Poll::Ready(None),
|
None => return Poll::Ready(None),
|
||||||
|
Some(inner) => this.inner_stream.set(Some(inner.into_stream())),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -52,15 +52,14 @@ where
|
||||||
let mut this = self.project();
|
let mut this = self.project();
|
||||||
loop {
|
loop {
|
||||||
if let Some(inner) = this.inner_stream.as_mut().as_pin_mut() {
|
if let Some(inner) = this.inner_stream.as_mut().as_pin_mut() {
|
||||||
match futures_core::ready!(inner.poll_next(cx)) {
|
if let item @ Some(_) = futures_core::ready!(inner.poll_next(cx)) {
|
||||||
item @ Some(_) => return Poll::Ready(item),
|
return Poll::Ready(item);
|
||||||
None => this.inner_stream.set(None),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
match futures_core::ready!(this.stream.as_mut().poll_next(cx)) {
|
match futures_core::ready!(this.stream.as_mut().poll_next(cx)) {
|
||||||
inner @ Some(_) => this.inner_stream.set(inner.map(IntoStream::into_stream)),
|
|
||||||
None => return Poll::Ready(None),
|
None => return Poll::Ready(None),
|
||||||
|
Some(inner) => this.inner_stream.set(Some(inner.into_stream())),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,6 +1,7 @@
|
||||||
use core::cmp::{Ord, Ordering};
|
use core::cmp::{Ord, Ordering};
|
||||||
use core::future::Future;
|
use core::marker::PhantomData;
|
||||||
use core::pin::Pin;
|
use core::pin::Pin;
|
||||||
|
use core::future::Future;
|
||||||
|
|
||||||
use pin_project_lite::pin_project;
|
use pin_project_lite::pin_project;
|
||||||
|
|
||||||
|
@ -10,23 +11,29 @@ use crate::task::{Context, Poll};
|
||||||
pin_project! {
|
pin_project! {
|
||||||
#[doc(hidden)]
|
#[doc(hidden)]
|
||||||
#[allow(missing_debug_implementations)]
|
#[allow(missing_debug_implementations)]
|
||||||
pub struct MaxFuture<S, T> {
|
pub struct MaxFuture<S, F, T> {
|
||||||
#[pin]
|
#[pin]
|
||||||
stream: S,
|
stream: S,
|
||||||
|
_compare: PhantomData<F>,
|
||||||
max: Option<T>,
|
max: Option<T>,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<S, T> MaxFuture<S, T> {
|
impl<S, F, T> MaxFuture<S, F, T> {
|
||||||
pub(super) fn new(stream: S) -> Self {
|
pub(super) fn new(stream: S) -> Self {
|
||||||
Self { stream, max: None }
|
Self {
|
||||||
|
stream,
|
||||||
|
_compare: PhantomData,
|
||||||
|
max: None,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<S> Future for MaxFuture<S, S::Item>
|
impl<S, F> Future for MaxFuture<S, F, S::Item>
|
||||||
where
|
where
|
||||||
S: Stream,
|
S: Stream,
|
||||||
S::Item: Ord,
|
S::Item: Ord,
|
||||||
|
F: FnMut(&S::Item, &S::Item) -> Ordering,
|
||||||
{
|
{
|
||||||
type Output = Option<S::Item>;
|
type Output = Option<S::Item>;
|
||||||
|
|
||||||
|
|
|
@ -1,6 +1,7 @@
|
||||||
use core::cmp::{Ord, Ordering};
|
use core::cmp::{Ord, Ordering};
|
||||||
use core::future::Future;
|
use core::marker::PhantomData;
|
||||||
use core::pin::Pin;
|
use core::pin::Pin;
|
||||||
|
use core::future::Future;
|
||||||
|
|
||||||
use pin_project_lite::pin_project;
|
use pin_project_lite::pin_project;
|
||||||
|
|
||||||
|
@ -10,23 +11,29 @@ use crate::task::{Context, Poll};
|
||||||
pin_project! {
|
pin_project! {
|
||||||
#[doc(hidden)]
|
#[doc(hidden)]
|
||||||
#[allow(missing_debug_implementations)]
|
#[allow(missing_debug_implementations)]
|
||||||
pub struct MinFuture<S, T> {
|
pub struct MinFuture<S, F, T> {
|
||||||
#[pin]
|
#[pin]
|
||||||
stream: S,
|
stream: S,
|
||||||
|
_compare: PhantomData<F>,
|
||||||
min: Option<T>,
|
min: Option<T>,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<S, T> MinFuture<S, T> {
|
impl<S, F, T> MinFuture<S, F, T> {
|
||||||
pub(super) fn new(stream: S) -> Self {
|
pub(super) fn new(stream: S) -> Self {
|
||||||
Self { stream, min: None }
|
Self {
|
||||||
|
stream,
|
||||||
|
_compare: PhantomData,
|
||||||
|
min: None,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<S> Future for MinFuture<S, S::Item>
|
impl<S, F> Future for MinFuture<S, F, S::Item>
|
||||||
where
|
where
|
||||||
S: Stream,
|
S: Stream,
|
||||||
S::Item: Ord,
|
S::Item: Ord,
|
||||||
|
F: FnMut(&S::Item, &S::Item) -> Ordering,
|
||||||
{
|
{
|
||||||
type Output = Option<S::Item>;
|
type Output = Option<S::Item>;
|
||||||
|
|
||||||
|
|
|
@ -1011,7 +1011,7 @@ extension_trait! {
|
||||||
|
|
||||||
# Examples
|
# Examples
|
||||||
|
|
||||||
```
|
```ignore
|
||||||
# fn main() { async_std::task::block_on(async {
|
# fn main() { async_std::task::block_on(async {
|
||||||
#
|
#
|
||||||
use async_std::prelude::*;
|
use async_std::prelude::*;
|
||||||
|
@ -1028,12 +1028,12 @@ extension_trait! {
|
||||||
# }) }
|
# }) }
|
||||||
```
|
```
|
||||||
"#]
|
"#]
|
||||||
fn max(
|
fn max<F>(
|
||||||
self,
|
self,
|
||||||
) -> impl Future<Output = Option<Self::Item>> [MaxFuture<Self, Self::Item>]
|
) -> impl Future<Output = Option<Self::Item>> [MaxFuture<Self, F, Self::Item>]
|
||||||
where
|
where
|
||||||
Self: Sized,
|
Self: Sized,
|
||||||
Self::Item: Ord,
|
F: FnMut(&Self::Item, &Self::Item) -> Ordering,
|
||||||
{
|
{
|
||||||
MaxFuture::new(self)
|
MaxFuture::new(self)
|
||||||
}
|
}
|
||||||
|
@ -1044,7 +1044,7 @@ extension_trait! {
|
||||||
|
|
||||||
# Examples
|
# Examples
|
||||||
|
|
||||||
```
|
```ignore
|
||||||
# fn main() { async_std::task::block_on(async {
|
# fn main() { async_std::task::block_on(async {
|
||||||
#
|
#
|
||||||
use async_std::prelude::*;
|
use async_std::prelude::*;
|
||||||
|
@ -1061,12 +1061,12 @@ extension_trait! {
|
||||||
# }) }
|
# }) }
|
||||||
```
|
```
|
||||||
"#]
|
"#]
|
||||||
fn min(
|
fn min<F>(
|
||||||
self,
|
self,
|
||||||
) -> impl Future<Output = Option<Self::Item>> [MinFuture<Self, Self::Item>]
|
) -> impl Future<Output = Option<Self::Item>> [MinFuture<Self, F, Self::Item>]
|
||||||
where
|
where
|
||||||
Self: Sized,
|
Self: Sized,
|
||||||
Self::Item: Ord,
|
F: FnMut(&Self::Item, &Self::Item) -> Ordering,
|
||||||
{
|
{
|
||||||
MinFuture::new(self)
|
MinFuture::new(self)
|
||||||
}
|
}
|
||||||
|
@ -1888,11 +1888,10 @@ extension_trait! {
|
||||||
#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
|
#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
|
||||||
fn collect<'a, B>(
|
fn collect<'a, B>(
|
||||||
self,
|
self,
|
||||||
) -> impl Future<Output = B> + 'a [Pin<Box<dyn Future<Output = B> + 'a + Send>>]
|
) -> impl Future<Output = B> + 'a [Pin<Box<dyn Future<Output = B> + 'a>>]
|
||||||
where
|
where
|
||||||
Self: Sized + 'a + Send,
|
Self: Sized + 'a,
|
||||||
B: FromStream<Self::Item>,
|
B: FromStream<Self::Item>,
|
||||||
Self::Item: Send,
|
|
||||||
{
|
{
|
||||||
FromStream::from_stream(self)
|
FromStream::from_stream(self)
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,12 +1,12 @@
|
||||||
use std::future::Future;
|
use std::future::Future;
|
||||||
use std::pin::Pin;
|
use std::pin::Pin;
|
||||||
use std::time::Duration;
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
use futures_timer::Delay;
|
||||||
use pin_project_lite::pin_project;
|
use pin_project_lite::pin_project;
|
||||||
|
|
||||||
use crate::stream::Stream;
|
use crate::stream::Stream;
|
||||||
use crate::task::{Context, Poll};
|
use crate::task::{Context, Poll};
|
||||||
use crate::utils::{timer_after, Timer};
|
|
||||||
|
|
||||||
pin_project! {
|
pin_project! {
|
||||||
/// A stream that only yields one element once every `duration`.
|
/// A stream that only yields one element once every `duration`.
|
||||||
|
@ -25,7 +25,7 @@ pin_project! {
|
||||||
#[pin]
|
#[pin]
|
||||||
blocked: bool,
|
blocked: bool,
|
||||||
#[pin]
|
#[pin]
|
||||||
delay: Timer,
|
delay: Delay,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -35,7 +35,7 @@ impl<S: Stream> Throttle<S> {
|
||||||
stream,
|
stream,
|
||||||
duration,
|
duration,
|
||||||
blocked: false,
|
blocked: false,
|
||||||
delay: timer_after(Duration::default()),
|
delay: Delay::new(Duration::default()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -59,7 +59,7 @@ impl<S: Stream> Stream for Throttle<S> {
|
||||||
Poll::Ready(None) => Poll::Ready(None),
|
Poll::Ready(None) => Poll::Ready(None),
|
||||||
Poll::Ready(Some(v)) => {
|
Poll::Ready(Some(v)) => {
|
||||||
*this.blocked = true;
|
*this.blocked = true;
|
||||||
let _ = std::mem::replace(&mut *this.delay, timer_after(*this.duration));
|
this.delay.reset(Instant::now() + *this.duration);
|
||||||
Poll::Ready(Some(v))
|
Poll::Ready(Some(v))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -4,11 +4,11 @@ use std::future::Future;
|
||||||
use std::pin::Pin;
|
use std::pin::Pin;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use futures_timer::Delay;
|
||||||
use pin_project_lite::pin_project;
|
use pin_project_lite::pin_project;
|
||||||
|
|
||||||
use crate::stream::Stream;
|
use crate::stream::Stream;
|
||||||
use crate::task::{Context, Poll};
|
use crate::task::{Context, Poll};
|
||||||
use crate::utils::{timer_after, Timer};
|
|
||||||
|
|
||||||
pin_project! {
|
pin_project! {
|
||||||
/// A stream with timeout time set
|
/// A stream with timeout time set
|
||||||
|
@ -17,13 +17,13 @@ pin_project! {
|
||||||
#[pin]
|
#[pin]
|
||||||
stream: S,
|
stream: S,
|
||||||
#[pin]
|
#[pin]
|
||||||
delay: Timer,
|
delay: Delay,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<S: Stream> Timeout<S> {
|
impl<S: Stream> Timeout<S> {
|
||||||
pub(crate) fn new(stream: S, dur: Duration) -> Self {
|
pub(crate) fn new(stream: S, dur: Duration) -> Self {
|
||||||
let delay = timer_after(dur);
|
let delay = Delay::new(dur);
|
||||||
|
|
||||||
Self { stream, delay }
|
Self { stream, delay }
|
||||||
}
|
}
|
||||||
|
|
|
@ -8,10 +8,7 @@ impl stream::Extend<char> for String {
|
||||||
fn extend<'a, S: IntoStream<Item = char> + 'a>(
|
fn extend<'a, S: IntoStream<Item = char> + 'a>(
|
||||||
&'a mut self,
|
&'a mut self,
|
||||||
stream: S,
|
stream: S,
|
||||||
) -> Pin<Box<dyn Future<Output = ()> + 'a + Send>>
|
) -> Pin<Box<dyn Future<Output = ()> + 'a>> {
|
||||||
where
|
|
||||||
<S as IntoStream>::IntoStream: Send,
|
|
||||||
{
|
|
||||||
let stream = stream.into_stream();
|
let stream = stream.into_stream();
|
||||||
self.reserve(stream.size_hint().0);
|
self.reserve(stream.size_hint().0);
|
||||||
|
|
||||||
|
@ -29,10 +26,7 @@ impl<'b> stream::Extend<&'b char> for String {
|
||||||
fn extend<'a, S: IntoStream<Item = &'b char> + 'a>(
|
fn extend<'a, S: IntoStream<Item = &'b char> + 'a>(
|
||||||
&'a mut self,
|
&'a mut self,
|
||||||
stream: S,
|
stream: S,
|
||||||
) -> Pin<Box<dyn Future<Output = ()> + 'a + Send>>
|
) -> Pin<Box<dyn Future<Output = ()> + 'a>> {
|
||||||
where
|
|
||||||
<S as IntoStream>::IntoStream: Send,
|
|
||||||
{
|
|
||||||
let stream = stream.into_stream();
|
let stream = stream.into_stream();
|
||||||
|
|
||||||
Box::pin(async move {
|
Box::pin(async move {
|
||||||
|
@ -49,10 +43,7 @@ impl<'b> stream::Extend<&'b str> for String {
|
||||||
fn extend<'a, S: IntoStream<Item = &'b str> + 'a>(
|
fn extend<'a, S: IntoStream<Item = &'b str> + 'a>(
|
||||||
&'a mut self,
|
&'a mut self,
|
||||||
stream: S,
|
stream: S,
|
||||||
) -> Pin<Box<dyn Future<Output = ()> + 'a + Send>>
|
) -> Pin<Box<dyn Future<Output = ()> + 'a>> {
|
||||||
where
|
|
||||||
<S as IntoStream>::IntoStream: Send,
|
|
||||||
{
|
|
||||||
let stream = stream.into_stream();
|
let stream = stream.into_stream();
|
||||||
|
|
||||||
Box::pin(async move {
|
Box::pin(async move {
|
||||||
|
@ -69,10 +60,7 @@ impl stream::Extend<String> for String {
|
||||||
fn extend<'a, S: IntoStream<Item = String> + 'a>(
|
fn extend<'a, S: IntoStream<Item = String> + 'a>(
|
||||||
&'a mut self,
|
&'a mut self,
|
||||||
stream: S,
|
stream: S,
|
||||||
) -> Pin<Box<dyn Future<Output = ()> + 'a + Send>>
|
) -> Pin<Box<dyn Future<Output = ()> + 'a>> {
|
||||||
where
|
|
||||||
<S as IntoStream>::IntoStream: Send,
|
|
||||||
{
|
|
||||||
let stream = stream.into_stream();
|
let stream = stream.into_stream();
|
||||||
|
|
||||||
Box::pin(async move {
|
Box::pin(async move {
|
||||||
|
@ -89,10 +77,7 @@ impl<'b> stream::Extend<Cow<'b, str>> for String {
|
||||||
fn extend<'a, S: IntoStream<Item = Cow<'b, str>> + 'a>(
|
fn extend<'a, S: IntoStream<Item = Cow<'b, str>> + 'a>(
|
||||||
&'a mut self,
|
&'a mut self,
|
||||||
stream: S,
|
stream: S,
|
||||||
) -> Pin<Box<dyn Future<Output = ()> + 'a + Send>>
|
) -> Pin<Box<dyn Future<Output = ()> + 'a>> {
|
||||||
where
|
|
||||||
<S as IntoStream>::IntoStream: Send,
|
|
||||||
{
|
|
||||||
let stream = stream.into_stream();
|
let stream = stream.into_stream();
|
||||||
|
|
||||||
Box::pin(async move {
|
Box::pin(async move {
|
||||||
|
|
|
@ -8,10 +8,7 @@ impl FromStream<char> for String {
|
||||||
#[inline]
|
#[inline]
|
||||||
fn from_stream<'a, S: IntoStream<Item = char> + 'a>(
|
fn from_stream<'a, S: IntoStream<Item = char> + 'a>(
|
||||||
stream: S,
|
stream: S,
|
||||||
) -> Pin<Box<dyn Future<Output = Self> + 'a + Send>>
|
) -> Pin<Box<dyn Future<Output = Self> + 'a>> {
|
||||||
where
|
|
||||||
<S as IntoStream>::IntoStream: Send,
|
|
||||||
{
|
|
||||||
let stream = stream.into_stream();
|
let stream = stream.into_stream();
|
||||||
|
|
||||||
Box::pin(async move {
|
Box::pin(async move {
|
||||||
|
@ -26,10 +23,7 @@ impl<'b> FromStream<&'b char> for String {
|
||||||
#[inline]
|
#[inline]
|
||||||
fn from_stream<'a, S: IntoStream<Item = &'b char> + 'a>(
|
fn from_stream<'a, S: IntoStream<Item = &'b char> + 'a>(
|
||||||
stream: S,
|
stream: S,
|
||||||
) -> Pin<Box<dyn Future<Output = Self> + 'a + Send>>
|
) -> Pin<Box<dyn Future<Output = Self> + 'a>> {
|
||||||
where
|
|
||||||
<S as IntoStream>::IntoStream: Send,
|
|
||||||
{
|
|
||||||
let stream = stream.into_stream();
|
let stream = stream.into_stream();
|
||||||
|
|
||||||
Box::pin(async move {
|
Box::pin(async move {
|
||||||
|
@ -44,10 +38,7 @@ impl<'b> FromStream<&'b str> for String {
|
||||||
#[inline]
|
#[inline]
|
||||||
fn from_stream<'a, S: IntoStream<Item = &'b str> + 'a>(
|
fn from_stream<'a, S: IntoStream<Item = &'b str> + 'a>(
|
||||||
stream: S,
|
stream: S,
|
||||||
) -> Pin<Box<dyn Future<Output = Self> + 'a + Send>>
|
) -> Pin<Box<dyn Future<Output = Self> + 'a>> {
|
||||||
where
|
|
||||||
<S as IntoStream>::IntoStream: Send,
|
|
||||||
{
|
|
||||||
let stream = stream.into_stream();
|
let stream = stream.into_stream();
|
||||||
|
|
||||||
Box::pin(async move {
|
Box::pin(async move {
|
||||||
|
@ -62,10 +53,7 @@ impl FromStream<String> for String {
|
||||||
#[inline]
|
#[inline]
|
||||||
fn from_stream<'a, S: IntoStream<Item = String> + 'a>(
|
fn from_stream<'a, S: IntoStream<Item = String> + 'a>(
|
||||||
stream: S,
|
stream: S,
|
||||||
) -> Pin<Box<dyn Future<Output = Self> + 'a + Send>>
|
) -> Pin<Box<dyn Future<Output = Self> + 'a>> {
|
||||||
where
|
|
||||||
<S as IntoStream>::IntoStream: Send,
|
|
||||||
{
|
|
||||||
let stream = stream.into_stream();
|
let stream = stream.into_stream();
|
||||||
|
|
||||||
Box::pin(async move {
|
Box::pin(async move {
|
||||||
|
@ -80,10 +68,7 @@ impl<'b> FromStream<Cow<'b, str>> for String {
|
||||||
#[inline]
|
#[inline]
|
||||||
fn from_stream<'a, S: IntoStream<Item = Cow<'b, str>> + 'a>(
|
fn from_stream<'a, S: IntoStream<Item = Cow<'b, str>> + 'a>(
|
||||||
stream: S,
|
stream: S,
|
||||||
) -> Pin<Box<dyn Future<Output = Self> + 'a + Send>>
|
) -> Pin<Box<dyn Future<Output = Self> + 'a>> {
|
||||||
where
|
|
||||||
<S as IntoStream>::IntoStream: Send,
|
|
||||||
{
|
|
||||||
let stream = stream.into_stream();
|
let stream = stream.into_stream();
|
||||||
|
|
||||||
Box::pin(async move {
|
Box::pin(async move {
|
||||||
|
|
|
@ -1,4 +1,6 @@
|
||||||
use crate::sync::{Condvar,Mutex};
|
use broadcaster::BroadcastChannel;
|
||||||
|
|
||||||
|
use crate::sync::Mutex;
|
||||||
|
|
||||||
/// A barrier enables multiple tasks to synchronize the beginning
|
/// A barrier enables multiple tasks to synchronize the beginning
|
||||||
/// of some computation.
|
/// of some computation.
|
||||||
|
@ -34,13 +36,14 @@ use crate::sync::{Condvar,Mutex};
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct Barrier {
|
pub struct Barrier {
|
||||||
state: Mutex<BarrierState>,
|
state: Mutex<BarrierState>,
|
||||||
cvar: Condvar,
|
wait: BroadcastChannel<(usize, usize)>,
|
||||||
num_tasks: usize,
|
n: usize,
|
||||||
}
|
}
|
||||||
|
|
||||||
// The inner state of a double barrier
|
// The inner state of a double barrier
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
struct BarrierState {
|
struct BarrierState {
|
||||||
|
waker: BroadcastChannel<(usize, usize)>,
|
||||||
count: usize,
|
count: usize,
|
||||||
generation_id: usize,
|
generation_id: usize,
|
||||||
}
|
}
|
||||||
|
@ -78,14 +81,25 @@ impl Barrier {
|
||||||
///
|
///
|
||||||
/// let barrier = Barrier::new(10);
|
/// let barrier = Barrier::new(10);
|
||||||
/// ```
|
/// ```
|
||||||
pub fn new(n: usize) -> Barrier {
|
pub fn new(mut n: usize) -> Barrier {
|
||||||
|
let waker = BroadcastChannel::new();
|
||||||
|
let wait = waker.clone();
|
||||||
|
|
||||||
|
if n == 0 {
|
||||||
|
// if n is 0, it's not clear what behavior the user wants.
|
||||||
|
// in std::sync::Barrier, an n of 0 exhibits the same behavior as n == 1, where every
|
||||||
|
// .wait() immediately unblocks, so we adopt that here as well.
|
||||||
|
n = 1;
|
||||||
|
}
|
||||||
|
|
||||||
Barrier {
|
Barrier {
|
||||||
state: Mutex::new(BarrierState {
|
state: Mutex::new(BarrierState {
|
||||||
|
waker,
|
||||||
count: 0,
|
count: 0,
|
||||||
generation_id: 1,
|
generation_id: 1,
|
||||||
}),
|
}),
|
||||||
cvar: Condvar::new(),
|
n,
|
||||||
num_tasks: n,
|
wait,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -129,20 +143,35 @@ impl Barrier {
|
||||||
/// # });
|
/// # });
|
||||||
/// ```
|
/// ```
|
||||||
pub async fn wait(&self) -> BarrierWaitResult {
|
pub async fn wait(&self) -> BarrierWaitResult {
|
||||||
let mut state = self.state.lock().await;
|
let mut lock = self.state.lock().await;
|
||||||
let local_gen = state.generation_id;
|
let local_gen = lock.generation_id;
|
||||||
state.count += 1;
|
|
||||||
|
|
||||||
if state.count < self.num_tasks {
|
lock.count += 1;
|
||||||
while local_gen == state.generation_id && state.count < self.num_tasks {
|
|
||||||
state = self.cvar.wait(state).await;
|
if lock.count < self.n {
|
||||||
|
let mut wait = self.wait.clone();
|
||||||
|
|
||||||
|
let mut generation_id = lock.generation_id;
|
||||||
|
let mut count = lock.count;
|
||||||
|
|
||||||
|
drop(lock);
|
||||||
|
|
||||||
|
while local_gen == generation_id && count < self.n {
|
||||||
|
let (g, c) = wait.recv().await.expect("sender has not been closed");
|
||||||
|
generation_id = g;
|
||||||
|
count = c;
|
||||||
}
|
}
|
||||||
|
|
||||||
BarrierWaitResult(false)
|
BarrierWaitResult(false)
|
||||||
} else {
|
} else {
|
||||||
state.count = 0;
|
lock.count = 0;
|
||||||
state.generation_id = state.generation_id.wrapping_add(1);
|
lock.generation_id = lock.generation_id.wrapping_add(1);
|
||||||
self.cvar.notify_all();
|
|
||||||
|
lock.waker
|
||||||
|
.send(&(lock.generation_id, lock.count))
|
||||||
|
.await
|
||||||
|
.expect("there should be at least one receiver");
|
||||||
|
|
||||||
BarrierWaitResult(true)
|
BarrierWaitResult(true)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -173,7 +202,7 @@ impl BarrierWaitResult {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(all(test, not(target_os = "unknown")))]
|
#[cfg(test)]
|
||||||
mod test {
|
mod test {
|
||||||
use futures::channel::mpsc::unbounded;
|
use futures::channel::mpsc::unbounded;
|
||||||
use futures::sink::SinkExt;
|
use futures::sink::SinkExt;
|
||||||
|
|
|
@ -1,6 +1,5 @@
|
||||||
use std::cell::UnsafeCell;
|
use std::cell::UnsafeCell;
|
||||||
use std::error::Error;
|
use std::fmt;
|
||||||
use std::fmt::{self, Debug, Display};
|
|
||||||
use std::future::Future;
|
use std::future::Future;
|
||||||
use std::isize;
|
use std::isize;
|
||||||
use std::marker::PhantomData;
|
use std::marker::PhantomData;
|
||||||
|
@ -22,8 +21,8 @@ use crate::sync::WakerSet;
|
||||||
/// This channel has a buffer that can hold at most `cap` messages at a time.
|
/// This channel has a buffer that can hold at most `cap` messages at a time.
|
||||||
///
|
///
|
||||||
/// Senders and receivers can be cloned. When all senders associated with a channel get dropped, it
|
/// Senders and receivers can be cloned. When all senders associated with a channel get dropped, it
|
||||||
/// becomes closed. Receive operations on a closed and empty channel return [RecvError] instead of
|
/// becomes closed. Receive operations on a closed and empty channel return `None` instead of
|
||||||
/// trying to await a message when using [Receiver::recv] or `None` when used as a [Stream].
|
/// trying to await a message.
|
||||||
///
|
///
|
||||||
/// # Panics
|
/// # Panics
|
||||||
///
|
///
|
||||||
|
@ -32,7 +31,6 @@ use crate::sync::WakerSet;
|
||||||
/// # Examples
|
/// # Examples
|
||||||
///
|
///
|
||||||
/// ```
|
/// ```
|
||||||
/// # fn main() -> Result<(), async_std::sync::RecvError> {
|
|
||||||
/// # async_std::task::block_on(async {
|
/// # async_std::task::block_on(async {
|
||||||
/// #
|
/// #
|
||||||
/// use std::time::Duration;
|
/// use std::time::Duration;
|
||||||
|
@ -43,7 +41,7 @@ use crate::sync::WakerSet;
|
||||||
/// let (s, r) = channel(1);
|
/// let (s, r) = channel(1);
|
||||||
///
|
///
|
||||||
/// // This call returns immediately because there is enough space in the channel.
|
/// // This call returns immediately because there is enough space in the channel.
|
||||||
/// s.send(1usize).await;
|
/// s.send(1).await;
|
||||||
///
|
///
|
||||||
/// task::spawn(async move {
|
/// task::spawn(async move {
|
||||||
/// // This call will have to wait because the channel is full.
|
/// // This call will have to wait because the channel is full.
|
||||||
|
@ -52,11 +50,10 @@ use crate::sync::WakerSet;
|
||||||
/// });
|
/// });
|
||||||
///
|
///
|
||||||
/// task::sleep(Duration::from_secs(1)).await;
|
/// task::sleep(Duration::from_secs(1)).await;
|
||||||
/// assert_eq!(r.recv().await?, 1);
|
/// assert_eq!(r.recv().await, Some(1));
|
||||||
/// assert_eq!(r.recv().await?, 2);
|
/// assert_eq!(r.recv().await, Some(2));
|
||||||
/// # Ok(())
|
|
||||||
/// #
|
/// #
|
||||||
/// # }) }
|
/// # })
|
||||||
/// ```
|
/// ```
|
||||||
#[cfg(feature = "unstable")]
|
#[cfg(feature = "unstable")]
|
||||||
#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
|
#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
|
||||||
|
@ -115,7 +112,6 @@ impl<T> Sender<T> {
|
||||||
/// # Examples
|
/// # Examples
|
||||||
///
|
///
|
||||||
/// ```
|
/// ```
|
||||||
/// # fn main() -> Result<(), async_std::sync::RecvError> {
|
|
||||||
/// # async_std::task::block_on(async {
|
/// # async_std::task::block_on(async {
|
||||||
/// #
|
/// #
|
||||||
/// use async_std::sync::channel;
|
/// use async_std::sync::channel;
|
||||||
|
@ -128,12 +124,11 @@ impl<T> Sender<T> {
|
||||||
/// s.send(2).await;
|
/// s.send(2).await;
|
||||||
/// });
|
/// });
|
||||||
///
|
///
|
||||||
/// assert_eq!(r.recv().await?, 1);
|
/// assert_eq!(r.recv().await, Some(1));
|
||||||
/// assert_eq!(r.recv().await?, 2);
|
/// assert_eq!(r.recv().await, Some(2));
|
||||||
/// assert!(r.recv().await.is_err());
|
/// assert_eq!(r.recv().await, None);
|
||||||
/// #
|
/// #
|
||||||
/// # Ok(())
|
/// # })
|
||||||
/// # }) }
|
|
||||||
/// ```
|
/// ```
|
||||||
pub async fn send(&self, msg: T) {
|
pub async fn send(&self, msg: T) {
|
||||||
struct SendFuture<'a, T> {
|
struct SendFuture<'a, T> {
|
||||||
|
@ -197,27 +192,6 @@ impl<T> Sender<T> {
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Attempts to send a message into the channel.
|
|
||||||
///
|
|
||||||
/// If the channel is full, this method will return an error.
|
|
||||||
///
|
|
||||||
/// # Examples
|
|
||||||
///
|
|
||||||
/// ```
|
|
||||||
/// # async_std::task::block_on(async {
|
|
||||||
/// #
|
|
||||||
/// use async_std::sync::channel;
|
|
||||||
///
|
|
||||||
/// let (s, r) = channel(1);
|
|
||||||
/// assert!(s.try_send(1).is_ok());
|
|
||||||
/// assert!(s.try_send(2).is_err());
|
|
||||||
/// #
|
|
||||||
/// # })
|
|
||||||
/// ```
|
|
||||||
pub fn try_send(&self, msg: T) -> Result<(), TrySendError<T>> {
|
|
||||||
self.channel.try_send(msg)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns the channel capacity.
|
/// Returns the channel capacity.
|
||||||
///
|
///
|
||||||
/// # Examples
|
/// # Examples
|
||||||
|
@ -339,7 +313,6 @@ impl<T> fmt::Debug for Sender<T> {
|
||||||
/// # Examples
|
/// # Examples
|
||||||
///
|
///
|
||||||
/// ```
|
/// ```
|
||||||
/// # fn main() -> Result<(), async_std::sync::RecvError> {
|
|
||||||
/// # async_std::task::block_on(async {
|
/// # async_std::task::block_on(async {
|
||||||
/// #
|
/// #
|
||||||
/// use std::time::Duration;
|
/// use std::time::Duration;
|
||||||
|
@ -350,16 +323,15 @@ impl<T> fmt::Debug for Sender<T> {
|
||||||
/// let (s, r) = channel(100);
|
/// let (s, r) = channel(100);
|
||||||
///
|
///
|
||||||
/// task::spawn(async move {
|
/// task::spawn(async move {
|
||||||
/// s.send(1usize).await;
|
/// s.send(1).await;
|
||||||
/// task::sleep(Duration::from_secs(1)).await;
|
/// task::sleep(Duration::from_secs(1)).await;
|
||||||
/// s.send(2).await;
|
/// s.send(2).await;
|
||||||
/// });
|
/// });
|
||||||
///
|
///
|
||||||
/// assert_eq!(r.recv().await?, 1); // Received immediately.
|
/// assert_eq!(r.recv().await, Some(1)); // Received immediately.
|
||||||
/// assert_eq!(r.recv().await?, 2); // Received after 1 second.
|
/// assert_eq!(r.recv().await, Some(2)); // Received after 1 second.
|
||||||
/// #
|
/// #
|
||||||
/// # Ok(())
|
/// # })
|
||||||
/// # }) }
|
|
||||||
/// ```
|
/// ```
|
||||||
#[cfg(feature = "unstable")]
|
#[cfg(feature = "unstable")]
|
||||||
#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
|
#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
|
||||||
|
@ -374,14 +346,12 @@ pub struct Receiver<T> {
|
||||||
impl<T> Receiver<T> {
|
impl<T> Receiver<T> {
|
||||||
/// Receives a message from the channel.
|
/// Receives a message from the channel.
|
||||||
///
|
///
|
||||||
/// If the channel is empty and still has senders, this method
|
/// If the channel is empty and still has senders, this method will wait until a message is
|
||||||
/// will wait until a message is sent into it. Once all senders
|
/// sent into the channel or until all senders get dropped.
|
||||||
/// have been dropped it will return [RecvError].
|
|
||||||
///
|
///
|
||||||
/// # Examples
|
/// # Examples
|
||||||
///
|
///
|
||||||
/// ```
|
/// ```
|
||||||
/// # fn main() -> Result<(), async_std::sync::RecvError> {
|
|
||||||
/// # async_std::task::block_on(async {
|
/// # async_std::task::block_on(async {
|
||||||
/// #
|
/// #
|
||||||
/// use async_std::sync::channel;
|
/// use async_std::sync::channel;
|
||||||
|
@ -390,26 +360,24 @@ impl<T> Receiver<T> {
|
||||||
/// let (s, r) = channel(1);
|
/// let (s, r) = channel(1);
|
||||||
///
|
///
|
||||||
/// task::spawn(async move {
|
/// task::spawn(async move {
|
||||||
/// s.send(1usize).await;
|
/// s.send(1).await;
|
||||||
/// s.send(2).await;
|
/// s.send(2).await;
|
||||||
/// // Then we drop the sender
|
|
||||||
/// });
|
/// });
|
||||||
///
|
///
|
||||||
/// assert_eq!(r.recv().await?, 1);
|
/// assert_eq!(r.recv().await, Some(1));
|
||||||
/// assert_eq!(r.recv().await?, 2);
|
/// assert_eq!(r.recv().await, Some(2));
|
||||||
/// assert!(r.recv().await.is_err());
|
/// assert_eq!(r.recv().await, None);
|
||||||
/// #
|
/// #
|
||||||
/// # Ok(())
|
/// # })
|
||||||
/// # }) }
|
|
||||||
/// ```
|
/// ```
|
||||||
pub async fn recv(&self) -> Result<T, RecvError> {
|
pub async fn recv(&self) -> Option<T> {
|
||||||
struct RecvFuture<'a, T> {
|
struct RecvFuture<'a, T> {
|
||||||
channel: &'a Channel<T>,
|
channel: &'a Channel<T>,
|
||||||
opt_key: Option<usize>,
|
opt_key: Option<usize>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T> Future for RecvFuture<'_, T> {
|
impl<T> Future for RecvFuture<'_, T> {
|
||||||
type Output = Result<T, RecvError>;
|
type Output = Option<T>;
|
||||||
|
|
||||||
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
||||||
poll_recv(
|
poll_recv(
|
||||||
|
@ -437,30 +405,6 @@ impl<T> Receiver<T> {
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Attempts to receive a message from the channel.
|
|
||||||
///
|
|
||||||
/// If the channel is empty, this method will return an error.
|
|
||||||
///
|
|
||||||
/// # Examples
|
|
||||||
///
|
|
||||||
/// ```
|
|
||||||
/// # async_std::task::block_on(async {
|
|
||||||
/// #
|
|
||||||
/// use async_std::sync::channel;
|
|
||||||
///
|
|
||||||
/// let (s, r) = channel(1);
|
|
||||||
///
|
|
||||||
/// s.send(1u8).await;
|
|
||||||
///
|
|
||||||
/// assert!(r.try_recv().is_ok());
|
|
||||||
/// assert!(r.try_recv().is_err());
|
|
||||||
/// #
|
|
||||||
/// # })
|
|
||||||
/// ```
|
|
||||||
pub fn try_recv(&self) -> Result<T, TryRecvError> {
|
|
||||||
self.channel.try_recv()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns the channel capacity.
|
/// Returns the channel capacity.
|
||||||
///
|
///
|
||||||
/// # Examples
|
/// # Examples
|
||||||
|
@ -575,13 +519,12 @@ impl<T> Stream for Receiver<T> {
|
||||||
|
|
||||||
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
|
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
|
||||||
let this = &mut *self;
|
let this = &mut *self;
|
||||||
let res = futures_core::ready!(poll_recv(
|
poll_recv(
|
||||||
&this.channel,
|
&this.channel,
|
||||||
&this.channel.stream_wakers,
|
&this.channel.stream_wakers,
|
||||||
&mut this.opt_key,
|
&mut this.opt_key,
|
||||||
cx,
|
cx,
|
||||||
));
|
)
|
||||||
Poll::Ready(res.ok())
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -600,7 +543,7 @@ fn poll_recv<T>(
|
||||||
wakers: &WakerSet,
|
wakers: &WakerSet,
|
||||||
opt_key: &mut Option<usize>,
|
opt_key: &mut Option<usize>,
|
||||||
cx: &mut Context<'_>,
|
cx: &mut Context<'_>,
|
||||||
) -> Poll<Result<T, RecvError>> {
|
) -> Poll<Option<T>> {
|
||||||
loop {
|
loop {
|
||||||
// If the current task is in the set, remove it.
|
// If the current task is in the set, remove it.
|
||||||
if let Some(key) = opt_key.take() {
|
if let Some(key) = opt_key.take() {
|
||||||
|
@ -609,8 +552,8 @@ fn poll_recv<T>(
|
||||||
|
|
||||||
// Try receiving a message.
|
// Try receiving a message.
|
||||||
match channel.try_recv() {
|
match channel.try_recv() {
|
||||||
Ok(msg) => return Poll::Ready(Ok(msg)),
|
Ok(msg) => return Poll::Ready(Some(msg)),
|
||||||
Err(TryRecvError::Disconnected) => return Poll::Ready(Err(RecvError {})),
|
Err(TryRecvError::Disconnected) => return Poll::Ready(None),
|
||||||
Err(TryRecvError::Empty) => {
|
Err(TryRecvError::Empty) => {
|
||||||
// Insert this receive operation.
|
// Insert this receive operation.
|
||||||
*opt_key = Some(wakers.insert(cx));
|
*opt_key = Some(wakers.insert(cx));
|
||||||
|
@ -989,11 +932,8 @@ impl<T> Drop for Channel<T> {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// An error returned from the `try_send` method.
|
/// An error returned from the `try_send()` method.
|
||||||
#[cfg(feature = "unstable")]
|
enum TrySendError<T> {
|
||||||
#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
|
|
||||||
#[derive(PartialEq, Eq)]
|
|
||||||
pub enum TrySendError<T> {
|
|
||||||
/// The channel is full but not disconnected.
|
/// The channel is full but not disconnected.
|
||||||
Full(T),
|
Full(T),
|
||||||
|
|
||||||
|
@ -1001,59 +941,11 @@ pub enum TrySendError<T> {
|
||||||
Disconnected(T),
|
Disconnected(T),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T> Error for TrySendError<T> {}
|
/// An error returned from the `try_recv()` method.
|
||||||
|
enum TryRecvError {
|
||||||
impl<T> Debug for TrySendError<T> {
|
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
||||||
match self {
|
|
||||||
Self::Full(_) => Debug::fmt("Full<T>", f),
|
|
||||||
Self::Disconnected(_) => Debug::fmt("Disconnected<T>", f),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T> Display for TrySendError<T> {
|
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
||||||
match self {
|
|
||||||
Self::Full(_) => Display::fmt("The channel is full.", f),
|
|
||||||
Self::Disconnected(_) => Display::fmt("The channel is full and disconnected.", f),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// An error returned from the `try_recv` method.
|
|
||||||
#[cfg(feature = "unstable")]
|
|
||||||
#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
|
|
||||||
#[derive(Debug, PartialEq, Eq)]
|
|
||||||
pub enum TryRecvError {
|
|
||||||
/// The channel is empty but not disconnected.
|
/// The channel is empty but not disconnected.
|
||||||
Empty,
|
Empty,
|
||||||
|
|
||||||
/// The channel is empty and disconnected.
|
/// The channel is empty and disconnected.
|
||||||
Disconnected,
|
Disconnected,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Error for TryRecvError {}
|
|
||||||
|
|
||||||
impl Display for TryRecvError {
|
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
||||||
match self {
|
|
||||||
Self::Empty => Display::fmt("The channel is empty.", f),
|
|
||||||
Self::Disconnected => Display::fmt("The channel is empty and disconnected.", f),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// An error returned from the `recv` method.
|
|
||||||
#[cfg(feature = "unstable")]
|
|
||||||
#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
|
|
||||||
#[derive(Debug, PartialEq, Eq)]
|
|
||||||
pub struct RecvError;
|
|
||||||
|
|
||||||
impl Error for RecvError {}
|
|
||||||
|
|
||||||
impl Display for RecvError {
|
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
||||||
Display::fmt("The channel is empty.", f)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
|
@ -1,417 +0,0 @@
|
||||||
use std::fmt;
|
|
||||||
use std::pin::Pin;
|
|
||||||
use std::time::Duration;
|
|
||||||
|
|
||||||
use super::MutexGuard;
|
|
||||||
use crate::future::{timeout, Future};
|
|
||||||
use crate::sync::WakerSet;
|
|
||||||
use crate::task::{Context, Poll};
|
|
||||||
|
|
||||||
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
|
|
||||||
pub struct WaitTimeoutResult(bool);
|
|
||||||
|
|
||||||
/// A type indicating whether a timed wait on a condition variable returned due to a time out or
|
|
||||||
/// not
|
|
||||||
impl WaitTimeoutResult {
|
|
||||||
/// Returns `true` if the wait was known to have timed out.
|
|
||||||
pub fn timed_out(self) -> bool {
|
|
||||||
self.0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A Condition Variable
|
|
||||||
///
|
|
||||||
/// This type is an async version of [`std::sync::Mutex`].
|
|
||||||
///
|
|
||||||
/// [`std::sync::Condvar`]: https://doc.rust-lang.org/std/sync/struct.Condvar.html
|
|
||||||
///
|
|
||||||
/// # Examples
|
|
||||||
///
|
|
||||||
/// ```
|
|
||||||
/// # async_std::task::block_on(async {
|
|
||||||
/// #
|
|
||||||
/// use std::sync::Arc;
|
|
||||||
///
|
|
||||||
/// use async_std::sync::{Mutex, Condvar};
|
|
||||||
/// use async_std::task;
|
|
||||||
///
|
|
||||||
/// let pair = Arc::new((Mutex::new(false), Condvar::new()));
|
|
||||||
/// let pair2 = pair.clone();
|
|
||||||
///
|
|
||||||
/// // Inside of our lock, spawn a new thread, and then wait for it to start.
|
|
||||||
/// task::spawn(async move {
|
|
||||||
/// let (lock, cvar) = &*pair2;
|
|
||||||
/// let mut started = lock.lock().await;
|
|
||||||
/// *started = true;
|
|
||||||
/// // We notify the condvar that the value has changed.
|
|
||||||
/// cvar.notify_one();
|
|
||||||
/// });
|
|
||||||
///
|
|
||||||
/// // Wait for the thread to start up.
|
|
||||||
/// let (lock, cvar) = &*pair;
|
|
||||||
/// let mut started = lock.lock().await;
|
|
||||||
/// while !*started {
|
|
||||||
/// started = cvar.wait(started).await;
|
|
||||||
/// }
|
|
||||||
///
|
|
||||||
/// # })
|
|
||||||
/// ```
|
|
||||||
pub struct Condvar {
|
|
||||||
wakers: WakerSet,
|
|
||||||
}
|
|
||||||
|
|
||||||
unsafe impl Send for Condvar {}
|
|
||||||
unsafe impl Sync for Condvar {}
|
|
||||||
|
|
||||||
impl Default for Condvar {
|
|
||||||
fn default() -> Self {
|
|
||||||
Condvar::new()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Condvar {
|
|
||||||
/// Creates a new condition variable
|
|
||||||
///
|
|
||||||
/// # Examples
|
|
||||||
///
|
|
||||||
/// ```
|
|
||||||
/// use async_std::sync::Condvar;
|
|
||||||
///
|
|
||||||
/// let cvar = Condvar::new();
|
|
||||||
/// ```
|
|
||||||
pub fn new() -> Self {
|
|
||||||
Condvar {
|
|
||||||
wakers: WakerSet::new(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Blocks the current task until this condition variable receives a notification.
|
|
||||||
///
|
|
||||||
/// Unlike the std equivalent, this does not check that a single mutex is used at runtime.
|
|
||||||
/// However, as a best practice avoid using with multiple mutexes.
|
|
||||||
///
|
|
||||||
/// # Examples
|
|
||||||
///
|
|
||||||
/// ```
|
|
||||||
/// # async_std::task::block_on(async {
|
|
||||||
/// use std::sync::Arc;
|
|
||||||
///
|
|
||||||
/// use async_std::sync::{Mutex, Condvar};
|
|
||||||
/// use async_std::task;
|
|
||||||
///
|
|
||||||
/// let pair = Arc::new((Mutex::new(false), Condvar::new()));
|
|
||||||
/// let pair2 = pair.clone();
|
|
||||||
///
|
|
||||||
/// task::spawn(async move {
|
|
||||||
/// let (lock, cvar) = &*pair2;
|
|
||||||
/// let mut started = lock.lock().await;
|
|
||||||
/// *started = true;
|
|
||||||
/// // We notify the condvar that the value has changed.
|
|
||||||
/// cvar.notify_one();
|
|
||||||
/// });
|
|
||||||
///
|
|
||||||
/// // Wait for the thread to start up.
|
|
||||||
/// let (lock, cvar) = &*pair;
|
|
||||||
/// let mut started = lock.lock().await;
|
|
||||||
/// while !*started {
|
|
||||||
/// started = cvar.wait(started).await;
|
|
||||||
/// }
|
|
||||||
/// # })
|
|
||||||
/// ```
|
|
||||||
#[allow(clippy::needless_lifetimes)]
|
|
||||||
pub async fn wait<'a, T>(&self, guard: MutexGuard<'a, T>) -> MutexGuard<'a, T> {
|
|
||||||
let mutex = MutexGuard::source(&guard);
|
|
||||||
|
|
||||||
self.await_notify(guard).await;
|
|
||||||
|
|
||||||
mutex.lock().await
|
|
||||||
}
|
|
||||||
|
|
||||||
fn await_notify<'a, T>(&self, guard: MutexGuard<'a, T>) -> AwaitNotify<'_, 'a, T> {
|
|
||||||
AwaitNotify {
|
|
||||||
cond: self,
|
|
||||||
guard: Some(guard),
|
|
||||||
key: None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Blocks the current taks until this condition variable receives a notification and the
|
|
||||||
/// required condition is met. Spurious wakeups are ignored and this function will only
|
|
||||||
/// return once the condition has been met.
|
|
||||||
///
|
|
||||||
/// # Examples
|
|
||||||
///
|
|
||||||
/// ```
|
|
||||||
/// # async_std::task::block_on(async {
|
|
||||||
/// #
|
|
||||||
/// use std::sync::Arc;
|
|
||||||
///
|
|
||||||
/// use async_std::sync::{Mutex, Condvar};
|
|
||||||
/// use async_std::task;
|
|
||||||
///
|
|
||||||
/// let pair = Arc::new((Mutex::new(false), Condvar::new()));
|
|
||||||
/// let pair2 = pair.clone();
|
|
||||||
///
|
|
||||||
/// task::spawn(async move {
|
|
||||||
/// let (lock, cvar) = &*pair2;
|
|
||||||
/// let mut started = lock.lock().await;
|
|
||||||
/// *started = true;
|
|
||||||
/// // We notify the condvar that the value has changed.
|
|
||||||
/// cvar.notify_one();
|
|
||||||
/// });
|
|
||||||
///
|
|
||||||
/// // Wait for the thread to start up.
|
|
||||||
/// let (lock, cvar) = &*pair;
|
|
||||||
/// // As long as the value inside the `Mutex<bool>` is `false`, we wait.
|
|
||||||
/// let _guard = cvar.wait_until(lock.lock().await, |started| { *started }).await;
|
|
||||||
/// #
|
|
||||||
/// # })
|
|
||||||
/// ```
|
|
||||||
#[allow(clippy::needless_lifetimes)]
|
|
||||||
pub async fn wait_until<'a, T, F>(
|
|
||||||
&self,
|
|
||||||
mut guard: MutexGuard<'a, T>,
|
|
||||||
mut condition: F,
|
|
||||||
) -> MutexGuard<'a, T>
|
|
||||||
where
|
|
||||||
F: FnMut(&mut T) -> bool,
|
|
||||||
{
|
|
||||||
while !condition(&mut *guard) {
|
|
||||||
guard = self.wait(guard).await;
|
|
||||||
}
|
|
||||||
guard
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Waits on this condition variable for a notification, timing out after a specified duration.
|
|
||||||
///
|
|
||||||
/// For these reasons `Condvar::wait_timeout_until` is recommended in most cases.
|
|
||||||
///
|
|
||||||
/// # Examples
|
|
||||||
///
|
|
||||||
/// ```
|
|
||||||
/// # async_std::task::block_on(async {
|
|
||||||
/// #
|
|
||||||
/// use std::sync::Arc;
|
|
||||||
/// use std::time::Duration;
|
|
||||||
///
|
|
||||||
/// use async_std::sync::{Mutex, Condvar};
|
|
||||||
/// use async_std::task;
|
|
||||||
///
|
|
||||||
/// let pair = Arc::new((Mutex::new(false), Condvar::new()));
|
|
||||||
/// let pair2 = pair.clone();
|
|
||||||
///
|
|
||||||
/// task::spawn(async move {
|
|
||||||
/// let (lock, cvar) = &*pair2;
|
|
||||||
/// let mut started = lock.lock().await;
|
|
||||||
/// *started = true;
|
|
||||||
/// // We notify the condvar that the value has changed.
|
|
||||||
/// cvar.notify_one();
|
|
||||||
/// });
|
|
||||||
///
|
|
||||||
/// // wait for the thread to start up
|
|
||||||
/// let (lock, cvar) = &*pair;
|
|
||||||
/// let mut started = lock.lock().await;
|
|
||||||
/// loop {
|
|
||||||
/// let result = cvar.wait_timeout(started, Duration::from_millis(10)).await;
|
|
||||||
/// started = result.0;
|
|
||||||
/// if *started == true {
|
|
||||||
/// // We received the notification and the value has been updated, we can leave.
|
|
||||||
/// break
|
|
||||||
/// }
|
|
||||||
/// }
|
|
||||||
/// #
|
|
||||||
/// # })
|
|
||||||
/// ```
|
|
||||||
#[allow(clippy::needless_lifetimes)]
|
|
||||||
pub async fn wait_timeout<'a, T>(
|
|
||||||
&self,
|
|
||||||
guard: MutexGuard<'a, T>,
|
|
||||||
dur: Duration,
|
|
||||||
) -> (MutexGuard<'a, T>, WaitTimeoutResult) {
|
|
||||||
let mutex = MutexGuard::source(&guard);
|
|
||||||
match timeout(dur, self.wait(guard)).await {
|
|
||||||
Ok(guard) => (guard, WaitTimeoutResult(false)),
|
|
||||||
Err(_) => (mutex.lock().await, WaitTimeoutResult(true)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Waits on this condition variable for a notification, timing out after a specified duration.
|
|
||||||
/// Spurious wakes will not cause this function to return.
|
|
||||||
///
|
|
||||||
/// # Examples
|
|
||||||
/// ```
|
|
||||||
/// # async_std::task::block_on(async {
|
|
||||||
/// use std::sync::Arc;
|
|
||||||
/// use std::time::Duration;
|
|
||||||
///
|
|
||||||
/// use async_std::sync::{Mutex, Condvar};
|
|
||||||
/// use async_std::task;
|
|
||||||
///
|
|
||||||
/// let pair = Arc::new((Mutex::new(false), Condvar::new()));
|
|
||||||
/// let pair2 = pair.clone();
|
|
||||||
///
|
|
||||||
/// task::spawn(async move {
|
|
||||||
/// let (lock, cvar) = &*pair2;
|
|
||||||
/// let mut started = lock.lock().await;
|
|
||||||
/// *started = true;
|
|
||||||
/// // We notify the condvar that the value has changed.
|
|
||||||
/// cvar.notify_one();
|
|
||||||
/// });
|
|
||||||
///
|
|
||||||
/// // wait for the thread to start up
|
|
||||||
/// let (lock, cvar) = &*pair;
|
|
||||||
/// let result = cvar.wait_timeout_until(
|
|
||||||
/// lock.lock().await,
|
|
||||||
/// Duration::from_millis(100),
|
|
||||||
/// |&mut started| started,
|
|
||||||
/// ).await;
|
|
||||||
/// if result.1.timed_out() {
|
|
||||||
/// // timed-out without the condition ever evaluating to true.
|
|
||||||
/// }
|
|
||||||
/// // access the locked mutex via result.0
|
|
||||||
/// # });
|
|
||||||
/// ```
|
|
||||||
#[allow(clippy::needless_lifetimes)]
|
|
||||||
pub async fn wait_timeout_until<'a, T, F>(
|
|
||||||
&self,
|
|
||||||
guard: MutexGuard<'a, T>,
|
|
||||||
dur: Duration,
|
|
||||||
condition: F,
|
|
||||||
) -> (MutexGuard<'a, T>, WaitTimeoutResult)
|
|
||||||
where
|
|
||||||
F: FnMut(&mut T) -> bool,
|
|
||||||
{
|
|
||||||
let mutex = MutexGuard::source(&guard);
|
|
||||||
match timeout(dur, self.wait_until(guard, condition)).await {
|
|
||||||
Ok(guard) => (guard, WaitTimeoutResult(false)),
|
|
||||||
Err(_) => (mutex.lock().await, WaitTimeoutResult(true)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Wakes up one blocked task on this condvar.
|
|
||||||
///
|
|
||||||
/// # Examples
|
|
||||||
///
|
|
||||||
/// ```
|
|
||||||
/// # fn main() { async_std::task::block_on(async {
|
|
||||||
/// use std::sync::Arc;
|
|
||||||
///
|
|
||||||
/// use async_std::sync::{Mutex, Condvar};
|
|
||||||
/// use async_std::task;
|
|
||||||
///
|
|
||||||
/// let pair = Arc::new((Mutex::new(false), Condvar::new()));
|
|
||||||
/// let pair2 = pair.clone();
|
|
||||||
///
|
|
||||||
/// task::spawn(async move {
|
|
||||||
/// let (lock, cvar) = &*pair2;
|
|
||||||
/// let mut started = lock.lock().await;
|
|
||||||
/// *started = true;
|
|
||||||
/// // We notify the condvar that the value has changed.
|
|
||||||
/// cvar.notify_one();
|
|
||||||
/// });
|
|
||||||
///
|
|
||||||
/// // Wait for the thread to start up.
|
|
||||||
/// let (lock, cvar) = &*pair;
|
|
||||||
/// let mut started = lock.lock().await;
|
|
||||||
/// while !*started {
|
|
||||||
/// started = cvar.wait(started).await;
|
|
||||||
/// }
|
|
||||||
/// # }) }
|
|
||||||
/// ```
|
|
||||||
pub fn notify_one(&self) {
|
|
||||||
self.wakers.notify_one();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Wakes up all blocked tasks on this condvar.
|
|
||||||
///
|
|
||||||
/// # Examples
|
|
||||||
/// ```
|
|
||||||
/// # fn main() { async_std::task::block_on(async {
|
|
||||||
/// #
|
|
||||||
/// use std::sync::Arc;
|
|
||||||
///
|
|
||||||
/// use async_std::sync::{Mutex, Condvar};
|
|
||||||
/// use async_std::task;
|
|
||||||
///
|
|
||||||
/// let pair = Arc::new((Mutex::new(false), Condvar::new()));
|
|
||||||
/// let pair2 = pair.clone();
|
|
||||||
///
|
|
||||||
/// task::spawn(async move {
|
|
||||||
/// let (lock, cvar) = &*pair2;
|
|
||||||
/// let mut started = lock.lock().await;
|
|
||||||
/// *started = true;
|
|
||||||
/// // We notify the condvar that the value has changed.
|
|
||||||
/// cvar.notify_all();
|
|
||||||
/// });
|
|
||||||
///
|
|
||||||
/// // Wait for the thread to start up.
|
|
||||||
/// let (lock, cvar) = &*pair;
|
|
||||||
/// let mut started = lock.lock().await;
|
|
||||||
/// // As long as the value inside the `Mutex<bool>` is `false`, we wait.
|
|
||||||
/// while !*started {
|
|
||||||
/// started = cvar.wait(started).await;
|
|
||||||
/// }
|
|
||||||
/// #
|
|
||||||
/// # }) }
|
|
||||||
/// ```
|
|
||||||
pub fn notify_all(&self) {
|
|
||||||
self.wakers.notify_all();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl fmt::Debug for Condvar {
|
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
||||||
f.pad("Condvar { .. }")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A future that waits for another task to notify the condition variable.
|
|
||||||
///
|
|
||||||
/// This is an internal future that `wait` and `wait_until` await on.
|
|
||||||
struct AwaitNotify<'a, 'b, T> {
|
|
||||||
/// The condition variable that we are waiting on
|
|
||||||
cond: &'a Condvar,
|
|
||||||
/// The lock used with `cond`.
|
|
||||||
/// This will be released the first time the future is polled,
|
|
||||||
/// after registering the context to be notified.
|
|
||||||
guard: Option<MutexGuard<'b, T>>,
|
|
||||||
/// A key into the conditions variable's `WakerSet`.
|
|
||||||
/// This is set to the index of the `Waker` for the context each time
|
|
||||||
/// the future is polled and not completed.
|
|
||||||
key: Option<usize>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a, 'b, T> Future for AwaitNotify<'a, 'b, T> {
|
|
||||||
type Output = ();
|
|
||||||
|
|
||||||
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
|
||||||
match self.guard.take() {
|
|
||||||
Some(_) => {
|
|
||||||
self.key = Some(self.cond.wakers.insert(cx));
|
|
||||||
// the guard is dropped when we return, which frees the lock
|
|
||||||
Poll::Pending
|
|
||||||
}
|
|
||||||
None => {
|
|
||||||
if let Some(key) = self.key {
|
|
||||||
if self.cond.wakers.remove_if_notified(key, cx) {
|
|
||||||
self.key = None;
|
|
||||||
Poll::Ready(())
|
|
||||||
} else {
|
|
||||||
Poll::Pending
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// This should only happen if it is polled twice after receiving a notification
|
|
||||||
Poll::Ready(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a, 'b, T> Drop for AwaitNotify<'a, 'b, T> {
|
|
||||||
fn drop(&mut self) {
|
|
||||||
if let Some(key) = self.key {
|
|
||||||
self.cond.wakers.cancel(key);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -176,20 +176,17 @@
|
||||||
#[doc(inline)]
|
#[doc(inline)]
|
||||||
pub use std::sync::{Arc, Weak};
|
pub use std::sync::{Arc, Weak};
|
||||||
|
|
||||||
#[doc(inline)]
|
pub use mutex::{Mutex, MutexGuard};
|
||||||
pub use async_mutex::{Mutex, MutexGuard};
|
|
||||||
|
|
||||||
pub use rwlock::{RwLock, RwLockReadGuard, RwLockWriteGuard};
|
pub use rwlock::{RwLock, RwLockReadGuard, RwLockWriteGuard};
|
||||||
|
|
||||||
|
mod mutex;
|
||||||
mod rwlock;
|
mod rwlock;
|
||||||
|
|
||||||
cfg_unstable! {
|
cfg_unstable! {
|
||||||
pub use barrier::{Barrier, BarrierWaitResult};
|
pub use barrier::{Barrier, BarrierWaitResult};
|
||||||
pub use channel::{channel, Sender, Receiver, RecvError, TryRecvError, TrySendError};
|
pub use channel::{channel, Sender, Receiver};
|
||||||
pub use condvar::Condvar;
|
|
||||||
|
|
||||||
mod barrier;
|
mod barrier;
|
||||||
mod condvar;
|
|
||||||
mod channel;
|
mod channel;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
289
src/sync/mutex.rs
Normal file
289
src/sync/mutex.rs
Normal file
|
@ -0,0 +1,289 @@
|
||||||
|
use std::cell::UnsafeCell;
|
||||||
|
use std::fmt;
|
||||||
|
use std::ops::{Deref, DerefMut};
|
||||||
|
use std::pin::Pin;
|
||||||
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
|
use std::future::Future;
|
||||||
|
|
||||||
|
use crate::sync::WakerSet;
|
||||||
|
use crate::task::{Context, Poll};
|
||||||
|
|
||||||
|
/// A mutual exclusion primitive for protecting shared data.
|
||||||
|
///
|
||||||
|
/// This type is an async version of [`std::sync::Mutex`].
|
||||||
|
///
|
||||||
|
/// [`std::sync::Mutex`]: https://doc.rust-lang.org/std/sync/struct.Mutex.html
|
||||||
|
///
|
||||||
|
/// # Examples
|
||||||
|
///
|
||||||
|
/// ```
|
||||||
|
/// # async_std::task::block_on(async {
|
||||||
|
/// #
|
||||||
|
/// use async_std::sync::{Arc, Mutex};
|
||||||
|
/// use async_std::task;
|
||||||
|
///
|
||||||
|
/// let m = Arc::new(Mutex::new(0));
|
||||||
|
/// let mut tasks = vec![];
|
||||||
|
///
|
||||||
|
/// for _ in 0..10 {
|
||||||
|
/// let m = m.clone();
|
||||||
|
/// tasks.push(task::spawn(async move {
|
||||||
|
/// *m.lock().await += 1;
|
||||||
|
/// }));
|
||||||
|
/// }
|
||||||
|
///
|
||||||
|
/// for t in tasks {
|
||||||
|
/// t.await;
|
||||||
|
/// }
|
||||||
|
/// assert_eq!(*m.lock().await, 10);
|
||||||
|
/// #
|
||||||
|
/// # })
|
||||||
|
/// ```
|
||||||
|
pub struct Mutex<T: ?Sized> {
|
||||||
|
locked: AtomicBool,
|
||||||
|
wakers: WakerSet,
|
||||||
|
value: UnsafeCell<T>,
|
||||||
|
}
|
||||||
|
|
||||||
|
unsafe impl<T: ?Sized + Send> Send for Mutex<T> {}
|
||||||
|
unsafe impl<T: ?Sized + Send> Sync for Mutex<T> {}
|
||||||
|
|
||||||
|
impl<T> Mutex<T> {
|
||||||
|
/// Creates a new mutex.
|
||||||
|
///
|
||||||
|
/// # Examples
|
||||||
|
///
|
||||||
|
/// ```
|
||||||
|
/// use async_std::sync::Mutex;
|
||||||
|
///
|
||||||
|
/// let mutex = Mutex::new(0);
|
||||||
|
/// ```
|
||||||
|
pub fn new(t: T) -> Mutex<T> {
|
||||||
|
Mutex {
|
||||||
|
locked: AtomicBool::new(false),
|
||||||
|
wakers: WakerSet::new(),
|
||||||
|
value: UnsafeCell::new(t),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: ?Sized> Mutex<T> {
|
||||||
|
/// Acquires the lock.
|
||||||
|
///
|
||||||
|
/// Returns a guard that releases the lock when dropped.
|
||||||
|
///
|
||||||
|
/// # Examples
|
||||||
|
///
|
||||||
|
/// ```
|
||||||
|
/// # async_std::task::block_on(async {
|
||||||
|
/// #
|
||||||
|
/// use async_std::sync::{Arc, Mutex};
|
||||||
|
/// use async_std::task;
|
||||||
|
///
|
||||||
|
/// let m1 = Arc::new(Mutex::new(10));
|
||||||
|
/// let m2 = m1.clone();
|
||||||
|
///
|
||||||
|
/// task::spawn(async move {
|
||||||
|
/// *m1.lock().await = 20;
|
||||||
|
/// })
|
||||||
|
/// .await;
|
||||||
|
///
|
||||||
|
/// assert_eq!(*m2.lock().await, 20);
|
||||||
|
/// #
|
||||||
|
/// # })
|
||||||
|
/// ```
|
||||||
|
pub async fn lock(&self) -> MutexGuard<'_, T> {
|
||||||
|
pub struct LockFuture<'a, T: ?Sized> {
|
||||||
|
mutex: &'a Mutex<T>,
|
||||||
|
opt_key: Option<usize>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a, T: ?Sized> Future for LockFuture<'a, T> {
|
||||||
|
type Output = MutexGuard<'a, T>;
|
||||||
|
|
||||||
|
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
||||||
|
loop {
|
||||||
|
// If the current task is in the set, remove it.
|
||||||
|
if let Some(key) = self.opt_key.take() {
|
||||||
|
self.mutex.wakers.remove(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Try acquiring the lock.
|
||||||
|
match self.mutex.try_lock() {
|
||||||
|
Some(guard) => return Poll::Ready(guard),
|
||||||
|
None => {
|
||||||
|
// Insert this lock operation.
|
||||||
|
self.opt_key = Some(self.mutex.wakers.insert(cx));
|
||||||
|
|
||||||
|
// If the mutex is still locked, return.
|
||||||
|
if self.mutex.locked.load(Ordering::SeqCst) {
|
||||||
|
return Poll::Pending;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: ?Sized> Drop for LockFuture<'_, T> {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
// If the current task is still in the set, that means it is being cancelled now.
|
||||||
|
if let Some(key) = self.opt_key {
|
||||||
|
self.mutex.wakers.cancel(key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
LockFuture {
|
||||||
|
mutex: self,
|
||||||
|
opt_key: None,
|
||||||
|
}
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Attempts to acquire the lock.
|
||||||
|
///
|
||||||
|
/// If the lock could not be acquired at this time, then [`None`] is returned. Otherwise, a
|
||||||
|
/// guard is returned that releases the lock when dropped.
|
||||||
|
///
|
||||||
|
/// [`None`]: https://doc.rust-lang.org/std/option/enum.Option.html#variant.None
|
||||||
|
///
|
||||||
|
/// # Examples
|
||||||
|
///
|
||||||
|
/// ```
|
||||||
|
/// # async_std::task::block_on(async {
|
||||||
|
/// #
|
||||||
|
/// use async_std::sync::{Arc, Mutex};
|
||||||
|
/// use async_std::task;
|
||||||
|
///
|
||||||
|
/// let m1 = Arc::new(Mutex::new(10));
|
||||||
|
/// let m2 = m1.clone();
|
||||||
|
///
|
||||||
|
/// task::spawn(async move {
|
||||||
|
/// if let Some(mut guard) = m1.try_lock() {
|
||||||
|
/// *guard = 20;
|
||||||
|
/// } else {
|
||||||
|
/// println!("try_lock failed");
|
||||||
|
/// }
|
||||||
|
/// })
|
||||||
|
/// .await;
|
||||||
|
///
|
||||||
|
/// assert_eq!(*m2.lock().await, 20);
|
||||||
|
/// #
|
||||||
|
/// # })
|
||||||
|
/// ```
|
||||||
|
#[inline]
|
||||||
|
pub fn try_lock(&self) -> Option<MutexGuard<'_, T>> {
|
||||||
|
if !self.locked.swap(true, Ordering::SeqCst) {
|
||||||
|
Some(MutexGuard(self))
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Consumes the mutex, returning the underlying data.
|
||||||
|
///
|
||||||
|
/// # Examples
|
||||||
|
///
|
||||||
|
/// ```
|
||||||
|
/// use async_std::sync::Mutex;
|
||||||
|
///
|
||||||
|
/// let mutex = Mutex::new(10);
|
||||||
|
/// assert_eq!(mutex.into_inner(), 10);
|
||||||
|
/// ```
|
||||||
|
pub fn into_inner(self) -> T where T: Sized {
|
||||||
|
self.value.into_inner()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns a mutable reference to the underlying data.
|
||||||
|
///
|
||||||
|
/// Since this call borrows the mutex mutably, no actual locking takes place -- the mutable
|
||||||
|
/// borrow statically guarantees no locks exist.
|
||||||
|
///
|
||||||
|
/// # Examples
|
||||||
|
///
|
||||||
|
/// ```
|
||||||
|
/// # async_std::task::block_on(async {
|
||||||
|
/// #
|
||||||
|
/// use async_std::sync::Mutex;
|
||||||
|
///
|
||||||
|
/// let mut mutex = Mutex::new(0);
|
||||||
|
/// *mutex.get_mut() = 10;
|
||||||
|
/// assert_eq!(*mutex.lock().await, 10);
|
||||||
|
/// #
|
||||||
|
/// # })
|
||||||
|
/// ```
|
||||||
|
pub fn get_mut(&mut self) -> &mut T {
|
||||||
|
unsafe { &mut *self.value.get() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: ?Sized + fmt::Debug> fmt::Debug for Mutex<T> {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
struct Locked;
|
||||||
|
impl fmt::Debug for Locked {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
f.write_str("<locked>")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
match self.try_lock() {
|
||||||
|
None => f.debug_struct("Mutex").field("data", &Locked).finish(),
|
||||||
|
Some(guard) => f.debug_struct("Mutex").field("data", &&*guard).finish(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> From<T> for Mutex<T> {
|
||||||
|
fn from(val: T) -> Mutex<T> {
|
||||||
|
Mutex::new(val)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: ?Sized + Default> Default for Mutex<T> {
|
||||||
|
fn default() -> Mutex<T> {
|
||||||
|
Mutex::new(Default::default())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A guard that releases the lock when dropped.
|
||||||
|
pub struct MutexGuard<'a, T: ?Sized>(&'a Mutex<T>);
|
||||||
|
|
||||||
|
unsafe impl<T: ?Sized + Send> Send for MutexGuard<'_, T> {}
|
||||||
|
unsafe impl<T: ?Sized + Sync> Sync for MutexGuard<'_, T> {}
|
||||||
|
|
||||||
|
impl<T: ?Sized> Drop for MutexGuard<'_, T> {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
// Use `SeqCst` ordering to synchronize with `WakerSet::insert()` and `WakerSet::update()`.
|
||||||
|
self.0.locked.store(false, Ordering::SeqCst);
|
||||||
|
|
||||||
|
// Notify a blocked `lock()` operation if none were notified already.
|
||||||
|
self.0.wakers.notify_any();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: ?Sized +fmt::Debug> fmt::Debug for MutexGuard<'_, T> {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
fmt::Debug::fmt(&**self, f)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: ?Sized + fmt::Display> fmt::Display for MutexGuard<'_, T> {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
(**self).fmt(f)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: ?Sized> Deref for MutexGuard<'_, T> {
|
||||||
|
type Target = T;
|
||||||
|
|
||||||
|
fn deref(&self) -> &T {
|
||||||
|
unsafe { &*self.0.value.get() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: ?Sized> DerefMut for MutexGuard<'_, T> {
|
||||||
|
fn deref_mut(&mut self) -> &mut T {
|
||||||
|
unsafe { &mut *self.0.value.get() }
|
||||||
|
}
|
||||||
|
}
|
|
@ -80,28 +80,6 @@ impl WakerSet {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// If the waker for this key is still waiting for a notification, then update
|
|
||||||
/// the waker for the entry, and return false. If the waker has been notified,
|
|
||||||
/// treat the entry as completed and return true.
|
|
||||||
#[cfg(feature = "unstable")]
|
|
||||||
pub fn remove_if_notified(&self, key: usize, cx: &Context<'_>) -> bool {
|
|
||||||
let mut inner = self.lock();
|
|
||||||
|
|
||||||
match &mut inner.entries[key] {
|
|
||||||
None => {
|
|
||||||
inner.entries.remove(key);
|
|
||||||
true
|
|
||||||
}
|
|
||||||
Some(w) => {
|
|
||||||
// We were never woken, so update instead
|
|
||||||
if !w.will_wake(cx.waker()) {
|
|
||||||
*w = cx.waker().clone();
|
|
||||||
}
|
|
||||||
false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Removes the waker of a cancelled operation.
|
/// Removes the waker of a cancelled operation.
|
||||||
///
|
///
|
||||||
/// Returns `true` if another blocked operation from the set was notified.
|
/// Returns `true` if another blocked operation from the set was notified.
|
||||||
|
|
|
@ -1,6 +1,14 @@
|
||||||
|
use std::cell::Cell;
|
||||||
use std::future::Future;
|
use std::future::Future;
|
||||||
|
use std::mem::{self, ManuallyDrop};
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::task::{RawWaker, RawWakerVTable};
|
||||||
|
|
||||||
use crate::task::Builder;
|
use crossbeam_utils::sync::Parker;
|
||||||
|
use kv_log_macro::trace;
|
||||||
|
use log::log_enabled;
|
||||||
|
|
||||||
|
use crate::task::{Context, Poll, Task, Waker};
|
||||||
|
|
||||||
/// Spawns a task and blocks the current thread on its result.
|
/// Spawns a task and blocks the current thread on its result.
|
||||||
///
|
///
|
||||||
|
@ -25,20 +33,105 @@ use crate::task::Builder;
|
||||||
/// })
|
/// })
|
||||||
/// }
|
/// }
|
||||||
/// ```
|
/// ```
|
||||||
#[cfg(not(target_os = "unknown"))]
|
|
||||||
pub fn block_on<F, T>(future: F) -> T
|
pub fn block_on<F, T>(future: F) -> T
|
||||||
where
|
where
|
||||||
F: Future<Output = T>,
|
F: Future<Output = T>,
|
||||||
{
|
{
|
||||||
Builder::new().blocking(future)
|
// Create a new task handle.
|
||||||
|
let task = Task::new(None);
|
||||||
|
|
||||||
|
// Log this `block_on` operation.
|
||||||
|
if log_enabled!(log::Level::Trace) {
|
||||||
|
trace!("block_on", {
|
||||||
|
task_id: task.id().0,
|
||||||
|
parent_task_id: Task::get_current(|t| t.id().0).unwrap_or(0),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let future = async move {
|
||||||
|
// Drop task-locals on exit.
|
||||||
|
defer! {
|
||||||
|
Task::get_current(|t| unsafe { t.drop_locals() });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Log completion on exit.
|
||||||
|
defer! {
|
||||||
|
if log_enabled!(log::Level::Trace) {
|
||||||
|
Task::get_current(|t| {
|
||||||
|
trace!("completed", {
|
||||||
|
task_id: t.id().0,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
future.await
|
||||||
|
};
|
||||||
|
|
||||||
|
// Run the future as a task.
|
||||||
|
unsafe { Task::set_current(&task, || run(future)) }
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Spawns a task and waits for it to finish.
|
/// Blocks the current thread on a future's result.
|
||||||
#[cfg(target_os = "unknown")]
|
fn run<F, T>(future: F) -> T
|
||||||
pub fn block_on<F, T>(future: F)
|
|
||||||
where
|
where
|
||||||
F: Future<Output = T> + 'static,
|
F: Future<Output = T>,
|
||||||
T: 'static,
|
|
||||||
{
|
{
|
||||||
Builder::new().local(future).unwrap();
|
thread_local! {
|
||||||
|
// May hold a pre-allocated parker that can be reused for efficiency.
|
||||||
|
//
|
||||||
|
// Note that each invocation of `block` needs its own parker. In particular, if `block`
|
||||||
|
// recursively calls itself, we must make sure that each recursive call uses a distinct
|
||||||
|
// parker instance.
|
||||||
|
static CACHE: Cell<Option<Arc<Parker>>> = Cell::new(None);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Virtual table for wakers based on `Arc<Parker>`.
|
||||||
|
static VTABLE: RawWakerVTable = {
|
||||||
|
unsafe fn clone_raw(ptr: *const ()) -> RawWaker {
|
||||||
|
let arc = ManuallyDrop::new(Arc::from_raw(ptr as *const Parker));
|
||||||
|
#[allow(clippy::redundant_clone)]
|
||||||
|
mem::forget(arc.clone());
|
||||||
|
RawWaker::new(ptr, &VTABLE)
|
||||||
|
}
|
||||||
|
|
||||||
|
unsafe fn wake_raw(ptr: *const ()) {
|
||||||
|
let arc = Arc::from_raw(ptr as *const Parker);
|
||||||
|
arc.unparker().unpark();
|
||||||
|
}
|
||||||
|
|
||||||
|
unsafe fn wake_by_ref_raw(ptr: *const ()) {
|
||||||
|
let arc = ManuallyDrop::new(Arc::from_raw(ptr as *const Parker));
|
||||||
|
arc.unparker().unpark();
|
||||||
|
}
|
||||||
|
|
||||||
|
unsafe fn drop_raw(ptr: *const ()) {
|
||||||
|
drop(Arc::from_raw(ptr as *const Parker))
|
||||||
|
}
|
||||||
|
|
||||||
|
RawWakerVTable::new(clone_raw, wake_raw, wake_by_ref_raw, drop_raw)
|
||||||
|
};
|
||||||
|
|
||||||
|
// Pin the future on the stack.
|
||||||
|
pin_utils::pin_mut!(future);
|
||||||
|
|
||||||
|
CACHE.with(|cache| {
|
||||||
|
// Reuse a cached parker or create a new one for this invocation of `block`.
|
||||||
|
let arc_parker: Arc<Parker> = cache.take().unwrap_or_else(|| Arc::new(Parker::new()));
|
||||||
|
let ptr = (&*arc_parker as *const Parker) as *const ();
|
||||||
|
|
||||||
|
// Create a waker and task context.
|
||||||
|
let waker = unsafe { ManuallyDrop::new(Waker::from_raw(RawWaker::new(ptr, &VTABLE))) };
|
||||||
|
let cx = &mut Context::from_waker(&waker);
|
||||||
|
|
||||||
|
loop {
|
||||||
|
if let Poll::Ready(t) = future.as_mut().poll(cx) {
|
||||||
|
// Save the parker for the next invocation of `block`.
|
||||||
|
cache.set(Some(arc_parker));
|
||||||
|
return t;
|
||||||
|
}
|
||||||
|
|
||||||
|
arc_parker.park();
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,13 +1,11 @@
|
||||||
use std::cell::Cell;
|
use kv_log_macro::trace;
|
||||||
|
use log::log_enabled;
|
||||||
use std::future::Future;
|
use std::future::Future;
|
||||||
use std::pin::Pin;
|
|
||||||
use std::sync::Arc;
|
|
||||||
use std::task::{Context, Poll};
|
|
||||||
|
|
||||||
use pin_project_lite::pin_project;
|
|
||||||
|
|
||||||
use crate::io;
|
use crate::io;
|
||||||
use crate::task::{JoinHandle, Task, TaskLocalsWrapper};
|
use crate::task::executor;
|
||||||
|
use crate::task::{JoinHandle, Task};
|
||||||
|
use crate::utils::abort_on_panic;
|
||||||
|
|
||||||
/// Task builder that configures the settings of a new task.
|
/// Task builder that configures the settings of a new task.
|
||||||
#[derive(Debug, Default)]
|
#[derive(Debug, Default)]
|
||||||
|
@ -29,174 +27,58 @@ impl Builder {
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
fn build<F, T>(self, future: F) -> SupportTaskLocals<F>
|
|
||||||
where
|
|
||||||
F: Future<Output = T>,
|
|
||||||
{
|
|
||||||
let name = self.name.map(Arc::new);
|
|
||||||
|
|
||||||
// Create a new task handle.
|
|
||||||
let task = Task::new(name);
|
|
||||||
|
|
||||||
#[cfg(not(target_os = "unknown"))]
|
|
||||||
once_cell::sync::Lazy::force(&crate::rt::RUNTIME);
|
|
||||||
|
|
||||||
let tag = TaskLocalsWrapper::new(task.clone());
|
|
||||||
|
|
||||||
SupportTaskLocals { tag, future }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Spawns a task with the configured settings.
|
/// Spawns a task with the configured settings.
|
||||||
#[cfg(not(target_os = "unknown"))]
|
|
||||||
pub fn spawn<F, T>(self, future: F) -> io::Result<JoinHandle<T>>
|
pub fn spawn<F, T>(self, future: F) -> io::Result<JoinHandle<T>>
|
||||||
where
|
where
|
||||||
F: Future<Output = T> + Send + 'static,
|
F: Future<Output = T> + Send + 'static,
|
||||||
T: Send + 'static,
|
T: Send + 'static,
|
||||||
{
|
{
|
||||||
let wrapped = self.build(future);
|
// Create a new task handle.
|
||||||
|
let task = Task::new(self.name);
|
||||||
|
|
||||||
kv_log_macro::trace!("spawn", {
|
// Log this `spawn` operation.
|
||||||
task_id: wrapped.tag.id().0,
|
if log_enabled!(log::Level::Trace) {
|
||||||
parent_task_id: TaskLocalsWrapper::get_current(|t| t.id().0).unwrap_or(0),
|
trace!("spawn", {
|
||||||
|
task_id: task.id().0,
|
||||||
|
parent_task_id: Task::get_current(|t| t.id().0).unwrap_or(0),
|
||||||
});
|
});
|
||||||
|
|
||||||
let task = wrapped.tag.task().clone();
|
|
||||||
let smol_task = smol::Task::spawn(wrapped).into();
|
|
||||||
|
|
||||||
Ok(JoinHandle::new(smol_task, task))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Spawns a task locally with the configured settings.
|
let future = async move {
|
||||||
#[cfg(all(not(target_os = "unknown"), feature = "unstable"))]
|
// Drop task-locals on exit.
|
||||||
pub fn local<F, T>(self, future: F) -> io::Result<JoinHandle<T>>
|
defer! {
|
||||||
where
|
Task::get_current(|t| unsafe { t.drop_locals() });
|
||||||
F: Future<Output = T> + 'static,
|
|
||||||
T: 'static,
|
|
||||||
{
|
|
||||||
let wrapped = self.build(future);
|
|
||||||
|
|
||||||
kv_log_macro::trace!("spawn_local", {
|
|
||||||
task_id: wrapped.tag.id().0,
|
|
||||||
parent_task_id: TaskLocalsWrapper::get_current(|t| t.id().0).unwrap_or(0),
|
|
||||||
});
|
|
||||||
|
|
||||||
let task = wrapped.tag.task().clone();
|
|
||||||
let smol_task = smol::Task::local(wrapped).into();
|
|
||||||
|
|
||||||
Ok(JoinHandle::new(smol_task, task))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Spawns a task locally with the configured settings.
|
// Log completion on exit.
|
||||||
#[cfg(all(target_arch = "wasm32", feature = "unstable"))]
|
defer! {
|
||||||
pub fn local<F, T>(self, future: F) -> io::Result<JoinHandle<T>>
|
if log_enabled!(log::Level::Trace) {
|
||||||
where
|
Task::get_current(|t| {
|
||||||
F: Future<Output = T> + 'static,
|
trace!("completed", {
|
||||||
T: 'static,
|
task_id: t.id().0,
|
||||||
{
|
|
||||||
use futures_channel::oneshot::channel;
|
|
||||||
let (sender, receiver) = channel();
|
|
||||||
|
|
||||||
let wrapped = self.build(async move {
|
|
||||||
let res = future.await;
|
|
||||||
let _ = sender.send(res);
|
|
||||||
});
|
});
|
||||||
kv_log_macro::trace!("spawn_local", {
|
|
||||||
task_id: wrapped.tag.id().0,
|
|
||||||
parent_task_id: TaskLocalsWrapper::get_current(|t| t.id().0).unwrap_or(0),
|
|
||||||
});
|
});
|
||||||
|
}
|
||||||
let task = wrapped.tag.task().clone();
|
|
||||||
wasm_bindgen_futures::spawn_local(wrapped);
|
|
||||||
|
|
||||||
Ok(JoinHandle::new(receiver, task))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Spawns a task locally with the configured settings.
|
future.await
|
||||||
#[cfg(all(target_arch = "wasm32", not(feature = "unstable")))]
|
|
||||||
pub(crate) fn local<F, T>(self, future: F) -> io::Result<JoinHandle<T>>
|
|
||||||
where
|
|
||||||
F: Future<Output = T> + 'static,
|
|
||||||
T: 'static,
|
|
||||||
{
|
|
||||||
use futures_channel::oneshot::channel;
|
|
||||||
let (sender, receiver) = channel();
|
|
||||||
|
|
||||||
let wrapped = self.build(async move {
|
|
||||||
let res = future.await;
|
|
||||||
let _ = sender.send(res);
|
|
||||||
});
|
|
||||||
|
|
||||||
kv_log_macro::trace!("spawn_local", {
|
|
||||||
task_id: wrapped.tag.id().0,
|
|
||||||
parent_task_id: TaskLocalsWrapper::get_current(|t| t.id().0).unwrap_or(0),
|
|
||||||
});
|
|
||||||
|
|
||||||
let task = wrapped.tag.task().clone();
|
|
||||||
wasm_bindgen_futures::spawn_local(wrapped);
|
|
||||||
|
|
||||||
Ok(JoinHandle::new(receiver, task))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Spawns a task with the configured settings, blocking on its execution.
|
|
||||||
#[cfg(not(target_os = "unknown"))]
|
|
||||||
pub fn blocking<F, T>(self, future: F) -> T
|
|
||||||
where
|
|
||||||
F: Future<Output = T>,
|
|
||||||
{
|
|
||||||
let wrapped = self.build(future);
|
|
||||||
|
|
||||||
// Log this `block_on` operation.
|
|
||||||
kv_log_macro::trace!("block_on", {
|
|
||||||
task_id: wrapped.tag.id().0,
|
|
||||||
parent_task_id: TaskLocalsWrapper::get_current(|t| t.id().0).unwrap_or(0),
|
|
||||||
});
|
|
||||||
|
|
||||||
thread_local! {
|
|
||||||
/// Tracks the number of nested block_on calls.
|
|
||||||
static NUM_NESTED_BLOCKING: Cell<usize> = Cell::new(0);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Run the future as a task.
|
|
||||||
NUM_NESTED_BLOCKING.with(|num_nested_blocking| {
|
|
||||||
let count = num_nested_blocking.get();
|
|
||||||
let should_run = count == 0;
|
|
||||||
// increase the count
|
|
||||||
num_nested_blocking.replace(count + 1);
|
|
||||||
|
|
||||||
unsafe {
|
|
||||||
TaskLocalsWrapper::set_current(&wrapped.tag, || {
|
|
||||||
let res = if should_run {
|
|
||||||
// The first call should use run.
|
|
||||||
smol::run(wrapped)
|
|
||||||
} else {
|
|
||||||
smol::block_on(wrapped)
|
|
||||||
};
|
};
|
||||||
num_nested_blocking.replace(num_nested_blocking.get() - 1);
|
|
||||||
res
|
let schedule = move |t| executor::schedule(Runnable(t));
|
||||||
})
|
let (task, handle) = async_task::spawn(future, schedule, task);
|
||||||
}
|
task.schedule();
|
||||||
})
|
Ok(JoinHandle::new(handle))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pin_project! {
|
/// A runnable task.
|
||||||
/// Wrapper to add support for task locals.
|
pub(crate) struct Runnable(async_task::Task<Task>);
|
||||||
struct SupportTaskLocals<F> {
|
|
||||||
tag: TaskLocalsWrapper,
|
|
||||||
#[pin]
|
|
||||||
future: F,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<F: Future> Future for SupportTaskLocals<F> {
|
impl Runnable {
|
||||||
type Output = F::Output;
|
/// Runs the task by polling its future once.
|
||||||
|
pub fn run(self) {
|
||||||
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
|
||||||
unsafe {
|
unsafe {
|
||||||
TaskLocalsWrapper::set_current(&self.tag, || {
|
Task::set_current(self.0.tag(), || abort_on_panic(|| self.0.run()));
|
||||||
let this = self.project();
|
|
||||||
this.future.poll(cx)
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
use crate::task::{Task, TaskLocalsWrapper};
|
use crate::task::Task;
|
||||||
|
|
||||||
/// Returns a handle to the current task.
|
/// Returns a handle to the current task.
|
||||||
///
|
///
|
||||||
|
@ -23,6 +23,6 @@ use crate::task::{Task, TaskLocalsWrapper};
|
||||||
/// # })
|
/// # })
|
||||||
/// ```
|
/// ```
|
||||||
pub fn current() -> Task {
|
pub fn current() -> Task {
|
||||||
TaskLocalsWrapper::get_current(|t| t.task().clone())
|
Task::get_current(|t| t.clone())
|
||||||
.expect("`task::current()` called outside the context of a task")
|
.expect("`task::current()` called outside the context of a task")
|
||||||
}
|
}
|
||||||
|
|
13
src/task/executor/mod.rs
Normal file
13
src/task/executor/mod.rs
Normal file
|
@ -0,0 +1,13 @@
|
||||||
|
//! Task executor.
|
||||||
|
//!
|
||||||
|
//! API bindings between `crate::task` and this module are very simple:
|
||||||
|
//!
|
||||||
|
//! * The only export is the `schedule` function.
|
||||||
|
//! * The only import is the `crate::task::Runnable` type.
|
||||||
|
|
||||||
|
pub(crate) use pool::schedule;
|
||||||
|
|
||||||
|
use sleepers::Sleepers;
|
||||||
|
|
||||||
|
mod pool;
|
||||||
|
mod sleepers;
|
179
src/task/executor/pool.rs
Normal file
179
src/task/executor/pool.rs
Normal file
|
@ -0,0 +1,179 @@
|
||||||
|
use std::cell::Cell;
|
||||||
|
use std::iter;
|
||||||
|
use std::thread;
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use crossbeam_deque::{Injector, Stealer, Worker};
|
||||||
|
use once_cell::sync::Lazy;
|
||||||
|
use once_cell::unsync::OnceCell;
|
||||||
|
|
||||||
|
use crate::task::executor::Sleepers;
|
||||||
|
use crate::task::Runnable;
|
||||||
|
use crate::utils::{abort_on_panic, random};
|
||||||
|
|
||||||
|
/// The state of an executor.
|
||||||
|
struct Pool {
|
||||||
|
/// The global queue of tasks.
|
||||||
|
injector: Injector<Runnable>,
|
||||||
|
|
||||||
|
/// Handles to local queues for stealing work from worker threads.
|
||||||
|
stealers: Vec<Stealer<Runnable>>,
|
||||||
|
|
||||||
|
/// Used for putting idle workers to sleep and notifying them when new tasks come in.
|
||||||
|
sleepers: Sleepers,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Global executor that runs spawned tasks.
|
||||||
|
static POOL: Lazy<Pool> = Lazy::new(|| {
|
||||||
|
let num_threads = num_cpus::get().max(1);
|
||||||
|
let mut stealers = Vec::new();
|
||||||
|
|
||||||
|
// Spawn worker threads.
|
||||||
|
for _ in 0..num_threads {
|
||||||
|
let worker = Worker::new_fifo();
|
||||||
|
stealers.push(worker.stealer());
|
||||||
|
|
||||||
|
let proc = Processor {
|
||||||
|
worker,
|
||||||
|
slot: Cell::new(None),
|
||||||
|
slot_runs: Cell::new(0),
|
||||||
|
};
|
||||||
|
|
||||||
|
thread::Builder::new()
|
||||||
|
.name("async-std/executor".to_string())
|
||||||
|
.spawn(|| {
|
||||||
|
let _ = PROCESSOR.with(|p| p.set(proc));
|
||||||
|
abort_on_panic(main_loop);
|
||||||
|
})
|
||||||
|
.expect("cannot start a thread driving tasks");
|
||||||
|
}
|
||||||
|
|
||||||
|
Pool {
|
||||||
|
injector: Injector::new(),
|
||||||
|
stealers,
|
||||||
|
sleepers: Sleepers::new(),
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
/// The state of a worker thread.
|
||||||
|
struct Processor {
|
||||||
|
/// The local task queue.
|
||||||
|
worker: Worker<Runnable>,
|
||||||
|
|
||||||
|
/// Contains the next task to run as an optimization that skips queues.
|
||||||
|
slot: Cell<Option<Runnable>>,
|
||||||
|
|
||||||
|
/// How many times in a row tasks have been taked from the slot rather than the queue.
|
||||||
|
slot_runs: Cell<u32>,
|
||||||
|
}
|
||||||
|
|
||||||
|
thread_local! {
|
||||||
|
/// Worker thread state.
|
||||||
|
static PROCESSOR: OnceCell<Processor> = OnceCell::new();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Schedules a new runnable task for execution.
|
||||||
|
pub(crate) fn schedule(task: Runnable) {
|
||||||
|
PROCESSOR.with(|proc| {
|
||||||
|
// If the current thread is a worker thread, store it into its task slot or push it into
|
||||||
|
// its local task queue. Otherwise, push it into the global task queue.
|
||||||
|
match proc.get() {
|
||||||
|
Some(proc) => {
|
||||||
|
// Replace the task in the slot.
|
||||||
|
if let Some(task) = proc.slot.replace(Some(task)) {
|
||||||
|
// If the slot already contained a task, push it into the local task queue.
|
||||||
|
proc.worker.push(task);
|
||||||
|
POOL.sleepers.notify_one();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
POOL.injector.push(task);
|
||||||
|
POOL.sleepers.notify_one();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Main loop running a worker thread.
|
||||||
|
fn main_loop() {
|
||||||
|
/// Number of yields when no runnable task is found.
|
||||||
|
const YIELDS: u32 = 3;
|
||||||
|
/// Number of short sleeps when no runnable task in found.
|
||||||
|
const SLEEPS: u32 = 1;
|
||||||
|
|
||||||
|
// The number of times the thread didn't find work in a row.
|
||||||
|
let mut fails = 0;
|
||||||
|
|
||||||
|
loop {
|
||||||
|
// Try to find a runnable task.
|
||||||
|
match find_runnable() {
|
||||||
|
Some(task) => {
|
||||||
|
fails = 0;
|
||||||
|
|
||||||
|
// Run the found task.
|
||||||
|
task.run();
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
fails += 1;
|
||||||
|
|
||||||
|
// Yield the current thread or put it to sleep.
|
||||||
|
if fails <= YIELDS {
|
||||||
|
thread::yield_now();
|
||||||
|
} else if fails <= YIELDS + SLEEPS {
|
||||||
|
thread::sleep(Duration::from_micros(10));
|
||||||
|
} else {
|
||||||
|
POOL.sleepers.wait();
|
||||||
|
fails = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Find the next runnable task.
|
||||||
|
fn find_runnable() -> Option<Runnable> {
|
||||||
|
/// Maximum number of times the slot can be used in a row.
|
||||||
|
const SLOT_LIMIT: u32 = 16;
|
||||||
|
|
||||||
|
PROCESSOR.with(|proc| {
|
||||||
|
let proc = proc.get().unwrap();
|
||||||
|
|
||||||
|
// Try taking a task from the slot.
|
||||||
|
let runs = proc.slot_runs.get();
|
||||||
|
if runs < SLOT_LIMIT {
|
||||||
|
if let Some(task) = proc.slot.take() {
|
||||||
|
proc.slot_runs.set(runs + 1);
|
||||||
|
return Some(task);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
proc.slot_runs.set(0);
|
||||||
|
|
||||||
|
// Pop a task from the local queue, if not empty.
|
||||||
|
proc.worker.pop().or_else(|| {
|
||||||
|
// Otherwise, we need to look for a task elsewhere.
|
||||||
|
iter::repeat_with(|| {
|
||||||
|
// Try stealing a batch of tasks from the global queue.
|
||||||
|
POOL.injector
|
||||||
|
.steal_batch_and_pop(&proc.worker)
|
||||||
|
// Or try stealing a batch of tasks from one of the other threads.
|
||||||
|
.or_else(|| {
|
||||||
|
// First, pick a random starting point in the list of local queues.
|
||||||
|
let len = POOL.stealers.len();
|
||||||
|
let start = random(len as u32) as usize;
|
||||||
|
|
||||||
|
// Try stealing a batch of tasks from each local queue starting from the
|
||||||
|
// chosen point.
|
||||||
|
let (l, r) = POOL.stealers.split_at(start);
|
||||||
|
let stealers = r.iter().chain(l.iter());
|
||||||
|
stealers
|
||||||
|
.map(|s| s.steal_batch_and_pop(&proc.worker))
|
||||||
|
.collect()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
// Loop while no task was stolen and any steal operation needs to be retried.
|
||||||
|
.find(|s| !s.is_retry())
|
||||||
|
// Extract the stolen task, if there is one.
|
||||||
|
.and_then(|s| s.success())
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
52
src/task/executor/sleepers.rs
Normal file
52
src/task/executor/sleepers.rs
Normal file
|
@ -0,0 +1,52 @@
|
||||||
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
|
use std::sync::{Condvar, Mutex};
|
||||||
|
|
||||||
|
/// The place where worker threads go to sleep.
|
||||||
|
///
|
||||||
|
/// Similar to how thread parking works, if a notification comes up while no threads are sleeping,
|
||||||
|
/// the next thread that attempts to go to sleep will pick up the notification immediately.
|
||||||
|
pub struct Sleepers {
|
||||||
|
/// How many threads are currently a sleep.
|
||||||
|
sleep: Mutex<usize>,
|
||||||
|
|
||||||
|
/// A condvar for notifying sleeping threads.
|
||||||
|
wake: Condvar,
|
||||||
|
|
||||||
|
/// Set to `true` if a notification came up while nobody was sleeping.
|
||||||
|
notified: AtomicBool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Sleepers {
|
||||||
|
/// Creates a new `Sleepers`.
|
||||||
|
pub fn new() -> Sleepers {
|
||||||
|
Sleepers {
|
||||||
|
sleep: Mutex::new(0),
|
||||||
|
wake: Condvar::new(),
|
||||||
|
notified: AtomicBool::new(false),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Puts the current thread to sleep.
|
||||||
|
pub fn wait(&self) {
|
||||||
|
let mut sleep = self.sleep.lock().unwrap();
|
||||||
|
|
||||||
|
if !self.notified.swap(false, Ordering::SeqCst) {
|
||||||
|
*sleep += 1;
|
||||||
|
let _ = self.wake.wait(sleep).unwrap();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Notifies one thread.
|
||||||
|
pub fn notify_one(&self) {
|
||||||
|
if !self.notified.load(Ordering::SeqCst) {
|
||||||
|
let mut sleep = self.sleep.lock().unwrap();
|
||||||
|
|
||||||
|
if *sleep > 0 {
|
||||||
|
*sleep -= 1;
|
||||||
|
self.wake.notify_one();
|
||||||
|
} else {
|
||||||
|
self.notified.store(true, Ordering::SeqCst);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -12,23 +12,15 @@ use crate::task::{Context, Poll, Task};
|
||||||
///
|
///
|
||||||
/// [spawned]: fn.spawn.html
|
/// [spawned]: fn.spawn.html
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct JoinHandle<T> {
|
pub struct JoinHandle<T>(async_task::JoinHandle<T, Task>);
|
||||||
handle: Option<InnerHandle<T>>,
|
|
||||||
task: Task,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(not(target_os = "unknown"))]
|
unsafe impl<T> Send for JoinHandle<T> {}
|
||||||
type InnerHandle<T> = async_task::JoinHandle<T, ()>;
|
unsafe impl<T> Sync for JoinHandle<T> {}
|
||||||
#[cfg(target_arch = "wasm32")]
|
|
||||||
type InnerHandle<T> = futures_channel::oneshot::Receiver<T>;
|
|
||||||
|
|
||||||
impl<T> JoinHandle<T> {
|
impl<T> JoinHandle<T> {
|
||||||
/// Creates a new `JoinHandle`.
|
/// Creates a new `JoinHandle`.
|
||||||
pub(crate) fn new(inner: InnerHandle<T>, task: Task) -> JoinHandle<T> {
|
pub(crate) fn new(inner: async_task::JoinHandle<T, Task>) -> JoinHandle<T> {
|
||||||
JoinHandle {
|
JoinHandle(inner)
|
||||||
handle: Some(inner),
|
|
||||||
task,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns a handle to the underlying task.
|
/// Returns a handle to the underlying task.
|
||||||
|
@ -47,23 +39,7 @@ impl<T> JoinHandle<T> {
|
||||||
/// #
|
/// #
|
||||||
/// # })
|
/// # })
|
||||||
pub fn task(&self) -> &Task {
|
pub fn task(&self) -> &Task {
|
||||||
&self.task
|
self.0.tag()
|
||||||
}
|
|
||||||
|
|
||||||
/// Cancel this task.
|
|
||||||
#[cfg(not(target_os = "unknown"))]
|
|
||||||
pub async fn cancel(mut self) -> Option<T> {
|
|
||||||
let handle = self.handle.take().unwrap();
|
|
||||||
handle.cancel();
|
|
||||||
handle.await
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Cancel this task.
|
|
||||||
#[cfg(target_arch = "wasm32")]
|
|
||||||
pub async fn cancel(mut self) -> Option<T> {
|
|
||||||
let mut handle = self.handle.take().unwrap();
|
|
||||||
handle.close();
|
|
||||||
handle.await.ok()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -71,11 +47,10 @@ impl<T> Future for JoinHandle<T> {
|
||||||
type Output = T;
|
type Output = T;
|
||||||
|
|
||||||
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
||||||
match Pin::new(&mut self.handle.as_mut().unwrap()).poll(cx) {
|
match Pin::new(&mut self.0).poll(cx) {
|
||||||
Poll::Pending => Poll::Pending,
|
Poll::Pending => Poll::Pending,
|
||||||
Poll::Ready(output) => {
|
Poll::Ready(None) => panic!("cannot await the result of a panicked task"),
|
||||||
Poll::Ready(output.expect("cannot await the result of a panicked task"))
|
Poll::Ready(Some(val)) => Poll::Ready(val),
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -138,39 +138,26 @@ cfg_default! {
|
||||||
pub use task_id::TaskId;
|
pub use task_id::TaskId;
|
||||||
pub use join_handle::JoinHandle;
|
pub use join_handle::JoinHandle;
|
||||||
pub use sleep::sleep;
|
pub use sleep::sleep;
|
||||||
#[cfg(not(target_os = "unknown"))]
|
|
||||||
pub use spawn::spawn;
|
pub use spawn::spawn;
|
||||||
pub use task_local::{AccessError, LocalKey};
|
pub use task_local::{AccessError, LocalKey};
|
||||||
|
|
||||||
pub(crate) use task_local::LocalsMap;
|
use builder::Runnable;
|
||||||
pub(crate) use task_locals_wrapper::TaskLocalsWrapper;
|
use task_local::LocalsMap;
|
||||||
|
|
||||||
mod block_on;
|
mod block_on;
|
||||||
mod builder;
|
mod builder;
|
||||||
mod current;
|
mod current;
|
||||||
|
mod executor;
|
||||||
mod join_handle;
|
mod join_handle;
|
||||||
mod sleep;
|
mod sleep;
|
||||||
#[cfg(not(target_os = "unknown"))]
|
|
||||||
mod spawn;
|
mod spawn;
|
||||||
#[cfg(not(target_os = "unknown"))]
|
|
||||||
mod spawn_blocking;
|
mod spawn_blocking;
|
||||||
mod task;
|
mod task;
|
||||||
mod task_id;
|
mod task_id;
|
||||||
mod task_local;
|
mod task_local;
|
||||||
mod task_locals_wrapper;
|
|
||||||
|
|
||||||
#[cfg(not(target_os = "unknown"))]
|
|
||||||
#[cfg(any(feature = "unstable", test))]
|
#[cfg(any(feature = "unstable", test))]
|
||||||
pub use spawn_blocking::spawn_blocking;
|
pub use spawn_blocking::spawn_blocking;
|
||||||
#[cfg(not(target_os = "unknown"))]
|
|
||||||
#[cfg(not(any(feature = "unstable", test)))]
|
#[cfg(not(any(feature = "unstable", test)))]
|
||||||
pub(crate) use spawn_blocking::spawn_blocking;
|
pub(crate) use spawn_blocking::spawn_blocking;
|
||||||
}
|
}
|
||||||
|
|
||||||
cfg_unstable! {
|
|
||||||
#[cfg(feature = "default")]
|
|
||||||
pub use spawn_local::spawn_local;
|
|
||||||
|
|
||||||
#[cfg(feature = "default")]
|
|
||||||
mod spawn_local;
|
|
||||||
}
|
|
||||||
|
|
|
@ -1,4 +1,12 @@
|
||||||
|
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||||
|
use std::thread;
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use crossbeam_channel::{unbounded, Receiver, Sender};
|
||||||
|
use once_cell::sync::Lazy;
|
||||||
|
|
||||||
use crate::task::{JoinHandle, Task};
|
use crate::task::{JoinHandle, Task};
|
||||||
|
use crate::utils::abort_on_panic;
|
||||||
|
|
||||||
/// Spawns a blocking task.
|
/// Spawns a blocking task.
|
||||||
///
|
///
|
||||||
|
@ -23,8 +31,7 @@ use crate::task::{JoinHandle, Task};
|
||||||
///
|
///
|
||||||
/// task::spawn_blocking(|| {
|
/// task::spawn_blocking(|| {
|
||||||
/// println!("long-running task here");
|
/// println!("long-running task here");
|
||||||
/// })
|
/// }).await;
|
||||||
/// .await;
|
|
||||||
/// #
|
/// #
|
||||||
/// # })
|
/// # })
|
||||||
/// ```
|
/// ```
|
||||||
|
@ -35,8 +42,80 @@ where
|
||||||
F: FnOnce() -> T + Send + 'static,
|
F: FnOnce() -> T + Send + 'static,
|
||||||
T: Send + 'static,
|
T: Send + 'static,
|
||||||
{
|
{
|
||||||
once_cell::sync::Lazy::force(&crate::rt::RUNTIME);
|
let schedule = |task| POOL.sender.send(task).unwrap();
|
||||||
|
let (task, handle) = async_task::spawn(async { f() }, schedule, Task::new(None));
|
||||||
let handle = smol::Task::blocking(async move { f() }).into();
|
task.schedule();
|
||||||
JoinHandle::new(handle, Task::new(None))
|
JoinHandle::new(handle)
|
||||||
|
}
|
||||||
|
|
||||||
|
type Runnable = async_task::Task<Task>;
|
||||||
|
|
||||||
|
/// The number of sleeping worker threads.
|
||||||
|
static SLEEPING: AtomicUsize = AtomicUsize::new(0);
|
||||||
|
|
||||||
|
struct Pool {
|
||||||
|
sender: Sender<Runnable>,
|
||||||
|
receiver: Receiver<Runnable>,
|
||||||
|
}
|
||||||
|
|
||||||
|
static POOL: Lazy<Pool> = Lazy::new(|| {
|
||||||
|
// Start a single worker thread waiting for the first task.
|
||||||
|
start_thread();
|
||||||
|
|
||||||
|
let (sender, receiver) = unbounded();
|
||||||
|
Pool { sender, receiver }
|
||||||
|
});
|
||||||
|
|
||||||
|
fn start_thread() {
|
||||||
|
SLEEPING.fetch_add(1, Ordering::SeqCst);
|
||||||
|
let timeout = Duration::from_secs(1);
|
||||||
|
|
||||||
|
thread::Builder::new()
|
||||||
|
.name("async-std/blocking".to_string())
|
||||||
|
.spawn(move || {
|
||||||
|
loop {
|
||||||
|
let mut task = match POOL.receiver.recv_timeout(timeout) {
|
||||||
|
Ok(task) => task,
|
||||||
|
Err(_) => {
|
||||||
|
// Check whether this is the last sleeping thread.
|
||||||
|
if SLEEPING.fetch_sub(1, Ordering::SeqCst) == 1 {
|
||||||
|
// If so, then restart the thread to make sure there is always at least
|
||||||
|
// one sleeping thread.
|
||||||
|
if SLEEPING.compare_and_swap(0, 1, Ordering::SeqCst) == 0 {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Stop the thread.
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// If there are no sleeping threads, then start one to make sure there is always at
|
||||||
|
// least one sleeping thread.
|
||||||
|
if SLEEPING.fetch_sub(1, Ordering::SeqCst) == 1 {
|
||||||
|
start_thread();
|
||||||
|
}
|
||||||
|
|
||||||
|
loop {
|
||||||
|
// Run the task.
|
||||||
|
abort_on_panic(|| task.run());
|
||||||
|
|
||||||
|
// Try taking another task if there are any available.
|
||||||
|
task = match POOL.receiver.try_recv() {
|
||||||
|
Ok(task) => task,
|
||||||
|
Err(_) => break,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// If there is at least one sleeping thread, stop this thread instead of putting it
|
||||||
|
// to sleep.
|
||||||
|
if SLEEPING.load(Ordering::SeqCst) > 0 {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
SLEEPING.fetch_add(1, Ordering::SeqCst);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.expect("cannot start a blocking thread");
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,31 +0,0 @@
|
||||||
use std::future::Future;
|
|
||||||
|
|
||||||
use crate::task::{Builder, JoinHandle};
|
|
||||||
|
|
||||||
/// Spawns a task onto the thread-local executor.
|
|
||||||
///
|
|
||||||
/// # Examples
|
|
||||||
///
|
|
||||||
/// ```
|
|
||||||
/// # #[cfg(feature = "unstable")]
|
|
||||||
/// # async_std::task::block_on(async {
|
|
||||||
/// #
|
|
||||||
/// use async_std::task;
|
|
||||||
///
|
|
||||||
/// let handle = task::spawn_local(async {
|
|
||||||
/// 1 + 2
|
|
||||||
/// });
|
|
||||||
///
|
|
||||||
/// assert_eq!(handle.await, 3);
|
|
||||||
/// #
|
|
||||||
/// # })
|
|
||||||
/// ```
|
|
||||||
#[cfg_attr(feature = "docs", doc(cfg(unstable)))]
|
|
||||||
#[inline]
|
|
||||||
pub fn spawn_local<F, T>(future: F) -> JoinHandle<T>
|
|
||||||
where
|
|
||||||
F: Future<Output = T> + 'static,
|
|
||||||
T: 'static,
|
|
||||||
{
|
|
||||||
Builder::new().local(future).expect("cannot spawn task")
|
|
||||||
}
|
|
150
src/task/task.rs
150
src/task/task.rs
|
@ -1,32 +1,74 @@
|
||||||
|
use std::cell::Cell;
|
||||||
use std::fmt;
|
use std::fmt;
|
||||||
|
use std::mem::ManuallyDrop;
|
||||||
|
use std::ptr;
|
||||||
|
use std::sync::atomic::{AtomicPtr, Ordering};
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
use crate::task::TaskId;
|
use crate::task::{LocalsMap, TaskId};
|
||||||
|
use crate::utils::abort_on_panic;
|
||||||
|
|
||||||
/// A handle to a task.
|
thread_local! {
|
||||||
#[derive(Clone)]
|
/// A pointer to the currently running task.
|
||||||
pub struct Task {
|
static CURRENT: Cell<*const Task> = Cell::new(ptr::null_mut());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The inner representation of a task handle.
|
||||||
|
struct Inner {
|
||||||
/// The task ID.
|
/// The task ID.
|
||||||
id: TaskId,
|
id: TaskId,
|
||||||
|
|
||||||
/// The optional task name.
|
/// The optional task name.
|
||||||
name: Option<Arc<String>>,
|
name: Option<Box<str>>,
|
||||||
|
|
||||||
|
/// The map holding task-local values.
|
||||||
|
locals: LocalsMap,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl Inner {
|
||||||
|
#[inline]
|
||||||
|
fn new(name: Option<String>) -> Inner {
|
||||||
|
Inner {
|
||||||
|
id: TaskId::generate(),
|
||||||
|
name: name.map(String::into_boxed_str),
|
||||||
|
locals: LocalsMap::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A handle to a task.
|
||||||
|
pub struct Task {
|
||||||
|
/// The inner representation.
|
||||||
|
///
|
||||||
|
/// This pointer is lazily initialized on first use. In most cases, the inner representation is
|
||||||
|
/// never touched and therefore we don't allocate it unless it's really needed.
|
||||||
|
inner: AtomicPtr<Inner>,
|
||||||
|
}
|
||||||
|
|
||||||
|
unsafe impl Send for Task {}
|
||||||
|
unsafe impl Sync for Task {}
|
||||||
|
|
||||||
impl Task {
|
impl Task {
|
||||||
/// Creates a new task handle.
|
/// Creates a new task handle.
|
||||||
|
///
|
||||||
|
/// If the task is unnamed, the inner representation of the task will be lazily allocated on
|
||||||
|
/// demand.
|
||||||
#[inline]
|
#[inline]
|
||||||
pub(crate) fn new(name: Option<Arc<String>>) -> Task {
|
pub(crate) fn new(name: Option<String>) -> Task {
|
||||||
Task {
|
let inner = match name {
|
||||||
id: TaskId::generate(),
|
None => AtomicPtr::default(),
|
||||||
name,
|
Some(name) => {
|
||||||
|
let raw = Arc::into_raw(Arc::new(Inner::new(Some(name))));
|
||||||
|
AtomicPtr::new(raw as *mut Inner)
|
||||||
}
|
}
|
||||||
|
};
|
||||||
|
Task { inner }
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Gets the task's unique identifier.
|
/// Gets the task's unique identifier.
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn id(&self) -> TaskId {
|
pub fn id(&self) -> TaskId {
|
||||||
self.id
|
self.inner().id
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the name of this task.
|
/// Returns the name of this task.
|
||||||
|
@ -35,7 +77,93 @@ impl Task {
|
||||||
///
|
///
|
||||||
/// [`Builder::name`]: struct.Builder.html#method.name
|
/// [`Builder::name`]: struct.Builder.html#method.name
|
||||||
pub fn name(&self) -> Option<&str> {
|
pub fn name(&self) -> Option<&str> {
|
||||||
self.name.as_ref().map(|s| s.as_str())
|
self.inner().name.as_ref().map(|s| &**s)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the map holding task-local values.
|
||||||
|
pub(crate) fn locals(&self) -> &LocalsMap {
|
||||||
|
&self.inner().locals
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Drops all task-local values.
|
||||||
|
///
|
||||||
|
/// This method is only safe to call at the end of the task.
|
||||||
|
#[inline]
|
||||||
|
pub(crate) unsafe fn drop_locals(&self) {
|
||||||
|
let raw = self.inner.load(Ordering::Acquire);
|
||||||
|
if let Some(inner) = raw.as_mut() {
|
||||||
|
// Abort the process if dropping task-locals panics.
|
||||||
|
abort_on_panic(|| {
|
||||||
|
inner.locals.clear();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the inner representation, initializing it on first use.
|
||||||
|
fn inner(&self) -> &Inner {
|
||||||
|
loop {
|
||||||
|
let raw = self.inner.load(Ordering::Acquire);
|
||||||
|
if !raw.is_null() {
|
||||||
|
return unsafe { &*raw };
|
||||||
|
}
|
||||||
|
|
||||||
|
let new = Arc::into_raw(Arc::new(Inner::new(None))) as *mut Inner;
|
||||||
|
if self.inner.compare_and_swap(raw, new, Ordering::AcqRel) != raw {
|
||||||
|
unsafe {
|
||||||
|
drop(Arc::from_raw(new));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Set a reference to the current task.
|
||||||
|
pub(crate) unsafe fn set_current<F, R>(task: *const Task, f: F) -> R
|
||||||
|
where
|
||||||
|
F: FnOnce() -> R,
|
||||||
|
{
|
||||||
|
CURRENT.with(|current| {
|
||||||
|
let old_task = current.replace(task);
|
||||||
|
defer! {
|
||||||
|
current.set(old_task);
|
||||||
|
}
|
||||||
|
f()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Gets a reference to the current task.
|
||||||
|
pub(crate) fn get_current<F, R>(f: F) -> Option<R>
|
||||||
|
where
|
||||||
|
F: FnOnce(&Task) -> R,
|
||||||
|
{
|
||||||
|
let res = CURRENT.try_with(|current| unsafe { current.get().as_ref().map(f) });
|
||||||
|
match res {
|
||||||
|
Ok(Some(val)) => Some(val),
|
||||||
|
Ok(None) | Err(_) => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for Task {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
// Deallocate the inner representation if it was initialized.
|
||||||
|
let raw = *self.inner.get_mut();
|
||||||
|
if !raw.is_null() {
|
||||||
|
unsafe {
|
||||||
|
drop(Arc::from_raw(raw));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Clone for Task {
|
||||||
|
fn clone(&self) -> Task {
|
||||||
|
// We need to make sure the inner representation is initialized now so that this instance
|
||||||
|
// and the clone have raw pointers that point to the same `Arc<Inner>`.
|
||||||
|
let arc = unsafe { ManuallyDrop::new(Arc::from_raw(self.inner())) };
|
||||||
|
let raw = Arc::into_raw(Arc::clone(&arc));
|
||||||
|
Task {
|
||||||
|
inner: AtomicPtr::new(raw as *mut Inner),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -1,5 +1,5 @@
|
||||||
use std::fmt;
|
use std::fmt;
|
||||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
use std::sync::atomic::{AtomicU64, Ordering};
|
||||||
|
|
||||||
/// A unique identifier for a task.
|
/// A unique identifier for a task.
|
||||||
///
|
///
|
||||||
|
@ -13,16 +13,15 @@ use std::sync::atomic::{AtomicUsize, Ordering};
|
||||||
/// })
|
/// })
|
||||||
/// ```
|
/// ```
|
||||||
#[derive(Eq, PartialEq, Clone, Copy, Hash, Debug)]
|
#[derive(Eq, PartialEq, Clone, Copy, Hash, Debug)]
|
||||||
pub struct TaskId(pub(crate) usize);
|
pub struct TaskId(pub(crate) u64);
|
||||||
|
|
||||||
impl TaskId {
|
impl TaskId {
|
||||||
/// Generates a new `TaskId`.
|
/// Generates a new `TaskId`.
|
||||||
pub(crate) fn generate() -> TaskId {
|
pub(crate) fn generate() -> TaskId {
|
||||||
// TODO: find a good version to emulate u64 atomics on 32 bit systems.
|
static COUNTER: AtomicU64 = AtomicU64::new(1);
|
||||||
static COUNTER: AtomicUsize = AtomicUsize::new(1);
|
|
||||||
|
|
||||||
let id = COUNTER.fetch_add(1, Ordering::Relaxed);
|
let id = COUNTER.fetch_add(1, Ordering::Relaxed);
|
||||||
if id > usize::max_value() / 2 {
|
if id > u64::max_value() / 2 {
|
||||||
std::process::abort();
|
std::process::abort();
|
||||||
}
|
}
|
||||||
TaskId(id)
|
TaskId(id)
|
||||||
|
|
|
@ -3,7 +3,7 @@ use std::error::Error;
|
||||||
use std::fmt;
|
use std::fmt;
|
||||||
use std::sync::atomic::{AtomicU32, Ordering};
|
use std::sync::atomic::{AtomicU32, Ordering};
|
||||||
|
|
||||||
use crate::task::TaskLocalsWrapper;
|
use crate::task::Task;
|
||||||
|
|
||||||
/// The key for accessing a task-local value.
|
/// The key for accessing a task-local value.
|
||||||
///
|
///
|
||||||
|
@ -98,7 +98,7 @@ impl<T: Send + 'static> LocalKey<T> {
|
||||||
where
|
where
|
||||||
F: FnOnce(&T) -> R,
|
F: FnOnce(&T) -> R,
|
||||||
{
|
{
|
||||||
TaskLocalsWrapper::get_current(|task| unsafe {
|
Task::get_current(|task| unsafe {
|
||||||
// Prepare the numeric key, initialization function, and the map of task-locals.
|
// Prepare the numeric key, initialization function, and the map of task-locals.
|
||||||
let key = self.key();
|
let key = self.key();
|
||||||
let init = || Box::new((self.__init)()) as Box<dyn Send>;
|
let init = || Box::new((self.__init)()) as Box<dyn Send>;
|
||||||
|
|
|
@ -1,84 +0,0 @@
|
||||||
use std::cell::Cell;
|
|
||||||
use std::ptr;
|
|
||||||
|
|
||||||
use crate::task::{LocalsMap, Task, TaskId};
|
|
||||||
use crate::utils::abort_on_panic;
|
|
||||||
|
|
||||||
thread_local! {
|
|
||||||
/// A pointer to the currently running task.
|
|
||||||
static CURRENT: Cell<*const TaskLocalsWrapper> = Cell::new(ptr::null_mut());
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A wrapper to store task local data.
|
|
||||||
pub(crate) struct TaskLocalsWrapper {
|
|
||||||
/// The actual task details.
|
|
||||||
task: Task,
|
|
||||||
|
|
||||||
/// The map holding task-local values.
|
|
||||||
locals: LocalsMap,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl TaskLocalsWrapper {
|
|
||||||
/// Creates a new task handle.
|
|
||||||
///
|
|
||||||
/// If the task is unnamed, the inner representation of the task will be lazily allocated on
|
|
||||||
/// demand.
|
|
||||||
#[inline]
|
|
||||||
pub(crate) fn new(task: Task) -> Self {
|
|
||||||
Self {
|
|
||||||
task,
|
|
||||||
locals: LocalsMap::new(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Gets the task's unique identifier.
|
|
||||||
#[inline]
|
|
||||||
pub fn id(&self) -> TaskId {
|
|
||||||
self.task.id()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns a reference to the inner `Task`.
|
|
||||||
pub(crate) fn task(&self) -> &Task {
|
|
||||||
&self.task
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns the map holding task-local values.
|
|
||||||
pub(crate) fn locals(&self) -> &LocalsMap {
|
|
||||||
&self.locals
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Set a reference to the current task.
|
|
||||||
pub(crate) unsafe fn set_current<F, R>(task: *const TaskLocalsWrapper, f: F) -> R
|
|
||||||
where
|
|
||||||
F: FnOnce() -> R,
|
|
||||||
{
|
|
||||||
CURRENT.with(|current| {
|
|
||||||
let old_task = current.replace(task);
|
|
||||||
defer! {
|
|
||||||
current.set(old_task);
|
|
||||||
}
|
|
||||||
f()
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Gets a reference to the current task.
|
|
||||||
pub(crate) fn get_current<F, R>(f: F) -> Option<R>
|
|
||||||
where
|
|
||||||
F: FnOnce(&TaskLocalsWrapper) -> R,
|
|
||||||
{
|
|
||||||
let res = CURRENT.try_with(|current| unsafe { current.get().as_ref().map(f) });
|
|
||||||
match res {
|
|
||||||
Ok(Some(val)) => Some(val),
|
|
||||||
Ok(None) | Err(_) => None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Drop for TaskLocalsWrapper {
|
|
||||||
fn drop(&mut self) {
|
|
||||||
// Abort the process if dropping task-locals panics.
|
|
||||||
abort_on_panic(|| {
|
|
||||||
unsafe { self.locals.clear() };
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,5 +1,5 @@
|
||||||
use std::future::Future;
|
|
||||||
use std::pin::Pin;
|
use std::pin::Pin;
|
||||||
|
use std::future::Future;
|
||||||
|
|
||||||
use crate::task::{Context, Poll};
|
use crate::task::{Context, Poll};
|
||||||
|
|
||||||
|
|
|
@ -4,13 +4,10 @@ use crate::prelude::*;
|
||||||
use crate::stream::{self, IntoStream};
|
use crate::stream::{self, IntoStream};
|
||||||
|
|
||||||
impl stream::Extend<()> for () {
|
impl stream::Extend<()> for () {
|
||||||
fn extend<'a, S: IntoStream<Item = ()> + 'a>(
|
fn extend<'a, T: IntoStream<Item = ()> + 'a>(
|
||||||
&'a mut self,
|
&'a mut self,
|
||||||
stream: S,
|
stream: T,
|
||||||
) -> Pin<Box<dyn Future<Output = ()> + 'a + Send>>
|
) -> Pin<Box<dyn Future<Output = ()> + 'a>> {
|
||||||
where
|
|
||||||
<S as IntoStream>::IntoStream: Send,
|
|
||||||
{
|
|
||||||
let stream = stream.into_stream();
|
let stream = stream.into_stream();
|
||||||
|
|
||||||
Box::pin(async move {
|
Box::pin(async move {
|
||||||
|
|
|
@ -7,10 +7,7 @@ impl FromStream<()> for () {
|
||||||
#[inline]
|
#[inline]
|
||||||
fn from_stream<'a, S: IntoStream<Item = ()> + 'a>(
|
fn from_stream<'a, S: IntoStream<Item = ()> + 'a>(
|
||||||
stream: S,
|
stream: S,
|
||||||
) -> Pin<Box<dyn Future<Output = Self> + 'a + Send>>
|
) -> Pin<Box<dyn Future<Output = Self> + 'a>> {
|
||||||
where
|
|
||||||
<S as IntoStream>::IntoStream: Send,
|
|
||||||
{
|
|
||||||
Box::pin(stream.into_stream().for_each(drop))
|
Box::pin(stream.into_stream().for_each(drop))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
52
src/utils.rs
52
src/utils.rs
|
@ -21,7 +21,7 @@ pub fn abort_on_panic<T>(f: impl FnOnce() -> T) -> T {
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Generates a random number in `0..n`.
|
/// Generates a random number in `0..n`.
|
||||||
#[cfg(feature = "unstable")]
|
#[cfg(any(feature = "unstable", feature = "default"))]
|
||||||
pub fn random(n: u32) -> u32 {
|
pub fn random(n: u32) -> u32 {
|
||||||
use std::cell::Cell;
|
use std::cell::Cell;
|
||||||
use std::num::Wrapping;
|
use std::num::Wrapping;
|
||||||
|
@ -59,51 +59,6 @@ pub(crate) trait Context {
|
||||||
fn context(self, message: impl Fn() -> String) -> Self;
|
fn context(self, message: impl Fn() -> String) -> Self;
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(all(not(target_os = "unknown"), feature = "default"))]
|
|
||||||
mod timer {
|
|
||||||
pub type Timer = smol::Timer;
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(any(feature = "unstable", feature = "default"))]
|
|
||||||
pub(crate) fn timer_after(dur: std::time::Duration) -> timer::Timer {
|
|
||||||
#[cfg(not(target_os = "unknown"))]
|
|
||||||
once_cell::sync::Lazy::force(&crate::rt::RUNTIME);
|
|
||||||
|
|
||||||
Timer::after(dur)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(any(
|
|
||||||
all(target_arch = "wasm32", feature = "default"),
|
|
||||||
all(feature = "unstable", not(feature = "default"))
|
|
||||||
))]
|
|
||||||
mod timer {
|
|
||||||
use std::pin::Pin;
|
|
||||||
use std::task::Poll;
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub(crate) struct Timer(futures_timer::Delay);
|
|
||||||
|
|
||||||
impl Timer {
|
|
||||||
pub(crate) fn after(dur: std::time::Duration) -> Self {
|
|
||||||
Timer(futures_timer::Delay::new(dur))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl std::future::Future for Timer {
|
|
||||||
type Output = ();
|
|
||||||
|
|
||||||
fn poll(mut self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
|
|
||||||
match Pin::new(&mut self.0).poll(cx) {
|
|
||||||
Poll::Pending => Poll::Pending,
|
|
||||||
Poll::Ready(_) => Poll::Ready(()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(any(feature = "unstable", feature = "default"))]
|
|
||||||
pub(crate) use timer::*;
|
|
||||||
|
|
||||||
/// Defers evaluation of a block of code until the end of the scope.
|
/// Defers evaluation of a block of code until the end of the scope.
|
||||||
#[cfg(feature = "default")]
|
#[cfg(feature = "default")]
|
||||||
#[doc(hidden)]
|
#[doc(hidden)]
|
||||||
|
@ -302,6 +257,11 @@ macro_rules! extension_trait {
|
||||||
$(#[cfg(feature = "docs")] $imp)*
|
$(#[cfg(feature = "docs")] $imp)*
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Optimization: expand `$head` eagerly before starting a new method definition.
|
||||||
|
(@ext ($($head:tt)*) #[doc = $d:literal] $($tail:tt)*) => {
|
||||||
|
$($head)* extension_trait!(@ext (#[doc = $d]) $($tail)*);
|
||||||
|
};
|
||||||
|
|
||||||
// Parse the return type in an extension method.
|
// Parse the return type in an extension method.
|
||||||
(@doc ($($head:tt)*) -> impl Future<Output = $out:ty> $(+ $lt:lifetime)? [$f:ty] $($tail:tt)*) => {
|
(@doc ($($head:tt)*) -> impl Future<Output = $out:ty> $(+ $lt:lifetime)? [$f:ty] $($tail:tt)*) => {
|
||||||
extension_trait!(@doc ($($head)* -> owned::ImplFuture<$out>) $($tail)*);
|
extension_trait!(@doc ($($head)* -> owned::ImplFuture<$out>) $($tail)*);
|
||||||
|
|
|
@ -3,14 +3,11 @@ use std::pin::Pin;
|
||||||
use crate::prelude::*;
|
use crate::prelude::*;
|
||||||
use crate::stream::{self, IntoStream};
|
use crate::stream::{self, IntoStream};
|
||||||
|
|
||||||
impl<T: Send> stream::Extend<T> for Vec<T> {
|
impl<T> stream::Extend<T> for Vec<T> {
|
||||||
fn extend<'a, S: IntoStream<Item = T> + 'a>(
|
fn extend<'a, S: IntoStream<Item = T> + 'a>(
|
||||||
&'a mut self,
|
&'a mut self,
|
||||||
stream: S,
|
stream: S,
|
||||||
) -> Pin<Box<dyn Future<Output = ()> + 'a + Send>>
|
) -> Pin<Box<dyn Future<Output = ()> + 'a>> {
|
||||||
where
|
|
||||||
<S as IntoStream>::IntoStream: Send,
|
|
||||||
{
|
|
||||||
let stream = stream.into_stream();
|
let stream = stream.into_stream();
|
||||||
|
|
||||||
self.reserve(stream.size_hint().0);
|
self.reserve(stream.size_hint().0);
|
||||||
|
|
|
@ -6,13 +6,13 @@ use std::sync::Arc;
|
||||||
use crate::prelude::*;
|
use crate::prelude::*;
|
||||||
use crate::stream::{self, FromStream, IntoStream};
|
use crate::stream::{self, FromStream, IntoStream};
|
||||||
|
|
||||||
impl<T: Send> FromStream<T> for Vec<T> {
|
impl<T> FromStream<T> for Vec<T> {
|
||||||
#[inline]
|
#[inline]
|
||||||
fn from_stream<'a, S: IntoStream<Item = T>>(
|
fn from_stream<'a, S: IntoStream<Item = T>>(
|
||||||
stream: S,
|
stream: S,
|
||||||
) -> Pin<Box<dyn Future<Output = Self> + 'a + Send>>
|
) -> Pin<Box<dyn Future<Output = Self> + 'a>>
|
||||||
where
|
where
|
||||||
<S as IntoStream>::IntoStream: 'a + Send,
|
<S as IntoStream>::IntoStream: 'a,
|
||||||
{
|
{
|
||||||
let stream = stream.into_stream();
|
let stream = stream.into_stream();
|
||||||
|
|
||||||
|
@ -24,14 +24,11 @@ impl<T: Send> FromStream<T> for Vec<T> {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'b, T: Clone + Send> FromStream<T> for Cow<'b, [T]> {
|
impl<'b, T: Clone> FromStream<T> for Cow<'b, [T]> {
|
||||||
#[inline]
|
#[inline]
|
||||||
fn from_stream<'a, S: IntoStream<Item = T> + 'a>(
|
fn from_stream<'a, S: IntoStream<Item = T> + 'a>(
|
||||||
stream: S,
|
stream: S,
|
||||||
) -> Pin<Box<dyn Future<Output = Self> + 'a + Send>>
|
) -> Pin<Box<dyn Future<Output = Self> + 'a>> {
|
||||||
where
|
|
||||||
<S as IntoStream>::IntoStream: Send
|
|
||||||
{
|
|
||||||
let stream = stream.into_stream();
|
let stream = stream.into_stream();
|
||||||
|
|
||||||
Box::pin(async move {
|
Box::pin(async move {
|
||||||
|
@ -40,14 +37,11 @@ impl<'b, T: Clone + Send> FromStream<T> for Cow<'b, [T]> {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T: Send> FromStream<T> for Box<[T]> {
|
impl<T> FromStream<T> for Box<[T]> {
|
||||||
#[inline]
|
#[inline]
|
||||||
fn from_stream<'a, S: IntoStream<Item = T> + 'a>(
|
fn from_stream<'a, S: IntoStream<Item = T> + 'a>(
|
||||||
stream: S,
|
stream: S,
|
||||||
) -> Pin<Box<dyn Future<Output = Self> + 'a + Send>>
|
) -> Pin<Box<dyn Future<Output = Self> + 'a>> {
|
||||||
where
|
|
||||||
<S as IntoStream>::IntoStream: Send
|
|
||||||
{
|
|
||||||
let stream = stream.into_stream();
|
let stream = stream.into_stream();
|
||||||
|
|
||||||
Box::pin(async move {
|
Box::pin(async move {
|
||||||
|
@ -56,14 +50,11 @@ impl<T: Send> FromStream<T> for Box<[T]> {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T: Send> FromStream<T> for Rc<[T]> {
|
impl<T> FromStream<T> for Rc<[T]> {
|
||||||
#[inline]
|
#[inline]
|
||||||
fn from_stream<'a, S: IntoStream<Item = T> + 'a>(
|
fn from_stream<'a, S: IntoStream<Item = T> + 'a>(
|
||||||
stream: S,
|
stream: S,
|
||||||
) -> Pin<Box<dyn Future<Output = Self> + 'a + Send>>
|
) -> Pin<Box<dyn Future<Output = Self> + 'a>> {
|
||||||
where
|
|
||||||
<S as IntoStream>::IntoStream: Send
|
|
||||||
{
|
|
||||||
let stream = stream.into_stream();
|
let stream = stream.into_stream();
|
||||||
|
|
||||||
Box::pin(async move {
|
Box::pin(async move {
|
||||||
|
@ -72,14 +63,11 @@ impl<T: Send> FromStream<T> for Rc<[T]> {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T: Send> FromStream<T> for Arc<[T]> {
|
impl<T> FromStream<T> for Arc<[T]> {
|
||||||
#[inline]
|
#[inline]
|
||||||
fn from_stream<'a, S: IntoStream<Item = T> + 'a>(
|
fn from_stream<'a, S: IntoStream<Item = T> + 'a>(
|
||||||
stream: S,
|
stream: S,
|
||||||
) -> Pin<Box<dyn Future<Output = Self> + 'a + Send>>
|
) -> Pin<Box<dyn Future<Output = Self> + 'a>> {
|
||||||
where
|
|
||||||
<S as IntoStream>::IntoStream: Send
|
|
||||||
{
|
|
||||||
let stream = stream.into_stream();
|
let stream = stream.into_stream();
|
||||||
|
|
||||||
Box::pin(async move {
|
Box::pin(async move {
|
||||||
|
|
|
@ -1,5 +1,3 @@
|
||||||
#![cfg(not(target_os = "unknown"))]
|
|
||||||
|
|
||||||
use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6};
|
use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6};
|
||||||
|
|
||||||
use async_std::net::ToSocketAddrs;
|
use async_std::net::ToSocketAddrs;
|
||||||
|
|
|
@ -1,63 +1,16 @@
|
||||||
#![cfg(not(target_os = "unknown"))]
|
use async_std::task;
|
||||||
|
|
||||||
use async_std::{future::ready, task::block_on};
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn smoke() {
|
fn smoke() {
|
||||||
let res = block_on(async { 1 + 2 });
|
let res = task::block_on(async { 1 + 2 });
|
||||||
assert_eq!(res, 3);
|
assert_eq!(res, 3);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
#[should_panic = "boom"]
|
#[should_panic = "boom"]
|
||||||
fn panic() {
|
fn panic() {
|
||||||
block_on(async {
|
task::block_on(async {
|
||||||
// This panic should get propagated into the parent thread.
|
// This panic should get propagated into the parent thread.
|
||||||
panic!("boom");
|
panic!("boom");
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "unstable")]
|
|
||||||
#[test]
|
|
||||||
fn nested_block_on_local() {
|
|
||||||
use async_std::task::spawn_local;
|
|
||||||
|
|
||||||
let x = block_on(async {
|
|
||||||
let a = block_on(async { block_on(async { ready(3).await }) });
|
|
||||||
let b = spawn_local(async { block_on(async { ready(2).await }) }).await;
|
|
||||||
let c = block_on(async { block_on(async { ready(1).await }) });
|
|
||||||
a + b + c
|
|
||||||
});
|
|
||||||
|
|
||||||
assert_eq!(x, 3 + 2 + 1);
|
|
||||||
|
|
||||||
let y = block_on(async {
|
|
||||||
let a = block_on(async { block_on(async { ready(3).await }) });
|
|
||||||
let b = spawn_local(async { block_on(async { ready(2).await }) }).await;
|
|
||||||
let c = block_on(async { block_on(async { ready(1).await }) });
|
|
||||||
a + b + c
|
|
||||||
});
|
|
||||||
|
|
||||||
assert_eq!(y, 3 + 2 + 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn nested_block_on() {
|
|
||||||
let x = block_on(async {
|
|
||||||
let a = block_on(async { block_on(async { ready(3).await }) });
|
|
||||||
let b = block_on(async { block_on(async { ready(2).await }) });
|
|
||||||
let c = block_on(async { block_on(async { ready(1).await }) });
|
|
||||||
a + b + c
|
|
||||||
});
|
|
||||||
|
|
||||||
assert_eq!(x, 3 + 2 + 1);
|
|
||||||
|
|
||||||
let y = block_on(async {
|
|
||||||
let a = block_on(async { block_on(async { ready(3).await }) });
|
|
||||||
let b = block_on(async { block_on(async { ready(2).await }) });
|
|
||||||
let c = block_on(async { block_on(async { ready(1).await }) });
|
|
||||||
a + b + c
|
|
||||||
});
|
|
||||||
|
|
||||||
assert_eq!(y, 3 + 2 + 1);
|
|
||||||
}
|
|
||||||
|
|
|
@ -2,19 +2,15 @@ use async_std::io::{self, BufWriter, SeekFrom};
|
||||||
use async_std::prelude::*;
|
use async_std::prelude::*;
|
||||||
use async_std::task;
|
use async_std::task;
|
||||||
|
|
||||||
#[cfg(target_arch = "wasm32")]
|
|
||||||
wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser);
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
|
|
||||||
fn test_buffered_writer() {
|
fn test_buffered_writer() {
|
||||||
#![allow(clippy::cognitive_complexity)]
|
#![allow(clippy::cognitive_complexity)]
|
||||||
task::block_on(async {
|
task::block_on(async {
|
||||||
let inner: Vec<u8> = Vec::new();
|
let inner = Vec::new();
|
||||||
let mut writer = BufWriter::<Vec<u8>>::with_capacity(2, inner);
|
let mut writer = BufWriter::with_capacity(2, inner);
|
||||||
|
|
||||||
writer.write(&[0, 1]).await.unwrap();
|
writer.write(&[0, 1]).await.unwrap();
|
||||||
assert!(writer.buffer().is_empty());
|
assert_eq!(writer.buffer(), []);
|
||||||
assert_eq!(*writer.get_ref(), [0, 1]);
|
assert_eq!(*writer.get_ref(), [0, 1]);
|
||||||
|
|
||||||
writer.write(&[2]).await.unwrap();
|
writer.write(&[2]).await.unwrap();
|
||||||
|
@ -26,7 +22,7 @@ fn test_buffered_writer() {
|
||||||
assert_eq!(*writer.get_ref(), [0, 1]);
|
assert_eq!(*writer.get_ref(), [0, 1]);
|
||||||
|
|
||||||
writer.flush().await.unwrap();
|
writer.flush().await.unwrap();
|
||||||
assert!(writer.buffer().is_empty());
|
assert_eq!(writer.buffer(), []);
|
||||||
assert_eq!(*writer.get_ref(), [0, 1, 2, 3]);
|
assert_eq!(*writer.get_ref(), [0, 1, 2, 3]);
|
||||||
|
|
||||||
writer.write(&[4]).await.unwrap();
|
writer.write(&[4]).await.unwrap();
|
||||||
|
@ -39,33 +35,31 @@ fn test_buffered_writer() {
|
||||||
assert_eq!(*writer.get_ref(), [0, 1, 2, 3, 4, 5]);
|
assert_eq!(*writer.get_ref(), [0, 1, 2, 3, 4, 5]);
|
||||||
|
|
||||||
writer.write(&[7, 8]).await.unwrap();
|
writer.write(&[7, 8]).await.unwrap();
|
||||||
assert!(writer.buffer().is_empty());
|
assert_eq!(writer.buffer(), []);
|
||||||
assert_eq!(*writer.get_ref(), [0, 1, 2, 3, 4, 5, 6, 7, 8]);
|
assert_eq!(*writer.get_ref(), [0, 1, 2, 3, 4, 5, 6, 7, 8]);
|
||||||
|
|
||||||
writer.write(&[9, 10, 11]).await.unwrap();
|
writer.write(&[9, 10, 11]).await.unwrap();
|
||||||
assert!(writer.buffer().is_empty());
|
assert_eq!(writer.buffer(), []);
|
||||||
assert_eq!(*writer.get_ref(), [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]);
|
assert_eq!(*writer.get_ref(), [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]);
|
||||||
|
|
||||||
writer.flush().await.unwrap();
|
writer.flush().await.unwrap();
|
||||||
assert!(writer.buffer().is_empty());
|
assert_eq!(writer.buffer(), []);
|
||||||
assert_eq!(*writer.get_ref(), [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]);
|
assert_eq!(*writer.get_ref(), [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]);
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
|
|
||||||
fn test_buffered_writer_inner_into_inner_flushes() {
|
fn test_buffered_writer_inner_into_inner_flushes() {
|
||||||
task::block_on(async {
|
task::block_on(async {
|
||||||
let mut w = BufWriter::with_capacity(3, Vec::<u8>::new());
|
let mut w = BufWriter::with_capacity(3, Vec::new());
|
||||||
w.write(&[0, 1]).await.unwrap();
|
w.write(&[0, 1]).await.unwrap();
|
||||||
assert!(w.get_ref().is_empty());
|
assert_eq!(*w.get_ref(), []);
|
||||||
let w = w.into_inner().await.unwrap();
|
let w = w.into_inner().await.unwrap();
|
||||||
assert_eq!(w, [0, 1]);
|
assert_eq!(w, [0, 1]);
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
|
|
||||||
fn test_buffered_writer_seek() {
|
fn test_buffered_writer_seek() {
|
||||||
task::block_on(async {
|
task::block_on(async {
|
||||||
let mut w = BufWriter::with_capacity(3, io::Cursor::new(Vec::new()));
|
let mut w = BufWriter::with_capacity(3, io::Cursor::new(Vec::new()));
|
||||||
|
|
|
@ -6,34 +6,25 @@ use std::time::Duration;
|
||||||
|
|
||||||
use async_std::sync::channel;
|
use async_std::sync::channel;
|
||||||
use async_std::task;
|
use async_std::task;
|
||||||
use rand::{Rng, SeedableRng};
|
use rand::{thread_rng, Rng};
|
||||||
|
|
||||||
#[cfg(not(target_os = "unknown"))]
|
|
||||||
use async_std::task::spawn;
|
|
||||||
#[cfg(target_os = "unknown")]
|
|
||||||
use async_std::task::spawn_local as spawn;
|
|
||||||
|
|
||||||
#[cfg(target_arch = "wasm32")]
|
|
||||||
wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser);
|
|
||||||
|
|
||||||
fn ms(ms: u64) -> Duration {
|
fn ms(ms: u64) -> Duration {
|
||||||
Duration::from_millis(ms)
|
Duration::from_millis(ms)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
|
|
||||||
fn smoke() {
|
fn smoke() {
|
||||||
task::block_on(async {
|
task::block_on(async {
|
||||||
let (s, r) = channel(1);
|
let (s, r) = channel(1);
|
||||||
|
|
||||||
s.send(7).await;
|
s.send(7).await;
|
||||||
assert_eq!(r.recv().await.unwrap(), 7);
|
assert_eq!(r.recv().await, Some(7));
|
||||||
|
|
||||||
s.send(8).await;
|
s.send(8).await;
|
||||||
assert_eq!(r.recv().await.unwrap(), 8);
|
assert_eq!(r.recv().await, Some(8));
|
||||||
|
|
||||||
drop(s);
|
drop(s);
|
||||||
assert!(r.recv().await.is_err());
|
assert_eq!(r.recv().await, None);
|
||||||
});
|
});
|
||||||
|
|
||||||
task::block_on(async {
|
task::block_on(async {
|
||||||
|
@ -44,7 +35,6 @@ fn smoke() {
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
|
|
||||||
fn capacity() {
|
fn capacity() {
|
||||||
for i in 1..10 {
|
for i in 1..10 {
|
||||||
let (s, r) = channel::<()>(i);
|
let (s, r) = channel::<()>(i);
|
||||||
|
@ -54,7 +44,6 @@ fn capacity() {
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
|
|
||||||
fn len_empty_full() {
|
fn len_empty_full() {
|
||||||
#![allow(clippy::cognitive_complexity)]
|
#![allow(clippy::cognitive_complexity)]
|
||||||
task::block_on(async {
|
task::block_on(async {
|
||||||
|
@ -85,7 +74,7 @@ fn len_empty_full() {
|
||||||
assert_eq!(r.is_empty(), false);
|
assert_eq!(r.is_empty(), false);
|
||||||
assert_eq!(r.is_full(), true);
|
assert_eq!(r.is_full(), true);
|
||||||
|
|
||||||
let _ = r.recv().await;
|
r.recv().await;
|
||||||
|
|
||||||
assert_eq!(s.len(), 1);
|
assert_eq!(s.len(), 1);
|
||||||
assert_eq!(s.is_empty(), false);
|
assert_eq!(s.is_empty(), false);
|
||||||
|
@ -97,18 +86,17 @@ fn len_empty_full() {
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
|
|
||||||
fn recv() {
|
fn recv() {
|
||||||
task::block_on(async {
|
task::block_on(async {
|
||||||
let (s, r) = channel(100);
|
let (s, r) = channel(100);
|
||||||
|
|
||||||
spawn(async move {
|
task::spawn(async move {
|
||||||
assert_eq!(r.recv().await.unwrap(), 7);
|
assert_eq!(r.recv().await, Some(7));
|
||||||
task::sleep(ms(1000)).await;
|
task::sleep(ms(1000)).await;
|
||||||
assert_eq!(r.recv().await.unwrap(), 8);
|
assert_eq!(r.recv().await, Some(8));
|
||||||
task::sleep(ms(1000)).await;
|
task::sleep(ms(1000)).await;
|
||||||
assert_eq!(r.recv().await.unwrap(), 9);
|
assert_eq!(r.recv().await, Some(9));
|
||||||
assert!(r.recv().await.is_err());
|
assert_eq!(r.recv().await, None);
|
||||||
});
|
});
|
||||||
|
|
||||||
task::sleep(ms(1500)).await;
|
task::sleep(ms(1500)).await;
|
||||||
|
@ -119,12 +107,11 @@ fn recv() {
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
|
|
||||||
fn send() {
|
fn send() {
|
||||||
task::block_on(async {
|
task::block_on(async {
|
||||||
let (s, r) = channel(1);
|
let (s, r) = channel(1);
|
||||||
|
|
||||||
spawn(async move {
|
task::spawn(async move {
|
||||||
s.send(7).await;
|
s.send(7).await;
|
||||||
task::sleep(ms(1000)).await;
|
task::sleep(ms(1000)).await;
|
||||||
s.send(8).await;
|
s.send(8).await;
|
||||||
|
@ -135,14 +122,13 @@ fn send() {
|
||||||
});
|
});
|
||||||
|
|
||||||
task::sleep(ms(1500)).await;
|
task::sleep(ms(1500)).await;
|
||||||
assert_eq!(r.recv().await.unwrap(), 7);
|
assert_eq!(r.recv().await, Some(7));
|
||||||
assert_eq!(r.recv().await.unwrap(), 8);
|
assert_eq!(r.recv().await, Some(8));
|
||||||
assert_eq!(r.recv().await.unwrap(), 9);
|
assert_eq!(r.recv().await, Some(9));
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
|
|
||||||
fn recv_after_disconnect() {
|
fn recv_after_disconnect() {
|
||||||
task::block_on(async {
|
task::block_on(async {
|
||||||
let (s, r) = channel(100);
|
let (s, r) = channel(100);
|
||||||
|
@ -153,15 +139,14 @@ fn recv_after_disconnect() {
|
||||||
|
|
||||||
drop(s);
|
drop(s);
|
||||||
|
|
||||||
assert_eq!(r.recv().await.unwrap(), 1);
|
assert_eq!(r.recv().await, Some(1));
|
||||||
assert_eq!(r.recv().await.unwrap(), 2);
|
assert_eq!(r.recv().await, Some(2));
|
||||||
assert_eq!(r.recv().await.unwrap(), 3);
|
assert_eq!(r.recv().await, Some(3));
|
||||||
assert!(r.recv().await.is_err());
|
assert_eq!(r.recv().await, None);
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
|
|
||||||
fn len() {
|
fn len() {
|
||||||
const COUNT: usize = 25_000;
|
const COUNT: usize = 25_000;
|
||||||
const CAP: usize = 1000;
|
const CAP: usize = 1000;
|
||||||
|
@ -179,7 +164,7 @@ fn len() {
|
||||||
}
|
}
|
||||||
|
|
||||||
for i in 0..50 {
|
for i in 0..50 {
|
||||||
let _ = r.recv().await;
|
r.recv().await;
|
||||||
assert_eq!(r.len(), 50 - i - 1);
|
assert_eq!(r.len(), 50 - i - 1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -199,11 +184,11 @@ fn len() {
|
||||||
assert_eq!(s.len(), 0);
|
assert_eq!(s.len(), 0);
|
||||||
assert_eq!(r.len(), 0);
|
assert_eq!(r.len(), 0);
|
||||||
|
|
||||||
let child = spawn({
|
let child = task::spawn({
|
||||||
let r = r.clone();
|
let r = r.clone();
|
||||||
async move {
|
async move {
|
||||||
for i in 0..COUNT {
|
for i in 0..COUNT {
|
||||||
assert_eq!(r.recv().await.unwrap(), i);
|
assert_eq!(r.recv().await, Some(i));
|
||||||
let len = r.len();
|
let len = r.len();
|
||||||
assert!(len <= CAP);
|
assert!(len <= CAP);
|
||||||
}
|
}
|
||||||
|
@ -224,13 +209,12 @@ fn len() {
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
|
|
||||||
fn disconnect_wakes_receiver() {
|
fn disconnect_wakes_receiver() {
|
||||||
task::block_on(async {
|
task::block_on(async {
|
||||||
let (s, r) = channel::<()>(1);
|
let (s, r) = channel::<()>(1);
|
||||||
|
|
||||||
let child = spawn(async move {
|
let child = task::spawn(async move {
|
||||||
assert!(r.recv().await.is_err());
|
assert_eq!(r.recv().await, None);
|
||||||
});
|
});
|
||||||
|
|
||||||
task::sleep(ms(1000)).await;
|
task::sleep(ms(1000)).await;
|
||||||
|
@ -241,18 +225,17 @@ fn disconnect_wakes_receiver() {
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
|
|
||||||
fn spsc() {
|
fn spsc() {
|
||||||
const COUNT: usize = 100_000;
|
const COUNT: usize = 100_000;
|
||||||
|
|
||||||
task::block_on(async {
|
task::block_on(async {
|
||||||
let (s, r) = channel(3);
|
let (s, r) = channel(3);
|
||||||
|
|
||||||
let child = spawn(async move {
|
let child = task::spawn(async move {
|
||||||
for i in 0..COUNT {
|
for i in 0..COUNT {
|
||||||
assert_eq!(r.recv().await.unwrap(), i);
|
assert_eq!(r.recv().await, Some(i));
|
||||||
}
|
}
|
||||||
assert!(r.recv().await.is_err());
|
assert_eq!(r.recv().await, None);
|
||||||
});
|
});
|
||||||
|
|
||||||
for i in 0..COUNT {
|
for i in 0..COUNT {
|
||||||
|
@ -265,7 +248,6 @@ fn spsc() {
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
|
|
||||||
fn mpmc() {
|
fn mpmc() {
|
||||||
const COUNT: usize = 25_000;
|
const COUNT: usize = 25_000;
|
||||||
const TASKS: usize = 4;
|
const TASKS: usize = 4;
|
||||||
|
@ -280,7 +262,7 @@ fn mpmc() {
|
||||||
for _ in 0..TASKS {
|
for _ in 0..TASKS {
|
||||||
let r = r.clone();
|
let r = r.clone();
|
||||||
let v = v.clone();
|
let v = v.clone();
|
||||||
tasks.push(spawn(async move {
|
tasks.push(task::spawn(async move {
|
||||||
for _ in 0..COUNT {
|
for _ in 0..COUNT {
|
||||||
let n = r.recv().await.unwrap();
|
let n = r.recv().await.unwrap();
|
||||||
v[n].fetch_add(1, Ordering::SeqCst);
|
v[n].fetch_add(1, Ordering::SeqCst);
|
||||||
|
@ -290,7 +272,7 @@ fn mpmc() {
|
||||||
|
|
||||||
for _ in 0..TASKS {
|
for _ in 0..TASKS {
|
||||||
let s = s.clone();
|
let s = s.clone();
|
||||||
tasks.push(spawn(async move {
|
tasks.push(task::spawn(async move {
|
||||||
for i in 0..COUNT {
|
for i in 0..COUNT {
|
||||||
s.send(i).await;
|
s.send(i).await;
|
||||||
}
|
}
|
||||||
|
@ -308,7 +290,6 @@ fn mpmc() {
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
|
|
||||||
fn oneshot() {
|
fn oneshot() {
|
||||||
const COUNT: usize = 10_000;
|
const COUNT: usize = 10_000;
|
||||||
|
|
||||||
|
@ -316,8 +297,8 @@ fn oneshot() {
|
||||||
for _ in 0..COUNT {
|
for _ in 0..COUNT {
|
||||||
let (s, r) = channel(1);
|
let (s, r) = channel(1);
|
||||||
|
|
||||||
let c1 = spawn(async move { r.recv().await.unwrap() });
|
let c1 = task::spawn(async move { r.recv().await.unwrap() });
|
||||||
let c2 = spawn(async move { s.send(0).await });
|
let c2 = task::spawn(async move { s.send(0).await });
|
||||||
|
|
||||||
c1.await;
|
c1.await;
|
||||||
c2.await;
|
c2.await;
|
||||||
|
@ -326,7 +307,6 @@ fn oneshot() {
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
|
|
||||||
fn drops() {
|
fn drops() {
|
||||||
const RUNS: usize = 100;
|
const RUNS: usize = 100;
|
||||||
|
|
||||||
|
@ -341,16 +321,17 @@ fn drops() {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let mut rng = thread_rng();
|
||||||
|
|
||||||
for _ in 0..RUNS {
|
for _ in 0..RUNS {
|
||||||
let mut rng = rand_xorshift::XorShiftRng::seed_from_u64(0);
|
task::block_on(async {
|
||||||
task::block_on(async move {
|
|
||||||
let steps = rng.gen_range(0, 10_000);
|
let steps = rng.gen_range(0, 10_000);
|
||||||
let additional = rng.gen_range(0, 50);
|
let additional = rng.gen_range(0, 50);
|
||||||
|
|
||||||
DROPS.store(0, Ordering::SeqCst);
|
DROPS.store(0, Ordering::SeqCst);
|
||||||
let (s, r) = channel::<DropCounter>(50);
|
let (s, r) = channel::<DropCounter>(50);
|
||||||
|
|
||||||
let child = spawn({
|
let child = task::spawn({
|
||||||
let r = r.clone();
|
let r = r.clone();
|
||||||
async move {
|
async move {
|
||||||
for _ in 0..steps {
|
for _ in 0..steps {
|
||||||
|
|
|
@ -1,20 +0,0 @@
|
||||||
#[cfg(feature = "unstable")]
|
|
||||||
#[test]
|
|
||||||
fn test_send() -> async_std::io::Result<()> {
|
|
||||||
use async_std::prelude::*;
|
|
||||||
use async_std::{stream, task};
|
|
||||||
|
|
||||||
task::block_on(async {
|
|
||||||
fn test_send_trait<T: Send>(_: &T) {}
|
|
||||||
|
|
||||||
let stream = stream::repeat(1u8).take(10);
|
|
||||||
test_send_trait(&stream);
|
|
||||||
|
|
||||||
let fut = stream.collect::<Vec<_>>();
|
|
||||||
|
|
||||||
// This line triggers a compilation error
|
|
||||||
test_send_trait(&fut);
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
})
|
|
||||||
}
|
|
103
tests/condvar.rs
103
tests/condvar.rs
|
@ -1,103 +0,0 @@
|
||||||
#![cfg(feature = "unstable")]
|
|
||||||
use std::sync::Arc;
|
|
||||||
use std::time::Duration;
|
|
||||||
|
|
||||||
use async_std::sync::{Condvar, Mutex};
|
|
||||||
use async_std::task::{self, JoinHandle};
|
|
||||||
|
|
||||||
#[cfg(not(target_os = "unknown"))]
|
|
||||||
use async_std::task::spawn;
|
|
||||||
#[cfg(target_os = "unknown")]
|
|
||||||
use async_std::task::spawn_local as spawn;
|
|
||||||
|
|
||||||
#[cfg(target_arch = "wasm32")]
|
|
||||||
wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser);
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
|
|
||||||
fn wait_timeout_with_lock() {
|
|
||||||
task::block_on(async {
|
|
||||||
let pair = Arc::new((Mutex::new(false), Condvar::new()));
|
|
||||||
let pair2 = pair.clone();
|
|
||||||
|
|
||||||
spawn(async move {
|
|
||||||
let (m, c) = &*pair2;
|
|
||||||
let _g = m.lock().await;
|
|
||||||
task::sleep(Duration::from_millis(200)).await;
|
|
||||||
c.notify_one();
|
|
||||||
});
|
|
||||||
|
|
||||||
let (m, c) = &*pair;
|
|
||||||
let (_, wait_result) = c
|
|
||||||
.wait_timeout(m.lock().await, Duration::from_millis(50))
|
|
||||||
.await;
|
|
||||||
assert!(wait_result.timed_out());
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
|
|
||||||
fn wait_timeout_without_lock() {
|
|
||||||
task::block_on(async {
|
|
||||||
let m = Mutex::new(false);
|
|
||||||
let c = Condvar::new();
|
|
||||||
|
|
||||||
let (_, wait_result) = c
|
|
||||||
.wait_timeout(m.lock().await, Duration::from_millis(10))
|
|
||||||
.await;
|
|
||||||
assert!(wait_result.timed_out());
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
|
|
||||||
fn wait_timeout_until_timed_out() {
|
|
||||||
task::block_on(async {
|
|
||||||
let m = Mutex::new(false);
|
|
||||||
let c = Condvar::new();
|
|
||||||
|
|
||||||
let (_, wait_result) = c
|
|
||||||
.wait_timeout_until(m.lock().await, Duration::from_millis(100), |&mut started| {
|
|
||||||
started
|
|
||||||
})
|
|
||||||
.await;
|
|
||||||
assert!(wait_result.timed_out());
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
|
|
||||||
fn notify_all() {
|
|
||||||
task::block_on(async {
|
|
||||||
let mut tasks: Vec<JoinHandle<()>> = Vec::new();
|
|
||||||
let pair = Arc::new((Mutex::new(0u32), Condvar::new()));
|
|
||||||
|
|
||||||
for _ in 0..10 {
|
|
||||||
let pair = pair.clone();
|
|
||||||
tasks.push(spawn(async move {
|
|
||||||
let (m, c) = &*pair;
|
|
||||||
let mut count = m.lock().await;
|
|
||||||
while *count == 0 {
|
|
||||||
count = c.wait(count).await;
|
|
||||||
}
|
|
||||||
*count += 1;
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Give some time for tasks to start up
|
|
||||||
task::sleep(Duration::from_millis(50)).await;
|
|
||||||
|
|
||||||
let (m, c) = &*pair;
|
|
||||||
{
|
|
||||||
let mut count = m.lock().await;
|
|
||||||
*count += 1;
|
|
||||||
c.notify_all();
|
|
||||||
}
|
|
||||||
|
|
||||||
for t in tasks {
|
|
||||||
t.await;
|
|
||||||
}
|
|
||||||
let count = m.lock().await;
|
|
||||||
assert_eq!(11, *count);
|
|
||||||
})
|
|
||||||
}
|
|
|
@ -5,14 +5,6 @@ use async_std::task;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
#[should_panic(expected = "timed out")]
|
#[should_panic(expected = "timed out")]
|
||||||
#[cfg(not(any(
|
|
||||||
target_os = "unknown",
|
|
||||||
target_arch = "arm",
|
|
||||||
target_arch = "mips",
|
|
||||||
target_arch = "powerpc",
|
|
||||||
target_arch = "powerpc64",
|
|
||||||
target_arch = "x86",
|
|
||||||
)))] // stdin tests fail when running through cross
|
|
||||||
fn io_timeout_timedout() {
|
fn io_timeout_timedout() {
|
||||||
task::block_on(async {
|
task::block_on(async {
|
||||||
io::timeout(Duration::from_secs(1), async {
|
io::timeout(Duration::from_secs(1), async {
|
||||||
|
|
|
@ -5,16 +5,7 @@ use async_std::sync::Mutex;
|
||||||
use async_std::task;
|
use async_std::task;
|
||||||
use futures::channel::mpsc;
|
use futures::channel::mpsc;
|
||||||
|
|
||||||
#[cfg(not(target_os = "unknown"))]
|
|
||||||
use async_std::task::spawn;
|
|
||||||
#[cfg(target_os = "unknown")]
|
|
||||||
use async_std::task::spawn_local as spawn;
|
|
||||||
|
|
||||||
#[cfg(target_arch = "wasm32")]
|
|
||||||
wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser);
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
|
|
||||||
fn smoke() {
|
fn smoke() {
|
||||||
task::block_on(async {
|
task::block_on(async {
|
||||||
let m = Mutex::new(());
|
let m = Mutex::new(());
|
||||||
|
@ -24,21 +15,18 @@ fn smoke() {
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
|
|
||||||
fn try_lock() {
|
fn try_lock() {
|
||||||
let m = Mutex::new(());
|
let m = Mutex::new(());
|
||||||
*m.try_lock().unwrap() = ();
|
*m.try_lock().unwrap() = ();
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
|
|
||||||
fn into_inner() {
|
fn into_inner() {
|
||||||
let m = Mutex::new(10);
|
let m = Mutex::new(10);
|
||||||
assert_eq!(m.into_inner(), 10);
|
assert_eq!(m.into_inner(), 10);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
|
|
||||||
fn get_mut() {
|
fn get_mut() {
|
||||||
let mut m = Mutex::new(10);
|
let mut m = Mutex::new(10);
|
||||||
*m.get_mut() = 20;
|
*m.get_mut() = 20;
|
||||||
|
@ -46,7 +34,6 @@ fn get_mut() {
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
|
|
||||||
fn contention() {
|
fn contention() {
|
||||||
task::block_on(async {
|
task::block_on(async {
|
||||||
let (tx, mut rx) = mpsc::unbounded();
|
let (tx, mut rx) = mpsc::unbounded();
|
||||||
|
@ -55,29 +42,22 @@ fn contention() {
|
||||||
let mutex = Arc::new(Mutex::new(0));
|
let mutex = Arc::new(Mutex::new(0));
|
||||||
let num_tasks = 10000;
|
let num_tasks = 10000;
|
||||||
|
|
||||||
let mut handles = Vec::new();
|
|
||||||
for _ in 0..num_tasks {
|
for _ in 0..num_tasks {
|
||||||
let tx = tx.clone();
|
let tx = tx.clone();
|
||||||
let mutex = mutex.clone();
|
let mutex = mutex.clone();
|
||||||
|
|
||||||
handles.push(spawn(async move {
|
task::spawn(async move {
|
||||||
let mut lock = mutex.lock().await;
|
let mut lock = mutex.lock().await;
|
||||||
*lock += 1;
|
*lock += 1;
|
||||||
tx.unbounded_send(()).unwrap();
|
tx.unbounded_send(()).unwrap();
|
||||||
drop(lock);
|
drop(lock);
|
||||||
}));
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
for _ in 0..num_tasks {
|
for _ in 0..num_tasks {
|
||||||
rx.next().await.unwrap();
|
rx.next().await.unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
for handle in handles.into_iter() {
|
|
||||||
handle.await;
|
|
||||||
}
|
|
||||||
|
|
||||||
dbg!("wait");
|
|
||||||
|
|
||||||
let lock = mutex.lock().await;
|
let lock = mutex.lock().await;
|
||||||
assert_eq!(num_tasks, *lock);
|
assert_eq!(num_tasks, *lock);
|
||||||
});
|
});
|
||||||
|
|
|
@ -10,14 +10,6 @@ use async_std::sync::RwLock;
|
||||||
use async_std::task;
|
use async_std::task;
|
||||||
use futures::channel::mpsc;
|
use futures::channel::mpsc;
|
||||||
|
|
||||||
#[cfg(not(target_os = "unknown"))]
|
|
||||||
use async_std::task::spawn;
|
|
||||||
#[cfg(target_os = "unknown")]
|
|
||||||
use async_std::task::spawn_local as spawn;
|
|
||||||
|
|
||||||
#[cfg(target_arch = "wasm32")]
|
|
||||||
wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser);
|
|
||||||
|
|
||||||
/// Generates a random number in `0..n`.
|
/// Generates a random number in `0..n`.
|
||||||
pub fn random(n: u32) -> u32 {
|
pub fn random(n: u32) -> u32 {
|
||||||
thread_local! {
|
thread_local! {
|
||||||
|
@ -43,7 +35,6 @@ pub fn random(n: u32) -> u32 {
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
|
|
||||||
fn smoke() {
|
fn smoke() {
|
||||||
task::block_on(async {
|
task::block_on(async {
|
||||||
let lock = RwLock::new(());
|
let lock = RwLock::new(());
|
||||||
|
@ -55,7 +46,6 @@ fn smoke() {
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
|
|
||||||
fn try_write() {
|
fn try_write() {
|
||||||
task::block_on(async {
|
task::block_on(async {
|
||||||
let lock = RwLock::new(0isize);
|
let lock = RwLock::new(0isize);
|
||||||
|
@ -66,14 +56,12 @@ fn try_write() {
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
|
|
||||||
fn into_inner() {
|
fn into_inner() {
|
||||||
let lock = RwLock::new(10);
|
let lock = RwLock::new(10);
|
||||||
assert_eq!(lock.into_inner(), 10);
|
assert_eq!(lock.into_inner(), 10);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
|
|
||||||
fn into_inner_and_drop() {
|
fn into_inner_and_drop() {
|
||||||
struct Counter(Arc<AtomicUsize>);
|
struct Counter(Arc<AtomicUsize>);
|
||||||
|
|
||||||
|
@ -96,7 +84,6 @@ fn into_inner_and_drop() {
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
|
|
||||||
fn get_mut() {
|
fn get_mut() {
|
||||||
let mut lock = RwLock::new(10);
|
let mut lock = RwLock::new(10);
|
||||||
*lock.get_mut() = 20;
|
*lock.get_mut() = 20;
|
||||||
|
@ -104,7 +91,6 @@ fn get_mut() {
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
|
|
||||||
fn contention() {
|
fn contention() {
|
||||||
const N: u32 = 10;
|
const N: u32 = 10;
|
||||||
const M: usize = 1000;
|
const M: usize = 1000;
|
||||||
|
@ -118,7 +104,7 @@ fn contention() {
|
||||||
let tx = tx.clone();
|
let tx = tx.clone();
|
||||||
let rw = rw.clone();
|
let rw = rw.clone();
|
||||||
|
|
||||||
spawn(async move {
|
task::spawn(async move {
|
||||||
for _ in 0..M {
|
for _ in 0..M {
|
||||||
if random(N) == 0 {
|
if random(N) == 0 {
|
||||||
drop(rw.write().await);
|
drop(rw.write().await);
|
||||||
|
@ -130,7 +116,7 @@ fn contention() {
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
task::block_on(async move {
|
task::block_on(async {
|
||||||
for _ in 0..N {
|
for _ in 0..N {
|
||||||
rx.next().await.unwrap();
|
rx.next().await.unwrap();
|
||||||
}
|
}
|
||||||
|
@ -138,7 +124,6 @@ fn contention() {
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
|
|
||||||
fn writer_and_readers() {
|
fn writer_and_readers() {
|
||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
struct Yield(Cell<bool>);
|
struct Yield(Cell<bool>);
|
||||||
|
@ -161,7 +146,7 @@ fn writer_and_readers() {
|
||||||
let (tx, mut rx) = mpsc::unbounded();
|
let (tx, mut rx) = mpsc::unbounded();
|
||||||
|
|
||||||
// Spawn a writer task.
|
// Spawn a writer task.
|
||||||
spawn({
|
task::spawn({
|
||||||
let lock = lock.clone();
|
let lock = lock.clone();
|
||||||
async move {
|
async move {
|
||||||
let mut lock = lock.write().await;
|
let mut lock = lock.write().await;
|
||||||
|
@ -179,13 +164,13 @@ fn writer_and_readers() {
|
||||||
let mut readers = Vec::new();
|
let mut readers = Vec::new();
|
||||||
for _ in 0..5 {
|
for _ in 0..5 {
|
||||||
let lock = lock.clone();
|
let lock = lock.clone();
|
||||||
readers.push(spawn(async move {
|
readers.push(task::spawn(async move {
|
||||||
let lock = lock.read().await;
|
let lock = lock.read().await;
|
||||||
assert!(*lock >= 0);
|
assert!(*lock >= 0);
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
task::block_on(async move {
|
task::block_on(async {
|
||||||
// Wait for readers to pass their asserts.
|
// Wait for readers to pass their asserts.
|
||||||
for r in readers {
|
for r in readers {
|
||||||
r.await;
|
r.await;
|
||||||
|
|
|
@ -1,5 +1,3 @@
|
||||||
use std::convert::identity;
|
|
||||||
use std::marker::Unpin;
|
|
||||||
use std::pin::Pin;
|
use std::pin::Pin;
|
||||||
use std::task::{Context, Poll};
|
use std::task::{Context, Poll};
|
||||||
|
|
||||||
|
@ -10,23 +8,14 @@ use async_std::stream;
|
||||||
use async_std::sync::channel;
|
use async_std::sync::channel;
|
||||||
use async_std::task;
|
use async_std::task;
|
||||||
|
|
||||||
#[cfg(target_arch = "wasm32")]
|
|
||||||
wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser);
|
|
||||||
|
|
||||||
#[cfg(not(target_os = "unknown"))]
|
|
||||||
use async_std::task::spawn;
|
|
||||||
#[cfg(target_os = "unknown")]
|
|
||||||
use async_std::task::spawn_local as spawn;
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
|
|
||||||
/// Checks that streams are merged fully even if one of the components
|
/// Checks that streams are merged fully even if one of the components
|
||||||
/// experiences delay.
|
/// experiences delay.
|
||||||
fn merging_delayed_streams_work() {
|
fn merging_delayed_streams_work() {
|
||||||
let (sender, receiver) = channel::<i32>(10);
|
let (sender, receiver) = channel::<i32>(10);
|
||||||
|
|
||||||
let mut s = receiver.merge(stream::empty());
|
let mut s = receiver.merge(stream::empty());
|
||||||
let t = spawn(async move {
|
let t = task::spawn(async move {
|
||||||
let mut xs = Vec::new();
|
let mut xs = Vec::new();
|
||||||
while let Some(x) = s.next().await {
|
while let Some(x) = s.next().await {
|
||||||
xs.push(x);
|
xs.push(x);
|
||||||
|
@ -45,7 +34,7 @@ fn merging_delayed_streams_work() {
|
||||||
let (sender, receiver) = channel::<i32>(10);
|
let (sender, receiver) = channel::<i32>(10);
|
||||||
|
|
||||||
let mut s = stream::empty().merge(receiver);
|
let mut s = stream::empty().merge(receiver);
|
||||||
let t = spawn(async move {
|
let t = task::spawn(async move {
|
||||||
let mut xs = Vec::new();
|
let mut xs = Vec::new();
|
||||||
while let Some(x) = s.next().await {
|
while let Some(x) = s.next().await {
|
||||||
xs.push(x);
|
xs.push(x);
|
||||||
|
@ -96,88 +85,16 @@ fn explode<S: Stream>(s: S) -> Explode<S> {
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
|
|
||||||
fn merge_works_with_unfused_streams() {
|
fn merge_works_with_unfused_streams() {
|
||||||
let s1 = explode(stream::once(92));
|
let s1 = explode(stream::once(92));
|
||||||
let s2 = explode(stream::once(92));
|
let s2 = explode(stream::once(92));
|
||||||
let mut s = s1.merge(s2);
|
let mut s = s1.merge(s2);
|
||||||
|
let xs = task::block_on(async move {
|
||||||
task::block_on(async move {
|
|
||||||
let mut xs = Vec::new();
|
let mut xs = Vec::new();
|
||||||
while let Some(x) = s.next().await {
|
while let Some(x) = s.next().await {
|
||||||
xs.push(x)
|
xs.push(x)
|
||||||
}
|
}
|
||||||
|
xs
|
||||||
|
});
|
||||||
assert_eq!(xs, vec![92, 92]);
|
assert_eq!(xs, vec![92, 92]);
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
struct S<T>(T);
|
|
||||||
|
|
||||||
impl<T: Stream + Unpin> Stream for S<T> {
|
|
||||||
type Item = T::Item;
|
|
||||||
|
|
||||||
fn poll_next(mut self: Pin<&mut Self>, ctx: &mut Context) -> Poll<Option<Self::Item>> {
|
|
||||||
unsafe { Pin::new_unchecked(&mut self.0) }.poll_next(ctx)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
struct StrictOnce {
|
|
||||||
polled: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Stream for StrictOnce {
|
|
||||||
type Item = ();
|
|
||||||
|
|
||||||
fn poll_next(mut self: Pin<&mut Self>, _: &mut Context) -> Poll<Option<Self::Item>> {
|
|
||||||
assert!(!self.polled, "Polled after completion!");
|
|
||||||
self.polled = true;
|
|
||||||
Poll::Ready(None)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
struct Interchanger {
|
|
||||||
polled: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Stream for Interchanger {
|
|
||||||
type Item = S<Box<dyn Stream<Item = ()> + Unpin>>;
|
|
||||||
|
|
||||||
fn poll_next(mut self: Pin<&mut Self>, ctx: &mut Context) -> Poll<Option<Self::Item>> {
|
|
||||||
if self.polled {
|
|
||||||
self.polled = false;
|
|
||||||
ctx.waker().wake_by_ref();
|
|
||||||
Poll::Pending
|
|
||||||
} else {
|
|
||||||
self.polled = true;
|
|
||||||
Poll::Ready(Some(S(Box::new(StrictOnce { polled: false }))))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn flat_map_doesnt_poll_completed_inner_stream() {
|
|
||||||
task::block_on(async {
|
|
||||||
assert_eq!(
|
|
||||||
Interchanger { polled: false }
|
|
||||||
.take(2)
|
|
||||||
.flat_map(identity)
|
|
||||||
.count()
|
|
||||||
.await,
|
|
||||||
0
|
|
||||||
);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn flatten_doesnt_poll_completed_inner_stream() {
|
|
||||||
task::block_on(async {
|
|
||||||
assert_eq!(
|
|
||||||
Interchanger { polled: false }
|
|
||||||
.take(2)
|
|
||||||
.flatten()
|
|
||||||
.count()
|
|
||||||
.await,
|
|
||||||
0
|
|
||||||
);
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -3,16 +3,7 @@ use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
use async_std::task;
|
use async_std::task;
|
||||||
use async_std::task_local;
|
use async_std::task_local;
|
||||||
|
|
||||||
#[cfg(not(target_os = "unknown"))]
|
|
||||||
use async_std::task::spawn;
|
|
||||||
#[cfg(target_os = "unknown")]
|
|
||||||
use async_std::task::spawn_local as spawn;
|
|
||||||
|
|
||||||
#[cfg(target_arch = "wasm32")]
|
|
||||||
wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser);
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
|
|
||||||
fn drop_local() {
|
fn drop_local() {
|
||||||
static DROP_LOCAL: AtomicBool = AtomicBool::new(false);
|
static DROP_LOCAL: AtomicBool = AtomicBool::new(false);
|
||||||
|
|
||||||
|
@ -29,7 +20,7 @@ fn drop_local() {
|
||||||
}
|
}
|
||||||
|
|
||||||
// Spawn a task that just touches its task-local.
|
// Spawn a task that just touches its task-local.
|
||||||
let handle = spawn(async {
|
let handle = task::spawn(async {
|
||||||
LOCAL.with(|_| ());
|
LOCAL.with(|_| ());
|
||||||
});
|
});
|
||||||
let task = handle.task().clone();
|
let task = handle.task().clone();
|
||||||
|
|
|
@ -1,5 +1,3 @@
|
||||||
#![cfg(not(target_os = "unknown"))]
|
|
||||||
|
|
||||||
use async_std::io;
|
use async_std::io;
|
||||||
use async_std::net::{TcpListener, TcpStream};
|
use async_std::net::{TcpListener, TcpStream};
|
||||||
use async_std::prelude::*;
|
use async_std::prelude::*;
|
||||||
|
|
|
@ -1,26 +0,0 @@
|
||||||
use std::time::Duration;
|
|
||||||
|
|
||||||
use async_std::future::timeout;
|
|
||||||
use async_std::task;
|
|
||||||
|
|
||||||
#[cfg(target_arch = "wasm32")]
|
|
||||||
wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser);
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
|
|
||||||
fn timeout_future_many() {
|
|
||||||
task::block_on(async {
|
|
||||||
let futures = (0..10)
|
|
||||||
.map(|i| {
|
|
||||||
timeout(Duration::from_millis(i * 50), async move {
|
|
||||||
task::sleep(Duration::from_millis(i)).await;
|
|
||||||
Ok::<(), async_std::future::TimeoutError>(())
|
|
||||||
})
|
|
||||||
})
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
|
|
||||||
for future in futures {
|
|
||||||
future.await.unwrap().unwrap();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
|
@ -1,5 +1,3 @@
|
||||||
#![cfg(not(target_os = "unknown"))]
|
|
||||||
|
|
||||||
use async_std::io;
|
use async_std::io;
|
||||||
use async_std::net::UdpSocket;
|
use async_std::net::UdpSocket;
|
||||||
use async_std::task;
|
use async_std::task;
|
||||||
|
@ -19,7 +17,7 @@ fn send_recv() -> io::Result<()> {
|
||||||
|
|
||||||
socket1.connect(socket2.local_addr()?).await?;
|
socket1.connect(socket2.local_addr()?).await?;
|
||||||
socket2.connect(socket1.local_addr()?).await?;
|
socket2.connect(socket1.local_addr()?).await?;
|
||||||
assert_eq!(socket1.peer_addr()?, socket2.local_addr()?);
|
|
||||||
socket1.send(THE_MERCHANT_OF_VENICE).await?;
|
socket1.send(THE_MERCHANT_OF_VENICE).await?;
|
||||||
|
|
||||||
let mut buf = [0u8; 1024];
|
let mut buf = [0u8; 1024];
|
||||||
|
|
26
tests/uds.rs
26
tests/uds.rs
|
@ -1,4 +1,4 @@
|
||||||
#![cfg(all(unix, not(target_os = "unknown")))]
|
#![cfg(unix)]
|
||||||
|
|
||||||
use async_std::io;
|
use async_std::io;
|
||||||
use async_std::os::unix::net::{UnixDatagram, UnixListener, UnixStream};
|
use async_std::os::unix::net::{UnixDatagram, UnixListener, UnixStream};
|
||||||
|
@ -94,27 +94,3 @@ async fn ping_pong_client(socket: &std::path::PathBuf, iterations: u32) -> std::
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn uds_clone() -> io::Result<()> {
|
|
||||||
task::block_on(async {
|
|
||||||
let tmp_dir = TempDir::new("socket_ping_pong").expect("Temp dir not created");
|
|
||||||
let sock_path = tmp_dir.as_ref().join("sock");
|
|
||||||
let input = UnixListener::bind(&sock_path).await?;
|
|
||||||
|
|
||||||
let mut writer = UnixStream::connect(&sock_path).await?;
|
|
||||||
let mut reader = input.incoming().next().await.unwrap()?;
|
|
||||||
|
|
||||||
writer.write(b"original").await.unwrap();
|
|
||||||
let mut original_buf = [0; 8];
|
|
||||||
reader.read(&mut original_buf).await?;
|
|
||||||
assert_eq!(&original_buf, b"original");
|
|
||||||
|
|
||||||
writer.clone().write(b"clone").await.unwrap();
|
|
||||||
let mut clone_buf = [0; 5];
|
|
||||||
reader.clone().read(&mut clone_buf).await?;
|
|
||||||
assert_eq!(&clone_buf, b"clone");
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
|
@ -1,5 +1,3 @@
|
||||||
#![cfg(not(target_os = "unknown"))]
|
|
||||||
|
|
||||||
use async_std::{fs, io, net::ToSocketAddrs, task};
|
use async_std::{fs, io, net::ToSocketAddrs, task};
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue