futures-0.3.30/.cargo_vcs_info.json 0000644 00000000145 00000000001 0012614 0 ustar {
"git": {
"sha1": "de1a0fd64a1bcae9a1534ed4da1699632993cc26"
},
"path_in_vcs": "futures"
} futures-0.3.30/Cargo.toml 0000644 00000005670 00000000001 0010622 0 ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
#
# When uploading crates to the registry Cargo will automatically
# "normalize" Cargo.toml files for maximal compatibility
# with all versions of Cargo and also rewrite `path` dependencies
# to registry (e.g., crates.io) dependencies.
#
# If you are reading this file be aware that the original Cargo.toml
# will likely look very different (and much more reasonable).
# See Cargo.toml.orig for the original contents.
[package]
edition = "2018"
rust-version = "1.56"
name = "futures"
version = "0.3.30"
description = """
An implementation of futures and streams featuring zero allocations,
composability, and iterator-like interfaces.
"""
homepage = "https://rust-lang.github.io/futures-rs"
readme = "README.md"
keywords = [
"futures",
"async",
"future",
]
categories = ["asynchronous"]
license = "MIT OR Apache-2.0"
repository = "https://github.com/rust-lang/futures-rs"
[package.metadata.docs.rs]
all-features = true
rustdoc-args = [
"--cfg",
"docsrs",
]
[package.metadata.playground]
features = [
"std",
"async-await",
"compat",
"io-compat",
"executor",
"thread-pool",
]
[dependencies.futures-channel]
version = "0.3.30"
features = ["sink"]
default-features = false
[dependencies.futures-core]
version = "0.3.30"
default-features = false
[dependencies.futures-executor]
version = "0.3.30"
optional = true
default-features = false
[dependencies.futures-io]
version = "0.3.30"
default-features = false
[dependencies.futures-sink]
version = "0.3.30"
default-features = false
[dependencies.futures-task]
version = "0.3.30"
default-features = false
[dependencies.futures-util]
version = "0.3.30"
features = ["sink"]
default-features = false
[dev-dependencies.assert_matches]
version = "1.3.0"
[dev-dependencies.pin-project]
version = "1.0.11"
[dev-dependencies.pin-utils]
version = "0.1.0"
[dev-dependencies.static_assertions]
version = "1"
[dev-dependencies.tokio]
version = "0.1.11"
[features]
alloc = [
"futures-core/alloc",
"futures-task/alloc",
"futures-sink/alloc",
"futures-channel/alloc",
"futures-util/alloc",
]
async-await = [
"futures-util/async-await",
"futures-util/async-await-macro",
]
bilock = ["futures-util/bilock"]
cfg-target-has-atomic = []
compat = [
"std",
"futures-util/compat",
]
default = [
"std",
"async-await",
"executor",
]
executor = [
"std",
"futures-executor/std",
]
io-compat = [
"compat",
"futures-util/io-compat",
]
std = [
"alloc",
"futures-core/std",
"futures-task/std",
"futures-io/std",
"futures-sink/std",
"futures-util/std",
"futures-util/io",
"futures-util/channel",
]
thread-pool = [
"executor",
"futures-executor/thread-pool",
]
unstable = [
"futures-core/unstable",
"futures-task/unstable",
"futures-channel/unstable",
"futures-io/unstable",
"futures-util/unstable",
]
write-all-vectored = ["futures-util/write-all-vectored"]
futures-0.3.30/Cargo.toml.orig 0000644 0000000 0000000 00000005235 10461020230 0014300 0 ustar 0000000 0000000 [package]
name = "futures"
version = "0.3.30"
edition = "2018"
rust-version = "1.56"
license = "MIT OR Apache-2.0"
readme = "../README.md"
keywords = ["futures", "async", "future"]
repository = "https://github.com/rust-lang/futures-rs"
homepage = "https://rust-lang.github.io/futures-rs"
description = """
An implementation of futures and streams featuring zero allocations,
composability, and iterator-like interfaces.
"""
categories = ["asynchronous"]
[dependencies]
futures-core = { path = "../futures-core", version = "0.3.30", default-features = false }
futures-task = { path = "../futures-task", version = "0.3.30", default-features = false }
futures-channel = { path = "../futures-channel", version = "0.3.30", default-features = false, features = ["sink"] }
futures-executor = { path = "../futures-executor", version = "0.3.30", default-features = false, optional = true }
futures-io = { path = "../futures-io", version = "0.3.30", default-features = false }
futures-sink = { path = "../futures-sink", version = "0.3.30", default-features = false }
futures-util = { path = "../futures-util", version = "0.3.30", default-features = false, features = ["sink"] }
[dev-dependencies]
futures-executor = { path = "../futures-executor", features = ["thread-pool"] }
futures-test = { path = "../futures-test" }
assert_matches = "1.3.0"
pin-project = "1.0.11"
pin-utils = "0.1.0"
static_assertions = "1"
tokio = "0.1.11"
[features]
default = ["std", "async-await", "executor"]
std = ["alloc", "futures-core/std", "futures-task/std", "futures-io/std", "futures-sink/std", "futures-util/std", "futures-util/io", "futures-util/channel"]
alloc = ["futures-core/alloc", "futures-task/alloc", "futures-sink/alloc", "futures-channel/alloc", "futures-util/alloc"]
async-await = ["futures-util/async-await", "futures-util/async-await-macro"]
compat = ["std", "futures-util/compat"]
io-compat = ["compat", "futures-util/io-compat"]
executor = ["std", "futures-executor/std"]
thread-pool = ["executor", "futures-executor/thread-pool"]
# Unstable features
# These features are outside of the normal semver guarantees and require the
# `unstable` feature as an explicit opt-in to unstable API.
unstable = ["futures-core/unstable", "futures-task/unstable", "futures-channel/unstable", "futures-io/unstable", "futures-util/unstable"]
bilock = ["futures-util/bilock"]
write-all-vectored = ["futures-util/write-all-vectored"]
# These features are no longer used.
# TODO: remove in the next major version.
cfg-target-has-atomic = []
[package.metadata.docs.rs]
all-features = true
rustdoc-args = ["--cfg", "docsrs"]
[package.metadata.playground]
features = ["std", "async-await", "compat", "io-compat", "executor", "thread-pool"]
futures-0.3.30/LICENSE-APACHE 0000644 0000000 0000000 00000025172 10461020230 0013337 0 ustar 0000000 0000000 Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright (c) 2016 Alex Crichton
Copyright (c) 2017 The Tokio Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
futures-0.3.30/LICENSE-MIT 0000644 0000000 0000000 00000002106 10461020230 0013037 0 ustar 0000000 0000000 Copyright (c) 2016 Alex Crichton
Copyright (c) 2017 The Tokio Authors
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
futures-0.3.30/README.md 0000644 0000000 0000000 00000003473 10461020230 0012672 0 ustar 0000000 0000000
`futures-rs` is a library providing the foundations for asynchronous programming in Rust.
It includes key trait definitions like `Stream`, as well as utilities like `join!`,
`select!`, and various futures combinator methods which enable expressive asynchronous
control flow.
## Usage
Add this to your `Cargo.toml`:
```toml
[dependencies]
futures = "0.3"
```
The current `futures` requires Rust 1.56 or later.
### Feature `std`
Futures-rs works without the standard library, such as in bare metal environments.
However, it has a significantly reduced API surface. To use futures-rs in
a `#[no_std]` environment, use:
```toml
[dependencies]
futures = { version = "0.3", default-features = false }
```
## License
Licensed under either of [Apache License, Version 2.0](LICENSE-APACHE) or
[MIT license](LICENSE-MIT) at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted
for inclusion in the work by you, as defined in the Apache-2.0 license, shall
be dual licensed as above, without any additional terms or conditions.
futures-0.3.30/src/lib.rs 0000644 0000000 0000000 00000023054 10461020230 0013313 0 ustar 0000000 0000000 //! Abstractions for asynchronous programming.
//!
//! This crate provides a number of core abstractions for writing asynchronous
//! code:
//!
//! - [Futures](crate::future) are single eventual values produced by
//! asynchronous computations. Some programming languages (e.g. JavaScript)
//! call this concept "promise".
//! - [Streams](crate::stream) represent a series of values
//! produced asynchronously.
//! - [Sinks](crate::sink) provide support for asynchronous writing of
//! data.
//! - [Executors](crate::executor) are responsible for running asynchronous
//! tasks.
//!
//! The crate also contains abstractions for [asynchronous I/O](crate::io) and
//! [cross-task communication](crate::channel).
//!
//! Underlying all of this is the *task system*, which is a form of lightweight
//! threading. Large asynchronous computations are built up using futures,
//! streams and sinks, and then spawned as independent tasks that are run to
//! completion, but *do not block* the thread running them.
//!
//! The following example describes how the task system context is built and used
//! within macros and keywords such as async and await!.
//!
//! ```rust
//! # use futures::channel::mpsc;
//! # use futures::executor; ///standard executors to provide a context for futures and streams
//! # use futures::executor::ThreadPool;
//! # use futures::StreamExt;
//! #
//! fn main() {
//! # {
//! let pool = ThreadPool::new().expect("Failed to build pool");
//! let (tx, rx) = mpsc::unbounded::();
//!
//! // Create a future by an async block, where async is responsible for an
//! // implementation of Future. At this point no executor has been provided
//! // to this future, so it will not be running.
//! let fut_values = async {
//! // Create another async block, again where the Future implementation
//! // is generated by async. Since this is inside of a parent async block,
//! // it will be provided with the executor of the parent block when the parent
//! // block is executed.
//! //
//! // This executor chaining is done by Future::poll whose second argument
//! // is a std::task::Context. This represents our executor, and the Future
//! // implemented by this async block can be polled using the parent async
//! // block's executor.
//! let fut_tx_result = async move {
//! (0..100).for_each(|v| {
//! tx.unbounded_send(v).expect("Failed to send");
//! })
//! };
//!
//! // Use the provided thread pool to spawn the generated future
//! // responsible for transmission
//! pool.spawn_ok(fut_tx_result);
//!
//! let fut_values = rx
//! .map(|v| v * 2)
//! .collect();
//!
//! // Use the executor provided to this async block to wait for the
//! // future to complete.
//! fut_values.await
//! };
//!
//! // Actually execute the above future, which will invoke Future::poll and
//! // subsequently chain appropriate Future::poll and methods needing executors
//! // to drive all futures. Eventually fut_values will be driven to completion.
//! let values: Vec = executor::block_on(fut_values);
//!
//! println!("Values={:?}", values);
//! # }
//! # std::thread::sleep(std::time::Duration::from_millis(500)); // wait for background threads closed: https://github.com/rust-lang/miri/issues/1371
//! }
//! ```
//!
//! The majority of examples and code snippets in this crate assume that they are
//! inside an async block as written above.
#![cfg_attr(not(feature = "std"), no_std)]
#![warn(
missing_debug_implementations,
missing_docs,
rust_2018_idioms,
single_use_lifetimes,
unreachable_pub
)]
#![doc(test(
no_crate_inject,
attr(
deny(warnings, rust_2018_idioms, single_use_lifetimes),
allow(dead_code, unused_assignments, unused_variables)
)
))]
#![cfg_attr(docsrs, feature(doc_cfg))]
#[cfg(all(feature = "bilock", not(feature = "unstable")))]
compile_error!("The `bilock` feature requires the `unstable` feature as an explicit opt-in to unstable features");
#[doc(no_inline)]
pub use futures_core::future::{Future, TryFuture};
#[doc(no_inline)]
pub use futures_util::future::{FutureExt, TryFutureExt};
#[doc(no_inline)]
pub use futures_core::stream::{Stream, TryStream};
#[doc(no_inline)]
pub use futures_util::stream::{StreamExt, TryStreamExt};
#[doc(no_inline)]
pub use futures_sink::Sink;
#[doc(no_inline)]
pub use futures_util::sink::SinkExt;
#[cfg(feature = "std")]
#[doc(no_inline)]
pub use futures_io::{AsyncBufRead, AsyncRead, AsyncSeek, AsyncWrite};
#[cfg(feature = "std")]
#[doc(no_inline)]
pub use futures_util::{AsyncBufReadExt, AsyncReadExt, AsyncSeekExt, AsyncWriteExt};
// Macro reexports
pub use futures_core::ready; // Readiness propagation
pub use futures_util::pin_mut;
#[cfg(feature = "std")]
#[cfg(feature = "async-await")]
pub use futures_util::select;
#[cfg(feature = "async-await")]
pub use futures_util::{join, pending, poll, select_biased, try_join}; // Async-await
// Module reexports
#[doc(inline)]
pub use futures_util::{future, never, sink, stream, task};
#[cfg(feature = "std")]
#[cfg(feature = "async-await")]
pub use futures_util::stream_select;
#[cfg(feature = "alloc")]
#[doc(inline)]
pub use futures_channel as channel;
#[cfg(feature = "alloc")]
#[doc(inline)]
pub use futures_util::lock;
#[cfg(feature = "std")]
#[doc(inline)]
pub use futures_util::io;
#[cfg(feature = "executor")]
#[cfg_attr(docsrs, doc(cfg(feature = "executor")))]
pub mod executor {
//! Built-in executors and related tools.
//!
//! All asynchronous computation occurs within an executor, which is
//! capable of spawning futures as tasks. This module provides several
//! built-in executors, as well as tools for building your own.
//!
//!
//! This module is only available when the `executor` feature of this
//! library is activated.
//!
//! # Using a thread pool (M:N task scheduling)
//!
//! Most of the time tasks should be executed on a [thread pool](ThreadPool).
//! A small set of worker threads can handle a very large set of spawned tasks
//! (which are much lighter weight than threads). Tasks spawned onto the pool
//! with the [`spawn_ok`](ThreadPool::spawn_ok) function will run ambiently on
//! the created threads.
//!
//! # Spawning additional tasks
//!
//! Tasks can be spawned onto a spawner by calling its [`spawn_obj`] method
//! directly. In the case of `!Send` futures, [`spawn_local_obj`] can be used
//! instead.
//!
//! # Single-threaded execution
//!
//! In addition to thread pools, it's possible to run a task (and the tasks
//! it spawns) entirely within a single thread via the [`LocalPool`] executor.
//! Aside from cutting down on synchronization costs, this executor also makes
//! it possible to spawn non-`Send` tasks, via [`spawn_local_obj`]. The
//! [`LocalPool`] is best suited for running I/O-bound tasks that do relatively
//! little work between I/O operations.
//!
//! There is also a convenience function [`block_on`] for simply running a
//! future to completion on the current thread.
//!
//! [`spawn_obj`]: https://docs.rs/futures/0.3/futures/task/trait.Spawn.html#tymethod.spawn_obj
//! [`spawn_local_obj`]: https://docs.rs/futures/0.3/futures/task/trait.LocalSpawn.html#tymethod.spawn_local_obj
pub use futures_executor::{
block_on, block_on_stream, enter, BlockingStream, Enter, EnterError, LocalPool,
LocalSpawner,
};
#[cfg(feature = "thread-pool")]
#[cfg_attr(docsrs, doc(cfg(feature = "thread-pool")))]
pub use futures_executor::{ThreadPool, ThreadPoolBuilder};
}
#[cfg(feature = "compat")]
#[cfg_attr(docsrs, doc(cfg(feature = "compat")))]
pub mod compat {
//! Interop between `futures` 0.1 and 0.3.
//!
//! This module is only available when the `compat` feature of this
//! library is activated.
pub use futures_util::compat::{
Compat, Compat01As03, Compat01As03Sink, CompatSink, Executor01As03, Executor01CompatExt,
Executor01Future, Future01CompatExt, Sink01CompatExt, Stream01CompatExt,
};
#[cfg(feature = "io-compat")]
#[cfg_attr(docsrs, doc(cfg(feature = "io-compat")))]
pub use futures_util::compat::{AsyncRead01CompatExt, AsyncWrite01CompatExt};
}
pub mod prelude {
//! A "prelude" for crates using the `futures` crate.
//!
//! This prelude is similar to the standard library's prelude in that you'll
//! almost always want to import its entire contents, but unlike the
//! standard library's prelude you'll have to do so manually:
//!
//! ```
//! # #[allow(unused_imports)]
//! use futures::prelude::*;
//! ```
//!
//! The prelude may grow over time as additional items see ubiquitous use.
pub use crate::future::{self, Future, TryFuture};
pub use crate::sink::{self, Sink};
pub use crate::stream::{self, Stream, TryStream};
#[doc(no_inline)]
#[allow(unreachable_pub)]
pub use crate::future::{FutureExt as _, TryFutureExt as _};
#[doc(no_inline)]
pub use crate::sink::SinkExt as _;
#[doc(no_inline)]
#[allow(unreachable_pub)]
pub use crate::stream::{StreamExt as _, TryStreamExt as _};
#[cfg(feature = "std")]
pub use crate::io::{AsyncBufRead, AsyncRead, AsyncSeek, AsyncWrite};
#[cfg(feature = "std")]
#[doc(no_inline)]
#[allow(unreachable_pub)]
pub use crate::io::{
AsyncBufReadExt as _, AsyncReadExt as _, AsyncSeekExt as _, AsyncWriteExt as _,
};
}
futures-0.3.30/tests/_require_features.rs 0000644 0000000 0000000 00000000542 10461020230 0016626 0 ustar 0000000 0000000 #[cfg(not(all(
feature = "std",
feature = "alloc",
feature = "async-await",
feature = "compat",
feature = "io-compat",
feature = "executor",
feature = "thread-pool",
)))]
compile_error!(
"`futures` tests must have all stable features activated: \
use `--all-features` or `--features default,thread-pool,io-compat`"
);
futures-0.3.30/tests/async_await_macros.rs 0000644 0000000 0000000 00000024720 10461020230 0016767 0 ustar 0000000 0000000 use futures::channel::{mpsc, oneshot};
use futures::executor::block_on;
use futures::future::{self, poll_fn, FutureExt};
use futures::sink::SinkExt;
use futures::stream::StreamExt;
use futures::task::{Context, Poll};
use futures::{
join, pending, pin_mut, poll, select, select_biased, stream, stream_select, try_join,
};
use std::mem;
#[test]
fn poll_and_pending() {
let pending_once = async { pending!() };
block_on(async {
pin_mut!(pending_once);
assert_eq!(Poll::Pending, poll!(&mut pending_once));
assert_eq!(Poll::Ready(()), poll!(&mut pending_once));
});
}
#[test]
fn join() {
let (tx1, rx1) = oneshot::channel::();
let (tx2, rx2) = oneshot::channel::();
let fut = async {
let res = join!(rx1, rx2);
assert_eq!((Ok(1), Ok(2)), res);
};
block_on(async {
pin_mut!(fut);
assert_eq!(Poll::Pending, poll!(&mut fut));
tx1.send(1).unwrap();
assert_eq!(Poll::Pending, poll!(&mut fut));
tx2.send(2).unwrap();
assert_eq!(Poll::Ready(()), poll!(&mut fut));
});
}
#[test]
fn select() {
let (tx1, rx1) = oneshot::channel::();
let (_tx2, rx2) = oneshot::channel::();
tx1.send(1).unwrap();
let mut ran = false;
block_on(async {
select! {
res = rx1.fuse() => {
assert_eq!(Ok(1), res);
ran = true;
},
_ = rx2.fuse() => unreachable!(),
}
});
assert!(ran);
}
#[test]
fn select_biased() {
let (tx1, rx1) = oneshot::channel::();
let (_tx2, rx2) = oneshot::channel::();
tx1.send(1).unwrap();
let mut ran = false;
block_on(async {
select_biased! {
res = rx1.fuse() => {
assert_eq!(Ok(1), res);
ran = true;
},
_ = rx2.fuse() => unreachable!(),
}
});
assert!(ran);
}
#[test]
fn select_streams() {
let (mut tx1, rx1) = mpsc::channel::(1);
let (mut tx2, rx2) = mpsc::channel::(1);
let mut rx1 = rx1.fuse();
let mut rx2 = rx2.fuse();
let mut ran = false;
let mut total = 0;
block_on(async {
let mut tx1_opt;
let mut tx2_opt;
select! {
_ = rx1.next() => panic!(),
_ = rx2.next() => panic!(),
default => {
tx1.send(2).await.unwrap();
tx2.send(3).await.unwrap();
tx1_opt = Some(tx1);
tx2_opt = Some(tx2);
}
complete => panic!(),
}
loop {
select! {
// runs first and again after default
x = rx1.next() => if let Some(x) = x { total += x; },
// runs second and again after default
x = rx2.next() => if let Some(x) = x { total += x; },
// runs third
default => {
assert_eq!(total, 5);
ran = true;
drop(tx1_opt.take().unwrap());
drop(tx2_opt.take().unwrap());
},
// runs last
complete => break,
};
}
});
assert!(ran);
}
#[test]
fn select_can_move_uncompleted_futures() {
let (tx1, rx1) = oneshot::channel::();
let (tx2, rx2) = oneshot::channel::();
tx1.send(1).unwrap();
tx2.send(2).unwrap();
let mut ran = false;
let mut rx1 = rx1.fuse();
let mut rx2 = rx2.fuse();
block_on(async {
select! {
res = rx1 => {
assert_eq!(Ok(1), res);
assert_eq!(Ok(2), rx2.await);
ran = true;
},
res = rx2 => {
assert_eq!(Ok(2), res);
assert_eq!(Ok(1), rx1.await);
ran = true;
},
}
});
assert!(ran);
}
#[test]
fn select_nested() {
let mut outer_fut = future::ready(1);
let mut inner_fut = future::ready(2);
let res = block_on(async {
select! {
x = outer_fut => {
select! {
y = inner_fut => x + y,
}
}
}
});
assert_eq!(res, 3);
}
#[cfg_attr(not(target_pointer_width = "64"), ignore)]
#[test]
fn select_size() {
let fut = async {
let mut ready = future::ready(0i32);
select! {
_ = ready => {},
}
};
assert_eq!(mem::size_of_val(&fut), 24);
let fut = async {
let mut ready1 = future::ready(0i32);
let mut ready2 = future::ready(0i32);
select! {
_ = ready1 => {},
_ = ready2 => {},
}
};
assert_eq!(mem::size_of_val(&fut), 40);
}
#[test]
fn select_on_non_unpin_expressions() {
// The returned Future is !Unpin
let make_non_unpin_fut = || async { 5 };
let res = block_on(async {
let select_res;
select! {
value_1 = make_non_unpin_fut().fuse() => select_res = value_1,
value_2 = make_non_unpin_fut().fuse() => select_res = value_2,
};
select_res
});
assert_eq!(res, 5);
}
#[test]
fn select_on_non_unpin_expressions_with_default() {
// The returned Future is !Unpin
let make_non_unpin_fut = || async { 5 };
let res = block_on(async {
let select_res;
select! {
value_1 = make_non_unpin_fut().fuse() => select_res = value_1,
value_2 = make_non_unpin_fut().fuse() => select_res = value_2,
default => select_res = 7,
};
select_res
});
assert_eq!(res, 5);
}
#[cfg_attr(not(target_pointer_width = "64"), ignore)]
#[test]
fn select_on_non_unpin_size() {
// The returned Future is !Unpin
let make_non_unpin_fut = || async { 5 };
let fut = async {
let select_res;
select! {
value_1 = make_non_unpin_fut().fuse() => select_res = value_1,
value_2 = make_non_unpin_fut().fuse() => select_res = value_2,
};
select_res
};
assert_eq!(32, mem::size_of_val(&fut));
}
#[test]
fn select_can_be_used_as_expression() {
block_on(async {
let res = select! {
x = future::ready(7) => x,
y = future::ready(3) => y + 1,
};
assert!(res == 7 || res == 4);
});
}
#[test]
fn select_with_default_can_be_used_as_expression() {
fn poll_always_pending(_cx: &mut Context<'_>) -> Poll {
Poll::Pending
}
block_on(async {
let res = select! {
x = poll_fn(poll_always_pending::).fuse() => x,
y = poll_fn(poll_always_pending::).fuse() => y + 1,
default => 99,
};
assert_eq!(res, 99);
});
}
#[test]
fn select_with_complete_can_be_used_as_expression() {
block_on(async {
let res = select! {
x = future::pending::() => x,
y = future::pending::() => y + 1,
default => 99,
complete => 237,
};
assert_eq!(res, 237);
});
}
#[test]
#[allow(unused_assignments)]
fn select_on_mutable_borrowing_future_with_same_borrow_in_block() {
async fn require_mutable(_: &mut i32) {}
async fn async_noop() {}
block_on(async {
let mut value = 234;
select! {
_ = require_mutable(&mut value).fuse() => { },
_ = async_noop().fuse() => {
value += 5;
},
}
});
}
#[test]
#[allow(unused_assignments)]
fn select_on_mutable_borrowing_future_with_same_borrow_in_block_and_default() {
async fn require_mutable(_: &mut i32) {}
async fn async_noop() {}
block_on(async {
let mut value = 234;
select! {
_ = require_mutable(&mut value).fuse() => { },
_ = async_noop().fuse() => {
value += 5;
},
default => {
value += 27;
},
}
});
}
#[test]
#[allow(unused_assignments)]
fn stream_select() {
// stream_select! macro
block_on(async {
let endless_ints = |i| stream::iter(vec![i].into_iter().cycle());
let mut endless_ones = stream_select!(endless_ints(1i32), stream::pending());
assert_eq!(endless_ones.next().await, Some(1));
assert_eq!(endless_ones.next().await, Some(1));
let mut finite_list =
stream_select!(stream::iter(vec![1].into_iter()), stream::iter(vec![1].into_iter()));
assert_eq!(finite_list.next().await, Some(1));
assert_eq!(finite_list.next().await, Some(1));
assert_eq!(finite_list.next().await, None);
let endless_mixed = stream_select!(endless_ints(1i32), endless_ints(2), endless_ints(3));
// Take 1000, and assert a somewhat even distribution of values.
// The fairness is randomized, but over 1000 samples we should be pretty close to even.
// This test may be a bit flaky. Feel free to adjust the margins as you see fit.
let mut count = 0;
let results = endless_mixed
.take_while(move |_| {
count += 1;
let ret = count < 1000;
async move { ret }
})
.collect::>()
.await;
assert!(results.iter().filter(|x| **x == 1).count() >= 299);
assert!(results.iter().filter(|x| **x == 2).count() >= 299);
assert!(results.iter().filter(|x| **x == 3).count() >= 299);
});
}
#[cfg_attr(not(target_pointer_width = "64"), ignore)]
#[test]
fn join_size() {
let fut = async {
let ready = future::ready(0i32);
join!(ready)
};
assert_eq!(mem::size_of_val(&fut), 24);
let fut = async {
let ready1 = future::ready(0i32);
let ready2 = future::ready(0i32);
join!(ready1, ready2)
};
assert_eq!(mem::size_of_val(&fut), 40);
}
#[cfg_attr(not(target_pointer_width = "64"), ignore)]
#[test]
fn try_join_size() {
let fut = async {
let ready = future::ready(Ok::(0));
try_join!(ready)
};
assert_eq!(mem::size_of_val(&fut), 24);
let fut = async {
let ready1 = future::ready(Ok::(0));
let ready2 = future::ready(Ok::(0));
try_join!(ready1, ready2)
};
assert_eq!(mem::size_of_val(&fut), 48);
}
#[allow(clippy::let_underscore_future)]
#[test]
fn join_doesnt_require_unpin() {
let _ = async { join!(async {}, async {}) };
}
#[allow(clippy::let_underscore_future)]
#[test]
fn try_join_doesnt_require_unpin() {
let _ = async { try_join!(async { Ok::<(), ()>(()) }, async { Ok::<(), ()>(()) },) };
}
futures-0.3.30/tests/auto_traits.rs 0000644 0000000 0000000 00000256050 10461020230 0015462 0 ustar 0000000 0000000 #![cfg(feature = "compat")]
//! Assert Send/Sync/Unpin for all public types.
use futures::{
future::Future,
sink::Sink,
stream::Stream,
task::{Context, Poll},
};
use static_assertions::{assert_impl_all as assert_impl, assert_not_impl_all as assert_not_impl};
use std::marker::PhantomPinned;
use std::{marker::PhantomData, pin::Pin};
pub type LocalFuture = Pin>>;
pub type LocalTryFuture = LocalFuture>;
pub type SendFuture = Pin + Send>>;
pub type SendTryFuture = SendFuture>;
pub type SyncFuture = Pin + Sync>>;
pub type SyncTryFuture = SyncFuture>;
pub type SendSyncFuture = Pin + Send + Sync>>;
pub type SendSyncTryFuture = SendSyncFuture>;
pub type UnpinFuture = LocalFuture;
pub type UnpinTryFuture = UnpinFuture>;
pub struct PinnedFuture(PhantomPinned, PhantomData);
impl Future for PinnedFuture {
type Output = T;
fn poll(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll {
unimplemented!()
}
}
pub type PinnedTryFuture = PinnedFuture>;
pub type LocalStream = Pin>>;
pub type LocalTryStream = LocalStream>;
pub type SendStream = Pin + Send>>;
pub type SendTryStream = SendStream>;
pub type SyncStream = Pin + Sync>>;
pub type SyncTryStream = SyncStream>;
pub type SendSyncStream = Pin + Send + Sync>>;
pub type SendSyncTryStream = SendSyncStream>;
pub type UnpinStream = LocalStream;
pub type UnpinTryStream = UnpinStream>;
pub struct PinnedStream(PhantomPinned, PhantomData);
impl Stream for PinnedStream {
type Item = T;
fn poll_next(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll