mirror of
https://github.com/tokio-rs/tokio.git
synced 2026-09-09 00:00:08 +02:00
Compare commits
130
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
dfe4013ff2 | ||
|
|
18779aa2e2 | ||
|
|
1baea398c4 | ||
|
|
3fbcf1ba50 | ||
|
|
580dc9594c | ||
|
|
8c395dfe61 | ||
|
|
e188e99ca3 | ||
|
|
0b93bd511d | ||
|
|
d846bf24b1 | ||
|
|
9ff7d8c352 | ||
|
|
8324317005 | ||
|
|
7207e3ca43 | ||
|
|
312321cbd3 | ||
|
|
17c7ce616c | ||
|
|
f9ce18a524 | ||
|
|
05c3cf3a0a | ||
|
|
2c5dc83019 | ||
|
|
6b9bdd5ca2 | ||
|
|
d4075a4457 | ||
|
|
177522cd43 | ||
|
|
7ac341b526 | ||
|
|
c4b6b130f3 | ||
|
|
6845a93cbf | ||
|
|
8ef39dfb22 | ||
|
|
541b0c3af2 | ||
|
|
55c5d12451 | ||
|
|
a945ce0996 | ||
|
|
14bb2f624f | ||
|
|
a08ce0d3e0 | ||
|
|
078e317c0b | ||
|
|
ce9697f2a2 | ||
|
|
73466f4b6c | ||
|
|
0ba1e3c3e1 | ||
|
|
1e2f893da2 | ||
|
|
2b9b558108 | ||
|
|
d6da67b2e6 | ||
|
|
c8a6bb0b90 | ||
|
|
9eeec039f2 | ||
|
|
39706b198c | ||
|
|
cab4a592ac | ||
|
|
a5ee2f0d3d | ||
|
|
917aad684b | ||
|
|
e366cf9b3e | ||
|
|
3a02d34d3a | ||
|
|
adad8fc3cd | ||
|
|
08f1b67fcb | ||
|
|
28d6879897 | ||
|
|
1a72b28f53 | ||
|
|
1d5655272b | ||
|
|
5513b6b825 | ||
|
|
787aca1826 | ||
|
|
e89c8981f1 | ||
|
|
bf8c77bea1 | ||
|
|
0074b963b8 | ||
|
|
eabb7ce61c | ||
|
|
618d2bfc71 | ||
|
|
f6e4e85dfb | ||
|
|
f93bc9bad1 | ||
|
|
b05b9a1788 | ||
|
|
b42f21ec3e | ||
|
|
8fc49dc522 | ||
|
|
9ec3393650 | ||
|
|
f7c181c2c4 | ||
|
|
fee76ea7d5 | ||
|
|
1a80d6eee5 | ||
|
|
7384813979 | ||
|
|
a257a3a2b1 | ||
|
|
9a3603fa75 | ||
|
|
724ba348d1 | ||
|
|
0dc4769708 | ||
|
|
6f896d8846 | ||
|
|
10abc45da1 | ||
|
|
227b3e0d9c | ||
|
|
c659e4a757 | ||
|
|
8ed825fd49 | ||
|
|
63395f061e | ||
|
|
69b129b405 | ||
|
|
0bfcbc8be5 | ||
|
|
81f47e8866 | ||
|
|
b4918adbd8 | ||
|
|
b1310ad14d | ||
|
|
dcac336dc7 | ||
|
|
c39d9867bb | ||
|
|
e4f76688a0 | ||
|
|
e6103d6661 | ||
|
|
cc90a5c679 | ||
|
|
f107c4f49b | ||
|
|
e6a9167bb7 | ||
|
|
345b29ca11 | ||
|
|
b75d02a2b6 | ||
|
|
a1b4bdee61 | ||
|
|
edfff7551a | ||
|
|
1cda0f16a2 | ||
|
|
e40ec3e424 | ||
|
|
6919f7cede | ||
|
|
bcb95db4e2 | ||
|
|
8c5cde9bc3 | ||
|
|
b08b5edb2c | ||
|
|
88863a0c5d | ||
|
|
d0e4dd1d7b | ||
|
|
872bc09e83 | ||
|
|
db1d90453c | ||
|
|
05eeea570e | ||
|
|
f70b9b84f7 | ||
|
|
704de8c01b | ||
|
|
47be928444 | ||
|
|
e06b257e09 | ||
|
|
0867a6fc03 | ||
|
|
0d838bf5ad | ||
|
|
fc23f8a1a5 | ||
|
|
fd93ecf5e0 | ||
|
|
d2ad7afd21 | ||
|
|
5756a005a6 | ||
|
|
017a483b5e | ||
|
|
112e160b62 | ||
|
|
c9d2a36c7b | ||
|
|
8efed43fa7 | ||
|
|
7de18af82c | ||
|
|
52457dcf5b | ||
|
|
53558cb489 | ||
|
|
36d7dab504 | ||
|
|
6fd06aaeec | ||
|
|
36bcfa6b9d | ||
|
|
e3f2dcf5bc | ||
|
|
7c6a1c4637 | ||
|
|
4099bfdef0 | ||
|
|
469b43de6a | ||
|
|
e827829402 | ||
|
|
58bd242831 | ||
|
|
6fd9084d47 |
@@ -9,7 +9,7 @@ name: CI
|
||||
env:
|
||||
RUSTFLAGS: -Dwarnings
|
||||
RUST_BACKTRACE: 1
|
||||
nightly: nightly-2020-09-21
|
||||
nightly: nightly-2021-04-25
|
||||
minrust: 1.45.2
|
||||
|
||||
jobs:
|
||||
@@ -68,6 +68,13 @@ jobs:
|
||||
run: cargo hack test --each-feature
|
||||
working-directory: tests-build
|
||||
|
||||
# Build benchmarks. Run of benchmarks is done by bench.yml workflow.
|
||||
- name: build benches
|
||||
run: cargo build --benches
|
||||
working-directory: benches
|
||||
# bench.yml workflow runs benchmarks only on linux.
|
||||
if: startsWith(matrix.os, 'ubuntu')
|
||||
|
||||
valgrind:
|
||||
name: valgrind
|
||||
runs-on: ubuntu-latest
|
||||
@@ -82,14 +89,23 @@ jobs:
|
||||
sudo apt-get install -y valgrind
|
||||
|
||||
# Compile tests
|
||||
- name: cargo build
|
||||
- name: cargo build test-mem
|
||||
run: cargo build --features rt-net --bin test-mem
|
||||
working-directory: tests-integration
|
||||
|
||||
# Run with valgrind
|
||||
- name: Run valgrind
|
||||
- name: Run valgrind test-mem
|
||||
run: valgrind --leak-check=full --show-leak-kinds=all ./target/debug/test-mem
|
||||
|
||||
# Compile tests
|
||||
- name: cargo build test-process-signal
|
||||
run: cargo build --features rt-process-signal --bin test-process-signal
|
||||
working-directory: tests-integration
|
||||
|
||||
# Run with valgrind
|
||||
- name: Run valgrind test-process-signal
|
||||
run: valgrind --leak-check=full --show-leak-kinds=all ./target/debug/test-process-signal
|
||||
|
||||
test-unstable:
|
||||
name: test tokio full --unstable
|
||||
runs-on: ${{ matrix.os }}
|
||||
@@ -268,9 +284,9 @@ jobs:
|
||||
override: true
|
||||
|
||||
- name: "doc --lib --all-features"
|
||||
run: cargo doc --lib --no-deps --all-features
|
||||
run: cargo doc --lib --no-deps --all-features --document-private-items
|
||||
env:
|
||||
RUSTDOCFLAGS: --cfg docsrs
|
||||
RUSTDOCFLAGS: --cfg docsrs -Dwarnings
|
||||
|
||||
loom:
|
||||
name: loom
|
||||
|
||||
+12
-3
@@ -124,17 +124,27 @@ arguments to many common cargo commands. This section lists some commonly needed
|
||||
commands.
|
||||
|
||||
Some commands just need the `--all-features` argument:
|
||||
|
||||
```
|
||||
cargo build --all-features
|
||||
cargo check --all-features
|
||||
cargo test --all-features
|
||||
```
|
||||
|
||||
When building documentation normally, the markers that list the features
|
||||
required for various parts of Tokio are missing. To build the documentation
|
||||
correctly, use this command:
|
||||
|
||||
```
|
||||
RUSTDOCFLAGS="--cfg docsrs" cargo +nightly doc --all-features
|
||||
```
|
||||
|
||||
There is currently a [bug in cargo] that means documentation cannot be built
|
||||
from the root of the workspace. If you `cd` into the `tokio` subdirectory the
|
||||
command shown above will work.
|
||||
|
||||
[bug in cargo]: https://github.com/rust-lang/cargo/issues/9274
|
||||
|
||||
The `cargo fmt` command does not work on the Tokio codebase. You can use the
|
||||
command below instead:
|
||||
|
||||
@@ -571,9 +581,8 @@ When releasing a new version of a crate, follow these steps:
|
||||
2. **Update Cargo metadata.** After releasing any path dependencies, update the
|
||||
`version` field in `Cargo.toml` to the new version, and the `documentation`
|
||||
field to the docs.rs URL of the new version.
|
||||
3. **Update other documentation links.** Update the `#![doc(html_root_url)]`
|
||||
attribute in the crate's `lib.rs` and the "Documentation" link in the crate's
|
||||
`README.md` to point to the docs.rs URL of the new version.
|
||||
3. **Update other documentation links.** Update the "Documentation" link in the
|
||||
crate's `README.md` to point to the docs.rs URL of the new version.
|
||||
4. **Update the changelog for the crate.** Each crate in the Tokio repository
|
||||
has its own `CHANGELOG.md` in that crate's subdirectory. Any changes to that
|
||||
crate since the last release should be added to the changelog. Change
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
Copyright (c) 2019 Tokio Contributors
|
||||
Copyright (c) 2021 Tokio Contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any
|
||||
person obtaining a copy of this software and associated
|
||||
|
||||
@@ -50,7 +50,15 @@ an asynchronous application.
|
||||
|
||||
## Example
|
||||
|
||||
A basic TCP echo server with Tokio:
|
||||
A basic TCP echo server with Tokio.
|
||||
|
||||
Make sure you activated the full features of the tokio crate on Cargo.toml:
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
tokio = { version = "1.5.0", features = ["full"] }
|
||||
```
|
||||
Then, on your main.rs:
|
||||
|
||||
```rust,no_run
|
||||
use tokio::net::TcpListener;
|
||||
|
||||
+10
-1
@@ -5,9 +5,13 @@ publish = false
|
||||
edition = "2018"
|
||||
|
||||
[dependencies]
|
||||
tokio = { version = "1.0.0", path = "../tokio", features = ["full"] }
|
||||
tokio = { version = "1.5.0", path = "../tokio", features = ["full"] }
|
||||
bencher = "0.1.5"
|
||||
|
||||
[dev-dependencies]
|
||||
tokio-util = { version = "0.6.6", path = "../tokio-util", features = ["full"] }
|
||||
tokio-stream = { path = "../tokio-stream" }
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
libc = "0.2.42"
|
||||
|
||||
@@ -41,3 +45,8 @@ harness = false
|
||||
name = "signal"
|
||||
path = "signal.rs"
|
||||
harness = false
|
||||
|
||||
[[bench]]
|
||||
name = "fs"
|
||||
path = "fs.rs"
|
||||
harness = false
|
||||
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
#![cfg(unix)]
|
||||
|
||||
use tokio_stream::StreamExt;
|
||||
|
||||
use tokio::fs::File;
|
||||
use tokio::io::AsyncReadExt;
|
||||
use tokio_util::codec::{BytesCodec, FramedRead /*FramedWrite*/};
|
||||
|
||||
use bencher::{benchmark_group, benchmark_main, Bencher};
|
||||
|
||||
use std::fs::File as StdFile;
|
||||
use std::io::Read as StdRead;
|
||||
|
||||
fn rt() -> tokio::runtime::Runtime {
|
||||
tokio::runtime::Builder::new_multi_thread()
|
||||
.worker_threads(2)
|
||||
.build()
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
const BLOCK_COUNT: usize = 1_000;
|
||||
|
||||
const BUFFER_SIZE: usize = 4096;
|
||||
const DEV_ZERO: &'static str = "/dev/zero";
|
||||
|
||||
fn async_read_codec(b: &mut Bencher) {
|
||||
let rt = rt();
|
||||
|
||||
b.iter(|| {
|
||||
let task = || async {
|
||||
let file = File::open(DEV_ZERO).await.unwrap();
|
||||
let mut input_stream = FramedRead::with_capacity(file, BytesCodec::new(), BUFFER_SIZE);
|
||||
|
||||
for _i in 0..BLOCK_COUNT {
|
||||
let _bytes = input_stream.next().await.unwrap();
|
||||
}
|
||||
};
|
||||
|
||||
rt.block_on(task());
|
||||
});
|
||||
}
|
||||
|
||||
fn async_read_buf(b: &mut Bencher) {
|
||||
let rt = rt();
|
||||
|
||||
b.iter(|| {
|
||||
let task = || async {
|
||||
let mut file = File::open(DEV_ZERO).await.unwrap();
|
||||
let mut buffer = [0u8; BUFFER_SIZE];
|
||||
|
||||
for _i in 0..BLOCK_COUNT {
|
||||
let count = file.read(&mut buffer).await.unwrap();
|
||||
if count == 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
rt.block_on(task());
|
||||
});
|
||||
}
|
||||
|
||||
fn async_read_std_file(b: &mut Bencher) {
|
||||
let rt = rt();
|
||||
|
||||
let task = || async {
|
||||
let mut file = tokio::task::block_in_place(|| Box::pin(StdFile::open(DEV_ZERO).unwrap()));
|
||||
|
||||
for _i in 0..BLOCK_COUNT {
|
||||
let mut buffer = [0u8; BUFFER_SIZE];
|
||||
let mut file_ref = file.as_mut();
|
||||
|
||||
tokio::task::block_in_place(move || {
|
||||
file_ref.read_exact(&mut buffer).unwrap();
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
b.iter(|| {
|
||||
rt.block_on(task());
|
||||
});
|
||||
}
|
||||
|
||||
fn sync_read(b: &mut Bencher) {
|
||||
b.iter(|| {
|
||||
let mut file = StdFile::open(DEV_ZERO).unwrap();
|
||||
let mut buffer = [0u8; BUFFER_SIZE];
|
||||
|
||||
for _i in 0..BLOCK_COUNT {
|
||||
file.read_exact(&mut buffer).unwrap();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
benchmark_group!(
|
||||
file,
|
||||
async_read_std_file,
|
||||
async_read_buf,
|
||||
async_read_codec,
|
||||
sync_read
|
||||
);
|
||||
|
||||
benchmark_main!(file);
|
||||
+3
-4
@@ -7,11 +7,10 @@ edition = "2018"
|
||||
# If you copy one of the examples into a new project, you should be using
|
||||
# [dependencies] instead.
|
||||
[dev-dependencies]
|
||||
tokio = { version = "1.0.0", features = ["full", "tracing"] }
|
||||
tokio-util = { version = "0.6.3", features = ["full"] }
|
||||
tokio-stream = { version = "0.1" }
|
||||
tokio = { version = "1.0.0", path = "../tokio",features = ["full", "tracing"] }
|
||||
tokio-util = { version = "0.6.3", path = "../tokio-util",features = ["full"] }
|
||||
tokio-stream = { version = "0.1", path = "../tokio-stream" }
|
||||
|
||||
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"
|
||||
|
||||
+31
-69
@@ -28,8 +28,8 @@
|
||||
|
||||
use tokio::net::{TcpListener, TcpStream};
|
||||
use tokio::sync::{mpsc, Mutex};
|
||||
use tokio_stream::{Stream, StreamExt};
|
||||
use tokio_util::codec::{Framed, LinesCodec, LinesCodecError};
|
||||
use tokio_stream::StreamExt;
|
||||
use tokio_util::codec::{Framed, LinesCodec};
|
||||
|
||||
use futures::SinkExt;
|
||||
use std::collections::HashMap;
|
||||
@@ -37,9 +37,7 @@ use std::env;
|
||||
use std::error::Error;
|
||||
use std::io;
|
||||
use std::net::SocketAddr;
|
||||
use std::pin::Pin;
|
||||
use std::sync::Arc;
|
||||
use std::task::{Context, Poll};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn Error>> {
|
||||
@@ -101,6 +99,9 @@ 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
|
||||
@@ -124,7 +125,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: Pin<Box<dyn Stream<Item = String> + Send>>,
|
||||
rx: Rx,
|
||||
}
|
||||
|
||||
impl Shared {
|
||||
@@ -156,58 +157,15 @@ impl Peer {
|
||||
let addr = lines.get_ref().peer_addr()?;
|
||||
|
||||
// Create a channel for this peer
|
||||
let (tx, mut rx) = mpsc::unbounded_channel();
|
||||
let (tx, 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 })
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
enum Message {
|
||||
/// A message that should be broadcasted to others.
|
||||
Broadcast(String),
|
||||
|
||||
/// A message that should be received by a client
|
||||
Received(String),
|
||||
}
|
||||
|
||||
// Peer implements `Stream` in a way that polls both the `Rx`, and `Framed` types.
|
||||
// A message is produced whenever an event is ready until the `Framed` stream returns `None`.
|
||||
impl Stream for Peer {
|
||||
type Item = Result<Message, LinesCodecError>;
|
||||
|
||||
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
|
||||
// First poll the `UnboundedReceiver`.
|
||||
|
||||
if let Poll::Ready(Some(v)) = Pin::new(&mut self.rx).poll_next(cx) {
|
||||
return Poll::Ready(Some(Ok(Message::Received(v))));
|
||||
}
|
||||
|
||||
// Secondly poll the `Framed` stream.
|
||||
let result: Option<_> = futures::ready!(Pin::new(&mut self.lines).poll_next(cx));
|
||||
|
||||
Poll::Ready(match result {
|
||||
// We've received a message we should broadcast to others.
|
||||
Some(Ok(message)) => Some(Ok(Message::Broadcast(message))),
|
||||
|
||||
// An error occurred.
|
||||
Some(Err(e)) => Some(Err(e)),
|
||||
|
||||
// The stream has been exhausted.
|
||||
None => None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Process an individual chat client
|
||||
async fn process(
|
||||
state: Arc<Mutex<Shared>>,
|
||||
@@ -241,28 +199,32 @@ async fn process(
|
||||
}
|
||||
|
||||
// Process incoming messages until our stream is exhausted by a disconnect.
|
||||
while let Some(result) = peer.next().await {
|
||||
match result {
|
||||
// A message was received from the current user, we should
|
||||
// broadcast this message to the other users.
|
||||
Ok(Message::Broadcast(msg)) => {
|
||||
let mut state = state.lock().await;
|
||||
let msg = format!("{}: {}", username, msg);
|
||||
|
||||
state.broadcast(addr, &msg).await;
|
||||
}
|
||||
// A message was received from a peer. Send it to the
|
||||
// current user.
|
||||
Ok(Message::Received(msg)) => {
|
||||
loop {
|
||||
tokio::select! {
|
||||
// A message was received from a peer. Send it to the current user.
|
||||
Some(msg) = peer.rx.recv() => {
|
||||
peer.lines.send(&msg).await?;
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!(
|
||||
"an error occurred while processing messages for {}; error = {:?}",
|
||||
username,
|
||||
e
|
||||
);
|
||||
}
|
||||
result = peer.lines.next() => match result {
|
||||
// A message was received from the current user, we should
|
||||
// broadcast this message to the other users.
|
||||
Some(Ok(msg)) => {
|
||||
let mut state = state.lock().await;
|
||||
let msg = format!("{}: {}", username, msg);
|
||||
|
||||
state.broadcast(addr, &msg).await;
|
||||
}
|
||||
// An error occurred.
|
||||
Some(Err(e)) => {
|
||||
tracing::error!(
|
||||
"an error occurred while processing messages for {}; error = {:?}",
|
||||
username,
|
||||
e
|
||||
);
|
||||
}
|
||||
// The stream has been exhausted.
|
||||
None => break,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
#![deny(dead_code)]
|
||||
|
||||
use tests_build::tokio;
|
||||
|
||||
#[tokio::main]
|
||||
async fn f() {}
|
||||
|
||||
fn main() {}
|
||||
@@ -0,0 +1,11 @@
|
||||
error: function is never used: `f`
|
||||
--> $DIR/macros_dead_code.rs:6:10
|
||||
|
|
||||
6 | async fn f() {}
|
||||
| ^
|
||||
|
|
||||
note: the lint level is defined here
|
||||
--> $DIR/macros_dead_code.rs:1:9
|
||||
|
|
||||
1 | #![deny(dead_code)]
|
||||
| ^^^^^^^^^
|
||||
@@ -12,12 +12,27 @@ async fn main_attr_has_path_args() {}
|
||||
#[tokio::test]
|
||||
fn test_is_not_async() {}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_fn_has_args(_x: u8) {}
|
||||
|
||||
#[tokio::test(foo)]
|
||||
async fn test_attr_has_args() {}
|
||||
|
||||
#[tokio::test(foo = 123)]
|
||||
async fn test_unexpected_attr() {}
|
||||
|
||||
#[tokio::test(flavor = 123)]
|
||||
async fn test_flavor_not_string() {}
|
||||
|
||||
#[tokio::test(flavor = "foo")]
|
||||
async fn test_unknown_flavor() {}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", start_paused = false)]
|
||||
async fn test_multi_thread_with_start_paused() {}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = "foo")]
|
||||
async fn test_worker_threads_not_int() {}
|
||||
|
||||
#[tokio::test(flavor = "current_thread", worker_threads = 4)]
|
||||
async fn test_worker_threads_and_current_thread() {}
|
||||
|
||||
#[tokio::test]
|
||||
#[test]
|
||||
async fn test_has_second_test_attr() {}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
error: the async keyword is missing from the function declaration
|
||||
error: the `async` keyword is missing from the function declaration
|
||||
--> $DIR/macros_invalid_input.rs:4:1
|
||||
|
|
||||
4 | fn main_is_not_async() {}
|
||||
@@ -16,26 +16,56 @@ error: Must have specified ident
|
||||
9 | #[tokio::main(threadpool::bar)]
|
||||
| ^^^^^^^^^^^^^^^
|
||||
|
||||
error: the async keyword is missing from the function declaration
|
||||
error: the `async` keyword is missing from the function declaration
|
||||
--> $DIR/macros_invalid_input.rs:13:1
|
||||
|
|
||||
13 | fn test_is_not_async() {}
|
||||
| ^^
|
||||
|
||||
error: the test function cannot accept arguments
|
||||
--> $DIR/macros_invalid_input.rs:16:27
|
||||
error: Unknown attribute foo is specified; expected one of: `flavor`, `worker_threads`, `start_paused`
|
||||
--> $DIR/macros_invalid_input.rs:15:15
|
||||
|
|
||||
16 | async fn test_fn_has_args(_x: u8) {}
|
||||
| ^^^^^^
|
||||
15 | #[tokio::test(foo)]
|
||||
| ^^^
|
||||
|
||||
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)]
|
||||
| ^^^
|
||||
18 | #[tokio::test(foo = 123)]
|
||||
| ^^^^^^^^^
|
||||
|
||||
error: Failed to parse value of `flavor` as string.
|
||||
--> $DIR/macros_invalid_input.rs:21:24
|
||||
|
|
||||
21 | #[tokio::test(flavor = 123)]
|
||||
| ^^^
|
||||
|
||||
error: No such runtime flavor `foo`. The runtime flavors are `current_thread` and `multi_thread`.
|
||||
--> $DIR/macros_invalid_input.rs:24:24
|
||||
|
|
||||
24 | #[tokio::test(flavor = "foo")]
|
||||
| ^^^^^
|
||||
|
||||
error: The `start_paused` option requires the `current_thread` runtime flavor. Use `#[tokio::test(flavor = "current_thread")]`
|
||||
--> $DIR/macros_invalid_input.rs:27:55
|
||||
|
|
||||
27 | #[tokio::test(flavor = "multi_thread", start_paused = false)]
|
||||
| ^^^^^
|
||||
|
||||
error: Failed to parse value of `worker_threads` as integer.
|
||||
--> $DIR/macros_invalid_input.rs:30:57
|
||||
|
|
||||
30 | #[tokio::test(flavor = "multi_thread", worker_threads = "foo")]
|
||||
| ^^^^^
|
||||
|
||||
error: The `worker_threads` option requires the `multi_thread` runtime flavor. Use `#[tokio::test(flavor = "multi_thread")]`
|
||||
--> $DIR/macros_invalid_input.rs:33:59
|
||||
|
|
||||
33 | #[tokio::test(flavor = "current_thread", worker_threads = 4)]
|
||||
| ^
|
||||
|
||||
error: second test attribute is supplied
|
||||
--> $DIR/macros_invalid_input.rs:22:1
|
||||
--> $DIR/macros_invalid_input.rs:37:1
|
||||
|
|
||||
22 | #[test]
|
||||
37 | #[test]
|
||||
| ^^^^^^^
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
use tests_build::tokio;
|
||||
|
||||
#[tokio::main]
|
||||
async fn missing_semicolon_or_return_type() {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn missing_return_type() {
|
||||
/* TODO(taiki-e): one of help messages still wrong
|
||||
help: consider using a semicolon here
|
||||
|
|
||||
16 | return Ok(());;
|
||||
|
|
||||
*/
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn extra_semicolon() -> Result<(), ()> {
|
||||
/* TODO(taiki-e): help message still wrong
|
||||
help: try using a variant of the expected enum
|
||||
|
|
||||
29 | Ok(Ok(());)
|
||||
|
|
||||
29 | Err(Ok(());)
|
||||
|
|
||||
*/
|
||||
Ok(());
|
||||
}
|
||||
|
||||
fn main() {}
|
||||
@@ -0,0 +1,51 @@
|
||||
error[E0308]: mismatched types
|
||||
--> $DIR/macros_type_mismatch.rs:5:5
|
||||
|
|
||||
5 | Ok(())
|
||||
| ^^^^^^ expected `()`, found enum `Result`
|
||||
|
|
||||
= note: expected unit type `()`
|
||||
found enum `Result<(), _>`
|
||||
help: consider using a semicolon here
|
||||
|
|
||||
5 | Ok(());
|
||||
| ^
|
||||
help: try adding a return type
|
||||
|
|
||||
4 | async fn missing_semicolon_or_return_type() -> Result<(), _> {
|
||||
| ^^^^^^^^^^^^^^^^
|
||||
|
||||
error[E0308]: mismatched types
|
||||
--> $DIR/macros_type_mismatch.rs:16:5
|
||||
|
|
||||
16 | return Ok(());
|
||||
| ^^^^^^^^^^^^^^ expected `()`, found enum `Result`
|
||||
|
|
||||
= note: expected unit type `()`
|
||||
found enum `Result<(), _>`
|
||||
help: consider using a semicolon here
|
||||
|
|
||||
16 | return Ok(());;
|
||||
| ^
|
||||
help: try adding a return type
|
||||
|
|
||||
9 | async fn missing_return_type() -> Result<(), _> {
|
||||
| ^^^^^^^^^^^^^^^^
|
||||
|
||||
error[E0308]: mismatched types
|
||||
--> $DIR/macros_type_mismatch.rs:29:5
|
||||
|
|
||||
20 | async fn extra_semicolon() -> Result<(), ()> {
|
||||
| -------------- expected `Result<(), ()>` because of return type
|
||||
...
|
||||
29 | Ok(());
|
||||
| ^^^^^^^ expected enum `Result`, found `()`
|
||||
|
|
||||
= note: expected enum `Result<(), ()>`
|
||||
found unit type `()`
|
||||
help: try using a variant of the expected enum
|
||||
|
|
||||
29 | Ok(Ok(());)
|
||||
|
|
||||
29 | Err(Ok(());)
|
||||
|
|
||||
@@ -2,9 +2,18 @@
|
||||
fn compile_fail_full() {
|
||||
let t = trybuild::TestCases::new();
|
||||
|
||||
#[cfg(feature = "full")]
|
||||
t.pass("tests/pass/forward_args_and_output.rs");
|
||||
|
||||
#[cfg(feature = "full")]
|
||||
t.compile_fail("tests/fail/macros_invalid_input.rs");
|
||||
|
||||
#[cfg(feature = "full")]
|
||||
t.compile_fail("tests/fail/macros_dead_code.rs");
|
||||
|
||||
#[cfg(feature = "full")]
|
||||
t.compile_fail("tests/fail/macros_type_mismatch.rs");
|
||||
|
||||
#[cfg(all(feature = "rt", not(feature = "full")))]
|
||||
t.compile_fail("tests/fail/macros_core_no_default.rs");
|
||||
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
use tests_build::tokio;
|
||||
|
||||
fn main() {}
|
||||
|
||||
// arguments and output type is forwarded so other macros can access them
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_fn_has_args(_x: u8) {}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_has_output() -> Result<(), Box<dyn std::error::Error>> {
|
||||
Ok(())
|
||||
}
|
||||
@@ -12,9 +12,15 @@ name = "test-cat"
|
||||
name = "test-mem"
|
||||
required-features = ["rt-net"]
|
||||
|
||||
[[bin]]
|
||||
name = "test-process-signal"
|
||||
required-features = ["rt-process-signal"]
|
||||
|
||||
[features]
|
||||
# For mem check
|
||||
rt-net = ["tokio/rt", "tokio/rt-multi-thread", "tokio/net"]
|
||||
# For test-process-signal
|
||||
rt-process-signal = ["rt", "tokio/process", "tokio/signal"]
|
||||
|
||||
full = [
|
||||
"macros",
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
// https://github.com/tokio-rs/tokio/issues/3550
|
||||
fn main() {
|
||||
for _ in 0..1000 {
|
||||
let rt = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.unwrap();
|
||||
|
||||
drop(rt);
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,6 @@
|
||||
name = "tokio-macros"
|
||||
# When releasing to crates.io:
|
||||
# - Remove path dependencies
|
||||
# - Update html_root_url.
|
||||
# - Update doc url
|
||||
# - Cargo.toml
|
||||
# - Update CHANGELOG.md.
|
||||
@@ -27,7 +26,7 @@ proc-macro = true
|
||||
[dependencies]
|
||||
proc-macro2 = "1.0.7"
|
||||
quote = "1"
|
||||
syn = { version = "1.0.3", features = ["full"] }
|
||||
syn = { version = "1.0.56", features = ["full"] }
|
||||
|
||||
[dev-dependencies]
|
||||
tokio = { version = "1.0.0", path = "../tokio", features = ["full"] }
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
Copyright (c) 2020 Tokio Contributors
|
||||
Copyright (c) 2021 Tokio Contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any
|
||||
person obtaining a copy of this software and associated
|
||||
|
||||
+81
-53
@@ -1,7 +1,6 @@
|
||||
use proc_macro::TokenStream;
|
||||
use proc_macro2::Span;
|
||||
use quote::quote;
|
||||
use syn::spanned::Spanned;
|
||||
use quote::{quote, quote_spanned, ToTokens};
|
||||
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum RuntimeFlavor {
|
||||
@@ -34,6 +33,7 @@ struct Configuration {
|
||||
flavor: Option<RuntimeFlavor>,
|
||||
worker_threads: Option<(usize, Span)>,
|
||||
start_paused: Option<(bool, Span)>,
|
||||
is_test: bool,
|
||||
}
|
||||
|
||||
impl Configuration {
|
||||
@@ -47,6 +47,7 @@ impl Configuration {
|
||||
flavor: None,
|
||||
worker_threads: None,
|
||||
start_paused: None,
|
||||
is_test,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -92,16 +93,25 @@ impl Configuration {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn macro_name(&self) -> &'static str {
|
||||
if self.is_test {
|
||||
"tokio::test"
|
||||
} else {
|
||||
"tokio::main"
|
||||
}
|
||||
}
|
||||
|
||||
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.",
|
||||
))
|
||||
let msg = format!(
|
||||
"The `worker_threads` option requires the `multi_thread` runtime flavor. Use `#[{}(flavor = \"multi_thread\")]`",
|
||||
self.macro_name(),
|
||||
);
|
||||
return Err(syn::Error::new(worker_threads_span, msg));
|
||||
}
|
||||
(CurrentThread, None) => None,
|
||||
(Threaded, worker_threads) if self.rt_multi_thread_available => {
|
||||
@@ -119,10 +129,11 @@ impl Configuration {
|
||||
|
||||
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.",
|
||||
));
|
||||
let msg = format!(
|
||||
"The `start_paused` option requires the `current_thread` runtime flavor. Use `#[{}(flavor = \"current_thread\")]`",
|
||||
self.macro_name(),
|
||||
);
|
||||
return Err(syn::Error::new(start_paused_span, msg));
|
||||
}
|
||||
(CurrentThread, Some((start_paused, _))) => Some(start_paused),
|
||||
(_, None) => None,
|
||||
@@ -142,12 +153,12 @@ fn parse_int(int: syn::Lit, span: Span, field: &str) -> Result<usize, syn::Error
|
||||
Ok(value) => Ok(value),
|
||||
Err(e) => Err(syn::Error::new(
|
||||
span,
|
||||
format!("Failed to parse {} as integer: {}", field, e),
|
||||
format!("Failed to parse value of `{}` as integer: {}", field, e),
|
||||
)),
|
||||
},
|
||||
_ => Err(syn::Error::new(
|
||||
span,
|
||||
format!("Failed to parse {} as integer.", field),
|
||||
format!("Failed to parse value of `{}` as integer.", field),
|
||||
)),
|
||||
}
|
||||
}
|
||||
@@ -158,7 +169,7 @@ fn parse_string(int: syn::Lit, span: Span, field: &str) -> Result<String, syn::E
|
||||
syn::Lit::Verbatim(s) => Ok(s.to_string()),
|
||||
_ => Err(syn::Error::new(
|
||||
span,
|
||||
format!("Failed to parse {} as string.", field),
|
||||
format!("Failed to parse value of `{}` as string.", field),
|
||||
)),
|
||||
}
|
||||
}
|
||||
@@ -168,7 +179,7 @@ fn parse_bool(bool: syn::Lit, span: Span, field: &str) -> Result<bool, syn::Erro
|
||||
syn::Lit::Bool(b) => Ok(b.value),
|
||||
_ => Err(syn::Error::new(
|
||||
span,
|
||||
format!("Failed to parse {} as bool.", field),
|
||||
format!("Failed to parse value of `{}` as bool.", field),
|
||||
)),
|
||||
}
|
||||
}
|
||||
@@ -179,24 +190,13 @@ fn parse_knobs(
|
||||
is_test: bool,
|
||||
rt_multi_thread: bool,
|
||||
) -> Result<TokenStream, syn::Error> {
|
||||
let sig = &mut input.sig;
|
||||
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 Err(syn::Error::new_spanned(sig.fn_token, msg));
|
||||
if input.sig.asyncness.take().is_none() {
|
||||
let msg = "the `async` keyword is missing from the function declaration";
|
||||
return Err(syn::Error::new_spanned(input.sig.fn_token, msg));
|
||||
}
|
||||
|
||||
sig.asyncness = None;
|
||||
|
||||
let macro_name = if is_test {
|
||||
"tokio::test"
|
||||
} else {
|
||||
"tokio::main"
|
||||
};
|
||||
let mut config = Configuration::new(is_test, rt_multi_thread);
|
||||
let macro_name = config.macro_name();
|
||||
|
||||
for arg in args {
|
||||
match arg {
|
||||
@@ -208,20 +208,32 @@ fn parse_knobs(
|
||||
}
|
||||
match ident.unwrap().to_string().to_lowercase().as_str() {
|
||||
"worker_threads" => {
|
||||
config.set_worker_threads(namevalue.lit.clone(), namevalue.span())?;
|
||||
config.set_worker_threads(
|
||||
namevalue.lit.clone(),
|
||||
syn::spanned::Spanned::span(&namevalue.lit),
|
||||
)?;
|
||||
}
|
||||
"flavor" => {
|
||||
config.set_flavor(namevalue.lit.clone(), namevalue.span())?;
|
||||
config.set_flavor(
|
||||
namevalue.lit.clone(),
|
||||
syn::spanned::Spanned::span(&namevalue.lit),
|
||||
)?;
|
||||
}
|
||||
"start_paused" => {
|
||||
config.set_start_paused(namevalue.lit.clone(), namevalue.span())?;
|
||||
config.set_start_paused(
|
||||
namevalue.lit.clone(),
|
||||
syn::spanned::Spanned::span(&namevalue.lit),
|
||||
)?;
|
||||
}
|
||||
"core_threads" => {
|
||||
let msg = "Attribute `core_threads` is renamed to `worker_threads`";
|
||||
return Err(syn::Error::new_spanned(namevalue, msg));
|
||||
}
|
||||
name => {
|
||||
let msg = format!("Unknown attribute {} is specified; expected one of: `flavor`, `worker_threads`", name);
|
||||
let msg = format!(
|
||||
"Unknown attribute {} is specified; expected one of: `flavor`, `worker_threads`, `start_paused`",
|
||||
name,
|
||||
);
|
||||
return Err(syn::Error::new_spanned(namevalue, msg));
|
||||
}
|
||||
}
|
||||
@@ -266,11 +278,29 @@ fn parse_knobs(
|
||||
|
||||
let config = config.build()?;
|
||||
|
||||
// If type mismatch occurs, the current rustc points to the last statement.
|
||||
let (last_stmt_start_span, last_stmt_end_span) = {
|
||||
let mut last_stmt = input
|
||||
.block
|
||||
.stmts
|
||||
.last()
|
||||
.map(ToTokens::into_token_stream)
|
||||
.unwrap_or_default()
|
||||
.into_iter();
|
||||
// `Span` on stable Rust has a limitation that only points to the first
|
||||
// token, not the whole tokens. We can work around this limitation by
|
||||
// using the first/last span of the tokens like
|
||||
// `syn::Error::new_spanned` does.
|
||||
let start = last_stmt.next().map_or_else(Span::call_site, |t| t.span());
|
||||
let end = last_stmt.last().map_or(start, |t| t.span());
|
||||
(start, end)
|
||||
};
|
||||
|
||||
let mut rt = match config.flavor {
|
||||
RuntimeFlavor::CurrentThread => quote! {
|
||||
RuntimeFlavor::CurrentThread => quote_spanned! {last_stmt_start_span=>
|
||||
tokio::runtime::Builder::new_current_thread()
|
||||
},
|
||||
RuntimeFlavor::Threaded => quote! {
|
||||
RuntimeFlavor::Threaded => quote_spanned! {last_stmt_start_span=>
|
||||
tokio::runtime::Builder::new_multi_thread()
|
||||
},
|
||||
};
|
||||
@@ -281,26 +311,31 @@ fn parse_knobs(
|
||||
rt = quote! { #rt.start_paused(#v) };
|
||||
}
|
||||
|
||||
let header = {
|
||||
if is_test {
|
||||
quote! {
|
||||
#[::core::prelude::v1::test]
|
||||
}
|
||||
} else {
|
||||
quote! {}
|
||||
let header = if is_test {
|
||||
quote! {
|
||||
#[::core::prelude::v1::test]
|
||||
}
|
||||
} else {
|
||||
quote! {}
|
||||
};
|
||||
|
||||
let result = quote! {
|
||||
#header
|
||||
#(#attrs)*
|
||||
#vis #sig {
|
||||
let body = &input.block;
|
||||
let brace_token = input.block.brace_token;
|
||||
input.block = syn::parse2(quote_spanned! {last_stmt_end_span=>
|
||||
{
|
||||
#rt
|
||||
.enable_all()
|
||||
.build()
|
||||
.unwrap()
|
||||
.block_on(async #body)
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
input.block.brace_token = brace_token;
|
||||
|
||||
let result = quote! {
|
||||
#header
|
||||
#input
|
||||
};
|
||||
|
||||
Ok(result.into())
|
||||
@@ -334,12 +369,5 @@ pub(crate) fn test(args: TokenStream, item: TokenStream, rt_multi_thread: bool)
|
||||
}
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
parse_knobs(input, args, true, rt_multi_thread).unwrap_or_else(|e| e.to_compile_error().into())
|
||||
}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
#![doc(html_root_url = "https://docs.rs/tokio-macros/1.1.0")]
|
||||
#![allow(clippy::needless_doctest_main)]
|
||||
#![warn(
|
||||
missing_debug_implementations,
|
||||
@@ -168,6 +167,8 @@ use proc_macro::TokenStream;
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Note that `start_paused` requires the `test-util` feature to be enabled.
|
||||
///
|
||||
/// ### NOTE:
|
||||
///
|
||||
/// If you rename the Tokio crate in your dependencies this macro will not work.
|
||||
@@ -258,6 +259,8 @@ pub fn main_rt(args: TokenStream, item: TokenStream) -> TokenStream {
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Note that `start_paused` requires the `test-util` feature to be enabled.
|
||||
///
|
||||
/// ### NOTE:
|
||||
///
|
||||
/// If you rename the Tokio crate in your dependencies this macro will not work.
|
||||
|
||||
@@ -1,3 +1,26 @@
|
||||
# 0.1.5 (March 20, 2021)
|
||||
|
||||
### Fixed
|
||||
|
||||
- stream: documentation note for throttle `Unpin` ([#3600])
|
||||
|
||||
[#3600]: https://github.com/tokio-rs/tokio/pull/3600
|
||||
|
||||
# 0.1.4 (March 9, 2021)
|
||||
|
||||
Added
|
||||
|
||||
- signal: add `Signal` wrapper ([#3510])
|
||||
|
||||
Fixed
|
||||
|
||||
- stream: remove duplicate `doc_cfg` declaration ([#3561])
|
||||
- sync: yield initial value in `WatchStream` ([#3576])
|
||||
|
||||
[#3510]: https://github.com/tokio-rs/tokio/pull/3510
|
||||
[#3561]: https://github.com/tokio-rs/tokio/pull/3561
|
||||
[#3576]: https://github.com/tokio-rs/tokio/pull/3576
|
||||
|
||||
# 0.1.3 (February 5, 2021)
|
||||
|
||||
Added
|
||||
|
||||
@@ -2,18 +2,17 @@
|
||||
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"
|
||||
version = "0.1.5"
|
||||
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"
|
||||
documentation = "https://docs.rs/tokio-stream/0.1.5/tokio_stream"
|
||||
description = """
|
||||
Utilities to work with `Stream` and `tokio`.
|
||||
"""
|
||||
@@ -26,20 +25,21 @@ net = ["tokio/net"]
|
||||
io-util = ["tokio/io-util"]
|
||||
fs = ["tokio/fs"]
|
||||
sync = ["tokio/sync", "tokio-util"]
|
||||
signal = ["tokio/signal"]
|
||||
|
||||
[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 }
|
||||
tokio = { version = "1.2.0", path = "../tokio", features = ["sync"] }
|
||||
tokio-util = { version = "0.6.3", path = "../tokio-util", optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
tokio = { version = "1.0", features = ["full", "test-util"] }
|
||||
tokio = { version = "1.2.0", path = "../tokio", features = ["full", "test-util"] }
|
||||
async-stream = "0.3"
|
||||
tokio-test = { path = "../tokio-test" }
|
||||
futures = { version = "0.3", default-features = false }
|
||||
|
||||
proptest = "0.10.0"
|
||||
proptest = "1"
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
all-features = true
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
Copyright (c) 2020 Tokio Contributors
|
||||
Copyright (c) 2021 Tokio Contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any
|
||||
person obtaining a copy of this software and associated
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
#![doc(html_root_url = "https://docs.rs/tokio-stream/0.1.3")]
|
||||
#![allow(
|
||||
clippy::cognitive_complexity,
|
||||
clippy::large_enum_variant,
|
||||
@@ -10,18 +9,12 @@
|
||||
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.
|
||||
//!
|
||||
|
||||
@@ -48,6 +48,16 @@ macro_rules! cfg_sync {
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! cfg_signal {
|
||||
($($item:item)*) => {
|
||||
$(
|
||||
#[cfg(feature = "signal")]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "signal")))]
|
||||
$item
|
||||
)*
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! ready {
|
||||
($e:expr $(,)?) => {
|
||||
match $e {
|
||||
|
||||
@@ -38,18 +38,21 @@ where
|
||||
|
||||
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));
|
||||
let mut stream = Pin::new(me.stream);
|
||||
|
||||
match next {
|
||||
Some(v) => {
|
||||
if !(me.f)(v) {
|
||||
Poll::Ready(false)
|
||||
} else {
|
||||
cx.waker().wake_by_ref();
|
||||
Poll::Pending
|
||||
// Take a maximum of 32 items from the stream before yielding.
|
||||
for _ in 0..32 {
|
||||
match futures_core::ready!(stream.as_mut().poll_next(cx)) {
|
||||
Some(v) => {
|
||||
if !(me.f)(v) {
|
||||
return Poll::Ready(false);
|
||||
}
|
||||
}
|
||||
None => return Poll::Ready(true),
|
||||
}
|
||||
None => Poll::Ready(true),
|
||||
}
|
||||
|
||||
cx.waker().wake_by_ref();
|
||||
Poll::Pending
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,18 +38,21 @@ where
|
||||
|
||||
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));
|
||||
let mut stream = Pin::new(me.stream);
|
||||
|
||||
match next {
|
||||
Some(v) => {
|
||||
if (me.f)(v) {
|
||||
Poll::Ready(true)
|
||||
} else {
|
||||
cx.waker().wake_by_ref();
|
||||
Poll::Pending
|
||||
// Take a maximum of 32 items from the stream before yielding.
|
||||
for _ in 0..32 {
|
||||
match futures_core::ready!(stream.as_mut().poll_next(cx)) {
|
||||
Some(v) => {
|
||||
if (me.f)(v) {
|
||||
return Poll::Ready(true);
|
||||
}
|
||||
}
|
||||
None => return Poll::Ready(false),
|
||||
}
|
||||
None => Poll::Ready(false),
|
||||
}
|
||||
|
||||
cx.waker().wake_by_ref();
|
||||
Poll::Pending
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,7 +23,8 @@ where
|
||||
}
|
||||
|
||||
pin_project! {
|
||||
/// Stream for the [`throttle`](throttle) function.
|
||||
/// Stream for the [`throttle`](throttle) function. This object is `!Unpin`. If you need it to
|
||||
/// implement `Unpin` you can pin your throttle like this: `Box::pin(your_throttle)`.
|
||||
#[derive(Debug)]
|
||||
#[must_use = "streams do nothing unless polled"]
|
||||
pub struct Throttle<T> {
|
||||
|
||||
@@ -605,10 +605,10 @@ mod rand {
|
||||
/// Fast random number generate
|
||||
///
|
||||
/// Implement xorshift64+: 2 32-bit xorshift sequences added together.
|
||||
/// Shift triplet [17,7,16] was calculated as indicated in Marsaglia's
|
||||
/// Xorshift paper: https://www.jstatsoft.org/article/view/v008i14/xorshift.pdf
|
||||
/// Shift triplet `[17,7,16]` was calculated as indicated in Marsaglia's
|
||||
/// Xorshift paper: <https://www.jstatsoft.org/article/view/v008i14/xorshift.pdf>
|
||||
/// This generator passes the SmallCrush suite, part of TestU01 framework:
|
||||
/// http://simul.iro.umontreal.ca/testu01/tu01.html
|
||||
/// <http://simul.iro.umontreal.ca/testu01/tu01.html>
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct FastRand {
|
||||
one: Cell<u32>,
|
||||
|
||||
@@ -1,4 +1,13 @@
|
||||
//! Wrappers for Tokio types that implement `Stream`.
|
||||
//!
|
||||
#![cfg_attr(
|
||||
unix,
|
||||
doc = "You are viewing documentation built under unix. To view windows-specific wrappers, change to the `x86_64-pc-windows-msvc` platform."
|
||||
)]
|
||||
#![cfg_attr(
|
||||
windows,
|
||||
doc = "You are viewing documentation built under windows. To view unix-specific wrappers, change to the `x86_64-unknown-linux-gnu` platform."
|
||||
)]
|
||||
|
||||
/// Error types for the wrappers.
|
||||
pub mod errors {
|
||||
@@ -21,6 +30,18 @@ cfg_sync! {
|
||||
pub use watch::WatchStream;
|
||||
}
|
||||
|
||||
cfg_signal! {
|
||||
#[cfg(unix)]
|
||||
mod signal_unix;
|
||||
#[cfg(unix)]
|
||||
pub use signal_unix::SignalStream;
|
||||
|
||||
#[cfg(windows)]
|
||||
mod signal_windows;
|
||||
#[cfg(windows)]
|
||||
pub use signal_windows::{CtrlCStream, CtrlBreakStream};
|
||||
}
|
||||
|
||||
cfg_time! {
|
||||
mod interval;
|
||||
pub use interval::IntervalStream;
|
||||
|
||||
@@ -27,6 +27,16 @@ pub enum BroadcastStreamRecvError {
|
||||
Lagged(u64),
|
||||
}
|
||||
|
||||
impl fmt::Display for BroadcastStreamRecvError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
BroadcastStreamRecvError::Lagged(amt) => write!(f, "channel lagged by {}", amt),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for BroadcastStreamRecvError {}
|
||||
|
||||
async fn make_future<T: Clone>(mut rx: Receiver<T>) -> (Result<T, RecvError>, Receiver<T>) {
|
||||
let result = rx.recv().await;
|
||||
(result, rx)
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
use crate::Stream;
|
||||
use std::pin::Pin;
|
||||
use std::task::{Context, Poll};
|
||||
use tokio::signal::unix::Signal;
|
||||
|
||||
/// A wrapper around [`Signal`] that implements [`Stream`].
|
||||
///
|
||||
/// [`Signal`]: struct@tokio::signal::unix::Signal
|
||||
/// [`Stream`]: trait@crate::Stream
|
||||
#[derive(Debug)]
|
||||
#[cfg_attr(docsrs, doc(cfg(all(unix, feature = "signal"))))]
|
||||
pub struct SignalStream {
|
||||
inner: Signal,
|
||||
}
|
||||
|
||||
impl SignalStream {
|
||||
/// Create a new `SignalStream`.
|
||||
pub fn new(interval: Signal) -> Self {
|
||||
Self { inner: interval }
|
||||
}
|
||||
|
||||
/// Get back the inner `Signal`.
|
||||
pub fn into_inner(self) -> Signal {
|
||||
self.inner
|
||||
}
|
||||
}
|
||||
|
||||
impl Stream for SignalStream {
|
||||
type Item = ();
|
||||
|
||||
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<()>> {
|
||||
self.inner.poll_recv(cx)
|
||||
}
|
||||
}
|
||||
|
||||
impl AsRef<Signal> for SignalStream {
|
||||
fn as_ref(&self) -> &Signal {
|
||||
&self.inner
|
||||
}
|
||||
}
|
||||
|
||||
impl AsMut<Signal> for SignalStream {
|
||||
fn as_mut(&mut self) -> &mut Signal {
|
||||
&mut self.inner
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
use crate::Stream;
|
||||
use std::pin::Pin;
|
||||
use std::task::{Context, Poll};
|
||||
use tokio::signal::windows::{CtrlBreak, CtrlC};
|
||||
|
||||
/// A wrapper around [`CtrlC`] that implements [`Stream`].
|
||||
///
|
||||
/// [`CtrlC`]: struct@tokio::signal::windows::CtrlC
|
||||
/// [`Stream`]: trait@crate::Stream
|
||||
#[derive(Debug)]
|
||||
#[cfg_attr(docsrs, doc(cfg(all(windows, feature = "signal"))))]
|
||||
pub struct CtrlCStream {
|
||||
inner: CtrlC,
|
||||
}
|
||||
|
||||
impl CtrlCStream {
|
||||
/// Create a new `CtrlCStream`.
|
||||
pub fn new(interval: CtrlC) -> Self {
|
||||
Self { inner: interval }
|
||||
}
|
||||
|
||||
/// Get back the inner `CtrlC`.
|
||||
pub fn into_inner(self) -> CtrlC {
|
||||
self.inner
|
||||
}
|
||||
}
|
||||
|
||||
impl Stream for CtrlCStream {
|
||||
type Item = ();
|
||||
|
||||
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<()>> {
|
||||
self.inner.poll_recv(cx)
|
||||
}
|
||||
}
|
||||
|
||||
impl AsRef<CtrlC> for CtrlCStream {
|
||||
fn as_ref(&self) -> &CtrlC {
|
||||
&self.inner
|
||||
}
|
||||
}
|
||||
|
||||
impl AsMut<CtrlC> for CtrlCStream {
|
||||
fn as_mut(&mut self) -> &mut CtrlC {
|
||||
&mut self.inner
|
||||
}
|
||||
}
|
||||
|
||||
/// A wrapper around [`CtrlBreak`] that implements [`Stream`].
|
||||
///
|
||||
/// [`CtrlBreak`]: struct@tokio::signal::windows::CtrlBreak
|
||||
/// [`Stream`]: trait@crate::Stream
|
||||
#[derive(Debug)]
|
||||
#[cfg_attr(docsrs, doc(cfg(all(windows, feature = "signal"))))]
|
||||
pub struct CtrlBreakStream {
|
||||
inner: CtrlBreak,
|
||||
}
|
||||
|
||||
impl CtrlBreakStream {
|
||||
/// Create a new `CtrlBreakStream`.
|
||||
pub fn new(interval: CtrlBreak) -> Self {
|
||||
Self { inner: interval }
|
||||
}
|
||||
|
||||
/// Get back the inner `CtrlBreak`.
|
||||
pub fn into_inner(self) -> CtrlBreak {
|
||||
self.inner
|
||||
}
|
||||
}
|
||||
|
||||
impl Stream for CtrlBreakStream {
|
||||
type Item = ();
|
||||
|
||||
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<()>> {
|
||||
self.inner.poll_recv(cx)
|
||||
}
|
||||
}
|
||||
|
||||
impl AsRef<CtrlBreak> for CtrlBreakStream {
|
||||
fn as_ref(&self) -> &CtrlBreak {
|
||||
&self.inner
|
||||
}
|
||||
}
|
||||
|
||||
impl AsMut<CtrlBreak> for CtrlBreakStream {
|
||||
fn as_mut(&mut self) -> &mut CtrlBreak {
|
||||
&mut self.inner
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,41 @@ use tokio::sync::watch::error::RecvError;
|
||||
|
||||
/// A wrapper around [`tokio::sync::watch::Receiver`] that implements [`Stream`].
|
||||
///
|
||||
/// This stream will always start by yielding the current value when the WatchStream is polled,
|
||||
/// regardles of whether it was the initial value or sent afterwards.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// # #[tokio::main]
|
||||
/// # async fn main() {
|
||||
/// use tokio_stream::{StreamExt, wrappers::WatchStream};
|
||||
/// use tokio::sync::watch;
|
||||
///
|
||||
/// let (tx, rx) = watch::channel("hello");
|
||||
/// let mut rx = WatchStream::new(rx);
|
||||
///
|
||||
/// assert_eq!(rx.next().await, Some("hello"));
|
||||
///
|
||||
/// tx.send("goodbye").unwrap();
|
||||
/// assert_eq!(rx.next().await, Some("goodbye"));
|
||||
/// # }
|
||||
/// ```
|
||||
///
|
||||
/// ```
|
||||
/// # #[tokio::main]
|
||||
/// # async fn main() {
|
||||
/// use tokio_stream::{StreamExt, wrappers::WatchStream};
|
||||
/// use tokio::sync::watch;
|
||||
///
|
||||
/// let (tx, rx) = watch::channel("hello");
|
||||
/// let mut rx = WatchStream::new(rx);
|
||||
///
|
||||
/// tx.send("goodbye").unwrap();
|
||||
/// assert_eq!(rx.next().await, Some("goodbye"));
|
||||
/// # }
|
||||
/// ```
|
||||
///
|
||||
/// [`tokio::sync::watch::Receiver`]: struct@tokio::sync::watch::Receiver
|
||||
/// [`Stream`]: trait@crate::Stream
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "sync")))]
|
||||
@@ -28,7 +63,7 @@ impl<T: 'static + Clone + Unpin + Send + Sync> WatchStream<T> {
|
||||
/// Create a new `WatchStream`.
|
||||
pub fn new(rx: Receiver<T>) -> Self {
|
||||
Self {
|
||||
inner: ReusableBoxFuture::new(make_future(rx)),
|
||||
inner: ReusableBoxFuture::new(async move { (Ok(()), rx) }),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,9 @@
|
||||
# 0.4.1 (March 10, 2021)
|
||||
|
||||
- Fix `io::Mock` to be `Send` and `Sync` ([#3594])
|
||||
|
||||
[#3594]: https://github.com/tokio-rs/tokio/pull/3594
|
||||
|
||||
# 0.4.0 (December 23, 2020)
|
||||
|
||||
- Track `tokio` 1.0 release.
|
||||
|
||||
@@ -2,25 +2,24 @@
|
||||
name = "tokio-test"
|
||||
# When releasing to crates.io:
|
||||
# - Remove path dependencies
|
||||
# - Update html_root_url.
|
||||
# - Update doc url
|
||||
# - Cargo.toml
|
||||
# - Update CHANGELOG.md.
|
||||
# - Create "tokio-test-0.4.x" git tag.
|
||||
version = "0.4.0"
|
||||
version = "0.4.1"
|
||||
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-test/0.4.0/tokio_test"
|
||||
documentation = "https://docs.rs/tokio-test/0.4.1/tokio_test"
|
||||
description = """
|
||||
Testing utilities for Tokio- and futures-based code
|
||||
"""
|
||||
categories = ["asynchronous", "testing"]
|
||||
|
||||
[dependencies]
|
||||
tokio = { version = "1.0.0", path = "../tokio", features = ["rt", "sync", "time", "test-util"] }
|
||||
tokio = { version = "1.2.0", path = "../tokio", features = ["rt", "sync", "time", "test-util"] }
|
||||
tokio-stream = { version = "0.1", path = "../tokio-stream" }
|
||||
async-stream = "0.3"
|
||||
|
||||
@@ -28,7 +27,7 @@ bytes = "1.0.0"
|
||||
futures-core = "0.3.0"
|
||||
|
||||
[dev-dependencies]
|
||||
tokio = { version = "1.0.0", path = "../tokio", features = ["full"] }
|
||||
tokio = { version = "1.2.0", path = "../tokio", features = ["full"] }
|
||||
futures-util = "0.3.0"
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
Copyright (c) 2020 Tokio Contributors
|
||||
Copyright (c) 2021 Tokio Contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any
|
||||
person obtaining a copy of this software and associated
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::time::{self, Duration, Instant, Sleep};
|
||||
use tokio_stream::wrappers::UnboundedReceiverStream;
|
||||
|
||||
use futures_core::{ready, Stream};
|
||||
use std::collections::VecDeque;
|
||||
@@ -69,8 +70,7 @@ struct Inner {
|
||||
waiting: Option<Instant>,
|
||||
sleep: Option<Pin<Box<Sleep>>>,
|
||||
read_wait: Option<Waker>,
|
||||
// rx: mpsc::UnboundedReceiver<Action>,
|
||||
rx: Pin<Box<dyn Stream<Item = Action> + Send>>,
|
||||
rx: UnboundedReceiverStream<Action>,
|
||||
}
|
||||
|
||||
impl Builder {
|
||||
@@ -185,13 +185,9 @@ impl Handle {
|
||||
|
||||
impl Inner {
|
||||
fn new(actions: VecDeque<Action>) -> (Inner, Handle) {
|
||||
let (tx, mut rx) = mpsc::unbounded_channel();
|
||||
let (tx, rx) = mpsc::unbounded_channel();
|
||||
|
||||
let rx = Box::pin(async_stream::stream! {
|
||||
while let Some(item) = rx.recv().await {
|
||||
yield item;
|
||||
}
|
||||
});
|
||||
let rx = UnboundedReceiverStream::new(rx);
|
||||
|
||||
let inner = Inner {
|
||||
actions,
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
#![doc(html_root_url = "https://docs.rs/tokio-test/0.4.0")]
|
||||
#![warn(
|
||||
missing_debug_implementations,
|
||||
missing_docs,
|
||||
@@ -22,9 +21,9 @@ pub mod task;
|
||||
/// future completes.
|
||||
///
|
||||
/// For more information, see the documentation for
|
||||
/// [`tokio::runtime::current_thread::Runtime::block_on`][runtime-block-on].
|
||||
/// [`tokio::runtime::Runtime::block_on`][runtime-block-on].
|
||||
///
|
||||
/// [runtime-block-on]: https://docs.rs/tokio/0.2.0-alpha.2/tokio/runtime/current_thread/struct.Runtime.html#method.block_on
|
||||
/// [runtime-block-on]: https://docs.rs/tokio/1.3.0/tokio/runtime/struct.Runtime.html#method.block_on
|
||||
pub fn block_on<F: std::future::Future>(future: F) -> F::Output {
|
||||
use tokio::runtime;
|
||||
|
||||
|
||||
@@ -259,3 +259,37 @@ macro_rules! assert_err {
|
||||
}
|
||||
}};
|
||||
}
|
||||
|
||||
/// Asserts that an exact duration has elapsed since since the start instant ±1ms.
|
||||
///
|
||||
/// ```rust
|
||||
/// use tokio::time::{self, Instant};
|
||||
/// use std::time::Duration;
|
||||
/// use tokio_test::assert_elapsed;
|
||||
/// # async fn test_time_passed() {
|
||||
///
|
||||
/// let start = Instant::now();
|
||||
/// let dur = Duration::from_millis(50);
|
||||
/// time::sleep(dur).await;
|
||||
/// assert_elapsed!(start, dur);
|
||||
/// # }
|
||||
/// ```
|
||||
///
|
||||
/// This 1ms buffer is required because Tokio's hashed-wheel timer has finite time resolution and
|
||||
/// will not always sleep for the exact interval.
|
||||
#[macro_export]
|
||||
macro_rules! assert_elapsed {
|
||||
($start:expr, $dur:expr) => {{
|
||||
let elapsed = $start.elapsed();
|
||||
// type ascription improves compiler error when wrong type is passed
|
||||
let lower: std::time::Duration = $dur;
|
||||
|
||||
// Handles ms rounding
|
||||
assert!(
|
||||
elapsed >= lower && elapsed <= lower + std::time::Duration::from_millis(1),
|
||||
"actual = {:?}, expected = {:?}",
|
||||
elapsed,
|
||||
lower
|
||||
);
|
||||
}};
|
||||
}
|
||||
|
||||
@@ -1,3 +1,43 @@
|
||||
# 0.6.6 (April 12, 2021)
|
||||
|
||||
### Added
|
||||
|
||||
- util: makes `Framed` and `FramedStream` resumable after eof ([#3272])
|
||||
- util: add `PollSemaphore::{add_permits, available_permits}` ([#3683])
|
||||
|
||||
### Fixed
|
||||
|
||||
- chore: avoid allocation if `PollSemaphore` is unused ([#3634])
|
||||
|
||||
[#3272]: https://github.com/tokio-rs/tokio/pull/3272
|
||||
[#3634]: https://github.com/tokio-rs/tokio/pull/3634
|
||||
[#3683]: https://github.com/tokio-rs/tokio/pull/3683
|
||||
|
||||
# 0.6.5 (March 20, 2021)
|
||||
|
||||
### Fixed
|
||||
|
||||
- util: annotate time module as requiring `time` feature ([#3606])
|
||||
|
||||
[#3606]: https://github.com/tokio-rs/tokio/pull/3606
|
||||
|
||||
# 0.6.4 (March 9, 2021)
|
||||
|
||||
### Added
|
||||
|
||||
- codec: `AnyDelimiter` codec ([#3406])
|
||||
- sync: add pollable `mpsc::Sender` ([#3490])
|
||||
|
||||
### Fixed
|
||||
|
||||
- codec: `LinesCodec` should only return `MaxLineLengthExceeded` once per line ([#3556])
|
||||
- sync: fuse PollSemaphore ([#3578])
|
||||
|
||||
[#3406]: https://github.com/tokio-rs/tokio/pull/3406
|
||||
[#3490]: https://github.com/tokio-rs/tokio/pull/3490
|
||||
[#3556]: https://github.com/tokio-rs/tokio/pull/3556
|
||||
[#3578]: https://github.com/tokio-rs/tokio/pull/3578
|
||||
|
||||
# 0.6.3 (January 31, 2021)
|
||||
|
||||
### Added
|
||||
|
||||
@@ -2,18 +2,17 @@
|
||||
name = "tokio-util"
|
||||
# When releasing to crates.io:
|
||||
# - Remove path dependencies
|
||||
# - Update html_root_url.
|
||||
# - Update doc url
|
||||
# - Cargo.toml
|
||||
# - Update CHANGELOG.md.
|
||||
# - Create "tokio-util-0.6.x" git tag.
|
||||
version = "0.6.3"
|
||||
version = "0.6.6"
|
||||
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-util/0.6.3/tokio_util"
|
||||
documentation = "https://docs.rs/tokio-util/0.6.6/tokio_util"
|
||||
description = """
|
||||
Additional utilities for working with Tokio.
|
||||
"""
|
||||
@@ -36,7 +35,7 @@ rt = ["tokio/rt"]
|
||||
__docs_rs = ["futures-util"]
|
||||
|
||||
[dependencies]
|
||||
tokio = { version = "1.0.0", features = ["sync"] }
|
||||
tokio = { version = "1.0.0", path = "../tokio", features = ["sync"] }
|
||||
|
||||
bytes = "1.0.0"
|
||||
futures-core = "0.3.0"
|
||||
@@ -48,9 +47,9 @@ pin-project-lite = "0.2.0"
|
||||
slab = { version = "0.4.1", optional = true } # Backs `DelayQueue`
|
||||
|
||||
[dev-dependencies]
|
||||
tokio = { version = "1.0.0", features = ["full"] }
|
||||
tokio-test = { version = "0.4.0" }
|
||||
tokio-stream = { version = "0.1" }
|
||||
tokio = { version = "1.0.0", path = "../tokio", features = ["full"] }
|
||||
tokio-test = { version = "0.4.0", path = "../tokio-test" }
|
||||
tokio-stream = { version = "0.1", path = "../tokio-stream" }
|
||||
|
||||
async-stream = "0.3.0"
|
||||
futures = "0.3.0"
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
Copyright (c) 2020 Tokio Contributors
|
||||
Copyright (c) 2021 Tokio Contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any
|
||||
person obtaining a copy of this software and associated
|
||||
|
||||
@@ -47,3 +47,13 @@ macro_rules! cfg_rt {
|
||||
)*
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! cfg_time {
|
||||
($($item:item)*) => {
|
||||
$(
|
||||
#[cfg(feature = "time")]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "time")))]
|
||||
$item
|
||||
)*
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,263 @@
|
||||
use crate::codec::decoder::Decoder;
|
||||
use crate::codec::encoder::Encoder;
|
||||
|
||||
use bytes::{Buf, BufMut, Bytes, BytesMut};
|
||||
use std::{cmp, fmt, io, str, usize};
|
||||
|
||||
const DEFAULT_SEEK_DELIMITERS: &[u8] = b",;\n\r";
|
||||
const DEFAULT_SEQUENCE_WRITER: &[u8] = b",";
|
||||
/// A simple [`Decoder`] and [`Encoder`] implementation that splits up data into chunks based on any character in the given delimiter string.
|
||||
///
|
||||
/// [`Decoder`]: crate::codec::Decoder
|
||||
/// [`Encoder`]: crate::codec::Encoder
|
||||
///
|
||||
/// # Example
|
||||
/// Decode string of bytes containing various different delimiters.
|
||||
///
|
||||
/// [`BytesMut`]: bytes::BytesMut
|
||||
/// [`Error`]: std::io::Error
|
||||
///
|
||||
/// ```
|
||||
/// use tokio_util::codec::{AnyDelimiterCodec, Decoder};
|
||||
/// use bytes::{BufMut, BytesMut};
|
||||
///
|
||||
/// #
|
||||
/// # #[tokio::main(flavor = "current_thread")]
|
||||
/// # async fn main() -> Result<(), std::io::Error> {
|
||||
/// let mut codec = AnyDelimiterCodec::new(b",;\r\n".to_vec(),b";".to_vec());
|
||||
/// let buf = &mut BytesMut::new();
|
||||
/// buf.reserve(200);
|
||||
/// buf.put_slice(b"chunk 1,chunk 2;chunk 3\n\r");
|
||||
/// assert_eq!("chunk 1", codec.decode(buf).unwrap().unwrap());
|
||||
/// assert_eq!("chunk 2", codec.decode(buf).unwrap().unwrap());
|
||||
/// assert_eq!("chunk 3", codec.decode(buf).unwrap().unwrap());
|
||||
/// assert_eq!("", codec.decode(buf).unwrap().unwrap());
|
||||
/// assert_eq!(None, codec.decode(buf).unwrap());
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// ```
|
||||
///
|
||||
#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
|
||||
pub struct AnyDelimiterCodec {
|
||||
// Stored index of the next index to examine for the delimiter character.
|
||||
// This is used to optimize searching.
|
||||
// For example, if `decode` was called with `abc` and the delimiter is '{}', it would hold `3`,
|
||||
// because that is the next index to examine.
|
||||
// The next time `decode` is called with `abcde}`, the method will
|
||||
// only look at `de}` before returning.
|
||||
next_index: usize,
|
||||
|
||||
/// The maximum length for a given chunk. If `usize::MAX`, chunks will be
|
||||
/// read until a delimiter character is reached.
|
||||
max_length: usize,
|
||||
|
||||
/// Are we currently discarding the remainder of a chunk which was over
|
||||
/// the length limit?
|
||||
is_discarding: bool,
|
||||
|
||||
/// The bytes that are using for search during decode
|
||||
seek_delimiters: Vec<u8>,
|
||||
|
||||
/// The bytes that are using for encoding
|
||||
sequence_writer: Vec<u8>,
|
||||
}
|
||||
|
||||
impl AnyDelimiterCodec {
|
||||
/// Returns a `AnyDelimiterCodec` for splitting up data into chunks.
|
||||
///
|
||||
/// # Note
|
||||
///
|
||||
/// The returned `AnyDelimiterCodec` will not have an upper bound on the length
|
||||
/// of a buffered chunk. See the documentation for [`new_with_max_length`]
|
||||
/// for information on why this could be a potential security risk.
|
||||
///
|
||||
/// [`new_with_max_length`]: crate::codec::AnyDelimiterCodec::new_with_max_length()
|
||||
pub fn new(seek_delimiters: Vec<u8>, sequence_writer: Vec<u8>) -> AnyDelimiterCodec {
|
||||
AnyDelimiterCodec {
|
||||
next_index: 0,
|
||||
max_length: usize::MAX,
|
||||
is_discarding: false,
|
||||
seek_delimiters,
|
||||
sequence_writer,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a `AnyDelimiterCodec` with a maximum chunk length limit.
|
||||
///
|
||||
/// If this is set, calls to `AnyDelimiterCodec::decode` will return a
|
||||
/// [`AnyDelimiterCodecError`] when a chunk exceeds the length limit. Subsequent calls
|
||||
/// will discard up to `limit` bytes from that chunk until a delimiter
|
||||
/// character is reached, returning `None` until the delimiter over the limit
|
||||
/// has been fully discarded. After that point, calls to `decode` will
|
||||
/// function as normal.
|
||||
///
|
||||
/// # Note
|
||||
///
|
||||
/// Setting a length limit is highly recommended for any `AnyDelimiterCodec` which
|
||||
/// will be exposed to untrusted input. Otherwise, the size of the buffer
|
||||
/// that holds the chunk currently being read is unbounded. An attacker could
|
||||
/// exploit this unbounded buffer by sending an unbounded amount of input
|
||||
/// without any delimiter characters, causing unbounded memory consumption.
|
||||
///
|
||||
/// [`AnyDelimiterCodecError`]: crate::codec::AnyDelimiterCodecError
|
||||
pub fn new_with_max_length(
|
||||
seek_delimiters: Vec<u8>,
|
||||
sequence_writer: Vec<u8>,
|
||||
max_length: usize,
|
||||
) -> Self {
|
||||
AnyDelimiterCodec {
|
||||
max_length,
|
||||
..AnyDelimiterCodec::new(seek_delimiters, sequence_writer)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the maximum chunk length when decoding.
|
||||
///
|
||||
/// ```
|
||||
/// use std::usize;
|
||||
/// use tokio_util::codec::AnyDelimiterCodec;
|
||||
///
|
||||
/// let codec = AnyDelimiterCodec::new(b",;\n".to_vec(), b";".to_vec());
|
||||
/// assert_eq!(codec.max_length(), usize::MAX);
|
||||
/// ```
|
||||
/// ```
|
||||
/// use tokio_util::codec::AnyDelimiterCodec;
|
||||
///
|
||||
/// let codec = AnyDelimiterCodec::new_with_max_length(b",;\n".to_vec(), b";".to_vec(), 256);
|
||||
/// assert_eq!(codec.max_length(), 256);
|
||||
/// ```
|
||||
pub fn max_length(&self) -> usize {
|
||||
self.max_length
|
||||
}
|
||||
}
|
||||
|
||||
impl Decoder for AnyDelimiterCodec {
|
||||
type Item = Bytes;
|
||||
type Error = AnyDelimiterCodecError;
|
||||
|
||||
fn decode(&mut self, buf: &mut BytesMut) -> Result<Option<Bytes>, AnyDelimiterCodecError> {
|
||||
loop {
|
||||
// Determine how far into the buffer we'll search for a delimiter. If
|
||||
// there's no max_length set, we'll read to the end of the buffer.
|
||||
let read_to = cmp::min(self.max_length.saturating_add(1), buf.len());
|
||||
|
||||
let new_chunk_offset = buf[self.next_index..read_to].iter().position(|b| {
|
||||
self.seek_delimiters
|
||||
.iter()
|
||||
.any(|delimiter| *b == *delimiter)
|
||||
});
|
||||
|
||||
match (self.is_discarding, new_chunk_offset) {
|
||||
(true, Some(offset)) => {
|
||||
// If we found a new chunk, discard up to that offset and
|
||||
// then stop discarding. On the next iteration, we'll try
|
||||
// to read a chunk normally.
|
||||
buf.advance(offset + self.next_index + 1);
|
||||
self.is_discarding = false;
|
||||
self.next_index = 0;
|
||||
}
|
||||
(true, None) => {
|
||||
// Otherwise, we didn't find a new chunk, so we'll discard
|
||||
// everything we read. On the next iteration, we'll continue
|
||||
// discarding up to max_len bytes unless we find a new chunk.
|
||||
buf.advance(read_to);
|
||||
self.next_index = 0;
|
||||
if buf.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
}
|
||||
(false, Some(offset)) => {
|
||||
// Found a chunk!
|
||||
let new_chunk_index = offset + self.next_index;
|
||||
self.next_index = 0;
|
||||
let mut chunk = buf.split_to(new_chunk_index + 1);
|
||||
chunk.truncate(chunk.len() - 1);
|
||||
let chunk = chunk.freeze();
|
||||
return Ok(Some(chunk));
|
||||
}
|
||||
(false, None) if buf.len() > self.max_length => {
|
||||
// Reached the maximum length without finding a
|
||||
// new chunk, return an error and start discarding on the
|
||||
// next call.
|
||||
self.is_discarding = true;
|
||||
return Err(AnyDelimiterCodecError::MaxChunkLengthExceeded);
|
||||
}
|
||||
(false, None) => {
|
||||
// We didn't find a chunk or reach the length limit, so the next
|
||||
// call will resume searching at the current offset.
|
||||
self.next_index = read_to;
|
||||
return Ok(None);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn decode_eof(&mut self, buf: &mut BytesMut) -> Result<Option<Bytes>, AnyDelimiterCodecError> {
|
||||
Ok(match self.decode(buf)? {
|
||||
Some(frame) => Some(frame),
|
||||
None => {
|
||||
// return remaining data, if any
|
||||
if buf.is_empty() {
|
||||
None
|
||||
} else {
|
||||
let chunk = buf.split_to(buf.len());
|
||||
self.next_index = 0;
|
||||
Some(chunk.freeze())
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Encoder<T> for AnyDelimiterCodec
|
||||
where
|
||||
T: AsRef<str>,
|
||||
{
|
||||
type Error = AnyDelimiterCodecError;
|
||||
|
||||
fn encode(&mut self, chunk: T, buf: &mut BytesMut) -> Result<(), AnyDelimiterCodecError> {
|
||||
let chunk = chunk.as_ref();
|
||||
buf.reserve(chunk.len() + 1);
|
||||
buf.put(chunk.as_bytes());
|
||||
buf.put(self.sequence_writer.as_ref());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for AnyDelimiterCodec {
|
||||
fn default() -> Self {
|
||||
Self::new(
|
||||
DEFAULT_SEEK_DELIMITERS.to_vec(),
|
||||
DEFAULT_SEQUENCE_WRITER.to_vec(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// An error occured while encoding or decoding a chunk.
|
||||
#[derive(Debug)]
|
||||
pub enum AnyDelimiterCodecError {
|
||||
/// The maximum chunk length was exceeded.
|
||||
MaxChunkLengthExceeded,
|
||||
/// An IO error occurred.
|
||||
Io(io::Error),
|
||||
}
|
||||
|
||||
impl fmt::Display for AnyDelimiterCodecError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
AnyDelimiterCodecError::MaxChunkLengthExceeded => {
|
||||
write!(f, "max chunk length exceeded")
|
||||
}
|
||||
AnyDelimiterCodecError::Io(e) => write!(f, "{}", e),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<io::Error> for AnyDelimiterCodecError {
|
||||
fn from(e: io::Error) -> AnyDelimiterCodecError {
|
||||
AnyDelimiterCodecError::Io(e)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for AnyDelimiterCodecError {}
|
||||
@@ -16,6 +16,20 @@ use std::io;
|
||||
/// implementing stateful streaming parsers. In many cases, though, this type
|
||||
/// will simply be a unit struct (e.g. `struct HttpDecoder`).
|
||||
///
|
||||
/// For some underlying data-sources, namely files and FIFOs,
|
||||
/// it's possible to temporarily read 0 bytes by reaching EOF.
|
||||
///
|
||||
/// In these cases `decode_eof` will be called until it signals
|
||||
/// fullfillment of all closing frames by returning `Ok(None)`.
|
||||
/// After that, repeated attempts to read from the [`Framed`] or [`FramedRead`]
|
||||
/// will not invoke `decode` or `decode_eof` again, until data can be read
|
||||
/// during a retry.
|
||||
///
|
||||
/// It is up to the Decoder to keep track of a restart after an EOF,
|
||||
/// and to decide how to handle such an event by, for example,
|
||||
/// allowing frames to cross EOF boundaries, re-emitting opening frames, or
|
||||
/// reseting the entire internal state.
|
||||
///
|
||||
/// [`Framed`]: crate::codec::Framed
|
||||
/// [`FramedRead`]: crate::codec::FramedRead
|
||||
pub trait Decoder {
|
||||
@@ -115,13 +129,18 @@ pub trait Decoder {
|
||||
/// This method defaults to calling `decode` and returns an error if
|
||||
/// `Ok(None)` is returned while there is unconsumed data in `buf`.
|
||||
/// Typically this doesn't need to be implemented unless the framing
|
||||
/// protocol differs near the end of the stream.
|
||||
/// protocol differs near the end of the stream, or if you need to construct
|
||||
/// frames _across_ eof boundaries on sources that can be resumed.
|
||||
///
|
||||
/// Note that the `buf` argument may be empty. If a previous call to
|
||||
/// `decode_eof` consumed all the bytes in the buffer, `decode_eof` will be
|
||||
/// called again until it returns `None`, indicating that there are no more
|
||||
/// frames to yield. This behavior enables returning finalization frames
|
||||
/// that may not be based on inbound data.
|
||||
///
|
||||
/// Once `None` has been returned, `decode_eof` won't be called again until
|
||||
/// an attempt to resume the stream has been made, where the underlying stream
|
||||
/// actually returned more data.
|
||||
fn decode_eof(&mut self, buf: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
|
||||
match self.decode(buf)? {
|
||||
Some(frame) => Ok(Some(frame)),
|
||||
|
||||
@@ -52,6 +52,11 @@ where
|
||||
/// calling [`split`] on the `Framed` returned by this method, which will
|
||||
/// break them into separate objects, allowing them to interact more easily.
|
||||
///
|
||||
/// Note that, for some byte sources, the stream can be resumed after an EOF
|
||||
/// by reading from it, even after it has returned `None`. Repeated attempts
|
||||
/// to do so, without new data available, continue to return `None` without
|
||||
/// creating more (closing) frames.
|
||||
///
|
||||
/// [`Stream`]: futures_core::Stream
|
||||
/// [`Sink`]: futures_sink::Sink
|
||||
/// [`Decode`]: crate::codec::Decoder
|
||||
|
||||
@@ -120,42 +120,97 @@ where
|
||||
|
||||
let mut pinned = self.project();
|
||||
let state: &mut ReadFrame = pinned.state.borrow_mut();
|
||||
// The following loops implements a state machine with each state corresponding
|
||||
// to a combination of the `is_readable` and `eof` flags. States persist across
|
||||
// loop entries and most state transitions occur with a return.
|
||||
//
|
||||
// The intitial state is `reading`.
|
||||
//
|
||||
// | state | eof | is_readable |
|
||||
// |---------|-------|-------------|
|
||||
// | reading | false | false |
|
||||
// | framing | false | true |
|
||||
// | pausing | true | true |
|
||||
// | paused | true | false |
|
||||
//
|
||||
// `decode_eof`
|
||||
// returns `Some` read 0 bytes
|
||||
// │ │ │ │
|
||||
// │ ▼ │ ▼
|
||||
// ┌───────┐ `decode_eof` ┌──────┐
|
||||
// ┌──read 0 bytes──▶│pausing│─returns `None`─▶│paused│──┐
|
||||
// │ └───────┘ └──────┘ │
|
||||
// pending read┐ │ ┌──────┐ │ ▲ │
|
||||
// │ │ │ │ │ │ │ │
|
||||
// │ ▼ │ │ `decode` returns `Some`│ pending read
|
||||
// │ ╔═══════╗ ┌───────┐◀─┘ │
|
||||
// └──║reading║─read n>0 bytes─▶│framing│ │
|
||||
// ╚═══════╝ └───────┘◀──────read n>0 bytes┘
|
||||
// ▲ │
|
||||
// │ │
|
||||
// └─`decode` returns `None`─┘
|
||||
loop {
|
||||
// Repeatedly call `decode` or `decode_eof` as long as it is
|
||||
// "readable". Readable is defined as not having returned `None`. If
|
||||
// the upstream has returned EOF, and the decoder is no longer
|
||||
// readable, it can be assumed that the decoder will never become
|
||||
// readable again, at which point the stream is terminated.
|
||||
// Repeatedly call `decode` or `decode_eof` while the buffer is "readable",
|
||||
// i.e. it _might_ contain data consumable as a frame or closing frame.
|
||||
// Both signal that there is no such data by returning `None`.
|
||||
//
|
||||
// If `decode` couldn't read a frame and the upstream source has returned eof,
|
||||
// `decode_eof` will attemp to decode the remaining bytes as closing frames.
|
||||
//
|
||||
// If the underlying AsyncRead is resumable, we may continue after an EOF,
|
||||
// but must finish emmiting all of it's associated `decode_eof` frames.
|
||||
// Furthermore, we don't want to emit any `decode_eof` frames on retried
|
||||
// reads after an EOF unless we've actually read more data.
|
||||
if state.is_readable {
|
||||
// pausing or framing
|
||||
if state.eof {
|
||||
// pausing
|
||||
let frame = pinned.codec.decode_eof(&mut state.buffer)?;
|
||||
if frame.is_none() {
|
||||
state.is_readable = false; // prepare pausing -> paused
|
||||
}
|
||||
// implicit pausing -> pausing or pausing -> paused
|
||||
return Poll::Ready(frame.map(Ok));
|
||||
}
|
||||
|
||||
// framing
|
||||
trace!("attempting to decode a frame");
|
||||
|
||||
if let Some(frame) = pinned.codec.decode(&mut state.buffer)? {
|
||||
trace!("frame decoded from buffer");
|
||||
// implicit framing -> framing
|
||||
return Poll::Ready(Some(Ok(frame)));
|
||||
}
|
||||
|
||||
// framing -> reading
|
||||
state.is_readable = false;
|
||||
}
|
||||
|
||||
assert!(!state.eof);
|
||||
|
||||
// Otherwise, try to read more data and try again. Make sure we've
|
||||
// got room for at least one byte to read to ensure that we don't
|
||||
// get a spurious 0 that looks like EOF
|
||||
// reading or paused
|
||||
// If we can't build a frame yet, try to read more data and try again.
|
||||
// Make sure we've got room for at least one byte to read to ensure
|
||||
// that we don't get a spurious 0 that looks like EOF.
|
||||
state.buffer.reserve(1);
|
||||
let bytect = match poll_read_buf(pinned.inner.as_mut(), cx, &mut state.buffer)? {
|
||||
Poll::Ready(ct) => ct,
|
||||
// implicit reading -> reading or implicit paused -> paused
|
||||
Poll::Pending => return Poll::Pending,
|
||||
};
|
||||
if bytect == 0 {
|
||||
if state.eof {
|
||||
// We're already at an EOF, and since we've reached this path
|
||||
// we're also not readable. This implies that we've already finished
|
||||
// our `decode_eof` handling, so we can simply return `None`.
|
||||
// implicit paused -> paused
|
||||
return Poll::Ready(None);
|
||||
}
|
||||
// prepare reading -> paused
|
||||
state.eof = true;
|
||||
} else {
|
||||
// prepare paused -> framing or noop reading -> framing
|
||||
state.eof = false;
|
||||
}
|
||||
|
||||
// paused -> framing or reading -> framing or reading -> pausing
|
||||
state.is_readable = true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -535,14 +535,14 @@ impl LengthDelimitedCodec {
|
||||
Ok(Some(n))
|
||||
}
|
||||
|
||||
fn decode_data(&self, n: usize, src: &mut BytesMut) -> io::Result<Option<BytesMut>> {
|
||||
fn decode_data(&self, n: usize, src: &mut BytesMut) -> Option<BytesMut> {
|
||||
// At this point, the buffer has already had the required capacity
|
||||
// reserved. All there is to do is read.
|
||||
if src.len() < n {
|
||||
return Ok(None);
|
||||
return None;
|
||||
}
|
||||
|
||||
Ok(Some(src.split_to(n)))
|
||||
Some(src.split_to(n))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -562,7 +562,7 @@ impl Decoder for LengthDelimitedCodec {
|
||||
DecodeState::Data(n) => n,
|
||||
};
|
||||
|
||||
match self.decode_data(n, src)? {
|
||||
match self.decode_data(n, src) {
|
||||
Some(data) => {
|
||||
// Update the decode state
|
||||
self.state = DecodeState::Head;
|
||||
|
||||
@@ -133,7 +133,7 @@ impl Decoder for LinesCodec {
|
||||
buf.advance(read_to);
|
||||
self.next_index = 0;
|
||||
if buf.is_empty() {
|
||||
return Err(LinesCodecError::MaxLineLengthExceeded);
|
||||
return Ok(None);
|
||||
}
|
||||
}
|
||||
(false, Some(offset)) => {
|
||||
|
||||
@@ -285,3 +285,6 @@ pub use self::length_delimited::{LengthDelimitedCodec, LengthDelimitedCodecError
|
||||
|
||||
mod lines_codec;
|
||||
pub use self::lines_codec::{LinesCodec, LinesCodecError};
|
||||
|
||||
mod any_delimiter_codec;
|
||||
pub use self::any_delimiter_codec::{AnyDelimiterCodec, AnyDelimiterCodecError};
|
||||
|
||||
@@ -215,3 +215,17 @@ where
|
||||
tokio::io::AsyncWrite::poll_shutdown(self.project().inner, cx)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
impl<T: std::os::unix::io::AsRawFd> std::os::unix::io::AsRawFd for Compat<T> {
|
||||
fn as_raw_fd(&self) -> std::os::unix::io::RawFd {
|
||||
self.inner.as_raw_fd()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
impl<T: std::os::windows::io::AsRawHandle> std::os::windows::io::AsRawHandle for Compat<T> {
|
||||
fn as_raw_handle(&self) -> std::os::windows::io::RawHandle {
|
||||
self.inner.as_raw_handle()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
#![doc(html_root_url = "https://docs.rs/tokio-util/0.6.3")]
|
||||
#![allow(clippy::needless_doctest_main)]
|
||||
#![warn(
|
||||
missing_debug_implementations,
|
||||
@@ -46,13 +45,14 @@ cfg_rt! {
|
||||
pub mod context;
|
||||
}
|
||||
|
||||
cfg_time! {
|
||||
pub mod time;
|
||||
}
|
||||
|
||||
pub mod sync;
|
||||
|
||||
pub mod either;
|
||||
|
||||
#[cfg(feature = "time")]
|
||||
pub mod time;
|
||||
|
||||
#[cfg(any(feature = "io", feature = "codec"))]
|
||||
mod util {
|
||||
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
|
||||
|
||||
@@ -5,6 +5,9 @@ pub use cancellation_token::{CancellationToken, WaitForCancellationFuture};
|
||||
|
||||
mod intrusive_double_linked_list;
|
||||
|
||||
mod mpsc;
|
||||
pub use mpsc::PollSender;
|
||||
|
||||
mod poll_semaphore;
|
||||
pub use poll_semaphore::PollSemaphore;
|
||||
|
||||
|
||||
@@ -0,0 +1,221 @@
|
||||
use futures_core::ready;
|
||||
use futures_sink::Sink;
|
||||
use std::pin::Pin;
|
||||
use std::sync::Arc;
|
||||
use std::task::{Context, Poll};
|
||||
use tokio::sync::mpsc::{error::SendError, Sender};
|
||||
|
||||
use super::ReusableBoxFuture;
|
||||
|
||||
// This implementation was chosen over something based on permits because to get a
|
||||
// `tokio::sync::mpsc::Permit` out of the `inner` future, you must transmute the
|
||||
// lifetime on the permit to `'static`.
|
||||
|
||||
/// A wrapper around [`mpsc::Sender`] that can be polled.
|
||||
///
|
||||
/// [`mpsc::Sender`]: tokio::sync::mpsc::Sender
|
||||
#[derive(Debug)]
|
||||
pub struct PollSender<T> {
|
||||
/// is none if closed
|
||||
sender: Option<Arc<Sender<T>>>,
|
||||
is_sending: bool,
|
||||
inner: ReusableBoxFuture<Result<(), SendError<T>>>,
|
||||
}
|
||||
|
||||
// By reusing the same async fn for both Some and None, we make sure every
|
||||
// future passed to ReusableBoxFuture has the same underlying type, and hence
|
||||
// the same size and alignment.
|
||||
async fn make_future<T>(data: Option<(Arc<Sender<T>>, T)>) -> Result<(), SendError<T>> {
|
||||
match data {
|
||||
Some((sender, value)) => sender.send(value).await,
|
||||
None => unreachable!(
|
||||
"This future should not be pollable, as is_sending should be set to false."
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Send + 'static> PollSender<T> {
|
||||
/// Create a new `PollSender`.
|
||||
pub fn new(sender: Sender<T>) -> Self {
|
||||
Self {
|
||||
sender: Some(Arc::new(sender)),
|
||||
is_sending: false,
|
||||
inner: ReusableBoxFuture::new(make_future(None)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Start sending a new item.
|
||||
///
|
||||
/// This method panics if a send is currently in progress. To ensure that no
|
||||
/// send is in progress, call `poll_send_done` first until it returns
|
||||
/// `Poll::Ready`.
|
||||
///
|
||||
/// If this method returns an error, that indicates that the channel is
|
||||
/// closed. Note that this method is not guaranteed to return an error if
|
||||
/// the channel is closed, but in that case the error would be reported by
|
||||
/// the first call to `poll_send_done`.
|
||||
pub fn start_send(&mut self, value: T) -> Result<(), SendError<T>> {
|
||||
if self.is_sending {
|
||||
panic!("start_send called while not ready.");
|
||||
}
|
||||
match self.sender.clone() {
|
||||
Some(sender) => {
|
||||
self.inner.set(make_future(Some((sender, value))));
|
||||
self.is_sending = true;
|
||||
Ok(())
|
||||
}
|
||||
None => Err(SendError(value)),
|
||||
}
|
||||
}
|
||||
|
||||
/// If a send is in progress, poll for its completion. If no send is in progress,
|
||||
/// this method returns `Poll::Ready(Ok(()))`.
|
||||
///
|
||||
/// This method can return the following values:
|
||||
///
|
||||
/// - `Poll::Ready(Ok(()))` if the in-progress send has been completed, or there is
|
||||
/// no send in progress (even if the channel is closed).
|
||||
/// - `Poll::Ready(Err(err))` if the in-progress send failed because the channel has
|
||||
/// been closed.
|
||||
/// - `Poll::Pending` if a send is in progress, but it could not complete now.
|
||||
///
|
||||
/// When this method returns `Poll::Pending`, the current task is scheduled
|
||||
/// to receive a wakeup when the message is sent, or when the entire channel
|
||||
/// is closed (but not if just this sender is closed by
|
||||
/// `close_this_sender`). Note that on multiple calls to `poll_send_done`,
|
||||
/// only the `Waker` from the `Context` passed to the most recent call is
|
||||
/// scheduled to receive a wakeup.
|
||||
///
|
||||
/// If this method returns `Poll::Ready`, then `start_send` is guaranteed to
|
||||
/// not panic.
|
||||
pub fn poll_send_done(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), SendError<T>>> {
|
||||
if !self.is_sending {
|
||||
return Poll::Ready(Ok(()));
|
||||
}
|
||||
|
||||
let result = self.inner.poll(cx);
|
||||
if result.is_ready() {
|
||||
self.is_sending = false;
|
||||
}
|
||||
if let Poll::Ready(Err(_)) = &result {
|
||||
self.sender = None;
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// Check whether the channel is ready to send more messages now.
|
||||
///
|
||||
/// If this method returns `true`, then `start_send` is guaranteed to not
|
||||
/// panic.
|
||||
///
|
||||
/// If the channel is closed, this method returns `true`.
|
||||
pub fn is_ready(&self) -> bool {
|
||||
!self.is_sending
|
||||
}
|
||||
|
||||
/// Check whether the channel has been closed.
|
||||
pub fn is_closed(&self) -> bool {
|
||||
match &self.sender {
|
||||
Some(sender) => sender.is_closed(),
|
||||
None => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Clone the underlying `Sender`.
|
||||
///
|
||||
/// If this method returns `None`, then the channel is closed. (But it is
|
||||
/// not guaranteed to return `None` if the channel is closed.)
|
||||
pub fn clone_inner(&self) -> Option<Sender<T>> {
|
||||
self.sender.as_ref().map(|sender| (&**sender).clone())
|
||||
}
|
||||
|
||||
/// Access the underlying `Sender`.
|
||||
///
|
||||
/// If this method returns `None`, then the channel is closed. (But it is
|
||||
/// not guaranteed to return `None` if the channel is closed.)
|
||||
pub fn inner_ref(&self) -> Option<&Sender<T>> {
|
||||
self.sender.as_deref()
|
||||
}
|
||||
|
||||
// This operation is supported because it is required by the Sink trait.
|
||||
/// Close this sender. No more messages can be sent from this sender.
|
||||
///
|
||||
/// Note that this only closes the channel from the view-point of this
|
||||
/// sender. The channel remains open until all senders have gone away, or
|
||||
/// until the [`Receiver`] closes the channel.
|
||||
///
|
||||
/// If there is a send in progress when this method is called, that send is
|
||||
/// unaffected by this operation, and `poll_send_done` can still be called
|
||||
/// to complete that send.
|
||||
///
|
||||
/// [`Receiver`]: tokio::sync::mpsc::Receiver
|
||||
pub fn close_this_sender(&mut self) {
|
||||
self.sender = None;
|
||||
}
|
||||
|
||||
/// Abort the current in-progress send, if any.
|
||||
///
|
||||
/// Returns `true` if a send was aborted.
|
||||
pub fn abort_send(&mut self) -> bool {
|
||||
if self.is_sending {
|
||||
self.inner.set(make_future(None));
|
||||
self.is_sending = false;
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Clone for PollSender<T> {
|
||||
/// Clones this `PollSender`. The resulting clone will not have any
|
||||
/// in-progress send operations, even if the current `PollSender` does.
|
||||
fn clone(&self) -> PollSender<T> {
|
||||
Self {
|
||||
sender: self.sender.clone(),
|
||||
is_sending: false,
|
||||
inner: ReusableBoxFuture::new(async { unreachable!() }),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Send + 'static> Sink<T> for PollSender<T> {
|
||||
type Error = SendError<T>;
|
||||
|
||||
/// This is equivalent to calling [`poll_send_done`].
|
||||
///
|
||||
/// [`poll_send_done`]: PollSender::poll_send_done
|
||||
fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
||||
Pin::into_inner(self).poll_send_done(cx)
|
||||
}
|
||||
|
||||
/// This is equivalent to calling [`poll_send_done`].
|
||||
///
|
||||
/// [`poll_send_done`]: PollSender::poll_send_done
|
||||
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
||||
Pin::into_inner(self).poll_send_done(cx)
|
||||
}
|
||||
|
||||
/// This is equivalent to calling [`start_send`].
|
||||
///
|
||||
/// [`start_send`]: PollSender::start_send
|
||||
fn start_send(self: Pin<&mut Self>, item: T) -> Result<(), Self::Error> {
|
||||
Pin::into_inner(self).start_send(item)
|
||||
}
|
||||
|
||||
/// This method will first flush the `PollSender`, and then close it by
|
||||
/// calling [`close_this_sender`].
|
||||
///
|
||||
/// If a send fails while flushing because the [`Receiver`] has gone away,
|
||||
/// then this function returns an error. The channel is still successfully
|
||||
/// closed in this situation.
|
||||
///
|
||||
/// [`close_this_sender`]: PollSender::close_this_sender
|
||||
/// [`Receiver`]: tokio::sync::mpsc::Receiver
|
||||
fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
||||
ready!(self.as_mut().poll_flush(cx))?;
|
||||
|
||||
Pin::into_inner(self).close_this_sender();
|
||||
Poll::Ready(Ok(()))
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,7 @@ use std::fmt;
|
||||
use std::pin::Pin;
|
||||
use std::sync::Arc;
|
||||
use std::task::{Context, Poll};
|
||||
use tokio::sync::{AcquireError, OwnedSemaphorePermit, Semaphore};
|
||||
use tokio::sync::{AcquireError, OwnedSemaphorePermit, Semaphore, TryAcquireError};
|
||||
|
||||
use super::ReusableBoxFuture;
|
||||
|
||||
@@ -12,17 +12,15 @@ use super::ReusableBoxFuture;
|
||||
/// [`Semaphore`]: tokio::sync::Semaphore
|
||||
pub struct PollSemaphore {
|
||||
semaphore: Arc<Semaphore>,
|
||||
permit_fut: ReusableBoxFuture<Result<OwnedSemaphorePermit, AcquireError>>,
|
||||
permit_fut: Option<ReusableBoxFuture<Result<OwnedSemaphorePermit, AcquireError>>>,
|
||||
}
|
||||
|
||||
impl PollSemaphore {
|
||||
/// Create a new `PollSemaphore`.
|
||||
pub fn new(semaphore: Arc<Semaphore>) -> Self {
|
||||
let fut = Arc::clone(&semaphore).acquire_owned();
|
||||
|
||||
Self {
|
||||
semaphore,
|
||||
permit_fut: ReusableBoxFuture::new(fut),
|
||||
permit_fut: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -55,15 +53,58 @@ impl PollSemaphore {
|
||||
/// the `Waker` from the `Context` passed to the most recent call is
|
||||
/// scheduled to receive a wakeup.
|
||||
pub fn poll_acquire(&mut self, cx: &mut Context<'_>) -> Poll<Option<OwnedSemaphorePermit>> {
|
||||
match ready!(self.permit_fut.poll(cx)) {
|
||||
Ok(permit) => {
|
||||
let permit_future = match self.permit_fut.as_mut() {
|
||||
Some(fut) => fut,
|
||||
None => {
|
||||
// avoid allocations completely if we can grab a permit immediately
|
||||
match Arc::clone(&self.semaphore).try_acquire_owned() {
|
||||
Ok(permit) => return Poll::Ready(Some(permit)),
|
||||
Err(TryAcquireError::Closed) => return Poll::Ready(None),
|
||||
Err(TryAcquireError::NoPermits) => {}
|
||||
}
|
||||
|
||||
let next_fut = Arc::clone(&self.semaphore).acquire_owned();
|
||||
self.permit_fut.set(next_fut);
|
||||
Poll::Ready(Some(permit))
|
||||
self.permit_fut
|
||||
.get_or_insert(ReusableBoxFuture::new(next_fut))
|
||||
}
|
||||
};
|
||||
|
||||
let result = ready!(permit_future.poll(cx));
|
||||
|
||||
let next_fut = Arc::clone(&self.semaphore).acquire_owned();
|
||||
permit_future.set(next_fut);
|
||||
|
||||
match result {
|
||||
Ok(permit) => Poll::Ready(Some(permit)),
|
||||
Err(_closed) => {
|
||||
self.permit_fut = None;
|
||||
Poll::Ready(None)
|
||||
}
|
||||
Err(_closed) => Poll::Ready(None),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the current number of available permits.
|
||||
///
|
||||
/// This is equivalent to the [`Semaphore::available_permits`] method on the
|
||||
/// `tokio::sync::Semaphore` type.
|
||||
///
|
||||
/// [`Semaphore::available_permits`]: tokio::sync::Semaphore::available_permits
|
||||
pub fn available_permits(&self) -> usize {
|
||||
self.semaphore.available_permits()
|
||||
}
|
||||
|
||||
/// Adds `n` new permits to the semaphore.
|
||||
///
|
||||
/// The maximum number of permits is `usize::MAX >> 3`, and this function
|
||||
/// will panic if the limit is exceeded.
|
||||
///
|
||||
/// This is equivalent to the [`Semaphore::add_permits`] method on the
|
||||
/// `tokio::sync::Semaphore` type.
|
||||
///
|
||||
/// [`Semaphore::add_permits`]: tokio::sync::Semaphore::add_permits
|
||||
pub fn add_permits(&self, n: usize) {
|
||||
self.semaphore.add_permits(n);
|
||||
}
|
||||
}
|
||||
|
||||
impl Stream for PollSemaphore {
|
||||
@@ -87,3 +128,9 @@ impl fmt::Debug for PollSemaphore {
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl AsRef<Semaphore> for PollSemaphore {
|
||||
fn as_ref(&self) -> &Semaphore {
|
||||
&*self.semaphore
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,24 +30,24 @@ use std::task::{self, Poll, Waker};
|
||||
///
|
||||
/// Once delays have been configured, the `DelayQueue` is used via its
|
||||
/// [`Stream`] implementation. [`poll_expired`] is called. If an entry has reached its
|
||||
/// deadline, it is returned. If not, `Poll::Pending` indicating that the
|
||||
/// deadline, it is returned. If not, `Poll::Pending` is returned indicating that the
|
||||
/// current task will be notified once the deadline has been reached.
|
||||
///
|
||||
/// # `Stream` implementation
|
||||
///
|
||||
/// Items are retrieved from the queue via [`DelayQueue::poll_expired`]. If no delays have
|
||||
/// expired, no items are returned. In this case, `Pending` is returned and the
|
||||
/// expired, no items are returned. In this case, `Poll::Pending` is returned and the
|
||||
/// current task is registered to be notified once the next item's delay has
|
||||
/// expired.
|
||||
///
|
||||
/// If no items are in the queue, i.e. `is_empty()` returns `true`, then `poll`
|
||||
/// returns `Ready(None)`. This indicates that the stream has reached an end.
|
||||
/// returns `Poll::Ready(None)`. This indicates that the stream has reached an end.
|
||||
/// However, if a new item is inserted *after*, `poll` will once again start
|
||||
/// returning items or `Pending.
|
||||
/// returning items or `Poll::Pending`.
|
||||
///
|
||||
/// Items are returned ordered by their expirations. Items that are configured
|
||||
/// to expire first will be returned first. There are no ordering guarantees
|
||||
/// for items configured to expire the same instant. Also note that delays are
|
||||
/// for items configured to expire at the same instant. Also note that delays are
|
||||
/// rounded to the closest millisecond.
|
||||
///
|
||||
/// # Implementation
|
||||
@@ -152,7 +152,7 @@ pub struct DelayQueue<T> {
|
||||
waker: Option<Waker>,
|
||||
}
|
||||
|
||||
/// An entry in `DelayQueue` that has expired and removed.
|
||||
/// An entry in `DelayQueue` that has expired and been removed.
|
||||
///
|
||||
/// Values are returned by [`DelayQueue::poll_expired`].
|
||||
///
|
||||
@@ -211,7 +211,7 @@ struct Data<T> {
|
||||
const MAX_ENTRIES: usize = (1 << 30) - 1;
|
||||
|
||||
impl<T> DelayQueue<T> {
|
||||
/// Creates a new, empty, `DelayQueue`
|
||||
/// Creates a new, empty, `DelayQueue`.
|
||||
///
|
||||
/// The queue will not allocate storage until items are inserted into it.
|
||||
///
|
||||
@@ -239,15 +239,15 @@ impl<T> DelayQueue<T> {
|
||||
///
|
||||
/// # #[tokio::main]
|
||||
/// # async fn main() {
|
||||
/// let mut delay_queue = DelayQueue::with_capacity(10);
|
||||
/// let mut delay_queue = DelayQueue::with_capacity(10);
|
||||
///
|
||||
/// // These insertions are done without further allocation
|
||||
/// for i in 0..10 {
|
||||
/// delay_queue.insert(i, Duration::from_secs(i));
|
||||
/// }
|
||||
/// // These insertions are done without further allocation
|
||||
/// for i in 0..10 {
|
||||
/// delay_queue.insert(i, Duration::from_secs(i));
|
||||
/// }
|
||||
///
|
||||
/// // This will make the queue allocate additional storage
|
||||
/// delay_queue.insert(11, Duration::from_secs(11));
|
||||
/// // This will make the queue allocate additional storage
|
||||
/// delay_queue.insert(11, Duration::from_secs(11));
|
||||
/// # }
|
||||
/// ```
|
||||
pub fn with_capacity(capacity: usize) -> DelayQueue<T> {
|
||||
@@ -272,8 +272,8 @@ impl<T> DelayQueue<T> {
|
||||
/// `value` will be returned from [`poll_expired`]. If `when` has already been
|
||||
/// reached, then `value` is immediately made available to poll.
|
||||
///
|
||||
/// The return value represents the insertion and is used at an argument to
|
||||
/// [`remove`] and [`reset`]. Note that [`Key`] is token and is reused once
|
||||
/// The return value represents the insertion and is used as an argument to
|
||||
/// [`remove`] and [`reset`]. Note that [`Key`] is a token and is reused once
|
||||
/// `value` is removed from the queue either by calling [`poll_expired`] after
|
||||
/// `when` is reached or by calling [`remove`]. At this point, the caller
|
||||
/// must take care to not use the returned [`Key`] again as it may reference
|
||||
@@ -295,13 +295,13 @@ impl<T> DelayQueue<T> {
|
||||
///
|
||||
/// # #[tokio::main]
|
||||
/// # async fn main() {
|
||||
/// let mut delay_queue = DelayQueue::new();
|
||||
/// let key = delay_queue.insert_at(
|
||||
/// "foo", Instant::now() + Duration::from_secs(5));
|
||||
/// let mut delay_queue = DelayQueue::new();
|
||||
/// let key = delay_queue.insert_at(
|
||||
/// "foo", Instant::now() + Duration::from_secs(5));
|
||||
///
|
||||
/// // Remove the entry
|
||||
/// let item = delay_queue.remove(&key);
|
||||
/// assert_eq!(*item.get_ref(), "foo");
|
||||
/// // Remove the entry
|
||||
/// let item = delay_queue.remove(&key);
|
||||
/// assert_eq!(*item.get_ref(), "foo");
|
||||
/// # }
|
||||
/// ```
|
||||
///
|
||||
@@ -353,7 +353,7 @@ impl<T> DelayQueue<T> {
|
||||
|
||||
/// Attempts to pull out the next value of the delay queue, registering the
|
||||
/// current task for wakeup if the value is not yet available, and returning
|
||||
/// None if the queue is exhausted.
|
||||
/// `None` if the queue is exhausted.
|
||||
pub fn poll_expired(
|
||||
&mut self,
|
||||
cx: &mut task::Context<'_>,
|
||||
@@ -391,7 +391,7 @@ impl<T> DelayQueue<T> {
|
||||
///
|
||||
/// `value` is stored in the queue until `timeout` duration has
|
||||
/// elapsed after `insert` was called. At that point, `value` will
|
||||
/// be returned from [`poll_expired`]. If `timeout` a Duration of
|
||||
/// be returned from [`poll_expired`]. If `timeout` is a `Duration` of
|
||||
/// zero, then `value` is immediately made available to poll.
|
||||
///
|
||||
/// The return value represents the insertion and is used as an
|
||||
@@ -419,12 +419,12 @@ impl<T> DelayQueue<T> {
|
||||
///
|
||||
/// # #[tokio::main]
|
||||
/// # async fn main() {
|
||||
/// let mut delay_queue = DelayQueue::new();
|
||||
/// let key = delay_queue.insert("foo", Duration::from_secs(5));
|
||||
/// let mut delay_queue = DelayQueue::new();
|
||||
/// let key = delay_queue.insert("foo", Duration::from_secs(5));
|
||||
///
|
||||
/// // Remove the entry
|
||||
/// let item = delay_queue.remove(&key);
|
||||
/// assert_eq!(*item.get_ref(), "foo");
|
||||
/// // Remove the entry
|
||||
/// let item = delay_queue.remove(&key);
|
||||
/// assert_eq!(*item.get_ref(), "foo");
|
||||
/// # }
|
||||
/// ```
|
||||
///
|
||||
@@ -452,11 +452,12 @@ impl<T> DelayQueue<T> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Removes the key fom the expired queue or the timer wheel
|
||||
/// depending on its expiration status
|
||||
/// Removes the key from the expired queue or the timer wheel
|
||||
/// depending on its expiration status.
|
||||
///
|
||||
/// # Panics
|
||||
/// Panics if the key is not contained in the expired queue or the wheel
|
||||
///
|
||||
/// Panics if the key is not contained in the expired queue or the wheel.
|
||||
fn remove_key(&mut self, key: &Key) {
|
||||
use crate::time::wheel::Stack;
|
||||
|
||||
@@ -488,12 +489,12 @@ impl<T> DelayQueue<T> {
|
||||
///
|
||||
/// # #[tokio::main]
|
||||
/// # async fn main() {
|
||||
/// let mut delay_queue = DelayQueue::new();
|
||||
/// let key = delay_queue.insert("foo", Duration::from_secs(5));
|
||||
/// let mut delay_queue = DelayQueue::new();
|
||||
/// let key = delay_queue.insert("foo", Duration::from_secs(5));
|
||||
///
|
||||
/// // Remove the entry
|
||||
/// let item = delay_queue.remove(&key);
|
||||
/// assert_eq!(*item.get_ref(), "foo");
|
||||
/// // Remove the entry
|
||||
/// let item = delay_queue.remove(&key);
|
||||
/// assert_eq!(*item.get_ref(), "foo");
|
||||
/// # }
|
||||
/// ```
|
||||
pub fn remove(&mut self, key: &Key) -> Expired<T> {
|
||||
@@ -531,14 +532,14 @@ impl<T> DelayQueue<T> {
|
||||
///
|
||||
/// # #[tokio::main]
|
||||
/// # async fn main() {
|
||||
/// let mut delay_queue = DelayQueue::new();
|
||||
/// let key = delay_queue.insert("foo", Duration::from_secs(5));
|
||||
/// let mut delay_queue = DelayQueue::new();
|
||||
/// let key = delay_queue.insert("foo", Duration::from_secs(5));
|
||||
///
|
||||
/// // "foo" is scheduled to be returned in 5 seconds
|
||||
/// // "foo" is scheduled to be returned in 5 seconds
|
||||
///
|
||||
/// delay_queue.reset_at(&key, Instant::now() + Duration::from_secs(10));
|
||||
/// delay_queue.reset_at(&key, Instant::now() + Duration::from_secs(10));
|
||||
///
|
||||
/// // "foo" is now scheduled to be returned in 10 seconds
|
||||
/// // "foo" is now scheduled to be returned in 10 seconds
|
||||
/// # }
|
||||
/// ```
|
||||
pub fn reset_at(&mut self, key: &Key, when: Instant) {
|
||||
@@ -559,7 +560,7 @@ impl<T> DelayQueue<T> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the next time poll as determined by the wheel
|
||||
/// Returns the next time to poll as determined by the wheel
|
||||
fn next_deadline(&mut self) -> Option<Instant> {
|
||||
self.wheel
|
||||
.poll_at()
|
||||
@@ -591,14 +592,14 @@ impl<T> DelayQueue<T> {
|
||||
///
|
||||
/// # #[tokio::main]
|
||||
/// # async fn main() {
|
||||
/// let mut delay_queue = DelayQueue::new();
|
||||
/// let key = delay_queue.insert("foo", Duration::from_secs(5));
|
||||
/// let mut delay_queue = DelayQueue::new();
|
||||
/// let key = delay_queue.insert("foo", Duration::from_secs(5));
|
||||
///
|
||||
/// // "foo" is scheduled to be returned in 5 seconds
|
||||
/// // "foo" is scheduled to be returned in 5 seconds
|
||||
///
|
||||
/// delay_queue.reset(&key, Duration::from_secs(10));
|
||||
/// delay_queue.reset(&key, Duration::from_secs(10));
|
||||
///
|
||||
/// // "foo"is now scheduled to be returned in 10 seconds
|
||||
/// // "foo"is now scheduled to be returned in 10 seconds
|
||||
/// # }
|
||||
/// ```
|
||||
pub fn reset(&mut self, key: &Key, timeout: Duration) {
|
||||
@@ -621,15 +622,15 @@ impl<T> DelayQueue<T> {
|
||||
///
|
||||
/// # #[tokio::main]
|
||||
/// # async fn main() {
|
||||
/// let mut delay_queue = DelayQueue::new();
|
||||
/// let mut delay_queue = DelayQueue::new();
|
||||
///
|
||||
/// delay_queue.insert("foo", Duration::from_secs(5));
|
||||
/// delay_queue.insert("foo", Duration::from_secs(5));
|
||||
///
|
||||
/// assert!(!delay_queue.is_empty());
|
||||
/// assert!(!delay_queue.is_empty());
|
||||
///
|
||||
/// delay_queue.clear();
|
||||
/// delay_queue.clear();
|
||||
///
|
||||
/// assert!(delay_queue.is_empty());
|
||||
/// assert!(delay_queue.is_empty());
|
||||
/// # }
|
||||
/// ```
|
||||
pub fn clear(&mut self) {
|
||||
@@ -663,10 +664,10 @@ impl<T> DelayQueue<T> {
|
||||
///
|
||||
/// # #[tokio::main]
|
||||
/// # async fn main() {
|
||||
/// let mut delay_queue: DelayQueue<i32> = DelayQueue::with_capacity(10);
|
||||
/// assert_eq!(delay_queue.len(), 0);
|
||||
/// delay_queue.insert(3, Duration::from_secs(5));
|
||||
/// assert_eq!(delay_queue.len(), 1);
|
||||
/// let mut delay_queue: DelayQueue<i32> = DelayQueue::with_capacity(10);
|
||||
/// assert_eq!(delay_queue.len(), 0);
|
||||
/// delay_queue.insert(3, Duration::from_secs(5));
|
||||
/// assert_eq!(delay_queue.len(), 1);
|
||||
/// # }
|
||||
/// ```
|
||||
pub fn len(&self) -> usize {
|
||||
@@ -698,12 +699,12 @@ impl<T> DelayQueue<T> {
|
||||
///
|
||||
/// # #[tokio::main]
|
||||
/// # async fn main() {
|
||||
/// let mut delay_queue = DelayQueue::new();
|
||||
/// let mut delay_queue = DelayQueue::new();
|
||||
///
|
||||
/// delay_queue.insert("hello", Duration::from_secs(10));
|
||||
/// delay_queue.reserve(10);
|
||||
/// delay_queue.insert("hello", Duration::from_secs(10));
|
||||
/// delay_queue.reserve(10);
|
||||
///
|
||||
/// assert!(delay_queue.capacity() >= 11);
|
||||
/// assert!(delay_queue.capacity() >= 11);
|
||||
/// # }
|
||||
/// ```
|
||||
pub fn reserve(&mut self, additional: usize) {
|
||||
@@ -713,7 +714,7 @@ impl<T> DelayQueue<T> {
|
||||
/// Returns `true` if there are no items in the queue.
|
||||
///
|
||||
/// Note that this function returns `false` even if all items have not yet
|
||||
/// expired and a call to `poll` will return `Pending`.
|
||||
/// expired and a call to `poll` will return `Poll::Pending`.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
@@ -723,11 +724,11 @@ impl<T> DelayQueue<T> {
|
||||
///
|
||||
/// # #[tokio::main]
|
||||
/// # async fn main() {
|
||||
/// let mut delay_queue = DelayQueue::new();
|
||||
/// assert!(delay_queue.is_empty());
|
||||
/// let mut delay_queue = DelayQueue::new();
|
||||
/// assert!(delay_queue.is_empty());
|
||||
///
|
||||
/// delay_queue.insert("hello", Duration::from_secs(5));
|
||||
/// assert!(!delay_queue.is_empty());
|
||||
/// delay_queue.insert("hello", Duration::from_secs(5));
|
||||
/// assert!(!delay_queue.is_empty());
|
||||
/// # }
|
||||
/// ```
|
||||
pub fn is_empty(&self) -> bool {
|
||||
|
||||
+35
-20
@@ -6,9 +6,12 @@ use tokio::{io::ReadBuf, net::UdpSocket};
|
||||
use bytes::{BufMut, BytesMut};
|
||||
use futures_core::ready;
|
||||
use futures_sink::Sink;
|
||||
use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4};
|
||||
use std::pin::Pin;
|
||||
use std::task::{Context, Poll};
|
||||
use std::{
|
||||
borrow::Borrow,
|
||||
net::{Ipv4Addr, SocketAddr, SocketAddrV4},
|
||||
};
|
||||
use std::{io, mem::MaybeUninit};
|
||||
|
||||
/// A unified [`Stream`] and [`Sink`] interface to an underlying `UdpSocket`, using
|
||||
@@ -32,10 +35,10 @@ use std::{io, mem::MaybeUninit};
|
||||
/// [`Sink`]: futures_sink::Sink
|
||||
/// [`split`]: https://docs.rs/futures/0.3/futures/stream/trait.StreamExt.html#method.split
|
||||
#[must_use = "sinks do nothing unless polled"]
|
||||
#[cfg_attr(docsrs, doc(all(feature = "codec", feature = "udp")))]
|
||||
#[cfg_attr(docsrs, doc(cfg(all(feature = "codec", feature = "udp"))))]
|
||||
#[derive(Debug)]
|
||||
pub struct UdpFramed<C> {
|
||||
socket: UdpSocket,
|
||||
pub struct UdpFramed<C, T = UdpSocket> {
|
||||
socket: T,
|
||||
codec: C,
|
||||
rd: BytesMut,
|
||||
wr: BytesMut,
|
||||
@@ -48,7 +51,13 @@ pub struct UdpFramed<C> {
|
||||
const INITIAL_RD_CAPACITY: usize = 64 * 1024;
|
||||
const INITIAL_WR_CAPACITY: usize = 8 * 1024;
|
||||
|
||||
impl<C: Decoder + Unpin> Stream for UdpFramed<C> {
|
||||
impl<C, T> Unpin for UdpFramed<C, T> {}
|
||||
|
||||
impl<C, T> Stream for UdpFramed<C, T>
|
||||
where
|
||||
T: Borrow<UdpSocket>,
|
||||
C: Decoder,
|
||||
{
|
||||
type Item = Result<(C::Item, SocketAddr), C::Error>;
|
||||
|
||||
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
|
||||
@@ -79,7 +88,7 @@ impl<C: Decoder + Unpin> Stream for UdpFramed<C> {
|
||||
let buf = &mut *(pin.rd.chunk_mut() as *mut _ as *mut [MaybeUninit<u8>]);
|
||||
let mut read = ReadBuf::uninit(buf);
|
||||
let ptr = read.filled().as_ptr();
|
||||
let res = ready!(Pin::new(&mut pin.socket).poll_recv_from(cx, &mut read));
|
||||
let res = ready!(pin.socket.borrow().poll_recv_from(cx, &mut read));
|
||||
|
||||
assert_eq!(ptr, read.filled().as_ptr());
|
||||
let addr = res?;
|
||||
@@ -93,7 +102,11 @@ impl<C: Decoder + Unpin> Stream for UdpFramed<C> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<I, C: Encoder<I> + Unpin> Sink<(I, SocketAddr)> for UdpFramed<C> {
|
||||
impl<I, C, T> Sink<(I, SocketAddr)> for UdpFramed<C, T>
|
||||
where
|
||||
T: Borrow<UdpSocket>,
|
||||
C: Encoder<I>,
|
||||
{
|
||||
type Error = C::Error;
|
||||
|
||||
fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
||||
@@ -125,13 +138,13 @@ impl<I, C: Encoder<I> + Unpin> Sink<(I, SocketAddr)> for UdpFramed<C> {
|
||||
}
|
||||
|
||||
let Self {
|
||||
ref mut socket,
|
||||
ref socket,
|
||||
ref mut out_addr,
|
||||
ref mut wr,
|
||||
..
|
||||
} = *self;
|
||||
|
||||
let n = ready!(socket.poll_send_to(cx, &wr, *out_addr))?;
|
||||
let n = ready!(socket.borrow().poll_send_to(cx, &wr, *out_addr))?;
|
||||
|
||||
let wrote_all = n == self.wr.len();
|
||||
self.wr.clear();
|
||||
@@ -156,11 +169,14 @@ impl<I, C: Encoder<I> + Unpin> Sink<(I, SocketAddr)> for UdpFramed<C> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<C> UdpFramed<C> {
|
||||
impl<C, T> UdpFramed<C, T>
|
||||
where
|
||||
T: Borrow<UdpSocket>,
|
||||
{
|
||||
/// Create a new `UdpFramed` backed by the given socket and codec.
|
||||
///
|
||||
/// See struct level documentation for more details.
|
||||
pub fn new(socket: UdpSocket, codec: C) -> UdpFramed<C> {
|
||||
pub fn new(socket: T, codec: C) -> UdpFramed<C, T> {
|
||||
Self {
|
||||
socket,
|
||||
codec,
|
||||
@@ -180,27 +196,21 @@ impl<C> UdpFramed<C> {
|
||||
/// Care should be taken to not tamper with the underlying stream of data
|
||||
/// coming in as it may corrupt the stream of frames otherwise being worked
|
||||
/// with.
|
||||
pub fn get_ref(&self) -> &UdpSocket {
|
||||
pub fn get_ref(&self) -> &T {
|
||||
&self.socket
|
||||
}
|
||||
|
||||
/// Returns a mutable reference to the underlying I/O stream wrapped by
|
||||
/// `Framed`.
|
||||
/// Returns a mutable reference to the underlying I/O stream wrapped by `Framed`.
|
||||
///
|
||||
/// # Note
|
||||
///
|
||||
/// Care should be taken to not tamper with the underlying stream of data
|
||||
/// coming in as it may corrupt the stream of frames otherwise being worked
|
||||
/// with.
|
||||
pub fn get_mut(&mut self) -> &mut UdpSocket {
|
||||
pub fn get_mut(&mut self) -> &mut T {
|
||||
&mut self.socket
|
||||
}
|
||||
|
||||
/// Consumes the `Framed`, returning its underlying I/O stream.
|
||||
pub fn into_inner(self) -> UdpSocket {
|
||||
self.socket
|
||||
}
|
||||
|
||||
/// Returns a reference to the underlying codec wrapped by
|
||||
/// `Framed`.
|
||||
///
|
||||
@@ -228,4 +238,9 @@ impl<C> UdpFramed<C> {
|
||||
pub fn read_buffer_mut(&mut self) -> &mut BytesMut {
|
||||
&mut self.rd
|
||||
}
|
||||
|
||||
/// Consumes the `Framed`, returning its underlying I/O stream.
|
||||
pub fn into_inner(self) -> T {
|
||||
self.socket
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
#![cfg(not(feature = "full"))]
|
||||
compile_error!("run tokio-util tests with `--features full`");
|
||||
+245
-1
@@ -1,6 +1,6 @@
|
||||
#![warn(rust_2018_idioms)]
|
||||
|
||||
use tokio_util::codec::{BytesCodec, Decoder, Encoder, LinesCodec};
|
||||
use tokio_util::codec::{AnyDelimiterCodec, BytesCodec, Decoder, Encoder, LinesCodec};
|
||||
|
||||
use bytes::{BufMut, Bytes, BytesMut};
|
||||
|
||||
@@ -201,7 +201,26 @@ fn lines_decoder_discard_repeat() {
|
||||
buf.put_slice(b"aa");
|
||||
assert!(codec.decode(buf).is_err());
|
||||
buf.put_slice(b"a");
|
||||
assert_eq!(None, codec.decode(buf).unwrap());
|
||||
}
|
||||
|
||||
// Regression test for [subsequent calls to LinesCodec decode does not return the desired results bug](https://github.com/tokio-rs/tokio/issues/3555)
|
||||
#[test]
|
||||
fn lines_decoder_max_length_underrun_twice() {
|
||||
const MAX_LENGTH: usize = 11;
|
||||
|
||||
let mut codec = LinesCodec::new_with_max_length(MAX_LENGTH);
|
||||
let buf = &mut BytesMut::new();
|
||||
|
||||
buf.reserve(200);
|
||||
buf.put_slice(b"line ");
|
||||
assert_eq!(None, codec.decode(buf).unwrap());
|
||||
buf.put_slice(b"too very l");
|
||||
assert!(codec.decode(buf).is_err());
|
||||
buf.put_slice(b"aaaaaaaaaaaaaaaaaaaaaaa");
|
||||
assert_eq!(None, codec.decode(buf).unwrap());
|
||||
buf.put_slice(b"ong\nshort\n");
|
||||
assert_eq!("short", codec.decode(buf).unwrap().unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -215,3 +234,228 @@ fn lines_encoder() {
|
||||
codec.encode("line 2", &mut buf).unwrap();
|
||||
assert_eq!("line 1\nline 2\n", buf);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn any_delimiters_decoder_any_character() {
|
||||
let mut codec = AnyDelimiterCodec::new(b",;\n\r".to_vec(), b",".to_vec());
|
||||
let buf = &mut BytesMut::new();
|
||||
buf.reserve(200);
|
||||
buf.put_slice(b"chunk 1,chunk 2;chunk 3\n\r");
|
||||
assert_eq!("chunk 1", codec.decode(buf).unwrap().unwrap());
|
||||
assert_eq!("chunk 2", codec.decode(buf).unwrap().unwrap());
|
||||
assert_eq!("chunk 3", codec.decode(buf).unwrap().unwrap());
|
||||
assert_eq!("", codec.decode(buf).unwrap().unwrap());
|
||||
assert_eq!(None, codec.decode(buf).unwrap());
|
||||
assert_eq!(None, codec.decode_eof(buf).unwrap());
|
||||
buf.put_slice(b"k");
|
||||
assert_eq!(None, codec.decode(buf).unwrap());
|
||||
assert_eq!("k", codec.decode_eof(buf).unwrap().unwrap());
|
||||
assert_eq!(None, codec.decode(buf).unwrap());
|
||||
assert_eq!(None, codec.decode_eof(buf).unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn any_delimiters_decoder_max_length() {
|
||||
const MAX_LENGTH: usize = 7;
|
||||
|
||||
let mut codec =
|
||||
AnyDelimiterCodec::new_with_max_length(b",;\n\r".to_vec(), b",".to_vec(), MAX_LENGTH);
|
||||
let buf = &mut BytesMut::new();
|
||||
|
||||
buf.reserve(200);
|
||||
buf.put_slice(b"chunk 1 is too long\nchunk 2\nchunk 3\r\nchunk 4\n\r\n");
|
||||
|
||||
assert!(codec.decode(buf).is_err());
|
||||
|
||||
let chunk = codec.decode(buf).unwrap().unwrap();
|
||||
assert!(
|
||||
chunk.len() <= MAX_LENGTH,
|
||||
"{:?}.len() <= {:?}",
|
||||
chunk,
|
||||
MAX_LENGTH
|
||||
);
|
||||
assert_eq!("chunk 2", chunk);
|
||||
|
||||
let chunk = codec.decode(buf).unwrap().unwrap();
|
||||
assert!(
|
||||
chunk.len() <= MAX_LENGTH,
|
||||
"{:?}.len() <= {:?}",
|
||||
chunk,
|
||||
MAX_LENGTH
|
||||
);
|
||||
assert_eq!("chunk 3", chunk);
|
||||
|
||||
// \r\n cause empty chunk
|
||||
let chunk = codec.decode(buf).unwrap().unwrap();
|
||||
assert!(
|
||||
chunk.len() <= MAX_LENGTH,
|
||||
"{:?}.len() <= {:?}",
|
||||
chunk,
|
||||
MAX_LENGTH
|
||||
);
|
||||
assert_eq!("", chunk);
|
||||
|
||||
let chunk = codec.decode(buf).unwrap().unwrap();
|
||||
assert!(
|
||||
chunk.len() <= MAX_LENGTH,
|
||||
"{:?}.len() <= {:?}",
|
||||
chunk,
|
||||
MAX_LENGTH
|
||||
);
|
||||
assert_eq!("chunk 4", chunk);
|
||||
|
||||
let chunk = codec.decode(buf).unwrap().unwrap();
|
||||
assert!(
|
||||
chunk.len() <= MAX_LENGTH,
|
||||
"{:?}.len() <= {:?}",
|
||||
chunk,
|
||||
MAX_LENGTH
|
||||
);
|
||||
assert_eq!("", chunk);
|
||||
|
||||
let chunk = codec.decode(buf).unwrap().unwrap();
|
||||
assert!(
|
||||
chunk.len() <= MAX_LENGTH,
|
||||
"{:?}.len() <= {:?}",
|
||||
chunk,
|
||||
MAX_LENGTH
|
||||
);
|
||||
assert_eq!("", chunk);
|
||||
|
||||
assert_eq!(None, codec.decode(buf).unwrap());
|
||||
assert_eq!(None, codec.decode_eof(buf).unwrap());
|
||||
buf.put_slice(b"k");
|
||||
assert_eq!(None, codec.decode(buf).unwrap());
|
||||
|
||||
let chunk = codec.decode_eof(buf).unwrap().unwrap();
|
||||
assert!(
|
||||
chunk.len() <= MAX_LENGTH,
|
||||
"{:?}.len() <= {:?}",
|
||||
chunk,
|
||||
MAX_LENGTH
|
||||
);
|
||||
assert_eq!("k", chunk);
|
||||
|
||||
assert_eq!(None, codec.decode(buf).unwrap());
|
||||
assert_eq!(None, codec.decode_eof(buf).unwrap());
|
||||
|
||||
// Delimiter that's one character too long. This could cause an out of bounds
|
||||
// error if we peek at the next characters using slice indexing.
|
||||
buf.put_slice(b"aaabbbcc");
|
||||
assert!(codec.decode(buf).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn any_delimiter_decoder_max_length_underrun() {
|
||||
const MAX_LENGTH: usize = 7;
|
||||
|
||||
let mut codec =
|
||||
AnyDelimiterCodec::new_with_max_length(b",;\n\r".to_vec(), b",".to_vec(), MAX_LENGTH);
|
||||
let buf = &mut BytesMut::new();
|
||||
|
||||
buf.reserve(200);
|
||||
buf.put_slice(b"chunk ");
|
||||
assert_eq!(None, codec.decode(buf).unwrap());
|
||||
buf.put_slice(b"too l");
|
||||
assert!(codec.decode(buf).is_err());
|
||||
buf.put_slice(b"ong\n");
|
||||
assert_eq!(None, codec.decode(buf).unwrap());
|
||||
|
||||
buf.put_slice(b"chunk 2");
|
||||
assert_eq!(None, codec.decode(buf).unwrap());
|
||||
buf.put_slice(b",");
|
||||
assert_eq!("chunk 2", codec.decode(buf).unwrap().unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn any_delimiter_decoder_max_length_underrun_twice() {
|
||||
const MAX_LENGTH: usize = 11;
|
||||
|
||||
let mut codec =
|
||||
AnyDelimiterCodec::new_with_max_length(b",;\n\r".to_vec(), b",".to_vec(), MAX_LENGTH);
|
||||
let buf = &mut BytesMut::new();
|
||||
|
||||
buf.reserve(200);
|
||||
buf.put_slice(b"chunk ");
|
||||
assert_eq!(None, codec.decode(buf).unwrap());
|
||||
buf.put_slice(b"too very l");
|
||||
assert!(codec.decode(buf).is_err());
|
||||
buf.put_slice(b"aaaaaaaaaaaaaaaaaaaaaaa");
|
||||
assert_eq!(None, codec.decode(buf).unwrap());
|
||||
buf.put_slice(b"ong\nshort\n");
|
||||
assert_eq!("short", codec.decode(buf).unwrap().unwrap());
|
||||
}
|
||||
#[test]
|
||||
fn any_delimiter_decoder_max_length_bursts() {
|
||||
const MAX_LENGTH: usize = 11;
|
||||
|
||||
let mut codec =
|
||||
AnyDelimiterCodec::new_with_max_length(b",;\n\r".to_vec(), b",".to_vec(), MAX_LENGTH);
|
||||
let buf = &mut BytesMut::new();
|
||||
|
||||
buf.reserve(200);
|
||||
buf.put_slice(b"chunk ");
|
||||
assert_eq!(None, codec.decode(buf).unwrap());
|
||||
buf.put_slice(b"too l");
|
||||
assert_eq!(None, codec.decode(buf).unwrap());
|
||||
buf.put_slice(b"ong\n");
|
||||
assert!(codec.decode(buf).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn any_delimiter_decoder_max_length_big_burst() {
|
||||
const MAX_LENGTH: usize = 11;
|
||||
|
||||
let mut codec =
|
||||
AnyDelimiterCodec::new_with_max_length(b",;\n\r".to_vec(), b",".to_vec(), MAX_LENGTH);
|
||||
let buf = &mut BytesMut::new();
|
||||
|
||||
buf.reserve(200);
|
||||
buf.put_slice(b"chunk ");
|
||||
assert_eq!(None, codec.decode(buf).unwrap());
|
||||
buf.put_slice(b"too long!\n");
|
||||
assert!(codec.decode(buf).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn any_delimiter_decoder_max_length_delimiter_between_decodes() {
|
||||
const MAX_LENGTH: usize = 5;
|
||||
|
||||
let mut codec =
|
||||
AnyDelimiterCodec::new_with_max_length(b",;\n\r".to_vec(), b",".to_vec(), MAX_LENGTH);
|
||||
let buf = &mut BytesMut::new();
|
||||
|
||||
buf.reserve(200);
|
||||
buf.put_slice(b"hello");
|
||||
assert_eq!(None, codec.decode(buf).unwrap());
|
||||
|
||||
buf.put_slice(b",world");
|
||||
assert_eq!("hello", codec.decode(buf).unwrap().unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn any_delimiter_decoder_discard_repeat() {
|
||||
const MAX_LENGTH: usize = 1;
|
||||
|
||||
let mut codec =
|
||||
AnyDelimiterCodec::new_with_max_length(b",;\n\r".to_vec(), b",".to_vec(), MAX_LENGTH);
|
||||
let buf = &mut BytesMut::new();
|
||||
|
||||
buf.reserve(200);
|
||||
buf.put_slice(b"aa");
|
||||
assert!(codec.decode(buf).is_err());
|
||||
buf.put_slice(b"a");
|
||||
assert_eq!(None, codec.decode(buf).unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn any_delimiter_encoder() {
|
||||
let mut codec = AnyDelimiterCodec::new(b",".to_vec(), b";--;".to_vec());
|
||||
let mut buf = BytesMut::new();
|
||||
|
||||
codec.encode("chunk 1", &mut buf).unwrap();
|
||||
assert_eq!("chunk 1;--;", buf);
|
||||
|
||||
codec.encode("chunk 2", &mut buf).unwrap();
|
||||
assert_eq!("chunk 1;--;chunk 2;--;", buf);
|
||||
}
|
||||
|
||||
@@ -254,6 +254,29 @@ fn multi_frames_on_eof() {
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_eof_then_resume() {
|
||||
let mut task = task::spawn(());
|
||||
let mock = mock! {
|
||||
Ok(b"\x00\x00\x00\x01".to_vec()),
|
||||
Ok(b"".to_vec()),
|
||||
Ok(b"\x00\x00\x00\x02".to_vec()),
|
||||
Ok(b"".to_vec()),
|
||||
Ok(b"\x00\x00\x00\x03".to_vec()),
|
||||
};
|
||||
let mut framed = FramedRead::new(mock, U32Decoder);
|
||||
|
||||
task.enter(|cx, _| {
|
||||
assert_read!(pin!(framed).poll_next(cx), 1);
|
||||
assert!(assert_ready!(pin!(framed).poll_next(cx)).is_none());
|
||||
assert_read!(pin!(framed).poll_next(cx), 2);
|
||||
assert!(assert_ready!(pin!(framed).poll_next(cx)).is_none());
|
||||
assert_read!(pin!(framed).poll_next(cx), 3);
|
||||
assert!(assert_ready!(pin!(framed).poll_next(cx)).is_none());
|
||||
assert!(assert_ready!(pin!(framed).poll_next(cx)).is_none());
|
||||
});
|
||||
}
|
||||
|
||||
// ===== Mock ======
|
||||
|
||||
struct Mock {
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
use futures::future::poll_fn;
|
||||
use tokio::sync::mpsc::channel;
|
||||
use tokio_test::task::spawn;
|
||||
use tokio_test::{assert_pending, assert_ready, assert_ready_err, assert_ready_ok};
|
||||
use tokio_util::sync::PollSender;
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_simple() {
|
||||
let (send, mut recv) = channel(3);
|
||||
let mut send = PollSender::new(send);
|
||||
|
||||
for i in 1..=3i32 {
|
||||
send.start_send(i).unwrap();
|
||||
assert_ready_ok!(spawn(poll_fn(|cx| send.poll_send_done(cx))).poll());
|
||||
}
|
||||
|
||||
send.start_send(4).unwrap();
|
||||
let mut fourth_send = spawn(poll_fn(|cx| send.poll_send_done(cx)));
|
||||
assert_pending!(fourth_send.poll());
|
||||
assert_eq!(recv.recv().await.unwrap(), 1);
|
||||
assert!(fourth_send.is_woken());
|
||||
assert_ready_ok!(fourth_send.poll());
|
||||
|
||||
drop(recv);
|
||||
|
||||
// Here, start_send is not guaranteed to fail, but if it doesn't the first
|
||||
// call to poll_send_done should.
|
||||
if send.start_send(5).is_ok() {
|
||||
assert_ready_err!(spawn(poll_fn(|cx| send.poll_send_done(cx))).poll());
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_abort() {
|
||||
let (send, mut recv) = channel(3);
|
||||
let mut send = PollSender::new(send);
|
||||
let send2 = send.clone_inner().unwrap();
|
||||
|
||||
for i in 1..=3i32 {
|
||||
send.start_send(i).unwrap();
|
||||
assert_ready_ok!(spawn(poll_fn(|cx| send.poll_send_done(cx))).poll());
|
||||
}
|
||||
|
||||
send.start_send(4).unwrap();
|
||||
{
|
||||
let mut fourth_send = spawn(poll_fn(|cx| send.poll_send_done(cx)));
|
||||
assert_pending!(fourth_send.poll());
|
||||
assert_eq!(recv.recv().await.unwrap(), 1);
|
||||
assert!(fourth_send.is_woken());
|
||||
}
|
||||
|
||||
let mut send2_send = spawn(send2.send(5));
|
||||
assert_pending!(send2_send.poll());
|
||||
send.abort_send();
|
||||
assert!(send2_send.is_woken());
|
||||
assert_ready_ok!(send2_send.poll());
|
||||
|
||||
assert_eq!(recv.recv().await.unwrap(), 2);
|
||||
assert_eq!(recv.recv().await.unwrap(), 3);
|
||||
assert_eq!(recv.recv().await.unwrap(), 5);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn close_sender_last() {
|
||||
let (send, mut recv) = channel::<i32>(3);
|
||||
let mut send = PollSender::new(send);
|
||||
|
||||
let mut recv_task = spawn(recv.recv());
|
||||
assert_pending!(recv_task.poll());
|
||||
|
||||
send.close_this_sender();
|
||||
|
||||
assert!(recv_task.is_woken());
|
||||
assert!(assert_ready!(recv_task.poll()).is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn close_sender_not_last() {
|
||||
let (send, mut recv) = channel::<i32>(3);
|
||||
let send2 = send.clone();
|
||||
let mut send = PollSender::new(send);
|
||||
|
||||
let mut recv_task = spawn(recv.recv());
|
||||
assert_pending!(recv_task.poll());
|
||||
|
||||
send.close_this_sender();
|
||||
|
||||
assert!(!recv_task.is_woken());
|
||||
assert_pending!(recv_task.poll());
|
||||
|
||||
drop(send2);
|
||||
|
||||
assert!(recv_task.is_woken());
|
||||
assert!(assert_ready!(recv_task.poll()).is_none());
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
use std::future::Future;
|
||||
use std::sync::Arc;
|
||||
use std::task::Poll;
|
||||
use tokio::sync::{OwnedSemaphorePermit, Semaphore};
|
||||
use tokio_util::sync::PollSemaphore;
|
||||
|
||||
type SemRet = Option<OwnedSemaphorePermit>;
|
||||
|
||||
fn semaphore_poll<'a>(
|
||||
sem: &'a mut PollSemaphore,
|
||||
) -> tokio_test::task::Spawn<impl Future<Output = SemRet> + 'a> {
|
||||
let fut = futures::future::poll_fn(move |cx| sem.poll_acquire(cx));
|
||||
tokio_test::task::spawn(fut)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn it_works() {
|
||||
let sem = Arc::new(Semaphore::new(1));
|
||||
let mut poll_sem = PollSemaphore::new(sem.clone());
|
||||
|
||||
let permit = sem.acquire().await.unwrap();
|
||||
let mut poll = semaphore_poll(&mut poll_sem);
|
||||
assert!(poll.poll().is_pending());
|
||||
drop(permit);
|
||||
|
||||
assert!(matches!(poll.poll(), Poll::Ready(Some(_))));
|
||||
drop(poll);
|
||||
|
||||
sem.close();
|
||||
|
||||
assert!(semaphore_poll(&mut poll_sem).await.is_none());
|
||||
|
||||
// Check that it is fused.
|
||||
assert!(semaphore_poll(&mut poll_sem).await.is_none());
|
||||
assert!(semaphore_poll(&mut poll_sem).await.is_none());
|
||||
}
|
||||
@@ -10,6 +10,7 @@ use futures::future::try_join;
|
||||
use futures::future::FutureExt;
|
||||
use futures::sink::SinkExt;
|
||||
use std::io;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[cfg_attr(any(target_os = "macos", target_os = "ios"), allow(unused_assignments))]
|
||||
#[tokio::test]
|
||||
@@ -101,3 +102,31 @@ async fn send_framed_lines_codec() -> std::io::Result<()> {
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn framed_half() -> std::io::Result<()> {
|
||||
let a_soc = Arc::new(UdpSocket::bind("127.0.0.1:0").await?);
|
||||
let b_soc = a_soc.clone();
|
||||
|
||||
let a_addr = a_soc.local_addr()?;
|
||||
let b_addr = b_soc.local_addr()?;
|
||||
|
||||
let mut a = UdpFramed::new(a_soc, ByteCodec);
|
||||
let mut b = UdpFramed::new(b_soc, LinesCodec::new());
|
||||
|
||||
let msg = b"1\r\n2\r\n3\r\n".to_vec();
|
||||
a.send((&msg, b_addr)).await?;
|
||||
|
||||
let msg = b"4\r\n5\r\n6\r\n".to_vec();
|
||||
a.send((&msg, b_addr)).await?;
|
||||
|
||||
assert_eq!(b.next().await.unwrap().unwrap(), ("1".to_string(), a_addr));
|
||||
assert_eq!(b.next().await.unwrap().unwrap(), ("2".to_string(), a_addr));
|
||||
assert_eq!(b.next().await.unwrap().unwrap(), ("3".to_string(), a_addr));
|
||||
|
||||
assert_eq!(b.next().await.unwrap().unwrap(), ("4".to_string(), a_addr));
|
||||
assert_eq!(b.next().await.unwrap().unwrap(), ("5".to_string(), a_addr));
|
||||
assert_eq!(b.next().await.unwrap().unwrap(), ("6".to_string(), a_addr));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1,3 +1,196 @@
|
||||
# 1.6.2 (June 14, 2021)
|
||||
|
||||
### Fixes
|
||||
|
||||
- test: sub-ms `time:advance` regression introduced in 1.6 ([#3852])
|
||||
|
||||
[#3852]: https://github.com/tokio-rs/tokio/pull/3852
|
||||
|
||||
# 1.6.1 (May 28, 2021)
|
||||
|
||||
This release reverts [#3518] because it doesn't work on some kernels due to
|
||||
a kernel bug. ([#3803])
|
||||
|
||||
[#3518]: https://github.com/tokio-rs/tokio/issues/3518
|
||||
[#3803]: https://github.com/tokio-rs/tokio/issues/3803
|
||||
|
||||
# 1.6.0 (May 14, 2021)
|
||||
|
||||
### Added
|
||||
|
||||
- fs: try doing a non-blocking read before punting to the threadpool ([#3518])
|
||||
- io: add `write_all_buf` to `AsyncWriteExt` ([#3737])
|
||||
- io: implement `AsyncSeek` for `BufReader`, `BufWriter`, and `BufStream` ([#3491])
|
||||
- net: support non-blocking vectored I/O ([#3761])
|
||||
- sync: add `mpsc::Sender::{reserve_owned, try_reserve_owned}` ([#3704])
|
||||
- sync: add a `MutexGuard::map` method that returns a `MappedMutexGuard` ([#2472])
|
||||
- time: add getter for Interval's period ([#3705])
|
||||
|
||||
### Fixed
|
||||
|
||||
- io: wake pending writers on `DuplexStream` close ([#3756])
|
||||
- process: avoid redundant effort to reap orphan processes ([#3743])
|
||||
- signal: use `std::os::raw::c_int` instead of `libc::c_int` on public API ([#3774])
|
||||
- sync: preserve permit state in `notify_waiters` ([#3660])
|
||||
- task: update `JoinHandle` panic message ([#3727])
|
||||
- time: prevent `time::advance` from going too far ([#3712])
|
||||
|
||||
### Documented
|
||||
|
||||
- net: hide `net::unix::datagram` module from docs ([#3775])
|
||||
- process: updated example ([#3748])
|
||||
- sync: `Barrier` doc should use task, not thread ([#3780])
|
||||
- task: update documentation on `block_in_place` ([#3753])
|
||||
|
||||
[#2472]: https://github.com/tokio-rs/tokio/pull/2472
|
||||
[#3491]: https://github.com/tokio-rs/tokio/pull/3491
|
||||
[#3518]: https://github.com/tokio-rs/tokio/pull/3518
|
||||
[#3660]: https://github.com/tokio-rs/tokio/pull/3660
|
||||
[#3704]: https://github.com/tokio-rs/tokio/pull/3704
|
||||
[#3705]: https://github.com/tokio-rs/tokio/pull/3705
|
||||
[#3712]: https://github.com/tokio-rs/tokio/pull/3712
|
||||
[#3727]: https://github.com/tokio-rs/tokio/pull/3727
|
||||
[#3737]: https://github.com/tokio-rs/tokio/pull/3737
|
||||
[#3743]: https://github.com/tokio-rs/tokio/pull/3743
|
||||
[#3748]: https://github.com/tokio-rs/tokio/pull/3748
|
||||
[#3753]: https://github.com/tokio-rs/tokio/pull/3753
|
||||
[#3756]: https://github.com/tokio-rs/tokio/pull/3756
|
||||
[#3761]: https://github.com/tokio-rs/tokio/pull/3761
|
||||
[#3774]: https://github.com/tokio-rs/tokio/pull/3774
|
||||
[#3775]: https://github.com/tokio-rs/tokio/pull/3775
|
||||
[#3780]: https://github.com/tokio-rs/tokio/pull/3780
|
||||
|
||||
# 1.5.0 (April 12, 2021)
|
||||
|
||||
### Added
|
||||
|
||||
- io: add `AsyncSeekExt::stream_position` ([#3650])
|
||||
- io: add `AsyncWriteExt::write_vectored` ([#3678])
|
||||
- io: add a `copy_bidirectional` utility ([#3572])
|
||||
- net: implement `IntoRawFd` for `TcpSocket` ([#3684])
|
||||
- sync: add `OnceCell` ([#3591])
|
||||
- sync: add `OwnedRwLockReadGuard` and `OwnedRwLockWriteGuard` ([#3340])
|
||||
- sync: add `Semaphore::is_closed` ([#3673])
|
||||
- sync: add `mpsc::Sender::capacity` ([#3690])
|
||||
- sync: allow configuring `RwLock` max reads ([#3644])
|
||||
- task: add `sync_scope` for `LocalKey` ([#3612])
|
||||
|
||||
### Fixed
|
||||
|
||||
- chore: try to avoid `noalias` attributes on intrusive linked list ([#3654])
|
||||
- rt: fix panic in `JoinHandle::abort()` when called from other threads ([#3672])
|
||||
- sync: don't panic in `oneshot::try_recv` ([#3674])
|
||||
- sync: fix notifications getting dropped on receiver drop ([#3652])
|
||||
- sync: fix `Semaphore` permit overflow calculation ([#3644])
|
||||
|
||||
### Documented
|
||||
|
||||
- io: clarify requirements of `AsyncFd` ([#3635])
|
||||
- runtime: fix unclear docs for `{Handle,Runtime}::block_on` ([#3628])
|
||||
- sync: document that `Semaphore` is fair ([#3693])
|
||||
- sync: improve doc on blocking mutex ([#3645])
|
||||
|
||||
[#3340]: https://github.com/tokio-rs/tokio/pull/3340
|
||||
[#3572]: https://github.com/tokio-rs/tokio/pull/3572
|
||||
[#3591]: https://github.com/tokio-rs/tokio/pull/3591
|
||||
[#3612]: https://github.com/tokio-rs/tokio/pull/3612
|
||||
[#3628]: https://github.com/tokio-rs/tokio/pull/3628
|
||||
[#3635]: https://github.com/tokio-rs/tokio/pull/3635
|
||||
[#3644]: https://github.com/tokio-rs/tokio/pull/3644
|
||||
[#3645]: https://github.com/tokio-rs/tokio/pull/3645
|
||||
[#3650]: https://github.com/tokio-rs/tokio/pull/3650
|
||||
[#3652]: https://github.com/tokio-rs/tokio/pull/3652
|
||||
[#3654]: https://github.com/tokio-rs/tokio/pull/3654
|
||||
[#3672]: https://github.com/tokio-rs/tokio/pull/3672
|
||||
[#3673]: https://github.com/tokio-rs/tokio/pull/3673
|
||||
[#3674]: https://github.com/tokio-rs/tokio/pull/3674
|
||||
[#3678]: https://github.com/tokio-rs/tokio/pull/3678
|
||||
[#3684]: https://github.com/tokio-rs/tokio/pull/3684
|
||||
[#3690]: https://github.com/tokio-rs/tokio/pull/3690
|
||||
[#3693]: https://github.com/tokio-rs/tokio/pull/3693
|
||||
|
||||
# 1.4.0 (March 20, 2021)
|
||||
|
||||
### Added
|
||||
|
||||
- macros: introduce biased argument for `select!` ([#3603])
|
||||
- runtime: add `Handle::block_on` ([#3569])
|
||||
|
||||
### Fixed
|
||||
|
||||
- runtime: avoid unnecessary polling of `block_on` future ([#3582])
|
||||
- runtime: fix memory leak/growth when creating many runtimes ([#3564])
|
||||
- runtime: mark `EnterGuard` with `must_use` ([#3609])
|
||||
|
||||
### Documented
|
||||
|
||||
- chore: mention fix for building docs in contributing guide ([#3618])
|
||||
- doc: add link to `PollSender` ([#3613])
|
||||
- doc: alias sleep to delay ([#3604])
|
||||
- sync: improve `Mutex` FIFO explanation ([#3615])
|
||||
- timer: fix double newline in module docs ([#3617])
|
||||
|
||||
[#3564]: https://github.com/tokio-rs/tokio/pull/3564
|
||||
[#3613]: https://github.com/tokio-rs/tokio/pull/3613
|
||||
[#3618]: https://github.com/tokio-rs/tokio/pull/3618
|
||||
[#3617]: https://github.com/tokio-rs/tokio/pull/3617
|
||||
[#3582]: https://github.com/tokio-rs/tokio/pull/3582
|
||||
[#3615]: https://github.com/tokio-rs/tokio/pull/3615
|
||||
[#3603]: https://github.com/tokio-rs/tokio/pull/3603
|
||||
[#3609]: https://github.com/tokio-rs/tokio/pull/3609
|
||||
[#3604]: https://github.com/tokio-rs/tokio/pull/3604
|
||||
[#3569]: https://github.com/tokio-rs/tokio/pull/3569
|
||||
|
||||
# 1.3.0 (March 9, 2021)
|
||||
|
||||
### Added
|
||||
|
||||
- coop: expose an `unconstrained()` opt-out ([#3547])
|
||||
- net: add `into_std` for net types without it ([#3509])
|
||||
- sync: add `same_channel` method to `mpsc::Sender` ([#3532])
|
||||
- sync: add `{try_,}acquire_many_owned` to `Semaphore` ([#3535])
|
||||
- sync: add back `RwLockWriteGuard::map` and `RwLockWriteGuard::try_map` ([#3348])
|
||||
|
||||
### Fixed
|
||||
|
||||
- sync: allow `oneshot::Receiver::close` after successful `try_recv` ([#3552])
|
||||
- time: do not panic on `timeout(Duration::MAX)` ([#3551])
|
||||
|
||||
### Documented
|
||||
|
||||
- doc: doc aliases for pre-1.0 function names ([#3523])
|
||||
- io: fix typos ([#3541])
|
||||
- io: note the EOF behaviour of `read_until` ([#3536])
|
||||
- io: update `AsyncRead::poll_read` doc ([#3557])
|
||||
- net: update `UdpSocket` splitting doc ([#3517])
|
||||
- runtime: add link to `LocalSet` on `new_current_thread` ([#3508])
|
||||
- runtime: update documentation of thread limits ([#3527])
|
||||
- sync: do not recommend `join_all` for `Barrier` ([#3514])
|
||||
- sync: documentation for `oneshot` ([#3592])
|
||||
- sync: rename `notify` to `notify_one` ([#3526])
|
||||
- time: fix typo in `Sleep` doc ([#3515])
|
||||
- time: sync `interval.rs` and `time/mod.rs` docs ([#3533])
|
||||
|
||||
[#3348]: https://github.com/tokio-rs/tokio/pull/3348
|
||||
[#3508]: https://github.com/tokio-rs/tokio/pull/3508
|
||||
[#3509]: https://github.com/tokio-rs/tokio/pull/3509
|
||||
[#3514]: https://github.com/tokio-rs/tokio/pull/3514
|
||||
[#3515]: https://github.com/tokio-rs/tokio/pull/3515
|
||||
[#3517]: https://github.com/tokio-rs/tokio/pull/3517
|
||||
[#3523]: https://github.com/tokio-rs/tokio/pull/3523
|
||||
[#3526]: https://github.com/tokio-rs/tokio/pull/3526
|
||||
[#3527]: https://github.com/tokio-rs/tokio/pull/3527
|
||||
[#3532]: https://github.com/tokio-rs/tokio/pull/3532
|
||||
[#3533]: https://github.com/tokio-rs/tokio/pull/3533
|
||||
[#3535]: https://github.com/tokio-rs/tokio/pull/3535
|
||||
[#3536]: https://github.com/tokio-rs/tokio/pull/3536
|
||||
[#3541]: https://github.com/tokio-rs/tokio/pull/3541
|
||||
[#3547]: https://github.com/tokio-rs/tokio/pull/3547
|
||||
[#3551]: https://github.com/tokio-rs/tokio/pull/3551
|
||||
[#3552]: https://github.com/tokio-rs/tokio/pull/3552
|
||||
[#3557]: https://github.com/tokio-rs/tokio/pull/3557
|
||||
[#3592]: https://github.com/tokio-rs/tokio/pull/3592
|
||||
|
||||
# 1.2.0 (February 5, 2021)
|
||||
|
||||
### Added
|
||||
|
||||
+4
-5
@@ -2,18 +2,17 @@
|
||||
name = "tokio"
|
||||
# When releasing to crates.io:
|
||||
# - Remove path dependencies
|
||||
# - Update html_root_url.
|
||||
# - Update doc url
|
||||
# - Cargo.toml
|
||||
# - README.md
|
||||
# - Update CHANGELOG.md.
|
||||
# - Create "v1.0.x" git tag.
|
||||
version = "1.2.0"
|
||||
version = "1.6.2"
|
||||
edition = "2018"
|
||||
authors = ["Tokio Contributors <[email protected]>"]
|
||||
license = "MIT"
|
||||
readme = "README.md"
|
||||
documentation = "https://docs.rs/tokio/1.2.0/tokio/"
|
||||
documentation = "https://docs.rs/tokio/1.6.2/tokio/"
|
||||
repository = "https://github.com/tokio-rs/tokio"
|
||||
homepage = "https://tokio.rs"
|
||||
description = """
|
||||
@@ -120,13 +119,13 @@ optional = true
|
||||
tokio-test = { version = "0.4.0", path = "../tokio-test" }
|
||||
tokio-stream = { version = "0.1", path = "../tokio-stream" }
|
||||
futures = { version = "0.3.0", features = ["async-await"] }
|
||||
proptest = "0.10.0"
|
||||
proptest = "1"
|
||||
rand = "0.8.0"
|
||||
tempfile = "3.1.0"
|
||||
async-stream = "0.3"
|
||||
|
||||
[target.'cfg(loom)'.dev-dependencies]
|
||||
loom = { version = "0.4", features = ["futures", "checkpoint"] }
|
||||
loom = { version = "0.5", features = ["futures", "checkpoint"] }
|
||||
|
||||
[build-dependencies]
|
||||
autocfg = "1" # Needed for conditionally enabling `track-caller`
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
Copyright (c) 2020 Tokio Contributors
|
||||
Copyright (c) 2021 Tokio Contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any
|
||||
person obtaining a copy of this software and associated
|
||||
|
||||
+32
-47
@@ -1,55 +1,33 @@
|
||||
#![cfg_attr(not(feature = "full"), allow(dead_code))]
|
||||
|
||||
//! Opt-in yield points for improved cooperative scheduling.
|
||||
//! Yield points for improved cooperative scheduling.
|
||||
//!
|
||||
//! A single call to [`poll`] on a top-level task may potentially do a lot of
|
||||
//! work before it returns `Poll::Pending`. If a task runs for a long period of
|
||||
//! time without yielding back to the executor, it can starve other tasks
|
||||
//! waiting on that executor to execute them, or drive underlying resources.
|
||||
//! Since Rust does not have a runtime, it is difficult to forcibly preempt a
|
||||
//! long-running task. Instead, this module provides an opt-in mechanism for
|
||||
//! futures to collaborate with the executor to avoid starvation.
|
||||
//! Documentation for this can be found in the [`tokio::task`] module.
|
||||
//!
|
||||
//! Consider a future like this one:
|
||||
//!
|
||||
//! ```
|
||||
//! # use tokio_stream::{Stream, StreamExt};
|
||||
//! async fn drop_all<I: Stream + Unpin>(mut input: I) {
|
||||
//! while let Some(_) = input.next().await {}
|
||||
//! }
|
||||
//! ```
|
||||
//!
|
||||
//! It may look harmless, but consider what happens under heavy load if the
|
||||
//! input stream is _always_ ready. If we spawn `drop_all`, the task will never
|
||||
//! yield, and will starve other tasks and resources on the same executor. With
|
||||
//! opt-in yield points, this problem is alleviated:
|
||||
//!
|
||||
//! ```ignore
|
||||
//! # use tokio_stream::{Stream, StreamExt};
|
||||
//! async fn drop_all<I: Stream + Unpin>(mut input: I) {
|
||||
//! while let Some(_) = input.next().await {
|
||||
//! tokio::coop::proceed().await;
|
||||
//! }
|
||||
//! }
|
||||
//! ```
|
||||
//!
|
||||
//! The `proceed` future will coordinate with the executor to make sure that
|
||||
//! every so often control is yielded back to the executor so it can run other
|
||||
//! tasks.
|
||||
//!
|
||||
//! # Placing yield points
|
||||
//!
|
||||
//! Voluntary yield points should be placed _after_ at least some work has been
|
||||
//! done. If they are not, a future sufficiently deep in the task hierarchy may
|
||||
//! end up _never_ getting to run because of the number of yield points that
|
||||
//! inevitably appear before it is reached. In general, you will want yield
|
||||
//! points to only appear in "leaf" futures -- those that do not themselves poll
|
||||
//! other futures. By doing this, you avoid double-counting each iteration of
|
||||
//! the outer future against the cooperating budget.
|
||||
//!
|
||||
//! [`poll`]: method@std::future::Future::poll
|
||||
//! [`tokio::task`]: crate::task.
|
||||
|
||||
// NOTE: The doctests in this module are ignored since the whole module is (currently) private.
|
||||
// ```ignore
|
||||
// # use tokio_stream::{Stream, StreamExt};
|
||||
// async fn drop_all<I: Stream + Unpin>(mut input: I) {
|
||||
// while let Some(_) = input.next().await {
|
||||
// tokio::coop::proceed().await;
|
||||
// }
|
||||
// }
|
||||
// ```
|
||||
//
|
||||
// The `proceed` future will coordinate with the executor to make sure that
|
||||
// every so often control is yielded back to the executor so it can run other
|
||||
// tasks.
|
||||
//
|
||||
// # Placing yield points
|
||||
//
|
||||
// Voluntary yield points should be placed _after_ at least some work has been
|
||||
// done. If they are not, a future sufficiently deep in the task hierarchy may
|
||||
// end up _never_ getting to run because of the number of yield points that
|
||||
// inevitably appear before it is reached. In general, you will want yield
|
||||
// points to only appear in "leaf" futures -- those that do not themselves poll
|
||||
// other futures. By doing this, you avoid double-counting each iteration of
|
||||
// the outer future against the cooperating budget.
|
||||
|
||||
use std::cell::Cell;
|
||||
|
||||
@@ -98,6 +76,13 @@ pub(crate) fn budget<R>(f: impl FnOnce() -> R) -> R {
|
||||
with_budget(Budget::initial(), f)
|
||||
}
|
||||
|
||||
/// Run the given closure with an unconstrained task budget. When the function returns, the budget
|
||||
/// is reset to the value prior to calling the function.
|
||||
#[inline(always)]
|
||||
pub(crate) fn with_unconstrained<R>(f: impl FnOnce() -> R) -> R {
|
||||
with_budget(Budget::unconstrained(), f)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn with_budget<R>(budget: Budget, f: impl FnOnce() -> R) -> R {
|
||||
struct ResetGuard<'a> {
|
||||
|
||||
+15
-11
@@ -8,7 +8,8 @@ use std::{task::Context, task::Poll};
|
||||
/// Associates an IO object backed by a Unix file descriptor with the tokio
|
||||
/// reactor, allowing for readiness to be polled. The file descriptor must be of
|
||||
/// a type that can be used with the OS polling facilities (ie, `poll`, `epoll`,
|
||||
/// `kqueue`, etc), such as a network socket or pipe.
|
||||
/// `kqueue`, etc), such as a network socket or pipe, and the file descriptor
|
||||
/// must have the nonblocking mode set to true.
|
||||
///
|
||||
/// Creating an AsyncFd registers the file descriptor with the current tokio
|
||||
/// Reactor, allowing you to directly await the file descriptor being readable
|
||||
@@ -36,18 +37,19 @@ use std::{task::Context, task::Poll};
|
||||
///
|
||||
/// On some platforms, the readiness detecting mechanism relies on
|
||||
/// edge-triggered notifications. This means that the OS will only notify Tokio
|
||||
/// when the file descriptor transitions from not-ready to ready. Tokio
|
||||
/// internally tracks when it has received a ready notification, and when
|
||||
/// when the file descriptor transitions from not-ready to ready. For this to
|
||||
/// work you should first try to read or write and only poll for readiness
|
||||
/// if that fails with an error of [`std::io::ErrorKind::WouldBlock`].
|
||||
///
|
||||
/// Tokio internally tracks when it has received a ready notification, and when
|
||||
/// readiness checking functions like [`readable`] and [`writable`] are called,
|
||||
/// if the readiness flag is set, these async functions will complete
|
||||
/// immediately.
|
||||
///
|
||||
/// This however does mean that it is critical to ensure that this ready flag is
|
||||
/// cleared when (and only when) the file descriptor ceases to be ready. The
|
||||
/// [`AsyncFdReadyGuard`] returned from readiness checking functions serves this
|
||||
/// function; after calling a readiness-checking async function, you must use
|
||||
/// this [`AsyncFdReadyGuard`] to signal to tokio whether the file descriptor is no
|
||||
/// longer in a ready state.
|
||||
/// immediately. This however does mean that it is critical to ensure that this
|
||||
/// ready flag is cleared when (and only when) the file descriptor ceases to be
|
||||
/// ready. The [`AsyncFdReadyGuard`] returned from readiness checking functions
|
||||
/// serves this function; after calling a readiness-checking async function,
|
||||
/// you must use this [`AsyncFdReadyGuard`] to signal to tokio whether the file
|
||||
/// descriptor is no longer in a ready state.
|
||||
///
|
||||
/// ## Use with to a poll-based API
|
||||
///
|
||||
@@ -519,6 +521,8 @@ impl<'a, Inner: AsRawFd> AsyncFdReadyGuard<'a, Inner> {
|
||||
/// create this `AsyncFdReadyGuard`.
|
||||
///
|
||||
/// [`WouldBlock`]: std::io::ErrorKind::WouldBlock
|
||||
// Alias for old name in 0.x
|
||||
#[cfg_attr(docsrs, doc(alias = "with_io"))]
|
||||
pub fn try_io<R>(
|
||||
&mut self,
|
||||
f: impl FnOnce(&AsyncFd<Inner>) -> io::Result<R>,
|
||||
|
||||
@@ -43,9 +43,9 @@ use std::task::{Context, Poll};
|
||||
pub trait AsyncRead {
|
||||
/// Attempts to read from the `AsyncRead` into `buf`.
|
||||
///
|
||||
/// On success, returns `Poll::Ready(Ok(()))` and fills `buf` with data
|
||||
/// read. If no data was read (`buf.filled().is_empty()`) it implies that
|
||||
/// EOF has been reached.
|
||||
/// On success, returns `Poll::Ready(Ok(()))` and places data in the
|
||||
/// unfilled portion of `buf`. If no data was read (`buf.filled().len()` is
|
||||
/// unchanged), it implies that EOF has been reached.
|
||||
///
|
||||
/// If no data is available for reading, the method returns `Poll::Pending`
|
||||
/// and arranges for the current task (via `cx.waker()`) to receive a
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
#![cfg_attr(not(feature = "net"), allow(unreachable_pub))]
|
||||
#![cfg_attr(not(feature = "net"), allow(dead_code, unreachable_pub))]
|
||||
|
||||
use crate::io::driver::Ready;
|
||||
|
||||
|
||||
@@ -273,7 +273,7 @@ cfg_not_rt! {
|
||||
/// This function panics if there is no current reactor set, or if the `rt`
|
||||
/// feature flag is not enabled.
|
||||
pub(super) fn current() -> Self {
|
||||
panic!(crate::util::error::CONTEXT_MISSING_ERROR)
|
||||
panic!("{}", crate::util::error::CONTEXT_MISSING_ERROR)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
#![cfg_attr(not(feature = "net"), allow(dead_code))]
|
||||
|
||||
use crate::io::driver::{Direction, Handle, Interest, ReadyEvent, ScheduledIo};
|
||||
use crate::util::slab;
|
||||
|
||||
@@ -12,8 +14,9 @@ cfg_io_driver! {
|
||||
/// that it will receive task notifications on readiness. This is the lowest
|
||||
/// level API for integrating with a reactor.
|
||||
///
|
||||
/// The association between an I/O resource is made by calling [`new`]. Once
|
||||
/// the association is established, it remains established until the
|
||||
/// The association between an I/O resource is made by calling
|
||||
/// [`new_with_interest_and_handle`].
|
||||
/// Once the association is established, it remains established until the
|
||||
/// registration instance is dropped.
|
||||
///
|
||||
/// A registration instance represents two separate readiness streams. One
|
||||
@@ -34,7 +37,7 @@ cfg_io_driver! {
|
||||
/// stream. The write readiness event stream is only for `Ready::writable()`
|
||||
/// events.
|
||||
///
|
||||
/// [`new`]: method@Self::new
|
||||
/// [`new_with_interest_and_handle`]: method@Self::new_with_interest_and_handle
|
||||
/// [`poll_read_ready`]: method@Self::poll_read_ready`
|
||||
/// [`poll_write_ready`]: method@Self::poll_write_ready`
|
||||
#[derive(Debug)]
|
||||
@@ -233,7 +236,10 @@ cfg_io_readiness! {
|
||||
|
||||
crate::future::poll_fn(|cx| {
|
||||
if self.handle.inner().is_none() {
|
||||
return Poll::Ready(Err(io::Error::new(io::ErrorKind::Other, "reactor gone")));
|
||||
return Poll::Ready(Err(io::Error::new(
|
||||
io::ErrorKind::Other,
|
||||
crate::util::error::RUNTIME_SHUTTING_DOWN_ERROR
|
||||
)));
|
||||
}
|
||||
|
||||
Pin::new(&mut fut).poll(cx).map(Ok)
|
||||
|
||||
@@ -443,7 +443,7 @@ cfg_io_readiness! {
|
||||
// Currently ready!
|
||||
let tick = TICK.unpack(curr) as u8;
|
||||
*state = State::Done;
|
||||
return Poll::Ready(ReadyEvent { ready, tick });
|
||||
return Poll::Ready(ReadyEvent { tick, ready });
|
||||
}
|
||||
|
||||
// Wasn't ready, take the lock (and check again while locked).
|
||||
@@ -462,7 +462,7 @@ cfg_io_readiness! {
|
||||
// Currently ready!
|
||||
let tick = TICK.unpack(curr) as u8;
|
||||
*state = State::Done;
|
||||
return Poll::Ready(ReadyEvent { ready, tick });
|
||||
return Poll::Ready(ReadyEvent { tick, ready });
|
||||
}
|
||||
|
||||
// Not ready even after locked, insert into list...
|
||||
|
||||
+1
-1
@@ -246,7 +246,7 @@ cfg_io_util! {
|
||||
pub(crate) mod seek;
|
||||
pub(crate) mod util;
|
||||
pub use util::{
|
||||
copy, copy_buf, duplex, empty, repeat, sink, AsyncBufReadExt, AsyncReadExt, AsyncSeekExt, AsyncWriteExt,
|
||||
copy, copy_bidirectional, copy_buf, duplex, empty, repeat, sink, AsyncBufReadExt, AsyncReadExt, AsyncSeekExt, AsyncWriteExt,
|
||||
BufReader, BufStream, BufWriter, DuplexStream, Empty, Lines, Repeat, Sink, Split, Take,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -10,10 +10,10 @@ cfg_io_driver! {
|
||||
/// [`std::io::Write`] traits with the reactor that drives it.
|
||||
///
|
||||
/// `PollEvented` uses [`Registration`] internally to take a type that
|
||||
/// implements [`mio::Evented`] as well as [`std::io::Read`] and or
|
||||
/// implements [`mio::event::Source`] as well as [`std::io::Read`] and or
|
||||
/// [`std::io::Write`] and associate it with a reactor that will drive it.
|
||||
///
|
||||
/// Once the [`mio::Evented`] type is wrapped by `PollEvented`, it can be
|
||||
/// Once the [`mio::event::Source`] type is wrapped by `PollEvented`, it can be
|
||||
/// used from within the future's execution model. As such, the
|
||||
/// `PollEvented` type provides [`AsyncRead`] and [`AsyncWrite`]
|
||||
/// implementations using the underlying I/O resource as well as readiness
|
||||
@@ -40,13 +40,13 @@ cfg_io_driver! {
|
||||
/// [`poll_read_ready`] again will also indicate read readiness.
|
||||
///
|
||||
/// When the operation is attempted and is unable to succeed due to the I/O
|
||||
/// resource not being ready, the caller must call [`clear_read_ready`] or
|
||||
/// [`clear_write_ready`]. This clears the readiness state until a new
|
||||
/// resource not being ready, the caller must call `clear_read_ready` or
|
||||
/// `clear_write_ready`. This clears the readiness state until a new
|
||||
/// readiness event is received.
|
||||
///
|
||||
/// This allows the caller to implement additional functions. For example,
|
||||
/// [`TcpListener`] implements poll_accept by using [`poll_read_ready`] and
|
||||
/// [`clear_read_ready`].
|
||||
/// `clear_read_ready`.
|
||||
///
|
||||
/// ## Platform-specific events
|
||||
///
|
||||
@@ -54,17 +54,11 @@ cfg_io_driver! {
|
||||
/// These events are included as part of the read readiness event stream. The
|
||||
/// write readiness event stream is only for `Ready::writable()` events.
|
||||
///
|
||||
/// [`std::io::Read`]: trait@std::io::Read
|
||||
/// [`std::io::Write`]: trait@std::io::Write
|
||||
/// [`AsyncRead`]: trait@AsyncRead
|
||||
/// [`AsyncWrite`]: trait@AsyncWrite
|
||||
/// [`mio::Evented`]: trait@mio::Evented
|
||||
/// [`Registration`]: struct@Registration
|
||||
/// [`TcpListener`]: struct@crate::net::TcpListener
|
||||
/// [`clear_read_ready`]: method@Self::clear_read_ready
|
||||
/// [`clear_write_ready`]: method@Self::clear_write_ready
|
||||
/// [`poll_read_ready`]: method@Self::poll_read_ready
|
||||
/// [`poll_write_ready`]: method@Self::poll_write_ready
|
||||
/// [`AsyncRead`]: crate::io::AsyncRead
|
||||
/// [`AsyncWrite`]: crate::io::AsyncWrite
|
||||
/// [`TcpListener`]: crate::net::TcpListener
|
||||
/// [`poll_read_ready`]: Registration::poll_read_ready
|
||||
/// [`poll_write_ready`]: Registration::poll_write_ready
|
||||
pub(crate) struct PollEvented<E: Source> {
|
||||
io: Option<E>,
|
||||
registration: Registration,
|
||||
@@ -121,6 +115,11 @@ impl<E: Source> PollEvented<E> {
|
||||
}
|
||||
|
||||
/// Returns a reference to the registration
|
||||
#[cfg(any(
|
||||
feature = "net",
|
||||
all(unix, feature = "process"),
|
||||
all(unix, feature = "signal"),
|
||||
))]
|
||||
pub(crate) fn registration(&self) -> &Registration {
|
||||
&self.registration
|
||||
}
|
||||
|
||||
@@ -23,6 +23,8 @@ cfg_io_util! {
|
||||
///
|
||||
/// If successful, this function will return the total number of bytes read.
|
||||
///
|
||||
/// If this function returns `Ok(0)`, the stream has reached EOF.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// This function will ignore all instances of [`ErrorKind::Interrupted`] and
|
||||
|
||||
@@ -35,7 +35,7 @@ cfg_io_util! {
|
||||
|
||||
/// Reads bytes from a source.
|
||||
///
|
||||
/// Implemented as an extention trait, adding utility methods to all
|
||||
/// Implemented as an extension trait, adding utility methods to all
|
||||
/// [`AsyncRead`] types. Callers will tend to import this trait instead of
|
||||
/// [`AsyncRead`].
|
||||
///
|
||||
|
||||
@@ -66,6 +66,17 @@ cfg_io_util! {
|
||||
{
|
||||
seek(self, pos)
|
||||
}
|
||||
|
||||
/// Creates a future which will return the current seek position from the
|
||||
/// start of the stream.
|
||||
///
|
||||
/// This is equivalent to `self.seek(SeekFrom::Current(0))`.
|
||||
fn stream_position(&mut self) -> Seek<'_, Self>
|
||||
where
|
||||
Self: Unpin,
|
||||
{
|
||||
self.seek(SeekFrom::Current(0))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ use crate::io::util::flush::{flush, Flush};
|
||||
use crate::io::util::shutdown::{shutdown, Shutdown};
|
||||
use crate::io::util::write::{write, Write};
|
||||
use crate::io::util::write_all::{write_all, WriteAll};
|
||||
use crate::io::util::write_all_buf::{write_all_buf, WriteAllBuf};
|
||||
use crate::io::util::write_buf::{write_buf, WriteBuf};
|
||||
use crate::io::util::write_int::{
|
||||
WriteI128, WriteI128Le, WriteI16, WriteI16Le, WriteI32, WriteI32Le, WriteI64, WriteI64Le,
|
||||
@@ -11,7 +12,9 @@ use crate::io::util::write_int::{
|
||||
WriteU128, WriteU128Le, WriteU16, WriteU16Le, WriteU32, WriteU32Le, WriteU64, WriteU64Le,
|
||||
WriteU8,
|
||||
};
|
||||
use crate::io::util::write_vectored::{write_vectored, WriteVectored};
|
||||
use crate::io::AsyncWrite;
|
||||
use std::io::IoSlice;
|
||||
|
||||
use bytes::Buf;
|
||||
|
||||
@@ -35,7 +38,7 @@ cfg_io_util! {
|
||||
|
||||
/// Writes bytes to a sink.
|
||||
///
|
||||
/// Implemented as an extention trait, adding utility methods to all
|
||||
/// Implemented as an extension trait, adding utility methods to all
|
||||
/// [`AsyncWrite`] types. Callers will tend to import this trait instead of
|
||||
/// [`AsyncWrite`].
|
||||
///
|
||||
@@ -116,6 +119,46 @@ cfg_io_util! {
|
||||
write(self, src)
|
||||
}
|
||||
|
||||
/// Like [`write`], except that it writes from a slice of buffers.
|
||||
///
|
||||
/// Equivalent to:
|
||||
///
|
||||
/// ```ignore
|
||||
/// async fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize>;
|
||||
/// ```
|
||||
///
|
||||
/// See [`AsyncWrite::poll_write_vectored`] for more details.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```no_run
|
||||
/// use tokio::io::{self, AsyncWriteExt};
|
||||
/// use tokio::fs::File;
|
||||
/// use std::io::IoSlice;
|
||||
///
|
||||
/// #[tokio::main]
|
||||
/// async fn main() -> io::Result<()> {
|
||||
/// let mut file = File::create("foo.txt").await?;
|
||||
///
|
||||
/// let bufs: &[_] = &[
|
||||
/// IoSlice::new(b"hello"),
|
||||
/// IoSlice::new(b" "),
|
||||
/// IoSlice::new(b"world"),
|
||||
/// ];
|
||||
///
|
||||
/// file.write_vectored(&bufs).await?;
|
||||
///
|
||||
/// Ok(())
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// [`write`]: AsyncWriteExt::write
|
||||
fn write_vectored<'a, 'b>(&'a mut self, bufs: &'a [IoSlice<'b>]) -> WriteVectored<'a, 'b, Self>
|
||||
where
|
||||
Self: Unpin,
|
||||
{
|
||||
write_vectored(self, bufs)
|
||||
}
|
||||
|
||||
/// Writes a buffer into this writer, advancing the buffer's internal
|
||||
/// cursor.
|
||||
@@ -154,10 +197,11 @@ cfg_io_util! {
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// [`File`] implements `Read` and [`Cursor<&[u8]>`] implements [`Buf`]:
|
||||
/// [`File`] implements [`AsyncWrite`] and [`Cursor`]`<&[u8]>` implements [`Buf`]:
|
||||
///
|
||||
/// [`File`]: crate::fs::File
|
||||
/// [`Buf`]: bytes::Buf
|
||||
/// [`Cursor`]: std::io::Cursor
|
||||
///
|
||||
/// ```no_run
|
||||
/// use tokio::io::{self, AsyncWriteExt};
|
||||
@@ -190,6 +234,59 @@ cfg_io_util! {
|
||||
write_buf(self, src)
|
||||
}
|
||||
|
||||
/// Attempts to write an entire buffer into this writer
|
||||
///
|
||||
/// Equivalent to:
|
||||
///
|
||||
/// ```ignore
|
||||
/// async fn write_all_buf(&mut self, buf: impl Buf) -> Result<(), io::Error> {
|
||||
/// while buf.has_remaining() {
|
||||
/// self.write_buf(&mut buf).await?;
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// This method will continuously call [`write`] until
|
||||
/// [`buf.has_remaining()`](bytes::Buf::has_remaining) returns false. This method will not
|
||||
/// return until the entire buffer has been successfully written or an error occurs. The
|
||||
/// first error generated will be returned.
|
||||
///
|
||||
/// The buffer is advanced after each chunk is successfully written. After failure,
|
||||
/// `src.chunk()` will return the chunk that failed to write.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// [`File`] implements [`AsyncWrite`] and [`Cursor`]`<&[u8]>` implements [`Buf`]:
|
||||
///
|
||||
/// [`File`]: crate::fs::File
|
||||
/// [`Buf`]: bytes::Buf
|
||||
/// [`Cursor`]: std::io::Cursor
|
||||
///
|
||||
/// ```no_run
|
||||
/// use tokio::io::{self, AsyncWriteExt};
|
||||
/// use tokio::fs::File;
|
||||
///
|
||||
/// use std::io::Cursor;
|
||||
///
|
||||
/// #[tokio::main]
|
||||
/// async fn main() -> io::Result<()> {
|
||||
/// let mut file = File::create("foo.txt").await?;
|
||||
/// let mut buffer = Cursor::new(b"data to write");
|
||||
///
|
||||
/// file.write_all_buf(&mut buffer).await?;
|
||||
/// Ok(())
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// [`write`]: AsyncWriteExt::write
|
||||
fn write_all_buf<'a, B>(&'a mut self, src: &'a mut B) -> WriteAllBuf<'a, Self, B>
|
||||
where
|
||||
Self: Sized + Unpin,
|
||||
B: Buf,
|
||||
{
|
||||
write_all_buf(self, src)
|
||||
}
|
||||
|
||||
/// Attempts to write an entire buffer into this writer.
|
||||
///
|
||||
/// Equivalent to:
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
use crate::io::util::DEFAULT_BUF_SIZE;
|
||||
use crate::io::{AsyncBufRead, AsyncRead, AsyncWrite, ReadBuf};
|
||||
use crate::io::{AsyncBufRead, AsyncRead, AsyncSeek, AsyncWrite, ReadBuf};
|
||||
|
||||
use pin_project_lite::pin_project;
|
||||
use std::io;
|
||||
use std::io::{self, SeekFrom};
|
||||
use std::pin::Pin;
|
||||
use std::task::{Context, Poll};
|
||||
use std::{cmp, fmt};
|
||||
use std::{cmp, fmt, mem};
|
||||
|
||||
pin_project! {
|
||||
/// The `BufReader` struct adds buffering to any reader.
|
||||
@@ -30,6 +30,7 @@ pin_project! {
|
||||
pub(super) buf: Box<[u8]>,
|
||||
pub(super) pos: usize,
|
||||
pub(super) cap: usize,
|
||||
pub(super) seek_state: SeekState,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -48,6 +49,7 @@ impl<R: AsyncRead> BufReader<R> {
|
||||
buf: buffer.into_boxed_slice(),
|
||||
pos: 0,
|
||||
cap: 0,
|
||||
seek_state: SeekState::Init,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -141,6 +143,122 @@ impl<R: AsyncRead> AsyncBufRead for BufReader<R> {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(super) enum SeekState {
|
||||
/// start_seek has not been called.
|
||||
Init,
|
||||
/// start_seek has been called, but poll_complete has not yet been called.
|
||||
Start(SeekFrom),
|
||||
/// Waiting for completion of the first poll_complete in the `n.checked_sub(remainder).is_none()` branch.
|
||||
PendingOverflowed(i64),
|
||||
/// Waiting for completion of poll_complete.
|
||||
Pending,
|
||||
}
|
||||
|
||||
/// Seek to an offset, in bytes, in the underlying reader.
|
||||
///
|
||||
/// The position used for seeking with `SeekFrom::Current(_)` is the
|
||||
/// position the underlying reader would be at if the `BufReader` had no
|
||||
/// internal buffer.
|
||||
///
|
||||
/// Seeking always discards the internal buffer, even if the seek position
|
||||
/// would otherwise fall within it. This guarantees that calling
|
||||
/// `.into_inner()` immediately after a seek yields the underlying reader
|
||||
/// at the same position.
|
||||
///
|
||||
/// See [`AsyncSeek`] for more details.
|
||||
///
|
||||
/// Note: In the edge case where you're seeking with `SeekFrom::Current(n)`
|
||||
/// where `n` minus the internal buffer length overflows an `i64`, two
|
||||
/// seeks will be performed instead of one. If the second seek returns
|
||||
/// `Err`, the underlying reader will be left at the same position it would
|
||||
/// have if you called `seek` with `SeekFrom::Current(0)`.
|
||||
impl<R: AsyncRead + AsyncSeek> AsyncSeek for BufReader<R> {
|
||||
fn start_seek(self: Pin<&mut Self>, pos: SeekFrom) -> io::Result<()> {
|
||||
// We needs to call seek operation multiple times.
|
||||
// And we should always call both start_seek and poll_complete,
|
||||
// as start_seek alone cannot guarantee that the operation will be completed.
|
||||
// poll_complete receives a Context and returns a Poll, so it cannot be called
|
||||
// inside start_seek.
|
||||
*self.project().seek_state = SeekState::Start(pos);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn poll_complete(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<u64>> {
|
||||
let res = match mem::replace(self.as_mut().project().seek_state, SeekState::Init) {
|
||||
SeekState::Init => {
|
||||
// 1.x AsyncSeek recommends calling poll_complete before start_seek.
|
||||
// We don't have to guarantee that the value returned by
|
||||
// poll_complete called without start_seek is correct,
|
||||
// so we'll return 0.
|
||||
return Poll::Ready(Ok(0));
|
||||
}
|
||||
SeekState::Start(SeekFrom::Current(n)) => {
|
||||
let remainder = (self.cap - self.pos) as i64;
|
||||
// it should be safe to assume that remainder fits within an i64 as the alternative
|
||||
// means we managed to allocate 8 exbibytes and that's absurd.
|
||||
// But it's not out of the realm of possibility for some weird underlying reader to
|
||||
// support seeking by i64::min_value() so we need to handle underflow when subtracting
|
||||
// remainder.
|
||||
if let Some(offset) = n.checked_sub(remainder) {
|
||||
self.as_mut()
|
||||
.get_pin_mut()
|
||||
.start_seek(SeekFrom::Current(offset))?;
|
||||
self.as_mut().get_pin_mut().poll_complete(cx)?
|
||||
} else {
|
||||
// seek backwards by our remainder, and then by the offset
|
||||
self.as_mut()
|
||||
.get_pin_mut()
|
||||
.start_seek(SeekFrom::Current(-remainder))?;
|
||||
if self.as_mut().get_pin_mut().poll_complete(cx)?.is_pending() {
|
||||
*self.as_mut().project().seek_state = SeekState::PendingOverflowed(n);
|
||||
return Poll::Pending;
|
||||
}
|
||||
|
||||
// https://github.com/rust-lang/rust/pull/61157#issuecomment-495932676
|
||||
self.as_mut().discard_buffer();
|
||||
|
||||
self.as_mut()
|
||||
.get_pin_mut()
|
||||
.start_seek(SeekFrom::Current(n))?;
|
||||
self.as_mut().get_pin_mut().poll_complete(cx)?
|
||||
}
|
||||
}
|
||||
SeekState::PendingOverflowed(n) => {
|
||||
if self.as_mut().get_pin_mut().poll_complete(cx)?.is_pending() {
|
||||
*self.as_mut().project().seek_state = SeekState::PendingOverflowed(n);
|
||||
return Poll::Pending;
|
||||
}
|
||||
|
||||
// https://github.com/rust-lang/rust/pull/61157#issuecomment-495932676
|
||||
self.as_mut().discard_buffer();
|
||||
|
||||
self.as_mut()
|
||||
.get_pin_mut()
|
||||
.start_seek(SeekFrom::Current(n))?;
|
||||
self.as_mut().get_pin_mut().poll_complete(cx)?
|
||||
}
|
||||
SeekState::Start(pos) => {
|
||||
// Seeking with Start/End doesn't care about our buffer length.
|
||||
self.as_mut().get_pin_mut().start_seek(pos)?;
|
||||
self.as_mut().get_pin_mut().poll_complete(cx)?
|
||||
}
|
||||
SeekState::Pending => self.as_mut().get_pin_mut().poll_complete(cx)?,
|
||||
};
|
||||
|
||||
match res {
|
||||
Poll::Ready(res) => {
|
||||
self.discard_buffer();
|
||||
Poll::Ready(Ok(res))
|
||||
}
|
||||
Poll::Pending => {
|
||||
*self.as_mut().project().seek_state = SeekState::Pending;
|
||||
Poll::Pending
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<R: AsyncRead + AsyncWrite> AsyncWrite for BufReader<R> {
|
||||
fn poll_write(
|
||||
self: Pin<&mut Self>,
|
||||
|
||||
@@ -94,9 +94,11 @@ impl<RW> From<BufWriter<BufReader<RW>>> for BufStream<RW> {
|
||||
buf: rbuf,
|
||||
pos,
|
||||
cap,
|
||||
seek_state: rseek_state,
|
||||
},
|
||||
buf: wbuf,
|
||||
written,
|
||||
seek_state: wseek_state,
|
||||
} = b;
|
||||
|
||||
BufStream {
|
||||
@@ -105,10 +107,12 @@ impl<RW> From<BufWriter<BufReader<RW>>> for BufStream<RW> {
|
||||
inner,
|
||||
buf: wbuf,
|
||||
written,
|
||||
seek_state: wseek_state,
|
||||
},
|
||||
buf: rbuf,
|
||||
pos,
|
||||
cap,
|
||||
seek_state: rseek_state,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
use crate::io::util::DEFAULT_BUF_SIZE;
|
||||
use crate::io::{AsyncBufRead, AsyncRead, AsyncWrite, ReadBuf};
|
||||
use crate::io::{AsyncBufRead, AsyncRead, AsyncSeek, AsyncWrite, ReadBuf};
|
||||
|
||||
use pin_project_lite::pin_project;
|
||||
use std::fmt;
|
||||
use std::io::{self, Write};
|
||||
use std::io::{self, SeekFrom, Write};
|
||||
use std::pin::Pin;
|
||||
use std::task::{Context, Poll};
|
||||
|
||||
@@ -34,6 +34,7 @@ pin_project! {
|
||||
pub(super) inner: W,
|
||||
pub(super) buf: Vec<u8>,
|
||||
pub(super) written: usize,
|
||||
pub(super) seek_state: SeekState,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -50,6 +51,7 @@ impl<W: AsyncWrite> BufWriter<W> {
|
||||
inner,
|
||||
buf: Vec::with_capacity(cap),
|
||||
written: 0,
|
||||
seek_state: SeekState::Init,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -142,6 +144,62 @@ impl<W: AsyncWrite> AsyncWrite for BufWriter<W> {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(super) enum SeekState {
|
||||
/// start_seek has not been called.
|
||||
Init,
|
||||
/// start_seek has been called, but poll_complete has not yet been called.
|
||||
Start(SeekFrom),
|
||||
/// Waiting for completion of poll_complete.
|
||||
Pending,
|
||||
}
|
||||
|
||||
/// Seek to the offset, in bytes, in the underlying writer.
|
||||
///
|
||||
/// Seeking always writes out the internal buffer before seeking.
|
||||
impl<W: AsyncWrite + AsyncSeek> AsyncSeek for BufWriter<W> {
|
||||
fn start_seek(self: Pin<&mut Self>, pos: SeekFrom) -> io::Result<()> {
|
||||
// We need to flush the internal buffer before seeking.
|
||||
// It receives a `Context` and returns a `Poll`, so it cannot be called
|
||||
// inside `start_seek`.
|
||||
*self.project().seek_state = SeekState::Start(pos);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn poll_complete(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<u64>> {
|
||||
let pos = match self.seek_state {
|
||||
SeekState::Init => {
|
||||
return self.project().inner.poll_complete(cx);
|
||||
}
|
||||
SeekState::Start(pos) => Some(pos),
|
||||
SeekState::Pending => None,
|
||||
};
|
||||
|
||||
// Flush the internal buffer before seeking.
|
||||
ready!(self.as_mut().flush_buf(cx))?;
|
||||
|
||||
let mut me = self.project();
|
||||
if let Some(pos) = pos {
|
||||
// Ensure previous seeks have finished before starting a new one
|
||||
ready!(me.inner.as_mut().poll_complete(cx))?;
|
||||
if let Err(e) = me.inner.as_mut().start_seek(pos) {
|
||||
*me.seek_state = SeekState::Init;
|
||||
return Poll::Ready(Err(e));
|
||||
}
|
||||
}
|
||||
match me.inner.poll_complete(cx) {
|
||||
Poll::Ready(res) => {
|
||||
*me.seek_state = SeekState::Init;
|
||||
Poll::Ready(res)
|
||||
}
|
||||
Poll::Pending => {
|
||||
*me.seek_state = SeekState::Pending;
|
||||
Poll::Pending
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<W: AsyncWrite + AsyncRead> AsyncRead for BufWriter<W> {
|
||||
fn poll_read(
|
||||
self: Pin<&mut Self>,
|
||||
|
||||
+78
-50
@@ -5,18 +5,85 @@ use std::io;
|
||||
use std::pin::Pin;
|
||||
use std::task::{Context, Poll};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(super) struct CopyBuffer {
|
||||
read_done: bool,
|
||||
pos: usize,
|
||||
cap: usize,
|
||||
amt: u64,
|
||||
buf: Box<[u8]>,
|
||||
}
|
||||
|
||||
impl CopyBuffer {
|
||||
pub(super) fn new() -> Self {
|
||||
Self {
|
||||
read_done: false,
|
||||
pos: 0,
|
||||
cap: 0,
|
||||
amt: 0,
|
||||
buf: vec![0; 2048].into_boxed_slice(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn poll_copy<R, W>(
|
||||
&mut self,
|
||||
cx: &mut Context<'_>,
|
||||
mut reader: Pin<&mut R>,
|
||||
mut writer: Pin<&mut W>,
|
||||
) -> Poll<io::Result<u64>>
|
||||
where
|
||||
R: AsyncRead + ?Sized,
|
||||
W: AsyncWrite + ?Sized,
|
||||
{
|
||||
loop {
|
||||
// If our buffer is empty, then we need to read some data to
|
||||
// continue.
|
||||
if self.pos == self.cap && !self.read_done {
|
||||
let me = &mut *self;
|
||||
let mut buf = ReadBuf::new(&mut me.buf);
|
||||
ready!(reader.as_mut().poll_read(cx, &mut buf))?;
|
||||
let n = buf.filled().len();
|
||||
if n == 0 {
|
||||
self.read_done = true;
|
||||
} else {
|
||||
self.pos = 0;
|
||||
self.cap = n;
|
||||
}
|
||||
}
|
||||
|
||||
// If our buffer has some data, let's write it out!
|
||||
while self.pos < self.cap {
|
||||
let me = &mut *self;
|
||||
let i = ready!(writer.as_mut().poll_write(cx, &me.buf[me.pos..me.cap]))?;
|
||||
if i == 0 {
|
||||
return Poll::Ready(Err(io::Error::new(
|
||||
io::ErrorKind::WriteZero,
|
||||
"write zero byte into writer",
|
||||
)));
|
||||
} else {
|
||||
self.pos += i;
|
||||
self.amt += i as u64;
|
||||
}
|
||||
}
|
||||
|
||||
// If we've written all the data and we've seen EOF, flush out the
|
||||
// data and finish the transfer.
|
||||
if self.pos == self.cap && self.read_done {
|
||||
ready!(writer.as_mut().poll_flush(cx))?;
|
||||
return Poll::Ready(Ok(self.amt));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A future that asynchronously copies the entire contents of a reader into a
|
||||
/// writer.
|
||||
#[derive(Debug)]
|
||||
#[must_use = "futures do nothing unless you `.await` or poll them"]
|
||||
struct Copy<'a, R: ?Sized, W: ?Sized> {
|
||||
reader: &'a mut R,
|
||||
read_done: bool,
|
||||
writer: &'a mut W,
|
||||
pos: usize,
|
||||
cap: usize,
|
||||
amt: u64,
|
||||
buf: Box<[u8]>,
|
||||
buf: CopyBuffer,
|
||||
}
|
||||
|
||||
cfg_io_util! {
|
||||
@@ -35,8 +102,8 @@ cfg_io_util! {
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// The returned future will finish with an error will return an error
|
||||
/// immediately if any call to `poll_read` or `poll_write` returns an error.
|
||||
/// The returned future will return an error immediately if any call to
|
||||
/// `poll_read` or `poll_write` returns an error.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
@@ -60,12 +127,8 @@ cfg_io_util! {
|
||||
{
|
||||
Copy {
|
||||
reader,
|
||||
read_done: false,
|
||||
writer,
|
||||
amt: 0,
|
||||
pos: 0,
|
||||
cap: 0,
|
||||
buf: vec![0; 2048].into_boxed_slice(),
|
||||
buf: CopyBuffer::new()
|
||||
}.await
|
||||
}
|
||||
}
|
||||
@@ -78,44 +141,9 @@ where
|
||||
type Output = io::Result<u64>;
|
||||
|
||||
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<u64>> {
|
||||
loop {
|
||||
// If our buffer is empty, then we need to read some data to
|
||||
// continue.
|
||||
if self.pos == self.cap && !self.read_done {
|
||||
let me = &mut *self;
|
||||
let mut buf = ReadBuf::new(&mut me.buf);
|
||||
ready!(Pin::new(&mut *me.reader).poll_read(cx, &mut buf))?;
|
||||
let n = buf.filled().len();
|
||||
if n == 0 {
|
||||
self.read_done = true;
|
||||
} else {
|
||||
self.pos = 0;
|
||||
self.cap = n;
|
||||
}
|
||||
}
|
||||
let me = &mut *self;
|
||||
|
||||
// If our buffer has some data, let's write it out!
|
||||
while self.pos < self.cap {
|
||||
let me = &mut *self;
|
||||
let i = ready!(Pin::new(&mut *me.writer).poll_write(cx, &me.buf[me.pos..me.cap]))?;
|
||||
if i == 0 {
|
||||
return Poll::Ready(Err(io::Error::new(
|
||||
io::ErrorKind::WriteZero,
|
||||
"write zero byte into writer",
|
||||
)));
|
||||
} else {
|
||||
self.pos += i;
|
||||
self.amt += i as u64;
|
||||
}
|
||||
}
|
||||
|
||||
// If we've written all the data and we've seen EOF, flush out the
|
||||
// data and finish the transfer.
|
||||
if self.pos == self.cap && self.read_done {
|
||||
let me = &mut *self;
|
||||
ready!(Pin::new(&mut *me.writer).poll_flush(cx))?;
|
||||
return Poll::Ready(Ok(self.amt));
|
||||
}
|
||||
}
|
||||
me.buf
|
||||
.poll_copy(cx, Pin::new(&mut *me.reader), Pin::new(&mut *me.writer))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
use super::copy::CopyBuffer;
|
||||
|
||||
use crate::io::{AsyncRead, AsyncWrite};
|
||||
|
||||
use std::future::Future;
|
||||
use std::io;
|
||||
use std::pin::Pin;
|
||||
use std::task::{Context, Poll};
|
||||
|
||||
enum TransferState {
|
||||
Running(CopyBuffer),
|
||||
ShuttingDown(u64),
|
||||
Done(u64),
|
||||
}
|
||||
|
||||
struct CopyBidirectional<'a, A: ?Sized, B: ?Sized> {
|
||||
a: &'a mut A,
|
||||
b: &'a mut B,
|
||||
a_to_b: TransferState,
|
||||
b_to_a: TransferState,
|
||||
}
|
||||
|
||||
fn transfer_one_direction<A, B>(
|
||||
cx: &mut Context<'_>,
|
||||
state: &mut TransferState,
|
||||
r: &mut A,
|
||||
w: &mut B,
|
||||
) -> Poll<io::Result<u64>>
|
||||
where
|
||||
A: AsyncRead + AsyncWrite + Unpin + ?Sized,
|
||||
B: AsyncRead + AsyncWrite + Unpin + ?Sized,
|
||||
{
|
||||
let mut r = Pin::new(r);
|
||||
let mut w = Pin::new(w);
|
||||
|
||||
loop {
|
||||
match state {
|
||||
TransferState::Running(buf) => {
|
||||
let count = ready!(buf.poll_copy(cx, r.as_mut(), w.as_mut()))?;
|
||||
*state = TransferState::ShuttingDown(count);
|
||||
}
|
||||
TransferState::ShuttingDown(count) => {
|
||||
ready!(w.as_mut().poll_shutdown(cx))?;
|
||||
|
||||
*state = TransferState::Done(*count);
|
||||
}
|
||||
TransferState::Done(count) => return Poll::Ready(Ok(*count)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, A, B> Future for CopyBidirectional<'a, A, B>
|
||||
where
|
||||
A: AsyncRead + AsyncWrite + Unpin + ?Sized,
|
||||
B: AsyncRead + AsyncWrite + Unpin + ?Sized,
|
||||
{
|
||||
type Output = io::Result<(u64, u64)>;
|
||||
|
||||
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
||||
// Unpack self into mut refs to each field to avoid borrow check issues.
|
||||
let CopyBidirectional {
|
||||
a,
|
||||
b,
|
||||
a_to_b,
|
||||
b_to_a,
|
||||
} = &mut *self;
|
||||
|
||||
let a_to_b = transfer_one_direction(cx, a_to_b, &mut *a, &mut *b)?;
|
||||
let b_to_a = transfer_one_direction(cx, b_to_a, &mut *b, &mut *a)?;
|
||||
|
||||
// It is not a problem if ready! returns early because transfer_one_direction for the
|
||||
// other direction will keep returning TransferState::Done(count) in future calls to poll
|
||||
let a_to_b = ready!(a_to_b);
|
||||
let b_to_a = ready!(b_to_a);
|
||||
|
||||
Poll::Ready(Ok((a_to_b, b_to_a)))
|
||||
}
|
||||
}
|
||||
|
||||
/// Copies data in both directions between `a` and `b`.
|
||||
///
|
||||
/// This function returns a future that will read from both streams,
|
||||
/// writing any data read to the opposing stream.
|
||||
/// This happens in both directions concurrently.
|
||||
///
|
||||
/// If an EOF is observed on one stream, [`shutdown()`] will be invoked on
|
||||
/// the other, and reading from that stream will stop. Copying of data in
|
||||
/// the other direction will continue.
|
||||
///
|
||||
/// The future will complete successfully once both directions of communication has been shut down.
|
||||
/// A direction is shut down when the reader reports EOF,
|
||||
/// at which point [`shutdown()`] is called on the corresponding writer. When finished,
|
||||
/// it will return a tuple of the number of bytes copied from a to b
|
||||
/// and the number of bytes copied from b to a, in that order.
|
||||
///
|
||||
/// [`shutdown()`]: crate::io::AsyncWriteExt::shutdown
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// The future will immediately return an error if any IO operation on `a`
|
||||
/// or `b` returns an error. Some data read from either stream may be lost (not
|
||||
/// written to the other stream) in this case.
|
||||
///
|
||||
/// # Return value
|
||||
///
|
||||
/// Returns a tuple of bytes copied `a` to `b` and bytes copied `b` to `a`.
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "io-util")))]
|
||||
pub async fn copy_bidirectional<A, B>(a: &mut A, b: &mut B) -> Result<(u64, u64), std::io::Error>
|
||||
where
|
||||
A: AsyncRead + AsyncWrite + Unpin + ?Sized,
|
||||
B: AsyncRead + AsyncWrite + Unpin + ?Sized,
|
||||
{
|
||||
CopyBidirectional {
|
||||
a,
|
||||
b,
|
||||
a_to_b: TransferState::Running(CopyBuffer::new()),
|
||||
b_to_a: TransferState::Running(CopyBuffer::new()),
|
||||
}
|
||||
.await
|
||||
}
|
||||
@@ -128,7 +128,7 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
Poll::Ready(Ok(Some(mem::replace(me.buf, String::new()))))
|
||||
Poll::Ready(Ok(Some(mem::take(me.buf))))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -16,6 +16,14 @@ use std::{
|
||||
/// that can be used as in-memory IO types. Writing to one of the pairs will
|
||||
/// allow that data to be read from the other, and vice versa.
|
||||
///
|
||||
/// # Closing a `DuplexStream`
|
||||
///
|
||||
/// If one end of the `DuplexStream` channel is dropped, any pending reads on
|
||||
/// the other side will continue to read data until the buffer is drained, then
|
||||
/// they will signal EOF by returning 0 bytes. Any writes to the other side,
|
||||
/// including pending ones (that are waiting for free space in the buffer) will
|
||||
/// return `Err(BrokenPipe)` immediately.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
@@ -37,6 +45,7 @@ use std::{
|
||||
/// # }
|
||||
/// ```
|
||||
#[derive(Debug)]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "io-util")))]
|
||||
pub struct DuplexStream {
|
||||
read: Arc<Mutex<Pipe>>,
|
||||
write: Arc<Mutex<Pipe>>,
|
||||
@@ -72,6 +81,7 @@ struct Pipe {
|
||||
///
|
||||
/// The `max_buf_size` argument is the maximum amount of bytes that can be
|
||||
/// written to a side before the write returns `Poll::Pending`.
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "io-util")))]
|
||||
pub fn duplex(max_buf_size: usize) -> (DuplexStream, DuplexStream) {
|
||||
let one = Arc::new(Mutex::new(Pipe::new(max_buf_size)));
|
||||
let two = Arc::new(Mutex::new(Pipe::new(max_buf_size)));
|
||||
@@ -134,7 +144,8 @@ impl AsyncWrite for DuplexStream {
|
||||
impl Drop for DuplexStream {
|
||||
fn drop(&mut self) {
|
||||
// notify the other side of the closure
|
||||
self.write.lock().close();
|
||||
self.write.lock().close_write();
|
||||
self.read.lock().close_read();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -151,12 +162,21 @@ impl Pipe {
|
||||
}
|
||||
}
|
||||
|
||||
fn close(&mut self) {
|
||||
fn close_write(&mut self) {
|
||||
self.is_closed = true;
|
||||
// needs to notify any readers that no more data will come
|
||||
if let Some(waker) = self.read_waker.take() {
|
||||
waker.wake();
|
||||
}
|
||||
}
|
||||
|
||||
fn close_read(&mut self) {
|
||||
self.is_closed = true;
|
||||
// needs to notify any writers that they have to abort
|
||||
if let Some(waker) = self.write_waker.take() {
|
||||
waker.wake();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AsyncRead for Pipe {
|
||||
@@ -217,7 +237,7 @@ impl AsyncWrite for Pipe {
|
||||
mut self: Pin<&mut Self>,
|
||||
_: &mut task::Context<'_>,
|
||||
) -> Poll<std::io::Result<()>> {
|
||||
self.close();
|
||||
self.close_write();
|
||||
Poll::Ready(Ok(()))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,6 +27,9 @@ cfg_io_util! {
|
||||
mod copy;
|
||||
pub use copy::copy;
|
||||
|
||||
mod copy_bidirectional;
|
||||
pub use copy_bidirectional::copy_bidirectional;
|
||||
|
||||
mod copy_buf;
|
||||
pub use copy_buf::copy_buf;
|
||||
|
||||
@@ -71,13 +74,15 @@ cfg_io_util! {
|
||||
pub use take::Take;
|
||||
|
||||
mod write;
|
||||
mod write_vectored;
|
||||
mod write_all;
|
||||
mod write_buf;
|
||||
mod write_all_buf;
|
||||
mod write_int;
|
||||
|
||||
|
||||
// used by `BufReader` and `BufWriter`
|
||||
// https://github.com/rust-lang/rust/blob/master/src/libstd/sys_common/io.rs#L1
|
||||
// https://github.com/rust-lang/rust/blob/master/library/std/src/sys_common/io.rs#L1
|
||||
const DEFAULT_BUF_SIZE: usize = 8 * 1024;
|
||||
}
|
||||
|
||||
|
||||
@@ -36,7 +36,7 @@ where
|
||||
{
|
||||
ReadLine {
|
||||
reader,
|
||||
buf: mem::replace(string, String::new()).into_bytes(),
|
||||
buf: mem::take(string).into_bytes(),
|
||||
output: string,
|
||||
read: 0,
|
||||
_pin: PhantomPinned,
|
||||
@@ -99,7 +99,7 @@ pub(super) fn read_line_internal<R: AsyncBufRead + ?Sized>(
|
||||
read: &mut usize,
|
||||
) -> Poll<io::Result<usize>> {
|
||||
let io_res = ready!(read_until_internal(reader, cx, b'\n', buf, read));
|
||||
let utf8_res = String::from_utf8(mem::replace(buf, Vec::new()));
|
||||
let utf8_res = String::from_utf8(mem::take(buf));
|
||||
|
||||
// At this point both buf and output are empty. The allocation is in utf8_res.
|
||||
|
||||
|
||||
@@ -37,7 +37,7 @@ pub(crate) fn read_to_string<'a, R>(
|
||||
where
|
||||
R: AsyncRead + ?Sized + Unpin,
|
||||
{
|
||||
let buf = mem::replace(string, String::new()).into_bytes();
|
||||
let buf = mem::take(string).into_bytes();
|
||||
ReadToString {
|
||||
reader,
|
||||
buf: VecWithInitialized::new(buf),
|
||||
|
||||
@@ -106,7 +106,7 @@ where
|
||||
me.buf.pop();
|
||||
}
|
||||
|
||||
Poll::Ready(Ok(Some(mem::replace(me.buf, Vec::new()))))
|
||||
Poll::Ready(Ok(Some(mem::take(me.buf))))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
use crate::io::AsyncWrite;
|
||||
|
||||
use bytes::Buf;
|
||||
use pin_project_lite::pin_project;
|
||||
use std::future::Future;
|
||||
use std::io;
|
||||
use std::marker::PhantomPinned;
|
||||
use std::pin::Pin;
|
||||
use std::task::{Context, Poll};
|
||||
|
||||
pin_project! {
|
||||
/// A future to write some of the buffer to an `AsyncWrite`.
|
||||
#[derive(Debug)]
|
||||
#[must_use = "futures do nothing unless you `.await` or poll them"]
|
||||
pub struct WriteAllBuf<'a, W, B> {
|
||||
writer: &'a mut W,
|
||||
buf: &'a mut B,
|
||||
#[pin]
|
||||
_pin: PhantomPinned,
|
||||
}
|
||||
}
|
||||
|
||||
/// Tries to write some bytes from the given `buf` to the writer in an
|
||||
/// asynchronous manner, returning a future.
|
||||
pub(crate) fn write_all_buf<'a, W, B>(writer: &'a mut W, buf: &'a mut B) -> WriteAllBuf<'a, W, B>
|
||||
where
|
||||
W: AsyncWrite + Unpin,
|
||||
B: Buf,
|
||||
{
|
||||
WriteAllBuf {
|
||||
writer,
|
||||
buf,
|
||||
_pin: PhantomPinned,
|
||||
}
|
||||
}
|
||||
|
||||
impl<W, B> Future for WriteAllBuf<'_, W, B>
|
||||
where
|
||||
W: AsyncWrite + Unpin,
|
||||
B: Buf,
|
||||
{
|
||||
type Output = io::Result<()>;
|
||||
|
||||
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||
let me = self.project();
|
||||
while me.buf.has_remaining() {
|
||||
let n = ready!(Pin::new(&mut *me.writer).poll_write(cx, me.buf.chunk())?);
|
||||
me.buf.advance(n);
|
||||
if n == 0 {
|
||||
return Poll::Ready(Err(io::ErrorKind::WriteZero.into()));
|
||||
}
|
||||
}
|
||||
|
||||
Poll::Ready(Ok(()))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
use crate::io::AsyncWrite;
|
||||
|
||||
use pin_project_lite::pin_project;
|
||||
use std::io;
|
||||
use std::marker::PhantomPinned;
|
||||
use std::pin::Pin;
|
||||
use std::task::{Context, Poll};
|
||||
use std::{future::Future, io::IoSlice};
|
||||
|
||||
pin_project! {
|
||||
/// A future to write a slice of buffers to an `AsyncWrite`.
|
||||
#[derive(Debug)]
|
||||
#[must_use = "futures do nothing unless you `.await` or poll them"]
|
||||
pub struct WriteVectored<'a, 'b, W: ?Sized> {
|
||||
writer: &'a mut W,
|
||||
bufs: &'a [IoSlice<'b>],
|
||||
// Make this future `!Unpin` for compatibility with async trait methods.
|
||||
#[pin]
|
||||
_pin: PhantomPinned,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn write_vectored<'a, 'b, W>(
|
||||
writer: &'a mut W,
|
||||
bufs: &'a [IoSlice<'b>],
|
||||
) -> WriteVectored<'a, 'b, W>
|
||||
where
|
||||
W: AsyncWrite + Unpin + ?Sized,
|
||||
{
|
||||
WriteVectored {
|
||||
writer,
|
||||
bufs,
|
||||
_pin: PhantomPinned,
|
||||
}
|
||||
}
|
||||
|
||||
impl<W> Future for WriteVectored<'_, '_, W>
|
||||
where
|
||||
W: AsyncWrite + Unpin + ?Sized,
|
||||
{
|
||||
type Output = io::Result<usize>;
|
||||
|
||||
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<usize>> {
|
||||
let me = self.project();
|
||||
Pin::new(&mut *me.writer).poll_write_vectored(cx, me.bufs)
|
||||
}
|
||||
}
|
||||
+2
-3
@@ -1,4 +1,3 @@
|
||||
#![doc(html_root_url = "https://docs.rs/tokio/1.2.0")]
|
||||
#![allow(
|
||||
clippy::cognitive_complexity,
|
||||
clippy::large_enum_variant,
|
||||
@@ -77,7 +76,7 @@
|
||||
//!
|
||||
//! ### Authoring libraries
|
||||
//!
|
||||
//! As a library author your goal should be to provide the lighest weight crate
|
||||
//! As a library author your goal should be to provide the lightest weight crate
|
||||
//! that is based on Tokio. To achieve this you should ensure that you only enable
|
||||
//! the features you need. This allows users to pick up your crate without having
|
||||
//! to enable unnecessary features.
|
||||
@@ -411,7 +410,7 @@ mod util;
|
||||
/// # Why was `Stream` not included in Tokio 1.0?
|
||||
///
|
||||
/// Originally, we had planned to ship Tokio 1.0 with a stable `Stream` type
|
||||
/// but unfortunetly the [RFC] had not been merged in time for `Stream` to
|
||||
/// but unfortunately the [RFC] had not been merged in time for `Stream` to
|
||||
/// reach `std` on a stable compiler in time for the 1.0 release of Tokio. For
|
||||
/// this reason, the team has decided to move all `Stream` based utilities to
|
||||
/// the [`tokio-stream`] crate. While this is not ideal, once `Stream` has made
|
||||
|
||||
@@ -357,3 +357,21 @@ macro_rules! cfg_coop {
|
||||
)*
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! cfg_not_coop {
|
||||
($($item:item)*) => {
|
||||
$(
|
||||
#[cfg(not(any(
|
||||
feature = "fs",
|
||||
feature = "io-std",
|
||||
feature = "net",
|
||||
feature = "process",
|
||||
feature = "rt",
|
||||
feature = "signal",
|
||||
feature = "sync",
|
||||
feature = "time",
|
||||
)))]
|
||||
$item
|
||||
)*
|
||||
}
|
||||
}
|
||||
|
||||
@@ -44,7 +44,7 @@
|
||||
/// Stream + Unpin`.
|
||||
///
|
||||
/// [`Future`]: trait@std::future::Future
|
||||
/// [`Box::pin`]: #
|
||||
/// [`Box::pin`]: std::boxed::Box::pin
|
||||
///
|
||||
/// # Usage
|
||||
///
|
||||
|
||||
+95
-28
@@ -14,7 +14,7 @@
|
||||
/// branch, which evaluates if none of the other branches match their patterns:
|
||||
///
|
||||
/// ```text
|
||||
/// else <expression>
|
||||
/// else => <expression>
|
||||
/// ```
|
||||
///
|
||||
/// The macro aggregates all `<async expression>` expressions and runs them
|
||||
@@ -129,8 +129,24 @@
|
||||
///
|
||||
/// ### Fairness
|
||||
///
|
||||
/// `select!` randomly picks a branch to check first. This provides some level
|
||||
/// of fairness when calling `select!` in a loop with branches that are always
|
||||
/// By default, `select!` randomly picks a branch to check first. This provides
|
||||
/// some level of fairness when calling `select!` in a loop with branches that
|
||||
/// are always ready.
|
||||
///
|
||||
/// This behavior can be overridden by adding `biased;` to the beginning of the
|
||||
/// macro usage. See the examples for details. This will cause `select` to poll
|
||||
/// the futures in the order they appear from top to bottom. There are a few
|
||||
/// reasons you may want this:
|
||||
///
|
||||
/// - The random number generation of `tokio::select!` has a non-zero CPU cost
|
||||
/// - Your futures may interact in a way where known polling order is significant
|
||||
///
|
||||
/// But there is an important caveat to this mode. It becomes your responsibility
|
||||
/// to ensure that the polling order of your futures is fair. If for example you
|
||||
/// are selecting between a stream and a shutdown future, and the stream has a
|
||||
/// huge volume of messages and zero or nearly zero time between them, you should
|
||||
/// place the shutdown future earlier in the `select!` list to ensure that it is
|
||||
/// always polled, and will not be ignored due to the stream being constantly
|
||||
/// ready.
|
||||
///
|
||||
/// # Panics
|
||||
@@ -138,7 +154,7 @@
|
||||
/// `select!` panics if all branches are disabled **and** there is no provided
|
||||
/// `else` branch. A branch is disabled when the provided `if` precondition
|
||||
/// returns `false` **or** when the pattern does not match the result of `<async
|
||||
/// expression>.
|
||||
/// expression>`.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
@@ -283,6 +299,45 @@
|
||||
/// assert_eq!(res.1, "second");
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Using the `biased;` mode to control polling order.
|
||||
///
|
||||
/// ```
|
||||
/// #[tokio::main]
|
||||
/// async fn main() {
|
||||
/// let mut count = 0u8;
|
||||
///
|
||||
/// loop {
|
||||
/// tokio::select! {
|
||||
/// // If you run this example without `biased;`, the polling order is
|
||||
/// // psuedo-random, and the assertions on the value of count will
|
||||
/// // (probably) fail.
|
||||
/// biased;
|
||||
///
|
||||
/// _ = async {}, if count < 1 => {
|
||||
/// count += 1;
|
||||
/// assert_eq!(count, 1);
|
||||
/// }
|
||||
/// _ = async {}, if count < 2 => {
|
||||
/// count += 1;
|
||||
/// assert_eq!(count, 2);
|
||||
/// }
|
||||
/// _ = async {}, if count < 3 => {
|
||||
/// count += 1;
|
||||
/// assert_eq!(count, 3);
|
||||
/// }
|
||||
/// _ = async {}, if count < 4 => {
|
||||
/// count += 1;
|
||||
/// assert_eq!(count, 4);
|
||||
/// }
|
||||
///
|
||||
/// else => {
|
||||
/// break;
|
||||
/// }
|
||||
/// };
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
#[macro_export]
|
||||
#[cfg_attr(docsrs, doc(cfg(feature = "macros")))]
|
||||
macro_rules! select {
|
||||
@@ -300,6 +355,10 @@ macro_rules! select {
|
||||
|
||||
// All input is normalized, now transform.
|
||||
(@ {
|
||||
// The index of the future to poll first (in bias mode), or the RNG
|
||||
// expression to use to pick a future to poll first.
|
||||
start=$start:expr;
|
||||
|
||||
// One `_` for each branch in the `select!` macro. Passing this to
|
||||
// `count!` converts $skip to an integer.
|
||||
( $($count:tt)* )
|
||||
@@ -357,9 +416,11 @@ macro_rules! select {
|
||||
// disabled.
|
||||
let mut is_pending = false;
|
||||
|
||||
// Randomly generate a starting point. This makes `select!` a
|
||||
// bit more fair and avoids always polling the first future.
|
||||
let start = $crate::macros::support::thread_rng_n(BRANCHES);
|
||||
// Choose a starting index to begin polling the futures at. In
|
||||
// practice, this will either be a psuedo-randomly generrated
|
||||
// number by default, or the constant 0 if `biased;` is
|
||||
// supplied.
|
||||
let start = $start;
|
||||
|
||||
for i in 0..BRANCHES {
|
||||
let branch;
|
||||
@@ -444,42 +505,48 @@ macro_rules! select {
|
||||
// These rules match a single `select!` branch and normalize it for
|
||||
// processing by the first rule.
|
||||
|
||||
(@ { $($t:tt)* } ) => {
|
||||
(@ { start=$start:expr; $($t:tt)* } ) => {
|
||||
// No `else` branch
|
||||
$crate::select!(@{ $($t)*; panic!("all branches are disabled and there is no else branch") })
|
||||
$crate::select!(@{ start=$start; $($t)*; panic!("all branches are disabled and there is no else branch") })
|
||||
};
|
||||
(@ { $($t:tt)* } else => $else:expr $(,)?) => {
|
||||
$crate::select!(@{ $($t)*; $else })
|
||||
(@ { start=$start:expr; $($t:tt)* } else => $else:expr $(,)?) => {
|
||||
$crate::select!(@{ start=$start; $($t)*; $else })
|
||||
};
|
||||
(@ { ( $($s:tt)* ) $($t:tt)* } $p:pat = $f:expr, if $c:expr => $h:block, $($r:tt)* ) => {
|
||||
$crate::select!(@{ ($($s)* _) $($t)* ($($s)*) $p = $f, if $c => $h, } $($r)*)
|
||||
(@ { start=$start:expr; ( $($s:tt)* ) $($t:tt)* } $p:pat = $f:expr, if $c:expr => $h:block, $($r:tt)* ) => {
|
||||
$crate::select!(@{ start=$start; ($($s)* _) $($t)* ($($s)*) $p = $f, if $c => $h, } $($r)*)
|
||||
};
|
||||
(@ { ( $($s:tt)* ) $($t:tt)* } $p:pat = $f:expr => $h:block, $($r:tt)* ) => {
|
||||
$crate::select!(@{ ($($s)* _) $($t)* ($($s)*) $p = $f, if true => $h, } $($r)*)
|
||||
(@ { start=$start:expr; ( $($s:tt)* ) $($t:tt)* } $p:pat = $f:expr => $h:block, $($r:tt)* ) => {
|
||||
$crate::select!(@{ start=$start; ($($s)* _) $($t)* ($($s)*) $p = $f, if true => $h, } $($r)*)
|
||||
};
|
||||
(@ { ( $($s:tt)* ) $($t:tt)* } $p:pat = $f:expr, if $c:expr => $h:block $($r:tt)* ) => {
|
||||
$crate::select!(@{ ($($s)* _) $($t)* ($($s)*) $p = $f, if $c => $h, } $($r)*)
|
||||
(@ { start=$start:expr; ( $($s:tt)* ) $($t:tt)* } $p:pat = $f:expr, if $c:expr => $h:block $($r:tt)* ) => {
|
||||
$crate::select!(@{ start=$start; ($($s)* _) $($t)* ($($s)*) $p = $f, if $c => $h, } $($r)*)
|
||||
};
|
||||
(@ { ( $($s:tt)* ) $($t:tt)* } $p:pat = $f:expr => $h:block $($r:tt)* ) => {
|
||||
$crate::select!(@{ ($($s)* _) $($t)* ($($s)*) $p = $f, if true => $h, } $($r)*)
|
||||
(@ { start=$start:expr; ( $($s:tt)* ) $($t:tt)* } $p:pat = $f:expr => $h:block $($r:tt)* ) => {
|
||||
$crate::select!(@{ start=$start; ($($s)* _) $($t)* ($($s)*) $p = $f, if true => $h, } $($r)*)
|
||||
};
|
||||
(@ { ( $($s:tt)* ) $($t:tt)* } $p:pat = $f:expr, if $c:expr => $h:expr ) => {
|
||||
$crate::select!(@{ ($($s)* _) $($t)* ($($s)*) $p = $f, if $c => $h, })
|
||||
(@ { start=$start:expr; ( $($s:tt)* ) $($t:tt)* } $p:pat = $f:expr, if $c:expr => $h:expr ) => {
|
||||
$crate::select!(@{ start=$start; ($($s)* _) $($t)* ($($s)*) $p = $f, if $c => $h, })
|
||||
};
|
||||
(@ { ( $($s:tt)* ) $($t:tt)* } $p:pat = $f:expr => $h:expr ) => {
|
||||
$crate::select!(@{ ($($s)* _) $($t)* ($($s)*) $p = $f, if true => $h, })
|
||||
(@ { start=$start:expr; ( $($s:tt)* ) $($t:tt)* } $p:pat = $f:expr => $h:expr ) => {
|
||||
$crate::select!(@{ start=$start; ($($s)* _) $($t)* ($($s)*) $p = $f, if true => $h, })
|
||||
};
|
||||
(@ { ( $($s:tt)* ) $($t:tt)* } $p:pat = $f:expr, if $c:expr => $h:expr, $($r:tt)* ) => {
|
||||
$crate::select!(@{ ($($s)* _) $($t)* ($($s)*) $p = $f, if $c => $h, } $($r)*)
|
||||
(@ { start=$start:expr; ( $($s:tt)* ) $($t:tt)* } $p:pat = $f:expr, if $c:expr => $h:expr, $($r:tt)* ) => {
|
||||
$crate::select!(@{ start=$start; ($($s)* _) $($t)* ($($s)*) $p = $f, if $c => $h, } $($r)*)
|
||||
};
|
||||
(@ { ( $($s:tt)* ) $($t:tt)* } $p:pat = $f:expr => $h:expr, $($r:tt)* ) => {
|
||||
$crate::select!(@{ ($($s)* _) $($t)* ($($s)*) $p = $f, if true => $h, } $($r)*)
|
||||
(@ { start=$start:expr; ( $($s:tt)* ) $($t:tt)* } $p:pat = $f:expr => $h:expr, $($r:tt)* ) => {
|
||||
$crate::select!(@{ start=$start; ($($s)* _) $($t)* ($($s)*) $p = $f, if true => $h, } $($r)*)
|
||||
};
|
||||
|
||||
// ===== Entry point =====
|
||||
|
||||
(biased; $p:pat = $($t:tt)* ) => {
|
||||
$crate::select!(@{ start=0; () } $p = $($t)*)
|
||||
};
|
||||
|
||||
( $p:pat = $($t:tt)* ) => {
|
||||
$crate::select!(@{ () } $p = $($t)*)
|
||||
// Randomly generate a starting point. This makes `select!` a bit more
|
||||
// fair and avoids always polling the first future.
|
||||
$crate::select!(@{ start={ $crate::macros::support::thread_rng_n(BRANCHES) }; () } $p = $($t)*)
|
||||
};
|
||||
() => {
|
||||
compile_error!("select! requires at least one branch.")
|
||||
|
||||
@@ -192,7 +192,6 @@ impl TcpListener {
|
||||
/// backing event loop. This allows configuration of options like
|
||||
/// `SO_REUSEPORT`, binding to multiple addresses, etc.
|
||||
///
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```rust,no_run
|
||||
@@ -221,6 +220,48 @@ impl TcpListener {
|
||||
Ok(TcpListener { io })
|
||||
}
|
||||
|
||||
/// Turn a [`tokio::net::TcpListener`] into a [`std::net::TcpListener`].
|
||||
///
|
||||
/// The returned [`std::net::TcpListener`] will have nonblocking mode set as
|
||||
/// `true`. Use [`set_nonblocking`] to change the blocking mode if needed.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```rust,no_run
|
||||
/// use std::error::Error;
|
||||
///
|
||||
/// #[tokio::main]
|
||||
/// async fn main() -> Result<(), Box<dyn Error>> {
|
||||
/// let tokio_listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
|
||||
/// let std_listener = tokio_listener.into_std()?;
|
||||
/// std_listener.set_nonblocking(false)?;
|
||||
/// Ok(())
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// [`tokio::net::TcpListener`]: TcpListener
|
||||
/// [`std::net::TcpListener`]: std::net::TcpListener
|
||||
/// [`set_nonblocking`]: fn@std::net::TcpListener::set_nonblocking
|
||||
pub fn into_std(self) -> io::Result<std::net::TcpListener> {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::io::{FromRawFd, IntoRawFd};
|
||||
self.io
|
||||
.into_inner()
|
||||
.map(|io| io.into_raw_fd())
|
||||
.map(|raw_fd| unsafe { std::net::TcpListener::from_raw_fd(raw_fd) })
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::io::{FromRawSocket, IntoRawSocket};
|
||||
self.io
|
||||
.into_inner()
|
||||
.map(|io| io.into_raw_socket())
|
||||
.map(|raw_socket| unsafe { std::net::TcpListener::from_raw_socket(raw_socket) })
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn new(listener: mio::net::TcpListener) -> io::Result<TcpListener> {
|
||||
let io = PollEvented::new(listener)?;
|
||||
Ok(TcpListener { io })
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user