Compare commits

...
483 Commits
Author SHA1 Message Date
Alice Ryhl 572a897d43 chore: prepare tokio v1.2.0 (#3506) 2021-02-05 23:27:42 +01:00
Alice Ryhl d41882e2a1 chore: prepare tokio-macros 1.1.0 (#3505) 2021-02-05 22:21:29 +01:00
Alice Ryhl 23fdc2b3c4 chore: prepare tokio-stream 0.1.3 (#3507) 2021-02-05 22:18:56 +01:00
Alice Ryhl 0a04954d5c stream: update features and doc for broadcast/watch stream (#3504) 2021-02-05 20:39:27 +01:00
Steven Fackler fcb6d041b9 time: make test-util paused time fully deterministic (#3492)
The time driver stores an Instant internally used as a "base" for future
time calculations. Since this is generated as the Runtime is being
constructed, it previously always happened before the user had a chance
to pause time. The fractional-millisecond variations in the timing
around the runtime construction and time pause cause tests running
entirely in paused time to be very slightly deterministic, with the time
driver advancing time by 1 millisecond more or less depending on how the
sub-millisecond components of the `Instant`s involved compared.

To avoid this, there is now a new option on `runtime::Builder` which
will create a `Runtime` with time "instantly" paused. This, along with a
small change to have the time driver use the provided clock as the
source for its start time allow totally deterministic tests with paused
time.
2021-02-05 20:12:25 +01:00
Fuyang Liu 1c1e0e3fc9 tokio-stream: add wrapper for broadcast and watch (#3384) 2021-02-05 19:56:24 +01:00
Fuyang Liu 77ca8a934c signal: make Signal::poll_recv method public (#3383)
Signed-off-by: Fuyang Liu <[email protected]>
2021-02-05 19:43:58 +01:00
surechen 3e5a0a7df6 runtime: fix a spelling mistake (#3503) 2021-02-04 12:30:31 +01:00
Artem VorotnikovandTaiki Endo cc97fb8a5f Suppress deprecated warnings for spin_loop_hint (#3497)
* Suppress deprecated warnings for spin_loop_hint

* Update tokio/src/loom/std/mod.rs

Co-authored-by: Taiki Endo <[email protected]>

* Update tokio/src/sync/task/atomic_waker.rs

Co-authored-by: Taiki Endo <[email protected]>

* fmt

Co-authored-by: Taiki Endo <[email protected]>
2021-02-01 15:55:21 +03:00
Alice Ryhl 60d88840f4 chore: prepare tokio-util v0.6.3 (#3488) 2021-01-31 12:39:22 +01:00
Alice Ryhl ee1f0c473f util: remove tokio-stream dependency from tokio-util (#3487) 2021-01-31 11:08:40 +01:00
Rob Ede 06d6adf4b7 util: use ReusableBoxFuture for PollSemaphore (#3463) 2021-01-30 10:57:04 +01:00
Alice Ryhl 891aba5f71 util: add ReusableBoxFuture utility (#3464) 2021-01-30 00:03:01 +01:00
Carl Lerche 10c3b2f4a3 Merge branch 'tokio-1.1.x' 2021-01-29 14:13:24 -08:00
Markus Westerlind 6f988728bb runtime: minimize the amount of duplicated code (#3416) 2021-01-29 21:45:29 +01:00
Carl Lerche 085f819f28 Merge branch 'tokio-1.0.x' into 'tokio-1.1.x' 2021-01-28 20:23:50 -08:00
Carl Lerche 5d0a81fb91 io: fix memory leak during shutdown (#3477)
In some cases, a cycle is created between I/O driver wakers and the I/O
driver resource slab. This patch clears stored wakers when an I/O
resource is dropped, breaking the cycle.

Fixes #3228
2021-01-28 17:49:10 -08:00
Ivan Petkov 1f9765fb5f process: add missing drop child stdin to wait() (#3421) 2021-01-28 23:08:44 +01:00
Jamie 225e8ea05f sync: update RwLock doc to mention possibility of deadlock (#3389) 2021-01-28 16:38:49 +01:00
Alice Ryhl cd7526873c net: improve discoverability of TcpSocket (#3471) 2021-01-28 14:09:14 +01:00
vitalyd 4968f59af6 sync: update Sender::try_reserve doc (#3476) 2021-01-28 10:31:23 +01:00
Ivan Petkov 34f1d3d040 process: allow for ergonomically piping stdio of one child into another (#3466)
* Add `TryInto<Stdio>` impls for `ChildStd{in,out,err}` for ergonomic
  conversions into `std::process::Stdio` so callers can perform the
  conversion without needing to manipulate raw fds/handles directly
2021-01-27 01:12:54 +00:00
Ontonator f13a9dd87a tokio: update dates in CHANGELOG.md to 2021 (#3469) 2021-01-25 12:04:58 +01:00
Alice Ryhl 35b1a4d0b3 chore: prepare Tokio 1.1.0 (#3462) 2021-01-22 23:05:37 +01:00
Alice Ryhl 6da5087b06 sync: improve bounded mpsc documentation (#3458) 2021-01-22 19:28:37 +01:00
Alice Ryhl c6f08120d0 task: add LocalSet example (#3438) 2021-01-21 16:36:26 +01:00
Alice Ryhl 29bd5fad5c sync: add link to PollSemaphore (#3456) 2021-01-21 15:20:55 +01:00
Alice Ryhl f2a048d990 time: document that Sleep is not Unpin (#3457) 2021-01-21 15:19:17 +01:00
Alice Ryhl 198363f4f1 chore: prepare tokio-util 0.6.2 (#3453) 2021-01-21 11:46:50 +01:00
vitalyd 5b7c7d565a io: use a sealed trait to constrain VecWithInitialized (#3450) 2021-01-21 11:32:42 +01:00
Blas Rodriguez Irizar 117fc2ef3e tests: fix ping pong saturation (#3390) 2021-01-21 11:02:40 +01:00
William Bain c4f66ed121 util: fix panics on updating DelayQueue entries (#3270) 2021-01-21 10:56:44 +01:00
Oğuz Bilgener 7d5b12c509 sync: fix panic in broadcast::Receiver drop (#3434) 2021-01-20 23:12:51 +01:00
Alice Ryhl cc0911aa64 net: update datagram docs on splitting (#3448) 2021-01-20 16:28:57 +01:00
Henry Gomersall 6f8a4d7a0b docs: trivial typo fix (#3449) 2021-01-20 16:28:35 +01:00
Arve Knudsen fdde5583f8 runtime: consolidate errors for context missing (#3441) 2021-01-20 14:29:13 +01:00
Rain 36cf95ab62 io: add ReadBuf::inner_mut (#3443) 2021-01-20 13:56:14 +01:00
Alice Ryhl 27b2d681e6 util: add pollable Semaphore (#3444) 2021-01-20 09:53:31 +01:00
Alice Ryhl c1cf6b7504 io: keep track of initialized bytes in read_to_end (#3426) 2021-01-20 09:49:24 +01:00
Henry Gomersall 5402c948ee io: clarify AsyncFd docs about changes of the inner fd (#3430) 2021-01-17 21:39:58 +01:00
Carl Lerche 2af9b755c5 Merge branch 'tokio-1.0.x' 2021-01-16 11:36:21 -08:00
Jacob O'Toole 7ac44a2d28 process: add documentation to process::Child fields (#3437) 2021-01-16 19:42:51 +01:00
Carl Lerche 3dc5f6c0ab chore: release tokio v1.0.2 (#3429) 2021-01-15 15:05:38 -08:00
Alice Ryhl 0a7117fd9a io: fix unsoundness in read_to_end (#3428) 2021-01-15 15:05:38 -08:00
Carl Lerche 5d35c907f6 chore: release tokio v1.0.2 (#3429) 2021-01-14 16:37:40 -08:00
Alice Ryhl ad8fb41103 io: fix unsoundness in read_to_end (#3428) 2021-01-14 15:09:07 -08:00
Nylonicious ecc32d1dca sync: add RwLock try_read and try_write methods (#3400)
Closes #2284
2021-01-14 15:05:07 -08:00
Markus Westerlind 204603b7de rt: reduce duplicated code in task harness (#3314)
Task spawning is a common operation that results in a lot of instantiations
of the task code. Reducing the amount of generated code should lead to
faster compile times overall.

This patch extracts code that does not depend on a type parameter into
functions with fewer or no type parameters at all. Reducing the amount of
duplicated code.
2021-01-14 10:07:56 -08:00
Taiki Endo 30b4a7486a chore: use CARGO_BIN_EXE instead of inspecting env::current_exe() (#3427) 2021-01-14 09:59:37 -08:00
Taiki Endo 0595902ba4 Update issue template (#3425)
`cargo tree` subcommand is available by default since Rust 1.44.
2021-01-14 23:09:05 +09:00
Lucio FrancoandAlice Ryhl 672be92a03 mpsc: Add Sender::try_reserve function (#3418)
* mpsc: Add `Sender::try_reserve` function

* Update tokio/src/sync/mpsc/bounded.rs

Co-authored-by: Alice Ryhl <[email protected]>

* Fix doc links

Co-authored-by: Alice Ryhl <[email protected]>
2021-01-13 14:24:23 -05:00
Alice Ryhl 766a89bf94 chore: prepare tokio-stream 0.1.2 (#3414) 2021-01-12 21:38:51 +01:00
David Kellum 8b9bb41809 docs: add tokio 1.0 policies to contributing guide (#3386) 2021-01-12 21:15:44 +01:00
Taiki Endo d37486dd06 util: remove path deps (#3413)
* util: remove path deps

* ci: run clippy with --all-features

* ci: run tests with --all-features on FreeBSD CI
2021-01-13 00:19:57 +09:00
Daiki Mizukami ed667c669a chore: prepare tokio-util v0.6.1 release (#3402) 2021-01-12 12:46:07 +01:00
Milan da09213c9f doc: typo fixes (#3401) 2021-01-11 21:39:50 -08:00
Taiki Endo 40d959263b macros: fix unused_braces in generated code (#3404) 2021-01-11 19:20:40 +09:00
Shantanu Sharma 0b8bdf9d32 runtime: fix typo (#3385) 2021-01-10 20:59:14 +09:00
cssivision 51a7082d13 docs: test-util feature is not enabled with full (#3397) 2021-01-09 14:01:10 +01:00
Cameron 22c27b9282 task: wake LocalSet on spawn_local (#3369) 2021-01-09 11:46:51 +01:00
David Raifaizen 2fe2f0401b util: expose FramedWrite/Framed::write_buffer/write_buffer_mut 2021-01-08 23:20:07 +01:00
Rust大闸蟹 e42317b072 chore: remove macro_rules semicolon (#3381)
fix build warning
2021-01-06 15:46:37 +09:00
Alice Ryhl 3549092a0c docs: fix tokio-stream features not being displayed (#3378) 2021-01-05 11:43:09 +01:00
Alice Ryhl 3b840fb305 stream: remove path deps (#3376) 2021-01-04 21:04:22 +01:00
Alice Ryhl 4beb1862ac chore: prepare tokio-stream 0.1.1 (#3374) 2021-01-04 19:46:01 +01:00
Alice Ryhl 7f17822ed9 stream: add Stream wrappers in tokio-stream (#3343) 2021-01-04 19:03:18 +01:00
cssivision 3b6bee822d net: add try_read_buf and try_recv_buf (#3351) 2021-01-02 10:37:34 +01:00
Rob Ede 56272b2ec7 stream: move async-stream to dev-deps (#3366) 2021-01-02 13:43:41 +09:00
John-John Tedro 53707f5d9d sync: remove underused internal Borrow wrapper (#3363) 2021-01-01 13:04:38 -08:00
Daiki Mizukami 36918e05e5 util: add more get_{ref,mut,pin_mut} methods (#3364)
This commit adds:

- Framed::get_pin_mut
- FramedRead::get_pin_mut
- FramedWrite::get_pin_mut
- StreamReader::get_ref
- StreamReader::get_mut
- StreamReader::get_pin_mut
- StreamReader::into_inner
2021-01-01 13:05:15 +01:00
Arniu Tseng cbd4f4472e docs: update CHANGELOG.md (#3336) 2020-12-27 16:36:36 +01:00
Danilo MartinsandDanilo 2d9bea8d63 runtime: fix typo (#3354)
Co-authored-by: Danilo <[email protected]>
2020-12-27 16:17:00 +01:00
zhongjnandAlice Ryhl 0048d43713 macros: improve select! error message (#3352)
Co-authored-by: Alice Ryhl <[email protected]>
2020-12-27 23:50:32 +09:00
Taiki Endo 770044caa7 chore: replace deprecated compare_and_swap with compare_exchange (#3331) 2020-12-27 10:44:21 +01:00
AJ Frantz c4929264bc examples: adjust buffering in examples (#3328) 2020-12-27 10:43:02 +01:00
Alice Ryhl 4d7b73f5b3 chore: create stream_ext module (#3342) 2020-12-26 17:05:51 +01:00
Alice Ryhl 2330edc875 chore: prepare tokio 1.0.1 release (#3347) 2020-12-25 22:20:05 +01:00
Alice Ryhl fe2664a4e1 sync: remove RwLockWriteGuard::map and RwLockWriteGuard::try_map (#3345) 2020-12-25 21:36:48 +01:00
Laurențiu Nicola 1eefbc250a docs: remove stream feature from docs (#3335) 2020-12-24 23:17:18 +09:00
Carl Lerche a66017f049 chore: prepare Tokio 1.0 release (#3319) 2020-12-23 09:26:14 -08:00
Paolo Barbolini aa6597ba66 compat: update traits naming to match tokio 1.0 (#3324) 2020-12-23 09:15:56 -08:00
Taiki Endo ce0e9c67cf chore: Revert "use #[non_exhaustive] instead of private unit field" (#3323)
This reverts commit 575938d457.
2020-12-23 08:27:58 -08:00
Taiki Endo 575938d457 chore: use #[non_exhaustive] instead of private unit field (#3320) 2020-12-23 22:48:33 +09:00
Carl Lerche 0deaeb8494 chore: remove unused slab dependency (#3318) 2020-12-22 21:56:22 -08:00
Luke Steensen a8dda19da4 chore: update to released bytes 1.0 (#3317) 2020-12-22 17:09:26 -08:00
Sean McArthur be9fdb697d time: make Interval::poll_tick() public (#3316) 2020-12-22 12:31:14 -08:00
Carl Lerche 2ee9520d10 fs: misc small API tweaks (#3315) 2020-12-22 11:13:41 -08:00
Carlos B 7d28e4cdbb examples: add futures executor threadpool (#3198) 2020-12-22 20:08:43 +01:00
Alice Ryhl 0b83b3b8cc fs,sync: expose poll_ fns on misc types (#3308)
Includes methods on:

* fs::DirEntry
* io::Lines
* io::Split
* sync::mpsc::Receiver
* sync::misc::UnboundedReceiver
2020-12-22 09:28:14 -08:00
Alice Ryhl f95ad18980 net: clarify when wakeups are sent (#3310) 2020-12-22 07:38:14 -08:00
Taiki Endo eee3ca65d6 deps: update rand to 0.8, loom to 0.4 (#3307) 2020-12-22 10:28:35 +01:00
Alice Ryhl 564c943309 io: rename AsyncFd::with_io() and rm with_poll() (#3306) 2020-12-21 15:42:38 -08:00
BhargavandAlice Ryhl c7671a0384 io: add _mut variants of methods on AsyncFd (#3304)
Co-authored-by: Alice Ryhl <[email protected]>
2020-12-21 22:51:28 +01:00
Carl Lerche 2893359988 chore: update to bytes 1.0 git branch (#3301)
Updates the code base to track the `bytes` git branch. This is in
preparation for the 1.0 release.

Closes #3058
2020-12-19 15:57:16 -08:00
Carl Lerche 5e5f513542 chore: remove some left over stream feature code (#3300)
Removes the `stream` feature flag from `Cargo.toml` and removes the
`futures-core` dependency. Once `Stream` lands in `std`, a feature flag
is most likely not needed.
2020-12-19 14:15:00 -08:00
Arve Knudsen 1b70507894 net: remove {Tcp,Unix}Stream::shutdown() (#3298)
`shutdown()` on `AsyncWrite` performs a TCP shutdown. This avoids method
conflicts.

Closes #3294
2020-12-19 12:17:52 -08:00
Alice Ryhl 78f2340d25 tokio: remove prelude (#3299)
Closes: #3257
2020-12-19 11:42:24 -08:00
Florian Hübsch e41e6cddbb docs: tokio::main macro is also supported on rt (#3243)
Fixes: #3144
Refs: #2225
2020-12-19 19:12:08 +01:00
Lucio Franco b99b00eb30 rt: change max_threads to max_blocking_threads (#3287)
Fixes #2802
2020-12-19 08:04:04 -08:00
Alice Ryhl d948ccedfc chore: fix stress test (#3297) 2020-12-19 12:11:10 +01:00
Alice RyhlandLucio Franco 3ecaf9fd9a codec: write documentation for codec (#3283)
Co-authored-by: Lucio Franco <[email protected]>
2020-12-18 21:32:27 +01:00
Carl Lerche abd4c00255 time: enforce current_thread rt for time::pause (#3289)
Pausing time is a capability added to assist with testing Tokio code
dependent on time. Currently, the capability implicitly requires the
current_thread runtime.

This change enforces the requirement by panicking if called from a
multi-threaded runtime.
2020-12-17 15:37:08 -08:00
Lucio FrancoandAlice Ryhl c5861ef62f docs: Add more comprehensive stream docs (#3286)
* docs: Add more comprehensive stream docs

* Apply suggestions from code review

Co-authored-by: Alice Ryhl <[email protected]>

* Fix doc tests

Co-authored-by: Alice Ryhl <[email protected]>
2020-12-17 11:46:09 -05:00
Lucio Franco 59e4b35f49 stream: Fix a few doc issues (#3285) 2020-12-17 10:35:49 -05:00
Carl Lerche d74d17307d time: remove Box from Sleep (#3278)
Removes the box from `Sleep`, taking advantage of intrusive wakers. The
`Sleep` future is now `!Unpin`.

Closes #3267
2020-12-16 21:51:34 -08:00
Lucio Franco 8efa62013b Move stream items into tokio-stream (#3277)
This change removes all references to `Stream` from
within the `tokio` crate and moves them into a new
`tokio-stream` crate. Most types have had their
`impl Stream` removed as well in-favor of their
inherent methods.

Closes #2870
2020-12-15 20:24:38 -08:00
Zahari Dichev fcce78b33a sync: add Semaphore::close (#3065)
## Motivation
The need to expose `Semaphore::close` as explained in #3061. 

## Solution
Expose `Semaphore::close`

Signed-off-by: Zahari Dichev <[email protected]>
2020-12-15 10:22:45 -08:00
Carl Lerche 79d25b0a48 tracing: switch to unstable for 1.0. (#3266)
Enabling `tracing` integration now requires compiling with `--cfg
tokio_unstable`. Once `tracing-core` guarantees the same level of
stability as Tokio 1.0, unstable can be removed.

Closes #3258
2020-12-14 17:22:31 -08:00
Carl Lerche 3f29212cb7 fs: use cfgs on fns instead of OS ext traits (#3264)
Instead of using OS specific extension traits, OS specific methods are
moved onto the structs themselves and guarded with `cfg`. The API
documentation should highlight the function is platform specific.

Closes #2925
2020-12-14 09:29:10 -08:00
Joshua Nelson 48961fac89 Document SinkExt and other futures traits on docs.rs (#3271)
These are extremely hard to find if you don't already know they exist.
2020-12-14 10:28:36 -05:00
Carl Lerche a7833e3007 sync: remove try_recv() from mpsc types (#3263)
The mpsc `try_recv()` functions have an issue where a sent message
happens-before a call to `try_recv()` but `try_recv()` returns `None`.
Fixing this is non-trivial, so the function is removed for 1.0. When the
bug is fixed, the function can be added back.

Closes #2020
2020-12-13 21:39:51 -08:00
Jacob O'Toole 1f862d2e95 sync: add watch::Sender::borrow() (#3269) 2020-12-13 20:46:11 -08:00
Sylvain Kerkour 9149d7bfae docs: mention blocking thread timeout in src/lib.rs (#3253) 2020-12-13 16:24:16 +01:00
cssivision 4c55419453 net: add UnixStream readiness and non-blocking ops (#3246) 2020-12-13 16:21:11 +01:00
Aldas f26f444f42 doc: added tracing to the feature flags section (#3254) 2020-12-13 15:26:56 +01:00
cssivision be2cb7a5ce net: check for false-positives in TcpStream::ready doc test (#3255) 2020-12-13 15:24:59 +01:00
Sunjay Varma df20c162ae sync: add blocking_recv method to UnboundedReceiver, similar to Receiver::blocking_recv (#3262) 2020-12-12 08:47:35 -08:00
Alice Ryhl c1ec469ad2 util: add constructors to TokioContext (#3221) 2020-12-11 20:41:22 -08:00
Lucio Franco b01b2dacf2 net: update TcpStream::poll_peek to use ReadBuf (#3259)
Closes #2987
2020-12-11 20:40:24 -08:00
Evan Cameron 68717c7efa net: remove empty udp module (#3260) 2020-12-11 14:45:57 -05:00
Alice Ryhl 69e62ef89e sync: make TryAcquireError public (#3250)
The [`Semaphore::try_acquire`][1] method currently returns a private error type.

[1]: https://docs.rs/tokio/0.3/tokio/sync/struct.Semaphore.html#method.try_acquire
2020-12-10 19:56:05 -08:00
Nylonicious 16c2e0983c net: Pass SocketAddr by value (#3125) 2020-12-10 14:58:27 -05:00
Yusuke Tanaka 4b1d76ec8f docs: fix typo in signal module documentation (#3249) 2020-12-10 08:11:45 -08:00
Clemens Koza 9646b4bce3 toml: enable test-util feature for the playground (#3224) 2020-12-10 10:39:05 +01:00
Alice Ryhland@tijsvd f60860af7e watch: fix spurious wakeup (#3234)
Co-authored-by: @tijsvd
2020-12-10 09:46:01 +01:00
cssivision 2a30e13f38 net: expose poll_* methods on UnixDatagram (#3223) 2020-12-10 08:36:43 +01:00
Nylonicious 52cd240053 task: add missing feature flags for task_local and spawn_blocking (#3237) 2020-12-09 23:49:28 +01:00
Carl Lerche 473ddaa277 chore: prepare for Tokio 1.0 work (#3238) 2020-12-09 09:42:05 -08:00
bdonlan 9706ca92a8 time: Fix race condition in timer drop (#3229)
Dropping a timer on the millisecond that it was scheduled for, when it was on
the pending list, could result in a panic previously, as we did not record the
pending-list state in cached_when.

Hopefully fixes: ZcashFoundation/zebra#1452
2020-12-08 16:42:43 -08:00
Blas Rodriguez Irizar fc7a4b3c6e chore: fix stress test (#3233) 2020-12-09 07:38:25 +09:00
Blas Rodriguez Irizar e01391351b Add stress test (#3222)
Created a simple echo TCP server that on two different runtimes that is
called from a GitHub action using Valgrind to ensure that there are
no memory leaks.

Fixes: #3022
2020-12-07 21:12:22 -08:00
bdonlan 57dffb9dfe rt: fix deadlock in shutdown (#3228)
Previously, the runtime shutdown logic would first-hand control over all cores
to a single thread, which would sequentially shut down all tasks on the core
and then wait for them to complete.

This could deadlock when one task is waiting for a later core's task to
complete. For example, in the newly added test, we have a `block_in_place` task
that is waiting for another task to be dropped. If the latter task adds its
core to the shutdown list later than the former, we end up waiting forever for
the `block_in_place` task to complete.

Additionally, there also was a bug wherein we'd attempt to park on the parker
after shutting it down which was fixed as part of the refactors above.

This change restructures the code to bring all tasks to a halt (and do any
parking needed) before we collapse to a single thread to avoid this deadlock.

There was also an issue in which canceled tasks would not unpark the
originating thread, due to what appears to be some sort of optimization gone
wrong. This has been fixed to be much more conservative in selecting when not
to unpark the source thread (this may be too conservative; please take a look
at the changes to `release()`).

Fixes: #2789
2020-12-07 20:55:02 -08:00
Carl Lerche 62023dffe5 sync: forward port 0.2 mpsc test (#3225)
Forward ports the test included in #3215. The mpsc sempahore has been
replaced in 0.3 and does not include the bug being fixed.
2020-12-07 11:24:15 -08:00
Fuyang Liu 0707f4c192 net: add TcpStream::into_std (#3189) 2020-12-06 14:33:04 +01:00
Iban Eguia 0dbba13984 deps: replace lazy_static with once_cell (#3187) 2020-12-04 10:23:13 +01:00
John-John Tedro a125ebd745 rt: fix panic in task abort when off rt (#3159)
A call to `JoinHandle::abort` releases a task. When called from outside of the runtime,
this panics due to the current implementation checking for a thread-local worker context.

This change makes accessing the thread-local context optional under release, by falling
back to remotely marking a task remotely as dropped. Behaving the same as if the core
was stolen by another worker.

Fixes #3157
2020-12-03 21:29:59 -08:00
Eliza Weisman 00500d1b35 util: prepare v0.5.1 release (#3210)
### Added

- io: `poll_read_buf` util fn (#2972).
- io: `poll_write_buf` util fn with vectored write support (#3156).

Signed-off-by: Eliza Weisman <[email protected]>
2020-12-03 15:30:52 -08:00
Eliza Weisman 647299866a util: add writev-aware poll_write_buf (#3156)
## Motivation

In Tokio 0.2, `AsyncRead` and `AsyncWrite` had `poll_write_buf` and
`poll_read_buf` methods for reading and writing to implementers of
`bytes` `Buf` and `BufMut` traits. In 0.3, these were removed, but
`poll_read_buf` was added as a free function in `tokio-util`. However,
there is currently no `poll_write_buf`.

Now that `AsyncWrite` has regained support for vectored writes in #3149,
there's a lot of potential benefit in having a `poll_write_buf` that
uses vectored writes when supported and non-vectored writes when not
supported, so that users don't have to reimplement this.

## Solution

This PR adds a `poll_write_buf` function to `tokio_util::io`, analogous
to the existing `poll_read_buf` function.

This function writes from a `Buf` to an `AsyncWrite`, advancing the
`Buf`'s internal cursor. In addition, when the `AsyncWrite` supports
vectored writes (i.e. its `is_write_vectored` method returns `true`),
it will use vectored IO.

I copied the documentation for this functions from the docs from Tokio
0.2's `AsyncWrite::poll_write_buf` , with some minor modifications as
appropriate.

Finally, I fixed a minor issue in the existing docs for `poll_read_buf`
and `read_buf`, and updated `tokio_util::codec` to use `poll_write_buf`.

Signed-off-by: Eliza Weisman <[email protected]>
2020-12-03 11:19:16 -08:00
Blas Rodriguez Irizar a6051a61ec sync: make add_permits panic with usize::MAX >> 3 permits (#3188) 2020-12-02 22:58:28 +01:00
cssivision a8e0f0a919 example: add back udp-codec example (#3205) 2020-12-01 12:20:20 +09:00
Alan Somers 7ae8135b62 process: fix the process_kill_on_drop.rs test on non-Linux systems (#3203)
"disown" is a bash builtin, not part of POSIX sh.
2020-12-01 10:20:49 +09:00
Alan Somers 353b0544a0 ci: reenable CI on FreeBSD i686 (#3204)
It was temporarily disabled in 06c473e628
and never reenabled.
2020-12-01 10:20:18 +09:00
Alan Somers 128495168d ci: switch FreeBSD CI environment to 12.2-RELEASE (#3202)
12.1 will be EoL in two months.
2020-12-01 10:19:54 +09:00
Carl Lerche 08548583b9 chore: prepare v0.3.5 release (#3201) 2020-11-30 12:57:31 -08:00
HK416-is-all-you-need 7707ba88ef io: add AsyncFd::with_interest (#3167)
Fixes #3072
2020-11-30 11:11:18 -08:00
Ivan Tham 72d6346c0d macros: #[tokio::main] can be used on non-main (#3199) 2020-11-30 17:34:11 +01:00
Kyle Kosic a85fdb884d runtime: test for shutdown_timeout(0) (#3196) 2020-11-29 21:30:19 +01:00
Alice Ryhl c55d846f4b util: add rt to tokio-util full feature (#3194) 2020-11-29 09:48:31 +01:00
Max Sharnoff 0acd06b42a runtime: fix shutdown_timeout(0) blocking (#3174) 2020-11-28 19:31:13 +01:00
Niklas Fiekas 4912943419 signal: expose CtrlC stream on windows (#3186)
* Make tokio::signal::windows::ctrl_c() public.
* Stop referring to private tokio::signal::windows::Event in module
  documentation.

Closes #3178
2020-11-27 19:53:17 +00:00
Rajiv Chauhan 5e406a7a47 macros: fix outdated documentation (#3180)
1. Changed 0.2 to 0.3
2. Changed ‘multi’ to ‘single’ to indicate that the behavior is single threaded
2020-11-26 19:46:15 +01:00
Max Sharnoff de33ee85ce time: replace 'ouClockTimeide' in internal docs with 'outside' (#3171) 2020-11-24 10:23:20 +01:00
漂流 874fc3320b codec: add read_buffer_mut to FramedRead (#3166) 2020-11-24 09:39:16 +01:00
bdonlan ae67851f11 time: use intrusive lists for timer tracking (#3080)
More-or-less a half-rewrite of the current time driver, supporting the
use of intrusive futures for timer registration.

Fixes: #3028, #3069
2020-11-23 10:42:50 -08:00
Eliza Weisman f927f01a34 macros: fix rustfmt on 1.48.0 (#3160)
## Motivation

Looks like the Rust 1.48.0 version of `rustfmt` changed some formatting
rules (fixed some bugs?), and some of the code in `tokio-macros` is no
longer correctly formatted. This is breaking CI.

## Solution

This commit runs rustfmt on Rust 1.48.0. This fixes CI.

Closes #3158
2020-11-20 10:19:26 -08:00
cssivision 49abfdb2ac util: fix typo in udp/frame.rs (#3154) 2020-11-20 15:06:14 +09:00
Carl Lerche 479c545c20 chore: prepare v0.3.4 release (#3152) 2020-11-18 12:38:13 -08:00
Sean McArthur 34fcef258b io: add vectored writes to AsyncWrite (#3149)
This adds `AsyncWrite::poll_write_vectored`, and implements it for
`TcpStream` and `UnixStream`.

Refs: #3135.
2020-11-18 10:41:47 -08:00
Zeki Sherif 7d11aa8668 net: add SO_LINGER get/set to TcpStream (#3143) 2020-11-17 09:58:00 -08:00
Carl Lerche 0ea2307650 net: add UdpSocket readiness and non-blocking ops (#3138)
Adds `ready()`, `readable()`, and `writable()` async methods for waiting
for socket readiness. Adds `try_send`, `try_send_to`, `try_recv`, and
`try_recv_from` for performing non-blocking operations on the socket.

This is the UDP equivalent of #3130.
2020-11-16 15:44:01 -08:00
Zahari Dichev d0ebb41547 sync: add Notify::notify_waiters (#3098)
This PR makes `Notify::notify_waiters` public. The method
already exists, but it changes the way `notify_waiters`,
is used. Previously in order for the consumer to
register interest, in a notification triggered by
`notify_waiters`, the `Notified` future had to be
polled. This introduced friction when using the api
as the future had to be pinned before polled.

This change introduces a counter that tracks how many
times `notified_waiters` has been called. Upon creation of
the future the number of times is loaded. When first
polled the future compares this number with the count
state of the `Notify` type. This avoids the need for
registering the waiter upfront.

Fixes: #3066
2020-11-16 12:49:35 -08:00
Eliza Weisman f5cb4c2042 net: Add send/recv buf size methods to TcpSocket (#3145)
This commit adds `set_{send, recv}_buffer_size` methods to `TcpSocket`
for setting the size of the TCP send and receive buffers, and `{send,
recv}_buffer_size` methods for returning the current value. These just
call into similar methods on `mio`'s `TcpSocket` type, which were added
in tokio-rs/mio#1384.

Refs: #3082

Signed-off-by: Eliza Weisman <[email protected]>
2020-11-16 12:29:03 -08:00
masnagam 4e39c9b818 net: restore TcpStream::{poll_read_ready, poll_write_ready} (#2743) 2020-11-16 09:51:06 -08:00
Carl Lerche 97c2c4203c chore: automate running benchmarks (#3140)
Uses Github actions to run benchmarks.
2020-11-13 19:30:52 -08:00
Taiki Endo 60366ca0fa chore: update pin-project-lite to 0.2.0 (#3139) 2020-11-13 15:24:06 -08:00
Carl Lerche 850bfc9efa net: add missing doc cfg on TcpSocket (#3137)
This adds the missing `net` feature flag in the generated API
documentation.
2020-11-13 11:05:22 -08:00
Carl Lerche 02b1117dca net: add TcpStream::ready and non-blocking ops (#3130)
Adds function to await for readiness on the TcpStream and non-blocking read/write functions.

`async fn TcpStream::ready(Interest)` waits for socket readiness satisfying **any** of the specified
interest. There are also two shorthand functions, `readable()` and `writable()`.

Once the stream is in a ready state, the caller may perform non-blocking operations on it using
`try_read()` and `try_write()`. These function return `WouldBlock` if the stream is not, in fact, ready.

The await readiness function are similar to `AsyncFd`, but do not require a guard. The guard in
`AsyncFd` protect against a potential race between receiving the readiness notification and clearing
it. The guard is needed as Tokio does not control the operations. With `TcpStream`, the `try_read()`
and `try_write()` function handle clearing stream readiness as needed.

This also exposes `Interest` and `Ready`, both defined in Tokio as wrappers for Mio types. These
types will also be useful for fixing #3072 .

Other I/O types, such as `TcpListener`, `UdpSocket`, `Unix*` should get similar functions, but this
is left for later PRs.

Refs: #3130
2020-11-12 20:07:43 -08:00
Nylonicious 685da8dadd fs: small documentation fixes (#3133) 2020-11-12 10:24:13 +01:00
Alice Ryhl 6a0e23c654 ci: minimal version check (#3131) 2020-11-11 23:08:34 +01:00
Alice Ryhl 9d0c0dd22c time: document maximum sleep duration (#3126) 2020-11-11 11:31:22 -08:00
Alice Ryhl 6d5423f3e9 stream: add docs regarding futures' StreamExt (#3128) 2020-11-11 11:20:14 -08:00
Ivan Petkov ebb8bab060 process: fix potential file descriptor leak (#3129) 2020-11-11 11:10:27 -08:00
Carl Lerche ce891a4df1 io: driver internal cleanup (#3124)
* Removes duplicated code by moving it to `Registration`.
* impl `Deref` for `PollEvented` to avoid `get_ref()`.
* Avoid extra waker clones in I/O driver.
* Add `Interest` wrapper around `mio::Interest`.
2020-11-11 09:28:21 -08:00
David Kellum d869e16990 Minor cleanup of parking_lot feature, now in full (#3119)
## Motivation

Some small cleanup items are apparent after merge of #2951

## Solution

Delete a now incorrect comment in Cargo.toml, and remove a now redundant CI test step.
2020-11-10 15:01:58 -08:00
Carl Lerche e1256d8ca4 io: update AsyncFd to use Registration (#3113) 2020-11-10 09:40:20 -08:00
Darius Carrier a52f5071bf sync: add acquire_many and try_acquire_many to Sempahore (#3067)
Fixes: #1550
2020-11-10 09:39:30 -08:00
Taiki Endo f1f8c3cde6 chore: update proptest and nix (#3110) 2020-11-08 20:47:44 +09:00
Oliver Gould c2e843d928 tokio-test: Update bytes to v0.6 (#3107) 2020-11-08 05:54:41 +09:00
bdonlanandBryan Donlan a43ec09b55 async_fd: make into_inner() deregister the fd (#3104)
* async_fd: make into_inner() deregister the fd

Fixes: #3103

* make clippy happy

Co-authored-by: Bryan Donlan <[email protected]>
2020-11-07 10:12:06 +01:00
Maarten de Vries 90c2a510e2 net: report PID in UCred for Solaris and Illumos. (#3085) 2020-11-06 17:04:19 +01:00
Alice Ryhl f51ddc5958 net: add set_nonblocking to doc (#3100) 2020-11-06 17:01:22 +01:00
Evan Cameron 47658a6da5 util: resurrect UdpFramed (#3044) 2020-11-06 16:59:15 +01:00
bdonlanandBryan Donlan d7e3fcb9ee rt: remove last slab dependency (#2917)
This removes the last slab dependency by replacing the current slab-based
JoinHandle tracking with one based on HashMap instead.

Co-authored-by: Bryan Donlan <[email protected]>
2020-11-05 10:38:37 -08:00
0b3918bce9 rt: bring back a public Handle type (#3076)
Signed-off-by: Marc-Antoine Perennou <[email protected]>
Co-authored-by: Alice Ryhl <[email protected]>
Co-authored-by: Carl Lerche <[email protected]>
2020-11-05 13:00:13 +01:00
Akira Hayakawa e309da0bee util: remove stream feature flag from DelayQueue (#3087) 2020-11-03 09:20:24 +01:00
Carl Lerche bbc8eb0f91 chore: update CI badge (#3091) 2020-11-03 09:17:47 +01:00
Artem Vorotnikov 06c7e73e99 stream: fix StreamMap Default bound (#3093) 2020-11-03 09:09:05 +01:00
Carl Lerche 42de3bc7a4 chore: prepare v0.3.3 release (#3090) 2020-11-02 15:36:17 -08:00
Alice Ryhl 20a2b9e263 rt: add missing Send bound (#3089) 2020-11-02 15:30:07 -08:00
Zeki Sherif ae4e8d7ad1 net: add get/set reuseport, reuseaddr, localaddr for TcpSocket (#3083) 2020-11-02 12:59:56 -08:00
Alice Ryhl 7a18ca2be0 doc: add from_std change to CHANGELOG (#3075) 2020-11-02 10:25:43 -08:00
Naja Melan 4a7b7c52d1 util: copy paste error in documentation for Compat (#3088) 2020-11-02 13:25:51 +01:00
Eliza Weisman fede3db76a tracing: replace future names with spawn locations in task spans (#3074)
## Motivation

Currently, the per-task `tracing` spans generated by tokio's `tracing`
feature flag include the `std::any::type_name` of the future that was
spawned. When future combinators and/or libraries like Tower are in use,
these future names can get _quite_ long. Furthermore, when formatting
the `tracing` spans with their parent spans as context, any other task
spans in the span context where the future was spawned from can _also_
include extremely long future names.

In some cases, this can result in extremely high memory use just to
store the future names. For example, in Linkerd, when we enable
`tokio=trace` to enable the task spans, there's a spawned task whose
future name is _232990 characters long_. A proxy with only 14 spawned
tasks generates a task list that's over 690 KB. Enabling task spans
under load results in the process getting OOM killed very quickly.

## Solution

This branch removes future type names from the spans generated by
`spawn`. As a replacement, to allow identifying which `spawn` call a
span corresponds to, the task span now contains the source code location
where `spawn` was called, when the compiler supports the
`#[track_caller]` attribute. Since `track_caller` was stabilized in Rust
1.46.0, and our minimum supported Rust version is 1.45.0, we can't
assume that `#[track_caller]` is always available. Instead, we have a
RUSTFLAGS cfg, `tokio_track_caller`, that guards whether or not we use
it. I've also added a `build.rs` that detects the compiler minor
version, and sets the cfg flag automatically if the current compiler
version is >= 1.46. This means users shouldn't have to enable
`tokio_track_caller` manually.

Here's the trace output from the `chat` example, before this change:
![Screenshot_20201030_110157](https://user-images.githubusercontent.com/2796466/97741071-6d408800-1a9f-11eb-9ed6-b25e72f58c7b.png)
...and after:
![Screenshot_20201030_110303](https://user-images.githubusercontent.com/2796466/97741112-7e899480-1a9f-11eb-9197-c5a3f9ea1c05.png)

Closes #3073

Signed-off-by: Eliza Weisman <[email protected]>
2020-11-01 10:48:44 -08:00
Dirkjan Ochtman 2b23aa7389 util: add back public poll_read_buf() function (#3079)
This was accidentally removed in #3064.
2020-11-01 10:22:22 +01:00
Finn Behrens 382ee6bf5d net: add pid to tokio::net::unix::UCred (#2633) 2020-10-31 10:30:55 +01:00
Carl Lerche 24ed874e81 chore: prepare tokio-util v0.5.0 release (#3078) 2020-10-30 11:26:15 -07:00
Dirkjan Ochtman 3965d91a5e util: update to bytes 0.6 (#3071)
Copies the implementation of poll_read_buf() from tokio::io::util::read_buf.
2020-10-29 10:45:19 -07:00
Dirkjan Ochtman a3ef4e4cf5 util: deduplicate implementations of poll_read_buf() (#3064) 2020-10-29 13:20:38 +01:00
Naja Melan 34eb47dde5 runtime: block_on should NOT be called from async context (#3070) 2020-10-29 12:10:42 +01:00
Tom Kaitchuck c8a484bbb2 tokio: remove unused dependency (#3063)
Signed-off-by: Tom Kaitchuck <[email protected]>
2020-10-28 08:06:53 +01:00
Carl Lerche 9097ae548f chore: prepare v0.3.2 release (#3059) 2020-10-27 14:31:39 -07:00
Carl Lerche d78655337a Revert "util: upgrade tokio-util to bytes 0.6 (#3052)" (#3060)
This reverts commit fe2b997.

We are avoiding adding poll_read_buf to tokio itself for now. The patch is
reverted now in order to not block the v0.3.2 release (#3059).
2020-10-27 13:42:00 -07:00
Zahari Dichev 38605c5c85 net: change mention of net2 (#3056) 2020-10-27 09:34:17 -07:00
Dirkjan Ochtman fe2b997675 util: upgrade tokio-util to bytes 0.6 (#3052) 2020-10-27 09:30:29 +01:00
Sean McArthur 6d0ba19af5 sync: make oneshot::Sender::poll_closed public again (#3032) 2020-10-26 08:54:25 -07:00
Alice Ryhl cbb8fe6069 udp: add UdpSocket::take_error (#3051) 2020-10-26 12:50:48 +01:00
Alice Ryhl a9da220923 oneshot: update closed() docs to use tokio::select! (#3050) 2020-10-26 11:44:46 +01:00
Alice Ryhl 1c28c3b0a8 macros: prepare tokio-macros 0.3.1 (#3042) 2020-10-26 10:02:39 +01:00
nickelc e31bd321ef readme: update the MSRV to 1.45 (#3048) 2020-10-26 09:46:15 +01:00
nickelc c30ce1f65c docs: remove max_threads mentions in tokio-macros (#3038) 2020-10-24 22:34:56 +02:00
Alice Ryhl a95378a850 io: expand on de-initialization of ReadBuf (#3035) 2020-10-24 22:29:19 +02:00
Zahari Dichev ce173fdc91 docs: update docs for from_std functions (#3016)
Fixes: #3007
2020-10-24 14:26:01 +02:00
Zahari Dichev e804f88d60 sync: add mem::forget to RwLockWriteGuard::downgrade. (#2957)
Currently when `RwLockWriteGuard::downgrade` the `MAX_READS - 1`
permits are added to the semaphore. When `RwLockWriteGuard::drop`
gets invoked however another `MAX_READS` permits are added. This
results in releasing more permits that were actually aquired when
downgrading a write to a read lock. This is why we need to call
`mem::forget` on the `RwLockWriteGuard` in order to avoid
invoking the destructor.

Fixes: #2941
2020-10-23 10:07:00 -07:00
bdonlan c153913211 io: Add AsyncFd, fix io::driver shutdown (#2903)
* io: Add AsyncFd

This adds AsyncFd, a unix-only structure to allow for read/writability states
to be monitored for arbitrary file descriptors.

Issue: #2728

* driver: fix shutdown notification unreliability

Previously, there was a race window in which an IO driver shutting down could
fail to notify ScheduledIo instances of this state; in particular, notification
of outstanding ScheduledIo registrations was driven by `Driver::drop`, but
registrations bypass `Driver` and go directly to a `Weak<Inner>`. The `Driver`
holds the `Arc<Inner>` keeping `Inner` alive, but it's possible that a new
handle could be registered (or a new readiness future created for an existing
handle) after the `Driver::drop` handler runs and prior to `Inner` being
dropped.

This change fixes this in two parts: First, notification of outstanding
ScheduledIo handles is pushed down into the drop method of `Inner` instead,
and, second, we add state to ScheduledIo to ensure that we remember that the IO
driver we're bound to has shut down after the initial shutdown notification, so
that subsequent readiness future registrations can immediately return (instead
of potentially blocking indefinitely).

Fixes: #2924
2020-10-22 14:12:41 -07:00
Evan Cameron 358e4f9f80 tokio: add back poll_* for udp (#2981) 2020-10-22 09:58:00 -07:00
Zhang Jingqiang adf822f5cc net: fix typo (#3023) 2020-10-22 08:59:47 +02:00
Carl Lerche d14cbf9116 chore: prepare v0.3.1 release (#3021) 2020-10-21 16:23:35 -07:00
Carl Lerche 8bfb1c92ce sync: revert Clone impl for broadcast::Receiver (#3020)
The `Receiver` handle maintains a position in the broadcast channel for
itself. Cloning implies copying the state of the value. Intuitively,
cloning a `broadcast::Receiver` would return a new receiver with an
identical position. However, the current implementation returns a new
`Receiver` positioned at the tail of the channel.

This behavior subtlety is why `new_subscriber()` is used to create
`Receiver` handles. An alternate API should consider the position issue.

Refs: #2933
2020-10-21 15:14:52 -07:00
Carl Lerche b48fec9655 net: fix use-after-free in slab compaction (#3019)
An off-by-one bug results in freeing the incorrect page. This
also adds an `asan` CI job.

Fixes: 3014
2020-10-21 14:43:57 -07:00
Carl Lerche 8dbc3c7937 io: add AsyncReadExt::read_buf (#3003)
Brings back `read_buf` from 0.2. This will be stabilized as part of 1.0.
2020-10-21 14:08:49 -07:00
Marc-Antoine Perennou 7fbfa9b649 tokio: deduplicate spawn_blocking (#3017)
Move common code and tracing integration into Handle

Fixes #2998
Closes #3004

Signed-off-by: Marc-Antoine Perennou <[email protected]>
2020-10-21 20:00:48 +02:00
Nikolai Kuklin 7d7b79e1d5 sync: add is_closed method to watch sender (#2991) 2020-10-21 13:35:13 +02:00
Zahari Dichev 8f37544a79 io: explain how to determine number of bytes read in AsyncRead (#3011)
Fixes: #2999
2020-10-21 13:32:50 +02:00
Philip Kannegaard Hayes 43d0714898 sync: remove extra clone in Semaphore::[try_]acquire_owned (#3015) 2020-10-21 08:16:03 +02:00
Zahari Dichev 16e272ea4b fs: flush on shutdown (#3009)
Fixes: #2950
2020-10-20 17:42:32 +02:00
John-John Tedro 6d99e1c7de util: prevent read buffer from being swapped during a read_poll (#2993) 2020-10-20 11:14:02 +02:00
pluth f73a2ad238 docs: adjust TcpListener::from_std documentation to match behavior (#3002) 2020-10-19 21:37:00 -07:00
Alice Ryhl c793ead0c3 runtime: remove unneeded #[cfg(feature = "rt")] (#2996) 2020-10-19 21:35:33 -07:00
Marc-Antoine Perennou 2696794771 tokio: add Runtime::spawn_blocking (#2980)
This allows writing

rt.spawn_blocking(f);

instead of

let _enter = rt.enter();
tokio::task::spawn_blocking(f);

Signed-off-by: Marc-Antoine Perennou <[email protected]>
2020-10-19 18:49:16 +02:00
nickelc cfd643d691 docs: fix typo in runtime module documentation (#2992) 2020-10-19 15:33:10 +02:00
John-John Tedro 8d17261a4b util: add a poll_read_buf shim to tokio-util (#2972) 2020-10-19 11:06:06 +02:00
Zahari Dichev 423ecc187a io: add copy_buf (#2884) 2020-10-19 10:15:25 +02:00
Zephyr Shannon fb28caa90c sync: implement Clone for broadcast::Receiver (#2933) 2020-10-19 10:12:40 +02:00
Evan Cameron e88e64bcc0 docs: fix typos on UdpSocket (#2979) 2020-10-17 12:13:23 +02:00
messense 3cc6ce7a99 doc: update version to 0.3 in module documentation (#2974) 2020-10-16 13:49:30 +02:00
Alice Ryhl 81db03204d Fix doc typo (#2967) 2020-10-16 12:37:21 +02:00
John-John Tedro 1644511bdf Update documentation of AsyncRead to reflect use of ReadBuf 2020-10-16 11:55:35 +02:00
Carl Lerche dc9742fbea chore: post release Cargo.toml fixes (#2963) 2020-10-15 11:46:10 -07:00
Carl Lerche 12f1dffa2d chore: prepare for v0.3.0 release (#2960) 2020-10-15 09:22:07 -07:00
Taiki Endo 871289b3e7 ci: run clippy on MSRV (#2962) 2020-10-15 06:30:20 +09:00
Lucio Franco 30b40ef518 rt: update docs for 0.3 changes (#2956)
This PR updates the runtime module docs to the changes made in `0.3`
release of tokio.

Closes #2720
2020-10-13 15:49:19 -07:00
Carl Lerche 22fa883296 rt: tweak spawn_blocking docs (#2955) 2020-10-13 15:07:10 -07:00
Carl Lerche 00b6127f2e rt: switch enter to an RAII guard (#2954) 2020-10-13 15:06:22 -07:00
Ivan Petkov a249421abc process: update docs regarding zombie processes (#2952) 2020-10-13 00:42:17 +00:00
Carl Lerche 1923350880 meta: combine net and dns, use parking_lot (#2951)
This combines the `dns` and `net` feature flags. Previously, `dns` was
included as part of `net`. Given that is is rare that one would want
`dns` without `net`, DNS is now entirely gated w/ `net`.

The `parking_lot` feature is included as part of `full`.

Some misc docs are tweaked to reflect feature flag changes.
2020-10-12 16:06:02 -07:00
Taiki Endo c90681bd8e rt: simplify rt-* features (#2949)
tokio:

    merge rt-core and rt-util as rt
    rename rt-threaded to rt-multi-thread

tokio-util:

    rename rt-core to rt

Closes #2942
2020-10-12 14:13:23 -07:00
Ivan Petkov 24d0a0cfa8 chore: refactor runtime driver usage of Either (#2918) 2020-10-12 19:57:22 +00:00
Lucio FrancoandAlice Ryhl 07802b2c84 rt: worker_threads must be non-zero (#2947)
Co-authored-by: Alice Ryhl <[email protected]>
2020-10-12 15:15:40 -04:00
Taiki Endo 891de3271d net: merge tcp, udp, uds features to net feature (#2943) 2020-10-13 03:36:26 +09:00
8880222036 rt: Remove threaded_scheduler() and basic_scheduler() (#2876)
Co-authored-by: Alice Ryhl <[email protected]>
Co-authored-by: Carl Lerche <[email protected]>
2020-10-12 13:44:54 -04:00
Juan Alvarez 0893841f31 time: move error types into time::error (#2938) 2020-10-12 10:21:44 -07:00
Lucio FrancoandAlice Ryhl ec99e61945 time: Clean up Instant docs to align with std (#2946)
Co-authored-by: Alice Ryhl <[email protected]>
2020-10-12 13:06:55 -04:00
Lucio Franco f8c91f2ead io: Rename ReadBuf methods (#2945)
This changes `ReadBuf::add_filled` to `ReadBuf::advance` and
`ReadBuf::append` to `ReadBuf::put_slice`. This is just a
mechanical change.

Closes #2769
2020-10-12 12:41:40 -04:00
Zahari Dichev b575082543 sync: change chan closed(&mut self) to closed(&self) (#2939) 2020-10-12 12:09:36 -04:00
Taiki Endo c4f620cb30 chore: remove use of doc_alias feature (#2944) 2020-10-12 09:42:59 +02:00
Taiki Endo b047f647b7 net: make UCred fields private (#2936) 2020-10-11 09:31:26 +02:00
Taiki Endo 2e05399f4b sync: move broadcast error types into broadcast::error module (#2937)
Refs: #2928
2020-10-09 10:10:22 -07:00
Carl Lerche afe535283c fs: future proof File (#2930)
Changes inherent methods to take `&self` instead of `&mut self`. This
brings the API in line with `std`.

This patch is implemented by using a `tokio::sync::Mutex` to guard the
internal `File` state. This is not an ideal implementation strategy
doesn't make a big impact compared to having to dispatch operations to a
background thread followed by a blocking syscall.

In the future, the implementation can be improved as we explore async
file-system APIs provided by the operating-system (iocp / io_uring).

Closes #2927
2020-10-09 10:02:55 -07:00
Carl Lerche ee597347c5 net: switch socket methods to &self (#2934)
Switches various socket methods from &mut self to &self. This uses the intrusive
waker infrastructure to handle multiple waiters.

Refs: #2928
2020-10-09 09:16:42 -07:00
Taiki Endo 41ac1ae2bc io: make Seek and Copy private (#2935)
Refs: #2928
2020-10-09 08:33:14 -07:00
Juan Alvarez 60d81bbe10 time: rename Delay future to Sleep (#2932) 2020-10-08 20:35:12 -07:00
bdonlanandBryan Donlan b704c53b9c chore: Fix clippy lints (#2931)
Closes: #2929

Co-authored-by: Bryan Donlan <[email protected]>
2020-10-08 17:14:39 -07:00
Carl Lerche 066965cd59 net: use &self with TcpListener::accept (#2919)
Uses the infrastructure added by #2828 to enable switching
`TcpListener::accept` to use `&self`.

This also switches `poll_accept` to use `&self`. While doing introduces
a hazard, `poll_*` style functions are considered low-level. Most users
will use the `async fn` variants which are more misuse-resistant.

TcpListener::incoming() is temporarily removed as it has the same
problem as `TcpSocket::by_ref()` and will be implemented later.
2020-10-08 12:12:56 -07:00
Taiki Endo 6259893094 fs: add os::windows::OpenOptionsExt (#2923) 2020-10-08 11:09:12 +02:00
Zahari Dichev 43bd11bf2f io: remove Poll from the AsyncSeek::start_seek return value (#2885) 2020-10-08 10:56:01 +02:00
Taiki Endo d94ab62c54 util: fix a typo in sync/cancellation_token.rs (#2922) 2020-10-07 15:46:13 -07:00
Carl Lerche a9a59ea90e net: add TcpSocket for configuring a socket (#2920)
This enables the caller to configure the socket and to explicitly bind
the socket before converting it to a `TcpStream` or `TcpListener`.

Closes: #2902
2020-10-07 13:02:29 -07:00
Taiki Endo c248167173 fs: switch to our own DirEntryExt trait (#2921) 2020-10-08 02:30:25 +09:00
Evan Cameron 601a3ef93f docs: more docs for UdpSocket (#2883) 2020-10-06 18:12:02 -07:00
greenwoodcm fcdf9345bf time: clean time driver (#2905)
* remove unnecessary wheel::Poll

the timer wheel uses the `wheel::Poll` struct as input when
advancing the timer to the next time step.  the `Poll` struct
contains an instant representing the time step to advance to
and also contains an optional and mutable reference to an
`Expiration` struct.  from what I can tell, the latter field
is only used in the context of polling the wheel and does not
need to be exposed outside of that method.  without the
expiration field the `Poll` struct is nothing more than a
wrapper around the instant being polled.  this change removes
the `Poll` struct and updates integration points accordingly.

* remove Stack trait in favor of concrete Stack implementation

* remove timer Registration struct
2020-10-06 12:48:01 -07:00
Ivan Petkov 4cf45c038b process: add ProcessDriver to handle orphan reaping (#2907) 2020-10-06 17:30:16 +00:00
bdonlanandBryan Donlan 9730317e94 time: move DelayQueue to tokio-util (#2897)
This change is intended to do the minimum to unblock 0.3; as such, for now, we
duplicate the internal `time::wheel` structures in tokio-util, rather than trying
to refactor things at this stage.

Co-authored-by: Bryan Donlan <[email protected]>
2020-10-05 14:25:04 -07:00
Taiki Endo 02311dcfa1 io, stream: assert !Unpin for ext trait futures (#2913) 2020-10-06 04:44:34 +09:00
Alice Ryhl aa171f2aa9 stream: remove bytes from public API (#2908) 2020-10-05 10:33:15 -07:00
Taiki Endo c23c1ecbcb io, stream: make ext trait futures !Unpin (#2910)
Make these future `!Unpin` for compatibility with async trait methods.
2020-10-05 10:32:11 -07:00
Taiki Endo 561a71ad63 net: implement AsRawSocket on Windows (#2911) 2020-10-05 10:22:19 -07:00
Alice Ryhl 242ea01189 sync: broadcast channel API tweaks (#2898)
Removes deprecated APIs and makes some small breaking changes.
2020-10-05 09:30:48 -07:00
Mikail Bagishov 1684e1c809 io: optimize writing large buffers to windows stdio (#2888) 2020-10-05 16:07:46 +02:00
Taiki Endo 0ed4127d5c fs: seal OpenOptionsExt and DirBuilderExt (#2909) 2020-10-05 00:47:35 +09:00
Carl Lerche 1e585ccb51 io: update to Mio 0.7 (#2893)
This also makes Mio an implementation detail, removing it from the
public API.

This is based on #1767.
2020-10-02 13:54:00 -07:00
Alice Ryhl 7ec6d88b21 chore: make #[doc(hidden)] apis private (#2901) 2020-10-01 21:13:28 -07:00
Alice Ryhl 13de30c53e task: remove deprecated JoinError constructors (#2900) 2020-10-02 01:01:11 +03:00
Alice Ryhl 496e889917 Fix new clippy warning (#2899) 2020-10-02 00:59:48 +03:00
Juan Alvarez 53ccfc1fd6 time: introduce sleep and sleep_until functions (#2826) 2020-10-01 09:24:33 +02:00
Sean McArthur 971ed2c6df Seal FromStream methods with an internal argument (#2894) 2020-09-29 07:41:20 -07:00
Matt Kennedy dcb11118d2 test: fix spelling error in documentation (#2895)
Fixes: #2754
2020-09-29 13:23:11 +02:00
Linus Behrbohm 3403be5e2e stream: add iter and iter_mut methods to StreamMap (#2890) 2020-09-29 10:07:22 +02:00
Sean McArthur c6fc35aadf Seal ToSocketAddrs methods with an internal argument (#2892)
Closes #2891
2020-09-28 14:43:41 -07:00
Mikail BagishovandAlice Ryhl 078d0a2ebc sync: Add is_closed method to mpsc senders (#2726)
Co-authored-by: Alice Ryhl <[email protected]>
2020-09-28 11:37:28 -04:00
Mikail Bagishov 99d4061203 bench: fix unused_mut lint in benches (#2889) 2020-09-27 11:07:55 +02:00
Sean McArthur dfdfd61372 Fix readiness future eagerly consuming entire socket readiness (#2887)
In the `readiness` future, before inserting a waiter into the list, the current socket readiness is eagerly checked. However, it would return as a `ReadyEvent` the entire socket readiness, instead of just the interest desired from `readiness(interest)`. This would result in the later call to `clear_readiness(event)` removing all of it.

Closes #2886
2020-09-25 16:34:40 -07:00
Zahari Dichev 55d932a21f sync: add mpsc::Sender::closed future (#2840)
Adding closed future, makes it possible to select over closed and some other
work, so that the task is woken when the channel is closed and can proactively
cancel itself.

Added a mpsc::Sender::closed future that will become ready when the receiver
is closed.
2020-09-25 08:40:31 -07:00
Zahari Dichev 444660664b chore: handle std Mutex poisoning in a shim (#2872)
As tokio does not rely on poisoning, we can
avoid always unwrapping when locking by handling
the `PoisonError` in the Mutex shim.

Signed-off-by: Zahari Dichev <[email protected]>
2020-09-25 08:38:13 -07:00
Carl Lerche cf025ba45f sync: support mpsc send with &self (#2861)
Updates the mpsc channel to use the intrusive waker based sempahore.
This enables using `Sender` with `&self`.

Instead of using `Sender::poll_ready` to ensure capacity and updating
the `Sender` state, `async fn Sender::reserve()` is added. This function
returns a `Permit` value representing the reserved capacity.

Fixes: #2637
Refs: #2718 (intrusive waiters)
2020-09-24 17:26:38 -07:00
Carl Lerche 4186b0aa38 io: remove poll_{read,write}_buf from traits (#2882)
These functions have object safety issues. It also has been decided to
avoid vectored operations on the I/O traits. A later PR will bring back
vectored operations on specific types that support them.

Refs: #2879, #2716
2020-09-24 17:26:03 -07:00
bdonlanandBryan Donlan 760ae89401 chore: Use IoSlice's Copy impl to clean up some repetitive code (#2875)
As we go into 0.3 we no longer need to support older versions of Rust where
IoSlice did not implement Copy and Clone, so we can more easily initialize the
IoSlice array in net::tcp::stream.

Co-authored-by: Bryan Donlan <[email protected]>
2020-09-24 14:50:10 -07:00
Ivan Petkov 56acde069f chore: remove internal io-driver cargo feature (#2881) 2020-09-24 21:36:42 +00:00
Ivan Petkov ffa5bdb22d chore: remove internal io-readiness cargo feature (#2878) 2020-09-24 20:14:39 +00:00
Ivan Petkov a1d0681cd2 process: do not publicly turn on signal when enabled (#2871)
This change will still internally compile any `signal` resources
required when `process` is enabled on unix systems, but it will not
publicly turn on the cargo feature
2020-09-24 10:51:46 -07:00
Lucio Franco 4dfbdbff7e rt: Allow concurrent Shell:block_on calls (#2868) 2020-09-24 13:31:49 -04:00
Taiki Endo c29f13b7a5 docs: use #[doc(no_inline)] on re-exports (#2874) 2020-09-24 22:59:47 +09:00
Sean McArthur a0557840eb io: use intrusive wait list for I/O driver (#2828)
This refactors I/O registration in a few ways:

- Cleans up the cached readiness in `PollEvented`. This cache used to
  be helpful when readiness was a linked list of `*mut Node`s in
  `Registration`. Previous refactors have turned `Registration` into just
  an `AtomicUsize` holding the current readiness, so the cache is just
  extra work and complexity. Gone.
- Polling the `Registration` for readiness now gives a `ReadyEvent`,
  which includes the driver tick. This event must be passed back into
  `clear_readiness`, so that the readiness is only cleared from `Registration`
  if the tick hasn't changed. Previously, it was possible to clear the
  readiness even though another thread had *just* polled the driver and
  found the socket ready again.
- Registration now also contains an `async fn readiness`, which stores
  wakers in an instrusive linked list. This allows an unbounded number
  of tasks to register for readiness (previously, only 1 per direction (read
  and write)). By using the intrusive linked list, there is no concern of
  leaking the storage of the wakers, since they are stored inside the `async fn`
  and released when the future is dropped.
- Registration retains a `poll_readiness(Direction)` method, to support
  `AsyncRead` and `AsyncWrite`. They aren't able to use `async fn`s, and
  so there are 2 reserved slots for those methods.
- IO types where it makes sense to have multiple tasks waiting on them
  now take advantage of this new `async fn readiness`, such as `UdpSocket`
  and `UnixDatagram`.

Additionally, this makes the `io-driver` "feature" internal-only (no longer
documented, not part of public API), and adds a second internal-only
feature, `io-readiness`, to group together linked list part of registration
that is only used by some of the IO types.

After a bit of discussion, changing stream-based transports (like
`TcpStream`) to have `async fn read(&self)` is punted, since that
is likely too easy of a footgun to activate.

Refs: #2779, #2728
2020-09-23 13:02:15 -07:00
Lucio Franco f25f12d576 rt: Allow concurrent block_on's with basic_scheduler (#2804) 2020-09-23 14:35:10 -04:00
Daniel Henry-Mantilla 0f70530ee7 sync: add get_mut() for Mutex,RwLock (#2856) 2020-09-23 10:30:43 -07:00
kalcutter 3114d9e826 net: change UnixListener::poll_accept to public (#2845) 2020-09-23 16:21:18 +02:00
Alice Ryhl 5467f0a573 io: move #[cfg(not(loom))] to fix warning (#2864) 2020-09-23 11:04:52 +02:00
Mikail Bagishov 555b74c7cd io: fix stdout and stderr buffering on windows (#2734) 2020-09-23 08:16:05 +02:00
Ivan Petkov 7ae5b7bd4f signal: move driver to runtime thread (#2835)
Refactors the signal infrastructure to move the driver to the runtime
thread. This follows the model put forth by the I/O driver and time
driver.
2020-09-22 15:40:44 -07:00
Alice Ryhl e09b90ea32 macros: add #[allow(unused_mut)] to select! (#2858) 2020-09-23 05:56:45 +09:00
Taiki Endo cb8f2ceb2e chore: remove unused future/pending.rs (#2860) 2020-09-23 05:55:58 +09:00
Taiki Endo 6866b24ca1 ci: deny warnings on '--cfg tokio_unstable' tests (#2859) 2020-09-23 05:55:35 +09:00
Zahari Dichev e7091fde78 sync: Remove readiness assertion in `watch::Receiver::changed() (#2839)
*In `watch::Receiver::changed` `Notified` was polled
for the first time to ensure the waiter is registered while
assuming that the first poll will always return `Pending`.
It is the case however that another instance of `Notified`
is dropped without receiving its notification, this "orphaned"
notification can be used to satisfy another waiter without
even registering it. This commit accounts for that scenario.
2020-09-22 08:12:57 -07:00
Carl Lerche 2348f678e6 Merge remote-tracking branch 'origin/v0.2.x' into merge-v0.2 2020-09-21 14:35:38 -07:00
Carl Lerche 93f8cb8df2 sync: fix missing notification during mpsc close (#2854)
When the mpsc channel receiver closes the channel, receiving should
return `None` once all in-progress sends have completed. When a sender
reserves capacity, this prevents the receiver from fully shutting down.
Previously, when the sender, after reserving capacity, dropped without
sending a message, the receiver was not notified. This results in
blocking the shutdown process until all sender handles drop.

This patch adds a receiver notification when the channel is both closed
and all outstanding sends have completed.
2020-09-21 14:35:09 -07:00
Carl Lerche c0c7124a4b sync: fix missing notification during mpsc close (#2854)
When the mpsc channel receiver closes the channel, receiving should
return `None` once all in-progress sends have completed. When a sender
reserves capacity, this prevents the receiver from fully shutting down.
Previously, when the sender, after reserving capacity, dropped without
sending a message, the receiver was not notified. This results in
blocking the shutdown process until all sender handles drop.

This patch adds a receiver notification when the channel is both closed
and all outstanding sends have completed.
2020-09-21 14:29:22 -07:00
Alice RyhlandTaiki Endo 1ac10fa80a ci: update miri flags (#2851)
* ci: update miri flags

* Update 2020-09-20 to 2020-09-21

Co-authored-by: Taiki Endo <[email protected]>

Co-authored-by: Taiki Endo <[email protected]>
2020-09-21 18:57:33 +02:00
Alice RyhlandBlas Rodriguez Irizar 2b96b1773d ci: update nightly and fix all sorts of new failures (#2852)
* ci: update miri flags

* ci: fix doc warnings

* doc: fix some links

Cherry-pick of 18ed761 from #2834

* ci: cherry-pick 00a2849

From: #2793

* ci: cherry-pick 6b61212

From: #2793

Co-authored-by: Blas Rodriguez Irizar <[email protected]>
2020-09-21 18:57:27 +02:00
Taiki Endo ba8680d667 io: fix doc-cfg on AsyncSeekExt (#2846) 2020-09-19 20:40:37 +09:00
Taiki Endo 111894fef9 util: remove Slice wrapper (#2847) 2020-09-19 20:40:20 +09:00
Taiki Endo 68f7eff39e time: remove outdated todo comment (#2848) 2020-09-19 20:40:03 +09:00
NyloniciousandAlice Ryhl 207320dbbb process: fix some docs (#2843)
* fix docs for Command::status and output

Co-authored-by: Alice Ryhl <[email protected]>
2020-09-18 22:49:13 +00:00
Nylonicious 3fd043931e sync: fix some doc typos (#2838)
Fixes #2781.
2020-09-17 08:03:38 +02:00
Alice Ryhl 4c4699be00 doc: fix some links (#2834) 2020-09-13 15:50:40 +02:00
Frank Steffahn 8d2e3bc575 sync: add const constructors to RwLock, Notify, and Semaphore (#2833)
* Add const constructors to `RwLock`, `Notify`, and `Semaphore`.

Referring to the types in `tokio::sync`.
Also add `const` to `new` for the remaining atomic integers in `src/loom` and `UnsafeCell`.

Builds upon previous work in #2790
Closes #2756
2020-09-12 22:58:58 +02:00
20ef286553 sync: add const-constructors for some sync primitives (#2790)
Co-authored-by: Mikail Bagishov <[email protected]>
Co-authored-by: Eliza Weisman <[email protected]>
Co-authored-by: Alice Ryhl <[email protected]>
2020-09-12 11:55:03 +02:00
Carl Lerche 2bc9a48152 sync: tweak watch API (#2814)
Decouples getting the latest `watch` value from receiving the change
notification. The `Receiver` async method becomes
`Receiver::changed()`. The latest value is obtained from
`Receiver::borrow()`.

The implementation is updated to use `Notify`. This requires adding
`Notify::notify_waiters`. This method is generally useful but is kept
private for now.
2020-09-11 15:14:45 -07:00
Max Heller c5a9ede157 sync: write guard to read guard downgrading for sync::RwLock (#2733) 2020-09-11 22:00:04 +02:00
Zephyr Shannon ce0af8f7a1 docs: more doc fixes (#2831)
Previous docs look like they were based on the docs for
`insert_at`. Changed names of variables referred to and the
explanation of when the value will be returned and under what
condition it will be immediately available to make sense for a
Duration argument instead of an Instant.
2020-09-11 12:44:33 -07:00
Zephyr Shannon be7462e50f sync: document mpsc::bounded minimum buffer size (#2808) 2020-09-09 22:28:28 +02:00
xd009642 1550dda5cf stream: module level docs for tokio::stream (#2786) 2020-09-09 09:08:23 +02:00
John-John Tedro cbb14a7bb9 sync: add JoinHandle::abort (#2474) 2020-09-08 20:52:57 -07:00
Blas Rodriguez Irizar a0a356152e sync: remove rt-core from blocking_{send,recv} (#2825) 2020-09-08 20:50:38 -07:00
Igor Aleksanov ea79c95c67 util: implement Either type (#2821) 2020-09-08 09:14:08 +02:00
37f405bd3b io: move StreamReader and ReaderStream into tokio_util (#2788)
Co-authored-by: Mikail Bagishov <[email protected]>
Co-authored-by: Eliza Weisman <[email protected]>
2020-09-08 09:12:32 +02:00
Ivan Petkov 7c254eca44 process: make Child::kill async (#2823)
* This changes the `Child::kill` to be an async method which awaits the
  child after sending a kill signal. This avoids leaving zombie
  processes on Unix platforms if the caller forgets to await the child
  after the kill completes
* A `start_kill` method was also added on `Child` which only sends the
  kill signal to the child process. This allows for kill signals to be
  sent even outside of async contexts.
2020-09-08 06:03:25 +00:00
Blas Rodriguez IrizarandEliza Weisman f4d6ed03d9 runtime: add custom keep_alive functionality (#2809)
Co-authored-by: Eliza Weisman <[email protected]>
Fixes: #2585
2020-09-07 21:32:34 +02:00
Juan Alvarez 38ec4845d1 sync: rename Notify::notify() -> notify_one() (#2822)
Closes: #2813
2020-09-07 20:56:15 +02:00
Ivan Petkov 842d5565bd process: add Child::{wait,try_wait} (#2796)
* add Child::try_wait to mirror the std API
* replace Future impl on Child with `.wait()` method to bring our
  APIs closer to those in std and it allow us to
  internally fuse the future so that repeated calls to `wait` result in
  the same value (similar to std) without forcing the caller to fuse the
  outer future
* Also change `Child::id` to return an Option result to avoid
  allowing the caller to accidentally use the pid on Unix systems after
  the child has been reaped
* Also remove deprecated Child methods
2020-09-07 03:30:40 +00:00
George Malayil Philip d74eabc7d7 runtime: mention on JoinHandle that the generic parameter is the return type (#2819) 2020-09-05 22:44:42 +02:00
Blas Rodriguez IrizarandMikail Bagishov 6260ed907b tokio: document missing timer panics (#2801)
Fixes: #2696
Co-authored-by: Mikail Bagishov <[email protected]>
2020-09-05 20:33:42 +02:00
Zahari Dichev 048174012d fs: remove File::seek (#2810)
Fixes: #1993
Signed-off-by: Zahari Dichev <[email protected]>
2020-09-05 20:32:20 +02:00
Igor Aleksanov 38cab93330 runtime: improve runtime vs #[tokio::main] doc (#2820) 2020-09-05 20:22:47 +02:00
Zahari Dichev 171cb57fa1 io: add ReadBuf::take (#2817)
Signed-off-by: Zahari Dichev <[email protected]>
2020-09-05 11:09:54 -07:00
mental c9f5bc2915 util: add const fn support for internal LinkedList. (#2805) 2020-09-02 12:37:13 -07:00
Blas Rodriguez Irizar 5cdb6f8fd6 time: move throttle to StreamExt (#2752)
Ref: #2727
2020-09-02 11:52:31 +02:00
Blas Rodriguez Irizar 5a1a6dc90c sync: watch channel breaking changes (#2806)
Fixes: #2172
2020-09-01 20:57:48 -07:00
Nikolai Vazquez 827077409c fs: implement FromRawFd & FromRawHandle for File (#2792) 2020-08-28 09:53:51 +02:00
Lucio FrancoandEliza Weisman d600ab9a8f rt: Refactor Runtime::block_on to take &self (#2782)
Co-authored-by: Eliza Weisman <[email protected]>
2020-08-27 20:05:48 -04:00
Blas Rodriguez IrizarandLucio Franco d9d909cb4c util: Add TokioContext future (#2791)
Co-authored-by: Lucio Franco <[email protected]>
2020-08-27 11:33:43 -04:00
Blas Rodriguez Irizar 262b19ae96 Docs delay queue (#2793) 2020-08-27 10:36:59 -04:00
John-John Tedro f0328f7810 sync: implement map methods of parking_lot fame (#2771)
* sync: Implement map methods of parking_lot fame

Generally, this mimics the way `MappedRwLock*Guard`s are implemented in
`parking_lot`. By storing a raw pointer in the guards themselves
referencing the mapped data and maintaining type invariants through
`PhantomData`. I didn't try to think too much about this, so if someone
has objections I'd love to hear them.

I've also dropped the internal use of `ReleasingPermit`, since it made
the guards unecessarily large. The number of permits that need to be
released are already known by the guards themselves, and is instead
governed directly in the relevant `Drop` impls.  This has the benefit of
making the guards as small as possible, for the non-mapped variants this
means a single reference is enough.

`fmt::Debug` impls have been adjusted to behave exactly like the
delegating impls in `parking_lot`. `fmt::Display` impls have been added
for all guard types which behave the same. This does change the format
of debug impls, for which I'm not sure if we provide any guarantees.
2020-08-27 08:23:38 +02:00
xd009642 347e18bc77 sync: add blocking_recv and blocking_send in mpsc (#2684)
Fixes: #2629
2020-08-26 21:39:06 +02:00
John-John Tedro 2e7e42bca7 sync: implement map methods of parking_lot fame (#2445)
Generally, this mimics the way `MappedRwLock*Guard`s are implemented in
`parking_lot`. By storing a raw pointer in the guards themselves
referencing the mapped data and maintaining type invariants through
`PhantomData`. I didn't try to think too much about this, so if someone
has objections I'd love to hear them.

I've also dropped the internal use of `ReleasingPermit`, since it made
the guards unecessarily large. The number of permits that need to be
released are already known by the guards themselves, and is instead
governed directly in the relevant `Drop` impls.  This has the benefit of
making the guards as small as possible, for the non-mapped variants this
means a single reference is enough.

`fmt::Debug` impls have been adjusted to behave exactly like the
delegating impls in `parking_lot`. `fmt::Display` impls have been added
for all guard types which behave the same. This does change the format
of debug impls, for which I'm not sure if we provide any guarantees.
2020-08-26 20:50:35 +02:00
James Mills 0ccc09ac92 sync: fix typo in Notify documentation (#2794) 2020-08-26 20:26:43 +02:00
wspsxing 4e12299826 runtime: add thread_name_fn method to runtime::Builder (#1921)
Fixes: #1907
2020-08-24 15:14:20 +02:00
Mikail Bagishov 30d4ec0a20 io: add ReaderStream (#2714) 2020-08-23 17:47:20 +02:00
Carl Lerche 9d58b70151 sync: move CancellationToken to tokio-util (#2721)
* sync: move CancellationToken to tokio-util

The `CancellationToken` utility is only available with the
`tokio_unstable` flag. This was done as the API is not final, but it
adds friction for users.

This patch moves `CancellationToken` to tokio-util where it is generally
available. The tokio-util crate does not have any constraints on
breaking change releases.

* fix clippy

* clippy again
2020-08-23 17:45:52 +02:00
caranatar fde72bf047 net: Add examples to UnixDatagram (#2765)
* net: adding examples for UnixDatagram

Adding examples to documentation for UnixDatagram

* net: document named UnixDatagrams persistence

Add documentation to indicate that named UnixDatagrams 'leak'
socket files after execution.

* net: rustfmt issue in UnixDatagram

Fixing rustfmt issue in UnixDatagram

* net: adding examples for UnixDatagram

Fixes: #2686
Refs: #1679
Refs: #1111
2020-08-23 17:45:10 +02:00
Blas Rodriguez Irizar 138eef3526 test: implement Drop for Mock to panic w/ unconsumed data (#2704) 2020-08-20 15:48:27 -04:00
Sean McArthur c393236dfd io: change AsyncRead to use a ReadBuf (#2758)
Works towards #2716. Changes the argument to `AsyncRead::poll_read` to
take a `ReadBuf` struct that safely manages writes to uninitialized memory.
2020-08-13 20:15:01 -07:00
Carl Lerche 71da06097b chore: reformat some imports for consistency (#2768) 2020-08-13 08:10:00 -07:00
Carl Lerche 8feebab7cd io: rewrite slab to support compaction (#2757)
The I/O driver uses a slab to store per-resource state. Doing this
provides two benefits. First, allocating state is streamlined. Second,
resources may be safely indexed using a `usize` type. The `usize` is
used passed to the OS's selector when registering for receiving events.

The original slab implementation used a `Vec` backed by `RwLock`. This
primarily caused contention when reading state. This implementation also
only **grew** the slab capacity but never shrank. In #1625, the slab was
rewritten to use a lock-free strategy. The lock contention was removed
but this implementation was still grow-only.

This change adds the ability to release memory. Similar to the previous
implementation, it structures the slab to use a vector of pages. This
enables growing the slab without having to move any previous entries. It
also adds the ability to release pages. This is done by introducing a
lock when allocating/releasing slab entries. This does not impact
benchmarks, primarily due to the existing implementation not being
"done" and also having a lock around allocating and releasing.

A `Slab::compact()` function is added. Pages are iterated. When a page
is found with no slots in use, the page is freed. The `compact()`
function is called occasionally by the I/O driver.

Fixes #2505
2020-08-11 22:28:43 -07:00
Kruno Tomola Fabro 674985d9fb fs: add comment explaing File flush is a no-op (#2761)
Signed-off-by: Kruno Tomola Fabro <[email protected]>
2020-08-11 11:51:02 -07:00
Carl Lerche 77e6bb8d06 chore: bump MSRV to 1.45 (#2759)
As 0.3 is a breaking change, the minimum supported Rust version can be
changed.
2020-08-10 21:39:10 -07:00
Cameron Taggart d8490c1626 io: use stderr in stderr documentation (#2746) 2020-08-09 09:37:55 +02:00
Blas Rodriguez Irizar e9adac288e sync: typo in impl Semaphore (#2745) 2020-08-09 08:42:04 +02:00
Blas Rodriguez Irizar 27bfe52bba sync: show correct permits in fmt::Debug (#2750)
Fixes: #2744
2020-08-08 13:41:55 -07:00
Carl Lerche 6ccefb77e2 chore: prepare for v0.3 breaking changes (#2747)
Bug fixes will be applied to the v0.2.x branch.
2020-08-07 20:27:53 -07:00
Blas Rodriguez Irizar 1167c09ae8 process: document remote killing for Child (#2736)
* process: document remote killing for Child

Fixes: #2703
2020-08-05 00:59:10 +00:00
南浦月 7276d47072 net: impl ToSocketAddrs for (String, u16) (#2724) 2020-08-01 15:27:14 +02:00
Max Bruckner 9f0b6d3166 sync: suspectible -> susceptible (#2732) 2020-07-31 22:10:31 +02:00
Mikail Bagishov 8fda719845 sync: better Debug for Mutex (#2725) 2020-07-31 21:00:23 +02:00
Émile Grégoire 646fbae765 rt: fix potential leak during runtime shutdown (#2649)
JoinHandle of threads created by the pool are now tracked and properly joined at
shutdown. If the thread does not return within the timeout, then it's not joined and
left to the OS for cleanup.

Also, break a cycle between wakers held by the timer and the runtime.

Fixes #2641, #2535
2020-07-28 20:43:19 -07:00
Kevin Leimkuhler 1562bb3144 add: Add UdpSocket::{try_send,try_send_to} methods (#1979) 2020-07-28 17:09:56 -07:00
Jon Gjengset 0366a3e6d1 Reset coop budget when blocking in block_on (#2711)
Previously, we would fail to reset the coop budget in this case, making
it so that `coop::poll_proceed` would perpetually yield `Poll::Pending`
in nested executers even when run in `block_in_place`.

This is also a further improvement on #2645.
2020-07-28 19:58:33 -04:00
Alice Ryhl 03b68f4e75 io: rewrite read_to_end and read_to_string (#2560)
The new implementation changes the behavior such that set_len is called
after poll_read. The motivation of this change is that it makes it much
more obvious that a rouge panic won't give the caller access to a vector
containing exposed uninitialized memory. The new implementation also
makes sure to not zero memory twice.

Additionally, it makes the various implementations more consistent with
each other regarding the naming of variables, and whether we store how many
bytes we have read, or how many were in the container originally.

Fixes: #2544
2020-07-28 15:45:02 -07:00
084fcd7954 chore: update parking_lot dependency to 0.11.0 (#2676)
Co-authored-by: Jasper Hugo <[email protected]>
Co-authored-by: Alice Ryhl <[email protected]>
2020-07-28 15:43:08 -07:00
Alice Ryhl cc2c358d25 chore: document issue labels (#2708) 2020-07-28 15:41:43 -07:00
Jeb Rosen 51e7933c35 ci: add information to the rustfmt check, hinting at the necessary fix (#2673) 2020-07-28 13:30:33 -07:00
Blas Rodriguez IrizarandAlice Ryhl 027351dd3a macros: silence unreachable_code warning in select! (#2678)
Solves #2665 by adding #[allow(unreachable_code)] inside a branch
matching arm.

Co-authored-by: Alice Ryhl <[email protected]>
2020-07-28 13:10:07 -07:00
Alice Ryhl ff6130da65 time: interval Stream impl requires stream feature (#2695)
Fixes: #1878
2020-07-26 21:23:06 +02:00
Alice Ryhl 018e345add time: fix incorrect argument name in doc (#2691) 2020-07-26 21:22:56 +02:00
Alice Ryhl e3e7cdeaff macros: document basic_scheduler option (#2697) 2020-07-26 09:51:56 -07:00
Felix Giese 7f29acd964 time: fix resetting expired timers causing panics (#2587)
* Add Unit Test demonstrating the issue

This test demonstrates a panic that occurs when the user inserts an
item with an instant in the past, and then tries to reset the timeout
using the returned key

* Guard reset_at against removals of expired items

Trying to remove an already expired Timer Wheel entry (called by
DelayQueue.reset()) causes panics in some cases as described in (#2573)

This prevents this panic by removing the item from the expired queue and
not the wheel in these cases

Fixes: #2473
2020-07-26 09:40:29 +02:00
jean-airoldie 2d97d5ad15 net: add try_recv/from & try_send/to to UnixDatagram (#1677)
This allows nonblocking sync send & recv operations on the socket.
2020-07-25 12:34:47 +02:00
Nikhil Benesch d1744bf260 time: report correct error for timers that exceed max duration (#2023)
Closes #1953
2020-07-24 22:03:37 -07:00
Carl Lerche de7b8914a9 chore: add ci job that depends on all tests (#2690)
This makes it a bit easier to block a PR from landing without CI
passing.
2020-07-24 21:17:37 -07:00
Carl Lerche 9943acda81 chore: complete CI migration to Github Actions (#2680) 2020-07-24 16:28:24 -07:00
Alice Ryhl 4fca1974e9 net: ensure that unix sockets have both split and into_split (#2687)
The documentation build failed with errors such as

error: `[read]` public documentation for `take` links to a private item
    --> tokio/src/io/util/async_read_ext.rs:1078:9
     |
1078 | /         /// Creates an adaptor which reads at most `limit` bytes from it.
1079 | |         ///
1080 | |         /// This function returns a new instance of `AsyncRead` which will read
1081 | |         /// at most `limit` bytes, after which it will always return EOF
...    |
1103 | |         /// }
1104 | |         /// ```
     | |_______________^
     |
note: the lint level is defined here
    --> tokio/src/lib.rs:13:9
     |
13   | #![deny(intra_doc_link_resolution_failure)]
     |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
     = note: the link appears in this line:

             bytes read and future calls to [`read()`][read] may succeed.
2020-07-24 12:56:38 -07:00
Blas Rodriguez Irizar 08872c55d1 doc: feature flags in README (#2682) 2020-07-24 20:51:34 +02:00
xd009642 844d9c6acb rt: document how #[tokio::main] is expanded (#2683) 2020-07-24 08:32:15 -07:00
cssivision ff7125ec7b net: introduce split on UnixDatagram (#2557) 2020-07-23 22:03:47 -07:00
Taiki Endo 7a60a0b362 io: always re-export std::io (#2606) 2020-07-23 22:00:27 -07:00
John Doneth 94b64cd70d udp: Fix UdpFramed with regards to Decode (#1445) 2020-07-23 11:27:43 -04:00
Alice Ryhl b5d2b0d05b doc: fix links to new website (#2674) 2020-07-22 20:35:02 -07:00
Sean McArthur 0e090b7ae2 io: add io::duplex() as bidirectional reader/writer (#2661)
`duplex` returns a pair of connected `DuplexStream`s.

`DuplexStream` is a bidirectional type that can be used to simulate IO,
but over an in-process piece of memory.
2020-07-22 15:07:39 -07:00
Eliza Weisman 21f726041c chore: prepare to release 0.2.22 (#2672)
# 0.2.22 (July 2!, 2020)

### Fixes
- docs: misc improvements (#2572, #2658, #2663, #2656, #2647, #2630, #2487, #2621,
  #2624, #2600, #2623, #2622, #2577, #2569, #2589, #2575, #2540, #2564, #2567,
  #2520, #2521, #2493)
- rt: allow calls to `block_on` inside calls to `block_in_place` that are
  themselves inside `block_on` (#2645)
- net: fix non-portable behavior when dropping `TcpStream` `OwnedWriteHalf` (#2597)
- io: improve stack usage by allocating large buffers on directly on the heap
  (#2634)
- io: fix unsound pin projection in `AsyncReadExt::read_buf` and
  `AsyncWriteExt::write_buf` (#2612)
- io: fix unnecessary zeroing for `AsyncRead` implementors (#2525)
- io: Fix `BufReader` not correctly forwarding `poll_write_buf` (#2654)
- io: fix panic in `AsyncReadExt::read_line` (#2541)

### Changes
- coop: returning `Poll::Pending` no longer decrements the task budget (#2549)

### Added
- io: little-endian variants of `AsyncReadExt` and `AsyncWriteExt` methods
  (#1915)
- task: add [`tracing`] instrumentation to spawned tasks (#2655)
- sync: allow unsized types in `Mutex` and `RwLock` (via `default` constructors)
  (#2615)
- net: add `ToSocketAddrs` implementation for `&[SocketAddr]` (#2604)
- fs: add `OpenOptionsExt` for `OpenOptions` (#2515)
- fs: add `DirBuilder` (#2524)

[`tracing`]: https://crates.io/crates/tracing

Signed-off-by: Eliza Weisman <[email protected]>
2020-07-21 17:52:16 -07:00
Kornel c344aac925 sync: support larger number of semaphore permits (#2607) 2020-07-21 16:51:42 -07:00
Zephyr Shannon cbb4abc8ae chore: add audit check (#2595) 2020-07-21 15:32:54 -07:00
Alice Ryhl 14723f9786 doc: update links in README.md and CONTRIBUTING.md (#2609) 2020-07-21 15:31:26 -07:00
04a2826084 provide a way to drop a runtime in an async context (#2646)
Dropping a runtime normally involves waiting for any outstanding blocking tasks
to complete. When this drop happens in an asynchronous context, we previously
would issue a cryptic panic due to trying to block in an asynchronous context.

This change improves the panic message, and adds a `shutdown_blocking()` function
which can be used to shutdown a runtime without blocking at all, as an out for
cases where this really is necessary.

Co-authored-by: Bryan Donlan <[email protected]>
Co-authored-by: Alice Ryhl <[email protected]>
2020-07-21 15:26:47 -07:00
Mikail Bagishov 28a93e6044 Update doc comments (#2572)
* Update doc comments

* Remove trailing whitespace
2020-07-20 14:50:59 -07:00
Markus Westerlind dd28831e13 io: Forward poll_write_buf on BufReader (#2654)
For some yet unknown reason using the default on a wrapped `Bufreader<TcpStream>`
causes the hyper server to sometimes fail to send the entire body in the
response.

This fixes that problem for us and ensures that hyper has a chance to
use vectored IO (making it a good change regardless of the mentioned
bug)
2020-07-20 14:49:38 -07:00
nicolaiunrein 6dcce1901a sync: remove misleading comment (#2666)
We are not returning the old value. I suppose this was once indented and this
is a leftover.
2020-07-20 14:30:28 -07:00
Blas Rodriguez Irizar 32f46d7b88 time: improve Entry field comment (#2671)
Applying a suggestion from #2617 to make the sentence more clear.
2020-07-20 14:29:25 -07:00
Alice Ryhl 356c81c977 dns: document that strings require the DNS feature (#2663) 2020-07-20 14:27:34 -07:00
Alice Ryhl d685bceb03 sync: "which kind of mutex?" section added to doc (#2658) 2020-07-20 19:15:15 +02:00
Alice Ryhl b094ee90e2 chore: fix new manual_non_exhaustive clippy lint (#2669)
Our minimum supported Rust version does not allow switching to `#[non_exhaustive]`.
2020-07-20 09:23:19 -07:00
Evan Cameron 7e4edb8963 io: add little endian variants for AsyncRead/WriteExt (#1915) 2020-07-16 07:50:43 +02:00
bdonlanandBryan Donlan fc63fa2606 rt: allow block_on inside block_in_place inside block_on (#2645)
A fast path in block_on_place was failing to call exit() in the case where we
were in a block_on call.

Fixes: #2639

Co-authored-by: Bryan Donlan <[email protected]>
2020-07-14 21:31:13 -07:00
Eliza Weisman b9e3d2edde task: add Tracing instrumentation to spawned tasks (#2655)
## Motivation

When debugging asynchronous systems, it can be very valuable to inspect
what tasks are currently active (see #2510). The [`tracing` crate] and
related libraries provide an interface for Rust libraries and
applications to emit and consume structured, contextual, and async-aware
diagnostic information. Because this diagnostic information is
structured and machine-readable, it is a better fit for the
task-tracking use case than textual logging — `tracing` spans can be
consumed to generate metrics ranging from a simple counter of active
tasks to histograms of poll durations, idle durations, and total task
lifetimes. This information is potentially valuable to both Tokio users
*and* to maintainers.

Additionally, `tracing` is maintained by the Tokio project and is
becoming widely adopted by other libraries in the "Tokio stack", such as
[`hyper`], [`h2`], and [`tonic`] and in [other] [parts] of the broader Rust
ecosystem. Therefore, it is suitable for use in Tokio itself.

[`tracing` crate]: https://github.com/tokio-rs/tracing
[`hyper`]: https://github.com/hyperium/hyper/pull/2204
[`h2`]: https://github.com/hyperium/h2/pull/475
[`tonic`]: https://github.com/hyperium/tonic/blob/570c606397e47406ec148fe1763586e87a8f5298/tonic/Cargo.toml#L48
[other]: https://github.com/rust-lang/chalk/pull/525
[parts]: https://github.com/rust-lang/compiler-team/issues/331

## Solution

This PR is an MVP for instrumenting Tokio with `tracing` spans. When the
"tracing" optional dependency is enabled, every spawned future will be
instrumented with a `tracing` span.

The generated spans are at the `TRACE` verbosity level, and have the
target "tokio::task", which may be used by consumers to filter whether
they should be recorded. They include fields for the type name of the
spawned future and for what kind of task the span corresponds to (a
standard `spawn`ed task, a local task spawned by `spawn_local`, or a
`blocking` task spawned by `spawn_blocking`). Because `tracing` has
separate concepts of "opening/closing" and "entering/exiting" a span, we
enter these spans every time the spawned task is polled. This allows
collecting data such as:

 - the total lifetime of the task from `spawn` to `drop`
 - the number of times the task was polled before it completed
 - the duration of each individual time that the span was polled (and
   therefore, aggregated metrics like histograms or averages of poll
   durations)
 - the total time a span was actively being polled, and the total time
   it was alive but **not** being polled
 - the time between when the task was `spawn`ed and the first poll

As an example, here is the output of a version of the `chat` example
instrumented with `tracing`:
![image](https://user-images.githubusercontent.com/2796466/87231927-e50f6900-c36f-11ea-8a90-6da9b93b9601.png)
And, with multiple connections actually sending messages:
![trace_example_1](https://user-images.githubusercontent.com/2796466/87231876-8d70fd80-c36f-11ea-91f1-0ad1a5b3112f.png)


I haven't added any `tracing` spans in the example, only converted the
existing `println!`s to `tracing::info` and `tracing::error` for
consistency. The span durations in the above output are generated by
`tracing-subscriber`. Of course, a Tokio-specific subscriber could
generate even more detailed statistics, but that's follow-up work once
basic tracing support has been added.

Note that the `Instrumented` type from `tracing-futures`, which attaches
a `tracing` span to a future, was reimplemented inside of Tokio to avoid
a dependency on that crate. `tracing-futures` has a feature flag that
enables an optional dependency on Tokio, and I believe that if another
crate in a dependency graph enables that feature while Tokio's `tracing`
support is also enabled, it would create a circular dependency that
Cargo wouldn't be able to handle. Also, it avoids a dependency for a
very small amount of code that is unlikely to ever change.

There is, of course, room for plenty of future work here. This might 
include:

 - instrumenting other parts of `tokio`, such as I/O resources and 
   channels (possibly via waker instrumentation)
 - instrumenting the threadpool so that the state of worker threads
   can be inspected
 - writing `tracing-subscriber` `Layer`s to collect and display
   Tokio-specific data from these traces
 - using `track_caller` (when it's stable) to record _where_ a task 
   was `spawn`ed from

However, this is intended as an MVP to get us started on that path.

Signed-off-by: Eliza Weisman <[email protected]>
2020-07-13 16:46:59 -07:00
Antoine Murat a23d2b2274 doc: fix typo from "Rust langague" to "Rust language" (#2656)
* doc: fix typo in addr

* doc: fix typo in stream

* doc: fix typo in stream/collect
2020-07-13 08:48:02 -07:00
Carl Lerche 98e7831479 net: fix OwnedWriteHalf behavior on drop (#2597)
Previously, dropping the Write handle would issue a `shutdown(Both)`. However,
shutting down the read half is not portable and not the correct action to take.

This changes the behavior of OwnedWriteHalf to only perform a `shutdown(Write)`
on drop.
2020-07-12 19:25:58 -07:00
alborq 8411a6945f example: close pending connection on proxy exemple (#2590) 2020-07-12 20:33:20 +02:00
Markus WesterlindandAlice Ryhl f69e5bfb87 fix: Update the docs of "pause" to state that time will still advance (#2647)
* doc: Update the docs of "pause" to state that time will still advance

This was changed in #2059. This had me extremely confused for some time
as my timeouts fired immediately, without the wrapped future that were
waiting on IO to actually run long enough.

I am not sure about the exact wording here but this had me very confused
for some time. Deprecating "pause" and giving it a more accurate name
may be a good idea as well.

```rust
async fn timeout_advances() {
    time::pause();

    timeout(ms(1), async {
        // Change to 1 and the this future resolve, 2 or
        // more and the timeout resolves
        for _ in 0..2 {
            tokio::task::yield_now().await
        }
    })
    .await
    .unwrap();
}

```

* Update tokio/src/time/clock.rs

Co-authored-by: Alice Ryhl <[email protected]>

Co-authored-by: Alice Ryhl <[email protected]>
2020-07-10 09:11:01 -07:00
Taiki Endo 2aa8751261 ci: use latest stable compiler on macOS ci (#2643) 2020-07-05 18:48:47 +02:00
htrefil be02d36a86 io: allocate buffer directly on heap (#2634) 2020-07-01 14:57:25 -07:00
GokulandAlice Ryhl cf2c05317c sync: update oneshot::Receiver::close doc link (#2630)
Co-authored-by: Alice Ryhl <[email protected]>
2020-06-25 10:43:22 -07:00
João Oliveira f0b2b708a7 test: fix new clippy lint (#2631) 2020-06-25 17:32:16 +02:00
Artem Pyanykh f75e5a7ef4 docs: BufWriter does not flush on drop (#2487)
Fixes: #2484
2020-06-18 21:42:28 +02:00
Jeb Rosen 0ab28627e2 docs: remove unneeded doc from AsyncReadExt::read_ext() (#2621)
This paragraph from `std::io::Read::read_ext()` applies to
*implementors* of `Read`. Since `AsyncReadExt` can't and shouldn't be
implemented outside of this crate, this documentation is unnecessary.
2020-06-18 21:36:06 +02:00
Alice Ryhl a43ec11daf sync: channel doc grammar change (#2624) 2020-06-18 21:22:29 +02:00
Alice Ryhl 3db22e29d1 sync: documentation for mpsc channels (#2600) 2020-06-17 22:14:09 +02:00
Craig Pastro e2adf2612d time: add example using interval to the time module (#2623) 2020-06-16 11:25:08 +02:00
s0lst1ce 2bc6bc14a8 doc: fix typo on select macro (#2622) 2020-06-15 15:30:50 +02:00
Taiki Endo d2f81b506a sync: allow unsized types in Mutex and RwLock (#2615) 2020-06-13 03:32:51 +09:00
Taiki Endo 6b6e76080a chore: reduce pin related unsafe code (#2613) 2020-06-12 19:49:39 +09:00
Taiki Endo 68b4ca9f55 ci: pin compiler version in miri tests (#2614) 2020-06-12 18:37:06 +09:00
Taiki Endo 1769f65d37 io: fix unsound pin projection in read_buf and write_buf (#2612) 2020-06-12 14:28:23 +09:00
Taiki Endo 1636910f0a net: impl ToSocketAddrs for &[SocketAddr] (#2604) 2020-06-11 11:06:15 +02:00
johnnydai0 adaa6849a5 docs: fix the link of contributing guide (#2577) 2020-06-11 10:51:49 +02:00
Alice Ryhl 0a422593f0 doc: add sleep alias to delay_for (#2589) 2020-06-10 23:30:08 +02:00
Taiki Endo d22301967b chore: fix macOS ci on github actions (#2602) 2020-06-11 04:51:24 +09:00
Taiki Endo 4010335c84 chore: fix ci failure on master (#2593)
* Fix clippy warnings
* Pin rustc version to 1.43.1 in macOS

Refs: https://github.com/rust-lang/rust/issues/73030
2020-06-07 20:38:02 +09:00
‏‏Dave be4577e22f io: fix typo on BufReader (#2569) 2020-06-02 08:49:47 +02:00
xliiv e70a1b6d64 docs: use intra-links in the docs (#2575) 2020-05-31 18:49:04 +02:00
Mikail Bagishov 9264b837d8 test: fix all clippy lints in tests (#2573) 2020-05-31 14:49:22 +02:00
Mikail Bagishov db0d6d75b3 chore: fix clippy errors (#2571) 2020-05-30 14:06:03 -07:00
xliiv f2f30d4cf6 docs: replace method links with intra-links (#2540) 2020-05-30 20:18:01 +02:00
Geoffry Song c624cb8ce3 io: update AsyncBufRead documentation (#2564) 2020-05-29 14:00:13 +02:00
Mathspy f7574d9023 net: add note about into_split's drop (#2567)
This took me a bit to catch on to because I didn't really think there was any reason to investigate the individual documentation of each half. As someone dealing with TCP streams directly for first time (without previous experience from other languages) this caught me by surprise
2020-05-28 10:11:55 +02:00
Alice Ryhl 954f2b7304 io: fix panic in read_line (#2541)
Fixes: #2532
2020-05-24 23:26:33 +02:00
Geoff Shannon d562e58871 ci: start migrating CI to Github Actions (#2531)
This migrates test_tokio, test_sub_crates, and test_integration to
GitHub Actions, as the first step in the migration from Azure Pipelines.
2020-05-25 01:46:48 +09:00
Jon Gjengset 9f63911adc coop: Undo budget decrement on Pending (#2549)
This patch updates the coop logic so that the budget is only decremented
if a future makes progress (that is, if it returns `Ready`). This is
realized by restoring the budget to its former value after
`poll_proceed` _unless_ the caller indicates that it made progress.

The thinking here is that we always want tasks to make progress when we
poll them. With the way things were, if a task polled 128 resources that
could make no progress, and just returned `Pending`, then a 129th
resource that _could_ make progress would not be polled. Worse yet, this
could manifest as a deadlock, if the first 128 resources were all
_waiting_ for the 129th resource, since it would _never_ be polled.

The downside of this change is that `Pending` resources now do not take
up any part of the budget, even though they _do_ take up time on the
executor. If a task is particularly aggressive (or unoptimized), and
polls a large number of resources that cannot make progress whenever it
is polled, then coop will allow it to run potentially much longer before
yielding than it could before. The impact of this should be relatively
contained though, because tasks that behaved in this way in the past
probably ignored `Pending` _anyway_, so whether a resource returned
`Pending` due to coop or due to lack of progress may not make a
difference to it.
2020-05-21 17:07:23 -04:00
Mikail Bagishov 1e54a35325 io: remove zeroing for AsyncRead implementors (#2525) 2020-05-21 19:42:28 +02:00
Charles Hovine 4f4f4807c3 fs: implement OpenOptionsExt for OpenOptions (#2515)
Trait OpenOptionsExt is now implemented for fs::OpenOption.

In order to access the underlying std::fs::OpenOptions wrapped in
tokio's OpenOption, an as_inner_mut method was added to OpenOption,
only visible to the parent module.

Fixes: #2366
2020-05-21 17:18:58 +02:00
Dmitri Shkurski 8fda5f1984 fs: add DirBuilder (#2524)
The initial idea was to implement  a thin wrapper  around an internally
held `std::fs::DirBuilder` instance.  This, however, didn't work due to
`std::fs::DirBuilder` not having a Copy/Clone traits implemented, which
are necessary  for constructing an instance to move-capture it  into  a
closure.

Instead,  we mirror `std::fs::DirBuilder` configuration by  storing the
`recursive` and (unix-only) `mode`  parameters locally,  which are then
used to construct an `std::fs::DirBuilder` instance on-the-fly.

This commit also mirrors the (unix-only) DirBuilderExt trait from std.

Fixes: #2369
2020-05-21 12:49:36 +02:00
Alice Ryhl 7cb5e3460c stream: update StreamExt::merge doc (#2520) 2020-05-21 11:54:52 +02:00
Alice Ryhl 9b81580be6 github: update issue templates (#2552) 2020-05-21 09:45:27 +02:00
Geoff Shannon 9b6744cc8e tokio-macros: warn about renaming the tokio dependency (#2521) 2020-05-20 21:50:41 +02:00
Ondřej Hruška 4563699838 codec: add Framed::read_buffer_mut (#2546)
Adds a method to retrieve a mutable reference to the Framed stream's read buffer.
This makes it possible to e.g. externally clear the buffer to prevent the codec from
parsing stale data.
2020-05-20 21:45:03 +02:00
Jake Goulding f48065910e doc: fix two -> to typo (#2527) 2020-05-16 16:31:47 +02:00
ZSL a5c1a7de03 sync: document maximum number of permits (#2539) 2020-05-16 12:41:45 +02:00
Sunjay Varma a343b1d180 Clarifying that Handle::current must be called on a thread managed by tokio (#2493) 2020-05-14 12:28:56 -04:00
Geoff Shannon b44ab27359 docs: improve discoverability of codec module (#2523) 2020-05-14 16:51:55 +02:00
Carl Lerche 02661ba30a chore: prepare v0.2.21 release (#2530) 2020-05-13 11:45:02 -07:00
Carl Lerche fb7dfcf432 sync: use intrusive list strategy for broadcast (#2509)
Previously, in the broadcast channel, receiver wakers were passed to the
sender via an atomic stack with allocated nodes. When a message was
sent, the stack was drained. This caused a problem when many receivers
pushed a waiter node then dropped. The waiter node remained indefinitely
in cases where no values were sent.

This patch switches broadcast to use the intrusive linked-list waiter
strategy used by `Notify` and `Semaphore.
2020-05-12 15:09:43 -07:00
Alice Ryhl a32f918671 chore: change norun to no_run (#2518)
I was building the docs and got the following documentation warning:

warning: unknown attribute `norun`. Did you mean `no_run`?
  --> tokio/src/time/throttle.rs:13:1
   |
13 | / /// Slows down a stream by enforcing a delay between items.
14 | | /// They will be produced not more often than the specified interval.
15 | | ///
16 | | /// # Example
...  |
31 | | /// # }
32 | | /// ```
   | |_______^
   |
   = help: the code block will either not be tested if not marked as a rust one or will be run (which you might not want)
2020-05-12 16:42:24 +02:00
Plecra 221f421464 codec: rewrite of codec::Framed (#2368)
Framed was designed to encapsulate both AsyncRead and AsyncWrite so
that it could wrap two-way connections. It used Fuse to manage the pinned
io object between the FramedWrite and FramedRead structs.

I replaced the Fuse struct by isolating the state used in reading and
writing, and making the code generic over that instead. This means
the FramedImpl struct now has a parameter for the state, and contains
the logic for both directions. The Framed* structs are now simply
wrappers around this type

Hopefully removing the `Pin` handling made things easier to
understand, too.
2020-05-12 13:47:38 +02:00
Jeb Rosen 1cc0168335 macros: disambiguate the built-in #[test] attribute in macro expansion (#2503)
`tokio::test` and related macros now use the absolute path
`::core::prelude::v1::test` to refer to the built-in `test` macro.

This absolute path was introduced in rust-lang/rust#62086.
2020-05-12 09:09:59 +02:00
Patrick Mooney 67220eac37 tokio: add support for illumos target (#2486)
Although very similar in many regards, illumos and Solaris have been
diverging since the end of OpenSolaris.  With the addition of illumos as
a Rust target, it must be wired into the same interfaces which it was
consuming when running under the 'solaris' target.
2020-05-11 22:23:49 +02:00
Boqin QinandAlice Ryhl 3ba818a177 io: add doc warning about concurrently calling poll_read/write_ready (#2439)
Co-authored-by: Alice Ryhl <[email protected]>
Fixes: #2429
2020-05-11 21:59:46 +02:00
Danny Browning 6aeeeff6e8 io: add mio::Ready argument to PollEvented (#2419)
Add additional methods to allow PollEvented to be created with an appropriate
mio::Ready state, so that it can be properly registered with the reactor.

Fixes #2413
2020-05-11 21:47:03 +02:00
Tom Ciborski a75fe38ba5 stream: fix documentation on filter_map (#2511) 2020-05-10 23:08:05 +02:00
Karl Voss adce911b02 doc: add link fragments to CONTRIBUTING.md (#2507)
Added GitHub style link fragments to the `[Commit Squashing]`
sections of CONTRIBUTING.md

Fixes: #2506
2020-05-08 14:40:23 +02:00
zeroed 8565a98601 docs: fix links in tokio::sync (#2491)
Fixes: #2489
2020-05-07 16:26:09 -07:00
Carl Lerche bff21aba6c rt: set task budget after block_in_place call (#2502)
In some cases, when a call to `block_in_place` completes, the runtime is
reinstated on the thread. In this case, the task budget must also be set
in order to avoid starving other tasks on the worker.
2020-05-07 16:25:04 -07:00
Adam C. Foltzer 07533a5255 rt: add Handle::spawn_blocking method (#2501)
This follows a similar pattern to `Handle::spawn` to add the
blocking spawn capabilities to `Handle`.
2020-05-07 16:24:24 -07:00
Carl Lerche 4748b2571f rt: simplify coop implementation (#2498)
Simplifies coop implementation. Prunes unused code, create a `Budget`
type to track the current budget.
2020-05-06 19:02:07 -07:00
Lucio Franco 66fef4a9bc Remove tokio-tls from master (#2497) 2020-05-06 17:30:01 -04:00
Lucio Franco 13e2a366de tls: Deprecate in favor of tokio-native-tls (#2485) 2020-05-06 16:10:57 -04:00
Carl Lerche cc8a662598 sync: simplify the broadcast channel (#2467)
Replace an ad hoc read/write lock with RwLock. Use
The parking_lot RwLock when possible.
2020-05-06 07:37:44 -07:00
Carl Lerche 264ae3bdb2 sync: move CancellationToken tests (#2477)
In preparation of work on `CancellationToken` internals, the tests are
moved into `tests/` and are updated to not depend on internals.
2020-05-03 12:35:47 -07:00
Matthias Einwag 187af2e6a3 sync: add CancellationToken (#2263)
As a first step towards structured concurrency, this change adds a
CancellationToken for graceful cancellation of tasks.

The task can be awaited by an arbitrary amount of tasks due to the usage
of an intrusive list.

The token can be cloned. In addition to this child tokens can be derived.
When the parent token gets cancelled, all child tokens will also get
cancelled.
2020-05-02 14:19:28 -07:00
zeroed 31315b9463 doc: remove reference to the Sink trait in the MPSC documentation (#2476)
The implementation of the Sink trait was removed in 8a7e5778.

Fixes: #2464
Refs: #2389
2020-05-02 13:41:40 -07:00
Eliza Weisman 20b5df9037 task: fix LocalSet having a single shared task budget (#2462)
## Motivation

Currently, an issue exists where a `LocalSet` has a single cooperative
task budget that's shared across all futures spawned on the `LocalSet`
_and_ by any future passed to `LocalSet::run_until` or
`LocalSet::block_on`. Because these methods will poll the `run_until`
future before polling spawned tasks, it is possible for that task to
_always_ deterministically starve the entire `LocalSet` so that no local
tasks can proceed. When the completion of that future _itself_ depends
on other tasks on the `LocalSet`, this will then result in a deadlock,
as in issue #2460.

A detailed description of why this is the case, taken from [this 
comment][1]:

`LocalSet` wraps each time a local task is run in `budget`:
https://github.com/tokio-rs/tokio/blob/947045b9445f15fb9314ba0892efa2251076ae73/tokio/src/task/local.rs#L406

This is identical to what tokio's other schedulers do when running
tasks, and in theory should give each task its own budget every time
it's polled. 

_However_, `LocalSet` is different from other schedulers. Unlike the
runtime schedulers, a `LocalSet` is itself a future that's run on
another scheduler, in `block_on`.  `block_on` _also_ sets a budget:
https://github.com/tokio-rs/tokio/blob/947045b9445f15fb9314ba0892efa2251076ae73/tokio/src/runtime/basic_scheduler.rs#L131

The docs for `budget` state that:
https://github.com/tokio-rs/tokio/blob/947045b9445f15fb9314ba0892efa2251076ae73/tokio/src/coop.rs#L73

This means that inside of a `LocalSet`, the calls to `budget` are
no-ops. Instead, each future polled by the `LocalSet` is subtracting
from a single global budget.

`LocalSet`'s `RunUntil` future polls the provided future before polling
any other tasks spawned on the local set:
https://github.com/tokio-rs/tokio/blob/947045b9445f15fb9314ba0892efa2251076ae73/tokio/src/task/local.rs#L525-L535

In this case, the provided future is `JoinAll`. Unfortunately, every
time a `JoinAll` is polled, it polls _every_ joined future that has not
yet completed. When the number of futures in the `JoinAll` is >= 128,
this means that the `JoinAll` immediately exhausts the task budget. This
would, in theory, be a _good_ thing --- if the `JoinAll` had a huge
number of `JoinHandle`s in it and none of them are ready, it would limit
the time we spend polling those join handles. 

However, because the `LocalSet` _actually_ has a single shared task
budget, this means polling the `JoinAll` _always_ exhausts the entire
budget. There is now no budget remaining to poll any other tasks spawned
on the `LocalSet`, and they are never able to complete.

[1]: https://github.com/tokio-rs/tokio/issues/2460#issuecomment-621403122

## Solution

This branch solves this issue by resetting the task budget when polling
a `LocalSet`. I've added a new function to `coop` for resetting the task
budget to `UNCONSTRAINED` for the duration of a closure, and thus
allowing the `budget` calls in `LocalSet` to _actually_ create a new
budget for each spawned local task. Additionally, I've changed
`LocalSet` to _also_ ensure that a separate task budget is applied to
any future passed to `block_on`/`run_until`.

Additionally, I've added a test reproducing the issue described in
#2460. This test fails prior to this change, and passes after it.

Fixes #2460

Signed-off-by: Eliza Weisman <[email protected]>
2020-04-30 15:19:17 -07:00
Carl Lerche fa9743f0d4 macros: scoped_thread_local should be private (#2470)
Do not export the `scoped_thread_local` macro outside of the Tokio
crate. This is not considered a breaking change as the macro never
worked if used from outside of the crate due to the generated code
referencing crate-private types.
2020-04-30 14:32:47 -07:00
Hanif Ariffin 7a89d66513 io: add get_mut, get_ref and into_inner to Lines (#2450) 2020-04-30 12:44:19 +02:00
Eliza Weisman 45773c5641 mutex: add OwnedMutexGuard for Arc<Mutex<T>>s (#2455)
This PR adds a new `OwnedMutexGuard` type and `lock_owned` and
`try_lock_owned` methods for `Arc<Mutex<T>>`.  This is pretty much the
same as the similar APIs added in #2421. 

I've also corrected some existing documentation that incorrectly
implied that the existing `lock` method cloned an internal `Arc` — I
think this may be a holdover from `tokio` 0.1's `Lock` type?

Signed-off-by: Eliza Weisman <[email protected]>
2020-04-29 15:48:08 -07:00
Matthijs Brobbel c52b78b792 chore: fix a typo (#2461) 2020-04-29 13:06:40 -07:00
Jonathan Foote 1d28060836 chore: add initial security policy (#2360)
Adds an initial security policy based on email discussions with @carllerche,
@hawkw, and co.
2020-04-29 12:37:09 -07:00
Thomas Whiteway 947045b944 time: notify when resetting a Delay to a time in the past (#2290)
If a Delay has been polled, then the task that polled it may be waiting
for a notification.  If the delay gets reset to a time in the past, then
it immediately becomes elapsed, so it should notify the relevant task.
2020-04-29 18:03:44 +02:00
John-John Tedro 2c53bebe56 runtime: mem::forget instead of keeping track of dropped state (#2451) 2020-04-29 08:24:55 -07:00
513 changed files with 35577 additions and 18717 deletions
+8 -21
View File
@@ -1,17 +1,17 @@
freebsd_instance:
image: freebsd-12-1-release-amd64
image: freebsd-12-2-release-amd64
# Test FreeBSD in a full VM on cirrus-ci.com. Test the i686 target too, in the
# same VM. The binary will be built in 32-bit mode, but will execute on a
# 64-bit kernel and in a 64-bit environment. Our tests don't execute any of
# the system's binaries, so the environment shouldn't matter.
task:
name: FreeBSD 12.0
name: FreeBSD
env:
LOOM_MAX_PREEMPTIONS: 2
RUSTFLAGS: -Dwarnings
setup_script:
- pkg install -y curl
- pkg install -y bash curl
- curl https://sh.rustup.rs -sSf --output rustup.sh
- sh rustup.sh -y --profile minimal --default-toolchain stable
- . $HOME/.cargo/env
@@ -19,24 +19,11 @@ task:
- |
echo "~~~~ rustc --version ~~~~"
rustc --version
# Remove any existing patch statements
mv Cargo.toml Cargo.toml.bck
sed -n '/\[patch.crates-io\]/q;p' Cargo.toml.bck > Cargo.toml
# Patch all crates
cat ci/patch.toml >> Cargo.toml
# Print `Cargo.toml` for debugging
echo "~~~~ Cargo.toml ~~~~"
cat Cargo.toml
echo "~~~~~~~~~~~~~~~~~~~~"
test_script:
- . $HOME/.cargo/env
- cargo test --all
- cargo test --all --all-features
- cargo doc --all --no-deps
# TODO: Re-enable
# i686_test_script:
# - . $HOME/.cargo/env
# - |
# cargo test --all --exclude tokio-tls --exclude tokio-macros --target i686-unknown-freebsd
i686_test_script:
- . $HOME/.cargo/env
- |
cargo test --all --all-features --target i686-unknown-freebsd
-51
View File
@@ -1,51 +0,0 @@
<!--
Thank you for reporting an issue.
Please fill in as much of the template below as you're able.
-->
## Version
<!--
List the versions of all `tokio` crates you are using. The easiest way to get
this information is using `cargo-tree`.
`cargo install cargo-tree`
(see install here: https://github.com/sfackler/cargo-tree)
Then:
`cargo tree | grep tokio`
-->
## Platform
<!---
Output of `uname -a` (UNIX), or version and 32 or 64-bit (Windows)
-->
## Subcrates
<!--
If known, please specify the affected Tokio sub crates. Otherwise, delete this
section.
-->
## Description
<!--
Enter your issue details below this comment.
One way to structure the description:
<short summary of the bug>
I tried this code:
<code sample that causes the bug>
I expected to see this happen: <explanation>
Instead, this happened: <explanation>
-->
+31
View File
@@ -0,0 +1,31 @@
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: A-tokio, C-bug
assignees: ''
---
**Version**
List the versions of all `tokio` crates you are using. The easiest way to get
this information is using `cargo tree` subcommand:
`cargo tree | grep tokio`
**Platform**
The output of `uname -a` (UNIX), or version and 32 or 64-bit (Windows)
**Description**
Enter your issue details here.
One way to structure the description:
[short summary of the bug]
I tried this code:
[code sample that causes the bug]
I expected to see this happen: [explanation]
Instead, this happened: [explanation]
+20
View File
@@ -0,0 +1,20 @@
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: A-tokio, C-feature-request
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.
+16
View File
@@ -0,0 +1,16 @@
---
name: Question
about: Please use the discussions tab for questions
title: ''
labels: ''
assignees: ''
---
Please post your question as a discussion here:
https://github.com/tokio-rs/tokio/discussions
You may also be able to find help here:
https://discord.gg/tokio
https://users.rust-lang.org/
+3
View File
@@ -5,6 +5,9 @@ the requirements below.
Bug fixes and new features should include tests.
Contributors guide: https://github.com/tokio-rs/tokio/blob/master/CONTRIBUTING.md
The contributors guide includes instructions for running rustfmt and building the
documentation, which requires special commands beyond `cargo fmt` and `cargo doc`.
-->
## Motivation
+22
View File
@@ -0,0 +1,22 @@
name: Security Audit
on:
push:
branches:
- master
paths:
- '**/Cargo.toml'
schedule:
- cron: '0 2 * * *' # run at 2 AM UTC
jobs:
security-audit:
runs-on: ubuntu-latest
if: "!contains(github.event.head_commit.message, 'ci skip')"
steps:
- uses: actions/checkout@v2
- name: Audit Check
uses: actions-rs/audit-check@v1
with:
token: ${{ secrets.GITHUB_TOKEN }}
+55
View File
@@ -0,0 +1,55 @@
name: Benchmark
on:
push:
branches:
- master
jobs:
benchmark:
name: Benchmark
runs-on: ubuntu-latest
strategy:
matrix:
bench:
- rt_multi_threaded
- sync_mpsc
- sync_rwlock
- sync_semaphore
steps:
- uses: actions/checkout@v2
- name: Install Rust
run: rustup update stable
# Run benchmark with `go test -bench` and stores the output to a file
- name: Run benchmark
run: cargo bench --bench ${{ matrix.bench }} | tee ../output.txt
working-directory: benches
# Download previous benchmark result from cache (if exists)
- name: Download previous benchmark data
uses: actions/cache@v1
with:
path: ./cache
key: ${{ runner.os }}-benchmark
# Run `github-action-benchmark` action
- name: Store benchmark result
uses: rhysd/github-action-benchmark@v1
with:
name: ${{ matrix.bench }}
# What benchmark tool the output.txt came from
tool: 'cargo'
# Where the output from the benchmark tool is stored
output-file-path: output.txt
# # Where the previous data file is stored
# external-data-json-path: ./cache/benchmark-data.json
# Workflow will fail when an alert happens
fail-on-alert: true
# GitHub API token to make a commit comment
github-token: ${{ secrets.GITHUB_TOKEN }}
# Enable alert commit comment
comment-on-alert: true
alert-comment-cc-users: '@tokio-rs/maintainers'
auto-push: true
# Upload the updated cache file for the next job by actions/cache
+298
View File
@@ -0,0 +1,298 @@
on:
push:
branches: ["master", "tokio-*.x"]
pull_request:
branches: ["master", "tokio-*.x"]
name: CI
env:
RUSTFLAGS: -Dwarnings
RUST_BACKTRACE: 1
nightly: nightly-2020-09-21
minrust: 1.45.2
jobs:
# Depends on all action sthat are required for a "successful" CI run.
tests-pass:
name: all systems go
runs-on: ubuntu-latest
needs:
- test
- test-unstable
- miri
- cross
- features
- minrust
- fmt
- clippy
- docs
- loom
- valgrind
steps:
- run: exit 0
test:
name: test tokio full
runs-on: ${{ matrix.os }}
strategy:
matrix:
os:
- windows-latest
- ubuntu-latest
- macos-latest
steps:
- uses: actions/checkout@v2
- name: Install Rust
run: rustup update stable
- name: Install cargo-hack
run: cargo install cargo-hack
# Run `tokio` with `full` features. This excludes testing utilities which
# can alter the runtime behavior of Tokio.
- name: test tokio full
run: cargo test --features full
working-directory: tokio
# Test **all** crates in the workspace with all features.
- name: test all --all-features
run: cargo test --workspace --all-features
# Run integration tests for each feature
- name: test tests-integration --each-feature
run: cargo hack test --each-feature
working-directory: tests-integration
# Run macro build tests
- name: test tests-build --each-feature
run: cargo hack test --each-feature
working-directory: tests-build
valgrind:
name: valgrind
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Install Rust
run: rustup update stable
- name: Install Valgrind
run: |
sudo apt-get update -y
sudo apt-get install -y valgrind
# Compile tests
- name: cargo build
run: cargo build --features rt-net --bin test-mem
working-directory: tests-integration
# Run with valgrind
- name: Run valgrind
run: valgrind --leak-check=full --show-leak-kinds=all ./target/debug/test-mem
test-unstable:
name: test tokio full --unstable
runs-on: ${{ matrix.os }}
strategy:
matrix:
os:
- windows-latest
- ubuntu-latest
- macos-latest
steps:
- uses: actions/checkout@v2
- name: Install Rust
run: rustup update stable
# Run `tokio` with "unstable" cfg flag.
- name: test tokio full --cfg unstable
run: cargo test --features full
working-directory: tokio
env:
RUSTFLAGS: --cfg tokio_unstable -Dwarnings
miri:
name: miri
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions-rs/toolchain@v1
with:
toolchain: ${{ env.nightly }}
override: true
- name: Install Miri
run: |
set -e
rustup component add miri
cargo miri setup
rm -rf tokio/tests
- name: miri
run: cargo miri test --features rt,rt-multi-thread,sync task
working-directory: tokio
san:
name: san
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions-rs/toolchain@v1
with:
toolchain: ${{ env.nightly }}
override: true
- name: asan
run: cargo test --all-features --target x86_64-unknown-linux-gnu --lib -- --test-threads 1
working-directory: tokio
env:
RUSTFLAGS: -Z sanitizer=address
ASAN_OPTIONS: detect_leaks=0
cross:
name: cross
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@v2
- uses: actions-rs/toolchain@v1
with:
toolchain: stable
target: ${{ matrix.target }}
override: true
- uses: actions-rs/cargo@v1
with:
use-cross: true
command: check
args: --workspace --target ${{ matrix.target }}
features:
name: features
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions-rs/toolchain@v1
with:
toolchain: ${{ env.nightly }}
override: true
- name: Install cargo-hack
run: cargo install cargo-hack
- name: check --each-feature
run: cargo hack check --all --each-feature -Z avoid-dev-deps
# Try with unstable feature flags
- name: check --each-feature --unstable
run: cargo hack check --all --each-feature -Z avoid-dev-deps
env:
RUSTFLAGS: --cfg tokio_unstable -Dwarnings
minrust:
name: minrust
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions-rs/toolchain@v1
with:
toolchain: ${{ env.minrust }}
override: true
- name: "test --workspace --all-features"
run: cargo check --workspace --all-features
minimal-versions:
name: minimal-versions
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions-rs/toolchain@v1
with:
toolchain: ${{ env.nightly }}
override: true
- name: Install cargo-hack
run: cargo install cargo-hack
- name: "check --all-features -Z minimal-versions"
run: |
# Remove dev-dependencies from Cargo.toml to prevent the next `cargo update`
# from determining minimal versions based on dev-dependencies.
cargo hack --remove-dev-deps --workspace
# Update Cargo.lock to minimal version dependencies.
cargo update -Z minimal-versions
cargo check --all-features
fmt:
name: fmt
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Install Rust
run: rustup update stable
- name: Install rustfmt
run: rustup component add rustfmt
# Check fmt
- name: "rustfmt --check"
# Workaround for rust-lang/cargo#7732
run: |
if ! rustfmt --check --edition 2018 $(find . -name '*.rs' -print); then
printf "Please run \`rustfmt --edition 2018 \$(find . -name '*.rs' -print)\` to fix rustfmt errors.\nSee CONTRIBUTING.md for more details.\n" >&2
exit 1
fi
clippy:
name: clippy
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Install Rust
run: rustup update ${{ env.minrust }} && rustup default ${{ env.minrust }}
- name: Install clippy
run: rustup component add clippy
# Run clippy
- name: "clippy --all"
run: cargo clippy --all --tests --all-features
docs:
name: docs
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions-rs/toolchain@v1
with:
toolchain: ${{ env.nightly }}
override: true
- name: "doc --lib --all-features"
run: cargo doc --lib --no-deps --all-features
env:
RUSTDOCFLAGS: --cfg docsrs
loom:
name: loom
runs-on: ubuntu-latest
strategy:
matrix:
scope:
- --skip loom_pool
- loom_pool::group_a
- loom_pool::group_b
- loom_pool::group_c
- loom_pool::group_d
- time::driver
steps:
- uses: actions/checkout@v2
- name: Install Rust
run: rustup update stable
- name: loom ${{ matrix.scope }}
run: cargo test --lib --release --features full -- --nocapture $SCOPE
working-directory: tokio
env:
RUSTFLAGS: --cfg loom --cfg tokio_unstable -Dwarnings
LOOM_MAX_PREEMPTIONS: 2
SCOPE: ${{ matrix.scope }}
+32
View File
@@ -0,0 +1,32 @@
name: Pull Request Security Audit
on:
push:
paths:
- '**/Cargo.toml'
pull_request:
paths:
- '**/Cargo.toml'
jobs:
security-audit:
runs-on: ubuntu-latest
if: "!contains(github.event.head_commit.message, 'ci skip')"
steps:
- uses: actions/checkout@v2
- name: Install cargo-audit
uses: actions-rs/cargo@v1
with:
command: install
args: cargo-audit
- name: Generate lockfile
uses: actions-rs/cargo@v1
with:
command: generate-lockfile
- name: Audit dependencies
uses: actions-rs/cargo@v1
with:
command: audit
+32
View File
@@ -0,0 +1,32 @@
name: Stress Test
on:
pull_request:
push:
branches:
- master
jobs:
stess-test:
name: Stress Test
runs-on: ubuntu-latest
strategy:
matrix:
stress-test:
- simple_echo_tcp
steps:
- uses: actions/checkout@v2
- name: Install Rust
run: rustup update stable
- name: Install Valgrind
run: |
sudo apt-get update -y
sudo apt-get install -y valgrind
# Compiles each of the stress test examples.
- name: Compile stress test examples
run: cargo build -p stress-test --release --example ${{ matrix.stress-test }}
# Runs each of the examples using Valgrind. Detects leaks and displays them.
- name: Run valgrind
run: valgrind --leak-check=full --show-leak-kinds=all ./target/release/examples/${{ matrix.stress-test }}
+134 -10
View File
@@ -15,12 +15,14 @@ It should be considered a map to help you navigate the process.
The [dev channel][dev] is available for any concerns not covered in this guide, please join
us!
[dev]: https://discord.gg/6yGkFeN
[dev]: https://discord.gg/tokio
## Conduct
The Tokio project adheres to the [Rust Code of Conduct][coc]. This describes
the _minimum_ behavior expected from all contributors. Instances of violations of the Code of Conduct can be reported by contacting the project team at [[email protected]](mailto:[email protected]).
the _minimum_ behavior expected from all contributors. Instances of violations of the
Code of Conduct can be reported by contacting the project team at
[[email protected]](mailto:[email protected]).
[coc]: https://github.com/rust-lang/rust/blob/master/CODE_OF_CONDUCT.md
@@ -29,8 +31,8 @@ the _minimum_ behavior expected from all contributors. Instances of violations o
For any issue, there are fundamentally three ways an individual can contribute:
1. By opening the issue for discussion: For instance, if you believe that you
have uncovered a bug in Tokio, creating a new issue in the tokio-rs/tokio
issue tracker is the way to report it.
have discovered a bug in Tokio, creating a new issue in [the tokio-rs/tokio
issue tracker][issue] is the way to report it.
2. By helping to triage the issue: This can be done by providing
supporting details (a test case that demonstrates a bug), providing
@@ -42,21 +44,25 @@ For any issue, there are fundamentally three ways an individual can contribute:
often, by opening a Pull Request that changes some bit of something in
Tokio in a concrete and reviewable manner.
[issue]: https://github.com/tokio-rs/tokio/issues
**Anybody can participate in any stage of contribution**. We urge you to
participate in the discussion around bugs and participate in reviewing PRs.
### Asking for General Help
If you have reviewed existing documentation and still have questions or are
having problems, you can open an issue asking for help.
having problems, you can [open a discussion] asking for help.
In exchange for receiving help, we ask that you contribute back a documentation
PR that helps others avoid the problems that you encountered.
[open a discussion]: https://github.com/tokio-rs/tokio/discussions/new
### Submitting a Bug Report
When opening a new issue in the Tokio issue tracker, users will be presented
with a [basic template][template] that should be filled in. If you believe that you have
When opening a new issue in the Tokio issue tracker, you will be presented
with a basic template that should be filled in. If you believe that you have
uncovered a bug, please fill out this form, following the template to the best
of your ability. Do not worry if you cannot answer every detail, just fill in
what you can.
@@ -72,7 +78,6 @@ cases should be limited, as much as possible, to using only Tokio APIs.
See [How to create a Minimal, Complete, and Verifiable example][mcve].
[mcve]: https://stackoverflow.com/help/mcve
[template]: .github/PULL_REQUEST_TEMPLATE.md
### Triaging a Bug Report
@@ -132,8 +137,13 @@ RUSTDOCFLAGS="--cfg docsrs" cargo +nightly doc --all-features
```
The `cargo fmt` command does not work on the Tokio codebase. You can use the
command below instead:
```
# Mac or Linux
rustfmt --check --edition 2018 $(find . -name '*.rs' -print)
# Powershell
Get-ChildItem . -Filter "*.rs" -Recurse | foreach { rustfmt --check --edition 2018 $_.FullName }
```
The `--check` argument prints the things that need to be fixed. If you remove
it, `rustfmt` will update your files locally instead.
@@ -250,7 +260,7 @@ That said, if you have a number of commits that are "checkpoints" and don't
represent a single logical change, please squash those together.
Note that multiple commits often get squashed when they are landed (see the
notes about [commit squashing]).
notes about [commit squashing](#commit-squashing)).
#### Commit message guidelines
@@ -321,7 +331,7 @@ in order to evaluate whether the changes are correct and necessary.
Keep an eye out for comments from code owners to provide guidance on conflicting
feedback.
**Once the PR is open, do not rebase the commits**. See [Commit Squashing] for
**Once the PR is open, do not rebase the commits**. See [Commit Squashing](#commit-squashing) for
more details.
### Commit Squashing
@@ -415,6 +425,120 @@ _Adapted from the [Node.js contributing guide][node]_.
[hiding-a-comment]: https://help.github.com/articles/managing-disruptive-comments/#hiding-a-comment
[documentation test]: https://doc.rust-lang.org/rustdoc/documentation-tests.html
## Keeping track of issues and PRs
The Tokio GitHub repository has a lot of issues and PRs to keep track of. This
section explains the meaning of various labels, as well as our [GitHub
project][project]. The section is primarily targeted at maintainers. Most
contributors aren't able to set these labels.
### Area
The area label describes the crates relevant to this issue or PR.
- **A-tokio** This issue concerns the main Tokio crate.
- **A-tokio-util** This issue concerns the `tokio-util` crate.
- **A-tokio-tls** This issue concerns the `tokio-tls` crate. Only used for
older issues, as the crate has been moved to another repository.
- **A-tokio-test** The issue concerns the `tokio-test` crate.
- **A-tokio-macros** This issue concerns the `tokio-macros` crate. Should only
be used for the procedural macros, and not `join!` or `select!`.
- **A-ci** This issue concerns our GitHub Actions setup.
### Category
- **C-bug** This is a bug-report. Bug-fix PRs use `C-enhancement` instead.
- **C-enhancement** This is a PR that adds a new features.
- **C-maintenance** This is an issue or PR about stuff such as documentation,
GitHub Actions or code quality.
- **C-feature-request** This is a feature request. Implementations of feature
requests use `C-enhancement` instead.
- **C-feature-accepted** If you submit a PR for this feature request, we wont
close it with the reason "we don't want this". Issues with this label should
also have the `C-feature-request` label.
- **C-musing** Stuff like tracking issues or roadmaps. "musings about a better
world"
- **C-proposal** A proposal of some kind, and a request for comments.
- **C-question** A user question. Large overlap with GitHub discussions.
- **C-request** A non-feature request, e.g. "please add deprecation notices to
`-alpha.*` versions of crates"
### Calls for participation
- **E-help-wanted** Stuff where we want help. Often seen together with `C-bug`
or `C-feature-accepted`.
- **E-easy** This is easy, ranging from quick documentation fixes to stuff you
can do after reading the tutorial on our website.
- **E-medium** This is not `E-easy` or `E-hard`.
- **E-hard** This either involves very tricky code, is something we don't know
how to solve, or is difficult for some other reason.
- **E-needs-mvce** This bug is missing a minimal complete and verifiable
example.
The "E-" prefix is the same as used in the Rust compiler repository. Some
issues are missing a difficulty rating, but feel free to ask on our Discord
server if you want to know how difficult an issue likely is.
### Module
The module label provides a more fine grained categorization than **Area**.
- **M-blocking** Things relevant to `spawn_blocking`, `block_in_place`.
- **M-codec** The `tokio_util::codec` module.
- **M-compat** The `tokio_util::compat` module.
- **M-coop** Things relevant to coop.
- **M-fs** The `tokio::fs` module.
- **M-io** The `tokio::io` module.
- **M-macros** Issues about any kind of macro.
- **M-net** The `tokio::net` module.
- **M-process** The `tokio::process` module.
- **M-runtime** The `tokio::runtime` module.
- **M-signal** The `tokio::signal` module.
- **M-sync** The `tokio::sync` module.
- **M-task** The `tokio::task` module.
- **M-time** The `tokio::time` module.
- **M-tracing** Tracing support in Tokio.
### Topic
Some extra information.
- **T-docs** This is about documentation.
- **T-performance** This is about performance.
- **T-v0.1.x** This is about old Tokio.
Any label not listed here is not in active use.
[project]: https://github.com/orgs/tokio-rs/projects/1
## LTS guarantees
Tokio ≥1.0.0 comes with LTS guarantees:
* A minimum of 5 years of maintenance.
* A minimum of 3 years before a hypothetical 2.0 release.
The goal of these guarantees is to provide stability to the ecosystem.
## Mininum Supported Rust Version (MSRV)
* All Tokio ≥1.0.0 releases will support at least a 6-month old Rust
compiler release.
* The MSRV will only be increased on 1.x releases.
## Versioning Policy
With Tokio ≥1.0.0:
* Patch (1.\_.x) releases _should only_ contain bug fixes or documentation
changes. Besides this, these releases should not substantially change
runtime behavior.
* Minor (1.x) releases may contain new functionality, MSRV increases (see
above), minor dependency updates, deprecations, and larger internal
implementation changes.
This is as defined by [Semantic Versioning 2.0](https://semver.org/).
## Releasing
Since the Tokio project consists of a number of crates, many of which depend on
+2 -1
View File
@@ -4,12 +4,13 @@ members = [
"tokio",
"tokio-macros",
"tokio-test",
"tokio-tls",
"tokio-stream",
"tokio-util",
# Internal
"benches",
"examples",
"stress-test",
"tests-build",
"tests-integration",
]
+24 -17
View File
@@ -14,22 +14,21 @@ the Rust programming language. It is:
[![Crates.io][crates-badge]][crates-url]
[![MIT licensed][mit-badge]][mit-url]
[![Build Status][azure-badge]][azure-url]
[![Build Status][actions-badge]][actions-url]
[![Discord chat][discord-badge]][discord-url]
[crates-badge]: https://img.shields.io/crates/v/tokio.svg
[crates-url]: https://crates.io/crates/tokio
[mit-badge]: https://img.shields.io/badge/license-MIT-blue.svg
[mit-url]: LICENSE
[azure-badge]: https://dev.azure.com/tokio-rs/Tokio/_apis/build/status/tokio-rs.tokio?branchName=master
[azure-url]: https://dev.azure.com/tokio-rs/Tokio/_build/latest?definitionId=1&branchName=master
[mit-url]: https://github.com/tokio-rs/tokio/blob/master/LICENSE
[actions-badge]: https://github.com/tokio-rs/tokio/workflows/CI/badge.svg
[actions-url]: https://github.com/tokio-rs/tokio/actions?query=workflow%3ACI+branch%3Amaster
[discord-badge]: https://img.shields.io/discord/500028886025895936.svg?logo=discord&style=flat-square
[discord-url]: https://discord.gg/tokio
[Website](https://tokio.rs) |
[Guides](https://tokio.rs/docs/overview/) |
[Guides](https://tokio.rs/tokio/tutorial) |
[API Docs](https://docs.rs/tokio/latest/tokio) |
[Roadmap](https://github.com/tokio-rs/tokio/blob/master/ROADMAP.md) |
[Chat](https://discord.gg/tokio)
## Overview
@@ -55,7 +54,7 @@ A basic TCP echo server with Tokio:
```rust,no_run
use tokio::net::TcpListener;
use tokio::prelude::*;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
@@ -90,19 +89,27 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
}
```
More examples can be found [here](examples).
More examples can be found [here][examples]. For a larger "real world" example, see the
[mini-redis] repository.
[examples]: https://github.com/tokio-rs/tokio/tree/master/examples
[mini-redis]: https://github.com/tokio-rs/mini-redis/
To see a list of the available features flags that can be enabled, check our
[docs][feature-flag-docs].
## Getting Help
First, see if the answer to your question can be found in the [Guides] or the
[API documentation]. If the answer is not there, there is an active community in
the [Tokio Discord server][chat]. We would be happy to try to answer your
question. Last, if that doesn't work, try opening an [issue] with the question.
question. You can also ask your question on [the discussions page][discussions].
[Guides]: https://tokio.rs/docs/overview/
[Guides]: https://tokio.rs/tokio/tutorial
[API documentation]: https://docs.rs/tokio/latest/tokio
[chat]: https://discord.gg/tokio
[issue]: https://github.com/tokio-rs/tokio/issues/new
[discussions]: https://github.com/tokio-rs/tokio/discussions
[feature-flag-docs]: https://docs.rs/tokio/#feature-flags
## Contributing
@@ -149,15 +156,15 @@ several other libraries, including:
## Supported Rust Versions
Tokio is built against the latest stable, nightly, and beta Rust releases. The
minimum version supported is the stable release from three months before the
current stable release version. For example, if the latest stable Rust is 1.29,
the minimum version supported is 1.26. The current Tokio version is not
guaranteed to build on Rust versions earlier than the minimum supported version.
Tokio is built against the latest stable release. The minimum supported version is 1.45.
The current Tokio version is not guaranteed to build on Rust versions earlier than the
minimum supported version.
## License
This project is licensed under the [MIT license](LICENSE).
This project is licensed under the [MIT license].
[MIT license]: https://github.com/tokio-rs/tokio/blob/master/LICENSE
### Contribution
-67
View File
@@ -1,67 +0,0 @@
# Tokio Roadmap
## A Roadmap to 1.0
The question of "why not 1.0?" has come up a few times. After all, Tokio 0.1 has
been stable for three years. The short answer: because it isn't time. There is
nobody who would rather ship a Tokio 1.0 than us. It also isn't something to rush.
After all, `async / await` only landed in the stable Rust channel weeks ago.
There has been no significant production validation yet, except maybe fuchsia
and that seems like a fairly specialized use case. This release of Tokio
includes significant new code and new strategies with feature flags. Also, there
are still big open questions, such as the [proposed changes][pr-1744] to
`AsyncRead` and `AsyncWrite`.
Tokio 1.0 will be released as soon as the APIs are proven to handle real-world
production cases.
### Tokio 1.0 in Q3 2020 with LTS support
The Tokio 1.0 release will be **no later** than Q3 2020. It will also come with
"long-term support" guarantees:
* A minimum of 5 years of maintenance.
* A minimum of 3 years before a hypothetical 2.0 release.
When Tokio 1.0 is released in Q3 2020, on-going support, security fixes, and
critical bug fixes are guaranteed until **at least** Q3 2025. Tokio 2.0 will not
be released until **at least** Q3 2023 (though, ideally there will never be a
Tokio 2.0 release).
### How to get there
While Tokio 0.1 probably should have been a 1.0, Tokio 0.2 will be a **true**
0.2 release. There will be breaking change releases every 2 ~ 3 months until 1.0.
These changes will be **much** smaller than going from 0.1 -> 0.2. It is
expected that the 1.0 release will look a lot like 0.2.
### What is expected to change
The biggest change will be the `AsyncRead` and `AsyncWrite` traits. Based on
experience gained over the past 3 years, there are a couple of issues to
address:
* Be able to **safely** use uninitialized memory as a read buffer.
* Practical read vectored and write vectored APIs.
There are a few strategies to solve these problems. These strategies need to be
investigated and the solution validated. You can see [this comment][pr-1744-comment] for a
detailed statement of the problem.
The other major change, which has been in the works for a while, is updating
Mio. Mio 0.6 was first released almost 4 years ago and has not had a breaking
change since. Mio 0.7 has been in the works for a while. It includes a full
rewrite of the windows support as well as a refined API. More will be written
about this shortly.
Finally, now that the API is starting to stabilize, effort will be put into
documentation. Tokio 0.2 is being released before updating the website and many
of the old content will no longer be relevant. In the coming weeks, expect to
see updates there.
So, we have our work cut out for us. We hope you enjoy this 0.2 release and are
looking forward to your feedback and help.
[pr-1744]: https://github.com/tokio-rs/tokio/pull/1744
[pr-1744-comment]: https://github.com/tokio-rs/tokio/pull/1744#issuecomment-553575438
+13
View File
@@ -0,0 +1,13 @@
## Report a security issue
The Tokio project team welcomes security reports and is committed to providing prompt attention to security issues. Security issues should be reported privately via [[email protected]](mailto:[email protected]). Security issues should not be reported via the public Github Issue tracker.
## Vulnerability coordination
Remediation of security vulnerabilities is prioritized by the project team. The project team coordinates remediation with third-party project stakeholders via [Github Security Advisories](https://help.github.com/en/github/managing-security-vulnerabilities/about-github-security-advisories). Third-party stakeholders may include the reporter of the issue, affected direct or indirect users of Tokio, and maintainers of upstream dependencies if applicable.
Downstream project maintainers and Tokio users can request participation in coordination of applicable security issues by sending your contact email address, Github username(s) and any other salient information to [[email protected]](mailto:[email protected]). Participation in security issue coordination processes is at the discretion of the Tokio team.
## Security advisories
The project team is committed to transparency in the security issue disclosure process. The Tokio team announces security issues via [project Github Release notes](https://github.com/tokio-rs/tokio/releases) and the [RustSec advisory database](https://github.com/RustSec/advisory-db) (i.e. `cargo-audit`).
-121
View File
@@ -1,121 +0,0 @@
trigger: ["master"]
pr: ["master"]
variables:
RUSTFLAGS: -Dwarnings
nightly: nightly-2020-01-25
jobs:
# Test top level crate
- template: ci/azure-test-stable.yml
parameters:
name: test_tokio
rust: stable
displayName: Test tokio
cross: true
crates:
- tokio
- tests-integration
# Test sub crates
- template: ci/azure-test-stable.yml
parameters:
name: test_linux
displayName: Test sub crates -
rust: stable
crates:
- tokio-macros
- tokio-test
- tokio-tls
- tokio-util
- examples
# Run integration tests
- template: ci/azure-test-integration.yml
parameters:
name: test_integration
displayName: Integration tests
rust: stable
# Run tests from `tests-build`. This requires a different process
- template: ci/azure-test-build.yml
parameters:
name: test_build
displayName: Test build permutations
rust: stable
# Run miri tests
- template: ci/azure-miri.yml
parameters:
name: miri
# Try cross compiling
- template: ci/azure-cross-compile.yml
parameters:
name: cross
rust: stable
# Check each feature works properly
- template: ci/azure-check-features.yml
parameters:
rust: $(nightly)
name: check_features
# This represents the minimum Rust version supported by
# Tokio. Updating this should be done in a dedicated PR and
# cannot be greater than two 0.x releases prior to the
# current stable.
#
# Tests are not run as tests may require newer versions of
# rust.
- template: ci/azure-check-minrust.yml
parameters:
name: minrust
rust: 1.39.0
# Check formatting
- template: ci/azure-rustfmt.yml
parameters:
rust: stable
name: rustfmt
# Apply clippy lints to all crates
- template: ci/azure-clippy.yml
parameters:
rust: stable
name: clippy
# Check doc generation
- template: ci/azure-check-docs.yml
parameters:
rust: $(nightly)
name: docs
# - template: ci/azure-tsan.yml
# parameters:
# name: tsan
# rust: stable
# Run loom tests
- template: ci/azure-loom.yml
parameters:
name: loom
rust: stable
- template: ci/azure-deploy-docs.yml
parameters:
rust: stable
dependsOn:
- rustfmt
- docs
- clippy
- test_tokio
- test_linux
- test_integration
- test_build
- loom
- miri
- cross
- minrust
- check_features
# - tsan
+13 -5
View File
@@ -5,22 +5,25 @@ publish = false
edition = "2018"
[dependencies]
tokio = { version = "0.2.0", path = "../tokio", features = ["full"] }
tokio = { version = "1.0.0", path = "../tokio", features = ["full"] }
bencher = "0.1.5"
[target.'cfg(unix)'.dependencies]
libc = "0.2.42"
[[bench]]
name = "spawn"
path = "spawn.rs"
harness = false
[[bench]]
name = "mpsc"
path = "mpsc.rs"
name = "sync_mpsc"
path = "sync_mpsc.rs"
harness = false
[[bench]]
name = "scheduler"
path = "scheduler.rs"
name = "rt_multi_threaded"
path = "rt_multi_threaded.rs"
harness = false
@@ -33,3 +36,8 @@ harness = false
name = "sync_semaphore"
path = "sync_semaphore.rs"
harness = false
[[bench]]
name = "signal"
path = "signal.rs"
harness = false
@@ -13,7 +13,7 @@ use std::sync::{mpsc, Arc};
fn spawn_many(b: &mut Bencher) {
const NUM_SPAWN: usize = 10_000;
let mut rt = rt();
let rt = rt();
let (tx, rx) = mpsc::sync_channel(1000);
let rem = Arc::new(AtomicUsize::new(0));
@@ -68,7 +68,7 @@ fn yield_many(b: &mut Bencher) {
fn ping_pong(b: &mut Bencher) {
const NUM_PINGS: usize = 1_000;
let mut rt = rt();
let rt = rt();
let (done_tx, done_rx) = mpsc::sync_channel(1000);
let rem = Arc::new(AtomicUsize::new(0));
@@ -111,7 +111,7 @@ fn ping_pong(b: &mut Bencher) {
fn chained_spawn(b: &mut Bencher) {
const ITER: usize = 1_000;
let mut rt = rt();
let rt = rt();
fn iter(done_tx: mpsc::SyncSender<()>, n: usize) {
if n == 0 {
@@ -139,9 +139,8 @@ fn chained_spawn(b: &mut Bencher) {
}
fn rt() -> Runtime {
runtime::Builder::new()
.threaded_scheduler()
.core_threads(4)
runtime::Builder::new_multi_thread()
.worker_threads(4)
.enable_all()
.build()
.unwrap()
+95
View File
@@ -0,0 +1,95 @@
//! Benchmark the delay in propagating OS signals to any listeners.
#![cfg(unix)]
use bencher::{benchmark_group, benchmark_main, Bencher};
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use tokio::runtime;
use tokio::signal::unix::{signal, SignalKind};
use tokio::sync::mpsc;
struct Spinner {
count: usize,
}
impl Future for Spinner {
type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
if self.count > 3 {
Poll::Ready(())
} else {
self.count += 1;
cx.waker().wake_by_ref();
Poll::Pending
}
}
}
impl Spinner {
fn new() -> Self {
Self { count: 0 }
}
}
pub fn send_signal(signal: libc::c_int) {
use libc::{getpid, kill};
unsafe {
assert_eq!(kill(getpid(), signal), 0);
}
}
fn many_signals(bench: &mut Bencher) {
let num_signals = 10;
let (tx, mut rx) = mpsc::channel(num_signals);
// Intentionally single threaded to measure delays in propagating wakes
let rt = runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
let spawn_signal = |kind| {
let tx = tx.clone();
rt.spawn(async move {
let mut signal = signal(kind).expect("failed to create signal");
while signal.recv().await.is_some() {
if tx.send(()).await.is_err() {
break;
}
}
});
};
for _ in 0..num_signals {
// Pick some random signals which don't terminate the test harness
spawn_signal(SignalKind::child());
spawn_signal(SignalKind::io());
}
drop(tx);
// Turn the runtime for a while to ensure that all the spawned
// tasks have been polled at least once
rt.block_on(Spinner::new());
bench.iter(|| {
rt.block_on(async {
send_signal(libc::SIGCHLD);
for _ in 0..num_signals {
rx.recv().await.expect("channel closed");
}
send_signal(libc::SIGIO);
for _ in 0..num_signals {
rx.recv().await.expect("channel closed");
}
});
});
}
benchmark_group!(signal_group, many_signals,);
benchmark_main!(signal_group);
+8 -14
View File
@@ -10,8 +10,7 @@ async fn work() -> usize {
}
fn basic_scheduler_local_spawn(bench: &mut Bencher) {
let mut runtime = tokio::runtime::Builder::new()
.basic_scheduler()
let runtime = tokio::runtime::Builder::new_current_thread()
.build()
.unwrap();
runtime.block_on(async {
@@ -23,8 +22,7 @@ fn basic_scheduler_local_spawn(bench: &mut Bencher) {
}
fn threaded_scheduler_local_spawn(bench: &mut Bencher) {
let mut runtime = tokio::runtime::Builder::new()
.threaded_scheduler()
let runtime = tokio::runtime::Builder::new_current_thread()
.build()
.unwrap();
runtime.block_on(async {
@@ -36,25 +34,21 @@ fn threaded_scheduler_local_spawn(bench: &mut Bencher) {
}
fn basic_scheduler_remote_spawn(bench: &mut Bencher) {
let runtime = tokio::runtime::Builder::new()
.basic_scheduler()
let runtime = tokio::runtime::Builder::new_current_thread()
.build()
.unwrap();
let handle = runtime.handle();
bench.iter(|| {
let h = handle.spawn(work());
let h = runtime.spawn(work());
black_box(h);
});
}
fn threaded_scheduler_remote_spawn(bench: &mut Bencher) {
let runtime = tokio::runtime::Builder::new()
.threaded_scheduler()
.build()
.unwrap();
let handle = runtime.handle();
let runtime = tokio::runtime::Builder::new_multi_thread().build().unwrap();
bench.iter(|| {
let h = handle.spawn(work());
let h = runtime.spawn(work());
black_box(h);
});
}
+25 -34
View File
@@ -4,6 +4,13 @@ use tokio::sync::mpsc;
type Medium = [usize; 64];
type Large = [Medium; 64];
fn rt() -> tokio::runtime::Runtime {
tokio::runtime::Builder::new_multi_thread()
.worker_threads(6)
.build()
.unwrap()
}
fn create_1_medium(b: &mut Bencher) {
b.iter(|| {
black_box(&mpsc::channel::<Medium>(1));
@@ -23,38 +30,38 @@ fn create_100_000_medium(b: &mut Bencher) {
}
fn send_medium(b: &mut Bencher) {
let rt = rt();
b.iter(|| {
let (mut tx, mut rx) = mpsc::channel::<Medium>(1000);
let (tx, mut rx) = mpsc::channel::<Medium>(1000);
let _ = tx.try_send([0; 64]);
let _ = rt.block_on(tx.send([0; 64]));
rx.try_recv().unwrap();
rt.block_on(rx.recv()).unwrap();
});
}
fn send_large(b: &mut Bencher) {
let rt = rt();
b.iter(|| {
let (mut tx, mut rx) = mpsc::channel::<Large>(1000);
let (tx, mut rx) = mpsc::channel::<Large>(1000);
let _ = tx.try_send([[0; 64]; 64]);
let _ = rt.block_on(tx.send([[0; 64]; 64]));
rx.try_recv().unwrap();
rt.block_on(rx.recv()).unwrap();
});
}
fn contention_bounded(b: &mut Bencher) {
let mut rt = tokio::runtime::Builder::new()
.core_threads(6)
.threaded_scheduler()
.build()
.unwrap();
let rt = rt();
b.iter(|| {
rt.block_on(async move {
let (tx, mut rx) = mpsc::channel::<usize>(1_000_000);
for _ in 0..5 {
let mut tx = tx.clone();
let tx = tx.clone();
tokio::spawn(async move {
for i in 0..1000 {
tx.send(i).await.unwrap();
@@ -70,18 +77,14 @@ fn contention_bounded(b: &mut Bencher) {
}
fn contention_bounded_full(b: &mut Bencher) {
let mut rt = tokio::runtime::Builder::new()
.core_threads(6)
.threaded_scheduler()
.build()
.unwrap();
let rt = rt();
b.iter(|| {
rt.block_on(async move {
let (tx, mut rx) = mpsc::channel::<usize>(100);
for _ in 0..5 {
let mut tx = tx.clone();
let tx = tx.clone();
tokio::spawn(async move {
for i in 0..1000 {
tx.send(i).await.unwrap();
@@ -97,11 +100,7 @@ fn contention_bounded_full(b: &mut Bencher) {
}
fn contention_unbounded(b: &mut Bencher) {
let mut rt = tokio::runtime::Builder::new()
.core_threads(6)
.threaded_scheduler()
.build()
.unwrap();
let rt = rt();
b.iter(|| {
rt.block_on(async move {
@@ -124,15 +123,11 @@ fn contention_unbounded(b: &mut Bencher) {
}
fn uncontented_bounded(b: &mut Bencher) {
let mut rt = tokio::runtime::Builder::new()
.core_threads(6)
.threaded_scheduler()
.build()
.unwrap();
let rt = rt();
b.iter(|| {
rt.block_on(async move {
let (mut tx, mut rx) = mpsc::channel::<usize>(1_000_000);
let (tx, mut rx) = mpsc::channel::<usize>(1_000_000);
for i in 0..5000 {
tx.send(i).await.unwrap();
@@ -146,11 +141,7 @@ fn uncontented_bounded(b: &mut Bencher) {
}
fn uncontented_unbounded(b: &mut Bencher) {
let mut rt = tokio::runtime::Builder::new()
.core_threads(6)
.threaded_scheduler()
.build()
.unwrap();
let rt = rt();
b.iter(|| {
rt.block_on(async move {
+8 -13
View File
@@ -3,9 +3,8 @@ use std::sync::Arc;
use tokio::{sync::RwLock, task};
fn read_uncontended(b: &mut Bencher) {
let mut rt = tokio::runtime::Builder::new()
.core_threads(6)
.threaded_scheduler()
let rt = tokio::runtime::Builder::new_multi_thread()
.worker_threads(6)
.build()
.unwrap();
@@ -22,9 +21,8 @@ fn read_uncontended(b: &mut Bencher) {
}
fn read_concurrent_uncontended_multi(b: &mut Bencher) {
let mut rt = tokio::runtime::Builder::new()
.core_threads(6)
.threaded_scheduler()
let rt = tokio::runtime::Builder::new_multi_thread()
.worker_threads(6)
.build()
.unwrap();
@@ -51,8 +49,7 @@ fn read_concurrent_uncontended_multi(b: &mut Bencher) {
}
fn read_concurrent_uncontended(b: &mut Bencher) {
let mut rt = tokio::runtime::Builder::new()
.basic_scheduler()
let rt = tokio::runtime::Builder::new_current_thread()
.build()
.unwrap();
@@ -78,9 +75,8 @@ fn read_concurrent_uncontended(b: &mut Bencher) {
}
fn read_concurrent_contended_multi(b: &mut Bencher) {
let mut rt = tokio::runtime::Builder::new()
.core_threads(6)
.threaded_scheduler()
let rt = tokio::runtime::Builder::new_multi_thread()
.worker_threads(6)
.build()
.unwrap();
@@ -108,8 +104,7 @@ fn read_concurrent_contended_multi(b: &mut Bencher) {
}
fn read_concurrent_contended(b: &mut Bencher) {
let mut rt = tokio::runtime::Builder::new()
.basic_scheduler()
let rt = tokio::runtime::Builder::new_current_thread()
.build()
.unwrap();
+8 -13
View File
@@ -3,9 +3,8 @@ use std::sync::Arc;
use tokio::{sync::Semaphore, task};
fn uncontended(b: &mut Bencher) {
let mut rt = tokio::runtime::Builder::new()
.core_threads(6)
.threaded_scheduler()
let rt = tokio::runtime::Builder::new_multi_thread()
.worker_threads(6)
.build()
.unwrap();
@@ -27,9 +26,8 @@ async fn task(s: Arc<Semaphore>) {
}
fn uncontended_concurrent_multi(b: &mut Bencher) {
let mut rt = tokio::runtime::Builder::new()
.core_threads(6)
.threaded_scheduler()
let rt = tokio::runtime::Builder::new_multi_thread()
.worker_threads(6)
.build()
.unwrap();
@@ -51,8 +49,7 @@ fn uncontended_concurrent_multi(b: &mut Bencher) {
}
fn uncontended_concurrent_single(b: &mut Bencher) {
let mut rt = tokio::runtime::Builder::new()
.basic_scheduler()
let rt = tokio::runtime::Builder::new_current_thread()
.build()
.unwrap();
@@ -73,9 +70,8 @@ fn uncontended_concurrent_single(b: &mut Bencher) {
}
fn contended_concurrent_multi(b: &mut Bencher) {
let mut rt = tokio::runtime::Builder::new()
.core_threads(6)
.threaded_scheduler()
let rt = tokio::runtime::Builder::new_multi_thread()
.worker_threads(6)
.build()
.unwrap();
@@ -97,8 +93,7 @@ fn contended_concurrent_multi(b: &mut Bencher) {
}
fn contended_concurrent_single(b: &mut Bencher) {
let mut rt = tokio::runtime::Builder::new()
.basic_scheduler()
let rt = tokio::runtime::Builder::new_current_thread()
.build()
.unwrap();
-29
View File
@@ -1,29 +0,0 @@
parameters:
noDefaultFeatures: '--no-default-features'
jobs:
- job: ${{ parameters.name }}
displayName: ${{ parameters.displayName }}
pool:
vmImage: ubuntu-16.04
steps:
- template: azure-install-rust.yml
parameters:
rust_version: ${{ parameters.rust }}
- template: azure-is-release.yml
- ${{ each crate in parameters.crates }}:
- ${{ each feature in crate.value }}:
- script: cargo check ${{ parameters.noDefaultFeatures }} --features ${{ feature }}
displayName: Check `${{ crate.key }}`, features = ${{ feature }}
workingDirectory: $(Build.SourcesDirectory)/${{ crate.key }}
condition: and(succeeded(), not(variables['isRelease']))
- template: azure-patch-crates.yml
- ${{ each crate in parameters.crates }}:
- ${{ each feature in crate.value }}:
- script: cargo check ${{ parameters.noDefaultFeatures }} --features ${{ feature }}
displayName: Check `${{ crate.key }}`, features = ${{ feature }}
workingDirectory: $(Build.SourcesDirectory)/${{ crate.key }}
-15
View File
@@ -1,15 +0,0 @@
jobs:
# Check docs
- job: ${{ parameters.name }}
displayName: Check docs
pool:
vmImage: ubuntu-16.04
steps:
- template: azure-install-rust.yml
parameters:
rust_version: ${{ parameters.rust }}
- script: |
RUSTDOCFLAGS="--cfg docsrs" cargo doc --lib --no-deps --all-features
displayName: Check docs
-32
View File
@@ -1,32 +0,0 @@
jobs:
- job: ${{ parameters.name }}
displayName: Check features
strategy:
matrix:
Linux:
vmImage: ubuntu-16.04
MacOS:
vmImage: macos-latest
Windows:
vmImage: vs2017-win2016
pool:
vmImage: $(vmImage)
steps:
- template: azure-install-rust.yml
parameters:
rust_version: ${{ parameters.rust }}
- template: azure-patch-crates.yml
- script: cargo install cargo-hack
displayName: Install cargo-hack
# Check each feature works properly
# * --each-feature
# run for each feature which includes --no-default-features and default features of package
# * -Z avoid-dev-deps
# build without dev-dependencies to avoid https://github.com/rust-lang/cargo/issues/4866
# tracking-issue: https://github.com/rust-lang/cargo/issues/5133
- script: cargo hack check --all --each-feature -Z avoid-dev-deps
displayName: cargo hack check --all --each-feature
-14
View File
@@ -1,14 +0,0 @@
jobs:
- job: ${{ parameters.name }}
displayName: Min supported Rust version
pool:
vmImage: ubuntu-16.04
steps:
- template: azure-install-rust.yml
parameters:
rust_version: ${{ parameters.rust }}
- template: azure-patch-crates.yml
- script: cargo check --all
displayName: cargo check --all
-16
View File
@@ -1,16 +0,0 @@
jobs:
- job: ${{ parameters.name }}
displayName: Clippy
pool:
vmImage: ubuntu-16.04
steps:
- template: azure-install-rust.yml
parameters:
rust_version: ${{ parameters.rust }}
- script: |
rustup component add clippy
cargo clippy --version
displayName: Install clippy
- script: |
cargo clippy --all --all-features
displayName: cargo clippy --all
-44
View File
@@ -1,44 +0,0 @@
jobs:
- job: ${{ parameters.name }}
displayName: ${{ parameters.displayName }}
strategy:
matrix:
i686:
vmImage: ubuntu-16.04
target: i686-unknown-linux-gnu
powerpc:
vmImage: ubuntu-16.04
target: powerpc-unknown-linux-gnu
powerpc64:
vmImage: ubuntu-16.04
target: powerpc64-unknown-linux-gnu
mips:
vmImage: ubuntu-16.04
target: mips-unknown-linux-gnu
arm:
vmImage: ubuntu-16.04
target: arm-linux-androideabi
pool:
vmImage: $(vmImage)
steps:
- template: azure-install-rust.yml
parameters:
rust_version: ${{ parameters.rust }}
- script: sudo apt-get update
displayName: apt-get update
- script: sudo apt-get install gcc-multilib
displayName: Install gcc-multilib
- script: cargo install cross
displayName: Install cross
# Always patch
- template: azure-patch-crates.yml
- script: cross check --all --exclude tokio-tls --target $(target)
displayName: Check source
# - script: cross check --tests --all --exclude tokio-tls --target $(target)
# displayName: Check tests
-39
View File
@@ -1,39 +0,0 @@
parameters:
dependsOn: []
jobs:
- job: documentation
displayName: 'Deploy API Documentation'
condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/master'))
pool:
vmImage: 'Ubuntu 16.04'
dependsOn:
- ${{ parameters.dependsOn }}
steps:
- template: azure-install-rust.yml
parameters:
# rust_version: stable
rust_version: ${{ parameters.rust }}
- script: |
cargo doc --all --no-deps --all-features
cp -R target/doc '$(Build.BinariesDirectory)'
displayName: 'Generate Documentation'
- script: |
set -e
git --version
ls -la
git init
git config user.name 'Deployment Bot (from Azure Pipelines)'
git config user.email '[email protected]'
git config --global credential.helper 'store --file ~/.my-credentials'
printf "protocol=https\nhost=github.com\nusername=carllerche\npassword=%s\n\n" "$GITHUB_TOKEN" | git credential-store --file ~/.my-credentials store
git remote add origin https://github.com/tokio-rs/tokio
git checkout -b gh-pages
git add .
git commit -m 'Deploy Tokio API documentation'
git push -f origin gh-pages
env:
GITHUB_TOKEN: $(githubPersonalToken)
workingDirectory: '$(Build.BinariesDirectory)'
displayName: 'Deploy Documentation'
-40
View File
@@ -1,40 +0,0 @@
steps:
# Linux and macOS.
- script: |
set -e
if [ "$RUSTUP_TOOLCHAIN" == "nightly" ]; then
echo "++ getting latest miri version"
export RUSTUP_TOOLCHAIN="nightly-$(curl -s https://rust-lang.github.io/rustup-components-history/x86_64-unknown-linux-gnu/miri)"
echo "$RUSTUP_TOOLCHAIN"
fi
curl https://sh.rustup.rs -sSf | sh -s -- -y --profile minimal --default-toolchain none
export PATH=$PATH:$HOME/.cargo/bin
rustup toolchain install $RUSTUP_TOOLCHAIN
rustup default $RUSTUP_TOOLCHAIN
echo "##vso[task.setvariable variable=PATH;]$PATH:$HOME/.cargo/bin"
env:
RUSTUP_TOOLCHAIN: ${{parameters.rust_version}}
displayName: "Install rust (*nix)"
condition: not(eq(variables['Agent.OS'], 'Windows_NT'))
# Windows.
- script: |
curl -sSf -o rustup-init.exe https://win.rustup.rs
rustup-init.exe -y --profile minimal --default-toolchain none
set PATH=%PATH%;%USERPROFILE%\.cargo\bin
rustup toolchain install %RUSTUP_TOOLCHAIN%
rustup default %RUSTUP_TOOLCHAIN%
echo "##vso[task.setvariable variable=PATH;]%PATH%;%USERPROFILE%\.cargo\bin"
env:
RUSTUP_TOOLCHAIN: ${{parameters.rust_version}}
displayName: "Install rust (windows)"
condition: eq(variables['Agent.OS'], 'Windows_NT')
# All platforms.
- script: |
rustup toolchain list
rustc -Vv
cargo -V
displayName: Query rust and cargo versions
-9
View File
@@ -1,9 +0,0 @@
steps:
- bash: |
set -e
if git log --no-merges -1 --format='%B' | grep -qF '[ci-release]'; then
echo "##vso[task.setvariable variable=isRelease]true"
fi
failOnStderr: true
displayName: Check if release commit
-29
View File
@@ -1,29 +0,0 @@
jobs:
- job: ${{ parameters.name }}
displayName: Loom tests
strategy:
matrix:
rest:
scope: --skip loom_pool
pool_group_a:
scope: loom_pool::group_a
pool_group_b:
scope: loom_pool::group_b
pool_group_c:
scope: loom_pool::group_c
pool_group_d:
scope: loom_pool::group_d
pool:
vmImage: ubuntu-16.04
steps:
- template: azure-install-rust.yml
parameters:
rust_version: ${{ parameters.rust }}
- script: RUSTFLAGS="--cfg loom" cargo test --lib --release --features "full" -- --nocapture $(scope)
env:
LOOM_MAX_PREEMPTIONS: 2
CI: 'True'
displayName: $(scope)
workingDirectory: $(Build.SourcesDirectory)/tokio
-23
View File
@@ -1,23 +0,0 @@
jobs:
- job: ${{ parameters.name }}
displayName: Miri
pool:
vmImage: ubuntu-16.04
steps:
- template: azure-install-rust.yml
parameters:
rust_version: nightly
- script: |
rustup component add miri
cargo miri setup
rm -rf $(Build.SourcesDirectory)/tokio/tests
displayName: Install miri
# TODO: enable all tests once they pass
- script: cargo miri test --features rt-core,rt-threaded,rt-util,sync -- -- task
env:
CI: 'True'
displayName: cargo miri test
workingDirectory: $(Build.SourcesDirectory)/tokio
-16
View File
@@ -1,16 +0,0 @@
steps:
- script: |
set -e
# Remove any existing patch statements
mv Cargo.toml Cargo.toml.bck
sed -n '/\[patch.crates-io\]/q;p' Cargo.toml.bck > Cargo.toml
# Patch all crates
cat ci/patch.toml >> Cargo.toml
# Print `Cargo.toml` for debugging
echo "~~~~ Cargo.toml ~~~~"
cat Cargo.toml
echo "~~~~~~~~~~~~~~~~~~~~"
displayName: Patch Cargo.toml
-18
View File
@@ -1,18 +0,0 @@
jobs:
# Check formatting
- job: ${{ parameters.name }}
displayName: Check rustfmt
pool:
vmImage: ubuntu-16.04
steps:
- template: azure-install-rust.yml
parameters:
rust_version: ${{ parameters.rust }}
- script: |
rustup component add rustfmt
cargo fmt --version
displayName: Install rustfmt
- script: |
# Workaround for rust-lang/cargo#7732
rustfmt --check --edition 2018 $(find . -name '*.rs' -print)
displayName: Check formatting
-17
View File
@@ -1,17 +0,0 @@
jobs:
- job: ${{ parameters.name }}
displayName: ${{ parameters.displayName }}
pool:
vmImage: 'Ubuntu 16.04'
steps:
- template: azure-install-rust.yml
parameters:
rust_version: ${{ parameters.rust }}
- script: cargo install cargo-hack
displayName: Install cargo-hack
- script: cargo hack test --each-feature
displayName: cargo hack test --each-feature
workingDirectory: $(Build.SourcesDirectory)/tests-build
-28
View File
@@ -1,28 +0,0 @@
jobs:
- job: ${{ parameters.name }}
displayName: ${{ parameters.displayName }}
strategy:
matrix:
Linux:
vmImage: ubuntu-16.04
MacOS:
vmImage: macos-latest
Windows:
vmImage: vs2017-win2016
pool:
vmImage: $(vmImage)
steps:
- template: azure-install-rust.yml
parameters:
rust_version: ${{ parameters.rust }}
- script: cargo install cargo-hack
displayName: Install cargo-hack
# Run with all crate features
- script: cargo hack test --each-feature
env:
CI: 'True'
displayName: cargo hack test --each-feature
workingDirectory: $(Build.SourcesDirectory)/tests-integration
-19
View File
@@ -1,19 +0,0 @@
jobs:
- job: ${{ parameters.name }}
displayName: ${{ parameters.displayName }}
pool:
vmImage: ubuntu-16.04
steps:
- template: azure-install-rust.yml
parameters:
rust_version: ${{ parameters.rust }}
- template: azure-patch-crates.yml
- script: cargo check --all
displayName: cargo check --all
# Check benches
- script: cargo check --benches --all
displayName: Check benchmarks
-47
View File
@@ -1,47 +0,0 @@
jobs:
- job: ${{ parameters.name }}
displayName: ${{ parameters.displayName }}
strategy:
matrix:
Linux:
vmImage: ubuntu-16.04
${{ if parameters.cross }}:
MacOS:
vmImage: macos-latest
Windows:
vmImage: vs2017-win2016
pool:
vmImage: $(vmImage)
steps:
- template: azure-install-rust.yml
parameters:
rust_version: ${{ parameters.rust }}
- template: azure-is-release.yml
- ${{ each crate in parameters.crates }}:
# Run with all crate features
- script: cargo test --all-features
env:
RUST_BACKTRACE: 1
CI: 'True'
displayName: ${{ crate }} - cargo test --all-features
workingDirectory: $(Build.SourcesDirectory)/${{ crate }}
# Check benches
- script: cargo check --all-features --benches
displayName: ${{ crate }} - cargo check --benches
workingDirectory: $(Build.SourcesDirectory)/${{ crate }}
- template: azure-patch-crates.yml
- ${{ each crate in parameters.crates }}:
# Run with all crate features
- script: cargo test --all-features
env:
RUST_BACKTRACE: 1
CI: 'True'
displayName: ${{ crate }} - cargo test --all-features
workingDirectory: $(Build.SourcesDirectory)/${{ crate }}
-34
View File
@@ -1,34 +0,0 @@
jobs:
- job: ${{ parameters.name }}
displayName: TSAN
strategy:
matrix:
Timer:
cmd: cargo test -p tokio-timer --test hammer
pool:
vmImage: ubuntu-16.04
steps:
- template: azure-install-rust.yml
parameters:
rust_version: ${{ parameters.rust }}
- template: azure-patch-crates.yml
- script: |
set -e
# Make sure the benchmarks compile
export ASAN_OPTIONS="detect_odr_violation=0 detect_leaks=0"
export TSAN_OPTIONS="suppressions=`pwd`/ci/tsan"
export RUST_BACKTRACE=1
# Run address sanitizer
RUSTFLAGS="-Z sanitizer=address" \
$(cmd) --target x86_64-unknown-linux-gnu
# Run thread sanitizer
RUSTFLAGS="-Z sanitizer=thread" \
$(cmd) --target x86_64-unknown-linux-gnu
displayName: TSAN / MSAN
env:
TSAN: yes
-8
View File
@@ -1,8 +0,0 @@
# Patch dependencies to run all tests against versions of the crate in the
# repository.
[patch.crates-io]
tokio = { path = "tokio" }
tokio-macros = { path = "tokio-macros" }
tokio-test = { path = "tokio-test" }
tokio-tls = { path = "tokio-tls" }
tokio-util = { path = "tokio-util" }
-39
View File
@@ -1,39 +0,0 @@
# TSAN suppressions file for Tokio
# TSAN does not understand fences and `Arc::drop` is implemented using a fence.
# This causes many false positives.
race:Arc*drop
race:Weak*drop
# `std` mpsc is not used in any Tokio code base. This race is triggered by some
# rust runtime logic.
race:std*mpsc_queue
race:std*lang_start
race:drop*std::thread*
# Probably more fences in std.
race:__call_tls_dtors
# The epoch-based GC uses fences.
race:crossbeam_epoch
# Push and steal operations in crossbeam-deque may cause data races, but such
# data races are safe. If a data race happens, the value read by `steal` is
# forgotten and the steal operation is then retried.
race:crossbeam_deque*push
race:crossbeam_deque*steal
# This filters out expected data race in the Treiber stack implementations.
# Treiber stacks are inherently racy. The pop operation will attempt to access
# the "next" pointer on the node it is attempting to pop. However, at this
# point it has not gained ownership of the node and another thread might beat
# it and take ownership of the node first (touching the next pointer). The
# original pop operation will fail due to the ABA guard, but tsan still picks
# up the access on the next pointer.
race:Backup::next_sleeper
race:Backup::set_next_sleeper
race:WorkerEntry::set_next_sleeper
# This ignores a false positive caused by `thread::park()`/`thread::unpark()`.
# See: https://github.com/rust-lang/rust/pull/54806#issuecomment-436193353
race:pthread_cond_destroy
+20 -4
View File
@@ -7,16 +7,23 @@ edition = "2018"
# If you copy one of the examples into a new project, you should be using
# [dependencies] instead.
[dev-dependencies]
tokio = { version = "0.2.0", path = "../tokio", features = ["full"] }
tokio-util = { version = "0.3.0", path = "../tokio-util", features = ["full"] }
bytes = "0.5"
futures = "0.3.0"
tokio = { version = "1.0.0", features = ["full", "tracing"] }
tokio-util = { version = "0.6.3", features = ["full"] }
tokio-stream = { version = "0.1" }
async-stream = "0.3"
tracing = "0.1"
tracing-subscriber = { version = "0.2.7", default-features = false, features = ["fmt", "ansi", "env-filter", "chrono", "tracing-log"] }
bytes = "1.0.0"
futures = { version = "0.3.0", features = ["thread-pool"]}
http = "0.2"
serde = "1.0"
serde_derive = "1.0"
serde_json = "1.0"
httparse = "1.0"
time = "0.1"
once_cell = "1.5.2"
[[example]]
name = "chat"
@@ -61,3 +68,12 @@ path = "udp-codec.rs"
[[example]]
name = "tinyhttp"
path = "tinyhttp.rs"
[[example]]
name = "custom-executor"
path = "custom-executor.rs"
[[example]]
name = "custom-executor-tokio-context"
path = "custom-executor-tokio-context.rs"
+1 -1
View File
@@ -19,5 +19,5 @@ If you've got an example you'd like to see here, please feel free to open an
issue. Otherwise if you've got an example you'd like to add, please feel free
to make a PR!
[tokioweb]: https://tokio.rs/docs/overview/
[tokioweb]: https://tokio.rs/tokio/tutorial
[redis]: https://github.com/tokio-rs/mini-redis
+39 -14
View File
@@ -27,8 +27,8 @@
#![warn(rust_2018_idioms)]
use tokio::net::{TcpListener, TcpStream};
use tokio::stream::{Stream, StreamExt};
use tokio::sync::{mpsc, Mutex};
use tokio_stream::{Stream, StreamExt};
use tokio_util::codec::{Framed, LinesCodec, LinesCodecError};
use futures::SinkExt;
@@ -43,6 +43,26 @@ use std::task::{Context, Poll};
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
use tracing_subscriber::{fmt::format::FmtSpan, EnvFilter};
// Configure a `tracing` subscriber that logs traces emitted by the chat
// server.
tracing_subscriber::fmt()
// Filter what traces are displayed based on the RUST_LOG environment
// variable.
//
// Traces emitted by the example code will always be displayed. You
// can set `RUST_LOG=tokio=trace` to enable additional traces emitted by
// Tokio itself.
.with_env_filter(EnvFilter::from_default_env().add_directive("chat=info".parse()?))
// Log events when `tracing` spans are created, entered, exited, or
// closed. When Tokio's internal tracing support is enabled (as
// described above), this can be used to track the lifecycle of spawned
// tasks on the Tokio runtime.
.with_span_events(FmtSpan::FULL)
// Set this subscriber as the default, to collect all traces emitted by
// the program.
.init();
// Create the shared state. This is how all the peers communicate.
//
// The server task will hold a handle to this. For every new client, the
@@ -57,9 +77,9 @@ async fn main() -> Result<(), Box<dyn Error>> {
// Bind a TCP listener to the socket address.
//
// Note that this is the Tokio TcpListener, which is fully async.
let mut listener = TcpListener::bind(&addr).await?;
let listener = TcpListener::bind(&addr).await?;
println!("server running on {}", addr);
tracing::info!("server running on {}", addr);
loop {
// Asynchronously wait for an inbound TcpStream.
@@ -70,8 +90,9 @@ async fn main() -> Result<(), Box<dyn Error>> {
// Spawn our handler to be run asynchronously.
tokio::spawn(async move {
tracing::debug!("accepted connection");
if let Err(e) = process(state, stream, addr).await {
println!("an error occurred; error = {:?}", e);
tracing::info!("an error occurred; error = {:?}", e);
}
});
}
@@ -80,9 +101,6 @@ async fn main() -> Result<(), Box<dyn Error>> {
/// Shorthand for the transmit half of the message channel.
type Tx = mpsc::UnboundedSender<String>;
/// Shorthand for the receive half of the message channel.
type Rx = mpsc::UnboundedReceiver<String>;
/// Data that is shared between all peers in the chat server.
///
/// This is the set of `Tx` handles for all connected clients. Whenever a
@@ -106,7 +124,7 @@ struct Peer {
///
/// This is used to receive messages from peers. When a message is received
/// off of this `Rx`, it will be written to the socket.
rx: Rx,
rx: Pin<Box<dyn Stream<Item = String> + Send>>,
}
impl Shared {
@@ -138,11 +156,17 @@ impl Peer {
let addr = lines.get_ref().peer_addr()?;
// Create a channel for this peer
let (tx, rx) = mpsc::unbounded_channel();
let (tx, mut rx) = mpsc::unbounded_channel();
// Add an entry for this `Peer` in the shared state map.
state.lock().await.peers.insert(addr, tx);
let rx = Box::pin(async_stream::stream! {
while let Some(item) = rx.recv().await {
yield item;
}
});
Ok(Peer { lines, rx })
}
}
@@ -200,7 +224,7 @@ async fn process(
Some(Ok(line)) => line,
// We didn't get a line so we return early here.
_ => {
println!("Failed to get username from {}. Client disconnected.", addr);
tracing::error!("Failed to get username from {}. Client disconnected.", addr);
return Ok(());
}
};
@@ -212,7 +236,7 @@ async fn process(
{
let mut state = state.lock().await;
let msg = format!("{} has joined the chat", username);
println!("{}", msg);
tracing::info!("{}", msg);
state.broadcast(addr, &msg).await;
}
@@ -233,9 +257,10 @@ async fn process(
peer.lines.send(&msg).await?;
}
Err(e) => {
println!(
tracing::error!(
"an error occurred while processing messages for {}; error = {:?}",
username, e
username,
e
);
}
}
@@ -248,7 +273,7 @@ async fn process(
state.peers.remove(&addr);
let msg = format!("{} has left the chat", username);
println!("{}", msg);
tracing::info!("{}", msg);
state.broadcast(addr, &msg).await;
}
+4 -6
View File
@@ -92,11 +92,10 @@ mod tcp {
mod udp {
use bytes::Bytes;
use futures::{future, Sink, SinkExt, Stream, StreamExt};
use futures::{Sink, SinkExt, Stream, StreamExt};
use std::error::Error;
use std::io;
use std::net::SocketAddr;
use tokio::net::udp::{RecvHalf, SendHalf};
use tokio::net::UdpSocket;
pub async fn connect(
@@ -114,16 +113,15 @@ mod udp {
let socket = UdpSocket::bind(&bind_addr).await?;
socket.connect(addr).await?;
let (mut r, mut w) = socket.split();
future::try_join(send(stdin, &mut w), recv(stdout, &mut r)).await?;
tokio::try_join!(send(stdin, &socket), recv(stdout, &socket))?;
Ok(())
}
async fn send(
mut stdin: impl Stream<Item = Result<Bytes, io::Error>> + Unpin,
writer: &mut SendHalf,
writer: &UdpSocket,
) -> Result<(), io::Error> {
while let Some(item) = stdin.next().await {
let buf = item?;
@@ -135,7 +133,7 @@ mod udp {
async fn recv(
mut stdout: impl Sink<Bytes, Error = io::Error> + Unpin,
reader: &mut RecvHalf,
reader: &UdpSocket,
) -> Result<(), io::Error> {
loop {
let mut buf = vec![0; 1024];
+32
View File
@@ -0,0 +1,32 @@
// This example shows how to use the tokio runtime with any other executor
//
//It takes advantage from RuntimeExt which provides the extension to customize your
//runtime.
use tokio::net::TcpListener;
use tokio::runtime::Builder;
use tokio::sync::oneshot;
use tokio_util::context::RuntimeExt;
fn main() {
let (tx, rx) = oneshot::channel();
let rt1 = Builder::new_multi_thread()
.worker_threads(1)
// no timer!
.build()
.unwrap();
let rt2 = Builder::new_multi_thread()
.worker_threads(1)
.enable_all()
.build()
.unwrap();
// Without the `HandleExt.wrap()` there would be a panic because there is
// no timer running, since it would be referencing runtime r1.
let _ = rt1.block_on(rt2.wrap(async move {
let listener = TcpListener::bind("0.0.0.0:0").await.unwrap();
println!("addr: {:?}", listener.local_addr());
tx.send(()).unwrap();
}));
futures::executor::block_on(rx).unwrap();
}
+56
View File
@@ -0,0 +1,56 @@
// This example shows how to use the tokio runtime with any other executor
//
// The main components are a spawn fn that will wrap futures in a special future
// that will always enter the tokio context on poll. This only spawns one extra thread
// to manage and run the tokio drivers in the background.
use tokio::net::TcpListener;
use tokio::sync::oneshot;
fn main() {
let (tx, rx) = oneshot::channel();
my_custom_runtime::spawn(async move {
let listener = TcpListener::bind("0.0.0.0:0").await.unwrap();
println!("addr: {:?}", listener.local_addr());
tx.send(()).unwrap();
});
futures::executor::block_on(rx).unwrap();
}
mod my_custom_runtime {
use once_cell::sync::Lazy;
use std::future::Future;
use tokio_util::context::TokioContext;
pub fn spawn(f: impl Future<Output = ()> + Send + 'static) {
EXECUTOR.spawn(f);
}
struct ThreadPool {
inner: futures::executor::ThreadPool,
rt: tokio::runtime::Runtime,
}
static EXECUTOR: Lazy<ThreadPool> = Lazy::new(|| {
// Spawn tokio runtime on a single background thread
// enabling IO and timers.
let rt = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.unwrap();
let inner = futures::executor::ThreadPool::builder().create().unwrap();
ThreadPool { inner, rt }
});
impl ThreadPool {
fn spawn(&self, f: impl Future<Output = ()> + Send + 'static) {
let handle = self.rt.handle().clone();
self.inner.spawn_ok(TokioContext::new(f, handle));
}
}
}
+1 -2
View File
@@ -15,7 +15,6 @@
use std::error::Error;
use std::net::SocketAddr;
use std::{env, io};
use tokio;
use tokio::net::UdpSocket;
struct Server {
@@ -27,7 +26,7 @@ struct Server {
impl Server {
async fn run(self) -> Result<(), io::Error> {
let Server {
mut socket,
socket,
mut buf,
mut to_send,
} = self;
+2 -3
View File
@@ -21,7 +21,6 @@
#![warn(rust_2018_idioms)]
use tokio;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpListener;
@@ -40,7 +39,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
// Next up we create a TCP listener which will listen for incoming
// connections. This TCP listener is bound to the address we determined
// above and must be associated with an event loop.
let mut listener = TcpListener::bind(&addr).await?;
let listener = TcpListener::bind(&addr).await?;
println!("Listening on: {}", addr);
loop {
@@ -56,7 +55,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
// which will allow all of our clients to be processed concurrently.
tokio::spawn(async move {
let mut buf = [0; 1024];
let mut buf = vec![0; 1024];
// In a loop, read data from the socket and write the data back.
loop {
+2 -2
View File
@@ -55,7 +55,7 @@
#![warn(rust_2018_idioms)]
use tokio::net::TcpListener;
use tokio::stream::StreamExt;
use tokio_stream::StreamExt;
use tokio_util::codec::{BytesCodec, Decoder};
use std::env;
@@ -74,7 +74,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
// above and must be associated with an event loop, so we pass in a handle
// to our event loop. After the socket's created we inform that we're ready
// to go and start accepting connections.
let mut listener = TcpListener::bind(&addr).await?;
let listener = TcpListener::bind(&addr).await?;
println!("Listening on: {}", addr);
loop {
+12 -5
View File
@@ -23,9 +23,9 @@
#![warn(rust_2018_idioms)]
use tokio::io;
use tokio::io::AsyncWriteExt;
use tokio::net::{TcpListener, TcpStream};
use futures::future::try_join;
use futures::FutureExt;
use std::env;
use std::error::Error;
@@ -42,7 +42,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
println!("Listening on: {}", listen_addr);
println!("Proxying to: {}", server_addr);
let mut listener = TcpListener::bind(listen_addr).await?;
let listener = TcpListener::bind(listen_addr).await?;
while let Ok((inbound, _)) = listener.accept().await {
let transfer = transfer(inbound, server_addr.clone()).map(|r| {
@@ -63,10 +63,17 @@ async fn transfer(mut inbound: TcpStream, proxy_addr: String) -> Result<(), Box<
let (mut ri, mut wi) = inbound.split();
let (mut ro, mut wo) = outbound.split();
let client_to_server = io::copy(&mut ri, &mut wo);
let server_to_client = io::copy(&mut ro, &mut wi);
let client_to_server = async {
io::copy(&mut ri, &mut wo).await?;
wo.shutdown().await
};
try_join(client_to_server, server_to_client).await?;
let server_to_client = async {
io::copy(&mut ro, &mut wi).await?;
wi.shutdown().await
};
tokio::try_join!(client_to_server, server_to_client)?;
Ok(())
}
+2 -2
View File
@@ -42,7 +42,7 @@
#![warn(rust_2018_idioms)]
use tokio::net::TcpListener;
use tokio::stream::StreamExt;
use tokio_stream::StreamExt;
use tokio_util::codec::{Framed, LinesCodec};
use futures::SinkExt;
@@ -89,7 +89,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
.nth(1)
.unwrap_or_else(|| "127.0.0.1:8080".to_string());
let mut listener = TcpListener::bind(&addr).await?;
let listener = TcpListener::bind(&addr).await?;
println!("Listening on: {}", addr);
// Create the shared state of this server that will be shared amongst all
+4 -7
View File
@@ -18,10 +18,9 @@ use futures::SinkExt;
use http::{header::HeaderValue, Request, Response, StatusCode};
#[macro_use]
extern crate serde_derive;
use serde_json;
use std::{env, error::Error, fmt, io};
use tokio::net::{TcpListener, TcpStream};
use tokio::stream::StreamExt;
use tokio_stream::StreamExt;
use tokio_util::codec::{Decoder, Encoder, Framed};
#[tokio::main]
@@ -31,19 +30,17 @@ async fn main() -> Result<(), Box<dyn Error>> {
let addr = env::args()
.nth(1)
.unwrap_or_else(|| "127.0.0.1:8080".to_string());
let mut server = TcpListener::bind(&addr).await?;
let mut incoming = server.incoming();
let server = TcpListener::bind(&addr).await?;
println!("Listening on: {}", addr);
while let Some(Ok(stream)) = incoming.next().await {
loop {
let (stream, _) = server.accept().await?;
tokio::spawn(async move {
if let Err(e) = process(stream).await {
println!("failed to process connection; error = {}", e);
}
});
}
Ok(())
}
async fn process(stream: TcpStream) -> Result<(), Box<dyn Error>> {
+1 -1
View File
@@ -55,7 +55,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
}
.parse()?;
let mut socket = UdpSocket::bind(local_addr).await?;
let socket = UdpSocket::bind(local_addr).await?;
const MAX_DATAGRAM_SIZE: usize = 65_507;
socket.connect(&remote_addr).await?;
let data = get_stdin_data()?;
+2 -2
View File
@@ -9,8 +9,8 @@
#![warn(rust_2018_idioms)]
use tokio::net::UdpSocket;
use tokio::stream::StreamExt;
use tokio::{io, time};
use tokio_stream::StreamExt;
use tokio_util::codec::BytesCodec;
use tokio_util::udp::UdpFramed;
@@ -45,7 +45,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
let b = pong(&mut b);
// Run both futures simultaneously of `a` and `b` sending messages back and forth.
match futures::future::try_join(a, b).await {
match tokio::try_join!(a, b) {
Err(e) => println!("an error occurred; error = {:?}", e),
_ => println!("done!"),
}
+14
View File
@@ -0,0 +1,14 @@
[package]
name = "stress-test"
version = "0.1.0"
authors = ["Tokio Contributors <[email protected]>"]
edition = "2018"
publish = false
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
tokio = { path = "../tokio/", features = ["full"] }
[dev-dependencies]
rand = "0.8"
+58
View File
@@ -0,0 +1,58 @@
//! Simple TCP echo server to check memory leaks using Valgrind.
use std::{thread::sleep, time::Duration};
use tokio::{
io::{AsyncReadExt, AsyncWriteExt},
net::{TcpListener, TcpSocket},
runtime::Builder,
sync::oneshot,
};
const TCP_ENDPOINT: &str = "127.0.0.1:8080";
const NUM_MSGS: usize = 100;
const MSG_SIZE: usize = 1024;
fn main() {
let rt = Builder::new_multi_thread().enable_io().build().unwrap();
let rt2 = Builder::new_multi_thread().enable_io().build().unwrap();
rt.spawn(async {
let listener = TcpListener::bind(TCP_ENDPOINT).await.unwrap();
let (mut socket, _) = listener.accept().await.unwrap();
let (mut rd, mut wr) = socket.split();
while tokio::io::copy(&mut rd, &mut wr).await.is_ok() {}
});
// wait a bit so that the listener binds.
sleep(Duration::from_millis(100));
// create a channel to let the main thread know that all the messages were sent and received.
let (tx, mut rx) = oneshot::channel();
rt2.spawn(async {
let addr = TCP_ENDPOINT.parse().unwrap();
let socket = TcpSocket::new_v4().unwrap();
let mut stream = socket.connect(addr).await.unwrap();
let mut buff = [0; MSG_SIZE];
for _ in 0..NUM_MSGS {
let one_mega_random_bytes: Vec<u8> =
(0..MSG_SIZE).map(|_| rand::random::<u8>()).collect();
stream
.write_all(one_mega_random_bytes.as_slice())
.await
.unwrap();
stream.read(&mut buff).await.unwrap();
}
tx.send(()).unwrap();
});
loop {
// check that we're done.
match rx.try_recv() {
Err(oneshot::error::TryRecvError::Empty) => (),
Err(oneshot::error::TryRecvError::Closed) => panic!("channel got closed..."),
Ok(()) => break,
}
}
}
+1
View File
@@ -7,6 +7,7 @@ publish = false
[features]
full = ["tokio/full"]
rt = ["tokio/rt", "tokio/macros"]
[dependencies]
tokio = { path = "../tokio", optional = true }
@@ -0,0 +1,6 @@
use tests_build::tokio;
#[tokio::main]
async fn my_fn() {}
fn main() {}
@@ -0,0 +1,7 @@
error: The default runtime flavor is `multi_thread`, but the `rt-multi-thread` feature is disabled.
--> $DIR/macros_core_no_default.rs:3:1
|
3 | #[tokio::main]
| ^^^^^^^^^^^^^^
|
= note: this error originates in an attribute macro (in Nightly builds, run with -Z macro-backtrace for more info)
@@ -4,7 +4,7 @@ error: the async keyword is missing from the function declaration
4 | fn main_is_not_async() {}
| ^^
error: Unknown attribute foo is specified; expected `basic_scheduler` or `threaded_scheduler`
error: Unknown attribute foo is specified; expected one of: `flavor`, `worker_threads`, `start_paused`
--> $DIR/macros_invalid_input.rs:6:15
|
6 | #[tokio::main(foo)]
@@ -28,7 +28,7 @@ error: the test function cannot accept arguments
16 | async fn test_fn_has_args(_x: u8) {}
| ^^^^^^
error: Unknown attribute foo is specified; expected `basic_scheduler` or `threaded_scheduler`
error: Unknown attribute foo is specified; expected one of: `flavor`, `worker_threads`, `start_paused`
--> $DIR/macros_invalid_input.rs:18:15
|
18 | #[tokio::test(foo)]
+4 -1
View File
@@ -1,9 +1,12 @@
#[test]
fn compile_fail() {
fn compile_fail_full() {
let t = trybuild::TestCases::new();
#[cfg(feature = "full")]
t.compile_fail("tests/fail/macros_invalid_input.rs");
#[cfg(all(feature = "rt", not(feature = "full")))]
t.compile_fail("tests/fail/macros_core_no_default.rs");
drop(t);
}
+14 -6
View File
@@ -5,24 +5,32 @@ authors = ["Tokio Contributors <[email protected]>"]
edition = "2018"
publish = false
[[bin]]
name = "test-cat"
[[bin]]
name = "test-mem"
required-features = ["rt-net"]
[features]
# For mem check
rt-net = ["tokio/rt", "tokio/rt-multi-thread", "tokio/net"]
full = [
"macros",
"rt-core",
"rt-threaded",
"rt",
"rt-multi-thread",
"tokio/full",
"tokio-test"
]
macros = ["tokio/macros"]
sync = ["tokio/sync"]
rt-core = ["tokio/rt-core"]
rt-threaded = ["rt-core", "tokio/rt-threaded"]
rt = ["tokio/rt"]
rt-multi-thread = ["rt", "tokio/rt-multi-thread"]
[dependencies]
tokio = { path = "../tokio" }
tokio-test = { path = "../tokio-test", optional = true }
doc-comment = "0.3.1"
[dev-dependencies]
futures = { version = "0.3.0", features = ["async-await"] }
+21
View File
@@ -0,0 +1,21 @@
use futures::future::poll_fn;
fn main() {
let rt = tokio::runtime::Builder::new_multi_thread()
.worker_threads(1)
.enable_io()
.build()
.unwrap();
rt.block_on(async {
let listener = tokio::net::TcpListener::bind("0.0.0.0:0").await.unwrap();
tokio::spawn(async move {
loop {
poll_fn(|cx| listener.poll_accept(cx)).await.unwrap();
}
});
});
std::thread::sleep(std::time::Duration::from_millis(50));
drop(rt);
}
+9 -12
View File
@@ -1,4 +1,4 @@
#![cfg(feature = "macros")]
#![cfg(all(feature = "macros", feature = "rt"))]
#[tokio::main]
async fn basic_main() -> usize {
@@ -10,18 +10,15 @@ async fn generic_fun<T: Default>() -> T {
T::default()
}
#[cfg(feature = "rt-core")]
mod spawn {
#[tokio::main]
async fn spawning() -> usize {
let join = tokio::spawn(async { 1 });
join.await.unwrap()
}
#[tokio::main]
async fn spawning() -> usize {
let join = tokio::spawn(async { 1 });
join.await.unwrap()
}
#[test]
fn main_with_spawn() {
assert_eq!(1, spawning());
}
#[test]
fn main_with_spawn() {
assert_eq!(1, spawning());
}
#[test]
+77 -12
View File
@@ -1,26 +1,19 @@
#![warn(rust_2018_idioms)]
#![cfg(feature = "full")]
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};
use tokio::join;
use tokio::process::{Child, Command};
use tokio_test::assert_ok;
use futures::future::{self, FutureExt};
use std::convert::TryInto;
use std::env;
use std::io;
use std::process::{ExitStatus, Stdio};
fn cat() -> Command {
let mut me = env::current_exe().unwrap();
me.pop();
if me.ends_with("deps") {
me.pop();
}
me.push("test-cat");
let mut cmd = Command::new(me);
let mut cmd = Command::new(env!("CARGO_BIN_EXE_test-cat"));
cmd.stdin(Stdio::piped()).stdout(Stdio::piped());
cmd
}
@@ -72,7 +65,7 @@ async fn feed_cat(mut cat: Child, n: usize) -> io::Result<ExitStatus> {
};
// Compose reading and writing concurrently.
future::join3(write, read, cat)
future::join3(write, read, cat.wait())
.map(|(_, _, status)| status)
.await
}
@@ -125,3 +118,75 @@ async fn status_closes_any_pipes() {
assert_ok!(child.await);
}
#[tokio::test]
async fn try_wait() {
let mut child = cat().spawn().unwrap();
let id = child.id().expect("missing id");
assert!(id > 0);
assert_eq!(None, assert_ok!(child.try_wait()));
// Drop the child's stdio handles so it can terminate
drop(child.stdin.take());
drop(child.stderr.take());
drop(child.stdout.take());
assert_ok!(child.wait().await);
// test that the `.try_wait()` method is fused just like the stdlib
assert!(assert_ok!(child.try_wait()).unwrap().success());
// Can't get id after process has exited
assert_eq!(child.id(), None);
}
#[tokio::test]
async fn pipe_from_one_command_to_another() {
let mut first = cat().spawn().expect("first cmd");
let mut third = cat().spawn().expect("third cmd");
// Convert ChildStdout to Stdio
let second_stdin: Stdio = first
.stdout
.take()
.expect("first.stdout")
.try_into()
.expect("first.stdout into Stdio");
// Convert ChildStdin to Stdio
let second_stdout: Stdio = third
.stdin
.take()
.expect("third.stdin")
.try_into()
.expect("third.stdin into Stdio");
let mut second = cat()
.stdin(second_stdin)
.stdout(second_stdout)
.spawn()
.expect("first cmd");
let msg = "hello world! please pipe this message through";
let mut stdin = first.stdin.take().expect("first.stdin");
let write = async move { stdin.write_all(msg.as_bytes()).await };
let mut stdout = third.stdout.take().expect("third.stdout");
let read = async move {
let mut data = String::new();
stdout.read_to_string(&mut data).await.map(|_| data)
};
let (read, write, first_status, second_status, third_status) =
join!(read, write, first.wait(), second.wait(), third.wait());
assert_eq!(msg, read.expect("read result"));
write.expect("write result");
assert!(first_status.expect("first status").success());
assert!(second_status.expect("second status").success());
assert!(third_status.expect("third status").success());
}
-32
View File
@@ -1,32 +0,0 @@
#![warn(rust_2018_idioms)]
#![cfg(feature = "sync")]
use tokio::runtime;
use tokio::sync::oneshot;
use std::sync::mpsc;
use std::thread;
#[test]
fn basic_shell_rt() {
let (feed_tx, feed_rx) = mpsc::channel::<oneshot::Sender<()>>();
let th = thread::spawn(move || {
for tx in feed_rx.iter() {
tx.send(()).unwrap();
}
});
for _ in 0..1_000 {
let mut rt = runtime::Builder::new().build().unwrap();
let (tx, rx) = oneshot::channel();
feed_tx.send(tx).unwrap();
rt.block_on(rx).unwrap();
}
drop(feed_tx);
th.join().unwrap();
}
+29 -5
View File
@@ -1,3 +1,25 @@
# 1.1.0 (February 5, 2021)
- add `start_paused` option to macros ([#3492])
# 1.0.0 (December 23, 2020)
- track `tokio` 1.0 release.
# 0.3.1 (October 25, 2020)
### Fixed
- fix incorrect docs regarding `max_threads` option ([#3038])
# 0.3.0 (October 15, 2020)
- Track `tokio` 0.3 release.
### Changed
- options are renamed to track `tokio` runtime builder fn names.
- `#[tokio::main]` macro requires `rt-multi-thread` when no `flavor` is specified.
# 0.2.5 (February 27, 2019)
### Fixed
@@ -30,9 +52,11 @@
- Initial release
[#2225]: https://github.com/tokio-rs/tokio/pull/2225
[#2177]: https://github.com/tokio-rs/tokio/pull/2177
[#2152]: https://github.com/tokio-rs/tokio/pull/2152
[#2038]: https://github.com/tokio-rs/tokio/pull/2038
[#2022]: https://github.com/tokio-rs/tokio/pull/2022
[#1954]: https://github.com/tokio-rs/tokio/pull/1954
[#2022]: https://github.com/tokio-rs/tokio/pull/2022
[#2038]: https://github.com/tokio-rs/tokio/pull/2038
[#2152]: https://github.com/tokio-rs/tokio/pull/2152
[#2177]: https://github.com/tokio-rs/tokio/pull/2177
[#2225]: https://github.com/tokio-rs/tokio/pull/2225
[#3038]: https://github.com/tokio-rs/tokio/pull/3038
[#3492]: https://github.com/tokio-rs/tokio/pull/3492
+4 -4
View File
@@ -6,14 +6,14 @@ name = "tokio-macros"
# - Update doc url
# - Cargo.toml
# - Update CHANGELOG.md.
# - Create "v0.1.x" git tag.
version = "0.2.5"
# - Create "tokio-macros-1.0.x" git tag.
version = "1.1.0"
edition = "2018"
authors = ["Tokio Contributors <[email protected]>"]
license = "MIT"
repository = "https://github.com/tokio-rs/tokio"
homepage = "https://tokio.rs"
documentation = "https://docs.rs/tokio-macros/0.2.5/tokio_macros"
documentation = "https://docs.rs/tokio-macros/1.1.0/tokio_macros"
description = """
Tokio's proc macros.
"""
@@ -30,7 +30,7 @@ quote = "1"
syn = { version = "1.0.3", features = ["full"] }
[dev-dependencies]
tokio = { version = "0.2.0", path = "../tokio", features = ["full"] }
tokio = { version = "1.0.0", path = "../tokio", features = ["full"] }
[package.metadata.docs.rs]
all-features = true
+1 -1
View File
@@ -1,4 +1,4 @@
Copyright (c) 2019 Tokio Contributors
Copyright (c) 2020 Tokio Contributors
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
+228 -242
View File
@@ -1,18 +1,183 @@
use proc_macro::TokenStream;
use proc_macro2::Span;
use quote::quote;
use std::num::NonZeroUsize;
use syn::spanned::Spanned;
#[derive(Clone, Copy, PartialEq)]
enum Runtime {
Basic,
enum RuntimeFlavor {
CurrentThread,
Threaded,
}
impl RuntimeFlavor {
fn from_str(s: &str) -> Result<RuntimeFlavor, String> {
match s {
"current_thread" => Ok(RuntimeFlavor::CurrentThread),
"multi_thread" => Ok(RuntimeFlavor::Threaded),
"single_thread" => Err("The single threaded runtime flavor is called `current_thread`.".to_string()),
"basic_scheduler" => Err("The `basic_scheduler` runtime flavor has been renamed to `current_thread`.".to_string()),
"threaded_scheduler" => Err("The `threaded_scheduler` runtime flavor has been renamed to `multi_thread`.".to_string()),
_ => Err(format!("No such runtime flavor `{}`. The runtime flavors are `current_thread` and `multi_thread`.", s)),
}
}
}
struct FinalConfig {
flavor: RuntimeFlavor,
worker_threads: Option<usize>,
start_paused: Option<bool>,
}
struct Configuration {
rt_multi_thread_available: bool,
default_flavor: RuntimeFlavor,
flavor: Option<RuntimeFlavor>,
worker_threads: Option<(usize, Span)>,
start_paused: Option<(bool, Span)>,
}
impl Configuration {
fn new(is_test: bool, rt_multi_thread: bool) -> Self {
Configuration {
rt_multi_thread_available: rt_multi_thread,
default_flavor: match is_test {
true => RuntimeFlavor::CurrentThread,
false => RuntimeFlavor::Threaded,
},
flavor: None,
worker_threads: None,
start_paused: None,
}
}
fn set_flavor(&mut self, runtime: syn::Lit, span: Span) -> Result<(), syn::Error> {
if self.flavor.is_some() {
return Err(syn::Error::new(span, "`flavor` set multiple times."));
}
let runtime_str = parse_string(runtime, span, "flavor")?;
let runtime =
RuntimeFlavor::from_str(&runtime_str).map_err(|err| syn::Error::new(span, err))?;
self.flavor = Some(runtime);
Ok(())
}
fn set_worker_threads(
&mut self,
worker_threads: syn::Lit,
span: Span,
) -> Result<(), syn::Error> {
if self.worker_threads.is_some() {
return Err(syn::Error::new(
span,
"`worker_threads` set multiple times.",
));
}
let worker_threads = parse_int(worker_threads, span, "worker_threads")?;
if worker_threads == 0 {
return Err(syn::Error::new(span, "`worker_threads` may not be 0."));
}
self.worker_threads = Some((worker_threads, span));
Ok(())
}
fn set_start_paused(&mut self, start_paused: syn::Lit, span: Span) -> Result<(), syn::Error> {
if self.start_paused.is_some() {
return Err(syn::Error::new(span, "`start_paused` set multiple times."));
}
let start_paused = parse_bool(start_paused, span, "start_paused")?;
self.start_paused = Some((start_paused, span));
Ok(())
}
fn build(&self) -> Result<FinalConfig, syn::Error> {
let flavor = self.flavor.unwrap_or(self.default_flavor);
use RuntimeFlavor::*;
let worker_threads = match (flavor, self.worker_threads) {
(CurrentThread, Some((_, worker_threads_span))) => {
return Err(syn::Error::new(
worker_threads_span,
"The `worker_threads` option requires the `multi_thread` runtime flavor.",
))
}
(CurrentThread, None) => None,
(Threaded, worker_threads) if self.rt_multi_thread_available => {
worker_threads.map(|(val, _span)| val)
}
(Threaded, _) => {
let msg = if self.flavor.is_none() {
"The default runtime flavor is `multi_thread`, but the `rt-multi-thread` feature is disabled."
} else {
"The runtime flavor `multi_thread` requires the `rt-multi-thread` feature."
};
return Err(syn::Error::new(Span::call_site(), msg));
}
};
let start_paused = match (flavor, self.start_paused) {
(Threaded, Some((_, start_paused_span))) => {
return Err(syn::Error::new(
start_paused_span,
"The `start_paused` option requires the `current_thread` runtime flavor.",
));
}
(CurrentThread, Some((start_paused, _))) => Some(start_paused),
(_, None) => None,
};
Ok(FinalConfig {
flavor,
worker_threads,
start_paused,
})
}
}
fn parse_int(int: syn::Lit, span: Span, field: &str) -> Result<usize, syn::Error> {
match int {
syn::Lit::Int(lit) => match lit.base10_parse::<usize>() {
Ok(value) => Ok(value),
Err(e) => Err(syn::Error::new(
span,
format!("Failed to parse {} as integer: {}", field, e),
)),
},
_ => Err(syn::Error::new(
span,
format!("Failed to parse {} as integer.", field),
)),
}
}
fn parse_string(int: syn::Lit, span: Span, field: &str) -> Result<String, syn::Error> {
match int {
syn::Lit::Str(s) => Ok(s.value()),
syn::Lit::Verbatim(s) => Ok(s.to_string()),
_ => Err(syn::Error::new(
span,
format!("Failed to parse {} as string.", field),
)),
}
}
fn parse_bool(bool: syn::Lit, span: Span, field: &str) -> Result<bool, syn::Error> {
match bool {
syn::Lit::Bool(b) => Ok(b.value),
_ => Err(syn::Error::new(
span,
format!("Failed to parse {} as bool.", field),
)),
}
}
fn parse_knobs(
mut input: syn::ItemFn,
args: syn::AttributeArgs,
is_test: bool,
rt_threaded: bool,
rt_multi_thread: bool,
) -> Result<TokenStream, syn::Error> {
let sig = &mut input.sig;
let body = &input.block;
@@ -26,9 +191,12 @@ fn parse_knobs(
sig.asyncness = None;
let mut runtime = None;
let mut core_threads = None;
let mut max_threads = None;
let macro_name = if is_test {
"tokio::test"
} else {
"tokio::main"
};
let mut config = Configuration::new(is_test, rt_multi_thread);
for arg in args {
match arg {
@@ -39,65 +207,21 @@ fn parse_knobs(
return Err(syn::Error::new_spanned(namevalue, msg));
}
match ident.unwrap().to_string().to_lowercase().as_str() {
"core_threads" => {
if rt_threaded {
match &namevalue.lit {
syn::Lit::Int(expr) => {
let num = expr.base10_parse::<NonZeroUsize>().unwrap();
if num.get() > 1 {
runtime = Some(Runtime::Threaded);
} else {
runtime = Some(Runtime::Basic);
}
if let Some(v) = max_threads {
if v < num {
return Err(syn::Error::new_spanned(
namevalue,
"max_threads cannot be less than core_threads",
));
}
}
core_threads = Some(num);
}
_ => {
return Err(syn::Error::new_spanned(
namevalue,
"core_threads argument must be an int",
))
}
}
} else {
return Err(syn::Error::new_spanned(
namevalue,
"core_threads can only be set with rt-threaded feature flag enabled",
));
}
"worker_threads" => {
config.set_worker_threads(namevalue.lit.clone(), namevalue.span())?;
}
"flavor" => {
config.set_flavor(namevalue.lit.clone(), namevalue.span())?;
}
"start_paused" => {
config.set_start_paused(namevalue.lit.clone(), namevalue.span())?;
}
"core_threads" => {
let msg = "Attribute `core_threads` is renamed to `worker_threads`";
return Err(syn::Error::new_spanned(namevalue, msg));
}
"max_threads" => match &namevalue.lit {
syn::Lit::Int(expr) => {
let num = expr.base10_parse::<NonZeroUsize>().unwrap();
if let Some(v) = core_threads {
if num < v {
return Err(syn::Error::new_spanned(
namevalue,
"max_threads cannot be less than core_threads",
));
}
}
max_threads = Some(num);
}
_ => {
return Err(syn::Error::new_spanned(
namevalue,
"max_threads argument must be an int",
))
}
},
name => {
let msg = format!("Unknown attribute pair {} is specified; expected one of: `core_threads`, `max_threads`", name);
let msg = format!("Unknown attribute {} is specified; expected one of: `flavor`, `worker_threads`", name);
return Err(syn::Error::new_spanned(namevalue, msg));
}
}
@@ -108,16 +232,28 @@ fn parse_knobs(
let msg = "Must have specified ident";
return Err(syn::Error::new_spanned(path, msg));
}
match ident.unwrap().to_string().to_lowercase().as_str() {
"threaded_scheduler" => {
runtime = Some(runtime.unwrap_or_else(|| Runtime::Threaded))
let name = ident.unwrap().to_string().to_lowercase();
let msg = match name.as_str() {
"threaded_scheduler" | "multi_thread" => {
format!(
"Set the runtime flavor with #[{}(flavor = \"multi_thread\")].",
macro_name
)
}
"basic_scheduler" | "current_thread" | "single_threaded" => {
format!(
"Set the runtime flavor with #[{}(flavor = \"current_thread\")].",
macro_name
)
}
"flavor" | "worker_threads" | "start_paused" => {
format!("The `{}` attribute requires an argument.", name)
}
"basic_scheduler" => runtime = Some(runtime.unwrap_or_else(|| Runtime::Basic)),
name => {
let msg = format!("Unknown attribute {} is specified; expected `basic_scheduler` or `threaded_scheduler`", name);
return Err(syn::Error::new_spanned(path, msg));
format!("Unknown attribute {} is specified; expected one of: `flavor`, `worker_threads`, `start_paused`", name)
}
}
};
return Err(syn::Error::new_spanned(path, msg));
}
other => {
return Err(syn::Error::new_spanned(
@@ -128,21 +264,27 @@ fn parse_knobs(
}
}
let mut rt = quote! { tokio::runtime::Builder::new().basic_scheduler() };
if rt_threaded && (runtime == Some(Runtime::Threaded) || (runtime.is_none() && !is_test)) {
rt = quote! { #rt.threaded_scheduler() };
let config = config.build()?;
let mut rt = match config.flavor {
RuntimeFlavor::CurrentThread => quote! {
tokio::runtime::Builder::new_current_thread()
},
RuntimeFlavor::Threaded => quote! {
tokio::runtime::Builder::new_multi_thread()
},
};
if let Some(v) = config.worker_threads {
rt = quote! { #rt.worker_threads(#v) };
}
if let Some(v) = core_threads.map(|v| v.get()) {
rt = quote! { #rt.core_threads(#v) };
}
if let Some(v) = max_threads.map(|v| v.get()) {
rt = quote! { #rt.max_threads(#v) };
if let Some(v) = config.start_paused {
rt = quote! { #rt.start_paused(#v) };
}
let header = {
if is_test {
quote! {
#[test]
#[::core::prelude::v1::test]
}
} else {
quote! {}
@@ -157,7 +299,7 @@ fn parse_knobs(
.enable_all()
.build()
.unwrap()
.block_on(async { #body })
.block_on(async #body)
}
};
@@ -165,21 +307,21 @@ fn parse_knobs(
}
#[cfg(not(test))] // Work around for rust-lang/rust#62127
pub(crate) fn main(args: TokenStream, item: TokenStream, rt_threaded: bool) -> TokenStream {
pub(crate) fn main(args: TokenStream, item: TokenStream, rt_multi_thread: bool) -> TokenStream {
let input = syn::parse_macro_input!(item as syn::ItemFn);
let args = syn::parse_macro_input!(args as syn::AttributeArgs);
if input.sig.ident == "main" && !input.sig.inputs.is_empty() {
let msg = "the main function cannot accept arguments";
return syn::Error::new_spanned(&input.sig.inputs, msg)
return syn::Error::new_spanned(&input.sig.ident, msg)
.to_compile_error()
.into();
}
parse_knobs(input, args, false, rt_threaded).unwrap_or_else(|e| e.to_compile_error().into())
parse_knobs(input, args, false, rt_multi_thread).unwrap_or_else(|e| e.to_compile_error().into())
}
pub(crate) fn test(args: TokenStream, item: TokenStream, rt_threaded: bool) -> TokenStream {
pub(crate) fn test(args: TokenStream, item: TokenStream, rt_multi_thread: bool) -> TokenStream {
let input = syn::parse_macro_input!(item as syn::ItemFn);
let args = syn::parse_macro_input!(args as syn::AttributeArgs);
@@ -199,161 +341,5 @@ pub(crate) fn test(args: TokenStream, item: TokenStream, rt_threaded: bool) -> T
.into();
}
parse_knobs(input, args, true, rt_threaded).unwrap_or_else(|e| e.to_compile_error().into())
}
pub(crate) mod old {
use proc_macro::TokenStream;
use quote::quote;
enum Runtime {
Basic,
Threaded,
Auto,
}
#[cfg(not(test))] // Work around for rust-lang/rust#62127
pub(crate) fn main(args: TokenStream, item: TokenStream) -> TokenStream {
let mut input = syn::parse_macro_input!(item as syn::ItemFn);
let args = syn::parse_macro_input!(args as syn::AttributeArgs);
let sig = &mut input.sig;
let name = &sig.ident;
let inputs = &sig.inputs;
let body = &input.block;
let attrs = &input.attrs;
let vis = input.vis;
if sig.asyncness.is_none() {
let msg = "the async keyword is missing from the function declaration";
return syn::Error::new_spanned(sig.fn_token, msg)
.to_compile_error()
.into();
} else if name == "main" && !inputs.is_empty() {
let msg = "the main function cannot accept arguments";
return syn::Error::new_spanned(&sig.inputs, msg)
.to_compile_error()
.into();
}
sig.asyncness = None;
let mut runtime = Runtime::Auto;
for arg in args {
if let syn::NestedMeta::Meta(syn::Meta::Path(path)) = arg {
let ident = path.get_ident();
if ident.is_none() {
let msg = "Must have specified ident";
return syn::Error::new_spanned(path, msg).to_compile_error().into();
}
match ident.unwrap().to_string().to_lowercase().as_str() {
"threaded_scheduler" => runtime = Runtime::Threaded,
"basic_scheduler" => runtime = Runtime::Basic,
name => {
let msg = format!("Unknown attribute {} is specified; expected `basic_scheduler` or `threaded_scheduler`", name);
return syn::Error::new_spanned(path, msg).to_compile_error().into();
}
}
}
}
let result = match runtime {
Runtime::Threaded | Runtime::Auto => quote! {
#(#attrs)*
#vis #sig {
tokio::runtime::Runtime::new().unwrap().block_on(async { #body })
}
},
Runtime::Basic => quote! {
#(#attrs)*
#vis #sig {
tokio::runtime::Builder::new()
.basic_scheduler()
.enable_all()
.build()
.unwrap()
.block_on(async { #body })
}
},
};
result.into()
}
pub(crate) fn test(args: TokenStream, item: TokenStream) -> TokenStream {
let input = syn::parse_macro_input!(item as syn::ItemFn);
let args = syn::parse_macro_input!(args as syn::AttributeArgs);
let ret = &input.sig.output;
let name = &input.sig.ident;
let body = &input.block;
let attrs = &input.attrs;
let vis = input.vis;
for attr in attrs {
if attr.path.is_ident("test") {
let msg = "second test attribute is supplied";
return syn::Error::new_spanned(&attr, msg)
.to_compile_error()
.into();
}
}
if input.sig.asyncness.is_none() {
let msg = "the async keyword is missing from the function declaration";
return syn::Error::new_spanned(&input.sig.fn_token, msg)
.to_compile_error()
.into();
} else if !input.sig.inputs.is_empty() {
let msg = "the test function cannot accept arguments";
return syn::Error::new_spanned(&input.sig.inputs, msg)
.to_compile_error()
.into();
}
let mut runtime = Runtime::Auto;
for arg in args {
if let syn::NestedMeta::Meta(syn::Meta::Path(path)) = arg {
let ident = path.get_ident();
if ident.is_none() {
let msg = "Must have specified ident";
return syn::Error::new_spanned(path, msg).to_compile_error().into();
}
match ident.unwrap().to_string().to_lowercase().as_str() {
"threaded_scheduler" => runtime = Runtime::Threaded,
"basic_scheduler" => runtime = Runtime::Basic,
name => {
let msg = format!("Unknown attribute {} is specified; expected `basic_scheduler` or `threaded_scheduler`", name);
return syn::Error::new_spanned(path, msg).to_compile_error().into();
}
}
}
}
let result = match runtime {
Runtime::Threaded => quote! {
#[test]
#(#attrs)*
#vis fn #name() #ret {
tokio::runtime::Runtime::new().unwrap().block_on(async { #body })
}
},
Runtime::Basic | Runtime::Auto => quote! {
#[test]
#(#attrs)*
#vis fn #name() #ret {
tokio::runtime::Builder::new()
.basic_scheduler()
.enable_all()
.build()
.unwrap()
.block_on(async { #body })
}
},
};
result.into()
}
parse_knobs(input, args, true, rt_multi_thread).unwrap_or_else(|e| e.to_compile_error().into())
}
+196 -81
View File
@@ -1,4 +1,4 @@
#![doc(html_root_url = "https://docs.rs/tokio-macros/0.2.5")]
#![doc(html_root_url = "https://docs.rs/tokio-macros/1.1.0")]
#![allow(clippy::needless_doctest_main)]
#![warn(
missing_debug_implementations,
@@ -6,7 +6,7 @@
rust_2018_idioms,
unreachable_pub
)]
#![deny(intra_doc_link_resolution_failure)]
#![cfg_attr(docsrs, deny(broken_intra_doc_links))]
#![doc(test(
no_crate_inject,
attr(deny(warnings, rust_2018_idioms), allow(dead_code, unused_variables))
@@ -24,13 +24,47 @@ mod select;
use proc_macro::TokenStream;
/// Marks async function to be executed by selected runtime.
/// Marks async function to be executed by the selected runtime. This macro
/// helps set up a `Runtime` without requiring the user to use
/// [Runtime](../tokio/runtime/struct.Runtime.html) or
/// [Builder](../tokio/runtime/struct.Builder.html) directly.
///
/// ## Options:
/// Note: This macro is designed to be simplistic and targets applications that
/// do not require a complex setup. If the provided functionality is not
/// sufficient, you may be interested in using
/// [Builder](../tokio/runtime/struct.Builder.html), which provides a more
/// powerful interface.
///
/// Note: This macro can be used on any function and not just the `main`
/// function. Using it on a non-main function makes the function behave as if it
/// was synchronous by starting a new runtime each time it is called. If the
/// function is called often, it is preferable to create the runtime using the
/// runtime builder so the runtime can be reused across calls.
///
/// - `core_threads=n` - Sets core threads to `n` (requires `rt-threaded` feature).
/// - `max_threads=n` - Sets max threads to `n` (requires `rt-core` or `rt-threaded` feature).
/// # Multi-threaded runtime
///
/// To use the multi-threaded runtime, the macro can be configured using
///
/// ```
/// #[tokio::main(flavor = "multi_thread", worker_threads = 10)]
/// # async fn main() {}
/// ```
///
/// The `worker_threads` option configures the number of worker threads, and
/// defaults to the number of cpus on the system. This is the default flavor.
///
/// Note: The multi-threaded runtime requires the `rt-multi-thread` feature
/// flag.
///
/// # Current thread runtime
///
/// To use the single-threaded runtime known as the `current_thread` runtime,
/// the macro can be configured using
///
/// ```
/// #[tokio::main(flavor = "current_thread")]
/// # async fn main() {}
/// ```
///
/// ## Function arguments:
///
@@ -38,7 +72,7 @@ use proc_macro::TokenStream;
///
/// ## Usage
///
/// ### Using default
/// ### Using the multi-thread runtime
///
/// ```rust
/// #[tokio::main]
@@ -47,61 +81,108 @@ use proc_macro::TokenStream;
/// }
/// ```
///
/// ### Set number of core threads
/// Equivalent code not using `#[tokio::main]`
///
/// ```rust
/// #[tokio::main(core_threads = 1)]
/// async fn main() {
/// println!("Hello world");
/// fn main() {
/// tokio::runtime::Builder::new_multi_thread()
/// .enable_all()
/// .build()
/// .unwrap()
/// .block_on(async {
/// println!("Hello world");
/// })
/// }
/// ```
#[proc_macro_attribute]
#[cfg(not(test))] // Work around for rust-lang/rust#62127
pub fn main_threaded(args: TokenStream, item: TokenStream) -> TokenStream {
entry::main(args, item, true)
}
/// Marks async function to be executed by selected runtime.
///
/// ## Options:
/// ### Using current thread runtime
///
/// - `basic_scheduler` - All tasks are executed on the current thread.
/// - `threaded_scheduler` - Uses the multi-threaded scheduler. Used by default (requires `rt-threaded` feature).
///
/// ## Function arguments:
///
/// Arguments are allowed for any functions aside from `main` which is special
///
/// ## Usage
///
/// ### Using default
/// The basic scheduler is single-threaded.
///
/// ```rust
/// #[tokio::main]
/// #[tokio::main(flavor = "current_thread")]
/// async fn main() {
/// println!("Hello world");
/// }
/// ```
///
/// ### Select runtime
/// Equivalent code not using `#[tokio::main]`
///
/// ```rust
/// #[tokio::main(basic_scheduler)]
/// fn main() {
/// tokio::runtime::Builder::new_current_thread()
/// .enable_all()
/// .build()
/// .unwrap()
/// .block_on(async {
/// println!("Hello world");
/// })
/// }
/// ```
///
/// ### Set number of worker threads
///
/// ```rust
/// #[tokio::main(worker_threads = 2)]
/// async fn main() {
/// println!("Hello world");
/// }
/// ```
///
/// Equivalent code not using `#[tokio::main]`
///
/// ```rust
/// fn main() {
/// tokio::runtime::Builder::new_multi_thread()
/// .worker_threads(2)
/// .enable_all()
/// .build()
/// .unwrap()
/// .block_on(async {
/// println!("Hello world");
/// })
/// }
/// ```
///
/// ### Configure the runtime to start with time paused
///
/// ```rust
/// #[tokio::main(flavor = "current_thread", start_paused = true)]
/// async fn main() {
/// println!("Hello world");
/// }
/// ```
///
/// Equivalent code not using `#[tokio::main]`
///
/// ```rust
/// fn main() {
/// tokio::runtime::Builder::new_current_thread()
/// .enable_all()
/// .start_paused(true)
/// .build()
/// .unwrap()
/// .block_on(async {
/// println!("Hello world");
/// })
/// }
/// ```
///
/// ### NOTE:
///
/// If you rename the Tokio crate in your dependencies this macro will not work.
/// If you must rename the current version of Tokio because you're also using an
/// older version of Tokio, you _must_ make the current version of Tokio
/// available as `tokio` in the module where this macro is expanded.
#[proc_macro_attribute]
#[cfg(not(test))] // Work around for rust-lang/rust#62127
pub fn main(args: TokenStream, item: TokenStream) -> TokenStream {
entry::old::main(args, item)
entry::main(args, item, true)
}
/// Marks async function to be executed by selected runtime.
///
/// ## Options:
///
/// - `max_threads=n` - Sets max threads to `n`.
/// Marks async function to be executed by selected runtime. This macro helps set up a `Runtime`
/// without requiring the user to use [Runtime](../tokio/runtime/struct.Runtime.html) or
/// [Builder](../tokio/runtime/struct.builder.html) directly.
///
/// ## Function arguments:
///
@@ -112,30 +193,46 @@ pub fn main(args: TokenStream, item: TokenStream) -> TokenStream {
/// ### Using default
///
/// ```rust
/// #[tokio::main]
/// #[tokio::main(flavor = "current_thread")]
/// async fn main() {
/// println!("Hello world");
/// }
/// ```
///
/// Equivalent code not using `#[tokio::main]`
///
/// ```rust
/// fn main() {
/// tokio::runtime::Builder::new_current_thread()
/// .enable_all()
/// .build()
/// .unwrap()
/// .block_on(async {
/// println!("Hello world");
/// })
/// }
/// ```
///
/// ### NOTE:
///
/// If you rename the Tokio crate in your dependencies this macro will not work.
/// If you must rename the current version of Tokio because you're also using an
/// older version of Tokio, you _must_ make the current version of Tokio
/// available as `tokio` in the module where this macro is expanded.
#[proc_macro_attribute]
#[cfg(not(test))] // Work around for rust-lang/rust#62127
pub fn main_basic(args: TokenStream, item: TokenStream) -> TokenStream {
pub fn main_rt(args: TokenStream, item: TokenStream) -> TokenStream {
entry::main(args, item, false)
}
/// Marks async function to be executed by runtime, suitable to test environment
///
/// ## Options:
///
/// - `core_threads=n` - Sets core threads to `n` (requires `rt-threaded` feature).
/// - `max_threads=n` - Sets max threads to `n` (requires `rt-core` or `rt-threaded` feature).
///
/// ## Usage
///
/// ### Select runtime
/// ### Multi-thread runtime
///
/// ```no_run
/// #[tokio::test(core_threads = 1)]
/// #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
/// async fn my_test() {
/// assert!(true);
/// }
@@ -143,65 +240,83 @@ pub fn main_basic(args: TokenStream, item: TokenStream) -> TokenStream {
///
/// ### Using default
///
/// The default test runtime is single-threaded.
///
/// ```no_run
/// #[tokio::test]
/// async fn my_test() {
/// assert!(true);
/// }
/// ```
///
/// ### Configure the runtime to start with time paused
///
/// ```no_run
/// #[tokio::test(start_paused = true)]
/// async fn my_test() {
/// assert!(true);
/// }
/// ```
///
/// ### NOTE:
///
/// If you rename the Tokio crate in your dependencies this macro will not work.
/// If you must rename the current version of Tokio because you're also using an
/// older version of Tokio, you _must_ make the current version of Tokio
/// available as `tokio` in the module where this macro is expanded.
#[proc_macro_attribute]
pub fn test_threaded(args: TokenStream, item: TokenStream) -> TokenStream {
pub fn test(args: TokenStream, item: TokenStream) -> TokenStream {
entry::test(args, item, true)
}
/// Marks async function to be executed by runtime, suitable to test environment
///
/// ## Options:
///
/// - `basic_scheduler` - All tasks are executed on the current thread. Used by default.
/// - `threaded_scheduler` - Use multi-threaded scheduler (requires `rt-threaded` feature).
///
/// ## Usage
///
/// ### Select runtime
///
/// ```no_run
/// #[tokio::test(threaded_scheduler)]
/// async fn my_test() {
/// assert!(true);
/// }
/// ```
///
/// ### Using default
///
/// ```no_run
/// #[tokio::test]
/// async fn my_test() {
/// assert!(true);
/// }
/// ```
///
/// ### NOTE:
///
/// If you rename the Tokio crate in your dependencies this macro will not work.
/// If you must rename the current version of Tokio because you're also using an
/// older version of Tokio, you _must_ make the current version of Tokio
/// available as `tokio` in the module where this macro is expanded.
#[proc_macro_attribute]
pub fn test(args: TokenStream, item: TokenStream) -> TokenStream {
entry::old::test(args, item)
pub fn test_rt(args: TokenStream, item: TokenStream) -> TokenStream {
entry::test(args, item, false)
}
/// Marks async function to be executed by runtime, suitable to test environment
///
/// ## Options:
///
/// - `max_threads=n` - Sets max threads to `n`.
///
/// ## Usage
///
/// ```no_run
/// #[tokio::test]
/// async fn my_test() {
/// assert!(true);
/// }
/// Always fails with the error message below.
/// ```text
/// The #[tokio::main] macro requires rt or rt-multi-thread.
/// ```
#[proc_macro_attribute]
pub fn test_basic(args: TokenStream, item: TokenStream) -> TokenStream {
entry::test(args, item, false)
pub fn main_fail(_args: TokenStream, _item: TokenStream) -> TokenStream {
syn::Error::new(
proc_macro2::Span::call_site(),
"The #[tokio::main] macro requires rt or rt-multi-thread.",
)
.to_compile_error()
.into()
}
/// Always fails with the error message below.
/// ```text
/// The #[tokio::test] macro requires rt or rt-multi-thread.
/// ```
#[proc_macro_attribute]
pub fn test_fail(_args: TokenStream, _item: TokenStream) -> TokenStream {
syn::Error::new(
proc_macro2::Span::call_site(),
"The #[tokio::test] macro requires rt or rt-multi-thread.",
)
.to_compile_error()
.into()
}
/// Implementation detail of the `select!` macro. This macro is **not** intended
+33
View File
@@ -0,0 +1,33 @@
# 0.1.3 (February 5, 2021)
Added
- sync: add wrapper for broadcast and watch ([#3384], [#3504])
[#3384]: https://github.com/tokio-rs/tokio/pull/3384
[#3504]: https://github.com/tokio-rs/tokio/pull/3504
# 0.1.2 (January 12, 2021)
Fixed
- docs: fix some wrappers missing in documentation ([#3378])
[#3378]: https://github.com/tokio-rs/tokio/pull/3378
# 0.1.1 (January 4, 2021)
Added
- add `Stream` wrappers ([#3343])
Fixed
- move `async-stream` to `dev-dependencies` ([#3366])
[#3366]: https://github.com/tokio-rs/tokio/pull/3366
[#3343]: https://github.com/tokio-rs/tokio/pull/3343
# 0.1.0 (December 23, 2020)
- Initial release
+46
View File
@@ -0,0 +1,46 @@
[package]
name = "tokio-stream"
# When releasing to crates.io:
# - Remove path dependencies
# - Update html_root_url.
# - Update doc url
# - Cargo.toml
# - Update CHANGELOG.md.
# - Create "tokio-stream-0.1.x" git tag.
version = "0.1.3"
edition = "2018"
authors = ["Tokio Contributors <[email protected]>"]
license = "MIT"
repository = "https://github.com/tokio-rs/tokio"
homepage = "https://tokio.rs"
documentation = "https://docs.rs/tokio-stream/0.1.3/tokio_stream"
description = """
Utilities to work with `Stream` and `tokio`.
"""
categories = ["asynchronous"]
[features]
default = ["time"]
time = ["tokio/time"]
net = ["tokio/net"]
io-util = ["tokio/io-util"]
fs = ["tokio/fs"]
sync = ["tokio/sync", "tokio-util"]
[dependencies]
futures-core = { version = "0.3.0" }
pin-project-lite = "0.2.0"
tokio = { version = "1.0", features = ["sync"] }
tokio-util = { version = "0.6.3", optional = true }
[dev-dependencies]
tokio = { version = "1.0", features = ["full", "test-util"] }
async-stream = "0.3"
tokio-test = { path = "../tokio-test" }
futures = { version = "0.3", default-features = false }
proptest = "0.10.0"
[package.metadata.docs.rs]
all-features = true
rustdoc-args = ["--cfg", "docsrs"]
+1 -1
View File
@@ -1,4 +1,4 @@
Copyright (c) 2019 Tokio Contributors
Copyright (c) 2020 Tokio Contributors
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
@@ -1,10 +1,10 @@
use crate::stream::Stream;
use crate::Stream;
use core::marker::PhantomData;
use core::pin::Pin;
use core::task::{Context, Poll};
/// Stream for the [`empty`] function.
/// Stream for the [`empty`](fn@empty) function.
#[derive(Debug)]
#[must_use = "streams do nothing unless polled"]
pub struct Empty<T>(PhantomData<T>);
@@ -24,7 +24,7 @@ unsafe impl<T> Sync for Empty<T> {}
/// Basic usage:
///
/// ```
/// use tokio::stream::{self, StreamExt};
/// use tokio_stream::{self as stream, StreamExt};
///
/// #[tokio::main]
/// async fn main() {
@@ -1,13 +1,14 @@
use crate::stream::Stream;
use crate::Stream;
use core::pin::Pin;
use core::task::{Context, Poll};
/// Stream for the [`iter`] function.
/// Stream for the [`iter`](fn@iter) function.
#[derive(Debug)]
#[must_use = "streams do nothing unless polled"]
pub struct Iter<I> {
iter: I,
yield_amt: usize,
}
impl<I> Unpin for Iter<I> {}
@@ -20,7 +21,7 @@ impl<I> Unpin for Iter<I> {}
///
/// ```
/// # async fn dox() {
/// use tokio::stream::{self, StreamExt};
/// use tokio_stream::{self as stream, StreamExt};
///
/// let mut stream = stream::iter(vec![17, 19]);
///
@@ -35,6 +36,7 @@ where
{
Iter {
iter: i.into_iter(),
yield_amt: 0,
}
}
@@ -45,8 +47,18 @@ where
type Item = I::Item;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<I::Item>> {
ready!(crate::coop::poll_proceed(cx));
Poll::Ready(self.iter.next())
// TODO: add coop back
if self.yield_amt >= 32 {
self.yield_amt = 0;
cx.waker().wake_by_ref();
Poll::Pending
} else {
self.yield_amt += 1;
Poll::Ready(self.iter.next())
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
+105
View File
@@ -0,0 +1,105 @@
#![doc(html_root_url = "https://docs.rs/tokio-stream/0.1.3")]
#![allow(
clippy::cognitive_complexity,
clippy::large_enum_variant,
clippy::needless_doctest_main
)]
#![warn(
missing_debug_implementations,
missing_docs,
rust_2018_idioms,
unreachable_pub
)]
#![cfg_attr(docsrs, deny(broken_intra_doc_links))]
#![doc(test(
no_crate_inject,
attr(deny(warnings, rust_2018_idioms), allow(dead_code, unused_variables))
))]
#![cfg_attr(docsrs, feature(doc_cfg))]
#![cfg_attr(docsrs, deny(broken_intra_doc_links))]
#![doc(test(
no_crate_inject,
attr(deny(warnings, rust_2018_idioms), allow(dead_code, unused_variables))
))]
#![cfg_attr(docsrs, feature(doc_cfg))]
//! Stream utilities for Tokio.
//!
//! A `Stream` is an asynchronous sequence of values. It can be thought of as
//! an asynchronous version of the standard library's `Iterator` trait.
//!
//! This crate provides helpers to work with them. For examples of usage and a more in-depth
//! description of streams you can also refer to the [streams
//! tutorial](https://tokio.rs/tokio/tutorial/streams) on the tokio website.
//!
//! # Iterating over a Stream
//!
//! Due to similarities with the standard library's `Iterator` trait, some new
//! users may assume that they can use `for in` syntax to iterate over a
//! `Stream`, but this is unfortunately not possible. Instead, you can use a
//! `while let` loop as follows:
//!
//! ```rust
//! use tokio_stream::{self as stream, StreamExt};
//!
//! #[tokio::main]
//! async fn main() {
//! let mut stream = stream::iter(vec![0, 1, 2]);
//!
//! while let Some(value) = stream.next().await {
//! println!("Got {}", value);
//! }
//! }
//! ```
//!
//! # Returning a Stream from a function
//!
//! A common way to stream values from a function is to pass in the sender
//! half of a channel and use the receiver as the stream. This requires awaiting
//! both futures to ensure progress is made. Another alternative is the
//! [async-stream] crate, which contains macros that provide a `yield` keyword
//! and allow you to return an `impl Stream`.
//!
//! [async-stream]: https://docs.rs/async-stream
//!
//! # Conversion to and from AsyncRead/AsyncWrite
//!
//! It is often desirable to convert a `Stream` into an [`AsyncRead`],
//! especially when dealing with plaintext formats streamed over the network.
//! The opposite conversion from an [`AsyncRead`] into a `Stream` is also
//! another commonly required feature. To enable these conversions,
//! [`tokio-util`] provides the [`StreamReader`] and [`ReaderStream`]
//! types when the io feature is enabled.
//!
//! [`tokio-util`]: https://docs.rs/tokio-util/0.4/tokio_util/codec/index.html
//! [`tokio::io`]: https://docs.rs/tokio/1.0/tokio/io/index.html
//! [`AsyncRead`]: https://docs.rs/tokio/1.0/tokio/io/trait.AsyncRead.html
//! [`AsyncWrite`]: https://docs.rs/tokio/1.0/tokio/io/trait.AsyncWrite.html
//! [`ReaderStream`]: https://docs.rs/tokio-util/0.4/tokio_util/io/struct.ReaderStream.html
//! [`StreamReader`]: https://docs.rs/tokio-util/0.4/tokio_util/io/struct.StreamReader.html
#[macro_use]
mod macros;
pub mod wrappers;
mod stream_ext;
pub use stream_ext::{collect::FromStream, StreamExt};
mod empty;
pub use empty::{empty, Empty};
mod iter;
pub use iter::{iter, Iter};
mod once;
pub use once::{once, Once};
mod pending;
pub use pending::{pending, Pending};
mod stream_map;
pub use stream_map::StreamMap;
#[doc(no_inline)]
pub use futures_core::Stream;
+58
View File
@@ -0,0 +1,58 @@
macro_rules! cfg_fs {
($($item:item)*) => {
$(
#[cfg(feature = "fs")]
#[cfg_attr(docsrs, doc(cfg(feature = "fs")))]
$item
)*
}
}
macro_rules! cfg_io_util {
($($item:item)*) => {
$(
#[cfg(feature = "io-util")]
#[cfg_attr(docsrs, doc(cfg(feature = "io-util")))]
$item
)*
}
}
macro_rules! cfg_net {
($($item:item)*) => {
$(
#[cfg(feature = "net")]
#[cfg_attr(docsrs, doc(cfg(feature = "net")))]
$item
)*
}
}
macro_rules! cfg_time {
($($item:item)*) => {
$(
#[cfg(feature = "time")]
#[cfg_attr(docsrs, doc(cfg(feature = "time")))]
$item
)*
}
}
macro_rules! cfg_sync {
($($item:item)*) => {
$(
#[cfg(feature = "sync")]
#[cfg_attr(docsrs, doc(cfg(feature = "sync")))]
$item
)*
}
}
macro_rules! ready {
($e:expr $(,)?) => {
match $e {
std::task::Poll::Ready(t) => t,
std::task::Poll::Pending => return std::task::Poll::Pending,
}
};
}
@@ -1,10 +1,10 @@
use crate::stream::{self, Iter, Stream};
use crate::{Iter, Stream};
use core::option;
use core::pin::Pin;
use core::task::{Context, Poll};
/// Stream for the [`once`] function.
/// Stream for the [`once`](fn@once) function.
#[derive(Debug)]
#[must_use = "streams do nothing unless polled"]
pub struct Once<T> {
@@ -20,7 +20,7 @@ impl<I> Unpin for Once<I> {}
/// # Examples
///
/// ```
/// use tokio::stream::{self, StreamExt};
/// use tokio_stream::{self as stream, StreamExt};
///
/// #[tokio::main]
/// async fn main() {
@@ -35,7 +35,7 @@ impl<I> Unpin for Once<I> {}
/// ```
pub fn once<T>(value: T) -> Once<T> {
Once {
iter: stream::iter(Some(value).into_iter()),
iter: crate::iter(Some(value).into_iter()),
}
}
@@ -1,10 +1,10 @@
use crate::stream::Stream;
use crate::Stream;
use core::marker::PhantomData;
use core::pin::Pin;
use core::task::{Context, Poll};
/// Stream for the [`pending`] function.
/// Stream for the [`pending`](fn@pending) function.
#[derive(Debug)]
#[must_use = "streams do nothing unless polled"]
pub struct Pending<T>(PhantomData<T>);
@@ -16,7 +16,7 @@ unsafe impl<T> Sync for Pending<T> {}
/// Creates a stream that is never ready
///
/// The returned stream is never ready. Attempting to call
/// [`next()`](crate::stream::StreamExt::next) will never complete. Use
/// [`next()`](crate::StreamExt::next) will never complete. Use
/// [`stream::empty()`](super::empty()) to obtain a stream that is is
/// immediately empty but returns no values.
///
@@ -25,7 +25,7 @@ unsafe impl<T> Sync for Pending<T> {}
/// Basic usage:
///
/// ```no_run
/// use tokio::stream::{self, StreamExt};
/// use tokio_stream::{self as stream, StreamExt};
///
/// #[tokio::main]
/// async fn main() {
@@ -1,8 +1,4 @@
//! Stream utilities for Tokio.
//!
//! A `Stream` is an asynchronous sequence of values. It can be thought of as an asynchronous version of the standard library's `Iterator` trait.
//!
//! This module provides helpers to work with them.
use futures_core::Stream;
mod all;
use all::AllFuture;
@@ -13,12 +9,8 @@ use any::AnyFuture;
mod chain;
use chain::Chain;
mod collect;
use collect::Collect;
pub use collect::FromStream;
mod empty;
pub use empty::{empty, Empty};
pub(crate) mod collect;
use collect::{Collect, FromStream};
mod filter;
use filter::Filter;
@@ -32,9 +24,6 @@ use fold::FoldFuture;
mod fuse;
use fuse::Fuse;
mod iter;
pub use iter::{iter, Iter};
mod map;
use map::Map;
@@ -44,15 +33,6 @@ use merge::Merge;
mod next;
use next::Next;
mod once;
pub use once::{once, Once};
mod pending;
pub use pending::{pending, Pending};
mod stream_map;
pub use stream_map::StreamMap;
mod skip;
use skip::Skip;
@@ -71,13 +51,44 @@ use take_while::TakeWhile;
cfg_time! {
mod timeout;
use timeout::Timeout;
use std::time::Duration;
use tokio::time::Duration;
mod throttle;
use throttle::{throttle, Throttle};
}
pub use futures_core::Stream;
/// An extension trait for `Stream`s that provides a variety of convenient
/// combinator functions.
/// An extension trait for the [`Stream`] trait that provides a variety of
/// convenient combinator functions.
///
/// Be aware that the `Stream` trait in Tokio is a re-export of the trait found
/// in the [futures] crate, however both Tokio and futures provide separate
/// `StreamExt` utility traits, and some utilities are only available on one of
/// these traits. Click [here][futures-StreamExt] to see the other `StreamExt`
/// trait in the futures crate.
///
/// If you need utilities from both `StreamExt` traits, you should prefer to
/// import one of them, and use the other through the fully qualified call
/// syntax. For example:
/// ```
/// // import one of the traits:
/// use futures::stream::StreamExt;
/// # #[tokio::main(flavor = "current_thread")]
/// # async fn main() {
///
/// let a = tokio_stream::iter(vec![1, 3, 5]);
/// let b = tokio_stream::iter(vec![2, 4, 6]);
///
/// // use the fully qualified call syntax for the other trait:
/// let merged = tokio_stream::StreamExt::merge(a, b);
///
/// // use normal call notation for futures::stream::StreamExt::collect
/// let output: Vec<_> = merged.collect().await;
/// assert_eq!(output, vec![1, 2, 3, 4, 5, 6]);
/// # }
/// ```
///
/// [`Stream`]: crate::Stream
/// [futures]: https://docs.rs/futures
/// [futures-StreamExt]: https://docs.rs/futures/0.3/futures/stream/trait.StreamExt.html
pub trait StreamExt: Stream {
/// Consumes and returns the next value in the stream or `None` if the
/// stream is finished.
@@ -100,7 +111,7 @@ pub trait StreamExt: Stream {
/// ```
/// # #[tokio::main]
/// # async fn main() {
/// use tokio::stream::{self, StreamExt};
/// use tokio_stream::{self as stream, StreamExt};
///
/// let mut stream = stream::iter(1..=3);
///
@@ -136,7 +147,7 @@ pub trait StreamExt: Stream {
/// ```
/// # #[tokio::main]
/// # async fn main() {
/// use tokio::stream::{self, StreamExt};
/// use tokio_stream::{self as stream, StreamExt};
///
/// let mut stream = stream::iter(vec![Ok(1), Ok(2), Err("nope")]);
///
@@ -168,7 +179,7 @@ pub trait StreamExt: Stream {
/// ```
/// # #[tokio::main]
/// # async fn main() {
/// use tokio::stream::{self, StreamExt};
/// use tokio_stream::{self as stream, StreamExt};
///
/// let stream = stream::iter(1..=3);
/// let mut stream = stream.map(|x| x + 3);
@@ -192,29 +203,48 @@ pub trait StreamExt: Stream {
/// Values are produced from the merged stream in the order they arrive from
/// the two source streams. If both source streams provide values
/// simultaneously, the merge stream alternates between them. This provides
/// some level of fairness.
/// some level of fairness. You should not chain calls to `merge`, as this
/// will break the fairness of the merging.
///
/// The merged stream completes once **both** source streams complete. When
/// one source stream completes before the other, the merge stream
/// exclusively polls the remaining stream.
///
/// For merging multiple streams, consider using [`StreamMap`] instead.
///
/// [`StreamMap`]: crate::StreamMap
///
/// # Examples
///
/// ```
/// use tokio::stream::StreamExt;
/// use tokio_stream::{StreamExt, Stream};
/// use tokio::sync::mpsc;
/// use tokio::time;
///
/// use std::time::Duration;
/// use std::pin::Pin;
///
/// # /*
/// #[tokio::main]
/// # */
/// # #[tokio::main(basic_scheduler)]
/// # #[tokio::main(flavor = "current_thread")]
/// async fn main() {
/// # time::pause();
/// let (mut tx1, rx1) = mpsc::channel(10);
/// let (mut tx2, rx2) = mpsc::channel(10);
/// let (tx1, mut rx1) = mpsc::channel::<usize>(10);
/// let (tx2, mut rx2) = mpsc::channel::<usize>(10);
///
/// // Convert the channels to a `Stream`.
/// let rx1 = Box::pin(async_stream::stream! {
/// while let Some(item) = rx1.recv().await {
/// yield item;
/// }
/// }) as Pin<Box<dyn Stream<Item = usize> + Send>>;
///
/// let rx2 = Box::pin(async_stream::stream! {
/// while let Some(item) = rx2.recv().await {
/// yield item;
/// }
/// }) as Pin<Box<dyn Stream<Item = usize> + Send>>;
///
/// let mut rx = rx1.merge(rx2);
///
@@ -224,18 +254,18 @@ pub trait StreamExt: Stream {
/// tx1.send(2).await.unwrap();
///
/// // Let the other task send values
/// time::delay_for(Duration::from_millis(20)).await;
/// time::sleep(Duration::from_millis(20)).await;
///
/// tx1.send(4).await.unwrap();
/// });
///
/// tokio::spawn(async move {
/// // Wait for the first task to send values
/// time::delay_for(Duration::from_millis(5)).await;
/// time::sleep(Duration::from_millis(5)).await;
///
/// tx2.send(3).await.unwrap();
///
/// time::delay_for(Duration::from_millis(25)).await;
/// time::sleep(Duration::from_millis(25)).await;
///
/// // Send the final value
/// tx2.send(5).await.unwrap();
@@ -277,7 +307,7 @@ pub trait StreamExt: Stream {
/// ```
/// # #[tokio::main]
/// # async fn main() {
/// use tokio::stream::{self, StreamExt};
/// use tokio_stream::{self as stream, StreamExt};
///
/// let stream = stream::iter(1..=8);
/// let mut evens = stream.filter(|x| x % 2 == 0);
@@ -303,7 +333,7 @@ pub trait StreamExt: Stream {
/// As values of this stream are made available, the provided function will
/// be run on them. If the predicate `f` resolves to
/// [`Some(item)`](Some) then the stream will yield the value `item`, but if
/// it resolves to [`None`] then the next value will be produced.
/// it resolves to [`None`], then the value will be skipped.
///
/// Note that this function consumes the stream passed into it and returns a
/// wrapped version of it, similar to [`Iterator::filter_map`] method in the
@@ -313,7 +343,7 @@ pub trait StreamExt: Stream {
/// ```
/// # #[tokio::main]
/// # async fn main() {
/// use tokio::stream::{self, StreamExt};
/// use tokio_stream::{self as stream, StreamExt};
///
/// let stream = stream::iter(1..=8);
/// let mut evens = stream.filter_map(|x| {
@@ -345,7 +375,7 @@ pub trait StreamExt: Stream {
/// # Examples
///
/// ```
/// use tokio::stream::{Stream, StreamExt};
/// use tokio_stream::{Stream, StreamExt};
///
/// use std::pin::Pin;
/// use std::task::{Context, Poll};
@@ -410,7 +440,7 @@ pub trait StreamExt: Stream {
/// ```
/// # #[tokio::main]
/// # async fn main() {
/// use tokio::stream::{self, StreamExt};
/// use tokio_stream::{self as stream, StreamExt};
///
/// let mut stream = stream::iter(1..=10).take(3);
///
@@ -439,7 +469,7 @@ pub trait StreamExt: Stream {
/// ```
/// # #[tokio::main]
/// # async fn main() {
/// use tokio::stream::{self, StreamExt};
/// use tokio_stream::{self as stream, StreamExt};
///
/// let mut stream = stream::iter(1..=10).take_while(|x| *x <= 3);
///
@@ -465,7 +495,7 @@ pub trait StreamExt: Stream {
/// ```
/// # #[tokio::main]
/// # async fn main() {
/// use tokio::stream::{self, StreamExt};
/// use tokio_stream::{self as stream, StreamExt};
///
/// let mut stream = stream::iter(1..=10).skip(7);
///
@@ -496,7 +526,7 @@ pub trait StreamExt: Stream {
/// ```
/// # #[tokio::main]
/// # async fn main() {
/// use tokio::stream::{self, StreamExt};
/// use tokio_stream::{self as stream, StreamExt};
/// let mut stream = stream::iter(vec![1,2,3,4,1]).skip_while(|x| *x < 3);
///
/// assert_eq!(Some(3), stream.next().await);
@@ -515,6 +545,12 @@ pub trait StreamExt: Stream {
/// Tests if every element of the stream matches a predicate.
///
/// Equivalent to:
///
/// ```ignore
/// async fn all<F>(&mut self, f: F) -> bool;
/// ```
///
/// `all()` takes a closure that returns `true` or `false`. It applies
/// this closure to each element of the stream, and if they all return
/// `true`, then so does `all`. If any of them return `false`, it
@@ -533,7 +569,7 @@ pub trait StreamExt: Stream {
/// ```
/// # #[tokio::main]
/// # async fn main() {
/// use tokio::stream::{self, StreamExt};
/// use tokio_stream::{self as stream, StreamExt};
///
/// let a = [1, 2, 3];
///
@@ -548,7 +584,7 @@ pub trait StreamExt: Stream {
/// ```
/// # #[tokio::main]
/// # async fn main() {
/// use tokio::stream::{self, StreamExt};
/// use tokio_stream::{self as stream, StreamExt};
///
/// let a = [1, 2, 3];
///
@@ -570,6 +606,12 @@ pub trait StreamExt: Stream {
/// Tests if any element of the stream matches a predicate.
///
/// Equivalent to:
///
/// ```ignore
/// async fn any<F>(&mut self, f: F) -> bool;
/// ```
///
/// `any()` takes a closure that returns `true` or `false`. It applies
/// this closure to each element of the stream, and if any of them return
/// `true`, then so does `any()`. If they all return `false`, it
@@ -586,7 +628,7 @@ pub trait StreamExt: Stream {
/// ```
/// # #[tokio::main]
/// # async fn main() {
/// use tokio::stream::{self, StreamExt};
/// use tokio_stream::{self as stream, StreamExt};
///
/// let a = [1, 2, 3];
///
@@ -601,7 +643,7 @@ pub trait StreamExt: Stream {
/// ```
/// # #[tokio::main]
/// # async fn main() {
/// use tokio::stream::{self, StreamExt};
/// use tokio_stream::{self as stream, StreamExt};
///
/// let a = [1, 2, 3];
///
@@ -630,7 +672,7 @@ pub trait StreamExt: Stream {
/// # Examples
///
/// ```
/// use tokio::stream::{self, StreamExt};
/// use tokio_stream::{self as stream, StreamExt};
///
/// #[tokio::main]
/// async fn main() {
@@ -659,12 +701,18 @@ pub trait StreamExt: Stream {
/// A combinator that applies a function to every element in a stream
/// producing a single, final value.
///
/// Equivalent to:
///
/// ```ignore
/// async fn fold<B, F>(self, init: B, f: F) -> B;
/// ```
///
/// # Examples
/// Basic usage:
/// ```
/// # #[tokio::main]
/// # async fn main() {
/// use tokio::stream::{self, *};
/// use tokio_stream::{self as stream, *};
///
/// let s = stream::iter(vec![1u8, 2, 3]);
/// let sum = s.fold(0, |acc, x| acc + x).await;
@@ -682,10 +730,18 @@ pub trait StreamExt: Stream {
/// Drain stream pushing all emitted values into a collection.
///
/// Equivalent to:
///
/// ```ignore
/// async fn collect<T>(self) -> T;
/// ```
///
/// `collect` streams all values, awaiting as needed. Values are pushed into
/// a collection. A number of different target collection types are
/// supported, including [`Vec`](std::vec::Vec),
/// [`String`](std::string::String), and [`Bytes`](bytes::Bytes).
/// [`String`](std::string::String), and [`Bytes`].
///
/// [`Bytes`]: https://docs.rs/bytes/0.6.0/bytes/struct.Bytes.html
///
/// # `Result`
///
@@ -697,14 +753,14 @@ pub trait StreamExt: Stream {
/// # Notes
///
/// `FromStream` is currently a sealed trait. Stabilization is pending
/// enhancements to the Rust langague.
/// enhancements to the Rust language.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use tokio::stream::{self, StreamExt};
/// use tokio_stream::{self as stream, StreamExt};
///
/// #[tokio::main]
/// async fn main() {
@@ -721,7 +777,7 @@ pub trait StreamExt: Stream {
/// Collecting a stream of `Result` values
///
/// ```
/// use tokio::stream::{self, StreamExt};
/// use tokio_stream::{self as stream, StreamExt};
///
/// #[tokio::main]
/// async fn main() {
@@ -777,11 +833,12 @@ pub trait StreamExt: Stream {
/// ```
/// # #[tokio::main]
/// # async fn main() {
/// use tokio::stream::{self, StreamExt};
/// use tokio_stream::{self as stream, StreamExt};
/// use std::time::Duration;
/// # let int_stream = stream::iter(1..=3);
///
/// let mut int_stream = int_stream.timeout(Duration::from_secs(1));
/// let int_stream = int_stream.timeout(Duration::from_secs(1));
/// tokio::pin!(int_stream);
///
/// // When no items time out, we get the 3 elements in succession:
/// assert_eq!(int_stream.try_next().await, Ok(Some(1)));
@@ -814,6 +871,34 @@ pub trait StreamExt: Stream {
{
Timeout::new(self, duration)
}
/// Slows down a stream by enforcing a delay between items.
///
/// # Example
///
/// Create a throttled stream.
/// ```rust,no_run
/// use std::time::Duration;
/// use tokio_stream::StreamExt;
///
/// # async fn dox() {
/// let item_stream = futures::stream::repeat("one").throttle(Duration::from_secs(2));
/// tokio::pin!(item_stream);
///
/// loop {
/// // The string will be produced at most every 2 seconds
/// println!("{:?}", item_stream.next().await);
/// }
/// # }
/// ```
#[cfg(all(feature = "time"))]
#[cfg_attr(docsrs, doc(cfg(feature = "time")))]
fn throttle(self, duration: Duration) -> Throttle<Self>
where
Self: Sized,
{
throttle(duration, self)
}
}
impl<St: ?Sized> StreamExt for St where St: Stream {}
+55
View File
@@ -0,0 +1,55 @@
use crate::Stream;
use core::future::Future;
use core::marker::PhantomPinned;
use core::pin::Pin;
use core::task::{Context, Poll};
use pin_project_lite::pin_project;
pin_project! {
/// Future for the [`all`](super::StreamExt::all) method.
#[derive(Debug)]
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct AllFuture<'a, St: ?Sized, F> {
stream: &'a mut St,
f: F,
// Make this future `!Unpin` for compatibility with async trait methods.
#[pin]
_pin: PhantomPinned,
}
}
impl<'a, St: ?Sized, F> AllFuture<'a, St, F> {
pub(super) fn new(stream: &'a mut St, f: F) -> Self {
Self {
stream,
f,
_pin: PhantomPinned,
}
}
}
impl<St, F> Future for AllFuture<'_, St, F>
where
St: ?Sized + Stream + Unpin,
F: FnMut(St::Item) -> bool,
{
type Output = bool;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let me = self.project();
let next = futures_core::ready!(Pin::new(me.stream).poll_next(cx));
match next {
Some(v) => {
if !(me.f)(v) {
Poll::Ready(false)
} else {
cx.waker().wake_by_ref();
Poll::Pending
}
}
None => Poll::Ready(true),
}
}
}
+55
View File
@@ -0,0 +1,55 @@
use crate::Stream;
use core::future::Future;
use core::marker::PhantomPinned;
use core::pin::Pin;
use core::task::{Context, Poll};
use pin_project_lite::pin_project;
pin_project! {
/// Future for the [`any`](super::StreamExt::any) method.
#[derive(Debug)]
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct AnyFuture<'a, St: ?Sized, F> {
stream: &'a mut St,
f: F,
// Make this future `!Unpin` for compatibility with async trait methods.
#[pin]
_pin: PhantomPinned,
}
}
impl<'a, St: ?Sized, F> AnyFuture<'a, St, F> {
pub(super) fn new(stream: &'a mut St, f: F) -> Self {
Self {
stream,
f,
_pin: PhantomPinned,
}
}
}
impl<St, F> Future for AnyFuture<'_, St, F>
where
St: ?Sized + Stream + Unpin,
F: FnMut(St::Item) -> bool,
{
type Output = bool;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let me = self.project();
let next = futures_core::ready!(Pin::new(me.stream).poll_next(cx));
match next {
Some(v) => {
if (me.f)(v) {
Poll::Ready(true)
} else {
cx.waker().wake_by_ref();
Poll::Pending
}
}
None => Poll::Ready(false),
}
}
}
@@ -1,4 +1,5 @@
use crate::stream::{Fuse, Stream};
use crate::stream_ext::Fuse;
use crate::Stream;
use core::pin::Pin;
use core::task::{Context, Poll};
+233
View File
@@ -0,0 +1,233 @@
use crate::Stream;
use core::future::Future;
use core::marker::PhantomPinned;
use core::mem;
use core::pin::Pin;
use core::task::{Context, Poll};
use pin_project_lite::pin_project;
// Do not export this struct until `FromStream` can be unsealed.
pin_project! {
/// Future returned by the [`collect`](super::StreamExt::collect) method.
#[must_use = "futures do nothing unless you `.await` or poll them"]
#[derive(Debug)]
pub struct Collect<T, U>
where
T: Stream,
U: FromStream<T::Item>,
{
#[pin]
stream: T,
collection: U::InternalCollection,
// Make this future `!Unpin` for compatibility with async trait methods.
#[pin]
_pin: PhantomPinned,
}
}
/// Convert from a [`Stream`](crate::Stream).
///
/// This trait is not intended to be used directly. Instead, call
/// [`StreamExt::collect()`](super::StreamExt::collect).
///
/// # Implementing
///
/// Currently, this trait may not be implemented by third parties. The trait is
/// sealed in order to make changes in the future. Stabilization is pending
/// enhancements to the Rust language.
pub trait FromStream<T>: sealed::FromStreamPriv<T> {}
impl<T, U> Collect<T, U>
where
T: Stream,
U: FromStream<T::Item>,
{
pub(super) fn new(stream: T) -> Collect<T, U> {
let (lower, upper) = stream.size_hint();
let collection = U::initialize(sealed::Internal, lower, upper);
Collect {
stream,
collection,
_pin: PhantomPinned,
}
}
}
impl<T, U> Future for Collect<T, U>
where
T: Stream,
U: FromStream<T::Item>,
{
type Output = U;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<U> {
use Poll::Ready;
loop {
let mut me = self.as_mut().project();
let item = match ready!(me.stream.poll_next(cx)) {
Some(item) => item,
None => {
return Ready(U::finalize(sealed::Internal, &mut me.collection));
}
};
if !U::extend(sealed::Internal, &mut me.collection, item) {
return Ready(U::finalize(sealed::Internal, &mut me.collection));
}
}
}
}
// ===== FromStream implementations
impl FromStream<()> for () {}
impl sealed::FromStreamPriv<()> for () {
type InternalCollection = ();
fn initialize(_: sealed::Internal, _lower: usize, _upper: Option<usize>) {}
fn extend(_: sealed::Internal, _collection: &mut (), _item: ()) -> bool {
true
}
fn finalize(_: sealed::Internal, _collection: &mut ()) {}
}
impl<T: AsRef<str>> FromStream<T> for String {}
impl<T: AsRef<str>> sealed::FromStreamPriv<T> for String {
type InternalCollection = String;
fn initialize(_: sealed::Internal, _lower: usize, _upper: Option<usize>) -> String {
String::new()
}
fn extend(_: sealed::Internal, collection: &mut String, item: T) -> bool {
collection.push_str(item.as_ref());
true
}
fn finalize(_: sealed::Internal, collection: &mut String) -> String {
mem::replace(collection, String::new())
}
}
impl<T> FromStream<T> for Vec<T> {}
impl<T> sealed::FromStreamPriv<T> for Vec<T> {
type InternalCollection = Vec<T>;
fn initialize(_: sealed::Internal, lower: usize, _upper: Option<usize>) -> Vec<T> {
Vec::with_capacity(lower)
}
fn extend(_: sealed::Internal, collection: &mut Vec<T>, item: T) -> bool {
collection.push(item);
true
}
fn finalize(_: sealed::Internal, collection: &mut Vec<T>) -> Vec<T> {
mem::replace(collection, vec![])
}
}
impl<T> FromStream<T> for Box<[T]> {}
impl<T> sealed::FromStreamPriv<T> for Box<[T]> {
type InternalCollection = Vec<T>;
fn initialize(_: sealed::Internal, lower: usize, upper: Option<usize>) -> Vec<T> {
<Vec<T> as sealed::FromStreamPriv<T>>::initialize(sealed::Internal, lower, upper)
}
fn extend(_: sealed::Internal, collection: &mut Vec<T>, item: T) -> bool {
<Vec<T> as sealed::FromStreamPriv<T>>::extend(sealed::Internal, collection, item)
}
fn finalize(_: sealed::Internal, collection: &mut Vec<T>) -> Box<[T]> {
<Vec<T> as sealed::FromStreamPriv<T>>::finalize(sealed::Internal, collection)
.into_boxed_slice()
}
}
impl<T, U, E> FromStream<Result<T, E>> for Result<U, E> where U: FromStream<T> {}
impl<T, U, E> sealed::FromStreamPriv<Result<T, E>> for Result<U, E>
where
U: FromStream<T>,
{
type InternalCollection = Result<U::InternalCollection, E>;
fn initialize(
_: sealed::Internal,
lower: usize,
upper: Option<usize>,
) -> Result<U::InternalCollection, E> {
Ok(U::initialize(sealed::Internal, lower, upper))
}
fn extend(
_: sealed::Internal,
collection: &mut Self::InternalCollection,
item: Result<T, E>,
) -> bool {
assert!(collection.is_ok());
match item {
Ok(item) => {
let collection = collection.as_mut().ok().expect("invalid state");
U::extend(sealed::Internal, collection, item)
}
Err(err) => {
*collection = Err(err);
false
}
}
}
fn finalize(_: sealed::Internal, collection: &mut Self::InternalCollection) -> Result<U, E> {
if let Ok(collection) = collection.as_mut() {
Ok(U::finalize(sealed::Internal, collection))
} else {
let res = mem::replace(collection, Ok(U::initialize(sealed::Internal, 0, Some(0))));
if let Err(err) = res {
Err(err)
} else {
unreachable!();
}
}
}
}
pub(crate) mod sealed {
#[doc(hidden)]
pub trait FromStreamPriv<T> {
/// Intermediate type used during collection process
///
/// The name of this type is internal and cannot be relied upon.
type InternalCollection;
/// Initialize the collection
fn initialize(
internal: Internal,
lower: usize,
upper: Option<usize>,
) -> Self::InternalCollection;
/// Extend the collection with the received item
///
/// Return `true` to continue streaming, `false` complete collection.
fn extend(internal: Internal, collection: &mut Self::InternalCollection, item: T) -> bool;
/// Finalize collection into target type.
fn finalize(internal: Internal, collection: &mut Self::InternalCollection) -> Self;
}
#[allow(missing_debug_implementations)]
pub struct Internal;
}
@@ -1,4 +1,4 @@
use crate::stream::Stream;
use crate::Stream;
use core::fmt;
use core::pin::Pin;
@@ -1,4 +1,4 @@
use crate::stream::Stream;
use crate::Stream;
use core::fmt;
use core::pin::Pin;
@@ -1,6 +1,7 @@
use crate::stream::Stream;
use crate::Stream;
use core::future::Future;
use core::marker::PhantomPinned;
use core::pin::Pin;
use core::task::{Context, Poll};
use pin_project_lite::pin_project;
@@ -8,11 +9,15 @@ use pin_project_lite::pin_project;
pin_project! {
/// Future returned by the [`fold`](super::StreamExt::fold) method.
#[derive(Debug)]
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct FoldFuture<St, B, F> {
#[pin]
stream: St,
acc: Option<B>,
f: F,
// Make this future `!Unpin` for compatibility with async trait methods.
#[pin]
_pin: PhantomPinned,
}
}
@@ -22,6 +27,7 @@ impl<St, B, F> FoldFuture<St, B, F> {
stream,
acc: Some(init),
f,
_pin: PhantomPinned,
}
}
}
@@ -1,4 +1,4 @@
use crate::stream::Stream;
use crate::Stream;
use pin_project_lite::pin_project;
use std::pin::Pin;
@@ -1,4 +1,4 @@
use crate::stream::Stream;
use crate::Stream;
use core::fmt;
use core::pin::Pin;
@@ -1,4 +1,5 @@
use crate::stream::{Fuse, Stream};
use crate::stream_ext::Fuse;
use crate::Stream;
use core::pin::Pin;
use core::task::{Context, Poll};
+37
View File
@@ -0,0 +1,37 @@
use crate::Stream;
use core::future::Future;
use core::marker::PhantomPinned;
use core::pin::Pin;
use core::task::{Context, Poll};
use pin_project_lite::pin_project;
pin_project! {
/// Future for the [`next`](super::StreamExt::next) method.
#[derive(Debug)]
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct Next<'a, St: ?Sized> {
stream: &'a mut St,
// Make this future `!Unpin` for compatibility with async trait methods.
#[pin]
_pin: PhantomPinned,
}
}
impl<'a, St: ?Sized> Next<'a, St> {
pub(super) fn new(stream: &'a mut St) -> Self {
Next {
stream,
_pin: PhantomPinned,
}
}
}
impl<St: ?Sized + Stream + Unpin> Future for Next<'_, St> {
type Output = Option<St::Item>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let me = self.project();
Pin::new(me.stream).poll_next(cx)
}
}
@@ -1,4 +1,4 @@
use crate::stream::Stream;
use crate::Stream;
use core::fmt;
use core::pin::Pin;
@@ -1,4 +1,4 @@
use crate::stream::Stream;
use crate::Stream;
use core::fmt;
use core::pin::Pin;
@@ -1,4 +1,4 @@
use crate::stream::Stream;
use crate::Stream;
use core::cmp;
use core::fmt;
@@ -1,4 +1,4 @@
use crate::stream::Stream;
use crate::Stream;
use core::fmt;
use core::pin::Pin;

Some files were not shown because too many files have changed in this diff Show More